Skip to main content

pitchfork_cli/
pitchfork_toml.rs

1use crate::daemon_id::DaemonId;
2use crate::deprecated_at;
3use crate::error::{ConfigParseError, DependencyError, FileError, find_similar_daemon};
4use crate::settings::SettingsPartial;
5use crate::settings::settings;
6use crate::state_file::StateFile;
7use crate::tui::theme::ThemeDef;
8use crate::{Result, env};
9use indexmap::IndexMap;
10use miette::Context;
11use once_cell::sync::Lazy;
12use schemars::JsonSchema;
13use std::collections::{HashMap, HashSet};
14use std::path::{Path, PathBuf};
15use std::sync::Mutex as StdMutex;
16use std::time::SystemTime;
17
18// Re-export config value types so existing `use crate::pitchfork_toml::X` paths keep working.
19pub use crate::config_types::{
20    CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, OnOutputHook,
21    PitchforkTomlAuto, PitchforkTomlCron, PitchforkTomlHooks, PortBump, PortConfig, ProxyConfig,
22    ProxyIdleTimeout, ProxyProtocol, ProxyTlsMode, ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort,
23    Retry, StopConfig, StopSignal, WatchMode,
24};
25
26/// Raw slug entry as read from TOML (uses String for dir path).
27/// Format in global config:
28/// ```toml
29/// [slugs]
30/// api = { dir = "/home/user/my-api", daemon = "server" }
31/// docs = { dir = "/home/user/docs-site" }  # daemon defaults to slug name
32/// ```
33#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
34pub struct SlugEntryRaw {
35    /// Project directory containing the pitchfork.toml
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub dir: Option<String>,
38    /// Namespace reference (alternative to dir)
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub namespace: Option<String>,
41    /// Daemon name within that project (defaults to slug name if omitted)
42    #[serde(skip_serializing_if = "Option::is_none", default)]
43    pub daemon: Option<String>,
44}
45
46/// Resolved slug entry with PathBuf.
47#[derive(Debug, Clone)]
48pub struct SlugEntry {
49    /// Project directory containing the pitchfork.toml
50    pub dir: Option<PathBuf>,
51    /// Namespace reference (alternative to dir)
52    pub namespace: Option<String>,
53    /// Daemon name within that project (defaults to slug name if omitted)
54    pub daemon: Option<String>,
55}
56
57impl SlugEntry {
58    /// Resolve the project directory.
59    /// If `dir` is set, use it. Otherwise look up `namespace` in the global namespace registry.
60    pub fn resolve_dir(&self) -> Option<PathBuf> {
61        self.dir.clone().or_else(|| {
62            self.namespace.as_ref().and_then(|ns| {
63                let namespaces = PitchforkToml::read_global_namespaces();
64                namespaces.get(ns).map(|entry| entry.dir.clone())
65            })
66        })
67    }
68
69    /// Resolve the namespace name.
70    /// If `namespace` is set, use it. Otherwise derive from `dir` via `namespace_for_dir`.
71    pub fn resolve_namespace(&self) -> Option<String> {
72        self.namespace.clone().or_else(|| {
73            self.resolve_dir()
74                .and_then(|dir| PitchforkToml::namespace_for_dir(&dir).ok())
75        })
76    }
77}
78
79/// Raw group entry as read from TOML.
80/// ```toml
81/// [groups.backend]
82/// daemons = ["api", "worker"]
83///
84/// [groups.all]
85/// groups = ["backend"]
86/// daemons = ["postgres"]
87/// ```
88#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, JsonSchema)]
89pub struct GroupEntryRaw {
90    /// Daemons in this group: short names or fully qualified IDs.
91    #[serde(default, skip_serializing_if = "Vec::is_empty")]
92    #[schemars(with = "Vec<DaemonId>")]
93    pub daemons: Vec<String>,
94    /// Names of other groups whose daemons this group also contains.
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub groups: Vec<String>,
97}
98
99/// Resolved group entry with qualified DaemonIds.
100///
101/// `groups` stays unexpanded: it names groups that may be defined in a
102/// different config file, so it is resolved by [`expand_group`] once the
103/// configs are merged.
104#[derive(Debug, Clone, Default)]
105pub struct GroupEntry {
106    pub daemons: Vec<DaemonId>,
107    pub groups: Vec<String>,
108}
109
110/// Expand a group into its deduplicated daemons, following `groups` includes.
111///
112/// Daemons of included groups come first, in the order the groups are listed,
113/// followed by the group's own `daemons`. A daemon reachable more than once is
114/// kept at its first position. Including an undefined group, or a group that
115/// includes itself directly or through other groups, is an error.
116pub fn expand_group(groups: &IndexMap<String, GroupEntry>, name: &str) -> Result<Vec<DaemonId>> {
117    fn visit(
118        groups: &IndexMap<String, GroupEntry>,
119        name: &str,
120        path: &mut Vec<String>,
121        done: &mut HashSet<String>,
122        seen: &mut HashSet<DaemonId>,
123        out: &mut Vec<DaemonId>,
124    ) -> Result<()> {
125        // Everything a finished group contributes is already in `out`, so
126        // revisiting it through another include only repeats work.
127        if done.contains(name) {
128            return Ok(());
129        }
130        let Some(group) = groups.get(name) else {
131            let suggestion = find_similar_daemon(name, groups.keys().map(|s| s.as_str()));
132            return Err(match path.last() {
133                Some(parent) => miette::miette!(
134                    "group '{parent}' includes undefined group '{name}'{}",
135                    suggestion.map(|s| format!(", {s}")).unwrap_or_default()
136                ),
137                None => miette::miette!(
138                    "group '{name}' not found in configuration{}",
139                    suggestion.map(|s| format!(", {s}")).unwrap_or_default()
140                ),
141            });
142        };
143        if path.iter().any(|p| p == name) {
144            return Err(miette::miette!(
145                "group include cycle: {} -> {name}",
146                path.join(" -> ")
147            ));
148        }
149        path.push(name.to_string());
150        for included in &group.groups {
151            visit(groups, included, path, done, seen, out)?;
152        }
153        path.pop();
154        for id in &group.daemons {
155            if seen.insert(id.clone()) {
156                out.push(id.clone());
157            }
158        }
159        done.insert(name.to_string());
160        Ok(())
161    }
162
163    let mut out = Vec::new();
164    visit(
165        groups,
166        name,
167        &mut Vec::new(),
168        &mut HashSet::new(),
169        &mut HashSet::new(),
170        &mut out,
171    )?;
172    Ok(out)
173}
174
175/// Raw namespace entry as read from TOML.
176/// ```toml
177/// [namespaces.myproject]
178/// dir = "/home/user/projects/myproject"
179/// ```
180#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
181pub struct NamespaceEntryRaw {
182    /// Project directory containing the pitchfork.toml
183    pub dir: String,
184    /// Additional configuration files, relative to dir or absolute.
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub config: Vec<String>,
187    /// Hostname label for the project, used instead of the namespace when the
188    /// namespace is only an identifier (for example a generated
189    /// `shop-528f92b13a6784f0`). Must already be a valid DNS label.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub label: Option<String>,
192}
193
194/// Resolved namespace entry with PathBuf.
195#[derive(Debug, Clone)]
196pub struct NamespaceEntry {
197    /// Project directory containing the pitchfork.toml
198    pub dir: PathBuf,
199    pub config: Vec<PathBuf>,
200    /// Hostname label for the project, when the registration names one.
201    pub label: Option<String>,
202}
203
204/// Internal structure for reading config files (uses String keys for short daemon names)
205#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
206struct PitchforkTomlRaw {
207    #[serde(skip_serializing_if = "Option::is_none", default)]
208    pub namespace: Option<String>,
209    /// Hostname label for this checkout when it is a linked git worktree.
210    #[serde(skip_serializing_if = "Option::is_none", default)]
211    pub worktree_label: Option<String>,
212    #[serde(default)]
213    pub daemons: IndexMap<String, PitchforkTomlDaemonRaw>,
214    /// Top-level environment variables applied to all daemons as defaults.
215    /// Per-daemon `env` overrides these. Values support Tera templates.
216    #[serde(skip_serializing_if = "Option::is_none", default)]
217    pub env: Option<IndexMap<String, String>>,
218    #[serde(default)]
219    pub settings: Option<SettingsPartial>,
220    /// Slug registry (only meaningful in global config).
221    /// Maps slug names to their configuration (dir + optional daemon name).
222    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
223    pub slugs: IndexMap<String, SlugEntryRaw>,
224    /// Named groups of daemons for batch operations.
225    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
226    pub groups: IndexMap<String, GroupEntryRaw>,
227    /// Namespace registry (only meaningful in global config).
228    /// Maps namespace names to their project directory.
229    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
230    pub namespaces: IndexMap<String, NamespaceEntryRaw>,
231    /// Custom TUI themes.
232    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
233    pub themes: IndexMap<String, ThemeDef>,
234}
235
236/// Per-daemon log configuration sub-table `[daemons.<name>.logs]`.
237///
238/// Fields here override the top-level daemon fields (`time_retention`,
239/// `line_retention`, `archive_hook`) and the global `[settings.logs]` defaults.
240#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
241pub struct PitchforkTomlDaemonLogs {
242    /// Log line format: `json`, `logfmt`, or `text`.
243    /// Defaults to `text` (no parsing).
244    #[serde(skip_serializing_if = "Option::is_none", default)]
245    pub log_format: Option<String>,
246    /// Maximum age of log entries to keep (e.g. "7d", "30d").
247    #[serde(skip_serializing_if = "Option::is_none", default)]
248    pub time_retention: Option<String>,
249    /// Maximum number of log entries to keep per daemon.
250    #[serde(skip_serializing_if = "Option::is_none", default)]
251    pub line_retention: Option<i64>,
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}
256
257/// Internal daemon config for reading (uses String for depends).
258///
259/// Note: This struct mirrors `PitchforkTomlDaemon` but uses `Vec<String>` for `depends`
260/// (before namespace resolution) and has serde attributes for TOML serialization.
261/// When adding new fields, remember to update both structs and the conversion code
262/// in `read()` and `write()`.
263#[derive(Debug, serde::Serialize, serde::Deserialize)]
264struct PitchforkTomlDaemonRaw {
265    pub run: RunCommand,
266    #[serde(skip_serializing_if = "Vec::is_empty", default)]
267    pub auto: Vec<PitchforkTomlAuto>,
268    #[serde(skip_serializing_if = "Option::is_none", default)]
269    pub oneshot: Option<bool>,
270    #[serde(skip_serializing_if = "Option::is_none", default)]
271    pub cron: Option<PitchforkTomlCron>,
272    #[serde(default)]
273    pub retry: Retry,
274    #[serde(skip_serializing_if = "Option::is_none", default)]
275    pub ready_delay: Option<u64>,
276    #[serde(skip_serializing_if = "Option::is_none", default)]
277    pub ready_output: Option<ReadyOutput>,
278    #[serde(skip_serializing_if = "Option::is_none", default)]
279    pub ready_http: Option<ReadyHttp>,
280    #[serde(skip_serializing_if = "Option::is_none", default)]
281    pub ready_port: Option<ReadyPort>,
282    #[serde(skip_serializing_if = "Option::is_none", default)]
283    pub ready_cmd: Option<ReadyCmd>,
284    #[serde(skip_serializing_if = "Option::is_none", default)]
285    pub health_cmd: Option<HealthCmd>,
286    #[serde(skip_serializing_if = "Option::is_none", default)]
287    pub health_http: Option<HealthHttp>,
288    #[serde(skip_serializing_if = "Option::is_none", default)]
289    pub health_port: Option<HealthPort>,
290    /// New port configuration (preferred)
291    #[serde(skip_serializing_if = "Option::is_none", default)]
292    pub port: Option<PortConfig>,
293    /// Proxy routing: `false` opts out, a string overrides the daemon's hostname label.
294    #[serde(skip_serializing_if = "Option::is_none", default)]
295    pub proxy: Option<ProxyConfig>,
296    /// Deprecated: use `port` instead
297    #[serde(skip_serializing_if = "Vec::is_empty", default)]
298    pub expected_port: Vec<u16>,
299    /// Deprecated: use `port.bump` instead
300    #[serde(skip_serializing_if = "Option::is_none", default)]
301    pub auto_bump_port: Option<bool>,
302    /// Deprecated: use `port.bump` instead
303    #[serde(skip_serializing_if = "Option::is_none", default)]
304    pub port_bump_attempts: Option<u32>,
305    /// TLS handling for this daemon's proxy hostname: `terminate` or `passthrough`.
306    #[serde(skip_serializing_if = "Option::is_none", default)]
307    pub proxy_tls: Option<ProxyTlsMode>,
308    /// HTTP version the proxy speaks to this daemon: `http1` or `h2c`.
309    #[serde(skip_serializing_if = "Option::is_none", default)]
310    pub proxy_protocol: Option<ProxyProtocol>,
311    /// Which of the daemon's ports the proxy hostname maps to.
312    #[serde(skip_serializing_if = "Option::is_none", default)]
313    pub proxy_tls_port: Option<u16>,
314    /// Shorter spelling of `proxy_tls_port`. Never written back out, so a
315    /// config that used it keeps one spelling rather than gaining both.
316    #[serde(skip_serializing_if = "Option::is_none", default)]
317    pub proxy_port: Option<u16>,
318    /// Stop after this long without proxy activity when the proxy started it.
319    #[serde(skip_serializing_if = "Option::is_none", default)]
320    pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
321    #[serde(skip_serializing_if = "Option::is_none", default)]
322    pub boot_start: Option<bool>,
323    #[serde(skip_serializing_if = "Vec::is_empty", default)]
324    pub depends: Vec<String>,
325    #[serde(skip_serializing_if = "Vec::is_empty", default)]
326    pub watch: Vec<String>,
327    #[serde(skip_serializing_if = "Option::is_none", default)]
328    pub watch_mode: Option<WatchMode>,
329    #[serde(skip_serializing_if = "Option::is_none", default)]
330    pub dir: Option<String>,
331    #[serde(skip_serializing_if = "Option::is_none", default)]
332    pub env: Option<IndexMap<String, String>>,
333    #[serde(skip_serializing_if = "Vec::is_empty", default)]
334    pub env_file: Vec<String>,
335    #[serde(skip_serializing_if = "Option::is_none", default)]
336    pub hooks: Option<PitchforkTomlHooks>,
337    #[serde(skip_serializing_if = "Option::is_none", default)]
338    pub mise: Option<bool>,
339    /// Unix user to run this daemon as.
340    /// On Windows, nonempty values prevent daemon startup with an error.
341    #[serde(skip_serializing_if = "Option::is_none", default)]
342    pub user: Option<String>,
343    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
344    #[serde(skip_serializing_if = "Option::is_none", default)]
345    pub memory_limit: Option<MemoryLimit>,
346    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
347    #[serde(skip_serializing_if = "Option::is_none", default)]
348    pub cpu_limit: Option<CpuLimit>,
349    /// Unix signal to send for graceful shutdown (default: SIGTERM)
350    #[serde(skip_serializing_if = "Option::is_none", default)]
351    pub stop_signal: Option<StopConfig>,
352    /// Allocate a pseudo-terminal on Unix. Windows rejects `true` at startup.
353    #[serde(skip_serializing_if = "Option::is_none", default)]
354    pub pty: Option<bool>,
355    /// Maximum age of log entries to keep (e.g. "7d", "30d").
356    /// Overrides the global `settings.logs.time_retention` when set.
357    #[serde(skip_serializing_if = "Option::is_none", default)]
358    pub time_retention: Option<String>,
359    /// Maximum number of log entries to keep per daemon.
360    /// Overrides the global `settings.logs.line_retention` when set.
361    #[serde(skip_serializing_if = "Option::is_none", default)]
362    pub line_retention: Option<i64>,
363    /// Archive hook command invoked before retention prunes this daemon's logs.
364    /// Overrides the global `settings.logs.archive_hook.command` when set.
365    #[serde(skip_serializing_if = "Option::is_none", default)]
366    pub archive_hook: Option<String>,
367    /// Per-daemon log configuration sub-table.
368    #[serde(skip_serializing_if = "Option::is_none", default)]
369    pub logs: Option<PitchforkTomlDaemonLogs>,
370}
371
372/// Configuration schema for pitchfork.toml daemon supervisor configuration files.
373///
374/// Note: When read from a file, daemon keys are short names (e.g., "api").
375/// After merging, keys become qualified DaemonIds (e.g., "project/api").
376#[derive(Debug, Clone, Default, JsonSchema)]
377#[schemars(title = "Pitchfork Configuration")]
378pub struct PitchforkToml {
379    /// Map of daemon IDs to their configurations
380    #[serde(default)]
381    pub daemons: IndexMap<DaemonId, PitchforkTomlDaemon>,
382    /// Top-level environment variables applied to all daemons as defaults.
383    /// Per-daemon `env` overrides these on key conflicts. Values support Tera
384    /// templates (e.g. `{{ daemons.api.port }}`, `{{ settings.proxy.tld }}`).
385    #[serde(skip_serializing_if = "Option::is_none", default)]
386    pub env: Option<IndexMap<String, String>>,
387    /// Optional explicit namespace declared in this file.
388    ///
389    /// This applies to per-file read/write flows. Merged configs may contain
390    /// daemons from multiple namespaces and leave this as `None`.
391    pub namespace: Option<String>,
392    /// Hostname label for this checkout when it is a linked git worktree.
393    ///
394    /// Overrides the worktree directory's name in proxy hostnames.
395    #[schemars(default, with = "Option<String>")]
396    pub worktree_label: Option<String>,
397    /// Settings configuration (merged from all config files).
398    ///
399    /// **Note:** This field exists for serialization round-trips and for
400    /// `PitchforkToml::merge()` to collect per-file overrides.  It is **not**
401    /// consumed by the global `settings()` singleton, which is populated
402    /// independently by `Settings::load()` to avoid a circular dependency
403    /// between `PitchforkToml` and `Settings`.  Do not rely on mutations to
404    /// this field being reflected in `settings()`.
405    #[serde(default)]
406    pub(crate) settings: SettingsPartial,
407    /// Slug registry (merged from global config files).
408    /// Maps slug names to their project directory and optional daemon name.
409    /// Only populated from global config files (`~/.config/pitchfork/config.toml`
410    /// or `/etc/pitchfork/config.toml`).
411    #[schemars(default, with = "IndexMap<String, SlugEntryRaw>")]
412    pub slugs: IndexMap<String, SlugEntry>,
413    /// Named groups of daemons for batch operations.
414    #[schemars(default, with = "IndexMap<String, GroupEntryRaw>")]
415    pub groups: IndexMap<String, GroupEntry>,
416    /// Namespace registry (merged from global config files).
417    /// Maps namespace names to their project directory.
418    #[schemars(default, with = "IndexMap<String, NamespaceEntryRaw>")]
419    pub namespaces: IndexMap<String, NamespaceEntry>,
420    /// Custom TUI themes, selected with `settings.tui.theme`
421    /// (or `light_theme` / `dark_theme`).
422    ///
423    /// Each theme lists only the colors it changes from its `base`
424    /// (`auto` by default, which follows the terminal's own palette).
425    ///
426    /// ```toml
427    /// [themes.mine]
428    /// base = "catppuccin_latte"
429    /// selection_bg = "#ddd6fe"
430    /// ```
431    #[serde(default)]
432    pub themes: IndexMap<String, ThemeDef>,
433    #[schemars(skip)]
434    pub path: Option<PathBuf>,
435    /// Top-level `[env]` of the registered project each daemon merged in from
436    /// another namespace came from, keyed by that daemon.
437    ///
438    /// Such a daemon renders against its own project's defaults, not those of
439    /// the checkout that requested it. Daemons from the requesting checkout's
440    /// own config chain are absent and use [`Self::env`], which carries every
441    /// override along that chain.
442    #[schemars(skip)]
443    pub(crate) foreign_env: IndexMap<DaemonId, Option<IndexMap<String, String>>>,
444}
445
446impl PitchforkToml {
447    /// The top-level `[env]` defaults `id` renders against: its own project's
448    /// when it came from another registered project, otherwise this config's.
449    pub(crate) fn env_for(&self, id: &DaemonId) -> Option<&IndexMap<String, String>> {
450        self.foreign_env
451            .get(id)
452            .map_or(self.env.as_ref(), |env| env.as_ref())
453    }
454}
455
456pub fn is_global_config(path: &Path) -> bool {
457    path == *env::PITCHFORK_GLOBAL_CONFIG_USER || path == *env::PITCHFORK_GLOBAL_CONFIG_SYSTEM
458}
459
460pub(crate) fn is_dot_config_pitchfork(path: &Path) -> bool {
461    path.ends_with(".config/pitchfork.toml") || path.ends_with(".config/pitchfork.local.toml")
462}
463
464fn parse_namespace_override_from_content(path: &Path, content: &str) -> Result<Option<String>> {
465    use toml::Value;
466
467    let doc: Value = toml::from_str(content)
468        .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
469    let Some(value) = doc.get("namespace") else {
470        return Ok(None);
471    };
472
473    match value {
474        Value::String(s) => Ok(Some(s.clone())),
475        _ => Err(ConfigParseError::InvalidNamespace {
476            path: path.to_path_buf(),
477            namespace: value.to_string(),
478            reason: "top-level 'namespace' must be a string".to_string(),
479        }
480        .into()),
481    }
482}
483
484fn read_namespace_override_from_file(path: &Path) -> Result<Option<String>> {
485    if !path.exists() {
486        return Ok(None);
487    }
488    let content = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
489        path: path.to_path_buf(),
490        source: e,
491    })?;
492    parse_namespace_override_from_content(path, &content)
493}
494
495pub fn project_dir_for_config(path: &Path) -> Option<PathBuf> {
496    crate::extra_configs::project_dir(path).or_else(|| {
497        if is_dot_config_pitchfork(path) {
498            path.parent().and_then(Path::parent).map(Path::to_path_buf)
499        } else {
500            path.parent().map(Path::to_path_buf)
501        }
502    })
503}
504
505fn project_config_family(path: &Path) -> Vec<PathBuf> {
506    let Some(dir) = project_dir_for_config(path) else {
507        return vec![path.to_path_buf()];
508    };
509    vec![
510        dir.join(".config/pitchfork.toml"),
511        dir.join(".config/pitchfork.local.toml"),
512        dir.join("pitchfork.toml"),
513        dir.join("pitchfork.local.toml"),
514    ]
515}
516
517/// Resolve one namespace override shared by all project config files in a
518/// directory. `content_override` represents unsaved content for `path`.
519fn directory_namespace_override(
520    path: &Path,
521    content_override: Option<&str>,
522) -> Result<Option<String>> {
523    if is_global_config(path) {
524        return match content_override {
525            Some(content) => parse_namespace_override_from_content(path, content),
526            None => read_namespace_override_from_file(path),
527        };
528    }
529
530    let mut selected: Option<(String, PathBuf)> = None;
531    for candidate in project_config_family(path) {
532        let explicit = if candidate == path {
533            match content_override {
534                Some(content) => parse_namespace_override_from_content(&candidate, content)?,
535                None => read_namespace_override_from_file(&candidate)?,
536            }
537        } else {
538            read_namespace_override_from_file(&candidate)?
539        };
540        let Some(namespace) = explicit else { continue };
541        if let Some((selected_namespace, selected_path)) = &selected
542            && selected_namespace != &namespace
543        {
544            return Err(ConfigParseError::InvalidNamespace {
545                path: candidate,
546                namespace,
547                reason: format!(
548                    "namespace does not match directory-level namespace '{}' declared in {}",
549                    selected_namespace,
550                    selected_path.display()
551                ),
552            }
553            .into());
554        }
555        selected = Some((namespace, candidate));
556    }
557    Ok(selected.map(|(namespace, _)| namespace))
558}
559
560fn validate_namespace(path: &Path, namespace: &str) -> Result<String> {
561    if let Err(e) = DaemonId::try_new(namespace, "probe") {
562        return Err(ConfigParseError::InvalidNamespace {
563            path: path.to_path_buf(),
564            namespace: namespace.to_string(),
565            reason: e.to_string(),
566        }
567        .into());
568    }
569    Ok(namespace.to_string())
570}
571
572fn derive_namespace_from_dir(path: &Path) -> Result<String> {
573    let dir_for_namespace = project_dir_for_config(path);
574    if let Some(namespace) = dir_for_namespace
575        .as_deref()
576        .and_then(crate::extra_configs::namespace_for_dir)
577    {
578        return validate_namespace(path, &namespace);
579    }
580    let raw_namespace = dir_for_namespace
581        .as_deref()
582        .and_then(|p| p.file_name())
583        .and_then(|n| n.to_str())
584        .ok_or_else(|| miette::miette!("cannot derive namespace from path '{}'", path.display()))?
585        .to_string();
586
587    validate_namespace(path, &raw_namespace).map_err(|e| {
588        ConfigParseError::InvalidNamespace {
589            path: path.to_path_buf(),
590            namespace: raw_namespace,
591            reason: format!(
592                "{e}. Set a valid top-level namespace, e.g. namespace = \"my-project\""
593            ),
594        }
595        .into()
596    })
597}
598
599fn namespace_from_path_with_override(path: &Path, explicit: Option<&str>) -> Result<String> {
600    if is_global_config(path) {
601        if let Some(ns) = explicit
602            && ns != "global"
603        {
604            return Err(ConfigParseError::InvalidNamespace {
605                path: path.to_path_buf(),
606                namespace: ns.to_string(),
607                reason: "global config files must use namespace 'global'".to_string(),
608            }
609            .into());
610        }
611        return Ok("global".to_string());
612    }
613
614    if let Some(ns) = explicit {
615        return validate_namespace(path, ns);
616    }
617
618    derive_namespace_from_dir(path)
619}
620
621fn namespace_from_file(path: &Path) -> Result<String> {
622    let explicit = directory_namespace_override(path, None)?;
623    namespace_from_path_with_override(path, explicit.as_deref())
624}
625
626/// Extracts a namespace from a config file path.
627///
628/// - For user global config (`~/.config/pitchfork/config.toml`): returns "global"
629/// - For system global config (`/etc/pitchfork/config.toml`): returns "global"
630/// - For project configs: uses top-level `namespace` if present, otherwise parent directory name
631///
632/// Examples:
633/// - `~/.config/pitchfork/config.toml` → `"global"`
634/// - `/etc/pitchfork/config.toml` → `"global"`
635/// - `/home/user/project-a/pitchfork.toml` → `"project-a"`
636/// - `/home/user/project-b/sub/pitchfork.toml` → `"sub"`
637/// - `/home/user/中文目录/pitchfork.toml` → error unless `namespace = "..."` is set
638pub fn namespace_from_path(path: &Path) -> Result<String> {
639    namespace_from_file(path)
640}
641
642/// Find the nearest ancestor directory of `dir` that contains a `.git` or
643/// `.jj` marker (the project root of a git worktree / jj workspace).
644///
645/// Returns `None` when `dir` is not inside any git/jj project, so callers can
646/// fall back to non-worktree behavior. In a linked git worktree, `.git` is a
647/// *file* (not a directory) pointing at the common gitdir, so we check
648/// existence rather than `is_dir()`.
649fn find_project_root(dir: &Path) -> Option<PathBuf> {
650    // Canonicalize the start dir so a symlinked path resolves into the
651    // repository hierarchy before traversing parents; otherwise `parent()`
652    // walks outside the repo and misses `.git`/`.jj`.
653    let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
654    let mut current = canonical_dir.as_path();
655    loop {
656        if current.join(".git").exists() || current.join(".jj").exists() {
657            return Some(current.to_path_buf());
658        }
659        current = current.parent()?;
660    }
661}
662
663/// Cached result of `all_merged_from`, keyed by the cwd used to discover config paths.
664///
665/// The cache key is the canonical cwd `PathBuf`. The entry stores the merged
666/// [`PitchforkToml`] plus a snapshot of every source file's (mtime, size) at
667/// cache time. A cache hit requires the same set of paths with identical
668/// mtimes **and** sizes.
669///
670/// Tracking size in addition to mtime catches timestamp-preserving content
671/// changes (e.g. `cp --preserve=timestamps`, same-second edits on filesystems
672/// with coarse mtime granularity like NFS) that mtime alone would miss.
673///
674/// **Known limitation**: an equal-size content replacement that also preserves
675/// mtime will not be detected. This is an accepted trade-off — fully closing
676/// this gap would require hashing file contents on every cache hit, negating
677/// the I/O savings the cache exists to provide. In practice, editors and `git
678/// pull` always change mtime, and `cp --preserve=timestamps` almost always
679/// changes size. The `ReloadConfig` IPC handler (`settings reload`) serves as
680/// an explicit escape hatch to force a full re-read when needed.
681struct ConfigCacheEntry {
682    config: PitchforkToml,
683    /// (path, (mtime, size)) snapshot — order matches `list_paths_from` at cache time.
684    source_meta: Vec<(PathBuf, Option<(SystemTime, u64)>)>,
685}
686
687/// Global config parse cache, keyed by canonical cwd.
688///
689/// Uses a `std::sync::Mutex` (not tokio) because config parsing is CPU-bound
690/// and callers like `spawn_blocking(PitchforkToml::all_merged)` run outside
691/// the async runtime. Contention is minimal: the mutex is held only for the
692/// metadata comparison and the occasional re-read, not across I/O.
693static CONFIG_CACHE: Lazy<StdMutex<HashMap<PathBuf, ConfigCacheEntry>>> =
694    Lazy::new(|| StdMutex::new(HashMap::new()));
695
696/// Compare a list of paths' current (mtime, size) against a cached snapshot.
697///
698/// Returns `true` if every path exists (or not) and has the same mtime and
699/// size as when the snapshot was taken. Any difference — a new file, a deleted
700/// file, a changed mtime, or a changed size — invalidates the cache.
701fn meta_matches(paths: &[PathBuf], snapshot: &[(PathBuf, Option<(SystemTime, u64)>)]) -> bool {
702    if paths.len() != snapshot.len() {
703        return false;
704    }
705    paths
706        .iter()
707        .zip(snapshot.iter())
708        .all(|(p, (snap_p, snap_meta))| p == snap_p && current_meta(p) == *snap_meta)
709}
710
711/// Best-effort (mtime, size) — `None` if the path doesn't exist or metadata fails.
712pub(crate) fn current_meta(path: &Path) -> Option<(SystemTime, u64)> {
713    let md = std::fs::metadata(path).ok()?;
714    Some((md.modified().ok()?, md.len()))
715}
716
717/// Snapshot all (path, (mtime, size)) pairs for a list of paths.
718fn snapshot_meta(paths: &[PathBuf]) -> Vec<(PathBuf, Option<(SystemTime, u64)>)> {
719    paths.iter().map(|p| (p.clone(), current_meta(p))).collect()
720}
721
722/// Invalidate the entire config parse cache.
723///
724/// Called after any config file write (`write()`, `write_unlocked()`,
725/// `add_slug_with_namespace()`, `remove_slug()`, `register_namespace()`,
726/// `remove_namespace()`) so that subsequent `all_merged_from` calls re-read
727/// from disk.
728///
729/// Also called by `settings reload` (via IPC `ReloadConfig`) so that external
730/// edits to config files are picked up.
731///
732/// **Cross-process note**: CLI and supervisor are separate processes with
733/// independent caches. When the CLI calls this after `write_unlocked()`, it
734/// only clears the CLI's own cache (which is about to exit anyway). The
735/// supervisor relies on mtime change detection to pick up CLI-written changes.
736/// The `ReloadConfig` IPC handler is the one that matters — it clears the
737/// supervisor's cache.
738pub fn invalidate_config_cache() {
739    crate::extra_configs::invalidate();
740    // The web project pages keep their own parsed-group cache, validated the
741    // same way, so it must be dropped here too.
742    crate::web::routes::api::projects::invalidate_group_cache();
743    if let Ok(mut cache) = CONFIG_CACHE.lock() {
744        cache.clear();
745    }
746}
747
748impl PitchforkToml {
749    /// Resolves a user-provided daemon ID to qualified DaemonIds.
750    ///
751    /// If the ID is already qualified (contains '/'), parses and returns it.
752    /// Otherwise, looks up the short ID in the config and returns
753    /// matching qualified IDs.
754    ///
755    /// # Arguments
756    /// * `user_id` - The daemon ID provided by the user
757    ///
758    /// # Returns
759    /// A Result containing a vector of matching DaemonIds (usually one, but could be multiple
760    /// if the same short ID exists in multiple namespaces), or an error if the ID is invalid.
761    pub fn resolve_daemon_id(&self, user_id: &str) -> Result<Vec<DaemonId>> {
762        // If already qualified, parse and return
763        if user_id.contains('/') {
764            return match DaemonId::parse(user_id) {
765                Ok(id) => Ok(vec![id]),
766                Err(e) => Err(e), // Invalid format - propagate error
767            };
768        }
769
770        // Check for slug match in global slugs registry
771        let global_slugs = Self::read_global_slugs();
772        if let Some(entry) = global_slugs.get(user_id) {
773            // Load the project's config from the slug's dir to find the daemon ID
774            let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
775            if let Some(dir) = entry.resolve_dir()
776                && let Ok(project_config) = Self::all_merged_from(&dir)
777            {
778                // Find daemon by short name in that project
779                let matches: Vec<DaemonId> = project_config
780                    .daemons
781                    .keys()
782                    .filter(|id| id.name() == daemon_name)
783                    .cloned()
784                    .collect();
785                match matches.as_slice() {
786                    [] => {}
787                    [id] => return Ok(vec![id.clone()]),
788                    _ => {
789                        let mut candidates: Vec<String> =
790                            matches.iter().map(|id| id.qualified()).collect();
791                        candidates.sort();
792                        return Err(miette::miette!(
793                            "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
794                            user_id,
795                            daemon_name,
796                            candidates.join(", ")
797                        ));
798                    }
799                }
800            }
801        }
802
803        // Look for matching qualified IDs in the config
804        let matches: Vec<DaemonId> = self
805            .daemons
806            .keys()
807            .filter(|id| id.name() == user_id)
808            .cloned()
809            .collect();
810
811        if matches.is_empty() {
812            // No config matches. Search state file for any daemon with matching short name.
813            let state_matches = Self::find_in_state_file(user_id);
814            match state_matches.as_slice() {
815                [] => {}
816                [id] => return Ok(vec![id.clone()]),
817                _ => {
818                    let mut candidates: Vec<String> =
819                        state_matches.iter().map(|id| id.qualified()).collect();
820                    candidates.sort();
821                    return Err(miette::miette!(
822                        "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
823                        user_id,
824                        candidates.join(", ")
825                    ));
826                }
827            }
828            // No config or state matches. Validate short ID format and return no matches.
829            let _ = DaemonId::try_new("global", user_id)?;
830        }
831        Ok(matches)
832    }
833
834    /// Finds all daemons in the persisted state file whose short name matches `short_name`.
835    ///
836    /// Logs a warning if the state file exists but cannot be read or parsed.
837    ///
838    /// Returns the matching `DaemonId`s. The caller must handle zero / one / many cases.
839    fn find_in_state_file(short_name: &str) -> Vec<DaemonId> {
840        match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
841            Ok(state) => state
842                .daemons
843                .keys()
844                .filter(|id| id.name() == short_name)
845                .cloned()
846                .collect(),
847            Err(e) => {
848                warn!("cannot read state file: {e}");
849                Vec::new()
850            }
851        }
852    }
853
854    /// Resolves a user-provided daemon ID to a qualified DaemonId, preferring the current directory's namespace.
855    ///
856    /// If the ID is already qualified (contains '/'), parses and returns it.
857    /// Otherwise, tries to find a daemon in the current directory's namespace first.
858    /// Falls back to any matching daemon if not found in current namespace.
859    ///
860    /// # Arguments
861    /// * `user_id` - The daemon ID provided by the user
862    /// * `current_dir` - The current working directory (used to determine namespace preference)
863    ///
864    /// # Returns
865    /// The resolved DaemonId, or an error if the ID format is invalid
866    ///
867    /// # Errors
868    /// Returns an error if `user_id` contains '/' but is not a valid qualified ID
869    /// (e.g., "foo/bar/baz" with multiple slashes), or if `user_id` contains invalid characters.
870    ///
871    /// # Warnings
872    /// If multiple daemons match the short name and none is in the current namespace,
873    /// a warning is logged to stderr indicating the ambiguity.
874    #[allow(dead_code)]
875    pub fn resolve_daemon_id_prefer_local(
876        &self,
877        user_id: &str,
878        current_dir: &Path,
879    ) -> Result<DaemonId> {
880        // If already qualified, parse and return (or error if invalid)
881        if user_id.contains('/') {
882            return DaemonId::parse(user_id);
883        }
884
885        // Determine the current directory's namespace by finding the nearest
886        // pitchfork.toml. Cache the namespace in the caller when resolving
887        // multiple IDs to avoid repeated filesystem traversal.
888        let current_namespace = Self::namespace_for_dir(current_dir)?;
889
890        self.resolve_daemon_id_with_namespace(user_id, &current_namespace)
891    }
892
893    /// Like `resolve_daemon_id_prefer_local` but accepts a pre-computed namespace,
894    /// avoiding redundant filesystem traversal when resolving multiple IDs.
895    fn resolve_daemon_id_with_namespace(
896        &self,
897        user_id: &str,
898        current_namespace: &str,
899    ) -> Result<DaemonId> {
900        // A daemon in the current namespace comes first, so another project's
901        // slug of the same name does not take over a local daemon. A slug can
902        // be a name no daemon can have (e.g. `my--alias`), so an invalid name
903        // only skips this check and is rejected after the slug lookup.
904        if let Ok(preferred_id) = DaemonId::try_new(current_namespace, user_id)
905            && self.daemons.contains_key(&preferred_id)
906        {
907            return Ok(preferred_id);
908        }
909
910        // Check for slug match in global slugs registry
911        let global_slugs = Self::read_global_slugs();
912        if let Some(entry) = global_slugs.get(user_id) {
913            let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
914            if let Some(dir) = entry.resolve_dir()
915                && let Ok(project_config) = Self::all_merged_from(&dir)
916            {
917                let matches: Vec<DaemonId> = project_config
918                    .daemons
919                    .keys()
920                    .filter(|id| id.name() == daemon_name)
921                    .cloned()
922                    .collect();
923                match matches.as_slice() {
924                    [] => {}
925                    [id] => return Ok(id.clone()),
926                    _ => {
927                        let mut candidates: Vec<String> =
928                            matches.iter().map(|id| id.qualified()).collect();
929                        candidates.sort();
930                        return Err(miette::miette!(
931                            "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
932                            user_id,
933                            daemon_name,
934                            candidates.join(", ")
935                        ));
936                    }
937                }
938            }
939        }
940
941        // Use try_new to validate user input
942        DaemonId::try_new(current_namespace, user_id)?;
943
944        // Fall back to any matching daemon
945        let matches = self.resolve_daemon_id(user_id)?;
946
947        // Error on ambiguity instead of implicitly preferring global.
948        if matches.len() > 1 {
949            let mut candidates: Vec<String> = matches.iter().map(|id| id.qualified()).collect();
950            candidates.sort();
951            return Err(miette::miette!(
952                "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
953                user_id,
954                candidates.join(", ")
955            ));
956        }
957
958        if let Some(id) = matches.into_iter().next() {
959            return Ok(id);
960        }
961
962        // If not found in current namespace or merged config matches, only fall back
963        // to global when it is explicitly configured.
964        let global_id = DaemonId::try_new("global", user_id)?;
965        if self.daemons.contains_key(&global_id) {
966            return Ok(global_id);
967        }
968
969        let suggestion = find_similar_daemon(user_id, self.daemons.keys().map(|id| id.name()));
970        Err(DependencyError::DaemonNotFound {
971            name: user_id.to_string(),
972            suggestion,
973        }
974        .into())
975    }
976
977    /// Resolve a project's namespace even when it has no ordinary config file.
978    pub fn namespace_for_project_dir(dir: &Path) -> Result<String> {
979        namespace_from_path(&dir.join("pitchfork.toml"))
980    }
981
982    /// Return the `worktree_label` declared for this project, ignoring configs
983    /// inherited from parent directories.
984    ///
985    /// This covers the project's own four config files and any external file
986    /// registered to this directory with `pitchfork config add --dir`, which is
987    /// where a generator such as mise writes its configuration. Later files win,
988    /// matching the ordinary configuration precedence.
989    pub fn project_worktree_label(dir: &Path) -> Option<String> {
990        let mut label = None;
991        let candidates = project_config_family(&dir.join("pitchfork.toml"))
992            .into_iter()
993            .chain(crate::extra_configs::configs_for_dir(dir));
994        for candidate in candidates {
995            if !candidate.exists() {
996                continue;
997            }
998            if let Ok(pt) = Self::read(&candidate)
999                && let Some(found) = pt.worktree_label
1000            {
1001                label = Some(found);
1002            }
1003        }
1004        label
1005    }
1006
1007    /// Return the explicit namespace shared by this project's own configuration files.
1008    pub fn project_namespace_override(dir: &Path) -> Result<Option<String>> {
1009        directory_namespace_override(&dir.join("pitchfork.toml"), None)
1010    }
1011
1012    /// Find the effective namespace from the nearest configuration file.
1013    pub fn namespace_for_dir(dir: &Path) -> Result<String> {
1014        Ok(Self::list_paths_from(dir)
1015            .iter()
1016            .filter(|p| p.exists())
1017            .max_by_key(|p| {
1018                if is_global_config(p) {
1019                    0
1020                } else {
1021                    project_dir_for_config(p).map_or(0, |dir| dir.components().count())
1022                }
1023            })
1024            .map(|p| namespace_from_path(p))
1025            .transpose()?
1026            .unwrap_or_else(|| "global".to_string()))
1027    }
1028
1029    /// Convenience method: resolves a single user ID using the merged config and current directory.
1030    ///
1031    /// Equivalent to:
1032    /// ```ignore
1033    /// PitchforkToml::all_merged().resolve_daemon_id_prefer_local(user_id, &env::CWD)
1034    /// ```
1035    ///
1036    /// # Errors
1037    /// Returns an error if `user_id` contains '/' but is not a valid qualified ID
1038    pub fn resolve_id(user_id: &str) -> Result<DaemonId> {
1039        if user_id.contains('/') {
1040            return DaemonId::parse(user_id);
1041        }
1042
1043        // Compute the namespace once and reuse it — avoids a second traversal
1044        // inside resolve_daemon_id_prefer_local.
1045        let config = Self::all_merged()?;
1046        let ns = Self::namespace_for_dir(&env::CWD)?;
1047        config.resolve_daemon_id_with_namespace(user_id, &ns)
1048    }
1049
1050    /// Like `resolve_id`, but allows ad-hoc short IDs in the current directory's
1051    /// derived namespace.
1052    ///
1053    /// This is intended for commands such as `pitchfork run` that create
1054    /// managed daemons without requiring prior config entries.
1055    pub fn resolve_id_allow_adhoc(user_id: &str) -> Result<DaemonId> {
1056        Self::resolve_id_allow_adhoc_from(user_id, &env::CWD)
1057    }
1058
1059    fn resolve_id_allow_adhoc_from(user_id: &str, dir: &Path) -> Result<DaemonId> {
1060        if user_id.contains('/') {
1061            return DaemonId::parse(user_id);
1062        }
1063
1064        let ns = Self::namespace_for_dir(dir)?;
1065        DaemonId::try_new(ns, user_id)
1066    }
1067
1068    /// Convenience method: resolves multiple user IDs using the merged config and current directory.
1069    ///
1070    /// Equivalent to:
1071    /// ```ignore
1072    /// let config = PitchforkToml::all_merged();
1073    /// ids.iter().map(|s| config.resolve_daemon_id_prefer_local(s, &env::CWD)).collect()
1074    /// ```
1075    ///
1076    /// # Errors
1077    /// Returns an error if any ID is malformed
1078    pub fn resolve_ids<S: AsRef<str>>(user_ids: &[S]) -> Result<Vec<DaemonId>> {
1079        // Fast path: all IDs are already qualified and can be parsed directly.
1080        if user_ids.iter().all(|s| s.as_ref().contains('/')) {
1081            return user_ids
1082                .iter()
1083                .map(|s| DaemonId::parse(s.as_ref()))
1084                .collect();
1085        }
1086
1087        let config = Self::all_merged()?;
1088        // Compute namespace once for all IDs
1089        let ns = Self::namespace_for_dir(&env::CWD)?;
1090        user_ids
1091            .iter()
1092            .map(|s| {
1093                let id = s.as_ref();
1094                if id.contains('/') {
1095                    DaemonId::parse(id)
1096                } else {
1097                    config.resolve_daemon_id_with_namespace(id, &ns)
1098                }
1099            })
1100            .collect()
1101    }
1102
1103    /// Resolve explicit daemon IDs and/or a group name into a deduplicated list of DaemonIds.
1104    ///
1105    /// This is more efficient than calling `resolve_ids` and `resolve_group` separately
1106    /// because it reads the merged config only once.
1107    pub fn resolve_ids_and_group<S: AsRef<str>>(
1108        user_ids: &[S],
1109        group_name: Option<&str>,
1110    ) -> Result<Vec<DaemonId>> {
1111        let config = Self::all_merged()?;
1112        let ns = Self::namespace_for_dir(&env::CWD)?;
1113        let mut ids = Vec::new();
1114        let mut seen = std::collections::HashSet::new();
1115
1116        for id in user_ids {
1117            let id_str = id.as_ref();
1118            let daemon_id = if id_str.contains('/') {
1119                DaemonId::parse(id_str)?
1120            } else {
1121                config.resolve_daemon_id_with_namespace(id_str, &ns)?
1122            };
1123            if seen.insert(daemon_id.clone()) {
1124                ids.push(daemon_id);
1125            }
1126        }
1127
1128        if let Some(name) = group_name {
1129            let members = expand_group(&config.groups, name)?;
1130            let missing: Vec<String> = members
1131                .iter()
1132                .filter(|id| !config.daemons.contains_key(*id))
1133                .map(|id| id.qualified())
1134                .collect();
1135            if !missing.is_empty() {
1136                return Err(miette::miette!(
1137                    "group '{}' references undefined daemon{}: {}",
1138                    name,
1139                    if missing.len() > 1 { "s" } else { "" },
1140                    missing.join(", ")
1141                ));
1142            }
1143            for daemon_id in members {
1144                if seen.insert(daemon_id.clone()) {
1145                    ids.push(daemon_id);
1146                }
1147            }
1148        }
1149
1150        Ok(ids)
1151    }
1152
1153    /// List all configuration file paths from the current working directory.
1154    /// See `list_paths_from` for details on the search order.
1155    pub fn list_paths() -> Vec<PathBuf> {
1156        Self::list_paths_from(&env::CWD)
1157    }
1158
1159    /// List all configuration file paths starting from a given directory.
1160    ///
1161    /// Returns paths in order of precedence (lowest to highest):
1162    /// 1. System-level: /etc/pitchfork/config.toml
1163    /// 2. User-level: ~/.config/pitchfork/config.toml
1164    /// 3. Project-level: .config/pitchfork.toml, .config/pitchfork.local.toml, pitchfork.toml and pitchfork.local.toml files
1165    ///    from filesystem root to the given directory
1166    ///
1167    /// Within each directory, .config/ comes before pitchfork.toml,
1168    /// which comes before pitchfork.local.toml, so local.toml values override base config.
1169    pub fn list_paths_from(cwd: &Path) -> Vec<PathBuf> {
1170        let mut paths = Vec::new();
1171        paths.push(env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone());
1172        paths.push(env::PITCHFORK_GLOBAL_CONFIG_USER.clone());
1173
1174        // Find all project config files. Order is reversed so after .reverse():
1175        // - each directory has: .config/pitchfork.toml < .config/pitchfork.local.toml < pitchfork.toml < pitchfork.local.toml
1176        // - directories go from root to cwd (later configs override earlier)
1177        let mut project_paths = xx::file::find_up_all(
1178            cwd,
1179            &[
1180                "pitchfork.local.toml",
1181                "pitchfork.toml",
1182                ".config/pitchfork.local.toml",
1183                ".config/pitchfork.toml",
1184            ],
1185        );
1186        project_paths.reverse();
1187        paths.extend(project_paths);
1188        paths.extend(crate::extra_configs::paths_for(cwd));
1189
1190        paths
1191    }
1192
1193    /// Merge all configuration files from the current working directory.
1194    /// See `all_merged_from` for details.
1195    pub fn all_merged() -> Result<PitchforkToml> {
1196        Self::all_merged_from(&env::CWD)
1197    }
1198    /// Load all merged config including daemons from ALL registered namespaces.
1199    ///
1200    /// Unlike `all_merged_from` which only merges configs from the cwd chain,
1201    /// this also iterates all `[namespaces]` entries and loads their daemon configs.
1202    /// Use this when you need a complete view (e.g. `start` for a daemon from
1203    /// another namespace).
1204    ///
1205    /// The read walks the filesystem and can start `git` or `jj` to find
1206    /// worktrees, so it runs on a blocking worker: being `async` is what keeps
1207    /// an async caller from running it on the runtime by accident. Code already
1208    /// on a blocking thread uses [`Self::all_merged_all_namespaces_blocking`].
1209    pub async fn all_merged_all_namespaces() -> Result<Self> {
1210        Self::all_merged_all_namespaces_from(&env::CWD).await
1211    }
1212
1213    /// [`Self::all_merged_all_namespaces`] starting from `start_dir`.
1214    pub(crate) async fn all_merged_all_namespaces_from(start_dir: &Path) -> Result<Self> {
1215        let start_dir = start_dir.to_path_buf();
1216        match tokio::task::spawn_blocking(move || {
1217            Self::all_merged_all_namespaces_from_blocking(&start_dir)
1218        })
1219        .await
1220        {
1221            Ok(result) => result,
1222            Err(e) => Err(miette::miette!("reading the merged config panicked: {e}")),
1223        }
1224    }
1225
1226    /// [`Self::all_merged_all_namespaces`] on the calling thread, for code that
1227    /// is already on a blocking thread and must not wait on the runtime.
1228    pub fn all_merged_all_namespaces_blocking() -> Result<Self> {
1229        Self::all_merged_all_namespaces_from_blocking(&env::CWD)
1230    }
1231
1232    /// Core of [`Self::all_merged_all_namespaces`], parameterized by the
1233    /// starting directory so it is testable without touching the global `CWD`.
1234    pub(crate) fn all_merged_all_namespaces_from_blocking(start_dir: &Path) -> Result<Self> {
1235        let mut pt = Self::all_merged_from(start_dir)?;
1236
1237        let namespaces = Self::read_global_namespaces();
1238        for (ns_name, entry) in namespaces {
1239            match Self::all_merged_from(&entry.dir) {
1240                Ok(ns_config) => {
1241                    for (daemon_id, daemon_config) in ns_config.daemons {
1242                        if !pt.daemons.contains_key(&daemon_id) {
1243                            pt.foreign_env
1244                                .insert(daemon_id.clone(), ns_config.env.clone());
1245                            pt.daemons.insert(daemon_id, daemon_config);
1246                        }
1247                    }
1248                    // Merge namespace-level settings so daemon-local
1249                    // overrides (e.g. hooks, env defaults) are available.
1250                    pt.settings.merge_from(&ns_config.settings);
1251                }
1252                Err(e) => {
1253                    log::warn!(
1254                        "Failed to load namespace '{ns_name}' from {}: {e}",
1255                        entry.dir.display()
1256                    );
1257                }
1258            }
1259        }
1260
1261        // Auto-discover git worktrees / jj workspaces under the current
1262        // project, so daemons defined in a worktree are visible to supervisor
1263        // background tasks (cron registration, boot_start, file watch) even
1264        // when that worktree's namespace was never registered in
1265        // `[namespaces]`. Discovery spawns a `git`/`jj` subprocess (<1ms) and
1266        // the per-worktree config reads are cached by `CONFIG_CACHE`, so no
1267        // extra caching layer is needed here.
1268        // Controlled by the global setting so disabling worktrees affects both config
1269        // discovery and proxy slug routing.
1270        if crate::settings::settings().general.worktree
1271            && let Some(project_root) = find_project_root(start_dir)
1272        {
1273            let worktrees = crate::proxy::worktree::discover_worktrees(&project_root);
1274            for wt in &worktrees {
1275                match Self::all_merged_from(&wt.path) {
1276                    Ok(wt_config) => {
1277                        for (daemon_id, daemon_config) in wt_config.daemons {
1278                            if !pt.daemons.contains_key(&daemon_id) {
1279                                pt.daemons.insert(daemon_id, daemon_config);
1280                            }
1281                        }
1282                        pt.settings.merge_from(&wt_config.settings);
1283                    }
1284                    Err(e) => {
1285                        log::warn!(
1286                            "Failed to load worktree '{}' config from {}: {e}",
1287                            wt.branch,
1288                            wt.path.display()
1289                        );
1290                    }
1291                }
1292            }
1293        }
1294
1295        Ok(pt)
1296    }
1297
1298    /// Merge all configuration files starting from a given directory.
1299    ///
1300    /// Reads and merges configuration files in precedence order.
1301    /// Each daemon ID is qualified with a namespace based on its config file location:
1302    /// - Global configs (`~/.config/pitchfork/config.toml`) use namespace "global"
1303    /// - Project configs use the parent directory name as namespace
1304    ///
1305    /// This prevents ID conflicts when multiple projects define daemons with the same name.
1306    ///
1307    /// Results are cached by cwd and invalidated when any source file's mtime
1308    /// changes or when [`invalidate_config_cache`] is called (e.g. after a
1309    /// config write via `write()` / `write_unlocked()`).
1310    ///
1311    /// # Errors
1312    /// Returns an error if any config file fails to parse. Aborts with an error
1313    /// if two *different* project config files produce the same namespace (e.g. two
1314    /// `pitchfork.toml` files in separate directories that share the same directory name).
1315    pub fn all_merged_from(cwd: &Path) -> Result<PitchforkToml> {
1316        let paths = Self::list_paths_from(cwd);
1317
1318        // Fast path: check the cache under a short-lived lock.
1319        // We canonicalize cwd for a stable key. If canonicalization fails
1320        // (e.g. the directory was just deleted), fall back to the raw path.
1321        let cache_key = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
1322
1323        {
1324            let cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1325            if let Some(entry) = cache.get(&cache_key)
1326                && meta_matches(&paths, &entry.source_meta)
1327            {
1328                return Ok(entry.config.clone());
1329            }
1330        }
1331
1332        // Cache miss: snapshot (mtime, size) BEFORE reading.
1333        // If a file changes during the read, the snapshot (old mtime/size) won't
1334        // match the current values on the next call, forcing a re-read.
1335        // Taking the snapshot after the read would store old content with new
1336        // metadata, serving stale data indefinitely.
1337        let snapshot = snapshot_meta(&paths);
1338        let pt = Self::all_merged_from_uncached(&paths)?;
1339
1340        // Store in cache.
1341        let mut cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1342        cache.insert(
1343            cache_key,
1344            ConfigCacheEntry {
1345                config: pt.clone(),
1346                source_meta: snapshot,
1347            },
1348        );
1349
1350        Ok(pt)
1351    }
1352
1353    /// Uncached merge of all configuration files from a list of paths.
1354    ///
1355    /// This is the original merge logic extracted from `all_merged_from` so that
1356    /// the cache layer can wrap it without duplicating the algorithm.
1357    fn all_merged_from_uncached(paths: &[PathBuf]) -> Result<PitchforkToml> {
1358        use std::collections::HashMap as StdHashMap;
1359
1360        let mut ns_to_origin: StdHashMap<String, (PathBuf, PathBuf)> = StdHashMap::new();
1361
1362        let mut pt = Self::default();
1363        for p in paths {
1364            match Self::read(p) {
1365                Ok(pt2) => {
1366                    // Detect collisions for all existing project configs, including
1367                    // pitchfork.local.toml. Allow sibling base/local files in the same
1368                    // directory to share a namespace, including siblings via .config subfolder
1369                    if p.exists() && !is_global_config(p) {
1370                        let ns = namespace_from_path(p)?;
1371                        let origin_dir = project_dir_for_config(p)
1372                            .map(|dir| dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()))
1373                            .unwrap_or_else(|| p.clone());
1374
1375                        if let Some((other_path, other_dir)) = ns_to_origin.get(ns.as_str())
1376                            && *other_dir != origin_dir
1377                        {
1378                            return Err(crate::error::ConfigParseError::NamespaceCollision {
1379                                path_a: other_path.clone(),
1380                                path_b: p.clone(),
1381                                ns,
1382                            }
1383                            .into());
1384                        }
1385                        ns_to_origin.insert(ns, (p.clone(), origin_dir));
1386                    }
1387
1388                    pt.merge(pt2)
1389                }
1390                Err(e) => return Err(e.wrap_err(format!("error reading {}", p.display()))),
1391            }
1392        }
1393        Ok(pt)
1394    }
1395}
1396
1397impl PitchforkToml {
1398    pub fn new(path: PathBuf) -> Self {
1399        Self {
1400            daemons: Default::default(),
1401            env: None,
1402            namespace: None,
1403            worktree_label: None,
1404            settings: SettingsPartial::default(),
1405            slugs: IndexMap::new(),
1406            groups: IndexMap::new(),
1407            namespaces: IndexMap::new(),
1408            themes: IndexMap::new(),
1409            path: Some(path),
1410            foreign_env: IndexMap::new(),
1411        }
1412    }
1413
1414    /// Parse TOML content as a [`PitchforkToml`] without touching the filesystem.
1415    ///
1416    /// Applies the same namespace derivation and daemon validation as [`read()`] but
1417    /// uses the provided `content` directly instead of reading from disk.  `path` is
1418    /// used only for namespace derivation and error messages.
1419    ///
1420    /// This is useful for validating user-edited content before saving it.
1421    pub fn parse_str(content: &str, path: &Path) -> Result<Self> {
1422        let mut raw_config: PitchforkTomlRaw = toml::from_str(content)
1423            .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
1424        if let Some(settings) = &mut raw_config.settings {
1425            settings.canonicalize_aliases();
1426        }
1427
1428        let explicit = directory_namespace_override(path, Some(content))?;
1429        let namespace = namespace_from_path_with_override(path, explicit.as_deref())?;
1430        let mut pt = Self::new(path.to_path_buf());
1431        pt.namespace = raw_config.namespace.clone();
1432        pt.worktree_label = raw_config.worktree_label.clone();
1433
1434        for (short_name, raw_daemon) in raw_config.daemons {
1435            let id = match DaemonId::try_new(&namespace, &short_name) {
1436                Ok(id) => id,
1437                Err(e) => {
1438                    return Err(ConfigParseError::InvalidDaemonName {
1439                        name: short_name,
1440                        path: path.to_path_buf(),
1441                        reason: e.to_string(),
1442                    }
1443                    .into());
1444                }
1445            };
1446
1447            let mut depends = Vec::new();
1448            for dep in raw_daemon.depends {
1449                let dep_id = if dep.contains('/') {
1450                    match DaemonId::parse(&dep) {
1451                        Ok(id) => id,
1452                        Err(e) => {
1453                            return Err(ConfigParseError::InvalidDependency {
1454                                daemon: short_name.clone(),
1455                                dependency: dep,
1456                                path: path.to_path_buf(),
1457                                reason: e.to_string(),
1458                            }
1459                            .into());
1460                        }
1461                    }
1462                } else {
1463                    match DaemonId::try_new(&namespace, &dep) {
1464                        Ok(id) => id,
1465                        Err(e) => {
1466                            return Err(ConfigParseError::InvalidDependency {
1467                                daemon: short_name.clone(),
1468                                dependency: dep,
1469                                path: path.to_path_buf(),
1470                                reason: e.to_string(),
1471                            }
1472                            .into());
1473                        }
1474                    }
1475                };
1476                depends.push(dep_id);
1477            }
1478
1479            // Resolve port config: prefer new `port` field, fall back to deprecated fields
1480            let has_deprecated = !raw_daemon.expected_port.is_empty()
1481                || raw_daemon.auto_bump_port.is_some()
1482                || raw_daemon.port_bump_attempts.is_some();
1483            let deprecated_port = has_deprecated.then(|| {
1484                let bump = if raw_daemon.auto_bump_port.unwrap_or(false) {
1485                    PortBump(
1486                        raw_daemon
1487                            .port_bump_attempts
1488                            .unwrap_or_else(|| settings().default_port_bump_attempts()),
1489                    )
1490                } else {
1491                    PortBump(0)
1492                };
1493                PortConfig {
1494                    expect: raw_daemon.expected_port,
1495                    bump,
1496                }
1497            });
1498            let port = match (raw_daemon.port, deprecated_port) {
1499                (Some(port), Some(deprecated)) => {
1500                    // Writing the config adds the deprecated fields beside
1501                    // `port` for older versions; only a disagreement is news.
1502                    if deprecated != port {
1503                        warn!(
1504                            "daemon {short_name}: both `port` and deprecated expected_port/auto_bump_port/port_bump_attempts are set; ignoring deprecated fields"
1505                        );
1506                    }
1507                    Some(port)
1508                }
1509                (Some(port), None) => Some(port),
1510                (None, Some(deprecated)) => {
1511                    deprecated_at!(
1512                        "2026-10-03",
1513                        "2027-10-03",
1514                        format!("port-fields:{id}"),
1515                        "daemon {short_name}: expected_port/auto_bump_port/port_bump_attempts are deprecated, use [daemons.{short_name}.port] instead."
1516                    );
1517                    Some(deprecated)
1518                }
1519                (None, None) => None,
1520            };
1521
1522            // `proxy_port` is the shorter spelling of the same setting.
1523            if let (Some(explicit), Some(short)) =
1524                (raw_daemon.proxy_tls_port, raw_daemon.proxy_port)
1525                && explicit != short
1526            {
1527                warn!(
1528                    "daemon {short_name}: proxy_tls_port ({explicit}) and proxy_port ({short}) \
1529                     disagree; using proxy_tls_port"
1530                );
1531            }
1532            let proxy_tls_port = raw_daemon.proxy_tls_port.or(raw_daemon.proxy_port);
1533
1534            // Port 0 asks the operating system to choose, so it names no port
1535            // a hostname can be sent to.
1536            for (key, value) in [
1537                ("proxy_tls_port", raw_daemon.proxy_tls_port),
1538                ("proxy_port", raw_daemon.proxy_port),
1539            ] {
1540                if value == Some(0) {
1541                    return Err(ConfigParseError::ProxyPortZero {
1542                        daemon: short_name.clone(),
1543                        key,
1544                        path: path.to_path_buf(),
1545                    }
1546                    .into());
1547                }
1548            }
1549
1550            // The hostname maps to one of the daemon's own ports, so a port it
1551            // never declares cannot be routed to.
1552            if let Some(port_want) = proxy_tls_port {
1553                let declared = port.as_ref().map(|p| p.expect.clone()).unwrap_or_default();
1554                if !declared.contains(&port_want) {
1555                    return Err(ConfigParseError::ProxyPortNotDeclared {
1556                        daemon: short_name.clone(),
1557                        port: port_want,
1558                        declared,
1559                        path: path.to_path_buf(),
1560                    }
1561                    .into());
1562                }
1563            }
1564
1565            // TLS passthrough splices the raw stream to 127.0.0.1:<port>, so a
1566            // daemon without a known port has nothing to splice to.
1567            if raw_daemon
1568                .proxy_tls
1569                .is_some_and(ProxyTlsMode::is_passthrough)
1570                && port
1571                    .as_ref()
1572                    .is_none_or(|p| p.expect.iter().all(|&port| port == 0))
1573            {
1574                return Err(ConfigParseError::PassthroughWithoutPort {
1575                    daemon: short_name.clone(),
1576                    path: path.to_path_buf(),
1577                }
1578                .into());
1579            }
1580
1581            if let RunCommand::Argv(argv) = &raw_daemon.run {
1582                match argv.first().map(String::as_str) {
1583                    None => {
1584                        return Err(ConfigParseError::EmptyRunArgv {
1585                            daemon: short_name.clone(),
1586                            path: path.to_path_buf(),
1587                        }
1588                        .into());
1589                    }
1590                    // Almost certainly a shell command line carried over: in
1591                    // an array it would look for a program called `exec`.
1592                    Some("exec") => {
1593                        return Err(ConfigParseError::ExecInRunArgv {
1594                            daemon: short_name.clone(),
1595                            path: path.to_path_buf(),
1596                        }
1597                        .into());
1598                    }
1599                    Some(_) => {}
1600                }
1601            }
1602
1603            if let Some(RunCommand::Argv(argv)) = raw_daemon.ready_cmd.as_ref().map(|c| &c.run) {
1604                match argv.first().map(String::as_str) {
1605                    // An empty program would fail every probe, and with no
1606                    // timeout the start would wait for readiness forever.
1607                    None | Some("") => {
1608                        return Err(ConfigParseError::EmptyReadyCmdArgv {
1609                            daemon: short_name.clone(),
1610                            path: path.to_path_buf(),
1611                        }
1612                        .into());
1613                    }
1614                    Some("exec") => {
1615                        return Err(ConfigParseError::ExecInReadyCmdArgv {
1616                            daemon: short_name.clone(),
1617                            path: path.to_path_buf(),
1618                        }
1619                        .into());
1620                    }
1621                    Some(_) => {}
1622                }
1623            }
1624
1625            if let Some(RunCommand::Argv(argv)) = raw_daemon.health_cmd.as_ref().map(|c| &c.run) {
1626                match argv.first().map(String::as_str) {
1627                    // An empty program would fail every probe, and the daemon
1628                    // would be killed once its health check retries ran out.
1629                    None | Some("") => {
1630                        return Err(ConfigParseError::EmptyHealthCmdArgv {
1631                            daemon: short_name.clone(),
1632                            path: path.to_path_buf(),
1633                        }
1634                        .into());
1635                    }
1636                    Some("exec") => {
1637                        return Err(ConfigParseError::ExecInHealthCmdArgv {
1638                            daemon: short_name.clone(),
1639                            path: path.to_path_buf(),
1640                        }
1641                        .into());
1642                    }
1643                    Some(_) => {}
1644                }
1645            }
1646
1647            let daemon = PitchforkTomlDaemon {
1648                run: raw_daemon.run,
1649                auto: raw_daemon.auto,
1650                oneshot: raw_daemon.oneshot,
1651                cron: raw_daemon.cron,
1652                retry: raw_daemon.retry,
1653                ready_delay: raw_daemon.ready_delay,
1654                ready_output: raw_daemon.ready_output,
1655                ready_http: raw_daemon.ready_http,
1656                ready_port: raw_daemon.ready_port,
1657                ready_cmd: raw_daemon.ready_cmd,
1658                health_cmd: raw_daemon.health_cmd,
1659                health_http: raw_daemon.health_http,
1660                health_port: raw_daemon.health_port,
1661                port,
1662                proxy: raw_daemon.proxy,
1663                proxy_tls: raw_daemon.proxy_tls,
1664                proxy_protocol: raw_daemon.proxy_protocol,
1665                proxy_tls_port: raw_daemon.proxy_tls_port,
1666                proxy_port: raw_daemon.proxy_port,
1667                proxy_idle_timeout: raw_daemon.proxy_idle_timeout,
1668                boot_start: raw_daemon.boot_start,
1669                depends,
1670                watch: raw_daemon.watch,
1671                watch_mode: raw_daemon.watch_mode.unwrap_or_default(),
1672                dir: raw_daemon.dir,
1673                env: raw_daemon.env,
1674                env_file: raw_daemon.env_file,
1675                hooks: raw_daemon.hooks,
1676                mise: raw_daemon.mise,
1677                deferred_template_context: None,
1678                user: raw_daemon.user,
1679                memory_limit: raw_daemon.memory_limit,
1680                cpu_limit: raw_daemon.cpu_limit,
1681                stop_signal: raw_daemon.stop_signal,
1682                pty: raw_daemon.pty,
1683                time_retention: raw_daemon.time_retention,
1684                line_retention: raw_daemon.line_retention,
1685                archive_hook: raw_daemon.archive_hook,
1686                logs: raw_daemon.logs,
1687                path: Some(path.to_path_buf()),
1688            };
1689            if daemon.is_oneshot() {
1690                let conflicts = daemon.oneshot_conflicts();
1691                if !conflicts.is_empty() {
1692                    return Err(ConfigParseError::OneshotConflict {
1693                        daemon: short_name.clone(),
1694                        path: path.to_path_buf(),
1695                        conflicts: conflicts.into_iter().map(str::to_string).collect(),
1696                    }
1697                    .into());
1698                }
1699            }
1700            pt.daemons.insert(id, daemon);
1701        }
1702
1703        // Copy settings if present
1704        if let Some(settings) = raw_config.settings {
1705            pt.settings = settings;
1706        }
1707
1708        // Copy top-level env
1709        pt.env = raw_config.env;
1710
1711        // Copy slugs registry (only meaningful in global config files)
1712        for (slug, entry) in raw_config.slugs {
1713            pt.slugs.insert(
1714                slug,
1715                SlugEntry {
1716                    dir: entry.dir.map(env::expand_tilde),
1717                    namespace: entry.namespace,
1718                    daemon: entry.daemon,
1719                },
1720            );
1721        }
1722
1723        // Copy namespaces registry (only meaningful in global config files)
1724        for (name, entry) in raw_config.namespaces {
1725            pt.namespaces.insert(
1726                name,
1727                NamespaceEntry {
1728                    config: entry
1729                        .config
1730                        .iter()
1731                        .map(|p| {
1732                            crate::extra_configs::resolve_path(&env::expand_tilde(&entry.dir), p)
1733                        })
1734                        .collect(),
1735                    dir: env::expand_tilde(entry.dir),
1736                    label: entry.label,
1737                },
1738            );
1739        }
1740
1741        // Resolve group entries: convert short daemon names to qualified DaemonIds
1742        for (group_name, raw_group) in raw_config.groups {
1743            let mut daemons = Vec::new();
1744            for daemon_name in &raw_group.daemons {
1745                let id = if daemon_name.contains('/') {
1746                    DaemonId::parse(daemon_name).map_err(|e| {
1747                        ConfigParseError::InvalidDependency {
1748                            daemon: group_name.clone(),
1749                            dependency: daemon_name.clone(),
1750                            path: path.to_path_buf(),
1751                            reason: e.to_string(),
1752                        }
1753                    })?
1754                } else {
1755                    DaemonId::try_new(&namespace, daemon_name).map_err(|e| {
1756                        ConfigParseError::InvalidDaemonName {
1757                            name: daemon_name.clone(),
1758                            path: path.to_path_buf(),
1759                            reason: e.to_string(),
1760                        }
1761                    })?
1762                };
1763                daemons.push(id);
1764            }
1765            pt.groups.insert(
1766                group_name,
1767                GroupEntry {
1768                    daemons,
1769                    groups: raw_group.groups,
1770                },
1771            );
1772        }
1773
1774        pt.themes = raw_config.themes;
1775
1776        Ok(pt)
1777    }
1778
1779    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
1780        let path = path.as_ref();
1781        if !path.exists() {
1782            return Ok(Self::new(path.to_path_buf()));
1783        }
1784        let _lock = xx::fslock::get(path, false)
1785            .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1786        let raw = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
1787            path: path.to_path_buf(),
1788            source: e,
1789        })?;
1790        Self::parse_str(&raw, path)
1791    }
1792
1793    pub fn write(&self) -> Result<()> {
1794        if let Some(path) = &self.path {
1795            let _lock = xx::fslock::get(path, false)
1796                .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
1797            self.write_unlocked()
1798        } else {
1799            Err(FileError::NoPath.into())
1800        }
1801    }
1802
1803    /// Write the config file without acquiring a file lock.
1804    ///
1805    /// The caller MUST hold the file lock (via `xx::fslock::get`) before
1806    /// calling this method. This is used by `register_slug` which needs to
1807    /// hold a single lock across a read-modify-write cycle.
1808    pub(crate) fn write_unlocked(&self) -> Result<()> {
1809        if let Some(path) = &self.path {
1810            // Determine the namespace for this config file
1811            // A new file without its own `namespace` shares the one its
1812            // directory's other config files declare, as it will once read.
1813            let config_namespace = if path.exists() || self.namespace.is_none() {
1814                namespace_from_path(path)?
1815            } else {
1816                namespace_from_path_with_override(path, self.namespace.as_deref())?
1817            };
1818
1819            // Convert back to raw format for writing (use short names as keys)
1820            // Preserve settings so read-modify-write (e.g. `settings set`, `proxy add`)
1821            // doesn't drop `[settings.*]`. Gate on is_empty to avoid a bare `[settings]`.
1822            let mut raw = PitchforkTomlRaw {
1823                namespace: self.namespace.clone(),
1824                worktree_label: self.worktree_label.clone(),
1825                env: self.env.clone(),
1826                settings: (!self.settings.is_empty()).then(|| self.settings.clone()),
1827                themes: self.themes.clone(),
1828                ..PitchforkTomlRaw::default()
1829            };
1830            for (id, daemon) in &self.daemons {
1831                if id.namespace() != config_namespace {
1832                    return Err(miette::miette!(
1833                        "cannot write daemon '{}' to {}: daemon belongs to namespace '{}' but file namespace is '{}'",
1834                        id,
1835                        path.display(),
1836                        id.namespace(),
1837                        config_namespace
1838                    ));
1839                }
1840                let port = daemon.port.as_ref();
1841                let raw_daemon = PitchforkTomlDaemonRaw {
1842                    run: daemon.run.clone(),
1843                    auto: daemon.auto.clone(),
1844                    oneshot: daemon.oneshot,
1845                    cron: daemon.cron.clone(),
1846                    retry: daemon.retry,
1847                    ready_delay: daemon.ready_delay,
1848                    ready_output: daemon.ready_output.clone(),
1849                    ready_http: daemon.ready_http.clone(),
1850                    ready_port: daemon.ready_port.clone(),
1851                    ready_cmd: daemon.ready_cmd.clone(),
1852                    health_cmd: daemon.health_cmd.clone(),
1853                    health_http: daemon.health_http.clone(),
1854                    health_port: daemon.health_port.clone(),
1855                    port: port.cloned(),
1856                    proxy: daemon.proxy.clone(),
1857                    proxy_tls: daemon.proxy_tls,
1858                    proxy_protocol: daemon.proxy_protocol,
1859                    proxy_tls_port: daemon.proxy_tls_port,
1860                    proxy_port: daemon.proxy_port,
1861                    proxy_idle_timeout: daemon.proxy_idle_timeout,
1862                    // Deprecated fields: written for backward compatibility with older pitchfork versions
1863                    expected_port: port.map(|p| p.expect.clone()).unwrap_or_default(),
1864                    auto_bump_port: port.filter(|p| p.auto_bump()).map(|_| true),
1865                    port_bump_attempts: port
1866                        .filter(|p| p.auto_bump())
1867                        .map(|p| p.max_bump_attempts()),
1868                    boot_start: daemon.boot_start,
1869                    // Preserve cross-namespace dependencies: use qualified ID if namespace differs,
1870                    // otherwise use short name
1871                    depends: daemon
1872                        .depends
1873                        .iter()
1874                        .map(|d| {
1875                            if d.namespace() == config_namespace {
1876                                d.name().to_string()
1877                            } else {
1878                                d.qualified()
1879                            }
1880                        })
1881                        .collect(),
1882                    watch: daemon.watch.clone(),
1883                    watch_mode: match daemon.watch_mode {
1884                        WatchMode::Native => None,
1885                        mode => Some(mode),
1886                    },
1887                    dir: daemon.dir.clone(),
1888                    env: daemon.env.clone(),
1889                    env_file: daemon.env_file.clone(),
1890                    hooks: daemon.hooks.clone(),
1891                    mise: daemon.mise,
1892                    user: daemon.user.clone(),
1893                    memory_limit: daemon.memory_limit,
1894                    cpu_limit: daemon.cpu_limit,
1895                    stop_signal: daemon.stop_signal,
1896                    pty: daemon.pty,
1897                    time_retention: daemon.time_retention.clone(),
1898                    line_retention: daemon.line_retention,
1899                    archive_hook: daemon.archive_hook.clone(),
1900                    logs: daemon.logs.clone(),
1901                };
1902                raw.daemons.insert(id.name().to_string(), raw_daemon);
1903            }
1904
1905            // Copy slugs registry to raw format
1906            for (slug, entry) in &self.slugs {
1907                raw.slugs.insert(
1908                    slug.clone(),
1909                    SlugEntryRaw {
1910                        dir: entry.dir.as_ref().map(|d| d.to_string_lossy().to_string()),
1911                        namespace: entry.namespace.clone(),
1912                        daemon: entry.daemon.clone(),
1913                    },
1914                );
1915            }
1916
1917            // Serialize groups back to raw format (preserve cross-namespace refs as qualified IDs)
1918            for (name, group) in &self.groups {
1919                let raw_daemons: Vec<String> = group
1920                    .daemons
1921                    .iter()
1922                    .map(|id| {
1923                        if id.namespace() == config_namespace {
1924                            id.name().to_string()
1925                        } else {
1926                            id.qualified()
1927                        }
1928                    })
1929                    .collect();
1930                raw.groups.insert(
1931                    name.clone(),
1932                    GroupEntryRaw {
1933                        daemons: raw_daemons,
1934                        groups: group.groups.clone(),
1935                    },
1936                );
1937            }
1938
1939            // Copy namespaces registry to raw format
1940            for (name, entry) in &self.namespaces {
1941                raw.namespaces.insert(
1942                    name.clone(),
1943                    NamespaceEntryRaw {
1944                        dir: entry.dir.to_string_lossy().to_string(),
1945                        config: entry
1946                            .config
1947                            .iter()
1948                            .map(|p| p.to_string_lossy().into_owned())
1949                            .collect(),
1950                        label: entry.label.clone(),
1951                    },
1952                );
1953            }
1954
1955            let raw_str = toml::to_string(&raw).map_err(|e| FileError::SerializeError {
1956                path: path.clone(),
1957                source: e,
1958            })?;
1959            xx::file::write(path, &raw_str).map_err(|e| FileError::WriteError {
1960                path: path.clone(),
1961                details: Some(e.to_string()),
1962            })?;
1963            invalidate_config_cache();
1964            Ok(())
1965        } else {
1966            Err(FileError::NoPath.into())
1967        }
1968    }
1969
1970    /// Simple merge without namespace re-qualification.
1971    /// Used primarily for testing or when merging configs from the same namespace.
1972    /// Since read() already qualifies daemon IDs with namespace, this just inserts them.
1973    /// Settings are also merged - later values override earlier ones.
1974    pub fn merge(&mut self, pt: Self) {
1975        if pt.worktree_label.is_some() {
1976            self.worktree_label = pt.worktree_label.clone();
1977        }
1978        for (id, d) in pt.daemons {
1979            self.daemons.insert(id, d);
1980        }
1981        // Merge top-level env - pt's values override self's values
1982        if let Some(env) = pt.env {
1983            let merged = self.env.get_or_insert_with(IndexMap::new);
1984            for (k, v) in env {
1985                merged.insert(k, v);
1986            }
1987        }
1988        // Merge slugs - pt's values override self's values
1989        for (slug, entry) in pt.slugs {
1990            self.slugs.insert(slug, entry);
1991        }
1992        // Merge groups - pt's values override self's values
1993        for (name, group) in pt.groups {
1994            self.groups.insert(name, group);
1995        }
1996        // Merge namespaces - pt's values override self's values
1997        for (name, entry) in pt.namespaces {
1998            self.namespaces.insert(name, entry);
1999        }
2000        // Merge themes - pt's values override self's values
2001        for (name, theme) in pt.themes {
2002            self.themes.insert(name, theme);
2003        }
2004        // Merge settings - pt's values override self's values
2005        self.settings.merge_from(&pt.settings);
2006    }
2007
2008    /// Read the global slug registry from the user-level global config.
2009    ///
2010    /// Returns a map of slug → SlugEntry from `[slugs]` in
2011    /// `~/.config/pitchfork/config.toml`.
2012    pub fn read_global_slugs() -> IndexMap<String, SlugEntry> {
2013        match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
2014            Ok(pt) => pt.slugs,
2015            Err(_) => IndexMap::new(),
2016        }
2017    }
2018
2019    /// Whether more than one registry key folds to `slug`'s ASCII-lowercased form.
2020    ///
2021    /// Host names are case-insensitive (RFC 4343), so the proxy refuses to route
2022    /// such a slug at all rather than pick one of the spellings.  Callers that
2023    /// turn a slug into a URL must not advertise an address the proxy will
2024    /// reject, so they check this first.
2025    pub fn slug_is_ambiguous(slug: &str, global_slugs: &IndexMap<String, SlugEntry>) -> bool {
2026        global_slugs
2027            .keys()
2028            .filter(|k| k.eq_ignore_ascii_case(slug))
2029            .count()
2030            > 1
2031    }
2032
2033    /// Find the registered slug for a daemon using a pre-loaded slug registry.
2034    ///
2035    /// Returns `None` for a slug the proxy will not route — see
2036    /// [`Self::slug_is_ambiguous`].
2037    pub fn find_slug_for_daemon_in_registry(
2038        daemon_id: &DaemonId,
2039        global_slugs: &IndexMap<String, SlugEntry>,
2040    ) -> Option<String> {
2041        global_slugs
2042            .iter()
2043            .find(|(slug, entry)| {
2044                let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
2045                if daemon_id.name() != daemon_name {
2046                    return false;
2047                }
2048
2049                // Skipped rather than returned and discarded: another alias for
2050                // the same daemon may still be routable.
2051                if Self::slug_is_ambiguous(slug, global_slugs) {
2052                    return false;
2053                }
2054
2055                match entry.resolve_namespace() {
2056                    Some(namespace) => daemon_id.namespace() == namespace,
2057                    None => false,
2058                }
2059            })
2060            .map(|(slug, _)| slug.clone())
2061    }
2062
2063    /// Check if a slug is registered in the global config's `[slugs]` section.
2064    #[allow(dead_code)]
2065    pub fn is_slug_registered(slug: &str) -> bool {
2066        Self::read_global_slugs().contains_key(slug)
2067    }
2068
2069    /// Add a slug entry to the global config's `[slugs]` section using namespace instead of dir.
2070    ///
2071    /// Reads the global config, adds/updates the slug entry, and writes it back.
2072    /// If `namespace` is provided but not yet registered in `[namespaces]`,
2073    /// also registers it at `dir` (acquired via `resolve_dir()` on the slug entry).
2074    pub fn add_slug_with_namespace(
2075        slug: &str,
2076        namespace: Option<&str>,
2077        daemon: Option<&str>,
2078    ) -> Result<()> {
2079        let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2080
2081        // Ensure the config directory exists
2082        if let Some(parent) = global_path.parent() {
2083            std::fs::create_dir_all(parent).map_err(|e| {
2084                miette::miette!(
2085                    "Failed to create config directory {}: {e}",
2086                    parent.display()
2087                )
2088            })?;
2089        }
2090
2091        let _lock = xx::fslock::get(global_path, false)
2092            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2093
2094        let mut pt = if global_path.exists() {
2095            let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2096                path: global_path.to_path_buf(),
2097                source: e,
2098            })?;
2099            Self::parse_str(&raw, global_path)?
2100        } else {
2101            Self::new(global_path.to_path_buf())
2102        };
2103
2104        // If caller provided a namespace that isn't yet registered,
2105        // auto-register it at the directory we can resolve.
2106        // Falls back to CWD if the slug dir cannot be resolved.
2107        if let Some(ns) = namespace
2108            && !pt.namespaces.contains_key(ns)
2109        {
2110            // Resolve against the already-parsed `pt` instead of
2111            // SlugEntry::resolve_dir(): that re-reads the global config via
2112            // read(), which would re-acquire the lock held above (flock is per
2113            // open file description, so the same process deadlocks on itself).
2114            let dir = pt
2115                .slugs
2116                .get(slug)
2117                .and_then(|e| {
2118                    e.dir.clone().or_else(|| {
2119                        e.namespace
2120                            .as_ref()
2121                            .and_then(|ns| pt.namespaces.get(ns).map(|entry| entry.dir.clone()))
2122                    })
2123                })
2124                .or_else(|| env::CWD.as_path().canonicalize().ok());
2125            if let Some(ref d) = dir {
2126                pt.namespaces.insert(
2127                    ns.to_string(),
2128                    NamespaceEntry {
2129                        dir: d.clone(),
2130                        config: Vec::new(),
2131                        label: None,
2132                    },
2133                );
2134            }
2135        }
2136
2137        pt.slugs.insert(
2138            slug.to_string(),
2139            SlugEntry {
2140                dir: None,
2141                namespace: namespace.map(str::to_string),
2142                daemon: daemon.map(str::to_string),
2143            },
2144        );
2145        pt.write_unlocked()?;
2146        // Sync hosts from the in-memory slug set, not sync_hosts_from_settings():
2147        // that re-reads the global config via read(), which acquires the lock held
2148        // above — flock is per open file description, so re-acquiring in the same
2149        // process deadlocks against our own lock. Staying under the lock also keeps
2150        // hosts writes ordered with config mutations across concurrent commands.
2151        let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2152        crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2153        Ok(())
2154    }
2155
2156    /// Remove a slug from the global config's `[slugs]` section.
2157    pub fn remove_slug(slug: &str) -> Result<bool> {
2158        let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2159        if !global_path.exists() {
2160            return Ok(false);
2161        }
2162
2163        let _lock = xx::fslock::get(global_path, false)
2164            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2165
2166        let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2167            path: global_path.to_path_buf(),
2168            source: e,
2169        })?;
2170        let mut pt = Self::parse_str(&raw, global_path)?;
2171
2172        let removed = pt.slugs.shift_remove(slug).is_some();
2173        if removed {
2174            pt.write_unlocked()?;
2175            // Sync hosts from the in-memory slug set, not sync_hosts_from_settings():
2176            // that re-reads the global config via read(), which acquires the lock held
2177            // above — flock is per open file description, so re-acquiring in the same
2178            // process deadlocks against our own lock. Staying under the lock also keeps
2179            // hosts writes ordered with config mutations across concurrent commands.
2180            let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2181            crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2182        }
2183        Ok(removed)
2184    }
2185    /// Returns a map of namespace → NamespaceEntry from `[namespaces]` in
2186    /// `~/.config/pitchfork/config.toml`.
2187    pub fn read_global_namespaces() -> IndexMap<String, NamespaceEntry> {
2188        match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
2189            Ok(pt) => pt.namespaces,
2190            Err(_) => IndexMap::new(),
2191        }
2192    }
2193
2194    /// Add a namespace entry to the global config's `[namespaces]` section.
2195    ///
2196    /// Reads the global config, adds/updates the namespace entry, and writes it back.
2197    pub fn register_namespace(name: &str, dir: &str) -> crate::Result<()> {
2198        let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2199
2200        // Ensure the config directory exists
2201        if let Some(parent) = global_path.parent() {
2202            std::fs::create_dir_all(parent).map_err(|e| {
2203                miette::miette!(
2204                    "Failed to create config directory {}: {e}",
2205                    parent.display()
2206                )
2207            })?;
2208        }
2209
2210        let _lock = xx::fslock::get(global_path, false)
2211            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2212
2213        let mut pt = if global_path.exists() {
2214            let raw = std::fs::read_to_string(global_path).map_err(|e| {
2215                crate::error::FileError::ReadError {
2216                    path: global_path.to_path_buf(),
2217                    source: e,
2218                }
2219            })?;
2220            Self::parse_str(&raw, global_path)?
2221        } else {
2222            Self::new(global_path.to_path_buf())
2223        };
2224
2225        let dir = env::expand_tilde(dir);
2226        if let Some(entry) = pt.namespaces.get_mut(name) {
2227            if crate::extra_configs::path_is_gone(&entry.dir)
2228                && crate::extra_configs::normalize(&entry.dir)
2229                    != crate::extra_configs::normalize(&dir)
2230            {
2231                if crate::extra_configs::namespace_has_running_daemon(name) {
2232                    // Retargeting would show the old project's running daemons
2233                    // to the new one.
2234                    miette::bail!(
2235                        "namespace '{name}' has running daemons from {}, which no longer exists; stop them first",
2236                        entry.dir.display()
2237                    );
2238                }
2239                // The old project is gone: its attachments and label go with it.
2240                entry.config.clear();
2241                entry.label = None;
2242            }
2243            if !entry.config.is_empty()
2244                && crate::extra_configs::normalize(&entry.dir)
2245                    != crate::extra_configs::normalize(&dir)
2246            {
2247                miette::bail!(
2248                    "namespace '{name}' has external configuration attached to another directory"
2249                );
2250            }
2251            entry.dir = dir;
2252        } else {
2253            pt.namespaces.insert(
2254                name.to_string(),
2255                NamespaceEntry {
2256                    dir,
2257                    config: Vec::new(),
2258                    label: None,
2259                },
2260            );
2261        }
2262        pt.write_unlocked()?;
2263        Ok(())
2264    }
2265
2266    /// Remove a namespace from the global config's `[namespaces]` section.
2267    pub fn remove_namespace(name: &str) -> crate::Result<bool> {
2268        let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
2269        if !global_path.exists() {
2270            return Ok(false);
2271        }
2272
2273        let _lock = xx::fslock::get(global_path, false)
2274            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2275
2276        let raw = std::fs::read_to_string(global_path).map_err(|e| {
2277            crate::error::FileError::ReadError {
2278                path: global_path.to_path_buf(),
2279                source: e,
2280            }
2281        })?;
2282        let mut pt = Self::parse_str(&raw, global_path)?;
2283
2284        let removed = pt.namespaces.shift_remove(name).is_some();
2285        if removed {
2286            pt.write_unlocked()?;
2287        }
2288        Ok(removed)
2289    }
2290}
2291
2292/// What [`PitchforkToml::prune_stale_registrations`] removed.
2293#[derive(Debug, Default, Clone, PartialEq, Eq)]
2294pub struct PruneReport {
2295    /// `[namespaces]` entries whose project directory no longer exists.
2296    pub namespaces: Vec<String>,
2297    /// `[slugs]` entries that pointed at a removed or missing directory.
2298    pub slugs: Vec<String>,
2299    /// Attached external configuration files that no longer exist.
2300    pub config_files: usize,
2301}
2302
2303impl PruneReport {
2304    pub fn is_empty(&self) -> bool {
2305        self.namespaces.is_empty() && self.slugs.is_empty() && self.config_files == 0
2306    }
2307}
2308
2309impl PitchforkToml {
2310    /// Drop `[namespaces]`, `[slugs]` and attached external config files in the
2311    /// user-level global config that point at paths that no longer exist.
2312    ///
2313    /// Tools and scratch projects register namespaces and slugs and are rarely
2314    /// able to unregister them when their directory is deleted, so the registry
2315    /// otherwise only ever grows.
2316    ///
2317    /// * `keep` names namespaces that must be left alone, typically those with
2318    ///   a running daemon.
2319    /// * `only` limits the pass to the listed namespaces; empty means all.
2320    ///
2321    /// A path is only treated as gone when the filesystem answers that it does
2322    /// not exist: an I/O error (permissions, a flaky mount) keeps the entry.
2323    pub fn prune_stale_registrations(
2324        keep: &std::collections::HashSet<String>,
2325        only: &[String],
2326    ) -> Result<PruneReport> {
2327        let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
2328        let mut report = PruneReport::default();
2329        if !global_path.exists() {
2330            return Ok(report);
2331        }
2332        let _lock = xx::fslock::get(global_path, false)
2333            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;
2334        let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
2335            path: global_path.to_path_buf(),
2336            source: e,
2337        })?;
2338        let mut pt = Self::parse_str(&raw, global_path)?;
2339        let in_scope = |ns: &str| only.is_empty() || only.iter().any(|o| o == ns);
2340
2341        for (name, entry) in pt.namespaces.iter_mut() {
2342            if keep.contains(name) || !in_scope(name) {
2343                continue;
2344            }
2345            if crate::extra_configs::path_is_gone(&entry.dir) {
2346                report.namespaces.push(name.clone());
2347                continue;
2348            }
2349            let before = entry.config.len();
2350            entry
2351                .config
2352                .retain(|file| !crate::extra_configs::path_is_gone(file));
2353            let dropped = before - entry.config.len();
2354            if dropped > 0 {
2355                report.config_files += dropped;
2356                if entry.config.is_empty() {
2357                    // Same as detaching the last file: the label goes with it.
2358                    entry.label = None;
2359                }
2360            }
2361        }
2362        for name in &report.namespaces {
2363            pt.namespaces.shift_remove(name);
2364        }
2365
2366        if only.is_empty() || !report.namespaces.is_empty() {
2367            for (slug, entry) in &pt.slugs {
2368                // A slug of a namespace with a running daemon stays, even if
2369                // its own directory moved.
2370                if entry.namespace.as_ref().is_some_and(|ns| keep.contains(ns)) {
2371                    continue;
2372                }
2373                let ns_pruned = entry
2374                    .namespace
2375                    .as_ref()
2376                    .is_some_and(|ns| report.namespaces.contains(ns));
2377                let dir_gone = entry
2378                    .dir
2379                    .as_ref()
2380                    .is_some_and(|d| crate::extra_configs::path_is_gone(d));
2381                // A slug that names a directory directly is only in scope for
2382                // an unscoped pass, since it belongs to no namespace.
2383                let scoped_ok = only.is_empty() || ns_pruned;
2384                if scoped_ok && (ns_pruned || dir_gone) {
2385                    report.slugs.push(slug.clone());
2386                }
2387            }
2388            for slug in &report.slugs {
2389                pt.slugs.shift_remove(slug);
2390            }
2391        }
2392
2393        if !report.is_empty() {
2394            pt.write_unlocked()?;
2395            if !report.slugs.is_empty() {
2396                let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
2397                crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
2398            }
2399        }
2400        Ok(report)
2401    }
2402}
2403
2404/// Configuration for a single daemon (internal representation with DaemonId)
2405#[derive(Debug, Clone, JsonSchema, Default)]
2406pub struct PitchforkTomlDaemon {
2407    /// The command to run: a command line for the shell, or an array of a
2408    /// program and its arguments to start without a shell. In the string
2409    /// form, prepend 'exec' to avoid shell process overhead.
2410    #[schemars(example = example_run_command())]
2411    pub run: RunCommand,
2412    /// Automatic start/stop behavior based on shell hooks
2413    #[schemars(default)]
2414    pub auto: Vec<PitchforkTomlAuto>,
2415    /// Run this daemon as a task that must finish rather than a long-running
2416    /// service. Readiness means the process exited with code 0, the daemon
2417    /// then reports the `completed` status, and daemons that `depends` on it
2418    /// wait for that completion. Cannot be combined with any `ready_*` or
2419    /// `health_*` field.
2420    pub oneshot: Option<bool>,
2421    /// Cron scheduling configuration for periodic execution
2422    pub cron: Option<PitchforkTomlCron>,
2423    /// Number of times to retry if the daemon fails.
2424    /// Can be a number (e.g., `3`) or `true` for infinite retries.
2425    #[schemars(default)]
2426    pub retry: Retry,
2427    /// Delay in seconds before considering the daemon ready
2428    pub ready_delay: Option<u64>,
2429    /// Regex pattern to match in ANSI-stripped stdout/stderr to determine readiness
2430    pub ready_output: Option<ReadyOutput>,
2431    /// HTTP URL to poll for readiness. Accepts any 2xx response by default, or configured statuses.
2432    pub ready_http: Option<ReadyHttp>,
2433    /// TCP port to check for readiness (connection success = ready).
2434    /// Accepts a port number, a Tera template string that renders to one, or an
2435    /// object with an optional overall polling timeout.
2436    pub ready_port: Option<ReadyPort>,
2437    /// Shell command to poll for readiness (exit code 0 = ready)
2438    pub ready_cmd: Option<ReadyCmd>,
2439    /// Shell command to poll for health (exit code 0 = healthy)
2440    pub health_cmd: Option<HealthCmd>,
2441    /// HTTP endpoint URL to poll for health
2442    pub health_http: Option<HealthHttp>,
2443    /// TCP port to probe for health (connection success = healthy).
2444    /// Accepts a port number, a Tera template string that renders to one, or an
2445    /// object with optional per-check `interval`, `retries`, and `timeout`.
2446    pub health_port: Option<HealthPort>,
2447    /// Port configuration: expected ports and auto-bump settings
2448    pub port: Option<PortConfig>,
2449    /// Proxy routing: `false` opts out of the automatic hostname, a string
2450    /// overrides the daemon label used in it.
2451    #[serde(skip_serializing_if = "Option::is_none", default)]
2452    pub proxy: Option<ProxyConfig>,
2453    /// TLS handling for this daemon's proxy hostname.
2454    ///
2455    /// - `terminate` (default): the proxy terminates TLS with its own
2456    ///   certificate and forwards plain HTTP to the daemon.
2457    /// - `passthrough`: the proxy reads the SNI hostname from the TLS
2458    ///   ClientHello and splices the raw TCP stream to the daemon, which
2459    ///   presents its own certificate and can require client certificates.
2460    ///   Requires `port`.
2461    pub proxy_tls: Option<ProxyTlsMode>,
2462    /// HTTP version the proxy speaks to this daemon.
2463    ///
2464    /// - `http1` (default): requests are forwarded as HTTP/1.1.
2465    /// - `h2c`: requests are forwarded as cleartext HTTP/2 with prior
2466    ///   knowledge, which gRPC servers require. Clients can still reach the
2467    ///   proxy over HTTP/1.1 or HTTP/2; this only changes the hop to the
2468    ///   daemon. WebSocket upgrades are not available on an `h2c` daemon.
2469    pub proxy_protocol: Option<ProxyProtocol>,
2470    /// Which of the daemon's ports the proxy hostname maps to.
2471    ///
2472    /// Must name one of the ports in `port`. Defaults to the daemon's first
2473    /// port. `proxy_port` is the shorter spelling of the same setting.
2474    #[schemars(range(min = 1))]
2475    pub proxy_tls_port: Option<u16>,
2476    /// Shorter spelling of `proxy_tls_port`. Set one or the other, not both.
2477    ///
2478    /// Kept separate rather than folded so that a config keeps the spelling
2479    /// its author chose when pitchfork rewrites it. Read
2480    /// [`Self::effective_proxy_tls_port`] rather than either field.
2481    #[schemars(range(min = 1))]
2482    pub proxy_port: Option<u16>,
2483    /// Idle timeout when the proxy auto-starts this daemon, for example `"15m"`.
2484    /// Accepts a duration string or `false`; `"0"` also disables idle shutdown.
2485    ///
2486    /// When omitted, a daemon started through its URL uses
2487    /// `settings.proxy.idle_timeout`; a dependency inherits the requested
2488    /// daemon's timeout. An explicit `false` exempts this daemon in either case.
2489    ///
2490    /// The timeout is recorded at startup. Explicitly started daemons are
2491    /// exempt; live dependents, active proxy connections, and tracked shell
2492    /// sessions prevent idle shutdown.
2493    pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
2494    /// Whether to start this daemon automatically on system boot
2495    pub boot_start: Option<bool>,
2496    /// List of daemon IDs that must be started before this one
2497    #[schemars(default)]
2498    pub depends: Vec<DaemonId>,
2499    /// File patterns to watch for changes
2500    #[schemars(default)]
2501    pub watch: Vec<String>,
2502    /// File watching backend mode.
2503    ///
2504    /// - `native`: use platform-native notifications (default)
2505    /// - `poll`: use polling-based watcher
2506    /// - `auto`: prefer native, fall back to polling if native watch fails
2507    #[schemars(default)]
2508    pub watch_mode: WatchMode,
2509    /// Working directory for the daemon. Relative paths are resolved from the pitchfork.toml location.
2510    pub dir: Option<String>,
2511    /// Environment variables to set for the daemon process
2512    pub env: Option<IndexMap<String, String>>,
2513    /// Dotenv files (e.g. `.env.local`) whose variables are added to the daemon's
2514    /// environment. Relative paths resolve from the project directory (the same base as
2515    /// `dir`); missing files are skipped. Values from `env` win over the files, and later files win
2516    /// over earlier ones. Values support Tera templates.
2517    #[serde(default)]
2518    pub env_file: Vec<String>,
2519    /// Lifecycle hooks (on_ready, on_fail, on_retry)
2520    pub hooks: Option<PitchforkTomlHooks>,
2521    /// Wrap this daemon's command with `mise x --` for tool/env setup.
2522    /// Overrides the global `settings.general.mise` when set.
2523    pub mise: Option<bool>,
2524    /// Pitchfork's template context as JSON, set while rendering when `run` was left
2525    /// unrendered for `mise x` to finish. Never read from or written to a file.
2526    #[schemars(skip)]
2527    pub deferred_template_context: Option<String>,
2528    /// Unix user to run this daemon as. Overrides `settings.supervisor.user` when set.
2529    /// On Windows, nonempty values prevent daemon startup with an error.
2530    pub user: Option<String>,
2531    /// Memory limit for the daemon process (e.g. "50MB", "1GiB").
2532    /// The supervisor periodically monitors RSS and kills the process if it exceeds the limit.
2533    pub memory_limit: Option<MemoryLimit>,
2534    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores).
2535    /// The supervisor periodically monitors CPU usage and kills the process if it exceeds the limit.
2536    pub cpu_limit: Option<CpuLimit>,
2537    /// Stop signal and optional per-daemon timeout. Accepts a signal name string
2538    /// or `{ signal = "...", timeout = "..." }` object.
2539    pub stop_signal: Option<StopConfig>,
2540    /// Allocate a pseudo-terminal on Unix. Windows rejects `true` at startup.
2541    pub pty: Option<bool>,
2542    /// Maximum age of log entries to keep (e.g. "7d", "30d").
2543    /// Overrides the global `settings.logs.time_retention` when set.
2544    pub time_retention: Option<String>,
2545    /// Maximum number of log entries to keep per daemon.
2546    /// Overrides the global `settings.logs.line_retention` when set.
2547    pub line_retention: Option<i64>,
2548    /// Archive hook command invoked before retention prunes this daemon's logs.
2549    /// Overrides the global `settings.logs.archive_hook.command` when set.
2550    pub archive_hook: Option<String>,
2551    /// Per-daemon log configuration sub-table.
2552    pub logs: Option<PitchforkTomlDaemonLogs>,
2553    #[schemars(skip)]
2554    pub path: Option<PathBuf>,
2555}
2556
2557impl PitchforkTomlDaemon {
2558    /// Which of the daemon's ports its proxy hostname maps to, from either
2559    /// spelling of the setting.
2560    ///
2561    /// `proxy_tls_port` wins when both are set; parsing has already warned
2562    /// about that combination.
2563    pub fn effective_proxy_tls_port(&self) -> Option<u16> {
2564        self.proxy_tls_port.or(self.proxy_port)
2565    }
2566
2567    /// Whether this daemon is a oneshot task (`oneshot = true`).
2568    pub fn is_oneshot(&self) -> bool {
2569        self.oneshot.unwrap_or(false)
2570    }
2571
2572    /// Names of the readiness and health fields that are set on this daemon
2573    /// and cannot be combined with `oneshot`. Empty when there is no conflict.
2574    pub(crate) fn oneshot_conflicts(&self) -> Vec<&'static str> {
2575        [
2576            ("ready_delay", self.ready_delay.is_some()),
2577            ("ready_output", self.ready_output.is_some()),
2578            ("ready_http", self.ready_http.is_some()),
2579            ("ready_port", self.ready_port.is_some()),
2580            ("ready_cmd", self.ready_cmd.is_some()),
2581            ("health_cmd", self.health_cmd.is_some()),
2582            ("health_http", self.health_http.is_some()),
2583            ("health_port", self.health_port.is_some()),
2584        ]
2585        .into_iter()
2586        .filter(|(_, set)| *set)
2587        .map(|(name, _)| name)
2588        .collect()
2589    }
2590
2591    /// Effective user for this daemon: per-daemon `user` overrides `settings.supervisor.user`.
2592    ///
2593    /// Returns `None` when neither is set (inherit the supervisor's user).
2594    pub fn effective_user(&self) -> Option<String> {
2595        let daemon_user = self
2596            .user
2597            .as_deref()
2598            .map(str::trim)
2599            .filter(|u| !u.is_empty());
2600        daemon_user.map(str::to_owned).or_else(|| {
2601            let s = crate::settings::settings();
2602            let su = s.supervisor.user.trim();
2603            (!su.is_empty()).then(|| su.to_owned())
2604        })
2605    }
2606
2607    /// Build RunOptions from this daemon configuration.
2608    ///
2609    /// Carries over all config fields and resolves the working directory.
2610    /// Callers can override specific fields on the returned value.
2611    pub fn to_run_options(
2612        &self,
2613        id: &crate::daemon_id::DaemonId,
2614        cmd: Vec<String>,
2615    ) -> crate::daemon::RunOptions {
2616        use crate::daemon::RunOptions;
2617
2618        let effective_user = self.effective_user();
2619        let dir = crate::ipc::batch::resolve_daemon_dir(
2620            self.dir.as_deref(),
2621            self.path.as_deref(),
2622            effective_user.as_deref(),
2623        );
2624        // The same lookup the proxy and the CLI use, so a slug the proxy
2625        // refuses to route as ambiguous is not handed to the daemon either.
2626        let slug = PitchforkToml::find_slug_for_daemon_in_registry(
2627            id,
2628            &PitchforkToml::read_global_slugs(),
2629        );
2630
2631        RunOptions {
2632            id: id.clone(),
2633            cmd,
2634            run: self.run.shell_script().map(str::to_string),
2635            no_shell: self.run.is_argv(),
2636            replaces_ready_checks: false,
2637            // Set by the IPC handler for a client's own request.
2638            requested_by_client: false,
2639            force: false,
2640            shell_pid: None,
2641            dir: Dir(dir),
2642            autostop: self.auto.contains(&PitchforkTomlAuto::Stop),
2643            oneshot: self.is_oneshot(),
2644            // Set only by the cron watcher's own call; a start built from
2645            // config is not the schedule asking for a run.
2646            cron_started: false,
2647            // Filled in by `build_run_options`, which resolves it against the
2648            // daemon's own project rather than whatever directory this process
2649            // happens to be in.
2650            oneshot_wait: None,
2651            on_directory_enter: false,
2652            cron_schedule: self.cron.as_ref().map(|c| c.schedule.clone()),
2653            cron_retrigger: self.cron.as_ref().map(|c| c.retrigger),
2654            cron_immediate: self.cron.as_ref().map(|c| c.immediate),
2655            retry: self.retry,
2656            retry_count: 0,
2657            ready_delay: self.ready_delay,
2658            ready_output: self.ready_output.clone(),
2659            ready_http: self.ready_http.clone(),
2660            ready_port: self.ready_port.clone(),
2661            ready_cmd: self.ready_cmd.clone(),
2662            health_cmd: self.health_cmd.clone(),
2663            health_http: self.health_http.clone(),
2664            health_port: self.health_port.clone(),
2665            port: self.port.clone(),
2666            wait_ready: false,
2667            depends: self.depends.clone(),
2668            env: self.env.clone(),
2669            watch: self.watch.clone(),
2670            watch_mode: self.watch_mode,
2671            watch_base_dir: Some(crate::ipc::batch::resolve_config_base_dir(
2672                self.path.as_deref(),
2673            )),
2674            mise: self.mise,
2675            deferred_template_context: self.deferred_template_context.clone(),
2676            // Resolved from the project settings by `build_run_options`.
2677            mise_bin: None,
2678            slug,
2679            proxy: None,
2680            user: self.user.clone(),
2681            memory_limit: self.memory_limit,
2682            cpu_limit: self.cpu_limit,
2683            stop_signal: self.stop_signal,
2684            archive_hook: self
2685                .logs
2686                .as_ref()
2687                .and_then(|l| l.archive_hook.clone())
2688                .or_else(|| self.archive_hook.clone()),
2689            log_format: self.logs.as_ref().and_then(|l| l.log_format.clone()),
2690            on_output_hook: self.hooks.as_ref().and_then(|h| h.on_output.clone()),
2691            pty: self.pty,
2692            // Explicit unless the proxy's start marks it otherwise.
2693            proxy_idle_timeout_ms: None,
2694            replaces_saved_record: true,
2695        }
2696    }
2697}
2698fn example_run_command() -> &'static str {
2699    "exec node server.js"
2700}
2701
2702/// A daemon's `run`: a command line for the shell, or a program and its
2703/// arguments to start without one.
2704#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, JsonSchema)]
2705#[serde(untagged)]
2706pub enum RunCommand {
2707    /// A command line, passed verbatim to the shell (`general.shell`, or
2708    /// `general.windows_shell` on Windows).
2709    Shell(String),
2710    /// A program and its arguments, started directly. No shell interprets
2711    /// them, so each argument reaches the program exactly as written, on
2712    /// every platform.
2713    Argv(#[schemars(length(min = 1))] Vec<String>),
2714}
2715
2716impl Default for RunCommand {
2717    fn default() -> Self {
2718        Self::Shell(String::new())
2719    }
2720}
2721
2722impl From<String> for RunCommand {
2723    fn from(run: String) -> Self {
2724        Self::Shell(run)
2725    }
2726}
2727
2728impl From<&str> for RunCommand {
2729    fn from(run: &str) -> Self {
2730        Self::Shell(run.to_string())
2731    }
2732}
2733
2734impl From<Vec<String>> for RunCommand {
2735    fn from(argv: Vec<String>) -> Self {
2736        Self::Argv(argv)
2737    }
2738}
2739
2740impl PartialEq<str> for RunCommand {
2741    fn eq(&self, other: &str) -> bool {
2742        matches!(self, Self::Shell(run) if run == other)
2743    }
2744}
2745
2746impl PartialEq<&str> for RunCommand {
2747    fn eq(&self, other: &&str) -> bool {
2748        self == *other
2749    }
2750}
2751
2752/// The command as a user would read it: the shell form as written, the argv
2753/// form quoted for a POSIX shell.
2754impl std::fmt::Display for RunCommand {
2755    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2756        match self {
2757            Self::Shell(run) => f.write_str(run),
2758            Self::Argv(argv) => f.write_str(&shell_words::join(argv)),
2759        }
2760    }
2761}
2762
2763impl RunCommand {
2764    /// The command as separate words: the argv form as it is, the shell form
2765    /// split the way a POSIX shell would.
2766    pub fn argv(&self) -> std::result::Result<Vec<String>, shell_words::ParseError> {
2767        match self {
2768            Self::Shell(run) => shell_words::split(run),
2769            Self::Argv(argv) => Ok(argv.clone()),
2770        }
2771    }
2772
2773    /// The command line for the shell, or `None` for the argv form.
2774    pub fn shell_script(&self) -> Option<&str> {
2775        match self {
2776            Self::Shell(run) => Some(run),
2777            Self::Argv(_) => None,
2778        }
2779    }
2780
2781    pub fn is_argv(&self) -> bool {
2782        matches!(self, Self::Argv(_))
2783    }
2784
2785    /// Apply `f` to the command line, or to each argument of the argv form.
2786    pub fn try_map<E>(
2787        &self,
2788        mut f: impl FnMut(&str) -> std::result::Result<String, E>,
2789    ) -> std::result::Result<Self, E> {
2790        Ok(match self {
2791            Self::Shell(run) => Self::Shell(f(run)?),
2792            Self::Argv(argv) => Self::Argv(
2793                argv.iter()
2794                    .map(|arg| f(arg))
2795                    .collect::<std::result::Result<_, _>>()?,
2796            ),
2797        })
2798    }
2799}
2800
2801#[cfg(test)]
2802mod tests {
2803    use super::*;
2804    use std::path::Path;
2805
2806    fn parse_groups(toml: &str) -> IndexMap<String, GroupEntry> {
2807        PitchforkToml::parse_str(toml, Path::new("/tmp/my-project/pitchfork.toml"))
2808            .unwrap()
2809            .groups
2810    }
2811
2812    fn names(ids: &[DaemonId]) -> Vec<&str> {
2813        ids.iter().map(|id| id.name()).collect()
2814    }
2815
2816    #[test]
2817    fn test_group_includes_expand_before_own_daemons_and_dedupe() {
2818        let groups = parse_groups(
2819            r#"
2820[groups.core]
2821daemons = ["db", "cache"]
2822
2823[groups.extras]
2824daemons = ["mailer", "cache"]
2825
2826[groups.all]
2827groups = ["core", "extras"]
2828daemons = ["api", "db"]
2829"#,
2830        );
2831        let all = expand_group(&groups, "all").unwrap();
2832        assert_eq!(names(&all), ["db", "cache", "mailer", "api"]);
2833    }
2834
2835    #[test]
2836    fn test_group_includes_nest_and_allow_diamonds() {
2837        let groups = parse_groups(
2838            r#"
2839[groups.base]
2840daemons = ["db"]
2841
2842[groups.left]
2843groups = ["base"]
2844daemons = ["l"]
2845
2846[groups.right]
2847groups = ["base"]
2848daemons = ["r"]
2849
2850[groups.top]
2851groups = ["left", "right"]
2852"#,
2853        );
2854        let top = expand_group(&groups, "top").unwrap();
2855        assert_eq!(names(&top), ["db", "l", "r"]);
2856    }
2857
2858    #[test]
2859    fn test_group_includes_shared_by_many_paths_are_expanded_once() {
2860        // Each level includes the next twice, so walking every path would
2861        // take 2^60 steps.
2862        let mut toml = String::from("[groups.g0]\ngroups = [\"g1\", \"g1\"]\n");
2863        for i in 1..60 {
2864            toml.push_str(&format!(
2865                "\n[groups.g{i}]\ngroups = [\"g{n}\", \"g{n}\"]\n",
2866                n = i + 1
2867            ));
2868        }
2869        toml.push_str("\n[groups.g60]\ndaemons = [\"db\"]\n");
2870        let groups = parse_groups(&toml);
2871        assert_eq!(names(&expand_group(&groups, "g0").unwrap()), ["db"]);
2872    }
2873
2874    #[test]
2875    fn test_group_include_cycle_is_an_error() {
2876        let groups = parse_groups(
2877            r#"
2878[groups.a]
2879groups = ["b"]
2880
2881[groups.b]
2882groups = ["c"]
2883
2884[groups.c]
2885groups = ["a"]
2886"#,
2887        );
2888        let err = expand_group(&groups, "a").unwrap_err().to_string();
2889        assert!(err.contains("a -> b -> c -> a"), "{err}");
2890        let err = expand_group(&parse_groups("[groups.x]\ngroups = [\"x\"]\n"), "x")
2891            .unwrap_err()
2892            .to_string();
2893        assert!(err.contains("x -> x"), "{err}");
2894    }
2895
2896    #[test]
2897    fn test_group_include_of_undefined_group_is_an_error() {
2898        let groups = parse_groups("[groups.all]\ngroups = [\"cor\"]\n\n[groups.core]\n");
2899        let err = expand_group(&groups, "all").unwrap_err().to_string();
2900        assert!(
2901            err.contains("group 'all' includes undefined group 'cor'"),
2902            "{err}"
2903        );
2904    }
2905
2906    #[test]
2907    fn test_group_without_daemons_key_parses() {
2908        let groups = parse_groups("[groups.empty]\n");
2909        assert!(expand_group(&groups, "empty").unwrap().is_empty());
2910    }
2911
2912    #[test]
2913    fn test_themes_parse_merge_and_survive_a_write() {
2914        let dir = tempfile::tempdir().unwrap();
2915        let path = dir.path().join("pitchfork.toml");
2916        std::fs::write(
2917            &path,
2918            "[themes.mine]\nbase = \"catppuccin_latte\"\nred = \"#ff0000\"\n",
2919        )
2920        .unwrap();
2921        let mut pt = PitchforkToml::read(&path).unwrap();
2922        assert_eq!(pt.themes["mine"].red.as_deref(), Some("#ff0000"));
2923
2924        let mut other = PitchforkToml::new(dir.path().join("other.toml"));
2925        other.themes.insert("mine".into(), ThemeDef::default());
2926        pt.merge(other);
2927        assert_eq!(pt.themes["mine"], ThemeDef::default());
2928
2929        let pt = PitchforkToml::read(&path).unwrap();
2930        pt.write().unwrap();
2931        assert_eq!(PitchforkToml::read(&path).unwrap().themes, pt.themes);
2932    }
2933
2934    #[test]
2935    fn test_daemon_user_parses_and_flows_to_run_options() {
2936        let pt = PitchforkToml::parse_str(
2937            r#"
2938[daemons.api]
2939run = "node server.js"
2940user = "postgres"
2941"#,
2942            Path::new("/tmp/my-project/pitchfork.toml"),
2943        )
2944        .unwrap();
2945
2946        let id = DaemonId::new("my-project", "api");
2947        let daemon = pt.daemons.get(&id).unwrap();
2948        assert_eq!(daemon.user.as_deref(), Some("postgres"));
2949
2950        let opts = daemon.to_run_options(&id, vec!["node".to_string(), "server.js".to_string()]);
2951        assert_eq!(opts.user.as_deref(), Some("postgres"));
2952        // A start from config describes the daemon in full.
2953        assert!(opts.replaces_saved_record);
2954    }
2955
2956    #[test]
2957    fn test_new_local_file_writes_daemons_of_the_directory_namespace() {
2958        let temp = tempfile::tempdir().unwrap();
2959        std::fs::write(
2960            temp.path().join("pitchfork.toml"),
2961            "namespace = \"myns\"\n\n[daemons.web]\nrun = \"sleep 60\"\n",
2962        )
2963        .unwrap();
2964        let path = temp.path().join("pitchfork.local.toml");
2965        let mut pt = PitchforkToml::new(path.clone());
2966        let id = DaemonId::new(namespace_from_path(&path).unwrap(), "api");
2967        assert_eq!(id.namespace(), "myns");
2968        pt.daemons.insert(
2969            id.clone(),
2970            PitchforkTomlDaemon {
2971                run: "sleep 60".into(),
2972                ..PitchforkTomlDaemon::default()
2973            },
2974        );
2975
2976        pt.write().unwrap();
2977
2978        let parsed = PitchforkToml::read(&path).unwrap();
2979        assert!(parsed.daemons.contains_key(&id));
2980    }
2981
2982    #[test]
2983    fn test_daemon_user_write_roundtrip() {
2984        let temp = tempfile::tempdir().unwrap();
2985        let path = temp.path().join("pitchfork.toml");
2986        let mut pt = PitchforkToml::new(path.clone());
2987        pt.namespace = Some("test-project".to_string());
2988        pt.daemons.insert(
2989            DaemonId::new("test-project", "api"),
2990            PitchforkTomlDaemon {
2991                run: "node server.js".into(),
2992                user: Some("postgres".to_string()),
2993                ..PitchforkTomlDaemon::default()
2994            },
2995        );
2996
2997        pt.write().unwrap();
2998
2999        let raw = std::fs::read_to_string(&path).unwrap();
3000        assert!(raw.contains("user = \"postgres\""));
3001
3002        let parsed = PitchforkToml::read(&path).unwrap();
3003        let daemon = parsed
3004            .daemons
3005            .get(&DaemonId::new("test-project", "api"))
3006            .unwrap();
3007        assert_eq!(daemon.user.as_deref(), Some("postgres"));
3008    }
3009
3010    /// Arguments a shell would reinterpret, which the argv form must not.
3011    fn awkward_argv() -> Vec<String> {
3012        [
3013            "node",
3014            "my server.js",
3015            "--name=\"a b\"",
3016            "it's",
3017            "a&b",
3018            "%PATH%",
3019            "$HOME",
3020        ]
3021        .map(str::to_string)
3022        .to_vec()
3023    }
3024
3025    #[test]
3026    fn test_run_array_parses_and_starts_without_a_shell() {
3027        let pt = PitchforkToml::parse_str(
3028            r#"
3029[daemons.api]
3030run = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3031"#,
3032            Path::new("/tmp/my-project/pitchfork.toml"),
3033        )
3034        .unwrap();
3035
3036        let id = DaemonId::new("my-project", "api");
3037        let daemon = pt.daemons.get(&id).unwrap();
3038        assert_eq!(daemon.run, RunCommand::Argv(awkward_argv()));
3039
3040        let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
3041        assert_eq!(opts.cmd, awkward_argv());
3042        assert!(opts.no_shell);
3043        assert_eq!(opts.run, None);
3044    }
3045
3046    #[test]
3047    fn test_run_string_still_goes_through_the_shell() {
3048        let pt = PitchforkToml::parse_str(
3049            "[daemons.api]\nrun = \"exec node server.js\"\n",
3050            Path::new("/tmp/my-project/pitchfork.toml"),
3051        )
3052        .unwrap();
3053
3054        let id = DaemonId::new("my-project", "api");
3055        let daemon = pt.daemons.get(&id).unwrap();
3056        let opts = daemon.to_run_options(&id, daemon.run.argv().unwrap());
3057        assert!(!opts.no_shell);
3058        assert_eq!(opts.run.as_deref(), Some("exec node server.js"));
3059    }
3060
3061    #[test]
3062    fn test_run_array_write_roundtrip() {
3063        let temp = tempfile::tempdir().unwrap();
3064        let path = temp.path().join("pitchfork.toml");
3065        let mut pt = PitchforkToml::new(path.clone());
3066        pt.namespace = Some("test-project".to_string());
3067        let id = DaemonId::new("test-project", "api");
3068        pt.daemons.insert(
3069            id.clone(),
3070            PitchforkTomlDaemon {
3071                run: RunCommand::Argv(awkward_argv()),
3072                ..PitchforkTomlDaemon::default()
3073            },
3074        );
3075        pt.daemons.insert(
3076            DaemonId::new("test-project", "worker"),
3077            PitchforkTomlDaemon {
3078                run: "exec ./worker --queue \"a b\"".into(),
3079                ..PitchforkTomlDaemon::default()
3080            },
3081        );
3082
3083        pt.write().unwrap();
3084
3085        let parsed = PitchforkToml::read(&path).unwrap();
3086        assert_eq!(parsed.daemons[&id].run, RunCommand::Argv(awkward_argv()));
3087        assert_eq!(
3088            parsed.daemons[&DaemonId::new("test-project", "worker")].run,
3089            "exec ./worker --queue \"a b\""
3090        );
3091    }
3092
3093    #[test]
3094    fn test_run_array_must_name_a_program() {
3095        let err = PitchforkToml::parse_str(
3096            "[daemons.api]\nrun = []\n",
3097            Path::new("/tmp/my-project/pitchfork.toml"),
3098        )
3099        .unwrap_err();
3100        assert!(
3101            err.chain()
3102                .any(|cause| cause.to_string().contains("empty run array")),
3103            "unexpected error: {err:?}"
3104        );
3105    }
3106
3107    #[test]
3108    fn test_run_array_rejects_exec() {
3109        let err = PitchforkToml::parse_str(
3110            "[daemons.api]\nrun = [\"exec\", \"node\", \"server.js\"]\n",
3111            Path::new("/tmp/my-project/pitchfork.toml"),
3112        )
3113        .unwrap_err();
3114        assert!(
3115            err.chain().any(|cause| cause
3116                .to_string()
3117                .contains("starts its run array with \"exec\"")),
3118            "unexpected error: {err:?}"
3119        );
3120    }
3121
3122    #[test]
3123    fn test_ready_cmd_array_parses_in_both_forms() {
3124        let pt = PitchforkToml::parse_str(
3125            r#"
3126[daemons.api]
3127run = "node server.js"
3128ready_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3129
3130[daemons.db]
3131run = "postgres"
3132ready_cmd = { run = ["pg_isready", "-h", "localhost"], timeout = "30s" }
3133
3134[daemons.cache]
3135run = "redis-server"
3136ready_cmd = "redis-cli ping"
3137"#,
3138            Path::new("/tmp/my-project/pitchfork.toml"),
3139        )
3140        .unwrap();
3141
3142        let ready = |name: &str| {
3143            pt.daemons[&DaemonId::new("my-project", name)]
3144                .ready_cmd
3145                .clone()
3146                .unwrap()
3147        };
3148        assert_eq!(ready("api").run, RunCommand::Argv(awkward_argv()));
3149        assert_eq!(ready("api").timeout, None);
3150        assert_eq!(
3151            ready("db").run,
3152            RunCommand::Argv(
3153                ["pg_isready", "-h", "localhost"]
3154                    .map(str::to_string)
3155                    .to_vec()
3156            )
3157        );
3158        assert_eq!(
3159            ready("db").timeout,
3160            Some(std::time::Duration::from_secs(30))
3161        );
3162        assert_eq!(ready("cache").run, "redis-cli ping");
3163    }
3164
3165    #[test]
3166    fn test_ready_cmd_array_write_roundtrip() {
3167        let temp = tempfile::tempdir().unwrap();
3168        let path = temp.path().join("pitchfork.toml");
3169        let mut pt = PitchforkToml::new(path.clone());
3170        pt.namespace = Some("test-project".to_string());
3171        let short = ReadyCmd::new(awkward_argv());
3172        let full = ReadyCmd {
3173            run: RunCommand::Argv(
3174                ["pg_isready", "-h", "localhost"]
3175                    .map(str::to_string)
3176                    .to_vec(),
3177            ),
3178            timeout: Some(std::time::Duration::from_secs(30)),
3179        };
3180        for (name, ready_cmd) in [("api", &short), ("db", &full)] {
3181            pt.daemons.insert(
3182                DaemonId::new("test-project", name),
3183                PitchforkTomlDaemon {
3184                    run: "true".into(),
3185                    ready_cmd: Some(ready_cmd.clone()),
3186                    ..PitchforkTomlDaemon::default()
3187                },
3188            );
3189        }
3190
3191        pt.write().unwrap();
3192
3193        let parsed = PitchforkToml::read(&path).unwrap();
3194        let ready = |name: &str| {
3195            parsed.daemons[&DaemonId::new("test-project", name)]
3196                .ready_cmd
3197                .clone()
3198        };
3199        assert_eq!(ready("api"), Some(short));
3200        assert_eq!(ready("db"), Some(full));
3201    }
3202
3203    #[test]
3204    fn test_ready_cmd_array_must_name_a_program() {
3205        for ready_cmd in ["[]", "[\"\"]", "{ run = [\"\", \"-h\"] }"] {
3206            let err = PitchforkToml::parse_str(
3207                &format!("[daemons.api]\nrun = \"true\"\nready_cmd = {ready_cmd}\n"),
3208                Path::new("/tmp/my-project/pitchfork.toml"),
3209            )
3210            .unwrap_err();
3211            assert!(
3212                err.chain().any(|cause| cause
3213                    .to_string()
3214                    .contains("has no program in its ready_cmd array")),
3215                "unexpected error for {ready_cmd}: {err:?}"
3216            );
3217        }
3218    }
3219
3220    #[test]
3221    fn test_ready_cmd_array_rejects_exec() {
3222        let err = PitchforkToml::parse_str(
3223            "[daemons.api]\nrun = \"true\"\nready_cmd = { run = [\"exec\", \"pg_isready\"] }\n",
3224            Path::new("/tmp/my-project/pitchfork.toml"),
3225        )
3226        .unwrap_err();
3227        assert!(
3228            err.chain().any(|cause| cause
3229                .to_string()
3230                .contains("starts its ready_cmd array with \"exec\"")),
3231            "unexpected error: {err:?}"
3232        );
3233    }
3234
3235    #[test]
3236    fn test_health_cmd_array_parses_and_round_trips() {
3237        let pt = PitchforkToml::parse_str(
3238            r#"
3239[daemons.api]
3240run = "node server.js"
3241health_cmd = ["node", "my server.js", "--name=\"a b\"", "it's", "a&b", "%PATH%", "$HOME"]
3242
3243[daemons.db]
3244run = "postgres"
3245health_cmd = { run = ["pg_isready", "-h", "localhost"], interval = "5s", retries = 2 }
3246
3247[daemons.cache]
3248run = "redis-server"
3249health_cmd = "redis-cli ping"
3250"#,
3251            Path::new("/tmp/my-project/pitchfork.toml"),
3252        )
3253        .unwrap();
3254        let health = |pt: &PitchforkToml, ns: &str, name: &str| {
3255            pt.daemons[&DaemonId::new(ns, name)]
3256                .health_cmd
3257                .clone()
3258                .unwrap()
3259        };
3260        assert_eq!(
3261            health(&pt, "my-project", "api").run,
3262            RunCommand::Argv(awkward_argv())
3263        );
3264        let db = health(&pt, "my-project", "db");
3265        assert_eq!(
3266            db.run,
3267            RunCommand::Argv(
3268                ["pg_isready", "-h", "localhost"]
3269                    .map(str::to_string)
3270                    .to_vec()
3271            )
3272        );
3273        assert_eq!(db.interval, Some(std::time::Duration::from_secs(5)));
3274        assert_eq!(db.retries, Some(2));
3275        assert_eq!(health(&pt, "my-project", "cache").run, "redis-cli ping");
3276
3277        let temp = tempfile::tempdir().unwrap();
3278        let path = temp.path().join("pitchfork.toml");
3279        let mut written = PitchforkToml::new(path.clone());
3280        written.namespace = Some("test-project".to_string());
3281        for name in ["api", "db"] {
3282            written.daemons.insert(
3283                DaemonId::new("test-project", name),
3284                PitchforkTomlDaemon {
3285                    run: "true".into(),
3286                    health_cmd: Some(health(&pt, "my-project", name)),
3287                    ..PitchforkTomlDaemon::default()
3288                },
3289            );
3290        }
3291        written.write().unwrap();
3292        let parsed = PitchforkToml::read(&path).unwrap();
3293        for name in ["api", "db"] {
3294            assert_eq!(
3295                health(&parsed, "test-project", name),
3296                health(&pt, "my-project", name)
3297            );
3298        }
3299    }
3300
3301    #[test]
3302    fn test_health_cmd_array_must_name_a_program_and_not_exec() {
3303        for (health_cmd, expected) in [
3304            ("[]", "has no program in its health_cmd array"),
3305            ("[\"\"]", "has no program in its health_cmd array"),
3306            (
3307                "{ run = [\"exec\", \"pg_isready\"] }",
3308                "starts its health_cmd array with \"exec\"",
3309            ),
3310        ] {
3311            let err = PitchforkToml::parse_str(
3312                &format!("[daemons.api]\nrun = \"true\"\nhealth_cmd = {health_cmd}\n"),
3313                Path::new("/tmp/my-project/pitchfork.toml"),
3314            )
3315            .unwrap_err();
3316            assert!(
3317                err.chain()
3318                    .any(|cause| cause.to_string().contains(expected)),
3319                "unexpected error for {health_cmd}: {err:?}"
3320            );
3321        }
3322    }
3323
3324    #[test]
3325    fn test_registry_dirs_expand_tilde() {
3326        let pt = PitchforkToml::parse_str(
3327            r#"
3328[slugs.api]
3329dir = "~/projects/api"
3330
3331[namespaces.web]
3332dir = "~/projects/web"
3333"#,
3334            Path::new("/tmp/config.toml"),
3335        )
3336        .unwrap();
3337
3338        assert_eq!(
3339            pt.slugs["api"].dir,
3340            Some(crate::env::HOME_DIR.join("projects/api"))
3341        );
3342        assert_eq!(
3343            pt.namespaces["web"].dir,
3344            crate::env::HOME_DIR.join("projects/web")
3345        );
3346    }
3347
3348    #[test]
3349    fn test_settings_write_roundtrip() {
3350        let temp = tempfile::tempdir().unwrap();
3351        let path = temp.path().join("pitchfork.toml");
3352        let mut pt = PitchforkToml::new(path.clone());
3353        pt.namespace = Some("test-project".to_string());
3354        pt.settings.web.auto_start = Some(true);
3355        pt.settings.general.log_level = Some("debug".to_string());
3356
3357        pt.write().unwrap();
3358
3359        let raw = std::fs::read_to_string(&path).unwrap();
3360        assert!(
3361            raw.contains("[settings.web]"),
3362            "settings.web section should be written, got:\n{raw}"
3363        );
3364        assert!(raw.contains("auto_start = true"));
3365        assert!(raw.contains("log_level = \"debug\""));
3366
3367        let parsed = PitchforkToml::read(&path).unwrap();
3368        assert_eq!(parsed.settings.web.auto_start, Some(true));
3369        assert_eq!(parsed.settings.general.log_level.as_deref(), Some("debug"));
3370    }
3371
3372    fn slug_entry(namespace: &str, daemon: Option<&str>) -> SlugEntry {
3373        SlugEntry {
3374            dir: None,
3375            namespace: Some(namespace.to_string()),
3376            daemon: daemon.map(str::to_string),
3377        }
3378    }
3379
3380    #[test]
3381    fn test_slug_is_ambiguous() {
3382        let mut slugs = IndexMap::new();
3383        slugs.insert("api".to_string(), slug_entry("my-project", None));
3384        assert!(!PitchforkToml::slug_is_ambiguous("api", &slugs));
3385
3386        slugs.insert("API".to_string(), slug_entry("other-project", None));
3387        // Host names are case-insensitive, so both spellings are ambiguous.
3388        assert!(PitchforkToml::slug_is_ambiguous("api", &slugs));
3389        assert!(PitchforkToml::slug_is_ambiguous("API", &slugs));
3390    }
3391
3392    #[test]
3393    fn test_find_slug_for_daemon_skips_case_collisions() {
3394        let id = DaemonId::new("my-project", "api");
3395        let mut slugs = IndexMap::new();
3396        slugs.insert("api".to_string(), slug_entry("my-project", None));
3397        assert_eq!(
3398            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3399            Some("api".to_string())
3400        );
3401
3402        // The proxy refuses to route either spelling, so no URL may be
3403        // advertised for this daemon.
3404        slugs.insert("API".to_string(), slug_entry("other-project", None));
3405        assert_eq!(
3406            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3407            None
3408        );
3409    }
3410
3411    #[test]
3412    fn test_find_slug_for_daemon_prefers_a_routable_alias() {
3413        let id = DaemonId::new("my-project", "api");
3414        let mut slugs = IndexMap::new();
3415        // A colliding pair comes first in config order, then a routable alias
3416        // for the same daemon.
3417        slugs.insert("api".to_string(), slug_entry("my-project", None));
3418        slugs.insert("API".to_string(), slug_entry("my-project", None));
3419        slugs.insert("my-api".to_string(), slug_entry("my-project", Some("api")));
3420
3421        assert_eq!(
3422            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
3423            Some("my-api".to_string())
3424        );
3425    }
3426
3427    #[test]
3428    fn test_settings_preserved_on_unrelated_write() {
3429        // Regression test for https://github.com/jdx/pitchfork/discussions/574
3430        // A read-modify-write of slugs/namespaces must not drop existing [settings].
3431        let temp = tempfile::tempdir().unwrap();
3432        let path = temp.path().join("pitchfork.toml");
3433        std::fs::write(&path, "[settings.web]\nauto_start = true\n").unwrap();
3434
3435        let mut pt = PitchforkToml::read(&path).unwrap();
3436        pt.slugs.insert(
3437            "api".to_string(),
3438            SlugEntry {
3439                dir: None,
3440                namespace: Some("myproject".to_string()),
3441                daemon: None,
3442            },
3443        );
3444        pt.namespaces.insert(
3445            "myproject".to_string(),
3446            NamespaceEntry {
3447                dir: PathBuf::from("/tmp/myproject"),
3448                config: Vec::new(),
3449                label: None,
3450            },
3451        );
3452        pt.write().unwrap();
3453
3454        let raw = std::fs::read_to_string(&path).unwrap();
3455        assert!(
3456            raw.contains("[settings.web]"),
3457            "existing settings must be preserved, got:\n{raw}"
3458        );
3459        assert!(raw.contains("auto_start = true"));
3460        assert!(raw.contains("[slugs.api]"));
3461
3462        let parsed = PitchforkToml::read(&path).unwrap();
3463        assert_eq!(parsed.settings.web.auto_start, Some(true));
3464        assert!(parsed.slugs.contains_key("api"));
3465    }
3466
3467    #[tokio::test]
3468    async fn test_proxy_worktree_alias_is_canonicalized_on_rewrite() {
3469        let temp = tempfile::tempdir().unwrap();
3470        let path = temp.path().join("pitchfork.toml");
3471        tokio::fs::write(&path, "[settings.proxy]\nworktree = false\n")
3472            .await
3473            .unwrap();
3474
3475        let read_path = path.clone();
3476        let pt = tokio::task::spawn_blocking(move || PitchforkToml::read(&read_path))
3477            .await
3478            .unwrap()
3479            .unwrap();
3480        assert_eq!(pt.settings.general.worktree, Some(false));
3481        assert_eq!(pt.settings.proxy.worktree, None);
3482        tokio::task::spawn_blocking(move || pt.write())
3483            .await
3484            .unwrap()
3485            .unwrap();
3486
3487        let raw = tokio::fs::read_to_string(&path).await.unwrap();
3488        assert!(raw.contains("[settings.general]"), "{raw}");
3489        assert!(raw.contains("worktree = false"), "{raw}");
3490        assert!(!raw.contains("[settings.proxy]"), "{raw}");
3491
3492        let parsed = tokio::task::spawn_blocking(move || PitchforkToml::read(&path))
3493            .await
3494            .unwrap()
3495            .unwrap();
3496        assert_eq!(parsed.settings.general.worktree, Some(false));
3497    }
3498
3499    #[test]
3500    fn test_config_cache_hit_and_invalidation() {
3501        let temp = tempfile::tempdir().unwrap();
3502        let dir = temp.path();
3503        let config_path = dir.join("pitchfork.toml");
3504        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3505
3506        // Clear any pre-existing cache entries for this directory.
3507        super::invalidate_config_cache();
3508
3509        // First call: cache miss, reads from disk.
3510        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3511        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3512        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3513
3514        // Second call: should be a cache hit (same mtime).
3515        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3516        assert_eq!(pt2.daemons[&daemon_id].run, "echo v1");
3517
3518        // Modify the config file — mtime changes, cache should miss.
3519        // Sleep briefly to ensure mtime resolution differs.
3520        std::thread::sleep(std::time::Duration::from_millis(50));
3521        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v2\"\n").unwrap();
3522
3523        let pt3 = PitchforkToml::all_merged_from(dir).unwrap();
3524        assert_eq!(pt3.daemons[&daemon_id].run, "echo v2");
3525
3526        // Explicit invalidation should also force a re-read.
3527        super::invalidate_config_cache();
3528        let pt4 = PitchforkToml::all_merged_from(dir).unwrap();
3529        assert_eq!(pt4.daemons[&daemon_id].run, "echo v2");
3530
3531        // Clean up.
3532        super::invalidate_config_cache();
3533    }
3534
3535    #[test]
3536    fn test_config_cache_invalidation_on_write() {
3537        let temp = tempfile::tempdir().unwrap();
3538        let dir = temp.path();
3539        let config_path = dir.join("pitchfork.toml");
3540        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3541
3542        super::invalidate_config_cache();
3543
3544        // Populate cache.
3545        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3546        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3547        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3548
3549        // Write via PitchforkToml::write() — should invalidate cache.
3550        let mut pt = PitchforkToml::read(&config_path).unwrap();
3551        pt.daemons.get_mut(&daemon_id).unwrap().run = "echo v3".into();
3552        // write() needs the path set and namespace match
3553        let _ = pt.write();
3554
3555        // Next read should see the updated value, not the cached one.
3556        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3557        assert_eq!(pt2.daemons[&daemon_id].run, "echo v3");
3558
3559        super::invalidate_config_cache();
3560    }
3561
3562    #[test]
3563    fn test_config_cache_size_invalidation() {
3564        let temp = tempfile::tempdir().unwrap();
3565        let dir = temp.path();
3566        let config_path = dir.join("pitchfork.toml");
3567        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();
3568
3569        super::invalidate_config_cache();
3570
3571        // Populate cache.
3572        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
3573        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
3574        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");
3575
3576        // Capture the original mtime, then write different-size content and
3577        // restore the *same* mtime — simulating `cp --preserve=timestamps`
3578        // or a same-second edit on a coarse-grained filesystem.
3579        let original_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
3580        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo different\"\n").unwrap();
3581        // On Windows, set_times requires the file handle to be opened with
3582        // write access; File::open is read-only.
3583        let file = std::fs::OpenOptions::new()
3584            .write(true)
3585            .open(&config_path)
3586            .unwrap();
3587        let times = std::fs::FileTimes::new().set_modified(original_mtime);
3588        file.set_times(times).unwrap();
3589
3590        // Size changed (shorter run string), so cache should miss even though
3591        // mtime is identical.
3592        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
3593        assert_eq!(
3594            pt2.daemons[&daemon_id].run, "echo different",
3595            "cache should invalidate on size change even with identical mtime"
3596        );
3597
3598        super::invalidate_config_cache();
3599    }
3600
3601    #[test]
3602    fn test_find_project_root_in_plain_dir_returns_none() {
3603        let temp = tempfile::tempdir().unwrap();
3604        assert_eq!(find_project_root(temp.path()), None);
3605    }
3606
3607    #[test]
3608    fn test_find_project_root_finds_git_marker() {
3609        let temp = tempfile::tempdir().unwrap();
3610        let repo = temp.path().join("my-repo");
3611        std::fs::create_dir(&repo).unwrap();
3612        std::fs::create_dir(repo.join(".git")).unwrap();
3613
3614        let sub = repo.join("sub/dir");
3615        std::fs::create_dir_all(&sub).unwrap();
3616
3617        // `find_project_root` canonicalizes, so compare against the canonical
3618        // path (on Windows this differs by the `\\?\` verbatim prefix).
3619        assert_eq!(find_project_root(&sub), Some(repo.canonicalize().unwrap()));
3620    }
3621
3622    #[test]
3623    fn test_find_project_root_accepts_git_file_marker() {
3624        // Linked git worktrees store `.git` as a *file* pointing at the
3625        // common gitdir, so `exists()` (not `is_dir()`) is the right check.
3626        let temp = tempfile::tempdir().unwrap();
3627        let wt = temp.path().join("my-worktree");
3628        std::fs::create_dir(&wt).unwrap();
3629        std::fs::write(wt.join(".git"), "gitdir: /tmp/some-common-gitdir\n").unwrap();
3630
3631        assert_eq!(find_project_root(&wt), Some(wt.canonicalize().unwrap()));
3632    }
3633
3634    /// A symlinked start dir must resolve into the repository hierarchy so
3635    /// `parent()` traversal does not walk out of the repo.
3636    #[cfg(unix)]
3637    #[test]
3638    fn test_find_project_root_resolves_symlinked_start_dir() {
3639        use std::os::unix::fs::symlink;
3640
3641        let temp = tempfile::tempdir().unwrap();
3642        let repo = temp.path().join("real-repo");
3643        std::fs::create_dir(&repo).unwrap();
3644        std::fs::create_dir(repo.join(".git")).unwrap();
3645
3646        let sub = repo.join("sub/dir");
3647        std::fs::create_dir_all(&sub).unwrap();
3648        let link = temp.path().join("link-to-sub");
3649        symlink(&sub, &link).unwrap();
3650
3651        assert_eq!(find_project_root(&link), Some(repo.canonicalize().unwrap()));
3652    }
3653
3654    /// Build a real git repository with a linked worktree and assert that
3655    /// `all_merged_all_namespaces_from` picks up daemons from both.
3656    #[test]
3657    fn test_all_merged_all_namespaces_discovers_worktrees() {
3658        let temp = tempfile::tempdir().unwrap();
3659        let repo = temp.path().join("my-repo");
3660        std::fs::create_dir(&repo).unwrap();
3661
3662        // git worktree add requires at least one commit.
3663        let git_init = std::process::Command::new("git")
3664            .args(["init", "-b", "main"])
3665            .current_dir(&repo)
3666            .output()
3667            .expect("git init");
3668        assert!(git_init.status.success(), "git init failed: {:?}", git_init);
3669
3670        std::fs::write(repo.join("main.toml"), "hello\n").unwrap();
3671
3672        let git_commit = std::process::Command::new("git")
3673            .args([
3674                "-c",
3675                "user.name=pitchfork-test",
3676                "-c",
3677                "user.email=pitchfork-test@example.com",
3678                "add",
3679                "-A",
3680            ])
3681            .current_dir(&repo)
3682            .output()
3683            .expect("git add");
3684        assert!(git_commit.status.success());
3685
3686        let git_commit = std::process::Command::new("git")
3687            .args([
3688                "-c",
3689                "user.name=pitchfork-test",
3690                "-c",
3691                "user.email=pitchfork-test@example.com",
3692                "commit",
3693                "-m",
3694                "init",
3695            ])
3696            .current_dir(&repo)
3697            .output()
3698            .expect("git commit");
3699        assert!(
3700            git_commit.status.success(),
3701            "git commit failed: {:?}",
3702            git_commit
3703        );
3704
3705        let wt = temp.path().join("my-repo-feature");
3706        let git_wt = std::process::Command::new("git")
3707            .args(["worktree", "add", "-b", "feature-x", wt.to_str().unwrap()])
3708            .current_dir(&repo)
3709            .output()
3710            .expect("git worktree add");
3711        assert!(
3712            git_wt.status.success(),
3713            "git worktree add failed: {:?}",
3714            git_wt
3715        );
3716
3717        // Config in the main checkout.
3718        std::fs::write(
3719            repo.join("pitchfork.toml"),
3720            "[daemons.api]\nrun = \"echo main\"\n",
3721        )
3722        .unwrap();
3723        // Config in the linked worktree (different namespace: dir name).
3724        std::fs::write(
3725            wt.join("pitchfork.toml"),
3726            "[daemons.worker]\nrun = \"echo wt\"\n",
3727        )
3728        .unwrap();
3729
3730        super::invalidate_config_cache();
3731
3732        // Resolve from inside the worktree: both namespaces must be visible.
3733        let pt = PitchforkToml::all_merged_all_namespaces_from_blocking(&wt).unwrap();
3734
3735        let main_id = DaemonId::new("my-repo", "api");
3736        let wt_id = DaemonId::new("my-repo-feature", "worker");
3737        assert!(
3738            pt.daemons.contains_key(&main_id),
3739            "main checkout daemon missing"
3740        );
3741        assert!(pt.daemons.contains_key(&wt_id), "worktree daemon missing");
3742
3743        // Resolving from the main checkout must also see the worktree daemon.
3744        let pt_from_main = PitchforkToml::all_merged_all_namespaces_from_blocking(&repo).unwrap();
3745        assert!(pt_from_main.daemons.contains_key(&wt_id));
3746
3747        // Clean up.
3748        let _ = std::process::Command::new("git")
3749            .args(["worktree", "remove", "--force", wt.to_str().unwrap()])
3750            .current_dir(&repo)
3751            .output();
3752        super::invalidate_config_cache();
3753    }
3754
3755    #[test]
3756    fn test_adhoc_id_uses_invocation_directory_namespace() {
3757        let temp = tempfile::tempdir().unwrap();
3758        let project = temp.path().join("feature-tree");
3759        std::fs::create_dir(&project).unwrap();
3760        std::fs::write(
3761            project.join("pitchfork.toml"),
3762            "[daemons.other]\nrun = \"true\"\n",
3763        )
3764        .unwrap();
3765
3766        let id = PitchforkToml::resolve_id_allow_adhoc_from("api", &project).unwrap();
3767        assert_eq!(id, DaemonId::new("feature-tree", "api"));
3768        let qualified =
3769            PitchforkToml::resolve_id_allow_adhoc_from("explicit/api", &project).unwrap();
3770        assert_eq!(qualified, DaemonId::new("explicit", "api"));
3771    }
3772
3773    #[test]
3774    fn test_adhoc_id_falls_back_to_global_without_project_config() {
3775        let temp = tempfile::tempdir().unwrap();
3776        let id = PitchforkToml::resolve_id_allow_adhoc_from("api", temp.path()).unwrap();
3777        assert_eq!(id, DaemonId::new("global", "api"));
3778    }
3779}