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