Skip to main content

pitchfork_cli/
settings.rs

1//! User-configurable settings for pitchfork.
2//!
3//! Settings can be configured in multiple ways (in order of precedence):
4//! 1. Environment variables (highest priority)
5//! 2. Project-level `pitchfork.toml` or `pitchfork.local.toml` (in `[settings]` section)
6//! 3. User-level `~/.config/pitchfork/config.toml` (in `[settings]` section)
7//! 4. System-level `/etc/pitchfork/config.toml` (in `[settings]` section)
8//! 5. Built-in defaults (lowest priority)
9//!
10//! Example pitchfork.toml with settings:
11//! ```toml
12//! [daemons.myapp]
13//! run = "node server.js"
14//!
15//! [settings.general]
16//! autostop_delay = "5m"
17//! log_level = "debug"
18//!
19//! [settings.web]
20//! auto_start = true
21//! ```
22//!
23//! The structs below are the single declaration of every setting:
24//! `#[derive(usage_rs::Config)]` generates the usage-config registry, the
25//! reader that fills the structs from a resolution, and the spec `config`
26//! block that documents them (carried into `pitchfork.usage.kdl` through
27//! `#[usage(config = ...)]` on the CLI root). There is no `settings.toml`
28//! and no build-script generator left to keep in step with this file.
29//!
30//! Resolution is usage-config's single origin-tracked merge, so explicitly
31//! setting a value equal to the default in a higher-precedence file still
32//! overrides a lower one, and `pitchfork settings` renders provenance from
33//! the same merge that produced the values.
34
35use std::path::{Path, PathBuf};
36use std::sync::Arc;
37use usage_rs::config::{
38    Const, EnvLayer, FileLayer, FileScope, Layers, Origin, Resolved, SourceKind, Trust, Ty, Value,
39    resolve,
40};
41
42/// The `api.*` settings: the standalone API server (JSON REST endpoints for
43/// the Vue SPA). When `api.auto_start` is enabled and `api.bind_port` is set, the API server binds
44/// independently of the web UI.
45#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
46#[usage(prefix = "api")]
47pub struct SettingsApi {
48    /// Automatically start the standalone API server
49    ///
50    /// When true, pitchfork starts a standalone API server on api.bind_address +
51    /// api.bind_port when the supervisor launches. The web UI does not need to
52    /// be enabled for this; you can run the API alone and serve the Vue SPA from
53    /// a separate static host (e.g. nginx, Vite dev server).
54    ///
55    /// Default is false so the API is only available through the bundled web UI.
56    #[usage(env = "PITCHFORK_API_AUTO_START", default = false)]
57    pub auto_start: bool,
58
59    /// IP address the API server binds to
60    ///
61    /// Use "0.0.0.0" to make the API reachable from other devices on your network.
62    /// Keep "127.0.0.1" (default) to restrict it to localhost.
63    #[usage(env = "PITCHFORK_API_BIND_ADDRESS", default = "127.0.0.1")]
64    pub bind_address: String,
65
66    /// Port the standalone API server listens on
67    ///
68    /// Set to 0 (default) to disable the standalone API server.
69    /// Set to a valid port (e.g. 8081) and enable `api.auto_start` to start the API on its own port.
70    #[usage(env = "PITCHFORK_API_BIND_PORT", default = 0)]
71    pub bind_port: i64,
72
73    /// Number of consecutive ports to try if api.bind_port is in use
74    #[usage(env = "PITCHFORK_API_PORT_ATTEMPTS", default = 10)]
75    pub port_attempts: i64,
76
77    /// Authentication token for API access when bound to non-loopback addresses
78    ///
79    /// When the API server or web UI is bound to a non-loopback address (e.g.,
80    /// "0.0.0.0"), this token is required on every API request via the
81    /// X-Pitchfork-Token header.
82    ///
83    /// If left empty and the bind address is non-loopback, a random 32-byte
84    /// hex token is auto-generated on startup and printed to the supervisor log.
85    /// This token is injected into the served index.html, so the bundled Vue
86    /// SPA works without additional configuration.
87    ///
88    /// For external API consumers (e.g., curl, mobile apps), set this to a
89    /// fixed value or pass it via the PITCHFORK_API_TOKEN environment variable.
90    #[usage(env = "PITCHFORK_API_TOKEN", default = "")]
91    pub token: String,
92}
93
94/// The `boot.*` settings.
95#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
96#[usage(prefix = "boot")]
97pub struct SettingsBoot {
98    /// Executable path written into boot registrations
99    ///
100    /// Set an absolute path to a stable executable or symlink to keep boot
101    /// registrations independent of versioned package-manager install paths.
102    /// The path is preserved as written, including symlinks. It must exist
103    /// and be executable. No shell, PATH lookup, or tilde expansion is used.
104    ///
105    /// Used by boot enable, explicit refresh, and automatic stale-path repair.
106    /// Set this in the user or system config so boot-time repair sees it too.
107    /// Project config files cannot select a boot executable.
108    /// Empty (default) uses the running binary's resolved path, as before.
109    #[usage(env = "PITCHFORK_BOOT_EXECUTABLE", default = "", scope = "global")]
110    pub executable: String,
111}
112
113/// The `general.*` settings.
114#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
115#[usage(prefix = "general")]
116pub struct SettingsGeneral {
117    /// Delay before auto-stopping daemons when leaving a directory
118    ///
119    /// When using shell hooks with `auto = ["stop"]`, this controls how long pitchfork waits
120    /// before stopping a daemon after you leave its directory.
121    ///
122    /// This delay prevents unnecessary stop/start cycles when briefly switching directories.
123    ///
124    /// **Examples:**
125    /// - `"0s"` - Stop immediately (no delay)
126    /// - `"30s"` - Wait 30 seconds
127    /// - `"1m"` - Wait 1 minute (default)
128    /// - `"5m"` - Wait 5 minutes
129    ///
130    /// Set to `"0s"` to disable the delay and stop daemons immediately.
131    #[usage(env = "PITCHFORK_AUTOSTOP_DELAY", default = "1m", ty = "duration")]
132    pub autostop_delay: String,
133
134    /// Supervisor background task refresh interval
135    ///
136    /// Controls how often the supervisor refreshes its internal state and checks for:
137    /// - Daemon health status changes
138    /// - Configuration file updates
139    /// - Process state synchronization
140    ///
141    /// Lower values provide more responsive status updates but use more resources.
142    ///
143    /// **Recommended values:**
144    /// - `"5s"` - For development/testing
145    /// - `"10s"` - Default, balanced
146    /// - `"30s"` - For production with many daemons
147    #[usage(
148        env = "PITCHFORK_INTERVAL",
149        deprecated_env("PITCHFORK_INTERVAL_SECS"),
150        default = "10s",
151        ty = "duration"
152    )]
153    pub interval: String,
154
155    /// File log level (trace, debug, info, warn, error)
156    ///
157    /// Controls the verbosity of log output written to log files.
158    /// Can be set independently from `log_level` to have more verbose file logs.
159    ///
160    /// For example, set console to `"info"` but file to `"debug"` to keep
161    /// detailed logs for troubleshooting without cluttering the console.
162    #[usage(env = "PITCHFORK_LOG_FILE_LEVEL", default = "info")]
163    pub log_file_level: String,
164
165    /// Console log level (trace, debug, info, warn, error)
166    ///
167    /// Controls the verbosity of log output to the console.
168    ///
169    /// **Available levels:**
170    /// - `"trace"` - Most verbose, includes all internal details
171    /// - `"debug"` - Detailed information for debugging
172    /// - `"info"` - Normal operation messages (default)
173    /// - `"warn"` - Warnings and potential issues
174    /// - `"error"` - Only errors
175    #[usage(env = "PITCHFORK_LOG", default = "info")]
176    pub log_level: String,
177
178    /// Wrap daemon commands with mise x -- globally
179    ///
180    /// When enabled, pitchfork wraps every daemon command with `mise x --` so that
181    /// [mise](https://mise.jdx.dev) sets up the correct tool versions, PATH,
182    /// and environment variables before the daemon runs.
183    ///
184    /// This is especially useful when pitchfork is started as a login item or boot
185    /// daemon, where the shell profile (`.zshrc`, `.bashrc`) is not sourced and
186    /// tools installed via Homebrew or mise are not on PATH.
187    ///
188    /// Individual daemons can override this with `mise = true` or `mise = false`
189    /// in their configuration.
190    #[usage(env = "PITCHFORK_MISE", default = false)]
191    pub mise: bool,
192
193    /// Explicit path to the mise binary
194    ///
195    /// By default, pitchfork searches well-known locations for the mise binary:
196    /// - `~/.local/bin/mise`
197    /// - `~/.cargo/bin/mise`
198    /// - `/usr/local/bin/mise`
199    /// - `/opt/homebrew/bin/mise`
200    /// - on Windows, `mise.exe` on `PATH`
201    ///
202    /// Set this to an absolute path if mise is installed elsewhere.
203    ///
204    /// For a daemon defined in a project's `pitchfork.toml`, the value comes
205    /// from that project, read when the daemon is started, and a relative path
206    /// is taken from the project's directory. `PITCHFORK_MISE_BIN` in the
207    /// environment of the `pitchfork` command that starts the daemon takes
208    /// precedence over the project's files. When the project does not set it,
209    /// the supervisor uses its own value, where a relative path is taken from
210    /// the directory the supervisor was started in. A value in the user's or
211    /// the system's configuration file counts as the supervisor's, not the
212    /// project's.
213    #[usage(env = "PITCHFORK_MISE_BIN", default = "")]
214    pub mise_bin: String,
215
216    /// Shell command used to execute daemon run scripts
217    ///
218    /// Controls the shell used to execute daemon `run` commands, as well as
219    /// `ready_cmd` / `health_cmd` probes, lifecycle hooks and the log archive
220    /// hook.
221    ///
222    /// The value is split with `shell_words::split` into a program and arguments,
223    /// then the daemon's `run` string is appended verbatim as the final argument
224    /// (passed to the shell's command flag, e.g. `sh -c "<run>"`).
225    ///
226    /// This means the `run` string is interpreted directly by the shell, so
227    /// variable expansion (`$VAR`), globs (`*.txt`), pipes (`|`), and command
228    /// chaining (`&&`) all work as expected.
229    ///
230    /// **Common configurations:**
231    /// - `"sh -c"` — Default, POSIX shell
232    /// - `"sh -o errexit -c"` — Exit on the first failing command
233    /// - `"bash -c"` — Use bash instead of sh
234    /// - `"bash -o errexit -o pipefail -c"` — `pipefail` is not a POSIX option,
235    ///   so name a shell that has it rather than relying on `sh`
236    ///
237    /// On Windows this setting applies only when it is set explicitly (in a
238    /// config file or via `PITCHFORK_SHELL`); otherwise
239    /// `general.windows_shell` is used. Setting it is the way to use one shell
240    /// on every platform, e.g. `"sh -c"` with Git for Windows' `sh.exe` on
241    /// `PATH`.
242    ///
243    /// When `mise = true` is enabled for a daemon, the shell wraps inside
244    /// `mise x --`, e.g. `mise x -- sh -c "<run>"`.
245    #[usage(env = "PITCHFORK_SHELL", default = "sh -c")]
246    pub shell: String,
247
248    /// Shell command used to execute daemon run scripts on Windows
249    ///
250    /// Used in place of `general.shell` on Windows, unless `general.shell` is
251    /// set explicitly. Split and used the same way: the program and arguments
252    /// come from this value, and the `run` string is appended as the final
253    /// argument, e.g. `cmd /C "<run>"`.
254    ///
255    /// The default is `cmd /C`, which is always available, so `run` strings are
256    /// read by cmd.exe: use `%VAR%` rather than `$VAR`, and double quotes
257    /// rather than single quotes.
258    ///
259    /// The split follows POSIX rules, so a path with spaces or backslashes has
260    /// to be quoted: `"'C:\Program Files\Git\bin\sh.exe' -c"`.
261    ///
262    /// When the shell is cmd.exe with `/C` last, the `run` string is handed to
263    /// it as `/S /C "<run>"`, so double quotes in it reach cmd as written, e.g.
264    /// `run = '"C:\Program Files\app\app.exe" --name "a b"'`. With
265    /// `mise = true`, a pitchfork helper preserves ordinary scripts on older
266    /// mise versions. Deferred templates use mise's native cmd forwarding
267    /// and quoting support (mise 2026.10.10 or later).
268    ///
269    /// When the shell is PowerShell (`powershell` or `pwsh`) with `-Command`
270    /// last, a `run` string that starts with a quote is run with the call
271    /// operator, as `& <run>`, so a quoted program path works there too, e.g.
272    /// `run = '"C:\Program Files\app\app.exe" --port 8080'`.
273    ///
274    /// **Common configurations:**
275    /// - `"cmd /C"` — Default
276    /// - `"powershell -Command"` / `"pwsh -Command"` — PowerShell
277    /// - `"sh -c"` — Git for Windows' sh, when `Git\bin` is on `PATH`
278    #[usage(env = "PITCHFORK_WINDOWS_SHELL", default = "cmd /C")]
279    pub windows_shell: String,
280
281    /// Show timestamps in startup log output
282    ///
283    /// When enabled, pitchfork prefixes each startup log line and result line
284    /// with a timestamp (e.g. `19:03:15`), making it easier to see how long
285    /// each daemon took to start.
286    ///
287    /// When disabled (default), a dim bullet (`•`) is used instead to keep
288    /// the output compact and aligned with the spinner / status icons.
289    #[usage(env = "PITCHFORK_STARTUP_LOG_TIMESTAMPS", default = false)]
290    pub startup_log_timestamps: bool,
291
292    /// Default readiness delay in seconds when a daemon has no ready check configured
293    ///
294    /// When a daemon has no other readiness check (output, HTTP, port, command),
295    /// pitchfork waits this long before considering it ready. Daemons can
296    /// override this with their own `ready_delay` setting.
297    #[usage(env = "PITCHFORK_READY_DELAY", default = "3s", ty = "duration")]
298    pub ready_delay: String,
299
300    /// Enable git worktree / jj workspace auto-discovery
301    ///
302    /// When enabled (default), pitchfork discovers git worktrees and jj workspaces for proxy
303    /// hostname routing and supervisor config discovery. Each worktree gets its own namespace,
304    /// and its daemons answer at `<daemon>.<worktree>.<project>.<tld>`.
305    ///
306    /// Set to `false` to disable all worktree/workspace discovery. The deprecated
307    /// `PITCHFORK_PROXY_WORKTREE` environment variable remains an alias during migration.
308    #[usage(
309        env = "PITCHFORK_WORKTREE",
310        deprecated_env("PITCHFORK_PROXY_WORKTREE"),
311        alias("proxy.worktree"),
312        default = true
313    )]
314    pub worktree: bool,
315}
316
317/// The `ipc.*` (inter-process communication) settings.
318#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
319#[usage(prefix = "ipc")]
320pub struct SettingsIpc {
321    /// Number of connection retry attempts
322    ///
323    /// How many times to retry connecting to the supervisor before giving up.
324    /// Each attempt uses exponential backoff between `connect_min_delay` and `connect_max_delay`.
325    #[usage(env = "PITCHFORK_IPC_CONNECT_ATTEMPTS", default = 5)]
326    pub connect_attempts: i64,
327
328    /// Maximum delay between connection retries
329    ///
330    /// The maximum delay between connection retry attempts.
331    /// Exponential backoff will not exceed this value.
332    #[usage(
333        env = "PITCHFORK_IPC_CONNECT_MAX_DELAY",
334        default = "1s",
335        ty = "duration"
336    )]
337    pub connect_max_delay: String,
338
339    /// Minimum delay between connection retries
340    ///
341    /// The initial delay between connection retry attempts.
342    /// The actual delay increases exponentially up to `connect_max_delay`.
343    #[usage(
344        env = "PITCHFORK_IPC_CONNECT_MIN_DELAY",
345        default = "100ms",
346        ty = "duration"
347    )]
348    pub connect_min_delay: String,
349
350    /// Maximum IPC requests per second per connection
351    ///
352    /// Rate limiting for IPC connections to prevent local DoS attacks.
353    /// Uses a sliding window algorithm.
354    ///
355    /// Most users won't need to change this. Increase if you have automated
356    /// tools making many rapid requests to the supervisor.
357    #[usage(env = "PITCHFORK_IPC_RATE_LIMIT", default = 100)]
358    pub rate_limit: i64,
359
360    /// Rate limit sliding window duration
361    ///
362    /// The time window for rate limiting calculations.
363    /// `rate_limit` requests are allowed within each window.
364    #[usage(
365        env = "PITCHFORK_IPC_RATE_LIMIT_WINDOW",
366        default = "1s",
367        ty = "duration"
368    )]
369    pub rate_limit_window: String,
370
371    /// Default timeout for IPC requests
372    ///
373    /// Maximum time to wait for a response from the supervisor for most operations.
374    ///
375    /// Note: Daemon start operations may use a longer timeout calculated from
376    /// the daemon's `ready_delay` setting plus a buffer.
377    #[usage(env = "PITCHFORK_IPC_REQUEST_TIMEOUT", default = "5s", ty = "duration")]
378    pub request_timeout: String,
379}
380
381/// The `logs.archive_hook.*` settings.
382#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
383#[usage(prefix = "logs.archive_hook")]
384pub struct SettingsLogsArchiveHook {
385    /// Maximum log entries per archive hook invocation
386    ///
387    /// Log entries selected for pruning are passed to the archive hook in batches of
388    /// this size. Smaller batches use less memory and are easier to retry, while larger
389    /// batches reduce hook invocation overhead.
390    #[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_BATCH_SIZE", default = 1000)]
391    pub batch_size: i64,
392
393    /// Command to run before retention deletes old log entries
394    ///
395    /// When set, the given command is invoked before log entries are permanently
396    /// pruned by retention. The command receives the entries about to be deleted as
397    /// JSON Lines (JSONL) on stdin. Each line is an object with the fields:
398    ///
399    /// - `id`: the SQLite row id
400    /// - `daemon_id`: the qualified daemon id (e.g. `"myproject/api"`)
401    /// - `timestamp`: the log timestamp in RFC 3339 format
402    /// - `message`: the raw log message text
403    ///
404    /// The following environment variables are also available:
405    ///
406    /// - `PITCHFORK_DAEMON_ID`: the qualified daemon id
407    /// - `PITCHFORK_ARCHIVE_REASON`: either `"age"` or `"count"`
408    ///
409    /// If the command exits with a non-zero status, the pruning is skipped for that
410    /// batch. This prevents data loss when the archive destination is unavailable.
411    ///
412    /// **Examples:**
413    ///
414    /// ```toml
415    /// [settings.logs.archive_hook]
416    /// command = "gzip -c >> /var/log/pitchfork/archive.jsonl.gz"
417    /// ```
418    ///
419    /// ```toml
420    /// [settings.logs.archive_hook]
421    /// command = "aws s3 cp - s3://my-bucket/pitchfork-logs/"
422    /// ```
423    #[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_COMMAND", default = "")]
424    pub command: String,
425}
426
427/// The `logs.*` settings.
428#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
429#[usage(prefix = "logs")]
430pub struct SettingsLogs {
431    #[usage(flatten)]
432    pub archive_hook: SettingsLogsArchiveHook,
433
434    /// Count-based log retention (e.g. 10000)
435    ///
436    /// Maximum number of log entries to keep per daemon in the SQLite log store.
437    ///
438    /// When set, only the most recent N log entries are retained. Older entries are
439    /// automatically pruned.
440    ///
441    /// When set to `0` (default), no count-based pruning is performed. You can combine
442    /// this with `time_retention` to enforce both a time limit and a line count limit.
443    ///
444    /// Logs are pruned automatically by the supervisor during its interval watcher
445    /// cycle (no more than once per hour). No manual rotation command is needed.
446    #[usage(env = "PITCHFORK_LOG_LINE_RETENTION", default = 0)]
447    pub line_retention: i64,
448
449    /// Default log format for daemons (json | logfmt | text)
450    #[usage(env = "PITCHFORK_LOG_FORMAT", default = "text")]
451    pub log_format: String,
452
453    /// Time-based log retention duration (e.g. '7d', '30d')
454    ///
455    /// Maximum age of log entries to keep in the SQLite log store.
456    ///
457    /// When set, log entries older than this duration are automatically pruned.
458    /// Examples: `"7d"` for 7 days, `"30d"` for 30 days, `"1h"` for 1 hour.
459    ///
460    /// When empty (default), no time-based pruning is performed. You can combine
461    /// this with `line_retention` to enforce both a time limit and a line count limit.
462    ///
463    /// Logs are pruned automatically by the supervisor during its interval watcher
464    /// cycle (no more than once per hour). No manual rotation command is needed.
465    #[usage(env = "PITCHFORK_LOG_TIME_RETENTION", default = "", ty = "duration")]
466    pub time_retention: String,
467
468    /// Show timestamps in log output
469    ///
470    /// When enabled (default), pitchfork prefixes each log line with a timestamp
471    /// (e.g. `07-10 10:30:00`).
472    ///
473    /// When disabled, timestamps are omitted from `pitchfork logs` output. This is
474    /// useful when piping logs to tools like `lnav` that expect raw JSON or when
475    /// you want to process log output without the timestamp prefix.
476    ///
477    /// Can be overridden per-invocation with `pitchfork logs --no-timestamp`.
478    #[usage(env = "PITCHFORK_LOG_TIMESTAMP", default = true)]
479    pub timestamp: bool,
480
481    /// strftime format for log timestamps in `pitchfork logs` output
482    ///
483    /// Controls the date/time format used when displaying timestamps in `pitchfork logs`
484    /// output. Uses chrono strftime syntax.
485    ///
486    /// Common format specifiers:
487    /// - `%Y` — full year (2024)
488    /// - `%m` — month (01-12)
489    /// - `%d` — day (01-31)
490    /// - `%H` — hour (00-23)
491    /// - `%M` — minute (00-59)
492    /// - `%S` — second (00-59)
493    ///
494    /// Examples:
495    /// - `%m-%d %H:%M:%S` — `07-10 10:30:00` (default)
496    /// - `%Y-%m-%d %H:%M:%S` — `2024-07-10 10:30:00`
497    /// - `%H:%M:%S` — `10:30:00` (time only)
498    /// - `%Y/%m/%d %H:%M` — `2024/07/10 10:30`
499    ///
500    /// Only affects the text display output, not `--json` or `--raw` modes.
501    #[usage(env = "PITCHFORK_LOG_TIMESTAMP_FORMAT", default = "%m-%d %H:%M:%S")]
502    pub timestamp_format: String,
503}
504
505/// The `proxy.*` settings.
506#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
507#[usage(prefix = "proxy")]
508pub struct SettingsProxy {
509    /// Automatically start daemons when accessed via proxy URL
510    ///
511    /// Enabled by default. Opening a stopped daemon's proxy URL starts its
512    /// `depends` dependencies first, using the same startup order and readiness
513    /// checks as `pitchfork start`. Oneshot dependencies must complete successfully.
514    ///
515    /// The first request waits for startup. Additional requests to the same daemon
516    /// receive a "Starting…" page that refreshes every two seconds until it is ready.
517    /// Opening a project or stack page does not start any daemons.
518    ///
519    /// Set to `false` to return a 502 error for stopped daemons and require manual startup.
520    #[usage(env = "PITCHFORK_PROXY_AUTO_START", default = true)]
521    pub auto_start: bool,
522
523    /// Maximum time to wait for an auto-started daemon to become ready
524    ///
525    /// Limits how long a proxy request waits for dependency startup, readiness
526    /// checks, and detection of the daemon's bound port. Defaults to 30 seconds.
527    ///
528    /// On timeout, the request receives an error page, but startup continues in
529    /// the background. Reload to check again, or increase this setting for a
530    /// longer startup sequence, for example `"60s"`.
531    #[usage(
532        env = "PITCHFORK_PROXY_AUTO_START_TIMEOUT",
533        default = "30s",
534        ty = "duration"
535    )]
536    pub auto_start_timeout: String,
537
538    /// Automatically trust the generated proxy CA certificate
539    ///
540    /// When enabled (default), pitchfork attempts to install its generated CA
541    /// certificate into the system trust store during HTTPS proxy startup.
542    ///
543    /// On macOS, this triggers a system authorization dialog (Touch ID or password).
544    /// On Linux, use `pitchfork proxy setup` to install the CA with sudo while
545    /// keeping the supervisor unprivileged.
546    ///
547    /// If auto-trust fails, pitchfork logs a warning and continues starting the
548    /// proxy. Use `pitchfork proxy doctor` to check trust, or
549    /// `pitchfork proxy trust` to install the CA manually (with sudo on Linux).
550    ///
551    /// Set to `false` to disable auto-trust entirely.
552    #[usage(env = "PITCHFORK_PROXY_AUTO_TRUST", default = true)]
553    pub auto_trust: bool,
554
555    /// Run a loopback DNS resolver for the proxy TLD
556    ///
557    /// While the proxy is running, answer UDP and TCP DNS queries on
558    /// `127.0.0.1:<proxy.dns_port>` for names under `proxy.tld`, including nested
559    /// project and worktree hostnames. Answers follow `proxy.host`, or the LAN
560    /// IPv4 address in LAN mode. Names outside the TLD receive REFUSED; queries
561    /// are never forwarded.
562    ///
563    /// Run `pitchfork proxy setup` to configure system resolution separately.
564    /// Set to `false` when using another resolver or when DNS is not needed.
565    #[usage(env = "PITCHFORK_PROXY_DNS", default = true)]
566    pub dns: bool,
567
568    /// Port the loopback DNS resolver listens on
569    ///
570    /// The resolver binds `127.0.0.1:<dns_port>` on both UDP and TCP.
571    ///
572    /// The default avoids privileged port 53 and the mDNS port, 5353.
573    #[usage(env = "PITCHFORK_PROXY_DNS_PORT", default = 15353)]
574    pub dns_port: i64,
575
576    /// Enable the reverse proxy server for daemons
577    ///
578    /// When enabled, pitchfork starts a reverse proxy that routes a stable
579    /// hostname to the daemon's actual listening port.
580    ///
581    /// Every daemon with a `port` gets a hostname built from its name, its
582    /// worktree when it lives in one, and its project, unless it opts out with
583    /// `proxy = false`. A daemon without a port is not routed.
584    ///
585    /// Example: `api.myproject.localhost:7777` -> `localhost:3000`
586    #[usage(env = "PITCHFORK_PROXY_ENABLE", default = false)]
587    pub enable: bool,
588
589    /// Bind address for the reverse proxy server
590    ///
591    /// IP address the reverse proxy listens on.
592    ///
593    /// **Security Warning:** The default `127.0.0.1` only allows local connections.
594    /// Setting this to `0.0.0.0` will expose the proxy on every network interface,
595    /// including externally routable ones -- anyone on the same LAN can then reach
596    /// your local daemons.
597    ///
598    /// **Examples:**
599    /// - `"127.0.0.1"` - Local only (default, recommended)
600    /// - `"0.0.0.0"` - All interfaces (use with caution)
601    /// - `"::1"` - IPv6 loopback
602    #[usage(env = "PITCHFORK_PROXY_HOST", default = "127.0.0.1")]
603    pub host: String,
604
605    /// Enable HTTPS for the reverse proxy
606    ///
607    /// When enabled (default), the proxy serves HTTPS instead of HTTP.
608    ///
609    /// You must also configure `proxy.tls_cert` and `proxy.tls_key`, or pitchfork
610    /// will auto-generate a self-signed certificate stored in the state directory.
611    ///
612    /// Set to `false` to use plain HTTP (e.g. for simple local development).
613    #[usage(env = "PITCHFORK_PROXY_HTTPS", default = true)]
614    pub https: bool,
615
616    /// Stop proxy-started daemons after this long without proxy activity
617    ///
618    /// Disabled by default: an empty string or `"0"` disables the default timeout.
619    /// Set a duration such as `"15m"` or `"1h"` to enable idle shutdown for daemons
620    /// started through their proxy URL. A daemon's `proxy_idle_timeout` overrides
621    /// this setting; dependencies without an override inherit the requested
622    /// daemon's timeout.
623    ///
624    /// HTTP requests count until their response ends. Streaming responses,
625    /// WebSockets, and TLS passthrough connections keep a daemon active while
626    /// open. DNS lookups, idle keep-alive connections, and traffic sent directly
627    /// to the daemon's port do not count.
628    ///
629    /// Only proxy-started daemons are eligible. Explicitly starting a daemon
630    /// exempts it and its dependencies from idle shutdown. Live dependents and
631    /// tracked shell sessions also prevent shutdown.
632    ///
633    /// Eligibility is checked every `general.interval` (10 seconds by default).
634    /// Dependencies stop after their dependents; shutdown may take longer than
635    /// the idle timeout. The timeout is recorded at startup, and activity
636    /// tracking resets after a supervisor restart.
637    #[usage(env = "PITCHFORK_PROXY_IDLE_TIMEOUT", default = "", ty = "duration")]
638    pub idle_timeout: String,
639
640    /// Enable LAN mode for the reverse proxy
641    ///
642    /// When enabled, the proxy switches to the `.local` TLD and publishes slug
643    /// hostnames via mDNS so that other devices on the same network can reach
644    /// your daemons (e.g. `myapp.local` from a phone or another computer).
645    ///
646    /// LAN mode:
647    /// - Forces `proxy.tld` to `local` (mDNS requirement)
648    /// - Publishes each slug as an mDNS address record (`<slug>.local → <LAN-IP>`)
649    /// - Binds the proxy to `0.0.0.0` instead of `127.0.0.1` (overridable via `proxy.host`)
650    /// - Auto-detects your LAN IP and re-publishes mDNS records if it changes
651    ///
652    /// Other devices must trust the pitchfork CA certificate to use HTTPS.
653    /// Run `pitchfork proxy trust` on each device, or use `proxy.https = false`.
654    #[usage(env = "PITCHFORK_PROXY_LAN", default = false)]
655    pub lan: bool,
656
657    /// Pin a specific LAN IP address instead of auto-detecting
658    ///
659    /// When set, skips auto-detection and uses this IP for mDNS publishing.
660    /// Implies `proxy.lan = true` if a non-empty value is provided.
661    #[usage(env = "PITCHFORK_PROXY_LAN_IP", default = "")]
662    pub lan_ip: String,
663
664    /// Port the reverse proxy server listens on
665    ///
666    /// The port pitchfork's reverse proxy binds to. Must be in the range 1-65535.
667    ///
668    /// Default is 443 (standard HTTPS port) since the proxy defaults to HTTPS.
669    /// Users can override this to any port (e.g. 7777) to avoid requiring
670    /// elevated privileges.
671    ///
672    /// To use standard ports without running the supervisor as root, choose
673    /// an unprivileged listener such as 8443 and run `pitchfork proxy setup`
674    /// to redirect local traffic on macOS or Linux. On Linux, setup can also
675    /// grant permission to bind ports below 1024 directly.
676    #[usage(env = "PITCHFORK_PROXY_PORT", default = 443)]
677    pub port: i64,
678
679    /// Automatically sync slug hostnames to /etc/hosts (deprecated)
680    ///
681    /// Deprecated and scheduled for removal after one release. Run
682    /// `pitchfork proxy setup`, check resolution with `pitchfork proxy doctor`,
683    /// then set `sync_hosts = false`. The loopback DNS resolver supports nested
684    /// hostnames without per-host entries.
685    ///
686    /// When enabled (default), pitchfork adds entries to `/etc/hosts` for
687    /// registered slugs (e.g. `127.0.0.1 myapp.localhost`) so that browsers can
688    /// resolve them. Entries are managed in a marked block and cleaned up when
689    /// the proxy shuts down. Writing to `/etc/hosts` may require `sudo`, and it
690    /// only ever covers registered slugs, never wildcard names.
691    #[usage(env = "PITCHFORK_PROXY_SYNC_HOSTS", default = true)]
692    pub sync_hosts: bool,
693
694    /// Top-level domain used for proxy URLs
695    ///
696    /// The TLD appended to daemon hostnames in proxy URLs.
697    ///
698    /// With the default `localhost`, daemon URLs look like:
699    ///   `api.myproject.localhost:7777`  (daemon `api` of project `myproject`)
700    ///
701    /// Run `pitchfork proxy setup` to configure system resolution, including
702    /// for custom TLDs such as `test`, or use `--pac` for applications that honor
703    /// automatic proxy settings. Restart the supervisor after changing the TLD.
704    #[usage(env = "PITCHFORK_PROXY_TLD", default = "localhost")]
705    pub tld: String,
706
707    /// Path to TLS certificate file (PEM format) for HTTPS proxy
708    ///
709    /// Path to a PEM-encoded TLS certificate file used when `proxy.https = true`.
710    /// It is served as-is for every hostname, and must match `proxy.tls_key`.
711    ///
712    /// If left empty and `proxy.https = true`, pitchfork generates a local
713    /// certificate authority at `$PITCHFORK_STATE_DIR/proxy/ca.pem` and signs a
714    /// certificate per hostname from it on the first TLS handshake, caching
715    /// them in `$PITCHFORK_STATE_DIR/proxy/host-certs/`. Trusting the CA once
716    /// with `pitchfork proxy trust` covers every proxy hostname.
717    ///
718    /// With a custom certificate, pitchfork serves that certificate without
719    /// signing per-hostname certificates. It must cover every hostname you
720    /// use, and clients must trust its issuer. Setup skips CA installation;
721    /// set `proxy.auto_trust = false` to also disable startup CA trust.
722    #[usage(env = "PITCHFORK_PROXY_TLS_CERT", default = "")]
723    pub tls_cert: String,
724
725    /// Path to TLS private key file (PEM format) for HTTPS proxy
726    ///
727    /// Path to a PEM-encoded private key file matching `proxy.tls_cert`. The
728    /// pair is checked at startup, so a mismatch is reported rather than
729    /// failing every handshake.
730    ///
731    /// If left empty and `proxy.https = true`, pitchfork generates a CA key at
732    /// `$PITCHFORK_STATE_DIR/proxy/ca-key.pem` instead. See `proxy.tls_cert`.
733    #[usage(env = "PITCHFORK_PROXY_TLS_KEY", default = "")]
734    pub tls_key: String,
735
736    /// Enable wildcard subdomain matching for proxy routes
737    ///
738    /// When enabled (default), extra labels to the left of a daemon's hostname
739    /// route to that same daemon.
740    ///
741    /// For example, with a daemon reachable at `api.myproject.localhost`:
742    ///
743    /// - `api.myproject.localhost` → exact match (always works)
744    ///
745    /// - `tenant.api.myproject.localhost` → wildcard fallback to the same daemon
746    ///
747    /// The same holds for a legacy slug, where `tenant.myapp.localhost` falls
748    /// back to the slug `myapp`.
749    ///
750    /// This is useful for multi-tenant apps where each tenant gets a unique
751    /// subdomain (e.g. `acme.myapp.localhost`, `globex.myapp.localhost`) but
752    /// all share the same backend server.
753    ///
754    /// Set to `false` to require exact hostname matches only.
755    #[usage(env = "PITCHFORK_PROXY_WILDCARD", default = true)]
756    pub wildcard: bool,
757}
758
759/// The `supervisor.*` settings.
760#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
761#[usage(prefix = "supervisor")]
762pub struct SettingsSupervisor {
763    /// Automatically start the supervisor when a client command needs it
764    ///
765    /// When enabled (default), commands such as `pitchfork start`, `pitchfork list`,
766    /// the TUI, and shell activation start a background supervisor automatically when
767    /// one is not already running.
768    ///
769    /// Disable this when the supervisor is managed by systemd, launchd, or another
770    /// service manager:
771    ///
772    /// ```toml
773    /// [settings.supervisor]
774    /// auto_start = false
775    /// ```
776    ///
777    /// With auto-start disabled, client commands wait for the configured IPC
778    /// connection attempts and then fail with an actionable error instead of spawning
779    /// an unmanaged supervisor. Explicit `pitchfork supervisor start` and
780    /// `pitchfork supervisor run` commands are unaffected.
781    #[usage(env = "PITCHFORK_SUPERVISOR_AUTO_START", default = true)]
782    pub auto_start: bool,
783
784    /// Reconcile orphaned daemon processes when supervisor starts
785    ///
786    /// When enabled, the supervisor scans the state file on startup for daemon
787    /// processes left behind by a previous supervisor instance that was killed
788    /// unexpectedly (for example, with `kill -9`) and reconciles them according
789    /// to `supervisor.orphan_policy` (re-adopt by default, or terminate).
790    ///
791    /// Before acting, the recorded process identity (PID plus kernel start
792    /// time) is verified so that a PID recycled by the OS to an unrelated process
793    /// is never adopted or killed — in that case only the stale state entry is
794    /// cleared. When terminating, Linux and Windows also pin that identity with a
795    /// pidfd or open process handle, so a recycled PID cannot be signaled. If the
796    /// identity cannot be verified or pinned, reconciliation fails closed: the
797    /// live process and its running state are retained rather than risk acting on
798    /// the wrong process or allowing a duplicate instance to start.
799    ///
800    /// Disabling this leaves orphaned processes and their state entries
801    /// completely untouched. This is a legacy escape hatch; prefer
802    /// `orphan_policy = "adopt"` (the default), which keeps daemons running
803    /// across a supervisor crash while resuming supervision.
804    #[usage(env = "PITCHFORK_CLEANUP_ORPHANS", default = true)]
805    pub cleanup_orphans: bool,
806
807    /// Enable container/PID1 mode for running inside Docker containers
808    ///
809    /// When enabled, pitchfork operates as a proper PID 1 process inside a container:
810    /// - Installs a SIGCHLD handler to reap all orphaned/zombie child processes
811    /// - Routes SIGTERM/SIGINT through the graceful shutdown sequence
812    ///
813    /// This is essential when running pitchfork as the entrypoint of a Docker container,
814    /// where PID 1 must reap zombie processes to prevent process table exhaustion.
815    ///
816    /// Can also be enabled via the `--container` CLI flag on `pitchfork supervisor run`.
817    #[usage(env = "PITCHFORK_CONTAINER", default = false)]
818    pub container: bool,
819
820    /// Consecutive CPU-over-limit samples before killing a daemon
821    ///
822    /// When a daemon has `cpu_limit` configured, the supervisor checks CPU usage at
823    /// each interval tick. To avoid killing daemons during transient spikes (e.g. JIT
824    /// warm-up, burst responses), the process is only killed after this many
825    /// **consecutive** samples exceed the limit. A single sample below the limit
826    /// resets the counter.
827    ///
828    /// **Examples:**
829    /// - `1` - Kill immediately on first over-limit sample (no grace period)
830    /// - `3` - Require 3 consecutive over-limit samples (default)
831    /// - `5` - More tolerant of short bursts
832    ///
833    /// With the default interval of `10s`, a threshold of `3` means a daemon must
834    /// exceed its CPU limit for ~30 seconds before being killed.
835    #[usage(env = "PITCHFORK_CPU_VIOLATION_THRESHOLD", default = 3)]
836    pub cpu_violation_threshold: i64,
837
838    /// Interval for checking cron schedules
839    ///
840    /// How often to check if any cron-scheduled daemons should be triggered.
841    ///
842    /// The default of 10 seconds supports sub-minute cron schedules.
843    /// Increase for lower resource usage if you don't need fine-grained scheduling.
844    #[usage(
845        env = "PITCHFORK_CRON_CHECK_INTERVAL",
846        default = "10s",
847        ty = "duration"
848    )]
849    pub cron_check_interval: String,
850
851    /// File watch debounce duration
852    ///
853    /// When using `watch` patterns to auto-restart daemons on file changes,
854    /// this controls how long to wait after the last change before triggering
855    /// a restart.
856    ///
857    /// This prevents rapid restart cycles when many files change at once
858    /// (e.g., during a build or git checkout).
859    #[usage(env = "PITCHFORK_FILE_WATCH_DEBOUNCE", default = "1s", ty = "duration")]
860    pub file_watch_debounce: String,
861
862    /// Default time between health probes
863    ///
864    /// When a daemon has `health_cmd`, `health_http` or `health_port`
865    /// configured but does not set its own `interval`, the supervisor probes
866    /// it this often.
867    #[usage(
868        env = "PITCHFORK_HEALTH_CHECK_INTERVAL",
869        default = "10s",
870        ty = "duration"
871    )]
872    pub health_check_interval: String,
873
874    /// Default consecutive health-check failures before killing a daemon
875    ///
876    /// When a daemon's `health_cmd`, `health_http` or `health_port` fails this
877    /// many times in a row, the daemon is killed as a crash so the retry logic
878    /// restarts it. Individual daemons can override this with `retries` in
879    /// their health check configuration.
880    #[usage(env = "PITCHFORK_HEALTH_CHECK_RETRIES", default = 3)]
881    pub health_check_retries: i64,
882
883    /// Default per-probe timeout for `health_cmd`
884    ///
885    /// Maximum time to wait for a `health_cmd` shell command to finish before
886    /// counting the probe as failed and cancelling it.
887    #[usage(env = "PITCHFORK_HEALTH_CMD_TIMEOUT", default = "10s", ty = "duration")]
888    pub health_cmd_timeout: String,
889
890    /// Default per-request timeout for `health_http`
891    ///
892    /// Maximum time to wait for a response from a `health_http` endpoint before
893    /// counting the probe as failed.
894    #[usage(env = "PITCHFORK_HEALTH_HTTP_TIMEOUT", default = "5s", ty = "duration")]
895    pub health_http_timeout: String,
896
897    /// Default per-connect timeout for `health_port`
898    ///
899    /// Maximum time to wait for a TCP connection to a `health_port` to
900    /// establish before counting the probe as failed.
901    #[usage(env = "PITCHFORK_HEALTH_PORT_TIMEOUT", default = "5s", ty = "duration")]
902    pub health_port_timeout: String,
903
904    /// Timeout for HTTP ready checks
905    ///
906    /// Maximum time to wait for a response when checking `ready_http` endpoints.
907    ///
908    /// Increase if your services take a while to respond during startup.
909    #[usage(env = "PITCHFORK_HTTP_CLIENT_TIMEOUT", default = "5s", ty = "duration")]
910    pub http_client_timeout: String,
911
912    /// Daemon log buffer flush interval
913    ///
914    /// How often daemon log output is flushed to disk.
915    /// Lower values mean logs appear faster in the UI but may impact performance.
916    #[usage(
917        env = "PITCHFORK_LOG_FLUSH_INTERVAL",
918        default = "500ms",
919        ty = "duration"
920    )]
921    pub log_flush_interval: String,
922
923    /// What to do with live orphaned daemons on supervisor startup: adopt or kill
924    ///
925    /// When the supervisor starts and finds daemons in the state file whose
926    /// processes are still alive from a previous supervisor instance that died
927    /// uncleanly, this policy decides what happens (after the process identity
928    /// is verified via PID plus kernel start time):
929    ///
930    /// - `adopt` (default): keep the process running and resume supervision.
931    ///   The daemon keeps its state (status, ports, proxy routing) and is
932    ///   monitored by polling. Log capture is unaffected, because a daemon's
933    ///   output is read by a sibling sink process rather than by the supervisor,
934    ///   so it continues uninterrupted across the crash. Exit codes of adopted
935    ///   daemons cannot be observed, though;
936    ///   an adopted daemon that dies unexpectedly is marked `errored` with an
937    ///   unknown exit code, which makes it eligible for its configured retries.
938    /// - `kill`: terminate the orphaned process group so the new supervisor
939    ///   starts with a clean slate, matching pre-adoption behavior.
940    ///
941    /// Daemons whose recorded PID is dead, or whose PID now belongs to a
942    /// different process, have their state reset under either policy. If the
943    /// process identity cannot be verified, reconciliation fails closed and
944    /// retains the running state without adopting or killing.
945    ///
946    /// The same policy applies when the interval watcher finds a running daemon
947    /// that has lost its monitor at runtime.
948    ///
949    /// This setting has no effect when `cleanup_orphans` is disabled.
950    #[usage(env = "PITCHFORK_ORPHAN_POLICY", default = "adopt")]
951    pub orphan_policy: String,
952
953    /// Maximum port increment attempts when auto_bump_port is enabled
954    ///
955    /// When `auto_bump_port = true` is set on a daemon, pitchfork will try incrementing
956    /// all of the daemon's ports by the same offset to find a free range. This setting
957    /// controls how many offsets are tried before giving up with an error.
958    ///
959    /// For example, with `port = [3000]` and `port_bump_attempts = 10`, pitchfork will
960    /// try ports 3000, 3001, 3002, ... up to 3009 before reporting failure.
961    ///
962    /// This is a global default; individual daemons can override it with
963    /// `port_bump_attempts` in their daemon configuration.
964    #[usage(env = "PITCHFORK_PORT_BUMP_ATTEMPTS", default = 10)]
965    pub port_bump_attempts: i64,
966
967    /// Interval between ready checks (HTTP, TCP, command)
968    ///
969    /// How often to poll when checking if a daemon is ready using:
970    /// - `ready_http` - HTTP health endpoint
971    /// - `ready_port` - TCP port listening
972    /// - `ready_cmd` - Shell command exit code
973    ///
974    /// Lower values detect readiness faster but use more resources.
975    #[usage(
976        env = "PITCHFORK_READY_CHECK_INTERVAL",
977        default = "500ms",
978        ty = "duration"
979    )]
980    pub ready_check_interval: String,
981
982    /// Delay between stop and start during restart
983    ///
984    /// Brief pause after stopping a daemon before starting it again.
985    /// Helps ensure resources (like ports) are fully released.
986    #[usage(env = "PITCHFORK_RESTART_DELAY", default = "100ms", ty = "duration")]
987    pub restart_delay: String,
988
989    /// Maximum time to wait for a oneshot daemon to finish
990    ///
991    /// A `oneshot = true` daemon is ready when its process exits `0`, so there is no
992    /// readiness check to bound the wait. `pitchfork start` gives up after this long
993    /// and reports a timeout; the task itself keeps running and is still recorded as
994    /// `completed` if it later exits successfully. A nonzero exit remains a failure.
995    ///
996    /// Set to `0` for no limit. Raise it for long migrations, backfills, or seeds.
997    #[usage(env = "PITCHFORK_ONESHOT_TIMEOUT", default = "1h", ty = "duration")]
998    pub oneshot_timeout: String,
999
1000    /// Maximum time to wait for daemon to stop gracefully
1001    ///
1002    /// When stopping a daemon, pitchfork sends its configured signal (SIGTERM by default) and waits this long
1003    /// for the process to exit gracefully before sending SIGKILL.
1004    ///
1005    /// Increase for daemons that need time to clean up (e.g., flush data).
1006    #[usage(env = "PITCHFORK_STOP_TIMEOUT", default = "5s", ty = "duration")]
1007    pub stop_timeout: String,
1008
1009    /// Default user to run daemon processes as
1010    ///
1011    /// Default Unix user for daemon processes spawned by the supervisor.
1012    ///
1013    /// When set, all daemons run as this user unless an individual daemon sets
1014    /// `user = "..."`. The value may be a username (for example `"postgres"`) or
1015    /// a numeric UID (for example `"501"`).
1016    ///
1017    /// If unset and the supervisor is running as root via `sudo`, daemons default to
1018    /// the sudo-calling user from `SUDO_UID`/`SUDO_GID` instead of running as root.
1019    /// A system boot service registered with `sudo pitchfork boot enable` records
1020    /// that user as `--invoking-user` and defaults to them in the same way.
1021    /// On Windows, a nonempty value prevents daemon startup with an error;
1022    /// user switching is only supported on Unix.
1023    #[usage(env = "PITCHFORK_USER", default = "")]
1024    pub user: String,
1025
1026    /// File watcher config refresh interval
1027    ///
1028    /// How often the supervisor refreshes file watch configuration when using `watch` patterns.
1029    ///
1030    /// This controls how quickly newly started/stopped daemons with watch patterns are reflected
1031    /// in the active watcher set.
1032    ///
1033    /// For polling watcher cadence, use `supervisor.watch_poll_interval`.
1034    ///
1035    /// Lower values react faster to configuration/runtime changes but use more CPU.
1036    /// The default `"10s"` is appropriate for most environments.
1037    #[usage(
1038        env = "PITCHFORK_WATCH_INTERVAL",
1039        deprecated_env("PITCHFORK_WATCH_INTERVAL_MS"),
1040        default = "10s",
1041        ty = "duration"
1042    )]
1043    pub watch_interval: String,
1044
1045    /// Polling watcher filesystem scan interval
1046    ///
1047    /// How often polling-based file watchers scan for changes.
1048    ///
1049    /// This applies when daemon `watch_mode` is `poll`, or when `watch_mode = "auto"`
1050    /// falls back to polling because native watchers are unavailable.
1051    ///
1052    /// Lower values detect changes faster but use more CPU and I/O.
1053    /// `"100ms"` is useful for highly interactive workflows;
1054    /// `"500ms"` is a practical default for remote/networked filesystems.
1055    #[usage(
1056        env = "PITCHFORK_WATCH_POLL_INTERVAL",
1057        default = "500ms",
1058        ty = "duration"
1059    )]
1060    pub watch_poll_interval: String,
1061}
1062
1063/// The `tui.*` (terminal UI) settings.
1064#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1065#[usage(prefix = "tui")]
1066pub struct SettingsTui {
1067    /// Status message display duration
1068    ///
1069    /// How long status messages (like "Daemon started") remain visible
1070    /// in the TUI before automatically clearing.
1071    #[usage(
1072        env = "PITCHFORK_TUI_MESSAGE_DURATION",
1073        default = "3s",
1074        ty = "duration"
1075    )]
1076    pub message_duration: String,
1077
1078    /// Daemon list refresh interval
1079    ///
1080    /// How often the TUI refreshes the daemon list and status information.
1081    ///
1082    /// Lower values provide more responsive updates but may increase CPU usage,
1083    /// especially with many daemons.
1084    ///
1085    /// **Recommended values:**
1086    /// - `"1s"` - More responsive
1087    /// - `"2s"` - Default, balanced
1088    /// - `"5s"` - Lower resource usage
1089    #[usage(env = "PITCHFORK_TUI_REFRESH_RATE", default = "2s", ty = "duration")]
1090    pub refresh_rate: String,
1091
1092    /// Number of stat samples to keep for graphs
1093    ///
1094    /// How many CPU/memory stat samples to keep for each daemon's graph.
1095    /// With the default refresh rate of 2s, 60 samples = ~2 minutes of history.
1096    ///
1097    /// Increase for longer history in graphs, at the cost of more memory.
1098    #[usage(env = "PITCHFORK_TUI_STAT_HISTORY", default = 60)]
1099    pub stat_history: i64,
1100
1101    /// Event loop tick rate
1102    ///
1103    /// How often the TUI checks for keyboard input and other events.
1104    /// This affects input responsiveness.
1105    ///
1106    /// Most users won't need to change this. Lower values make the UI more
1107    /// responsive but use more CPU.
1108    #[usage(env = "PITCHFORK_TUI_TICK_RATE", default = "100ms", ty = "duration")]
1109    pub tick_rate: String,
1110
1111    /// Color theme
1112    ///
1113    /// `auto` only uses the terminal's own palette, so it adapts to light and
1114    /// dark terminals. Other values are a built-in theme (`catppuccin_latte`,
1115    /// `catppuccin_frappe`, `catppuccin_macchiato`, `catppuccin_mocha`) or a
1116    /// custom theme declared under `[themes.<name>]` in a config file.
1117    ///
1118    /// ```toml
1119    /// [settings.tui]
1120    /// theme = "mine"
1121    ///
1122    /// [themes.mine]
1123    /// base = "auto"
1124    /// selection_bg = "#ddd6fe"
1125    /// ```
1126    #[usage(env = "PITCHFORK_TUI_THEME", default = "auto")]
1127    pub theme: String,
1128
1129    /// Theme for a light terminal
1130    ///
1131    /// Used instead of `theme` when `theme` is `auto` and the terminal's
1132    /// background is light. Same values as `theme`. Empty keeps `auto`.
1133    ///
1134    /// The background is queried when the TUI starts; if the terminal does not
1135    /// answer, `theme` is used.
1136    #[usage(env = "PITCHFORK_TUI_LIGHT_THEME", default = "")]
1137    pub light_theme: String,
1138
1139    /// Theme for a dark terminal
1140    ///
1141    /// Used instead of `theme` when `theme` is `auto` and the terminal's
1142    /// background is dark. Same values as `theme`. Empty keeps `auto`.
1143    #[usage(env = "PITCHFORK_TUI_DARK_THEME", default = "")]
1144    pub dark_theme: String,
1145}
1146
1147/// The `web.*` (web UI) settings.
1148#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1149#[usage(prefix = "web")]
1150pub struct SettingsWeb {
1151    /// Automatically start web UI when supervisor starts
1152    ///
1153    /// When enabled, the web UI server will automatically start alongside the supervisor.
1154    ///
1155    /// By default, this is disabled. You can also start the web UI manually with:
1156    /// ```text
1157    /// pitchfork supervisor start --web-port=3120
1158    /// ```
1159    #[usage(env = "PITCHFORK_WEB_AUTO_START", default = false)]
1160    pub auto_start: bool,
1161
1162    /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
1163    ///
1164    /// Serves the web UI under a sub-path prefix, useful when running behind a reverse
1165    /// proxy that routes a path prefix to pitchfork.
1166    ///
1167    /// **Examples:**
1168    /// - `""` - Serve at root `/` (default)
1169    /// - `"ps"` - Serve at `/ps/`
1170    /// - `"tools/pitchfork"` - Serve at `/tools/pitchfork/`
1171    ///
1172    /// Equivalent to the `--web-path` CLI flag. The CLI flag takes priority over this setting.
1173    #[usage(env = "PITCHFORK_WEB_PATH", default = "")]
1174    pub base_path: String,
1175
1176    /// Web server bind address
1177    ///
1178    /// IP address for the web UI to listen on.
1179    ///
1180    /// **Security Warning:** The default `127.0.0.1` only allows local connections.
1181    /// Setting this to `0.0.0.0` will expose the web UI to your network.
1182    ///
1183    /// **Examples:**
1184    /// - `"127.0.0.1"` - Local only (default, recommended)
1185    /// - `"0.0.0.0"` - All interfaces (use with caution)
1186    /// - `"192.168.1.100"` - Specific interface
1187    #[usage(env = "PITCHFORK_WEB_BIND_ADDRESS", default = "127.0.0.1")]
1188    pub bind_address: String,
1189
1190    /// Default web server port
1191    ///
1192    /// The port number for the web UI. If this port is in use, pitchfork will
1193    /// try subsequent ports up to `port_attempts` times.
1194    #[usage(env = "PITCHFORK_WEB_BIND_PORT", default = 3120)]
1195    pub bind_port: i64,
1196
1197    /// Initial number of log lines to display
1198    ///
1199    /// How many lines of logs to show initially when viewing daemon logs in the web UI.
1200    /// More lines means slower initial load but more history visible.
1201    #[usage(env = "PITCHFORK_WEB_LOG_LINES", default = 100)]
1202    pub log_lines: i64,
1203
1204    /// Number of ports to try if default is in use
1205    ///
1206    /// If the default port is occupied, pitchfork will try this many consecutive
1207    /// ports before giving up.
1208    ///
1209    /// For example, with `bind_port = 3120` and `port_attempts = 10`,
1210    /// it will try ports 3120, 3121, 3122, ... up to 3129.
1211    #[usage(env = "PITCHFORK_WEB_PORT_ATTEMPTS", default = 10)]
1212    pub port_attempts: i64,
1213
1214    /// Server-Sent Events poll interval for log streaming
1215    ///
1216    /// How often the web UI checks for new log lines when streaming logs.
1217    /// Lower values provide more real-time updates but use more resources.
1218    #[usage(
1219        env = "PITCHFORK_WEB_SSE_POLL_INTERVAL",
1220        default = "500ms",
1221        ty = "duration"
1222    )]
1223    pub sse_poll_interval: String,
1224}
1225
1226/// Every setting pitchfork has.
1227///
1228/// `SETTINGS_PROPS`, `SETTINGS_REGISTRY`, `read`, and `spec_kdl` are generated
1229/// from these fields; the CLI's emitted spec carries the `config` block
1230/// through `#[usage(config = ...)]` on the root.
1231#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1232// `file(...)` is intentionally repeatable in usage's configuration DSL.
1233#[allow(clippy::duplicated_attributes)]
1234#[usage(
1235    file(path = "/etc/pitchfork/config.toml", scope = "system", format = "toml"),
1236    file(
1237        path = "~/.config/pitchfork/config.toml",
1238        scope = "global",
1239        format = "toml"
1240    ),
1241    file(
1242        path = ".config/pitchfork.toml",
1243        findup,
1244        scope = "project",
1245        format = "toml"
1246    ),
1247    file(
1248        path = ".config/pitchfork.local.toml",
1249        findup,
1250        scope = "project",
1251        format = "toml"
1252    ),
1253    file(path = "pitchfork.toml", findup, scope = "project", format = "toml"),
1254    file(
1255        path = "pitchfork.local.toml",
1256        findup,
1257        scope = "project",
1258        format = "toml"
1259    )
1260)]
1261pub struct Settings {
1262    #[usage(flatten)]
1263    pub api: SettingsApi,
1264    #[usage(flatten)]
1265    pub boot: SettingsBoot,
1266    #[usage(flatten)]
1267    pub general: SettingsGeneral,
1268    #[usage(flatten)]
1269    pub ipc: SettingsIpc,
1270    #[usage(flatten)]
1271    pub logs: SettingsLogs,
1272    #[usage(flatten)]
1273    pub proxy: SettingsProxy,
1274    #[usage(flatten)]
1275    pub supervisor: SettingsSupervisor,
1276    #[usage(flatten)]
1277    pub tui: SettingsTui,
1278    #[usage(flatten)]
1279    pub web: SettingsWeb,
1280}
1281
1282impl Default for Settings {
1283    /// The declared defaults, read the same way any other resolution is.
1284    fn default() -> Self {
1285        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1286            .expect("no layers were given, so there is nothing to fail");
1287        Settings::read(&resolved).expect("every pitchfork setting has a declared default")
1288    }
1289}
1290
1291/// Generate the `Duration` convenience getters the rest of the codebase uses
1292/// (e.g. `settings().general_autostop_delay()`), each parsing its humantime
1293/// string field and silently falling back to the schema default. Invalid
1294/// values were already warned about once at load time.
1295macro_rules! duration_getters {
1296    ($($name:ident => $group:ident . $field:ident, $default:literal;)+) => {
1297        impl Settings {
1298            $(
1299                #[doc = concat!("Get `", stringify!($group), ".", stringify!($field), "` as Duration")]
1300                #[allow(dead_code)]
1301                pub fn $name(&self) -> std::time::Duration {
1302                    Self::parse_duration(&self.$group.$field).unwrap_or_else(|| {
1303                        humantime::parse_duration($default)
1304                            .unwrap_or(std::time::Duration::from_secs(1))
1305                    })
1306                }
1307            )+
1308        }
1309    };
1310}
1311
1312duration_getters! {
1313    general_autostop_delay => general.autostop_delay, "1m";
1314    general_interval => general.interval, "10s";
1315    general_ready_delay => general.ready_delay, "3s";
1316    ipc_connect_max_delay => ipc.connect_max_delay, "1s";
1317    ipc_connect_min_delay => ipc.connect_min_delay, "100ms";
1318    ipc_rate_limit_window => ipc.rate_limit_window, "1s";
1319    ipc_request_timeout => ipc.request_timeout, "5s";
1320    logs_time_retention => logs.time_retention, "";
1321    proxy_auto_start_timeout => proxy.auto_start_timeout, "30s";
1322    supervisor_cron_check_interval => supervisor.cron_check_interval, "10s";
1323    supervisor_file_watch_debounce => supervisor.file_watch_debounce, "1s";
1324    supervisor_health_check_interval => supervisor.health_check_interval, "10s";
1325    supervisor_health_cmd_timeout => supervisor.health_cmd_timeout, "10s";
1326    supervisor_health_http_timeout => supervisor.health_http_timeout, "5s";
1327    supervisor_health_port_timeout => supervisor.health_port_timeout, "5s";
1328    supervisor_http_client_timeout => supervisor.http_client_timeout, "5s";
1329    supervisor_log_flush_interval => supervisor.log_flush_interval, "500ms";
1330    supervisor_oneshot_timeout => supervisor.oneshot_timeout, "1h";
1331    supervisor_ready_check_interval => supervisor.ready_check_interval, "500ms";
1332    supervisor_restart_delay => supervisor.restart_delay, "100ms";
1333    supervisor_stop_timeout => supervisor.stop_timeout, "5s";
1334    supervisor_watch_interval => supervisor.watch_interval, "10s";
1335    supervisor_watch_poll_interval => supervisor.watch_poll_interval, "500ms";
1336    tui_message_duration => tui.message_duration, "3s";
1337    tui_refresh_rate => tui.refresh_rate, "2s";
1338    tui_tick_rate => tui.tick_rate, "100ms";
1339    web_sse_poll_interval => web.sse_poll_interval, "500ms";
1340}
1341
1342impl Settings {
1343    /// How long to wait for a `oneshot` daemon to finish.
1344    ///
1345    /// `supervisor.oneshot_timeout = "0"` means no limit: a task's natural end
1346    /// is its exit, and a long migration should not be called failed merely for
1347    /// outlasting a default. That is an absent deadline, not a very large one,
1348    /// so no task can outlive the substitute and be reported as timed out
1349    /// despite the setting promising otherwise.
1350    pub fn supervisor_oneshot_wait(&self) -> crate::config_types::OneshotWait {
1351        let configured = self.supervisor_oneshot_timeout();
1352        if configured.is_zero() {
1353            crate::config_types::OneshotWait::Unlimited
1354        } else {
1355            crate::config_types::OneshotWait::For(configured)
1356        }
1357    }
1358
1359    /// `proxy.idle_timeout` as a grace period, or `None` when idle shutdown
1360    /// is off (empty, zero, or invalid — invalid values were already warned
1361    /// about at load time).
1362    pub fn proxy_idle_timeout(&self) -> Option<std::time::Duration> {
1363        Self::parse_duration(self.proxy.idle_timeout.trim()).filter(|d| !d.is_zero())
1364    }
1365
1366    /// Resolve `general.ready_delay` as whole seconds.
1367    ///
1368    /// The ready-check pipeline (RunOptions/IPC/supervisor) models the delay
1369    /// in whole seconds. Reject subsecond values that would otherwise be
1370    /// silently truncated to a zero delay by `as_secs()`.
1371    pub fn general_ready_delay_secs(&self) -> Result<u64, String> {
1372        let delay = self.general_ready_delay();
1373        if delay.subsec_nanos() != 0 {
1374            return Err(format!(
1375                "settings.general.ready_delay must be a whole number of seconds, got \"{}\"",
1376                self.general.ready_delay
1377            ));
1378        }
1379        Ok(delay.as_secs())
1380    }
1381}
1382
1383impl Settings {
1384    /// Load settings from pitchfork.toml files, then overlay environment variables.
1385    /// Settings are loaded from all pitchfork.toml files in precedence order:
1386    /// 1. System-level: /etc/pitchfork/config.toml
1387    /// 2. User-level: ~/.config/pitchfork/config.toml
1388    /// 3. Project-level: pitchfork.toml files from root to current directory
1389    ///
1390    /// Environment variables override all file-based settings.
1391    ///
1392    /// The global [`settings()`] accessor resolves through
1393    /// [`Settings::resolve_from_dir`] so it can keep the provenance; this
1394    /// stays as the public one-shot entry point.
1395    #[allow(dead_code)]
1396    pub fn load() -> Self {
1397        Self::load_from_dir(&crate::env::CWD)
1398    }
1399
1400    /// Load settings for a specific project directory, then overlay environment variables.
1401    ///
1402    /// This is used when operating on daemons from registered namespaces whose project
1403    /// settings may differ from those of the invoking process's current directory.
1404    pub fn load_from_dir(start_dir: &Path) -> Self {
1405        Self::resolve_from_dir(start_dir).0
1406    }
1407
1408    /// Resolve settings for `start_dir`, returning both the typed struct and
1409    /// the origin-tracked resolution it was read from (for `pitchfork settings`).
1410    pub(crate) fn resolve_from_dir(start_dir: &Path) -> (Self, Resolved) {
1411        let env_layer = EnvLayer::from_process();
1412        // Highest precedence first, below the environment.
1413        let file_layers = Self::file_layers_from(start_dir);
1414        let mut layers = Layers::new().then(&env_layer);
1415        for layer in &file_layers {
1416            layers = layers.then(layer);
1417        }
1418        let mut resolved = match resolve(Settings::SETTINGS_REGISTRY, layers) {
1419            Ok(resolved) => resolved,
1420            Err(e) => {
1421                // Should not happen: every file was pre-validated above. Fall
1422                // back to env + defaults rather than failing to start.
1423                eprintln!("pitchfork: warning: failed to resolve settings from config files: {e}");
1424                resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env_layer)).unwrap_or_else(
1425                    |_| {
1426                        resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1427                            .expect("resolving only defaults cannot fail")
1428                    },
1429                )
1430            }
1431        };
1432        sanitize_durations(&mut resolved);
1433        for warning in usage_rs::config::explain::warnings(&resolved) {
1434            warn!("{warning}");
1435        }
1436        // Lossy, because the alternative is worse than the problem: `read` is all or nothing,
1437        // so one field the merge could not hand to its type used to cost every *other* setting
1438        // too — `Settings::default()` throws away the environment and every config file over a
1439        // single bad value. Here the offending field falls back to its own declared default and
1440        // nothing else is touched. Warn and keep going is pitchfork's call to make: a
1441        // supervisor that refuses to start because one duration is misspelled is a supervisor
1442        // that took the whole machine's daemons down with it.
1443        let (settings, errors) = Settings::read_lossy(&resolved);
1444        for error in &errors.0 {
1445            warn!("{error}");
1446        }
1447        // Every setting declares a default, so the only way this is `None` is a setting added
1448        // without one — a hole in the declaration rather than anything a user did.
1449        let settings = settings.unwrap_or_else(|| {
1450            warn!("a setting has no value and no default; falling back to built-in defaults");
1451            Settings::default()
1452        });
1453        (settings, resolved)
1454    }
1455
1456    /// The config file layers for `start_dir`, highest precedence first.
1457    ///
1458    /// Project files are found by walking up from `start_dir`; within one
1459    /// directory `pitchfork.local.toml` outranks `pitchfork.toml`, which
1460    /// outranks the same pair under `.config/`, and any file in a nearer
1461    /// directory outranks every file in a farther one. Below the project
1462    /// files come the user-level and system-level configs.
1463    ///
1464    /// Files that exist but cannot be parsed are warned about and skipped,
1465    /// matching the previous loader: a broken file must not stop pitchfork
1466    /// from starting.
1467    fn file_layers_from(start_dir: &Path) -> Vec<FileLayer> {
1468        let mut candidates: Vec<(PathBuf, FileScope)> = xx::file::find_up_all(
1469            start_dir,
1470            &[
1471                "pitchfork.local.toml",
1472                "pitchfork.toml",
1473                ".config/pitchfork.local.toml",
1474                ".config/pitchfork.toml",
1475            ],
1476        )
1477        .into_iter()
1478        .map(|path| (path, FileScope::Project))
1479        .collect();
1480        let extras = crate::extra_configs::paths_for(start_dir)
1481            .into_iter()
1482            .rev()
1483            .map(|p| (p, FileScope::Project));
1484        candidates.splice(0..0, extras);
1485        candidates.push((
1486            crate::env::PITCHFORK_GLOBAL_CONFIG_USER.clone(),
1487            FileScope::Global,
1488        ));
1489        candidates.push((
1490            crate::env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone(),
1491            FileScope::System,
1492        ));
1493        candidates
1494            .into_iter()
1495            .filter(|(path, _)| readable_settings_file(path))
1496            .map(|(path, scope)| FileLayer::at(path, scope).under("settings"))
1497            .collect()
1498    }
1499
1500    /// Parse a duration string (humantime format) to Duration
1501    pub fn parse_duration(s: &str) -> Option<std::time::Duration> {
1502        humantime::parse_duration(s).ok()
1503    }
1504
1505    /// Resolve the mise binary path.
1506    ///
1507    /// If `general.mise_bin` is explicitly set, returns that path.
1508    /// Otherwise, searches well-known install locations:
1509    /// - `~/.local/bin/mise`
1510    /// - `~/.cargo/bin/mise`
1511    /// - `/usr/local/bin/mise`
1512    /// - `/opt/homebrew/bin/mise`
1513    /// - on Windows, `mise.exe` on `PATH`
1514    ///
1515    /// Returns `None` if mise cannot be found.
1516    pub fn resolve_mise_bin(&self) -> Option<std::path::PathBuf> {
1517        self.resolve_mise_bin_with_path(std::env::var_os("PATH").as_deref())
1518    }
1519
1520    /// The `general.mise_bin` a daemon's project sets, from the resolution
1521    /// these settings were read with, without checking or searching. The
1522    /// supervisor, whose own settings do not see the project's, prefers it;
1523    /// see [`Self::resolve_daemon_mise_bin`].
1524    ///
1525    /// Only a value from one of the project's files, with a relative path
1526    /// taken from `project_dir`, or from the environment counts. One from the
1527    /// user's or the system's configuration is no more the project's than the
1528    /// supervisor's, which applies it itself, so it gives `None`, as no value
1529    /// does.
1530    pub(crate) fn project_mise_bin(
1531        &self,
1532        resolved: &Resolved,
1533        project_dir: &Path,
1534    ) -> Option<PathBuf> {
1535        if self.general.mise_bin.is_empty() {
1536            return None;
1537        }
1538        let origin = resolved.origin_key("general.mise_bin")?;
1539        project_mise_bin_from(&self.general.mise_bin, origin, project_dir)
1540    }
1541
1542    /// Resolve the mise binary for a daemon, preferring `project_mise_bin`.
1543    ///
1544    /// `project_mise_bin` is the `general.mise_bin` of the daemon's project,
1545    /// which the client reads because these settings are the supervisor's
1546    /// own and do not see the project's. Without it, falls back to
1547    /// [`Self::resolve_mise_bin`].
1548    pub fn resolve_daemon_mise_bin(
1549        &self,
1550        project_mise_bin: Option<&std::path::Path>,
1551    ) -> Option<std::path::PathBuf> {
1552        match project_mise_bin {
1553            Some(p) => configured_mise_bin(p),
1554            None => self.resolve_mise_bin(),
1555        }
1556    }
1557
1558    /// [`Self::resolve_mise_bin`] with `path` in place of the `PATH` variable.
1559    fn resolve_mise_bin_with_path(
1560        &self,
1561        path: Option<&std::ffi::OsStr>,
1562    ) -> Option<std::path::PathBuf> {
1563        // Explicit configuration takes priority
1564        if !self.general.mise_bin.is_empty() {
1565            return configured_mise_bin(Path::new(&self.general.mise_bin));
1566        }
1567
1568        // Search well-known install paths
1569        let home = crate::env::HOME_DIR.as_path();
1570        let candidates = [
1571            home.join(".local/bin/mise"),
1572            home.join(".cargo/bin/mise"),
1573            PathBuf::from("/usr/local/bin/mise"),
1574            PathBuf::from("/opt/homebrew/bin/mise"),
1575        ];
1576
1577        candidates.into_iter().find(|p| p.is_file()).or_else(|| {
1578            // Windows package managers install mise to locations of their
1579            // own, none of them above, so look for it on PATH instead.
1580            if cfg!(windows) {
1581                find_in_path("mise.exe", path)
1582            } else {
1583                None
1584            }
1585        })
1586    }
1587
1588    /// Resolve the shell used for daemon `run` scripts, `ready_cmd` /
1589    /// `health_cmd` probes, lifecycle hooks and the log archive hook, split
1590    /// into a program and its arguments.
1591    ///
1592    /// `general.shell` applies everywhere. On Windows it applies only when it
1593    /// was set explicitly (`shell_is_explicit`); a Windows machine that leaves
1594    /// it at its default uses `general.windows_shell` instead, because the
1595    /// `sh` that `general.shell` defaults to is not on a stock Windows `PATH`.
1596    /// [`crate::settings::resolve_shell`] supplies that flag from the origin
1597    /// of the merged value; it is a parameter here so the precedence can be
1598    /// tested without a resolution.
1599    ///
1600    /// `Err` names the key whose value is empty or could not be split.
1601    pub fn resolve_shell(&self, shell_is_explicit: bool) -> Result<Vec<String>, String> {
1602        let (key, configured) = if cfg!(windows) && !shell_is_explicit {
1603            ("general.windows_shell", &self.general.windows_shell)
1604        } else {
1605            ("general.shell", &self.general.shell)
1606        };
1607        match shell_words::split(configured) {
1608            Ok(parts) if !parts.is_empty() => Ok(parts),
1609            Ok(_) => Err(format!("{key} setting is empty")),
1610            Err(e) => Err(format!("failed to parse {key} setting {configured:?}: {e}")),
1611        }
1612    }
1613
1614    /// Return `supervisor.port_bump_attempts` as `u32`, clamping out-of-range
1615    /// values to the schema default (10) and zero to 1.
1616    ///
1617    /// This is the single source of truth for the fallback so that call-sites
1618    /// don't each duplicate the hardcoded `10`.
1619    pub fn default_port_bump_attempts(&self) -> u32 {
1620        let v = u32::try_from(self.supervisor.port_bump_attempts).unwrap_or_else(|_| {
1621            warn!(
1622                "supervisor.port_bump_attempts value {} is out of range (0-{}), clamping to 10",
1623                self.supervisor.port_bump_attempts,
1624                u32::MAX
1625            );
1626            10
1627        });
1628        if v == 0 {
1629            warn!("supervisor.port_bump_attempts is 0; defaulting to 1");
1630            1
1631        } else {
1632            v
1633        }
1634    }
1635}
1636
1637/// Whether `path` holds a settings file this loader can hand to a `FileLayer`.
1638///
1639/// Mirrors the previous loader's per-file error handling: a missing file is
1640/// the ordinary case, and a file that exists but cannot be read or parsed —
1641/// or whose `settings` key is not a table — is warned about and skipped
1642/// rather than turned into a startup failure.
1643fn readable_settings_file(path: &Path) -> bool {
1644    if !path.exists() {
1645        return false;
1646    }
1647    let content = match std::fs::read_to_string(path) {
1648        Ok(content) => content,
1649        Err(e) => {
1650            eprintln!(
1651                "pitchfork: warning: failed to read {}: {}",
1652                path.display(),
1653                e
1654            );
1655            return false;
1656        }
1657    };
1658    let table: toml::Table = match content.parse() {
1659        Ok(table) => table,
1660        Err(e) => {
1661            eprintln!(
1662                "pitchfork: warning: failed to parse {}: {}",
1663                path.display(),
1664                e
1665            );
1666            return false;
1667        }
1668    };
1669    match table.get("settings") {
1670        None => true,
1671        Some(toml::Value::Table(_)) => true,
1672        Some(_) => {
1673            eprintln!(
1674                "pitchfork: warning: invalid [settings] in {}: not a table",
1675                path.display()
1676            );
1677            false
1678        }
1679    }
1680}
1681
1682/// Validate every duration-typed setting in a resolution.
1683///
1684/// The registry's `duration` type stores the humantime text as-is, so an
1685/// invalid value would otherwise ride into the struct. This warns once and
1686/// rewrites the value to the schema default through [`Resolved::coerced`],
1687/// so `pitchfork settings get/list` and the typed getters all agree —
1688/// matching the previous loader, which rejected invalid durations at load
1689/// time. A value equal to the declared default is left alone (the
1690/// `logs.time_retention` default is the empty string, meaning "disabled").
1691/// Duration settings where `0s` is never meaningful: the value is passed
1692/// straight into `tokio::time::timeout` for a health probe, so a zero
1693/// timeout fails every probe immediately and would crash-kill a healthy
1694/// daemon after the retry threshold. Same defect family as the per-daemon
1695/// health timeout rejection in `config_types.rs` (`parse_positive_timeout`).
1696const NON_ZERO_DURATION_KEYS: &[&str] = &[
1697    "supervisor.health_cmd_timeout",
1698    "supervisor.health_http_timeout",
1699    "supervisor.health_port_timeout",
1700];
1701
1702fn sanitize_durations(resolved: &mut Resolved) {
1703    let registry = Settings::SETTINGS_REGISTRY;
1704    for id in registry.ids() {
1705        let meta = registry.get(id);
1706        if !matches!(meta.ty.inner(), Ty::Duration) {
1707            continue;
1708        }
1709        let Some(Value::String(text)) = resolved.get(id) else {
1710            continue;
1711        };
1712        let default_text = match meta.default {
1713            Some(Const::Str(s)) => s,
1714            _ => "",
1715        };
1716        if text == default_text {
1717            continue;
1718        }
1719        let reason = match humantime::parse_duration(text) {
1720            Err(_) => Some(format!("invalid duration {text:?}")),
1721            Ok(d) if d.is_zero() && NON_ZERO_DURATION_KEYS.contains(&meta.key) => Some(format!(
1722                "supervisor health probe timeout must be greater than 0, got {text:?}"
1723            )),
1724            Ok(_) => None,
1725        };
1726        let Some(reason) = reason else {
1727            continue;
1728        };
1729        let origin = resolved
1730            .origin(id)
1731            .map(|o| o.describe().to_string())
1732            .unwrap_or_default();
1733        warn!("{reason} (set by {origin}), using default");
1734        resolved.coerced(
1735            id,
1736            Value::String(default_text.to_string()),
1737            format!("{reason}; the default stands"),
1738        );
1739    }
1740}
1741
1742/// Global settings instance, kept beside the resolution it was read from
1743/// (RwLock<Arc> to support runtime reload).
1744type SettingsState = (Arc<Settings>, Arc<Resolved>);
1745static SETTINGS: std::sync::RwLock<Option<SettingsState>> = std::sync::RwLock::new(None);
1746
1747fn settings_state() -> SettingsState {
1748    // Fast path: if already initialized, clone the Arc pointers.
1749    {
1750        let lock = SETTINGS.read().unwrap();
1751        if let Some(state) = lock.as_ref() {
1752            return state.clone();
1753        }
1754    }
1755    // Slow path: initialize on first access
1756    let mut lock = SETTINGS.write().unwrap();
1757    if let Some(state) = lock.as_ref() {
1758        return state.clone();
1759    }
1760    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1761    let state = (Arc::new(settings), Arc::new(resolved));
1762    *lock = Some(state.clone());
1763    state
1764}
1765
1766/// Get the global settings instance
1767pub fn settings() -> Arc<Settings> {
1768    settings_state().0
1769}
1770
1771/// The origin-tracked resolution behind [`settings()`], for the settings CLI.
1772pub(crate) fn settings_resolved() -> Arc<Resolved> {
1773    settings_state().1
1774}
1775
1776/// Whether `general.shell` was set by the user rather than left at its default.
1777///
1778/// Asked of the merge, not of the text, the same way `pitchfork settings`
1779/// decides what to mark as default: `shell = "sh -c"` written in a config file
1780/// is the same string as the default, and only its origin tells them apart.
1781fn shell_is_explicit(resolved: &Resolved) -> bool {
1782    resolved
1783        .origin_key("general.shell")
1784        .is_some_and(|origin| origin.kind != SourceKind::DEFAULTS)
1785}
1786
1787/// `value` as the project's mise_bin, given where it was set: a project file
1788/// takes a relative path from `project_dir`, the environment from the working
1789/// directory of the command it was set for.
1790fn project_mise_bin_from(value: &str, origin: &Origin, project_dir: &Path) -> Option<PathBuf> {
1791    if origin.kind == SourceKind::ENV {
1792        return Some(std::path::absolute(value).unwrap_or_else(|_| PathBuf::from(value)));
1793    }
1794    (origin.kind == SourceKind::FILE && origin.trust == Trust::Project)
1795        .then(|| project_dir.join(value))
1796}
1797
1798/// An explicitly configured `mise_bin`, if the file exists, as an absolute
1799/// path. A missing file is warned about and gives `None`, not a search for
1800/// another mise.
1801///
1802/// A relative path is taken from this process's working directory, which is
1803/// where it is checked; the daemon it wraps runs in a directory of its own,
1804/// where the same relative path could name another file or none.
1805fn configured_mise_bin(path: &Path) -> Option<PathBuf> {
1806    let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
1807    if path.is_file() {
1808        return Some(path);
1809    }
1810    warn!("mise_bin is set to {path:?} but the file does not exist");
1811    None
1812}
1813
1814/// The file called `name` in the first directory of `path` (a `PATH`-style
1815/// list) that holds one, as an absolute path.
1816///
1817/// A relative entry is looked up from this process's working directory, but
1818/// the result is used from a daemon's, so it is made absolute here.
1819fn find_in_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
1820    std::env::split_paths(path?)
1821        .map(|dir| dir.join(name))
1822        .find(|candidate| candidate.is_file())
1823        .and_then(|found| std::path::absolute(found).ok())
1824}
1825
1826/// Resolve the shell for daemon `run` scripts, command probes and hooks from
1827/// the global settings. See [`Settings::resolve_shell`].
1828pub fn resolve_shell() -> Result<Vec<String>, String> {
1829    let (settings, resolved) = settings_state();
1830    settings.resolve_shell(shell_is_explicit(&resolved))
1831}
1832
1833/// Reload settings from config files.
1834///
1835/// Called when the supervisor receives a ReloadConfig IPC request,
1836/// typically after `pitchfork settings set` modifies a config file.
1837///
1838/// Old Arc references remain valid until all holders drop them,
1839/// so no use-after-free can occur.
1840pub fn reload_settings() {
1841    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1842    let mut lock = SETTINGS.write().unwrap();
1843    *lock = Some((Arc::new(settings), Arc::new(resolved)));
1844}
1845
1846// ============================================================================
1847// Partial (all-Option) mirror structs
1848//
1849// These exist for `pitchfork.toml` round-trips: `PitchforkToml` deserializes
1850// its `[settings]` table into `SettingsPartial`, merges per-file overrides,
1851// and serializes it back out (`pitchfork settings set`, `proxy add`, ...).
1852// Settings *resolution* no longer goes through these — usage-config's
1853// origin-tracked merge replaced the apply/merge chain.
1854// ============================================================================
1855
1856macro_rules! settings_partial {
1857    (
1858        $(#[$meta:meta])*
1859        $name:ident {
1860            $(@group $group_field:ident: $group_ty:ty,)*
1861            $($(#[$fdoc:meta])* $field:ident: $ty:ty,)*
1862        }
1863    ) => {
1864        $(#[$meta])*
1865        #[derive(
1866            Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
1867        )]
1868        #[serde(default)]
1869        pub struct $name {
1870            $(
1871                #[serde(default, skip_serializing_if = "is_empty_partial")]
1872                pub $group_field: $group_ty,
1873            )*
1874            $(
1875                $(#[$fdoc])*
1876                #[serde(skip_serializing_if = "Option::is_none", default)]
1877                pub $field: Option<$ty>,
1878            )*
1879        }
1880
1881        #[allow(dead_code)]
1882        impl $name {
1883            /// Whether any field (or nested group field) is set.
1884            pub fn has_any_set(&self) -> bool {
1885                false
1886                $(|| self.$group_field.has_any_set())*
1887                $(|| self.$field.is_some())*
1888            }
1889
1890            pub fn is_empty(&self) -> bool {
1891                !self.has_any_set()
1892            }
1893
1894            /// Merge another partial onto this one.
1895            /// All `Some` values in `other` override the corresponding values in `self`.
1896            pub fn merge_from(&mut self, other: &Self) {
1897                $(self.$group_field.merge_from(&other.$group_field);)*
1898                $(
1899                    if other.$field.is_some() {
1900                        self.$field = other.$field.clone();
1901                    }
1902                )*
1903            }
1904        }
1905    };
1906}
1907
1908/// serde `skip_serializing_if` helper for nested partial groups.
1909fn is_empty_partial<T: HasAnySet>(v: &T) -> bool {
1910    !v.has_any_set()
1911}
1912
1913/// Internal trait so one serde skip helper serves every partial group.
1914trait HasAnySet {
1915    fn has_any_set(&self) -> bool;
1916}
1917
1918macro_rules! impl_has_any_set {
1919    ($($name:ident),+ $(,)?) => {
1920        $(impl HasAnySet for $name {
1921            fn has_any_set(&self) -> bool {
1922                $name::has_any_set(self)
1923            }
1924        })+
1925    };
1926}
1927
1928settings_partial! {
1929    /// Partial mirror of [`SettingsApi`].
1930    SettingsApiPartial {
1931        /// Automatically start the standalone API server
1932        auto_start: bool,
1933        /// IP address the API server binds to
1934        bind_address: String,
1935        /// Port the standalone API server listens on
1936        bind_port: i64,
1937        /// Number of consecutive ports to try if api.bind_port is in use
1938        port_attempts: i64,
1939        /// Authentication token for API access when bound to non-loopback addresses
1940        token: String,
1941    }
1942}
1943
1944settings_partial! {
1945    /// Partial mirror of [`SettingsBoot`].
1946    SettingsBootPartial {
1947        /// Absolute executable path written into boot registrations
1948        executable: String,
1949    }
1950}
1951
1952settings_partial! {
1953    /// Partial mirror of [`SettingsGeneral`].
1954    SettingsGeneralPartial {
1955        /// Delay before auto-stopping daemons when leaving a directory
1956        autostop_delay: String,
1957        /// Supervisor background task refresh interval
1958        interval: String,
1959        /// File log level (trace, debug, info, warn, error)
1960        log_file_level: String,
1961        /// Console log level (trace, debug, info, warn, error)
1962        log_level: String,
1963        /// Wrap daemon commands with mise x -- globally
1964        mise: bool,
1965        /// Explicit path to the mise binary
1966        mise_bin: String,
1967        /// Shell command used to execute daemon run scripts
1968        shell: String,
1969        /// Shell command used to execute daemon run scripts on Windows
1970        windows_shell: String,
1971        /// Show timestamps in startup log output
1972        startup_log_timestamps: bool,
1973        /// Default readiness delay in seconds when a daemon has no ready check configured
1974        ready_delay: String,
1975        /// Enable git worktree / jj workspace auto-discovery
1976        worktree: bool,
1977    }
1978}
1979
1980settings_partial! {
1981    /// Partial mirror of [`SettingsIpc`].
1982    SettingsIpcPartial {
1983        /// Number of connection retry attempts
1984        connect_attempts: i64,
1985        /// Maximum delay between connection retries
1986        connect_max_delay: String,
1987        /// Minimum delay between connection retries
1988        connect_min_delay: String,
1989        /// Maximum IPC requests per second per connection
1990        rate_limit: i64,
1991        /// Rate limit sliding window duration
1992        rate_limit_window: String,
1993        /// Default timeout for IPC requests
1994        request_timeout: String,
1995    }
1996}
1997
1998settings_partial! {
1999    /// Partial mirror of [`SettingsLogsArchiveHook`].
2000    SettingsLogsArchiveHookPartial {
2001        /// Maximum log entries per archive hook invocation
2002        batch_size: i64,
2003        /// Command to run before retention deletes old log entries
2004        command: String,
2005    }
2006}
2007
2008settings_partial! {
2009    /// Partial mirror of [`SettingsLogs`].
2010    SettingsLogsPartial {
2011        @group archive_hook: SettingsLogsArchiveHookPartial,
2012        /// Count-based log retention (e.g. 10000)
2013        line_retention: i64,
2014        /// Default log format for daemons (json | logfmt | text)
2015        log_format: String,
2016        /// Time-based log retention duration (e.g. '7d', '30d')
2017        time_retention: String,
2018        /// Show timestamps in log output
2019        timestamp: bool,
2020        /// strftime format for log timestamps in `pitchfork logs` output
2021        timestamp_format: String,
2022    }
2023}
2024
2025settings_partial! {
2026    /// Partial mirror of [`SettingsProxy`].
2027    SettingsProxyPartial {
2028        /// Automatically start daemons when accessed via proxy URL
2029        auto_start: bool,
2030        /// Maximum time to wait for an auto-started daemon to become ready
2031        auto_start_timeout: String,
2032        /// Automatically install the proxy TLS certificate into the system trust store
2033        auto_trust: bool,
2034        /// Run a loopback DNS resolver for the proxy TLD
2035        dns: bool,
2036        /// Port the loopback DNS resolver listens on
2037        dns_port: i64,
2038        /// Enable the reverse proxy server for daemons
2039        enable: bool,
2040        /// Bind address for the reverse proxy server
2041        host: String,
2042        /// Enable HTTPS for the reverse proxy
2043        https: bool,
2044        /// Stop proxy-started daemons after this long without proxy activity
2045        idle_timeout: String,
2046        /// Enable LAN mode for the reverse proxy
2047        lan: bool,
2048        /// Pin a specific LAN IP address instead of auto-detecting
2049        lan_ip: String,
2050        /// Port the reverse proxy server listens on
2051        port: i64,
2052        /// Automatically sync slug hostnames to /etc/hosts (deprecated)
2053        sync_hosts: bool,
2054        /// Top-level domain used for proxy URLs
2055        tld: String,
2056        /// Path to TLS certificate file (PEM format) for HTTPS proxy
2057        tls_cert: String,
2058        /// Path to TLS private key file (PEM format) for HTTPS proxy
2059        tls_key: String,
2060        /// Enable wildcard subdomain matching for proxy routes
2061        wildcard: bool,
2062        /// Compatibility alias for general.worktree
2063        worktree: bool,
2064    }
2065}
2066
2067settings_partial! {
2068    /// Partial mirror of [`SettingsSupervisor`].
2069    SettingsSupervisorPartial {
2070        /// Automatically start the supervisor when a client command needs it
2071        auto_start: bool,
2072        /// Reconcile orphaned daemon processes when supervisor starts
2073        cleanup_orphans: bool,
2074        /// Enable container/PID1 mode for running inside Docker containers
2075        container: bool,
2076        /// Consecutive CPU-over-limit samples before killing a daemon
2077        cpu_violation_threshold: i64,
2078        /// Interval for checking cron schedules
2079        cron_check_interval: String,
2080        /// File watch debounce duration
2081        file_watch_debounce: String,
2082        /// Default time between health probes
2083        health_check_interval: String,
2084        /// Default consecutive health-check failures before killing a daemon
2085        health_check_retries: i64,
2086        /// Default per-probe timeout for health_cmd
2087        health_cmd_timeout: String,
2088        /// Default per-request timeout for health_http
2089        health_http_timeout: String,
2090        /// Default per-connect timeout for health_port
2091        health_port_timeout: String,
2092        /// Timeout for HTTP ready checks
2093        http_client_timeout: String,
2094        /// Daemon log buffer flush interval
2095        log_flush_interval: String,
2096        /// What to do with live orphaned daemons on supervisor startup: adopt or kill
2097        orphan_policy: String,
2098        /// Maximum port increment attempts when auto_bump_port is enabled
2099        port_bump_attempts: i64,
2100        /// Maximum time to wait for a oneshot daemon to finish
2101        oneshot_timeout: String,
2102        /// Interval between ready checks (HTTP, TCP, command)
2103        ready_check_interval: String,
2104        /// Delay between stop and start during restart
2105        restart_delay: String,
2106        /// Maximum time to wait for daemon to stop gracefully
2107        stop_timeout: String,
2108        /// Default user to run daemon processes as
2109        user: String,
2110        /// File watcher config refresh interval
2111        watch_interval: String,
2112        /// Polling watcher filesystem scan interval
2113        watch_poll_interval: String,
2114    }
2115}
2116
2117settings_partial! {
2118    /// Partial mirror of [`SettingsTui`].
2119    SettingsTuiPartial {
2120        /// Status message display duration
2121        message_duration: String,
2122        /// Daemon list refresh interval
2123        refresh_rate: String,
2124        /// Number of stat samples to keep for graphs
2125        stat_history: i64,
2126        /// Event loop tick rate
2127        tick_rate: String,
2128        /// Color theme
2129        theme: String,
2130        /// Theme for a light terminal
2131        light_theme: String,
2132        /// Theme for a dark terminal
2133        dark_theme: String,
2134    }
2135}
2136
2137settings_partial! {
2138    /// Partial mirror of [`SettingsWeb`].
2139    SettingsWebPartial {
2140        /// Automatically start web UI when supervisor starts
2141        auto_start: bool,
2142        /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
2143        base_path: String,
2144        /// Web server bind address
2145        bind_address: String,
2146        /// Default web server port
2147        bind_port: i64,
2148        /// Initial number of log lines to display
2149        log_lines: i64,
2150        /// Number of ports to try if default is in use
2151        port_attempts: i64,
2152        /// Server-Sent Events poll interval for log streaming
2153        sse_poll_interval: String,
2154    }
2155}
2156
2157settings_partial! {
2158    /// Partial mirror of [`Settings`], for `[settings]` tables in
2159    /// pitchfork.toml files.
2160    SettingsPartial {
2161        @group api: SettingsApiPartial,
2162        @group boot: SettingsBootPartial,
2163        @group general: SettingsGeneralPartial,
2164        @group ipc: SettingsIpcPartial,
2165        @group logs: SettingsLogsPartial,
2166        @group proxy: SettingsProxyPartial,
2167        @group supervisor: SettingsSupervisorPartial,
2168        @group tui: SettingsTuiPartial,
2169        @group web: SettingsWebPartial,
2170    }
2171}
2172
2173impl_has_any_set!(
2174    SettingsApiPartial,
2175    SettingsBootPartial,
2176    SettingsGeneralPartial,
2177    SettingsIpcPartial,
2178    SettingsLogsArchiveHookPartial,
2179    SettingsLogsPartial,
2180    SettingsProxyPartial,
2181    SettingsSupervisorPartial,
2182    SettingsTuiPartial,
2183    SettingsWebPartial,
2184);
2185
2186impl SettingsPartial {
2187    /// Move supported legacy keys to their canonical locations before a
2188    /// read-modify-write cycle serializes this partial again.
2189    pub(crate) fn canonicalize_aliases(&mut self) {
2190        if self.general.worktree.is_none() {
2191            self.general.worktree = self.proxy.worktree.take();
2192        } else {
2193            self.proxy.worktree = None;
2194        }
2195    }
2196}
2197
2198#[cfg(test)]
2199mod tests {
2200    use super::*;
2201    use std::time::Duration;
2202
2203    #[test]
2204    fn find_in_path_takes_the_first_directory_that_has_the_file() {
2205        let empty = tempfile::tempdir().unwrap();
2206        let first = tempfile::tempdir().unwrap();
2207        let second = tempfile::tempdir().unwrap();
2208        std::fs::write(first.path().join("mise.exe"), "").unwrap();
2209        std::fs::write(second.path().join("mise.exe"), "").unwrap();
2210        // A directory with the name, not a file, does not count.
2211        std::fs::create_dir(empty.path().join("mise.exe")).unwrap();
2212
2213        let path = std::env::join_paths([empty.path(), first.path(), second.path()]).unwrap();
2214        assert_eq!(
2215            find_in_path("mise.exe", Some(&path)),
2216            Some(first.path().join("mise.exe"))
2217        );
2218        assert_eq!(find_in_path("missing.exe", Some(&path)), None);
2219        assert_eq!(find_in_path("mise.exe", None), None);
2220    }
2221
2222    #[test]
2223    fn configured_mise_bin_is_absolute() {
2224        // Tests run from the crate root, where `Cargo.toml` is.
2225        let relative = Path::new("Cargo.toml");
2226        assert_eq!(
2227            configured_mise_bin(relative),
2228            Some(std::env::current_dir().unwrap().join(relative))
2229        );
2230    }
2231
2232    #[test]
2233    fn project_mise_bin_takes_only_the_projects_own_value() {
2234        let dir = tempfile::tempdir().unwrap();
2235        let project_dir = dir.path().join("project");
2236        std::fs::create_dir_all(&project_dir).unwrap();
2237        let project_file = project_dir.join("pitchfork.toml");
2238        let user_file = dir.path().join("config.toml");
2239        std::fs::write(
2240            &project_file,
2241            "[settings.general]\nmise_bin = \"tools/mise\"\n",
2242        )
2243        .unwrap();
2244        std::fs::write(&user_file, "[settings.general]\nmise_bin = \"bin/mise\"\n").unwrap();
2245        let project = FileLayer::at(project_file, FileScope::Project).under("settings");
2246        let user = FileLayer::at(user_file, FileScope::Global).under("settings");
2247        // Absolute on every platform: `/opt/mise` is not on Windows.
2248        let env_mise = dir.path().join("env-mise");
2249        let env = EnvLayer::new([(
2250            "PITCHFORK_MISE_BIN".to_string(),
2251            env_mise.to_string_lossy().into_owned(),
2252        )]);
2253        let project_mise_bin = |layers: Layers| {
2254            let resolved = resolve(Settings::SETTINGS_REGISTRY, layers).unwrap();
2255            Settings::read(&resolved)
2256                .unwrap()
2257                .project_mise_bin(&resolved, &project_dir)
2258        };
2259
2260        // The project's own file, over the user's, from the project directory.
2261        assert_eq!(
2262            project_mise_bin(Layers::new().then(&project).then(&user)),
2263            Some(project_dir.join("tools/mise"))
2264        );
2265        // Only the user's configuration sets it: the supervisor applies that.
2266        assert_eq!(project_mise_bin(Layers::new().then(&user)), None);
2267        // The environment takes precedence over the project's file.
2268        assert_eq!(
2269            project_mise_bin(Layers::new().then(&env).then(&project)),
2270            Some(env_mise.clone())
2271        );
2272        // Not set anywhere.
2273        assert_eq!(project_mise_bin(Layers::new()), None);
2274    }
2275
2276    #[test]
2277    fn resolve_daemon_mise_bin_prefers_the_project_mise_bin() {
2278        let dir = tempfile::tempdir().unwrap();
2279        let supervisor_mise = dir.path().join("supervisor-mise");
2280        let project_mise = dir.path().join("project-mise");
2281        std::fs::write(&supervisor_mise, "").unwrap();
2282        std::fs::write(&project_mise, "").unwrap();
2283
2284        let mut settings = Settings::default();
2285        settings.general.mise_bin = supervisor_mise.to_string_lossy().into_owned();
2286
2287        assert_eq!(
2288            settings.resolve_daemon_mise_bin(Some(&project_mise)),
2289            Some(project_mise)
2290        );
2291        // A project mise_bin that does not exist is not replaced by another.
2292        assert_eq!(
2293            settings.resolve_daemon_mise_bin(Some(&dir.path().join("missing"))),
2294            None
2295        );
2296        // Without one, the supervisor's own setting applies, as before.
2297        assert_eq!(
2298            settings.resolve_daemon_mise_bin(None),
2299            Some(supervisor_mise)
2300        );
2301    }
2302
2303    #[cfg(windows)]
2304    #[test]
2305    fn resolve_mise_bin_finds_mise_exe_on_path_on_windows() {
2306        let dir = tempfile::tempdir().unwrap();
2307        let mise = dir.path().join("mise.exe");
2308        std::fs::write(&mise, "").unwrap();
2309        let path = std::env::join_paths([dir.path()]).unwrap();
2310
2311        // No `mise_bin`, and none of the Unix locations exist on Windows.
2312        let settings = Settings::default();
2313        assert_eq!(settings.resolve_mise_bin_with_path(Some(&path)), Some(mise));
2314        assert_eq!(settings.resolve_mise_bin_with_path(None), None);
2315    }
2316
2317    #[test]
2318    fn find_in_path_returns_an_absolute_path_for_a_relative_entry() {
2319        // A relative entry is found against the supervisor's working
2320        // directory, but the path is used from the daemon's, so it has to be
2321        // made absolute. Created in the working directory itself, which
2322        // always exists, unlike a build directory Cargo may put elsewhere.
2323        let dir = tempfile::tempdir_in(".").unwrap();
2324        std::fs::write(dir.path().join("mise.exe"), "").unwrap();
2325        let relative = dir
2326            .path()
2327            .strip_prefix(std::env::current_dir().unwrap())
2328            .unwrap_or(dir.path());
2329        assert!(relative.is_relative(), "{relative:?}");
2330
2331        let found = find_in_path("mise.exe", Some(relative.as_os_str())).unwrap();
2332        assert!(found.is_absolute(), "{found:?}");
2333        assert!(found.is_file());
2334    }
2335
2336    #[test]
2337    fn shell_defaults() {
2338        let settings = Settings::default();
2339        assert_eq!(settings.general.shell, "sh -c");
2340        assert_eq!(settings.general.windows_shell, "cmd /C");
2341    }
2342
2343    #[test]
2344    fn shell_precedence() {
2345        let mut settings = Settings::default();
2346        settings.general.shell = "unix-sh -c".to_string();
2347        settings.general.windows_shell = "win-sh /C".to_string();
2348        let unix = vec!["unix-sh".to_string(), "-c".to_string()];
2349        let windows = vec!["win-sh".to_string(), "/C".to_string()];
2350
2351        // An explicit general.shell wins on every platform.
2352        assert_eq!(settings.resolve_shell(true).unwrap(), unix);
2353
2354        // Left at its default, general.shell yields to windows_shell on
2355        // Windows and is the only setting consulted elsewhere.
2356        let expected = if cfg!(windows) { windows } else { unix };
2357        assert_eq!(settings.resolve_shell(false).unwrap(), expected);
2358    }
2359
2360    #[test]
2361    fn shell_is_explicit_comes_from_the_origin_not_the_text() {
2362        // `PITCHFORK_SHELL="sh -c"` is the same string as the default, and
2363        // must still count as set: on Windows it decides whether
2364        // windows_shell is consulted at all.
2365        let untouched =
2366            resolve(Settings::SETTINGS_REGISTRY, Layers::new()).expect("resolving defaults");
2367        assert!(!shell_is_explicit(&untouched));
2368
2369        let layer = EnvLayer::new([("PITCHFORK_SHELL".to_string(), "sh -c".to_string())]);
2370        let explicit = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer))
2371            .expect("resolving an override");
2372        assert!(shell_is_explicit(&explicit));
2373    }
2374
2375    #[test]
2376    fn an_unusable_shell_names_the_key_it_came_from() {
2377        let mut settings = Settings::default();
2378        settings.general.shell = "sh -c 'unbalanced".to_string();
2379        let err = settings.resolve_shell(true).unwrap_err();
2380        assert!(err.contains("general.shell"), "{err}");
2381
2382        settings.general.shell = String::new();
2383        let err = settings.resolve_shell(true).unwrap_err();
2384        assert!(err.contains("general.shell setting is empty"), "{err}");
2385
2386        settings.general.windows_shell = String::new();
2387        let key = if cfg!(windows) {
2388            "general.windows_shell"
2389        } else {
2390            "general.shell"
2391        };
2392        let err = settings.resolve_shell(false).unwrap_err();
2393        assert!(err.contains(key), "{err}");
2394    }
2395
2396    #[test]
2397    fn test_default_settings() {
2398        let settings = Settings::default();
2399
2400        // Test general settings
2401        assert_eq!(settings.general.autostop_delay, "1m");
2402        assert_eq!(settings.general.interval, "10s");
2403        assert_eq!(settings.general.log_level, "info");
2404        assert_eq!(settings.general.ready_delay, "3s");
2405
2406        // Test IPC settings
2407        assert_eq!(settings.ipc.connect_attempts, 5);
2408        assert_eq!(settings.ipc.request_timeout, "5s");
2409        assert_eq!(settings.ipc.rate_limit, 100);
2410
2411        // Test web settings
2412        assert!(!settings.web.auto_start);
2413        assert_eq!(settings.web.bind_address, "127.0.0.1");
2414        assert_eq!(settings.web.bind_port, 3120);
2415        assert_eq!(settings.web.log_lines, 100);
2416
2417        // Test TUI settings
2418        assert_eq!(settings.tui.refresh_rate, "2s");
2419        assert_eq!(settings.tui.stat_history, 60);
2420
2421        // Test supervisor settings
2422        assert!(settings.supervisor.auto_start);
2423        assert_eq!(settings.supervisor.ready_check_interval, "500ms");
2424        assert_eq!(settings.supervisor.file_watch_debounce, "1s");
2425        assert_eq!(settings.supervisor.user, "");
2426    }
2427
2428    #[test]
2429    fn a_bad_value_costs_only_its_own_setting() {
2430        // `Settings::read` is all or nothing, and the fallback for its failure used to be
2431        // `Settings::default()` — one field the merge could not hand to its type demoting all
2432        // sixty-eight settings and discarding the environment along with them.
2433        let env = EnvLayer::new([("PITCHFORK_LOG".to_string(), "debug".to_string())]);
2434        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2435
2436        // The one door into a resolution the merge does not check: a post-merge hook, which is
2437        // what `sanitize_durations` is. A bool where an integer belongs is what a buggy one
2438        // could write.
2439        let registry = Settings::SETTINGS_REGISTRY;
2440        let rate_limit = registry.lookup("ipc.rate_limit").unwrap().id;
2441        resolved.coerced(rate_limit, Value::Bool(true), "a hook that got it wrong");
2442
2443        assert!(
2444            Settings::read(&resolved).is_err(),
2445            "the strict read still refuses it"
2446        );
2447
2448        let (settings, errors) = Settings::read_lossy(&resolved);
2449        let settings = settings.expect("every setting declares a default");
2450        assert_eq!(
2451            settings.ipc.rate_limit, 100,
2452            "the bad field takes its declared default"
2453        );
2454        assert_eq!(
2455            settings.general.log_level, "debug",
2456            "and PITCHFORK_LOG is not collateral damage"
2457        );
2458        assert_eq!(errors.0.len(), 1, "{errors}");
2459        assert_eq!(errors.0[0].key, "ipc.rate_limit");
2460    }
2461
2462    #[test]
2463    fn every_setting_declares_a_default() {
2464        // What makes the `None` arm of the lossy read unreachable: a setting with no value and
2465        // no default is a hole in this file, not something a user can cause. Adding one without
2466        // a default should fail here rather than silently demote the whole struct at runtime.
2467        let missing: Vec<&str> = Settings::SETTINGS_PROPS
2468            .iter()
2469            .filter(|meta| meta.default.is_none())
2470            .map(|meta| meta.key)
2471            .collect();
2472        assert!(
2473            missing.is_empty(),
2474            "these settings declare no default: {missing:?}"
2475        );
2476    }
2477
2478    #[test]
2479    fn test_registry_matches_previous_schema() {
2480        // The emitted config block is the settings documentation now; make
2481        // sure the registry still declares what settings.toml used to.
2482        let keys: Vec<&str> = Settings::SETTINGS_PROPS
2483            .iter()
2484            .map(|meta| meta.key)
2485            .collect();
2486        // 75 before either change, plus `supervisor.oneshot_timeout` from main,
2487        // `proxy.dns` / `proxy.dns_port`, `proxy.idle_timeout`, `boot.executable`, `tui.theme`, `tui.light_theme` and `tui.dark_theme`.
2488        assert_eq!(keys.len(), 83, "{keys:?}");
2489        assert!(keys.contains(&"boot.executable"));
2490        assert!(keys.contains(&"general.autostop_delay"));
2491        assert!(keys.contains(&"supervisor.oneshot_timeout"));
2492        assert!(keys.contains(&"logs.archive_hook.command"));
2493        assert!(keys.contains(&"supervisor.health_check_interval"));
2494        assert!(keys.contains(&"supervisor.watch_interval"));
2495        assert!(keys.contains(&"proxy.dns"));
2496        assert!(keys.contains(&"proxy.dns_port"));
2497        assert!(keys.contains(&"proxy.idle_timeout"));
2498
2499        let registry = Settings::SETTINGS_REGISTRY;
2500        let interval = registry.get(registry.lookup("general.interval").unwrap().id);
2501        assert_eq!(interval.envs, &["PITCHFORK_INTERVAL"]);
2502        assert_eq!(interval.deprecated_envs, &["PITCHFORK_INTERVAL_SECS"]);
2503        let watch = registry.get(registry.lookup("supervisor.watch_interval").unwrap().id);
2504        assert_eq!(watch.deprecated_envs, &["PITCHFORK_WATCH_INTERVAL_MS"]);
2505        let log_level = registry.get(registry.lookup("general.log_level").unwrap().id);
2506        assert_eq!(log_level.envs, &["PITCHFORK_LOG"]);
2507        let worktree = registry.get(registry.lookup("general.worktree").unwrap().id);
2508        assert_eq!(worktree.envs, &["PITCHFORK_WORKTREE"]);
2509        assert_eq!(worktree.deprecated_envs, &["PITCHFORK_PROXY_WORKTREE"]);
2510        assert_eq!(worktree.aliases, &["proxy.worktree"]);
2511        assert_eq!(
2512            registry.lookup("proxy.worktree").unwrap().id,
2513            registry.lookup("general.worktree").unwrap().id,
2514        );
2515
2516        let spec = Settings::spec_kdl();
2517        let files = [
2518            "file \"/etc/pitchfork/config.toml\" scope=\"system\" format=\"toml\"",
2519            "file \"~/.config/pitchfork/config.toml\" scope=\"global\" format=\"toml\"",
2520            "file \".config/pitchfork.toml\" findup=#true format=\"toml\"",
2521            "file \".config/pitchfork.local.toml\" findup=#true format=\"toml\"",
2522            "file \"pitchfork.toml\" findup=#true format=\"toml\"",
2523            "file \"pitchfork.local.toml\" findup=#true format=\"toml\"",
2524        ];
2525        let positions: Vec<usize> = files
2526            .iter()
2527            .map(|file| spec.find(file).unwrap_or_else(|| panic!("missing {file}")))
2528            .collect();
2529        assert!(
2530            positions.windows(2).all(|pair| pair[0] < pair[1]),
2531            "config files must be documented from lowest to highest precedence:\n{spec}"
2532        );
2533    }
2534
2535    #[test]
2536    fn every_registry_key_round_trips_through_the_partial() {
2537        // A setting added to the derive structs but missed in `settings_partial!`
2538        // makes `pitchfork settings set` report success and write nothing.
2539        for meta in Settings::SETTINGS_PROPS {
2540            let value = match meta.ty.inner() {
2541                Ty::Bool => toml::Value::Boolean(true),
2542                Ty::Int | Ty::Uint => toml::Value::Integer(1),
2543                _ => toml::Value::String("x".to_string()),
2544            };
2545            let parts: Vec<&str> = meta.key.split('.').collect();
2546            let mut table = toml::Table::new();
2547            let mut cursor = &mut table;
2548            for part in &parts[..parts.len() - 1] {
2549                cursor = cursor
2550                    .entry(part.to_string())
2551                    .or_insert_with(|| toml::Value::Table(toml::Table::new()))
2552                    .as_table_mut()
2553                    .unwrap();
2554            }
2555            cursor.insert(parts[parts.len() - 1].to_string(), value);
2556
2557            let partial: SettingsPartial = table.clone().try_into().unwrap();
2558            let back = toml::Table::try_from(&partial).unwrap();
2559            assert_eq!(
2560                back, table,
2561                "{} is declared in the registry but not mirrored in SettingsPartial",
2562                meta.key
2563            );
2564        }
2565    }
2566
2567    #[test]
2568    fn test_parse_duration() {
2569        assert_eq!(Settings::parse_duration("1s"), Some(Duration::from_secs(1)));
2570        assert_eq!(
2571            Settings::parse_duration("500ms"),
2572            Some(Duration::from_millis(500))
2573        );
2574        assert_eq!(
2575            Settings::parse_duration("1m"),
2576            Some(Duration::from_secs(60))
2577        );
2578        assert_eq!(
2579            Settings::parse_duration("2h"),
2580            Some(Duration::from_secs(7200))
2581        );
2582        assert_eq!(Settings::parse_duration("invalid"), None);
2583    }
2584
2585    #[test]
2586    fn test_env_override() {
2587        // The environment is described rather than reached for, so this test
2588        // does not mutate process env vars (the old test needed a mutex).
2589        let env = EnvLayer::new([
2590            ("PITCHFORK_AUTOSTOP_DELAY".to_string(), "10m".to_string()),
2591            ("PITCHFORK_INTERVAL".to_string(), "5s".to_string()),
2592            (
2593                "PITCHFORK_IPC_CONNECT_ATTEMPTS".to_string(),
2594                "20".to_string(),
2595            ),
2596            (
2597                "PITCHFORK_SUPERVISOR_AUTO_START".to_string(),
2598                "false".to_string(),
2599            ),
2600            ("PITCHFORK_WEB_AUTO_START".to_string(), "true".to_string()),
2601        ]);
2602        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2603        let settings = Settings::read(&resolved).unwrap();
2604
2605        assert_eq!(settings.general.autostop_delay, "10m");
2606        assert_eq!(settings.general.interval, "5s");
2607        assert_eq!(settings.ipc.connect_attempts, 20);
2608        assert!(!settings.supervisor.auto_start);
2609        assert!(settings.web.auto_start);
2610
2611        // Fields with no corresponding env var set remain at defaults
2612        assert_eq!(settings.general.log_level, "info");
2613        assert_eq!(settings.ipc.rate_limit, 100);
2614    }
2615
2616    #[test]
2617    fn test_deprecated_env_still_works_and_warns() {
2618        let env = EnvLayer::new([
2619            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
2620            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
2621        ]);
2622        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2623        let settings = Settings::read(&resolved).unwrap();
2624        assert_eq!(settings.general.interval, "30s");
2625        assert!(!settings.general.worktree);
2626        let warnings = usage_rs::config::explain::warnings(&resolved);
2627        assert!(
2628            warnings
2629                .iter()
2630                .any(|w| w.contains("PITCHFORK_INTERVAL_SECS is deprecated")),
2631            "{warnings:?}"
2632        );
2633        assert!(
2634            warnings
2635                .iter()
2636                .any(|w| w.contains("PITCHFORK_PROXY_WORKTREE is deprecated")),
2637            "{warnings:?}"
2638        );
2639
2640        // The current name wins over the deprecated alias when both are set.
2641        let env = EnvLayer::new([
2642            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
2643            ("PITCHFORK_INTERVAL".to_string(), "7s".to_string()),
2644            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
2645            ("PITCHFORK_WORKTREE".to_string(), "true".to_string()),
2646        ]);
2647        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2648        let settings = Settings::read(&resolved).unwrap();
2649        assert_eq!(settings.general.interval, "7s");
2650        assert!(settings.general.worktree);
2651    }
2652
2653    #[test]
2654    fn test_invalid_duration_from_env_falls_back_to_default() {
2655        // The previous loader rejected invalid durations at load time; the
2656        // sanitize pass reproduces that through Resolved::coerced.
2657        let env = EnvLayer::new([(
2658            "PITCHFORK_AUTOSTOP_DELAY".to_string(),
2659            "not_a_duration".to_string(),
2660        )]);
2661        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2662        sanitize_durations(&mut resolved);
2663        let settings = Settings::read(&resolved).unwrap();
2664        assert_eq!(settings.general.autostop_delay, "1m");
2665        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2666    }
2667
2668    #[test]
2669    fn test_zero_health_timeout_from_env_falls_back_to_default() {
2670        // A zero health probe timeout goes straight into tokio::time::timeout
2671        // and fails every probe immediately; the sanitize pass falls back to
2672        // the schema default like any other invalid duration.
2673        let env = EnvLayer::new([
2674            ("PITCHFORK_HEALTH_CMD_TIMEOUT".to_string(), "0s".to_string()),
2675            (
2676                "PITCHFORK_HEALTH_HTTP_TIMEOUT".to_string(),
2677                "0s".to_string(),
2678            ),
2679            (
2680                "PITCHFORK_HEALTH_PORT_TIMEOUT".to_string(),
2681                "0s".to_string(),
2682            ),
2683        ]);
2684        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2685        sanitize_durations(&mut resolved);
2686        let settings = Settings::read(&resolved).unwrap();
2687        assert_eq!(settings.supervisor.health_cmd_timeout, "10s");
2688        assert_eq!(
2689            settings.supervisor_health_cmd_timeout(),
2690            Duration::from_secs(10)
2691        );
2692        assert_eq!(settings.supervisor.health_http_timeout, "5s");
2693        assert_eq!(settings.supervisor.health_port_timeout, "5s");
2694    }
2695
2696    #[test]
2697    fn test_invalid_duration_fallback() {
2698        let mut settings = Settings::default();
2699
2700        // Set invalid duration values
2701        settings.general.autostop_delay = "invalid".to_string();
2702        settings.general.interval = "not_a_duration".to_string();
2703
2704        // Convenience methods should fallback to default values
2705        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60)); // default "1m"
2706        assert_eq!(settings.general_interval(), Duration::from_secs(10)); // default "10s"
2707    }
2708
2709    #[test]
2710    fn oneshot_wait_defaults_to_an_hour() {
2711        use crate::config_types::OneshotWait;
2712        let settings = Settings::default();
2713        assert_eq!(
2714            settings.supervisor_oneshot_timeout(),
2715            Duration::from_secs(3600)
2716        );
2717        assert_eq!(
2718            settings.supervisor_oneshot_wait(),
2719            OneshotWait::For(Duration::from_secs(3600))
2720        );
2721    }
2722
2723    #[test]
2724    fn oneshot_wait_of_zero_means_no_deadline_at_all() {
2725        // A task's natural end is its exit, so `0` has to read as "wait",
2726        // never as "give up immediately" — and never as a distant substitute
2727        // deadline that a long enough task could still outlive.
2728        use crate::config_types::OneshotWait;
2729        let mut settings = Settings::default();
2730        for value in ["0", "0s"] {
2731            settings.supervisor.oneshot_timeout = value.to_string();
2732            assert!(settings.supervisor_oneshot_timeout().is_zero());
2733            assert_eq!(
2734                settings.supervisor_oneshot_wait(),
2735                OneshotWait::Unlimited,
2736                "{value} should wait without a deadline"
2737            );
2738            assert_eq!(settings.supervisor_oneshot_wait().duration(), None);
2739        }
2740    }
2741
2742    #[test]
2743    fn oneshot_wait_honours_a_configured_value() {
2744        use crate::config_types::OneshotWait;
2745        let mut settings = Settings::default();
2746        settings.supervisor.oneshot_timeout = "6h".to_string();
2747        assert_eq!(
2748            settings.supervisor_oneshot_wait(),
2749            OneshotWait::For(Duration::from_secs(6 * 3600))
2750        );
2751        assert_eq!(
2752            settings.supervisor_oneshot_wait().duration(),
2753            Some(Duration::from_secs(6 * 3600))
2754        );
2755    }
2756
2757    #[test]
2758    fn test_duration_methods_all_fields() {
2759        let settings = Settings::default();
2760
2761        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2762        assert_eq!(settings.general_interval(), Duration::from_secs(10));
2763        assert_eq!(settings.general_ready_delay(), Duration::from_secs(3));
2764        assert_eq!(settings.ipc_connect_min_delay(), Duration::from_millis(100));
2765        assert_eq!(settings.ipc_connect_max_delay(), Duration::from_secs(1));
2766        assert_eq!(settings.ipc_request_timeout(), Duration::from_secs(5));
2767        assert_eq!(settings.ipc_rate_limit_window(), Duration::from_secs(1));
2768        assert_eq!(settings.web_sse_poll_interval(), Duration::from_millis(500));
2769        assert_eq!(settings.tui_refresh_rate(), Duration::from_secs(2));
2770        assert_eq!(settings.tui_tick_rate(), Duration::from_millis(100));
2771        assert_eq!(settings.tui_message_duration(), Duration::from_secs(3));
2772        assert_eq!(
2773            settings.supervisor_ready_check_interval(),
2774            Duration::from_millis(500)
2775        );
2776        assert_eq!(
2777            settings.supervisor_file_watch_debounce(),
2778            Duration::from_secs(1)
2779        );
2780        assert_eq!(
2781            settings.supervisor_log_flush_interval(),
2782            Duration::from_millis(500)
2783        );
2784        assert_eq!(settings.supervisor_stop_timeout(), Duration::from_secs(5));
2785        assert_eq!(
2786            settings.supervisor_restart_delay(),
2787            Duration::from_millis(100)
2788        );
2789        assert_eq!(
2790            settings.supervisor_cron_check_interval(),
2791            Duration::from_secs(10)
2792        );
2793        assert_eq!(
2794            settings.supervisor_http_client_timeout(),
2795            Duration::from_secs(5)
2796        );
2797    }
2798
2799    #[test]
2800    fn test_general_ready_delay_secs() {
2801        let mut settings = Settings::default();
2802
2803        // Default "3s" resolves to whole seconds.
2804        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2805
2806        // Subsecond values are rejected, not silently truncated by as_secs().
2807        settings.general.ready_delay = "500ms".to_string();
2808        let err = settings.general_ready_delay_secs().unwrap_err();
2809        assert!(err.contains("500ms"), "unexpected error: {err}");
2810        assert!(
2811            err.contains("whole number of seconds"),
2812            "unexpected error: {err}"
2813        );
2814
2815        settings.general.ready_delay = "1.5s".to_string();
2816        let err = settings.general_ready_delay_secs().unwrap_err();
2817        assert!(err.contains("1.5s"), "unexpected error: {err}");
2818
2819        // Empty string falls back to the schema default "3s".
2820        settings.general.ready_delay = String::new();
2821        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2822
2823        // Whole-second values resolve as seconds.
2824        settings.general.ready_delay = "90s".to_string();
2825        assert_eq!(settings.general_ready_delay_secs(), Ok(90));
2826    }
2827
2828    /// A directory tree, cleaned up when the test ends.
2829    struct Tree(std::path::PathBuf);
2830
2831    impl Tree {
2832        fn new(name: &str) -> Self {
2833            let dir = std::env::temp_dir()
2834                .join(format!("pitchfork_settings_{}_{name}", std::process::id()));
2835            let _ = std::fs::remove_dir_all(&dir);
2836            std::fs::create_dir_all(&dir).unwrap();
2837            Self(dir)
2838        }
2839
2840        fn write(&self, rel: &str, text: &str) -> std::path::PathBuf {
2841            let path = self.0.join(rel);
2842            if let Some(parent) = path.parent() {
2843                std::fs::create_dir_all(parent).unwrap();
2844            }
2845            std::fs::write(&path, text).unwrap();
2846            path
2847        }
2848    }
2849
2850    impl Drop for Tree {
2851        fn drop(&mut self) {
2852            let _ = std::fs::remove_dir_all(&self.0);
2853        }
2854    }
2855
2856    #[test]
2857    fn test_settings_read_from_pitchfork_toml_settings_table() {
2858        let tree = Tree::new("table");
2859        let path = tree.write(
2860            "pitchfork.toml",
2861            r#"
2862[daemons.myapp]
2863run = "node server.js"
2864
2865[settings.general]
2866autostop_delay = "5m"
2867log_level = "debug"
2868
2869[settings.web]
2870auto_start = true
2871bind_port = 8080
2872
2873[settings.supervisor]
2874auto_start = false
2875user = "postgres"
2876"#,
2877        );
2878        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2879        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2880        let settings = Settings::read(&resolved).unwrap();
2881
2882        assert_eq!(settings.general.autostop_delay, "5m");
2883        assert_eq!(settings.general.log_level, "debug");
2884        assert!(settings.web.auto_start);
2885        assert_eq!(settings.web.bind_port, 8080);
2886        assert!(!settings.supervisor.auto_start);
2887        assert_eq!(settings.supervisor.user, "postgres");
2888        // Unset fields fall back to defaults, and [daemons] is not a warning.
2889        assert_eq!(settings.general.interval, "10s");
2890        assert_eq!(settings.ipc.connect_attempts, 5);
2891        assert!(resolved.warnings.is_empty(), "{:?}", resolved.warnings);
2892    }
2893
2894    #[test]
2895    fn test_proxy_worktree_config_alias_still_works() {
2896        let tree = Tree::new("proxy_worktree_alias");
2897        let path = tree.write("pitchfork.toml", "[settings.proxy]\nworktree = false\n");
2898        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2899        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2900        let settings = Settings::read(&resolved).unwrap();
2901
2902        assert!(!settings.general.worktree);
2903        assert_eq!(
2904            resolved.get(
2905                Settings::SETTINGS_REGISTRY
2906                    .lookup("general.worktree")
2907                    .unwrap()
2908                    .id
2909            ),
2910            Some(&Value::Bool(false)),
2911        );
2912    }
2913
2914    #[test]
2915    fn test_explicit_default_value_in_higher_file_still_overrides() {
2916        // "Bug 5": the old merge_from skipped values equal to the default, so
2917        // a higher-precedence file explicitly setting log_level = "info"
2918        // could not override "warn" from a lower one. usage-config's
2919        // origin-tracked merge does this natively; pin it.
2920        let tree = Tree::new("bug5");
2921        let lower = tree.write("lower.toml", "[settings.general]\nlog_level = \"warn\"\n");
2922        let higher = tree.write("higher.toml", "[settings.general]\nlog_level = \"info\"\n");
2923        let lower = FileLayer::at(&lower, FileScope::Global).under("settings");
2924        let higher = FileLayer::at(&higher, FileScope::Project).under("settings");
2925        let resolved = resolve(
2926            Settings::SETTINGS_REGISTRY,
2927            Layers::new().then(&higher).then(&lower),
2928        )
2929        .unwrap();
2930        let settings = Settings::read(&resolved).unwrap();
2931        assert_eq!(settings.general.log_level, "info");
2932
2933        // And the provenance says the higher file set it, not the default.
2934        let id = Settings::SETTINGS_REGISTRY
2935            .lookup("general.log_level")
2936            .unwrap()
2937            .id;
2938        let origin = resolved.origin(id).unwrap().describe();
2939        assert!(origin.contains("higher.toml"), "{origin}");
2940    }
2941
2942    #[test]
2943    fn boot_executable_rejects_project_config() {
2944        let tree = Tree::new("boot-scope");
2945        let project = tree.write(
2946            "pitchfork.toml",
2947            "[settings.boot]\nexecutable = \"/tmp/project/pitchfork\"\n",
2948        );
2949        let global = tree.write(
2950            "config.toml",
2951            "[settings.boot]\nexecutable = \"/opt/pitchfork/stable\"\n",
2952        );
2953        let project = FileLayer::at(&project, FileScope::Project).under("settings");
2954        let global = FileLayer::at(&global, FileScope::Global).under("settings");
2955
2956        let resolved = resolve(
2957            Settings::SETTINGS_REGISTRY,
2958            Layers::new().then(&project).then(&global),
2959        )
2960        .unwrap();
2961        assert_eq!(
2962            Settings::read(&resolved).unwrap().boot.executable,
2963            "/opt/pitchfork/stable"
2964        );
2965        assert!(resolved.warnings.iter().any(|warning| {
2966            warning.message.contains("boot.executable") && warning.message.contains("cannot be set")
2967        }));
2968
2969        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&project)).unwrap();
2970        assert!(
2971            Settings::read(&resolved)
2972                .unwrap()
2973                .boot
2974                .executable
2975                .is_empty()
2976        );
2977    }
2978
2979    #[test]
2980    fn test_file_precedence_local_over_base_and_nearer_dir_wins() {
2981        let tree = Tree::new("precedence");
2982        tree.write("pitchfork.toml", "[settings.general]\ninterval = \"9s\"\n");
2983        tree.write(
2984            "pitchfork.local.toml",
2985            "[settings.general]\ninterval = \"2s\"\n",
2986        );
2987        tree.write(
2988            ".config/pitchfork.toml",
2989            "[settings.general]\ninterval = \"7s\"\n[settings.web]\nbind_port = 9999\n",
2990        );
2991        let layers = Settings::file_layers_from(&tree.0);
2992        let mut chain = Layers::new();
2993        for layer in &layers {
2994            chain = chain.then(layer);
2995        }
2996        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
2997        let settings = Settings::read(&resolved).unwrap();
2998        // pitchfork.local.toml > pitchfork.toml > .config/pitchfork.toml
2999        assert_eq!(settings.general.interval, "2s");
3000        // A key only the lowest file sets still applies.
3001        assert_eq!(settings.web.bind_port, 9999);
3002
3003        // A nested directory's file outranks everything above it.
3004        let deep = tree.0.join("a").join("b");
3005        std::fs::create_dir_all(&deep).unwrap();
3006        tree.write(
3007            "a/b/pitchfork.toml",
3008            "[settings.general]\ninterval = \"1s\"\n",
3009        );
3010        let layers = Settings::file_layers_from(&deep);
3011        let mut chain = Layers::new();
3012        for layer in &layers {
3013            chain = chain.then(layer);
3014        }
3015        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
3016        let settings = Settings::read(&resolved).unwrap();
3017        assert_eq!(settings.general.interval, "1s");
3018    }
3019
3020    #[test]
3021    fn test_broken_file_is_skipped_rather_than_fatal() {
3022        let tree = Tree::new("broken");
3023        let broken = tree.write("pitchfork.toml", "[invalid toml [[");
3024        // The broken file is skipped with a warning, so the resolution still
3025        // happens and produces the defaults.
3026        let layers = Settings::file_layers_from(&tree.0);
3027        assert!(
3028            layers.iter().all(|layer| !layer.paths().contains(&broken)),
3029            "the broken project file must not become a settings layer"
3030        );
3031    }
3032
3033    #[test]
3034    fn test_unknown_settings_keys_do_not_fail_the_load() {
3035        // Forward compatibility: a config written for a newer pitchfork must
3036        // still load. Unknown keys are warned about rather than fatal.
3037        let tree = Tree::new("unknown");
3038        let path = tree.write(
3039            "pitchfork.toml",
3040            "[settings.general]\nlog_level = \"debug\"\nfrom_the_future = true\n",
3041        );
3042        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
3043        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
3044        let settings = Settings::read(&resolved).unwrap();
3045        assert_eq!(settings.general.log_level, "debug");
3046        assert_eq!(resolved.warnings.len(), 1, "{:?}", resolved.warnings);
3047    }
3048
3049    #[test]
3050    fn test_partial_merge_from() {
3051        let mut base = SettingsPartial::default();
3052        base.general.log_level = Some("warn".to_string());
3053        base.web.bind_address = Some("0.0.0.0".to_string());
3054
3055        let mut overlay = SettingsPartial::default();
3056        overlay.general.log_level = Some("debug".to_string());
3057        overlay.tui.refresh_rate = Some("1s".to_string());
3058
3059        base.merge_from(&overlay);
3060        assert_eq!(base.general.log_level.as_deref(), Some("debug"));
3061        assert_eq!(base.web.bind_address.as_deref(), Some("0.0.0.0"));
3062        assert_eq!(base.tui.refresh_rate.as_deref(), Some("1s"));
3063
3064        // An empty partial changes nothing.
3065        let sealed = base.clone();
3066        base.merge_from(&SettingsPartial::default());
3067        assert_eq!(base.general.log_level, sealed.general.log_level);
3068        assert!(SettingsPartial::default().is_empty());
3069        assert!(base.has_any_set());
3070    }
3071
3072    #[test]
3073    fn test_partial_serialization_skips_unset() {
3074        let mut partial = SettingsPartial::default();
3075        partial.general.interval = Some("5s".to_string());
3076        let toml = toml::to_string_pretty(&partial).unwrap();
3077        assert_eq!(toml, "[general]\ninterval = \"5s\"\n");
3078    }
3079}