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
1112/// The `web.*` (web UI) settings.
1113#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1114#[usage(prefix = "web")]
1115pub struct SettingsWeb {
1116    /// Automatically start web UI when supervisor starts
1117    ///
1118    /// When enabled, the web UI server will automatically start alongside the supervisor.
1119    ///
1120    /// By default, this is disabled. You can also start the web UI manually with:
1121    /// ```text
1122    /// pitchfork supervisor start --web-port=3120
1123    /// ```
1124    #[usage(env = "PITCHFORK_WEB_AUTO_START", default = false)]
1125    pub auto_start: bool,
1126
1127    /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
1128    ///
1129    /// Serves the web UI under a sub-path prefix, useful when running behind a reverse
1130    /// proxy that routes a path prefix to pitchfork.
1131    ///
1132    /// **Examples:**
1133    /// - `""` - Serve at root `/` (default)
1134    /// - `"ps"` - Serve at `/ps/`
1135    /// - `"tools/pitchfork"` - Serve at `/tools/pitchfork/`
1136    ///
1137    /// Equivalent to the `--web-path` CLI flag. The CLI flag takes priority over this setting.
1138    #[usage(env = "PITCHFORK_WEB_PATH", default = "")]
1139    pub base_path: String,
1140
1141    /// Web server bind address
1142    ///
1143    /// IP address for the web UI to listen on.
1144    ///
1145    /// **Security Warning:** The default `127.0.0.1` only allows local connections.
1146    /// Setting this to `0.0.0.0` will expose the web UI to your network.
1147    ///
1148    /// **Examples:**
1149    /// - `"127.0.0.1"` - Local only (default, recommended)
1150    /// - `"0.0.0.0"` - All interfaces (use with caution)
1151    /// - `"192.168.1.100"` - Specific interface
1152    #[usage(env = "PITCHFORK_WEB_BIND_ADDRESS", default = "127.0.0.1")]
1153    pub bind_address: String,
1154
1155    /// Default web server port
1156    ///
1157    /// The port number for the web UI. If this port is in use, pitchfork will
1158    /// try subsequent ports up to `port_attempts` times.
1159    #[usage(env = "PITCHFORK_WEB_BIND_PORT", default = 3120)]
1160    pub bind_port: i64,
1161
1162    /// Initial number of log lines to display
1163    ///
1164    /// How many lines of logs to show initially when viewing daemon logs in the web UI.
1165    /// More lines means slower initial load but more history visible.
1166    #[usage(env = "PITCHFORK_WEB_LOG_LINES", default = 100)]
1167    pub log_lines: i64,
1168
1169    /// Number of ports to try if default is in use
1170    ///
1171    /// If the default port is occupied, pitchfork will try this many consecutive
1172    /// ports before giving up.
1173    ///
1174    /// For example, with `bind_port = 3120` and `port_attempts = 10`,
1175    /// it will try ports 3120, 3121, 3122, ... up to 3129.
1176    #[usage(env = "PITCHFORK_WEB_PORT_ATTEMPTS", default = 10)]
1177    pub port_attempts: i64,
1178
1179    /// Server-Sent Events poll interval for log streaming
1180    ///
1181    /// How often the web UI checks for new log lines when streaming logs.
1182    /// Lower values provide more real-time updates but use more resources.
1183    #[usage(
1184        env = "PITCHFORK_WEB_SSE_POLL_INTERVAL",
1185        default = "500ms",
1186        ty = "duration"
1187    )]
1188    pub sse_poll_interval: String,
1189}
1190
1191/// Every setting pitchfork has.
1192///
1193/// `SETTINGS_PROPS`, `SETTINGS_REGISTRY`, `read`, and `spec_kdl` are generated
1194/// from these fields; the CLI's emitted spec carries the `config` block
1195/// through `#[usage(config = ...)]` on the root.
1196#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1197// `file(...)` is intentionally repeatable in usage's configuration DSL.
1198#[allow(clippy::duplicated_attributes)]
1199#[usage(
1200    file(path = "/etc/pitchfork/config.toml", scope = "system", format = "toml"),
1201    file(
1202        path = "~/.config/pitchfork/config.toml",
1203        scope = "global",
1204        format = "toml"
1205    ),
1206    file(
1207        path = ".config/pitchfork.toml",
1208        findup,
1209        scope = "project",
1210        format = "toml"
1211    ),
1212    file(
1213        path = ".config/pitchfork.local.toml",
1214        findup,
1215        scope = "project",
1216        format = "toml"
1217    ),
1218    file(path = "pitchfork.toml", findup, scope = "project", format = "toml"),
1219    file(
1220        path = "pitchfork.local.toml",
1221        findup,
1222        scope = "project",
1223        format = "toml"
1224    )
1225)]
1226pub struct Settings {
1227    #[usage(flatten)]
1228    pub api: SettingsApi,
1229    #[usage(flatten)]
1230    pub boot: SettingsBoot,
1231    #[usage(flatten)]
1232    pub general: SettingsGeneral,
1233    #[usage(flatten)]
1234    pub ipc: SettingsIpc,
1235    #[usage(flatten)]
1236    pub logs: SettingsLogs,
1237    #[usage(flatten)]
1238    pub proxy: SettingsProxy,
1239    #[usage(flatten)]
1240    pub supervisor: SettingsSupervisor,
1241    #[usage(flatten)]
1242    pub tui: SettingsTui,
1243    #[usage(flatten)]
1244    pub web: SettingsWeb,
1245}
1246
1247impl Default for Settings {
1248    /// The declared defaults, read the same way any other resolution is.
1249    fn default() -> Self {
1250        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1251            .expect("no layers were given, so there is nothing to fail");
1252        Settings::read(&resolved).expect("every pitchfork setting has a declared default")
1253    }
1254}
1255
1256/// Generate the `Duration` convenience getters the rest of the codebase uses
1257/// (e.g. `settings().general_autostop_delay()`), each parsing its humantime
1258/// string field and silently falling back to the schema default. Invalid
1259/// values were already warned about once at load time.
1260macro_rules! duration_getters {
1261    ($($name:ident => $group:ident . $field:ident, $default:literal;)+) => {
1262        impl Settings {
1263            $(
1264                #[doc = concat!("Get `", stringify!($group), ".", stringify!($field), "` as Duration")]
1265                #[allow(dead_code)]
1266                pub fn $name(&self) -> std::time::Duration {
1267                    Self::parse_duration(&self.$group.$field).unwrap_or_else(|| {
1268                        humantime::parse_duration($default)
1269                            .unwrap_or(std::time::Duration::from_secs(1))
1270                    })
1271                }
1272            )+
1273        }
1274    };
1275}
1276
1277duration_getters! {
1278    general_autostop_delay => general.autostop_delay, "1m";
1279    general_interval => general.interval, "10s";
1280    general_ready_delay => general.ready_delay, "3s";
1281    ipc_connect_max_delay => ipc.connect_max_delay, "1s";
1282    ipc_connect_min_delay => ipc.connect_min_delay, "100ms";
1283    ipc_rate_limit_window => ipc.rate_limit_window, "1s";
1284    ipc_request_timeout => ipc.request_timeout, "5s";
1285    logs_time_retention => logs.time_retention, "";
1286    proxy_auto_start_timeout => proxy.auto_start_timeout, "30s";
1287    supervisor_cron_check_interval => supervisor.cron_check_interval, "10s";
1288    supervisor_file_watch_debounce => supervisor.file_watch_debounce, "1s";
1289    supervisor_health_check_interval => supervisor.health_check_interval, "10s";
1290    supervisor_health_cmd_timeout => supervisor.health_cmd_timeout, "10s";
1291    supervisor_health_http_timeout => supervisor.health_http_timeout, "5s";
1292    supervisor_health_port_timeout => supervisor.health_port_timeout, "5s";
1293    supervisor_http_client_timeout => supervisor.http_client_timeout, "5s";
1294    supervisor_log_flush_interval => supervisor.log_flush_interval, "500ms";
1295    supervisor_oneshot_timeout => supervisor.oneshot_timeout, "1h";
1296    supervisor_ready_check_interval => supervisor.ready_check_interval, "500ms";
1297    supervisor_restart_delay => supervisor.restart_delay, "100ms";
1298    supervisor_stop_timeout => supervisor.stop_timeout, "5s";
1299    supervisor_watch_interval => supervisor.watch_interval, "10s";
1300    supervisor_watch_poll_interval => supervisor.watch_poll_interval, "500ms";
1301    tui_message_duration => tui.message_duration, "3s";
1302    tui_refresh_rate => tui.refresh_rate, "2s";
1303    tui_tick_rate => tui.tick_rate, "100ms";
1304    web_sse_poll_interval => web.sse_poll_interval, "500ms";
1305}
1306
1307impl Settings {
1308    /// How long to wait for a `oneshot` daemon to finish.
1309    ///
1310    /// `supervisor.oneshot_timeout = "0"` means no limit: a task's natural end
1311    /// is its exit, and a long migration should not be called failed merely for
1312    /// outlasting a default. That is an absent deadline, not a very large one,
1313    /// so no task can outlive the substitute and be reported as timed out
1314    /// despite the setting promising otherwise.
1315    pub fn supervisor_oneshot_wait(&self) -> crate::config_types::OneshotWait {
1316        let configured = self.supervisor_oneshot_timeout();
1317        if configured.is_zero() {
1318            crate::config_types::OneshotWait::Unlimited
1319        } else {
1320            crate::config_types::OneshotWait::For(configured)
1321        }
1322    }
1323
1324    /// `proxy.idle_timeout` as a grace period, or `None` when idle shutdown
1325    /// is off (empty, zero, or invalid — invalid values were already warned
1326    /// about at load time).
1327    pub fn proxy_idle_timeout(&self) -> Option<std::time::Duration> {
1328        Self::parse_duration(self.proxy.idle_timeout.trim()).filter(|d| !d.is_zero())
1329    }
1330
1331    /// Resolve `general.ready_delay` as whole seconds.
1332    ///
1333    /// The ready-check pipeline (RunOptions/IPC/supervisor) models the delay
1334    /// in whole seconds. Reject subsecond values that would otherwise be
1335    /// silently truncated to a zero delay by `as_secs()`.
1336    pub fn general_ready_delay_secs(&self) -> Result<u64, String> {
1337        let delay = self.general_ready_delay();
1338        if delay.subsec_nanos() != 0 {
1339            return Err(format!(
1340                "settings.general.ready_delay must be a whole number of seconds, got \"{}\"",
1341                self.general.ready_delay
1342            ));
1343        }
1344        Ok(delay.as_secs())
1345    }
1346}
1347
1348impl Settings {
1349    /// Load settings from pitchfork.toml files, then overlay environment variables.
1350    /// Settings are loaded from all pitchfork.toml files in precedence order:
1351    /// 1. System-level: /etc/pitchfork/config.toml
1352    /// 2. User-level: ~/.config/pitchfork/config.toml
1353    /// 3. Project-level: pitchfork.toml files from root to current directory
1354    ///
1355    /// Environment variables override all file-based settings.
1356    ///
1357    /// The global [`settings()`] accessor resolves through
1358    /// [`Settings::resolve_from_dir`] so it can keep the provenance; this
1359    /// stays as the public one-shot entry point.
1360    #[allow(dead_code)]
1361    pub fn load() -> Self {
1362        Self::load_from_dir(&crate::env::CWD)
1363    }
1364
1365    /// Load settings for a specific project directory, then overlay environment variables.
1366    ///
1367    /// This is used when operating on daemons from registered namespaces whose project
1368    /// settings may differ from those of the invoking process's current directory.
1369    pub fn load_from_dir(start_dir: &Path) -> Self {
1370        Self::resolve_from_dir(start_dir).0
1371    }
1372
1373    /// Resolve settings for `start_dir`, returning both the typed struct and
1374    /// the origin-tracked resolution it was read from (for `pitchfork settings`).
1375    pub(crate) fn resolve_from_dir(start_dir: &Path) -> (Self, Resolved) {
1376        let env_layer = EnvLayer::from_process();
1377        // Highest precedence first, below the environment.
1378        let file_layers = Self::file_layers_from(start_dir);
1379        let mut layers = Layers::new().then(&env_layer);
1380        for layer in &file_layers {
1381            layers = layers.then(layer);
1382        }
1383        let mut resolved = match resolve(Settings::SETTINGS_REGISTRY, layers) {
1384            Ok(resolved) => resolved,
1385            Err(e) => {
1386                // Should not happen: every file was pre-validated above. Fall
1387                // back to env + defaults rather than failing to start.
1388                eprintln!("pitchfork: warning: failed to resolve settings from config files: {e}");
1389                resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env_layer)).unwrap_or_else(
1390                    |_| {
1391                        resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1392                            .expect("resolving only defaults cannot fail")
1393                    },
1394                )
1395            }
1396        };
1397        sanitize_durations(&mut resolved);
1398        for warning in usage_rs::config::explain::warnings(&resolved) {
1399            warn!("{warning}");
1400        }
1401        // Lossy, because the alternative is worse than the problem: `read` is all or nothing,
1402        // so one field the merge could not hand to its type used to cost every *other* setting
1403        // too — `Settings::default()` throws away the environment and every config file over a
1404        // single bad value. Here the offending field falls back to its own declared default and
1405        // nothing else is touched. Warn and keep going is pitchfork's call to make: a
1406        // supervisor that refuses to start because one duration is misspelled is a supervisor
1407        // that took the whole machine's daemons down with it.
1408        let (settings, errors) = Settings::read_lossy(&resolved);
1409        for error in &errors.0 {
1410            warn!("{error}");
1411        }
1412        // Every setting declares a default, so the only way this is `None` is a setting added
1413        // without one — a hole in the declaration rather than anything a user did.
1414        let settings = settings.unwrap_or_else(|| {
1415            warn!("a setting has no value and no default; falling back to built-in defaults");
1416            Settings::default()
1417        });
1418        (settings, resolved)
1419    }
1420
1421    /// The config file layers for `start_dir`, highest precedence first.
1422    ///
1423    /// Project files are found by walking up from `start_dir`; within one
1424    /// directory `pitchfork.local.toml` outranks `pitchfork.toml`, which
1425    /// outranks the same pair under `.config/`, and any file in a nearer
1426    /// directory outranks every file in a farther one. Below the project
1427    /// files come the user-level and system-level configs.
1428    ///
1429    /// Files that exist but cannot be parsed are warned about and skipped,
1430    /// matching the previous loader: a broken file must not stop pitchfork
1431    /// from starting.
1432    fn file_layers_from(start_dir: &Path) -> Vec<FileLayer> {
1433        let mut candidates: Vec<(PathBuf, FileScope)> = xx::file::find_up_all(
1434            start_dir,
1435            &[
1436                "pitchfork.local.toml",
1437                "pitchfork.toml",
1438                ".config/pitchfork.local.toml",
1439                ".config/pitchfork.toml",
1440            ],
1441        )
1442        .into_iter()
1443        .map(|path| (path, FileScope::Project))
1444        .collect();
1445        let extras = crate::extra_configs::paths_for(start_dir)
1446            .into_iter()
1447            .rev()
1448            .map(|p| (p, FileScope::Project));
1449        candidates.splice(0..0, extras);
1450        candidates.push((
1451            crate::env::PITCHFORK_GLOBAL_CONFIG_USER.clone(),
1452            FileScope::Global,
1453        ));
1454        candidates.push((
1455            crate::env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone(),
1456            FileScope::System,
1457        ));
1458        candidates
1459            .into_iter()
1460            .filter(|(path, _)| readable_settings_file(path))
1461            .map(|(path, scope)| FileLayer::at(path, scope).under("settings"))
1462            .collect()
1463    }
1464
1465    /// Parse a duration string (humantime format) to Duration
1466    pub fn parse_duration(s: &str) -> Option<std::time::Duration> {
1467        humantime::parse_duration(s).ok()
1468    }
1469
1470    /// Resolve the mise binary path.
1471    ///
1472    /// If `general.mise_bin` is explicitly set, returns that path.
1473    /// Otherwise, searches well-known install locations:
1474    /// - `~/.local/bin/mise`
1475    /// - `~/.cargo/bin/mise`
1476    /// - `/usr/local/bin/mise`
1477    /// - `/opt/homebrew/bin/mise`
1478    /// - on Windows, `mise.exe` on `PATH`
1479    ///
1480    /// Returns `None` if mise cannot be found.
1481    pub fn resolve_mise_bin(&self) -> Option<std::path::PathBuf> {
1482        self.resolve_mise_bin_with_path(std::env::var_os("PATH").as_deref())
1483    }
1484
1485    /// The `general.mise_bin` a daemon's project sets, from the resolution
1486    /// these settings were read with, without checking or searching. The
1487    /// supervisor, whose own settings do not see the project's, prefers it;
1488    /// see [`Self::resolve_daemon_mise_bin`].
1489    ///
1490    /// Only a value from one of the project's files, with a relative path
1491    /// taken from `project_dir`, or from the environment counts. One from the
1492    /// user's or the system's configuration is no more the project's than the
1493    /// supervisor's, which applies it itself, so it gives `None`, as no value
1494    /// does.
1495    pub(crate) fn project_mise_bin(
1496        &self,
1497        resolved: &Resolved,
1498        project_dir: &Path,
1499    ) -> Option<PathBuf> {
1500        if self.general.mise_bin.is_empty() {
1501            return None;
1502        }
1503        let origin = resolved.origin_key("general.mise_bin")?;
1504        project_mise_bin_from(&self.general.mise_bin, origin, project_dir)
1505    }
1506
1507    /// Resolve the mise binary for a daemon, preferring `project_mise_bin`.
1508    ///
1509    /// `project_mise_bin` is the `general.mise_bin` of the daemon's project,
1510    /// which the client reads because these settings are the supervisor's
1511    /// own and do not see the project's. Without it, falls back to
1512    /// [`Self::resolve_mise_bin`].
1513    pub fn resolve_daemon_mise_bin(
1514        &self,
1515        project_mise_bin: Option<&std::path::Path>,
1516    ) -> Option<std::path::PathBuf> {
1517        match project_mise_bin {
1518            Some(p) => configured_mise_bin(p),
1519            None => self.resolve_mise_bin(),
1520        }
1521    }
1522
1523    /// [`Self::resolve_mise_bin`] with `path` in place of the `PATH` variable.
1524    fn resolve_mise_bin_with_path(
1525        &self,
1526        path: Option<&std::ffi::OsStr>,
1527    ) -> Option<std::path::PathBuf> {
1528        // Explicit configuration takes priority
1529        if !self.general.mise_bin.is_empty() {
1530            return configured_mise_bin(Path::new(&self.general.mise_bin));
1531        }
1532
1533        // Search well-known install paths
1534        let home = crate::env::HOME_DIR.as_path();
1535        let candidates = [
1536            home.join(".local/bin/mise"),
1537            home.join(".cargo/bin/mise"),
1538            PathBuf::from("/usr/local/bin/mise"),
1539            PathBuf::from("/opt/homebrew/bin/mise"),
1540        ];
1541
1542        candidates.into_iter().find(|p| p.is_file()).or_else(|| {
1543            // Windows package managers install mise to locations of their
1544            // own, none of them above, so look for it on PATH instead.
1545            if cfg!(windows) {
1546                find_in_path("mise.exe", path)
1547            } else {
1548                None
1549            }
1550        })
1551    }
1552
1553    /// Resolve the shell used for daemon `run` scripts, `ready_cmd` /
1554    /// `health_cmd` probes, lifecycle hooks and the log archive hook, split
1555    /// into a program and its arguments.
1556    ///
1557    /// `general.shell` applies everywhere. On Windows it applies only when it
1558    /// was set explicitly (`shell_is_explicit`); a Windows machine that leaves
1559    /// it at its default uses `general.windows_shell` instead, because the
1560    /// `sh` that `general.shell` defaults to is not on a stock Windows `PATH`.
1561    /// [`crate::settings::resolve_shell`] supplies that flag from the origin
1562    /// of the merged value; it is a parameter here so the precedence can be
1563    /// tested without a resolution.
1564    ///
1565    /// `Err` names the key whose value is empty or could not be split.
1566    pub fn resolve_shell(&self, shell_is_explicit: bool) -> Result<Vec<String>, String> {
1567        let (key, configured) = if cfg!(windows) && !shell_is_explicit {
1568            ("general.windows_shell", &self.general.windows_shell)
1569        } else {
1570            ("general.shell", &self.general.shell)
1571        };
1572        match shell_words::split(configured) {
1573            Ok(parts) if !parts.is_empty() => Ok(parts),
1574            Ok(_) => Err(format!("{key} setting is empty")),
1575            Err(e) => Err(format!("failed to parse {key} setting {configured:?}: {e}")),
1576        }
1577    }
1578
1579    /// Return `supervisor.port_bump_attempts` as `u32`, clamping out-of-range
1580    /// values to the schema default (10) and zero to 1.
1581    ///
1582    /// This is the single source of truth for the fallback so that call-sites
1583    /// don't each duplicate the hardcoded `10`.
1584    pub fn default_port_bump_attempts(&self) -> u32 {
1585        let v = u32::try_from(self.supervisor.port_bump_attempts).unwrap_or_else(|_| {
1586            warn!(
1587                "supervisor.port_bump_attempts value {} is out of range (0-{}), clamping to 10",
1588                self.supervisor.port_bump_attempts,
1589                u32::MAX
1590            );
1591            10
1592        });
1593        if v == 0 {
1594            warn!("supervisor.port_bump_attempts is 0; defaulting to 1");
1595            1
1596        } else {
1597            v
1598        }
1599    }
1600}
1601
1602/// Whether `path` holds a settings file this loader can hand to a `FileLayer`.
1603///
1604/// Mirrors the previous loader's per-file error handling: a missing file is
1605/// the ordinary case, and a file that exists but cannot be read or parsed —
1606/// or whose `settings` key is not a table — is warned about and skipped
1607/// rather than turned into a startup failure.
1608fn readable_settings_file(path: &Path) -> bool {
1609    if !path.exists() {
1610        return false;
1611    }
1612    let content = match std::fs::read_to_string(path) {
1613        Ok(content) => content,
1614        Err(e) => {
1615            eprintln!(
1616                "pitchfork: warning: failed to read {}: {}",
1617                path.display(),
1618                e
1619            );
1620            return false;
1621        }
1622    };
1623    let table: toml::Table = match content.parse() {
1624        Ok(table) => table,
1625        Err(e) => {
1626            eprintln!(
1627                "pitchfork: warning: failed to parse {}: {}",
1628                path.display(),
1629                e
1630            );
1631            return false;
1632        }
1633    };
1634    match table.get("settings") {
1635        None => true,
1636        Some(toml::Value::Table(_)) => true,
1637        Some(_) => {
1638            eprintln!(
1639                "pitchfork: warning: invalid [settings] in {}: not a table",
1640                path.display()
1641            );
1642            false
1643        }
1644    }
1645}
1646
1647/// Validate every duration-typed setting in a resolution.
1648///
1649/// The registry's `duration` type stores the humantime text as-is, so an
1650/// invalid value would otherwise ride into the struct. This warns once and
1651/// rewrites the value to the schema default through [`Resolved::coerced`],
1652/// so `pitchfork settings get/list` and the typed getters all agree —
1653/// matching the previous loader, which rejected invalid durations at load
1654/// time. A value equal to the declared default is left alone (the
1655/// `logs.time_retention` default is the empty string, meaning "disabled").
1656/// Duration settings where `0s` is never meaningful: the value is passed
1657/// straight into `tokio::time::timeout` for a health probe, so a zero
1658/// timeout fails every probe immediately and would crash-kill a healthy
1659/// daemon after the retry threshold. Same defect family as the per-daemon
1660/// health timeout rejection in `config_types.rs` (`parse_positive_timeout`).
1661const NON_ZERO_DURATION_KEYS: &[&str] = &[
1662    "supervisor.health_cmd_timeout",
1663    "supervisor.health_http_timeout",
1664    "supervisor.health_port_timeout",
1665];
1666
1667fn sanitize_durations(resolved: &mut Resolved) {
1668    let registry = Settings::SETTINGS_REGISTRY;
1669    for id in registry.ids() {
1670        let meta = registry.get(id);
1671        if !matches!(meta.ty.inner(), Ty::Duration) {
1672            continue;
1673        }
1674        let Some(Value::String(text)) = resolved.get(id) else {
1675            continue;
1676        };
1677        let default_text = match meta.default {
1678            Some(Const::Str(s)) => s,
1679            _ => "",
1680        };
1681        if text == default_text {
1682            continue;
1683        }
1684        let reason = match humantime::parse_duration(text) {
1685            Err(_) => Some(format!("invalid duration {text:?}")),
1686            Ok(d) if d.is_zero() && NON_ZERO_DURATION_KEYS.contains(&meta.key) => Some(format!(
1687                "supervisor health probe timeout must be greater than 0, got {text:?}"
1688            )),
1689            Ok(_) => None,
1690        };
1691        let Some(reason) = reason else {
1692            continue;
1693        };
1694        let origin = resolved
1695            .origin(id)
1696            .map(|o| o.describe().to_string())
1697            .unwrap_or_default();
1698        warn!("{reason} (set by {origin}), using default");
1699        resolved.coerced(
1700            id,
1701            Value::String(default_text.to_string()),
1702            format!("{reason}; the default stands"),
1703        );
1704    }
1705}
1706
1707/// Global settings instance, kept beside the resolution it was read from
1708/// (RwLock<Arc> to support runtime reload).
1709type SettingsState = (Arc<Settings>, Arc<Resolved>);
1710static SETTINGS: std::sync::RwLock<Option<SettingsState>> = std::sync::RwLock::new(None);
1711
1712fn settings_state() -> SettingsState {
1713    // Fast path: if already initialized, clone the Arc pointers.
1714    {
1715        let lock = SETTINGS.read().unwrap();
1716        if let Some(state) = lock.as_ref() {
1717            return state.clone();
1718        }
1719    }
1720    // Slow path: initialize on first access
1721    let mut lock = SETTINGS.write().unwrap();
1722    if let Some(state) = lock.as_ref() {
1723        return state.clone();
1724    }
1725    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1726    let state = (Arc::new(settings), Arc::new(resolved));
1727    *lock = Some(state.clone());
1728    state
1729}
1730
1731/// Get the global settings instance
1732pub fn settings() -> Arc<Settings> {
1733    settings_state().0
1734}
1735
1736/// The origin-tracked resolution behind [`settings()`], for the settings CLI.
1737pub(crate) fn settings_resolved() -> Arc<Resolved> {
1738    settings_state().1
1739}
1740
1741/// Whether `general.shell` was set by the user rather than left at its default.
1742///
1743/// Asked of the merge, not of the text, the same way `pitchfork settings`
1744/// decides what to mark as default: `shell = "sh -c"` written in a config file
1745/// is the same string as the default, and only its origin tells them apart.
1746fn shell_is_explicit(resolved: &Resolved) -> bool {
1747    resolved
1748        .origin_key("general.shell")
1749        .is_some_and(|origin| origin.kind != SourceKind::DEFAULTS)
1750}
1751
1752/// `value` as the project's mise_bin, given where it was set: a project file
1753/// takes a relative path from `project_dir`, the environment from the working
1754/// directory of the command it was set for.
1755fn project_mise_bin_from(value: &str, origin: &Origin, project_dir: &Path) -> Option<PathBuf> {
1756    if origin.kind == SourceKind::ENV {
1757        return Some(std::path::absolute(value).unwrap_or_else(|_| PathBuf::from(value)));
1758    }
1759    (origin.kind == SourceKind::FILE && origin.trust == Trust::Project)
1760        .then(|| project_dir.join(value))
1761}
1762
1763/// An explicitly configured `mise_bin`, if the file exists, as an absolute
1764/// path. A missing file is warned about and gives `None`, not a search for
1765/// another mise.
1766///
1767/// A relative path is taken from this process's working directory, which is
1768/// where it is checked; the daemon it wraps runs in a directory of its own,
1769/// where the same relative path could name another file or none.
1770fn configured_mise_bin(path: &Path) -> Option<PathBuf> {
1771    let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
1772    if path.is_file() {
1773        return Some(path);
1774    }
1775    warn!("mise_bin is set to {path:?} but the file does not exist");
1776    None
1777}
1778
1779/// The file called `name` in the first directory of `path` (a `PATH`-style
1780/// list) that holds one, as an absolute path.
1781///
1782/// A relative entry is looked up from this process's working directory, but
1783/// the result is used from a daemon's, so it is made absolute here.
1784fn find_in_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
1785    std::env::split_paths(path?)
1786        .map(|dir| dir.join(name))
1787        .find(|candidate| candidate.is_file())
1788        .and_then(|found| std::path::absolute(found).ok())
1789}
1790
1791/// Resolve the shell for daemon `run` scripts, command probes and hooks from
1792/// the global settings. See [`Settings::resolve_shell`].
1793pub fn resolve_shell() -> Result<Vec<String>, String> {
1794    let (settings, resolved) = settings_state();
1795    settings.resolve_shell(shell_is_explicit(&resolved))
1796}
1797
1798/// Reload settings from config files.
1799///
1800/// Called when the supervisor receives a ReloadConfig IPC request,
1801/// typically after `pitchfork settings set` modifies a config file.
1802///
1803/// Old Arc references remain valid until all holders drop them,
1804/// so no use-after-free can occur.
1805pub fn reload_settings() {
1806    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1807    let mut lock = SETTINGS.write().unwrap();
1808    *lock = Some((Arc::new(settings), Arc::new(resolved)));
1809}
1810
1811// ============================================================================
1812// Partial (all-Option) mirror structs
1813//
1814// These exist for `pitchfork.toml` round-trips: `PitchforkToml` deserializes
1815// its `[settings]` table into `SettingsPartial`, merges per-file overrides,
1816// and serializes it back out (`pitchfork settings set`, `proxy add`, ...).
1817// Settings *resolution* no longer goes through these — usage-config's
1818// origin-tracked merge replaced the apply/merge chain.
1819// ============================================================================
1820
1821macro_rules! settings_partial {
1822    (
1823        $(#[$meta:meta])*
1824        $name:ident {
1825            $(@group $group_field:ident: $group_ty:ty,)*
1826            $($(#[$fdoc:meta])* $field:ident: $ty:ty,)*
1827        }
1828    ) => {
1829        $(#[$meta])*
1830        #[derive(
1831            Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
1832        )]
1833        #[serde(default)]
1834        pub struct $name {
1835            $(
1836                #[serde(default, skip_serializing_if = "is_empty_partial")]
1837                pub $group_field: $group_ty,
1838            )*
1839            $(
1840                $(#[$fdoc])*
1841                #[serde(skip_serializing_if = "Option::is_none", default)]
1842                pub $field: Option<$ty>,
1843            )*
1844        }
1845
1846        #[allow(dead_code)]
1847        impl $name {
1848            /// Whether any field (or nested group field) is set.
1849            pub fn has_any_set(&self) -> bool {
1850                false
1851                $(|| self.$group_field.has_any_set())*
1852                $(|| self.$field.is_some())*
1853            }
1854
1855            pub fn is_empty(&self) -> bool {
1856                !self.has_any_set()
1857            }
1858
1859            /// Merge another partial onto this one.
1860            /// All `Some` values in `other` override the corresponding values in `self`.
1861            pub fn merge_from(&mut self, other: &Self) {
1862                $(self.$group_field.merge_from(&other.$group_field);)*
1863                $(
1864                    if other.$field.is_some() {
1865                        self.$field = other.$field.clone();
1866                    }
1867                )*
1868            }
1869        }
1870    };
1871}
1872
1873/// serde `skip_serializing_if` helper for nested partial groups.
1874fn is_empty_partial<T: HasAnySet>(v: &T) -> bool {
1875    !v.has_any_set()
1876}
1877
1878/// Internal trait so one serde skip helper serves every partial group.
1879trait HasAnySet {
1880    fn has_any_set(&self) -> bool;
1881}
1882
1883macro_rules! impl_has_any_set {
1884    ($($name:ident),+ $(,)?) => {
1885        $(impl HasAnySet for $name {
1886            fn has_any_set(&self) -> bool {
1887                $name::has_any_set(self)
1888            }
1889        })+
1890    };
1891}
1892
1893settings_partial! {
1894    /// Partial mirror of [`SettingsApi`].
1895    SettingsApiPartial {
1896        /// Automatically start the standalone API server
1897        auto_start: bool,
1898        /// IP address the API server binds to
1899        bind_address: String,
1900        /// Port the standalone API server listens on
1901        bind_port: i64,
1902        /// Number of consecutive ports to try if api.bind_port is in use
1903        port_attempts: i64,
1904        /// Authentication token for API access when bound to non-loopback addresses
1905        token: String,
1906    }
1907}
1908
1909settings_partial! {
1910    /// Partial mirror of [`SettingsBoot`].
1911    SettingsBootPartial {
1912        /// Absolute executable path written into boot registrations
1913        executable: String,
1914    }
1915}
1916
1917settings_partial! {
1918    /// Partial mirror of [`SettingsGeneral`].
1919    SettingsGeneralPartial {
1920        /// Delay before auto-stopping daemons when leaving a directory
1921        autostop_delay: String,
1922        /// Supervisor background task refresh interval
1923        interval: String,
1924        /// File log level (trace, debug, info, warn, error)
1925        log_file_level: String,
1926        /// Console log level (trace, debug, info, warn, error)
1927        log_level: String,
1928        /// Wrap daemon commands with mise x -- globally
1929        mise: bool,
1930        /// Explicit path to the mise binary
1931        mise_bin: String,
1932        /// Shell command used to execute daemon run scripts
1933        shell: String,
1934        /// Shell command used to execute daemon run scripts on Windows
1935        windows_shell: String,
1936        /// Show timestamps in startup log output
1937        startup_log_timestamps: bool,
1938        /// Default readiness delay in seconds when a daemon has no ready check configured
1939        ready_delay: String,
1940        /// Enable git worktree / jj workspace auto-discovery
1941        worktree: bool,
1942    }
1943}
1944
1945settings_partial! {
1946    /// Partial mirror of [`SettingsIpc`].
1947    SettingsIpcPartial {
1948        /// Number of connection retry attempts
1949        connect_attempts: i64,
1950        /// Maximum delay between connection retries
1951        connect_max_delay: String,
1952        /// Minimum delay between connection retries
1953        connect_min_delay: String,
1954        /// Maximum IPC requests per second per connection
1955        rate_limit: i64,
1956        /// Rate limit sliding window duration
1957        rate_limit_window: String,
1958        /// Default timeout for IPC requests
1959        request_timeout: String,
1960    }
1961}
1962
1963settings_partial! {
1964    /// Partial mirror of [`SettingsLogsArchiveHook`].
1965    SettingsLogsArchiveHookPartial {
1966        /// Maximum log entries per archive hook invocation
1967        batch_size: i64,
1968        /// Command to run before retention deletes old log entries
1969        command: String,
1970    }
1971}
1972
1973settings_partial! {
1974    /// Partial mirror of [`SettingsLogs`].
1975    SettingsLogsPartial {
1976        @group archive_hook: SettingsLogsArchiveHookPartial,
1977        /// Count-based log retention (e.g. 10000)
1978        line_retention: i64,
1979        /// Default log format for daemons (json | logfmt | text)
1980        log_format: String,
1981        /// Time-based log retention duration (e.g. '7d', '30d')
1982        time_retention: String,
1983        /// Show timestamps in log output
1984        timestamp: bool,
1985        /// strftime format for log timestamps in `pitchfork logs` output
1986        timestamp_format: String,
1987    }
1988}
1989
1990settings_partial! {
1991    /// Partial mirror of [`SettingsProxy`].
1992    SettingsProxyPartial {
1993        /// Automatically start daemons when accessed via proxy URL
1994        auto_start: bool,
1995        /// Maximum time to wait for an auto-started daemon to become ready
1996        auto_start_timeout: String,
1997        /// Automatically install the proxy TLS certificate into the system trust store
1998        auto_trust: bool,
1999        /// Run a loopback DNS resolver for the proxy TLD
2000        dns: bool,
2001        /// Port the loopback DNS resolver listens on
2002        dns_port: i64,
2003        /// Enable the reverse proxy server for daemons
2004        enable: bool,
2005        /// Bind address for the reverse proxy server
2006        host: String,
2007        /// Enable HTTPS for the reverse proxy
2008        https: bool,
2009        /// Stop proxy-started daemons after this long without proxy activity
2010        idle_timeout: String,
2011        /// Enable LAN mode for the reverse proxy
2012        lan: bool,
2013        /// Pin a specific LAN IP address instead of auto-detecting
2014        lan_ip: String,
2015        /// Port the reverse proxy server listens on
2016        port: i64,
2017        /// Automatically sync slug hostnames to /etc/hosts (deprecated)
2018        sync_hosts: bool,
2019        /// Top-level domain used for proxy URLs
2020        tld: String,
2021        /// Path to TLS certificate file (PEM format) for HTTPS proxy
2022        tls_cert: String,
2023        /// Path to TLS private key file (PEM format) for HTTPS proxy
2024        tls_key: String,
2025        /// Enable wildcard subdomain matching for proxy routes
2026        wildcard: bool,
2027        /// Compatibility alias for general.worktree
2028        worktree: bool,
2029    }
2030}
2031
2032settings_partial! {
2033    /// Partial mirror of [`SettingsSupervisor`].
2034    SettingsSupervisorPartial {
2035        /// Automatically start the supervisor when a client command needs it
2036        auto_start: bool,
2037        /// Reconcile orphaned daemon processes when supervisor starts
2038        cleanup_orphans: bool,
2039        /// Enable container/PID1 mode for running inside Docker containers
2040        container: bool,
2041        /// Consecutive CPU-over-limit samples before killing a daemon
2042        cpu_violation_threshold: i64,
2043        /// Interval for checking cron schedules
2044        cron_check_interval: String,
2045        /// File watch debounce duration
2046        file_watch_debounce: String,
2047        /// Default time between health probes
2048        health_check_interval: String,
2049        /// Default consecutive health-check failures before killing a daemon
2050        health_check_retries: i64,
2051        /// Default per-probe timeout for health_cmd
2052        health_cmd_timeout: String,
2053        /// Default per-request timeout for health_http
2054        health_http_timeout: String,
2055        /// Default per-connect timeout for health_port
2056        health_port_timeout: String,
2057        /// Timeout for HTTP ready checks
2058        http_client_timeout: String,
2059        /// Daemon log buffer flush interval
2060        log_flush_interval: String,
2061        /// What to do with live orphaned daemons on supervisor startup: adopt or kill
2062        orphan_policy: String,
2063        /// Maximum port increment attempts when auto_bump_port is enabled
2064        port_bump_attempts: i64,
2065        /// Maximum time to wait for a oneshot daemon to finish
2066        oneshot_timeout: String,
2067        /// Interval between ready checks (HTTP, TCP, command)
2068        ready_check_interval: String,
2069        /// Delay between stop and start during restart
2070        restart_delay: String,
2071        /// Maximum time to wait for daemon to stop gracefully
2072        stop_timeout: String,
2073        /// Default user to run daemon processes as
2074        user: String,
2075        /// File watcher config refresh interval
2076        watch_interval: String,
2077        /// Polling watcher filesystem scan interval
2078        watch_poll_interval: String,
2079    }
2080}
2081
2082settings_partial! {
2083    /// Partial mirror of [`SettingsTui`].
2084    SettingsTuiPartial {
2085        /// Status message display duration
2086        message_duration: String,
2087        /// Daemon list refresh interval
2088        refresh_rate: String,
2089        /// Number of stat samples to keep for graphs
2090        stat_history: i64,
2091        /// Event loop tick rate
2092        tick_rate: String,
2093    }
2094}
2095
2096settings_partial! {
2097    /// Partial mirror of [`SettingsWeb`].
2098    SettingsWebPartial {
2099        /// Automatically start web UI when supervisor starts
2100        auto_start: bool,
2101        /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
2102        base_path: String,
2103        /// Web server bind address
2104        bind_address: String,
2105        /// Default web server port
2106        bind_port: i64,
2107        /// Initial number of log lines to display
2108        log_lines: i64,
2109        /// Number of ports to try if default is in use
2110        port_attempts: i64,
2111        /// Server-Sent Events poll interval for log streaming
2112        sse_poll_interval: String,
2113    }
2114}
2115
2116settings_partial! {
2117    /// Partial mirror of [`Settings`], for `[settings]` tables in
2118    /// pitchfork.toml files.
2119    SettingsPartial {
2120        @group api: SettingsApiPartial,
2121        @group boot: SettingsBootPartial,
2122        @group general: SettingsGeneralPartial,
2123        @group ipc: SettingsIpcPartial,
2124        @group logs: SettingsLogsPartial,
2125        @group proxy: SettingsProxyPartial,
2126        @group supervisor: SettingsSupervisorPartial,
2127        @group tui: SettingsTuiPartial,
2128        @group web: SettingsWebPartial,
2129    }
2130}
2131
2132impl_has_any_set!(
2133    SettingsApiPartial,
2134    SettingsBootPartial,
2135    SettingsGeneralPartial,
2136    SettingsIpcPartial,
2137    SettingsLogsArchiveHookPartial,
2138    SettingsLogsPartial,
2139    SettingsProxyPartial,
2140    SettingsSupervisorPartial,
2141    SettingsTuiPartial,
2142    SettingsWebPartial,
2143);
2144
2145impl SettingsPartial {
2146    /// Move supported legacy keys to their canonical locations before a
2147    /// read-modify-write cycle serializes this partial again.
2148    pub(crate) fn canonicalize_aliases(&mut self) {
2149        if self.general.worktree.is_none() {
2150            self.general.worktree = self.proxy.worktree.take();
2151        } else {
2152            self.proxy.worktree = None;
2153        }
2154    }
2155}
2156
2157#[cfg(test)]
2158mod tests {
2159    use super::*;
2160    use std::time::Duration;
2161
2162    #[test]
2163    fn find_in_path_takes_the_first_directory_that_has_the_file() {
2164        let empty = tempfile::tempdir().unwrap();
2165        let first = tempfile::tempdir().unwrap();
2166        let second = tempfile::tempdir().unwrap();
2167        std::fs::write(first.path().join("mise.exe"), "").unwrap();
2168        std::fs::write(second.path().join("mise.exe"), "").unwrap();
2169        // A directory with the name, not a file, does not count.
2170        std::fs::create_dir(empty.path().join("mise.exe")).unwrap();
2171
2172        let path = std::env::join_paths([empty.path(), first.path(), second.path()]).unwrap();
2173        assert_eq!(
2174            find_in_path("mise.exe", Some(&path)),
2175            Some(first.path().join("mise.exe"))
2176        );
2177        assert_eq!(find_in_path("missing.exe", Some(&path)), None);
2178        assert_eq!(find_in_path("mise.exe", None), None);
2179    }
2180
2181    #[test]
2182    fn configured_mise_bin_is_absolute() {
2183        // Tests run from the crate root, where `Cargo.toml` is.
2184        let relative = Path::new("Cargo.toml");
2185        assert_eq!(
2186            configured_mise_bin(relative),
2187            Some(std::env::current_dir().unwrap().join(relative))
2188        );
2189    }
2190
2191    #[test]
2192    fn project_mise_bin_takes_only_the_projects_own_value() {
2193        let dir = tempfile::tempdir().unwrap();
2194        let project_dir = dir.path().join("project");
2195        std::fs::create_dir_all(&project_dir).unwrap();
2196        let project_file = project_dir.join("pitchfork.toml");
2197        let user_file = dir.path().join("config.toml");
2198        std::fs::write(
2199            &project_file,
2200            "[settings.general]\nmise_bin = \"tools/mise\"\n",
2201        )
2202        .unwrap();
2203        std::fs::write(&user_file, "[settings.general]\nmise_bin = \"bin/mise\"\n").unwrap();
2204        let project = FileLayer::at(project_file, FileScope::Project).under("settings");
2205        let user = FileLayer::at(user_file, FileScope::Global).under("settings");
2206        // Absolute on every platform: `/opt/mise` is not on Windows.
2207        let env_mise = dir.path().join("env-mise");
2208        let env = EnvLayer::new([(
2209            "PITCHFORK_MISE_BIN".to_string(),
2210            env_mise.to_string_lossy().into_owned(),
2211        )]);
2212        let project_mise_bin = |layers: Layers| {
2213            let resolved = resolve(Settings::SETTINGS_REGISTRY, layers).unwrap();
2214            Settings::read(&resolved)
2215                .unwrap()
2216                .project_mise_bin(&resolved, &project_dir)
2217        };
2218
2219        // The project's own file, over the user's, from the project directory.
2220        assert_eq!(
2221            project_mise_bin(Layers::new().then(&project).then(&user)),
2222            Some(project_dir.join("tools/mise"))
2223        );
2224        // Only the user's configuration sets it: the supervisor applies that.
2225        assert_eq!(project_mise_bin(Layers::new().then(&user)), None);
2226        // The environment takes precedence over the project's file.
2227        assert_eq!(
2228            project_mise_bin(Layers::new().then(&env).then(&project)),
2229            Some(env_mise.clone())
2230        );
2231        // Not set anywhere.
2232        assert_eq!(project_mise_bin(Layers::new()), None);
2233    }
2234
2235    #[test]
2236    fn resolve_daemon_mise_bin_prefers_the_project_mise_bin() {
2237        let dir = tempfile::tempdir().unwrap();
2238        let supervisor_mise = dir.path().join("supervisor-mise");
2239        let project_mise = dir.path().join("project-mise");
2240        std::fs::write(&supervisor_mise, "").unwrap();
2241        std::fs::write(&project_mise, "").unwrap();
2242
2243        let mut settings = Settings::default();
2244        settings.general.mise_bin = supervisor_mise.to_string_lossy().into_owned();
2245
2246        assert_eq!(
2247            settings.resolve_daemon_mise_bin(Some(&project_mise)),
2248            Some(project_mise)
2249        );
2250        // A project mise_bin that does not exist is not replaced by another.
2251        assert_eq!(
2252            settings.resolve_daemon_mise_bin(Some(&dir.path().join("missing"))),
2253            None
2254        );
2255        // Without one, the supervisor's own setting applies, as before.
2256        assert_eq!(
2257            settings.resolve_daemon_mise_bin(None),
2258            Some(supervisor_mise)
2259        );
2260    }
2261
2262    #[cfg(windows)]
2263    #[test]
2264    fn resolve_mise_bin_finds_mise_exe_on_path_on_windows() {
2265        let dir = tempfile::tempdir().unwrap();
2266        let mise = dir.path().join("mise.exe");
2267        std::fs::write(&mise, "").unwrap();
2268        let path = std::env::join_paths([dir.path()]).unwrap();
2269
2270        // No `mise_bin`, and none of the Unix locations exist on Windows.
2271        let settings = Settings::default();
2272        assert_eq!(settings.resolve_mise_bin_with_path(Some(&path)), Some(mise));
2273        assert_eq!(settings.resolve_mise_bin_with_path(None), None);
2274    }
2275
2276    #[test]
2277    fn find_in_path_returns_an_absolute_path_for_a_relative_entry() {
2278        // A relative entry is found against the supervisor's working
2279        // directory, but the path is used from the daemon's, so it has to be
2280        // made absolute. Created in the working directory itself, which
2281        // always exists, unlike a build directory Cargo may put elsewhere.
2282        let dir = tempfile::tempdir_in(".").unwrap();
2283        std::fs::write(dir.path().join("mise.exe"), "").unwrap();
2284        let relative = dir
2285            .path()
2286            .strip_prefix(std::env::current_dir().unwrap())
2287            .unwrap_or(dir.path());
2288        assert!(relative.is_relative(), "{relative:?}");
2289
2290        let found = find_in_path("mise.exe", Some(relative.as_os_str())).unwrap();
2291        assert!(found.is_absolute(), "{found:?}");
2292        assert!(found.is_file());
2293    }
2294
2295    #[test]
2296    fn shell_defaults() {
2297        let settings = Settings::default();
2298        assert_eq!(settings.general.shell, "sh -c");
2299        assert_eq!(settings.general.windows_shell, "cmd /C");
2300    }
2301
2302    #[test]
2303    fn shell_precedence() {
2304        let mut settings = Settings::default();
2305        settings.general.shell = "unix-sh -c".to_string();
2306        settings.general.windows_shell = "win-sh /C".to_string();
2307        let unix = vec!["unix-sh".to_string(), "-c".to_string()];
2308        let windows = vec!["win-sh".to_string(), "/C".to_string()];
2309
2310        // An explicit general.shell wins on every platform.
2311        assert_eq!(settings.resolve_shell(true).unwrap(), unix);
2312
2313        // Left at its default, general.shell yields to windows_shell on
2314        // Windows and is the only setting consulted elsewhere.
2315        let expected = if cfg!(windows) { windows } else { unix };
2316        assert_eq!(settings.resolve_shell(false).unwrap(), expected);
2317    }
2318
2319    #[test]
2320    fn shell_is_explicit_comes_from_the_origin_not_the_text() {
2321        // `PITCHFORK_SHELL="sh -c"` is the same string as the default, and
2322        // must still count as set: on Windows it decides whether
2323        // windows_shell is consulted at all.
2324        let untouched =
2325            resolve(Settings::SETTINGS_REGISTRY, Layers::new()).expect("resolving defaults");
2326        assert!(!shell_is_explicit(&untouched));
2327
2328        let layer = EnvLayer::new([("PITCHFORK_SHELL".to_string(), "sh -c".to_string())]);
2329        let explicit = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer))
2330            .expect("resolving an override");
2331        assert!(shell_is_explicit(&explicit));
2332    }
2333
2334    #[test]
2335    fn an_unusable_shell_names_the_key_it_came_from() {
2336        let mut settings = Settings::default();
2337        settings.general.shell = "sh -c 'unbalanced".to_string();
2338        let err = settings.resolve_shell(true).unwrap_err();
2339        assert!(err.contains("general.shell"), "{err}");
2340
2341        settings.general.shell = String::new();
2342        let err = settings.resolve_shell(true).unwrap_err();
2343        assert!(err.contains("general.shell setting is empty"), "{err}");
2344
2345        settings.general.windows_shell = String::new();
2346        let key = if cfg!(windows) {
2347            "general.windows_shell"
2348        } else {
2349            "general.shell"
2350        };
2351        let err = settings.resolve_shell(false).unwrap_err();
2352        assert!(err.contains(key), "{err}");
2353    }
2354
2355    #[test]
2356    fn test_default_settings() {
2357        let settings = Settings::default();
2358
2359        // Test general settings
2360        assert_eq!(settings.general.autostop_delay, "1m");
2361        assert_eq!(settings.general.interval, "10s");
2362        assert_eq!(settings.general.log_level, "info");
2363        assert_eq!(settings.general.ready_delay, "3s");
2364
2365        // Test IPC settings
2366        assert_eq!(settings.ipc.connect_attempts, 5);
2367        assert_eq!(settings.ipc.request_timeout, "5s");
2368        assert_eq!(settings.ipc.rate_limit, 100);
2369
2370        // Test web settings
2371        assert!(!settings.web.auto_start);
2372        assert_eq!(settings.web.bind_address, "127.0.0.1");
2373        assert_eq!(settings.web.bind_port, 3120);
2374        assert_eq!(settings.web.log_lines, 100);
2375
2376        // Test TUI settings
2377        assert_eq!(settings.tui.refresh_rate, "2s");
2378        assert_eq!(settings.tui.stat_history, 60);
2379
2380        // Test supervisor settings
2381        assert!(settings.supervisor.auto_start);
2382        assert_eq!(settings.supervisor.ready_check_interval, "500ms");
2383        assert_eq!(settings.supervisor.file_watch_debounce, "1s");
2384        assert_eq!(settings.supervisor.user, "");
2385    }
2386
2387    #[test]
2388    fn a_bad_value_costs_only_its_own_setting() {
2389        // `Settings::read` is all or nothing, and the fallback for its failure used to be
2390        // `Settings::default()` — one field the merge could not hand to its type demoting all
2391        // sixty-eight settings and discarding the environment along with them.
2392        let env = EnvLayer::new([("PITCHFORK_LOG".to_string(), "debug".to_string())]);
2393        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2394
2395        // The one door into a resolution the merge does not check: a post-merge hook, which is
2396        // what `sanitize_durations` is. A bool where an integer belongs is what a buggy one
2397        // could write.
2398        let registry = Settings::SETTINGS_REGISTRY;
2399        let rate_limit = registry.lookup("ipc.rate_limit").unwrap().id;
2400        resolved.coerced(rate_limit, Value::Bool(true), "a hook that got it wrong");
2401
2402        assert!(
2403            Settings::read(&resolved).is_err(),
2404            "the strict read still refuses it"
2405        );
2406
2407        let (settings, errors) = Settings::read_lossy(&resolved);
2408        let settings = settings.expect("every setting declares a default");
2409        assert_eq!(
2410            settings.ipc.rate_limit, 100,
2411            "the bad field takes its declared default"
2412        );
2413        assert_eq!(
2414            settings.general.log_level, "debug",
2415            "and PITCHFORK_LOG is not collateral damage"
2416        );
2417        assert_eq!(errors.0.len(), 1, "{errors}");
2418        assert_eq!(errors.0[0].key, "ipc.rate_limit");
2419    }
2420
2421    #[test]
2422    fn every_setting_declares_a_default() {
2423        // What makes the `None` arm of the lossy read unreachable: a setting with no value and
2424        // no default is a hole in this file, not something a user can cause. Adding one without
2425        // a default should fail here rather than silently demote the whole struct at runtime.
2426        let missing: Vec<&str> = Settings::SETTINGS_PROPS
2427            .iter()
2428            .filter(|meta| meta.default.is_none())
2429            .map(|meta| meta.key)
2430            .collect();
2431        assert!(
2432            missing.is_empty(),
2433            "these settings declare no default: {missing:?}"
2434        );
2435    }
2436
2437    #[test]
2438    fn test_registry_matches_previous_schema() {
2439        // The emitted config block is the settings documentation now; make
2440        // sure the registry still declares what settings.toml used to.
2441        let keys: Vec<&str> = Settings::SETTINGS_PROPS
2442            .iter()
2443            .map(|meta| meta.key)
2444            .collect();
2445        // 75 before either change, plus `supervisor.oneshot_timeout` from main,
2446        // `proxy.dns` / `proxy.dns_port`, `proxy.idle_timeout`, and `boot.executable`.
2447        assert_eq!(keys.len(), 80, "{keys:?}");
2448        assert!(keys.contains(&"boot.executable"));
2449        assert!(keys.contains(&"general.autostop_delay"));
2450        assert!(keys.contains(&"supervisor.oneshot_timeout"));
2451        assert!(keys.contains(&"logs.archive_hook.command"));
2452        assert!(keys.contains(&"supervisor.health_check_interval"));
2453        assert!(keys.contains(&"supervisor.watch_interval"));
2454        assert!(keys.contains(&"proxy.dns"));
2455        assert!(keys.contains(&"proxy.dns_port"));
2456        assert!(keys.contains(&"proxy.idle_timeout"));
2457
2458        let registry = Settings::SETTINGS_REGISTRY;
2459        let interval = registry.get(registry.lookup("general.interval").unwrap().id);
2460        assert_eq!(interval.envs, &["PITCHFORK_INTERVAL"]);
2461        assert_eq!(interval.deprecated_envs, &["PITCHFORK_INTERVAL_SECS"]);
2462        let watch = registry.get(registry.lookup("supervisor.watch_interval").unwrap().id);
2463        assert_eq!(watch.deprecated_envs, &["PITCHFORK_WATCH_INTERVAL_MS"]);
2464        let log_level = registry.get(registry.lookup("general.log_level").unwrap().id);
2465        assert_eq!(log_level.envs, &["PITCHFORK_LOG"]);
2466        let worktree = registry.get(registry.lookup("general.worktree").unwrap().id);
2467        assert_eq!(worktree.envs, &["PITCHFORK_WORKTREE"]);
2468        assert_eq!(worktree.deprecated_envs, &["PITCHFORK_PROXY_WORKTREE"]);
2469        assert_eq!(worktree.aliases, &["proxy.worktree"]);
2470        assert_eq!(
2471            registry.lookup("proxy.worktree").unwrap().id,
2472            registry.lookup("general.worktree").unwrap().id,
2473        );
2474
2475        let spec = Settings::spec_kdl();
2476        let files = [
2477            "file \"/etc/pitchfork/config.toml\" scope=\"system\" format=\"toml\"",
2478            "file \"~/.config/pitchfork/config.toml\" scope=\"global\" format=\"toml\"",
2479            "file \".config/pitchfork.toml\" findup=#true format=\"toml\"",
2480            "file \".config/pitchfork.local.toml\" findup=#true format=\"toml\"",
2481            "file \"pitchfork.toml\" findup=#true format=\"toml\"",
2482            "file \"pitchfork.local.toml\" findup=#true format=\"toml\"",
2483        ];
2484        let positions: Vec<usize> = files
2485            .iter()
2486            .map(|file| spec.find(file).unwrap_or_else(|| panic!("missing {file}")))
2487            .collect();
2488        assert!(
2489            positions.windows(2).all(|pair| pair[0] < pair[1]),
2490            "config files must be documented from lowest to highest precedence:\n{spec}"
2491        );
2492    }
2493
2494    #[test]
2495    fn every_registry_key_round_trips_through_the_partial() {
2496        // A setting added to the derive structs but missed in `settings_partial!`
2497        // makes `pitchfork settings set` report success and write nothing.
2498        for meta in Settings::SETTINGS_PROPS {
2499            let value = match meta.ty.inner() {
2500                Ty::Bool => toml::Value::Boolean(true),
2501                Ty::Int | Ty::Uint => toml::Value::Integer(1),
2502                _ => toml::Value::String("x".to_string()),
2503            };
2504            let parts: Vec<&str> = meta.key.split('.').collect();
2505            let mut table = toml::Table::new();
2506            let mut cursor = &mut table;
2507            for part in &parts[..parts.len() - 1] {
2508                cursor = cursor
2509                    .entry(part.to_string())
2510                    .or_insert_with(|| toml::Value::Table(toml::Table::new()))
2511                    .as_table_mut()
2512                    .unwrap();
2513            }
2514            cursor.insert(parts[parts.len() - 1].to_string(), value);
2515
2516            let partial: SettingsPartial = table.clone().try_into().unwrap();
2517            let back = toml::Table::try_from(&partial).unwrap();
2518            assert_eq!(
2519                back, table,
2520                "{} is declared in the registry but not mirrored in SettingsPartial",
2521                meta.key
2522            );
2523        }
2524    }
2525
2526    #[test]
2527    fn test_parse_duration() {
2528        assert_eq!(Settings::parse_duration("1s"), Some(Duration::from_secs(1)));
2529        assert_eq!(
2530            Settings::parse_duration("500ms"),
2531            Some(Duration::from_millis(500))
2532        );
2533        assert_eq!(
2534            Settings::parse_duration("1m"),
2535            Some(Duration::from_secs(60))
2536        );
2537        assert_eq!(
2538            Settings::parse_duration("2h"),
2539            Some(Duration::from_secs(7200))
2540        );
2541        assert_eq!(Settings::parse_duration("invalid"), None);
2542    }
2543
2544    #[test]
2545    fn test_env_override() {
2546        // The environment is described rather than reached for, so this test
2547        // does not mutate process env vars (the old test needed a mutex).
2548        let env = EnvLayer::new([
2549            ("PITCHFORK_AUTOSTOP_DELAY".to_string(), "10m".to_string()),
2550            ("PITCHFORK_INTERVAL".to_string(), "5s".to_string()),
2551            (
2552                "PITCHFORK_IPC_CONNECT_ATTEMPTS".to_string(),
2553                "20".to_string(),
2554            ),
2555            (
2556                "PITCHFORK_SUPERVISOR_AUTO_START".to_string(),
2557                "false".to_string(),
2558            ),
2559            ("PITCHFORK_WEB_AUTO_START".to_string(), "true".to_string()),
2560        ]);
2561        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2562        let settings = Settings::read(&resolved).unwrap();
2563
2564        assert_eq!(settings.general.autostop_delay, "10m");
2565        assert_eq!(settings.general.interval, "5s");
2566        assert_eq!(settings.ipc.connect_attempts, 20);
2567        assert!(!settings.supervisor.auto_start);
2568        assert!(settings.web.auto_start);
2569
2570        // Fields with no corresponding env var set remain at defaults
2571        assert_eq!(settings.general.log_level, "info");
2572        assert_eq!(settings.ipc.rate_limit, 100);
2573    }
2574
2575    #[test]
2576    fn test_deprecated_env_still_works_and_warns() {
2577        let env = EnvLayer::new([
2578            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
2579            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
2580        ]);
2581        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2582        let settings = Settings::read(&resolved).unwrap();
2583        assert_eq!(settings.general.interval, "30s");
2584        assert!(!settings.general.worktree);
2585        let warnings = usage_rs::config::explain::warnings(&resolved);
2586        assert!(
2587            warnings
2588                .iter()
2589                .any(|w| w.contains("PITCHFORK_INTERVAL_SECS is deprecated")),
2590            "{warnings:?}"
2591        );
2592        assert!(
2593            warnings
2594                .iter()
2595                .any(|w| w.contains("PITCHFORK_PROXY_WORKTREE is deprecated")),
2596            "{warnings:?}"
2597        );
2598
2599        // The current name wins over the deprecated alias when both are set.
2600        let env = EnvLayer::new([
2601            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
2602            ("PITCHFORK_INTERVAL".to_string(), "7s".to_string()),
2603            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
2604            ("PITCHFORK_WORKTREE".to_string(), "true".to_string()),
2605        ]);
2606        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2607        let settings = Settings::read(&resolved).unwrap();
2608        assert_eq!(settings.general.interval, "7s");
2609        assert!(settings.general.worktree);
2610    }
2611
2612    #[test]
2613    fn test_invalid_duration_from_env_falls_back_to_default() {
2614        // The previous loader rejected invalid durations at load time; the
2615        // sanitize pass reproduces that through Resolved::coerced.
2616        let env = EnvLayer::new([(
2617            "PITCHFORK_AUTOSTOP_DELAY".to_string(),
2618            "not_a_duration".to_string(),
2619        )]);
2620        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2621        sanitize_durations(&mut resolved);
2622        let settings = Settings::read(&resolved).unwrap();
2623        assert_eq!(settings.general.autostop_delay, "1m");
2624        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2625    }
2626
2627    #[test]
2628    fn test_zero_health_timeout_from_env_falls_back_to_default() {
2629        // A zero health probe timeout goes straight into tokio::time::timeout
2630        // and fails every probe immediately; the sanitize pass falls back to
2631        // the schema default like any other invalid duration.
2632        let env = EnvLayer::new([
2633            ("PITCHFORK_HEALTH_CMD_TIMEOUT".to_string(), "0s".to_string()),
2634            (
2635                "PITCHFORK_HEALTH_HTTP_TIMEOUT".to_string(),
2636                "0s".to_string(),
2637            ),
2638            (
2639                "PITCHFORK_HEALTH_PORT_TIMEOUT".to_string(),
2640                "0s".to_string(),
2641            ),
2642        ]);
2643        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2644        sanitize_durations(&mut resolved);
2645        let settings = Settings::read(&resolved).unwrap();
2646        assert_eq!(settings.supervisor.health_cmd_timeout, "10s");
2647        assert_eq!(
2648            settings.supervisor_health_cmd_timeout(),
2649            Duration::from_secs(10)
2650        );
2651        assert_eq!(settings.supervisor.health_http_timeout, "5s");
2652        assert_eq!(settings.supervisor.health_port_timeout, "5s");
2653    }
2654
2655    #[test]
2656    fn test_invalid_duration_fallback() {
2657        let mut settings = Settings::default();
2658
2659        // Set invalid duration values
2660        settings.general.autostop_delay = "invalid".to_string();
2661        settings.general.interval = "not_a_duration".to_string();
2662
2663        // Convenience methods should fallback to default values
2664        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60)); // default "1m"
2665        assert_eq!(settings.general_interval(), Duration::from_secs(10)); // default "10s"
2666    }
2667
2668    #[test]
2669    fn oneshot_wait_defaults_to_an_hour() {
2670        use crate::config_types::OneshotWait;
2671        let settings = Settings::default();
2672        assert_eq!(
2673            settings.supervisor_oneshot_timeout(),
2674            Duration::from_secs(3600)
2675        );
2676        assert_eq!(
2677            settings.supervisor_oneshot_wait(),
2678            OneshotWait::For(Duration::from_secs(3600))
2679        );
2680    }
2681
2682    #[test]
2683    fn oneshot_wait_of_zero_means_no_deadline_at_all() {
2684        // A task's natural end is its exit, so `0` has to read as "wait",
2685        // never as "give up immediately" — and never as a distant substitute
2686        // deadline that a long enough task could still outlive.
2687        use crate::config_types::OneshotWait;
2688        let mut settings = Settings::default();
2689        for value in ["0", "0s"] {
2690            settings.supervisor.oneshot_timeout = value.to_string();
2691            assert!(settings.supervisor_oneshot_timeout().is_zero());
2692            assert_eq!(
2693                settings.supervisor_oneshot_wait(),
2694                OneshotWait::Unlimited,
2695                "{value} should wait without a deadline"
2696            );
2697            assert_eq!(settings.supervisor_oneshot_wait().duration(), None);
2698        }
2699    }
2700
2701    #[test]
2702    fn oneshot_wait_honours_a_configured_value() {
2703        use crate::config_types::OneshotWait;
2704        let mut settings = Settings::default();
2705        settings.supervisor.oneshot_timeout = "6h".to_string();
2706        assert_eq!(
2707            settings.supervisor_oneshot_wait(),
2708            OneshotWait::For(Duration::from_secs(6 * 3600))
2709        );
2710        assert_eq!(
2711            settings.supervisor_oneshot_wait().duration(),
2712            Some(Duration::from_secs(6 * 3600))
2713        );
2714    }
2715
2716    #[test]
2717    fn test_duration_methods_all_fields() {
2718        let settings = Settings::default();
2719
2720        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2721        assert_eq!(settings.general_interval(), Duration::from_secs(10));
2722        assert_eq!(settings.general_ready_delay(), Duration::from_secs(3));
2723        assert_eq!(settings.ipc_connect_min_delay(), Duration::from_millis(100));
2724        assert_eq!(settings.ipc_connect_max_delay(), Duration::from_secs(1));
2725        assert_eq!(settings.ipc_request_timeout(), Duration::from_secs(5));
2726        assert_eq!(settings.ipc_rate_limit_window(), Duration::from_secs(1));
2727        assert_eq!(settings.web_sse_poll_interval(), Duration::from_millis(500));
2728        assert_eq!(settings.tui_refresh_rate(), Duration::from_secs(2));
2729        assert_eq!(settings.tui_tick_rate(), Duration::from_millis(100));
2730        assert_eq!(settings.tui_message_duration(), Duration::from_secs(3));
2731        assert_eq!(
2732            settings.supervisor_ready_check_interval(),
2733            Duration::from_millis(500)
2734        );
2735        assert_eq!(
2736            settings.supervisor_file_watch_debounce(),
2737            Duration::from_secs(1)
2738        );
2739        assert_eq!(
2740            settings.supervisor_log_flush_interval(),
2741            Duration::from_millis(500)
2742        );
2743        assert_eq!(settings.supervisor_stop_timeout(), Duration::from_secs(5));
2744        assert_eq!(
2745            settings.supervisor_restart_delay(),
2746            Duration::from_millis(100)
2747        );
2748        assert_eq!(
2749            settings.supervisor_cron_check_interval(),
2750            Duration::from_secs(10)
2751        );
2752        assert_eq!(
2753            settings.supervisor_http_client_timeout(),
2754            Duration::from_secs(5)
2755        );
2756    }
2757
2758    #[test]
2759    fn test_general_ready_delay_secs() {
2760        let mut settings = Settings::default();
2761
2762        // Default "3s" resolves to whole seconds.
2763        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2764
2765        // Subsecond values are rejected, not silently truncated by as_secs().
2766        settings.general.ready_delay = "500ms".to_string();
2767        let err = settings.general_ready_delay_secs().unwrap_err();
2768        assert!(err.contains("500ms"), "unexpected error: {err}");
2769        assert!(
2770            err.contains("whole number of seconds"),
2771            "unexpected error: {err}"
2772        );
2773
2774        settings.general.ready_delay = "1.5s".to_string();
2775        let err = settings.general_ready_delay_secs().unwrap_err();
2776        assert!(err.contains("1.5s"), "unexpected error: {err}");
2777
2778        // Empty string falls back to the schema default "3s".
2779        settings.general.ready_delay = String::new();
2780        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2781
2782        // Whole-second values resolve as seconds.
2783        settings.general.ready_delay = "90s".to_string();
2784        assert_eq!(settings.general_ready_delay_secs(), Ok(90));
2785    }
2786
2787    /// A directory tree, cleaned up when the test ends.
2788    struct Tree(std::path::PathBuf);
2789
2790    impl Tree {
2791        fn new(name: &str) -> Self {
2792            let dir = std::env::temp_dir()
2793                .join(format!("pitchfork_settings_{}_{name}", std::process::id()));
2794            let _ = std::fs::remove_dir_all(&dir);
2795            std::fs::create_dir_all(&dir).unwrap();
2796            Self(dir)
2797        }
2798
2799        fn write(&self, rel: &str, text: &str) -> std::path::PathBuf {
2800            let path = self.0.join(rel);
2801            if let Some(parent) = path.parent() {
2802                std::fs::create_dir_all(parent).unwrap();
2803            }
2804            std::fs::write(&path, text).unwrap();
2805            path
2806        }
2807    }
2808
2809    impl Drop for Tree {
2810        fn drop(&mut self) {
2811            let _ = std::fs::remove_dir_all(&self.0);
2812        }
2813    }
2814
2815    #[test]
2816    fn test_settings_read_from_pitchfork_toml_settings_table() {
2817        let tree = Tree::new("table");
2818        let path = tree.write(
2819            "pitchfork.toml",
2820            r#"
2821[daemons.myapp]
2822run = "node server.js"
2823
2824[settings.general]
2825autostop_delay = "5m"
2826log_level = "debug"
2827
2828[settings.web]
2829auto_start = true
2830bind_port = 8080
2831
2832[settings.supervisor]
2833auto_start = false
2834user = "postgres"
2835"#,
2836        );
2837        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2838        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2839        let settings = Settings::read(&resolved).unwrap();
2840
2841        assert_eq!(settings.general.autostop_delay, "5m");
2842        assert_eq!(settings.general.log_level, "debug");
2843        assert!(settings.web.auto_start);
2844        assert_eq!(settings.web.bind_port, 8080);
2845        assert!(!settings.supervisor.auto_start);
2846        assert_eq!(settings.supervisor.user, "postgres");
2847        // Unset fields fall back to defaults, and [daemons] is not a warning.
2848        assert_eq!(settings.general.interval, "10s");
2849        assert_eq!(settings.ipc.connect_attempts, 5);
2850        assert!(resolved.warnings.is_empty(), "{:?}", resolved.warnings);
2851    }
2852
2853    #[test]
2854    fn test_proxy_worktree_config_alias_still_works() {
2855        let tree = Tree::new("proxy_worktree_alias");
2856        let path = tree.write("pitchfork.toml", "[settings.proxy]\nworktree = false\n");
2857        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2858        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2859        let settings = Settings::read(&resolved).unwrap();
2860
2861        assert!(!settings.general.worktree);
2862        assert_eq!(
2863            resolved.get(
2864                Settings::SETTINGS_REGISTRY
2865                    .lookup("general.worktree")
2866                    .unwrap()
2867                    .id
2868            ),
2869            Some(&Value::Bool(false)),
2870        );
2871    }
2872
2873    #[test]
2874    fn test_explicit_default_value_in_higher_file_still_overrides() {
2875        // "Bug 5": the old merge_from skipped values equal to the default, so
2876        // a higher-precedence file explicitly setting log_level = "info"
2877        // could not override "warn" from a lower one. usage-config's
2878        // origin-tracked merge does this natively; pin it.
2879        let tree = Tree::new("bug5");
2880        let lower = tree.write("lower.toml", "[settings.general]\nlog_level = \"warn\"\n");
2881        let higher = tree.write("higher.toml", "[settings.general]\nlog_level = \"info\"\n");
2882        let lower = FileLayer::at(&lower, FileScope::Global).under("settings");
2883        let higher = FileLayer::at(&higher, FileScope::Project).under("settings");
2884        let resolved = resolve(
2885            Settings::SETTINGS_REGISTRY,
2886            Layers::new().then(&higher).then(&lower),
2887        )
2888        .unwrap();
2889        let settings = Settings::read(&resolved).unwrap();
2890        assert_eq!(settings.general.log_level, "info");
2891
2892        // And the provenance says the higher file set it, not the default.
2893        let id = Settings::SETTINGS_REGISTRY
2894            .lookup("general.log_level")
2895            .unwrap()
2896            .id;
2897        let origin = resolved.origin(id).unwrap().describe();
2898        assert!(origin.contains("higher.toml"), "{origin}");
2899    }
2900
2901    #[test]
2902    fn boot_executable_rejects_project_config() {
2903        let tree = Tree::new("boot-scope");
2904        let project = tree.write(
2905            "pitchfork.toml",
2906            "[settings.boot]\nexecutable = \"/tmp/project/pitchfork\"\n",
2907        );
2908        let global = tree.write(
2909            "config.toml",
2910            "[settings.boot]\nexecutable = \"/opt/pitchfork/stable\"\n",
2911        );
2912        let project = FileLayer::at(&project, FileScope::Project).under("settings");
2913        let global = FileLayer::at(&global, FileScope::Global).under("settings");
2914
2915        let resolved = resolve(
2916            Settings::SETTINGS_REGISTRY,
2917            Layers::new().then(&project).then(&global),
2918        )
2919        .unwrap();
2920        assert_eq!(
2921            Settings::read(&resolved).unwrap().boot.executable,
2922            "/opt/pitchfork/stable"
2923        );
2924        assert!(resolved.warnings.iter().any(|warning| {
2925            warning.message.contains("boot.executable") && warning.message.contains("cannot be set")
2926        }));
2927
2928        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&project)).unwrap();
2929        assert!(
2930            Settings::read(&resolved)
2931                .unwrap()
2932                .boot
2933                .executable
2934                .is_empty()
2935        );
2936    }
2937
2938    #[test]
2939    fn test_file_precedence_local_over_base_and_nearer_dir_wins() {
2940        let tree = Tree::new("precedence");
2941        tree.write("pitchfork.toml", "[settings.general]\ninterval = \"9s\"\n");
2942        tree.write(
2943            "pitchfork.local.toml",
2944            "[settings.general]\ninterval = \"2s\"\n",
2945        );
2946        tree.write(
2947            ".config/pitchfork.toml",
2948            "[settings.general]\ninterval = \"7s\"\n[settings.web]\nbind_port = 9999\n",
2949        );
2950        let layers = Settings::file_layers_from(&tree.0);
2951        let mut chain = Layers::new();
2952        for layer in &layers {
2953            chain = chain.then(layer);
2954        }
2955        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
2956        let settings = Settings::read(&resolved).unwrap();
2957        // pitchfork.local.toml > pitchfork.toml > .config/pitchfork.toml
2958        assert_eq!(settings.general.interval, "2s");
2959        // A key only the lowest file sets still applies.
2960        assert_eq!(settings.web.bind_port, 9999);
2961
2962        // A nested directory's file outranks everything above it.
2963        let deep = tree.0.join("a").join("b");
2964        std::fs::create_dir_all(&deep).unwrap();
2965        tree.write(
2966            "a/b/pitchfork.toml",
2967            "[settings.general]\ninterval = \"1s\"\n",
2968        );
2969        let layers = Settings::file_layers_from(&deep);
2970        let mut chain = Layers::new();
2971        for layer in &layers {
2972            chain = chain.then(layer);
2973        }
2974        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
2975        let settings = Settings::read(&resolved).unwrap();
2976        assert_eq!(settings.general.interval, "1s");
2977    }
2978
2979    #[test]
2980    fn test_broken_file_is_skipped_rather_than_fatal() {
2981        let tree = Tree::new("broken");
2982        let broken = tree.write("pitchfork.toml", "[invalid toml [[");
2983        // The broken file is skipped with a warning, so the resolution still
2984        // happens and produces the defaults.
2985        let layers = Settings::file_layers_from(&tree.0);
2986        assert!(
2987            layers.iter().all(|layer| !layer.paths().contains(&broken)),
2988            "the broken project file must not become a settings layer"
2989        );
2990    }
2991
2992    #[test]
2993    fn test_unknown_settings_keys_do_not_fail_the_load() {
2994        // Forward compatibility: a config written for a newer pitchfork must
2995        // still load. Unknown keys are warned about rather than fatal.
2996        let tree = Tree::new("unknown");
2997        let path = tree.write(
2998            "pitchfork.toml",
2999            "[settings.general]\nlog_level = \"debug\"\nfrom_the_future = true\n",
3000        );
3001        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
3002        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
3003        let settings = Settings::read(&resolved).unwrap();
3004        assert_eq!(settings.general.log_level, "debug");
3005        assert_eq!(resolved.warnings.len(), 1, "{:?}", resolved.warnings);
3006    }
3007
3008    #[test]
3009    fn test_partial_merge_from() {
3010        let mut base = SettingsPartial::default();
3011        base.general.log_level = Some("warn".to_string());
3012        base.web.bind_address = Some("0.0.0.0".to_string());
3013
3014        let mut overlay = SettingsPartial::default();
3015        overlay.general.log_level = Some("debug".to_string());
3016        overlay.tui.refresh_rate = Some("1s".to_string());
3017
3018        base.merge_from(&overlay);
3019        assert_eq!(base.general.log_level.as_deref(), Some("debug"));
3020        assert_eq!(base.web.bind_address.as_deref(), Some("0.0.0.0"));
3021        assert_eq!(base.tui.refresh_rate.as_deref(), Some("1s"));
3022
3023        // An empty partial changes nothing.
3024        let sealed = base.clone();
3025        base.merge_from(&SettingsPartial::default());
3026        assert_eq!(base.general.log_level, sealed.general.log_level);
3027        assert!(SettingsPartial::default().is_empty());
3028        assert!(base.has_any_set());
3029    }
3030
3031    #[test]
3032    fn test_partial_serialization_skips_unset() {
3033        let mut partial = SettingsPartial::default();
3034        partial.general.interval = Some("5s".to_string());
3035        let toml = toml::to_string_pretty(&partial).unwrap();
3036        assert_eq!(toml, "[general]\ninterval = \"5s\"\n");
3037    }
3038}