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, Resolved, Ty, Value, resolve,
39};
40
41/// The `api.*` settings: the standalone API server (JSON REST endpoints for
42/// the Vue SPA). When `api.bind_port` is set, the API server binds
43/// independently of the web UI.
44#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
45#[usage(prefix = "api")]
46pub struct SettingsApi {
47    /// Automatically start the standalone API server
48    ///
49    /// When true, pitchfork starts a standalone API server on api.bind_address +
50    /// api.bind_port when the supervisor launches. The web UI does not need to
51    /// be enabled for this; you can run the API alone and serve the Vue SPA from
52    /// a separate static host (e.g. nginx, Vite dev server).
53    ///
54    /// Default is false so the API is only available through the bundled web UI.
55    #[usage(env = "PITCHFORK_API_AUTO_START", default = false)]
56    pub auto_start: bool,
57
58    /// IP address the API server binds to
59    ///
60    /// Use "0.0.0.0" to make the API reachable from other devices on your network.
61    /// Keep "127.0.0.1" (default) to restrict it to localhost.
62    #[usage(env = "PITCHFORK_API_BIND_ADDRESS", default = "127.0.0.1")]
63    pub bind_address: String,
64
65    /// Port the standalone API server listens on
66    ///
67    /// Set to 0 (default) to disable the standalone API server.
68    /// Set to any valid port number (e.g. 8081) to start the API on its own port.
69    #[usage(env = "PITCHFORK_API_BIND_PORT", default = 0)]
70    pub bind_port: i64,
71
72    /// Number of consecutive ports to try if api.bind_port is in use
73    #[usage(env = "PITCHFORK_API_PORT_ATTEMPTS", default = 10)]
74    pub port_attempts: i64,
75
76    /// Authentication token for API access when bound to non-loopback addresses
77    ///
78    /// When the API server or web UI is bound to a non-loopback address (e.g.,
79    /// "0.0.0.0"), this token is required on every API request via the
80    /// X-Pitchfork-Token header.
81    ///
82    /// If left empty and the bind address is non-loopback, a random 32-byte
83    /// hex token is auto-generated on startup and printed to the supervisor log.
84    /// This token is injected into the served index.html, so the bundled Vue
85    /// SPA works without additional configuration.
86    ///
87    /// For external API consumers (e.g., curl, mobile apps), set this to a
88    /// fixed value or pass it via the PITCHFORK_API_TOKEN environment variable.
89    #[usage(env = "PITCHFORK_API_TOKEN", default = "")]
90    pub token: String,
91}
92
93/// The `general.*` settings.
94#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
95#[usage(prefix = "general")]
96pub struct SettingsGeneral {
97    /// Delay before auto-stopping daemons when leaving a directory
98    ///
99    /// When using shell hooks with `auto = ["stop"]`, this controls how long pitchfork waits
100    /// before stopping a daemon after you leave its directory.
101    ///
102    /// This delay prevents unnecessary stop/start cycles when briefly switching directories.
103    ///
104    /// **Examples:**
105    /// - `"0s"` - Stop immediately (no delay)
106    /// - `"30s"` - Wait 30 seconds
107    /// - `"1m"` - Wait 1 minute (default)
108    /// - `"5m"` - Wait 5 minutes
109    ///
110    /// Set to `"0s"` to disable the delay and stop daemons immediately.
111    #[usage(env = "PITCHFORK_AUTOSTOP_DELAY", default = "1m", ty = "duration")]
112    pub autostop_delay: String,
113
114    /// Supervisor background task refresh interval
115    ///
116    /// Controls how often the supervisor refreshes its internal state and checks for:
117    /// - Daemon health status changes
118    /// - Configuration file updates
119    /// - Process state synchronization
120    ///
121    /// Lower values provide more responsive status updates but use more resources.
122    ///
123    /// **Recommended values:**
124    /// - `"5s"` - For development/testing
125    /// - `"10s"` - Default, balanced
126    /// - `"30s"` - For production with many daemons
127    #[usage(
128        env = "PITCHFORK_INTERVAL",
129        deprecated_env("PITCHFORK_INTERVAL_SECS"),
130        default = "10s",
131        ty = "duration"
132    )]
133    pub interval: String,
134
135    /// File log level (trace, debug, info, warn, error)
136    ///
137    /// Controls the verbosity of log output written to log files.
138    /// Can be set independently from `log_level` to have more verbose file logs.
139    ///
140    /// For example, set console to `"info"` but file to `"debug"` to keep
141    /// detailed logs for troubleshooting without cluttering the console.
142    #[usage(env = "PITCHFORK_LOG_FILE_LEVEL", default = "info")]
143    pub log_file_level: String,
144
145    /// Console log level (trace, debug, info, warn, error)
146    ///
147    /// Controls the verbosity of log output to the console.
148    ///
149    /// **Available levels:**
150    /// - `"trace"` - Most verbose, includes all internal details
151    /// - `"debug"` - Detailed information for debugging
152    /// - `"info"` - Normal operation messages (default)
153    /// - `"warn"` - Warnings and potential issues
154    /// - `"error"` - Only errors
155    #[usage(env = "PITCHFORK_LOG", default = "info")]
156    pub log_level: String,
157
158    /// Wrap daemon commands with mise x -- globally
159    ///
160    /// When enabled, pitchfork wraps every daemon command with `mise x --` so that
161    /// [mise](https://mise.jdx.dev) sets up the correct tool versions, PATH,
162    /// and environment variables before the daemon runs.
163    ///
164    /// This is especially useful when pitchfork is started as a login item or boot
165    /// daemon, where the shell profile (`.zshrc`, `.bashrc`) is not sourced and
166    /// tools installed via Homebrew or mise are not on PATH.
167    ///
168    /// Individual daemons can override this with `mise = true` or `mise = false`
169    /// in their configuration.
170    #[usage(env = "PITCHFORK_MISE", default = false)]
171    pub mise: bool,
172
173    /// Explicit path to the mise binary
174    ///
175    /// By default, pitchfork searches well-known locations for the mise binary:
176    /// - `~/.local/bin/mise`
177    /// - `~/.cargo/bin/mise`
178    /// - `/usr/local/bin/mise`
179    /// - `/opt/homebrew/bin/mise`
180    ///
181    /// Set this to an absolute path if mise is installed elsewhere.
182    #[usage(env = "PITCHFORK_MISE_BIN", default = "")]
183    pub mise_bin: String,
184
185    /// Shell command used to execute daemon run scripts
186    ///
187    /// Controls the shell used to execute daemon `run` commands.
188    ///
189    /// The value is split with `shell_words::split` into a program and arguments,
190    /// then the daemon's `run` string is appended verbatim as the final argument
191    /// (passed to the shell's command flag, e.g. `sh -c "<run>"`).
192    ///
193    /// This means the `run` string is interpreted directly by the shell, so
194    /// variable expansion (`$VAR`), globs (`*.txt`), pipes (`|`), and command
195    /// chaining (`&&`) all work as expected.
196    ///
197    /// **Common configurations:**
198    /// - `"sh -c"` — Default, POSIX shell
199    /// - `"sh -o errexit -o pipefail -c"` — Exit on error, fail on pipe failure
200    /// - `"bash -c"` — Use bash instead of sh
201    ///
202    /// When `mise = true` is enabled for a daemon, the shell wraps inside
203    /// `mise x --`, e.g. `mise x -- sh -c "<run>"`.
204    #[usage(env = "PITCHFORK_SHELL", default = "sh -c")]
205    pub shell: String,
206
207    /// Show timestamps in startup log output
208    ///
209    /// When enabled, pitchfork prefixes each startup log line and result line
210    /// with a timestamp (e.g. `19:03:15`), making it easier to see how long
211    /// each daemon took to start.
212    ///
213    /// When disabled (default), a dim bullet (`•`) is used instead to keep
214    /// the output compact and aligned with the spinner / status icons.
215    #[usage(env = "PITCHFORK_STARTUP_LOG_TIMESTAMPS", default = false)]
216    pub startup_log_timestamps: bool,
217
218    /// Default readiness delay in seconds when a daemon has no ready check configured
219    ///
220    /// When a daemon has no other readiness check (output, HTTP, port, command),
221    /// pitchfork waits this long before considering it ready. Daemons can
222    /// override this with their own `ready_delay` setting.
223    #[usage(env = "PITCHFORK_READY_DELAY", default = "3s", ty = "duration")]
224    pub ready_delay: String,
225
226    /// Enable git worktree / jj workspace auto-discovery
227    ///
228    /// When enabled (default), pitchfork discovers git worktrees and jj workspaces for proxy
229    /// slug routing and supervisor config discovery. Each worktree gets its own namespace.
230    ///
231    /// Set to `false` to disable all worktree/workspace discovery. The deprecated
232    /// `PITCHFORK_PROXY_WORKTREE` environment variable remains an alias during migration.
233    #[usage(
234        env = "PITCHFORK_WORKTREE",
235        deprecated_env("PITCHFORK_PROXY_WORKTREE"),
236        alias("proxy.worktree"),
237        default = true
238    )]
239    pub worktree: bool,
240}
241
242/// The `ipc.*` (inter-process communication) settings.
243#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
244#[usage(prefix = "ipc")]
245pub struct SettingsIpc {
246    /// Number of connection retry attempts
247    ///
248    /// How many times to retry connecting to the supervisor before giving up.
249    /// Each attempt uses exponential backoff between `connect_min_delay` and `connect_max_delay`.
250    #[usage(env = "PITCHFORK_IPC_CONNECT_ATTEMPTS", default = 5)]
251    pub connect_attempts: i64,
252
253    /// Maximum delay between connection retries
254    ///
255    /// The maximum delay between connection retry attempts.
256    /// Exponential backoff will not exceed this value.
257    #[usage(
258        env = "PITCHFORK_IPC_CONNECT_MAX_DELAY",
259        default = "1s",
260        ty = "duration"
261    )]
262    pub connect_max_delay: String,
263
264    /// Minimum delay between connection retries
265    ///
266    /// The initial delay between connection retry attempts.
267    /// The actual delay increases exponentially up to `connect_max_delay`.
268    #[usage(
269        env = "PITCHFORK_IPC_CONNECT_MIN_DELAY",
270        default = "100ms",
271        ty = "duration"
272    )]
273    pub connect_min_delay: String,
274
275    /// Maximum IPC requests per second per connection
276    ///
277    /// Rate limiting for IPC connections to prevent local DoS attacks.
278    /// Uses a sliding window algorithm.
279    ///
280    /// Most users won't need to change this. Increase if you have automated
281    /// tools making many rapid requests to the supervisor.
282    #[usage(env = "PITCHFORK_IPC_RATE_LIMIT", default = 100)]
283    pub rate_limit: i64,
284
285    /// Rate limit sliding window duration
286    ///
287    /// The time window for rate limiting calculations.
288    /// `rate_limit` requests are allowed within each window.
289    #[usage(
290        env = "PITCHFORK_IPC_RATE_LIMIT_WINDOW",
291        default = "1s",
292        ty = "duration"
293    )]
294    pub rate_limit_window: String,
295
296    /// Default timeout for IPC requests
297    ///
298    /// Maximum time to wait for a response from the supervisor for most operations.
299    ///
300    /// Note: Daemon start operations may use a longer timeout calculated from
301    /// the daemon's `ready_delay` setting plus a buffer.
302    #[usage(env = "PITCHFORK_IPC_REQUEST_TIMEOUT", default = "5s", ty = "duration")]
303    pub request_timeout: String,
304}
305
306/// The `logs.archive_hook.*` settings.
307#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
308#[usage(prefix = "logs.archive_hook")]
309pub struct SettingsLogsArchiveHook {
310    /// Maximum log entries per archive hook invocation
311    ///
312    /// Log entries selected for pruning are passed to the archive hook in batches of
313    /// this size. Smaller batches use less memory and are easier to retry, while larger
314    /// batches reduce hook invocation overhead.
315    #[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_BATCH_SIZE", default = 1000)]
316    pub batch_size: i64,
317
318    /// Command to run before retention deletes old log entries
319    ///
320    /// When set, the given command is invoked before log entries are permanently
321    /// pruned by retention. The command receives the entries about to be deleted as
322    /// JSON Lines (JSONL) on stdin. Each line is an object with the fields:
323    ///
324    /// - `id`: the SQLite row id
325    /// - `daemon_id`: the qualified daemon id (e.g. `"myproject/api"`)
326    /// - `timestamp`: the log timestamp in RFC 3339 format
327    /// - `message`: the raw log message text
328    ///
329    /// The following environment variables are also available:
330    ///
331    /// - `PITCHFORK_DAEMON_ID`: the qualified daemon id
332    /// - `PITCHFORK_ARCHIVE_REASON`: either `"age"` or `"count"`
333    ///
334    /// If the command exits with a non-zero status, the pruning is skipped for that
335    /// batch. This prevents data loss when the archive destination is unavailable.
336    ///
337    /// **Examples:**
338    ///
339    /// ```toml
340    /// [logs.archive_hook]
341    /// command = "gzip -c >> /var/log/pitchfork/archive.jsonl.gz"
342    /// ```
343    ///
344    /// ```toml
345    /// [logs.archive_hook]
346    /// command = "aws s3 cp - s3://my-bucket/pitchfork-logs/"
347    /// ```
348    #[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_COMMAND", default = "")]
349    pub command: String,
350}
351
352/// The `logs.*` settings.
353#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
354#[usage(prefix = "logs")]
355pub struct SettingsLogs {
356    #[usage(flatten)]
357    pub archive_hook: SettingsLogsArchiveHook,
358
359    /// Count-based log retention (e.g. 10000)
360    ///
361    /// Maximum number of log entries to keep per daemon in the SQLite log store.
362    ///
363    /// When set, only the most recent N log entries are retained. Older entries are
364    /// automatically pruned.
365    ///
366    /// When set to `0` (default), no count-based pruning is performed. You can combine
367    /// this with `time_retention` to enforce both a time limit and a line count limit.
368    ///
369    /// Logs are pruned automatically by the supervisor during its interval watcher
370    /// cycle (no more than once per hour). No manual rotation command is needed.
371    #[usage(env = "PITCHFORK_LOG_LINE_RETENTION", default = 0)]
372    pub line_retention: i64,
373
374    /// Default log format for daemons (json | logfmt | text)
375    #[usage(env = "PITCHFORK_LOG_FORMAT", default = "text")]
376    pub log_format: String,
377
378    /// Time-based log retention duration (e.g. '7d', '30d')
379    ///
380    /// Maximum age of log entries to keep in the SQLite log store.
381    ///
382    /// When set, log entries older than this duration are automatically pruned.
383    /// Examples: `"7d"` for 7 days, `"30d"` for 30 days, `"1h"` for 1 hour.
384    ///
385    /// When empty (default), no time-based pruning is performed. You can combine
386    /// this with `line_retention` to enforce both a time limit and a line count limit.
387    ///
388    /// Logs are pruned automatically by the supervisor during its interval watcher
389    /// cycle (no more than once per hour). No manual rotation command is needed.
390    #[usage(env = "PITCHFORK_LOG_TIME_RETENTION", default = "", ty = "duration")]
391    pub time_retention: String,
392
393    /// Show timestamps in log output
394    ///
395    /// When enabled (default), pitchfork prefixes each log line with a timestamp
396    /// (e.g. `07-10 10:30:00`).
397    ///
398    /// When disabled, timestamps are omitted from `pitchfork logs` output. This is
399    /// useful when piping logs to tools like `lnav` that expect raw JSON or when
400    /// you want to process log output without the timestamp prefix.
401    ///
402    /// Can be overridden per-invocation with `pitchfork logs --no-timestamp`.
403    #[usage(env = "PITCHFORK_LOG_TIMESTAMP", default = true)]
404    pub timestamp: bool,
405
406    /// strftime format for log timestamps in `pitchfork logs` output
407    ///
408    /// Controls the date/time format used when displaying timestamps in `pitchfork logs`
409    /// output. Uses chrono strftime syntax.
410    ///
411    /// Common format specifiers:
412    /// - `%Y` — full year (2024)
413    /// - `%m` — month (01-12)
414    /// - `%d` — day (01-31)
415    /// - `%H` — hour (00-23)
416    /// - `%M` — minute (00-59)
417    /// - `%S` — second (00-59)
418    ///
419    /// Examples:
420    /// - `%m-%d %H:%M:%S` — `07-10 10:30:00` (default)
421    /// - `%Y-%m-%d %H:%M:%S` — `2024-07-10 10:30:00`
422    /// - `%H:%M:%S` — `10:30:00` (time only)
423    /// - `%Y/%m/%d %H:%M` — `2024/07/10 10:30`
424    ///
425    /// Only affects the text display output, not `--json` or `--raw` modes.
426    #[usage(env = "PITCHFORK_LOG_TIMESTAMP_FORMAT", default = "%m-%d %H:%M:%S")]
427    pub timestamp_format: String,
428}
429
430/// The `proxy.*` settings.
431#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
432#[usage(prefix = "proxy")]
433pub struct SettingsProxy {
434    /// Automatically start daemons when accessed via proxy URL
435    ///
436    /// When enabled (default), visiting a proxy URL for a stopped daemon will
437    /// automatically start that daemon. The browser receives a "Starting…" page
438    /// that refreshes every 2 seconds until the daemon is ready, at which point
439    /// the request is proxied normally.
440    ///
441    /// Set to `false` to disable auto-start and return a plain 502 error for
442    /// stopped daemons (the previous behaviour).
443    #[usage(env = "PITCHFORK_PROXY_AUTO_START", default = true)]
444    pub auto_start: bool,
445
446    /// Maximum time to wait for an auto-started daemon to become ready
447    ///
448    /// When a daemon is auto-started via a proxy request, the proxy waits up to
449    /// this duration for the **entire** auto-start operation to complete — including
450    /// waiting for the daemon's readiness signal and detecting the bound port.
451    ///
452    /// If the daemon does not become ready and bind a port within this timeout,
453    /// the browser receives an error page indicating the startup timed out.
454    ///
455    /// **Examples:**
456    /// - `"15s"` - Shorter timeout for fast-starting services
457    /// - `"30s"` - Default, suitable for most daemons
458    /// - `"60s"` - For daemons with slow initialisation (e.g. large Java apps)
459    #[usage(
460        env = "PITCHFORK_PROXY_AUTO_START_TIMEOUT",
461        default = "30s",
462        ty = "duration"
463    )]
464    pub auto_start_timeout: String,
465
466    /// Automatically install the proxy TLS certificate into the system trust store
467    ///
468    /// When enabled (default), pitchfork automatically installs the proxy's
469    /// self-signed CA certificate into the system trust store during supervisor
470    /// startup, so that browsers and tools trust HTTPS proxy URLs without
471    /// certificate warnings.
472    ///
473    /// On macOS, this triggers a system authorization dialog (Touch ID or password).
474    /// On Linux, this requires write access to the system CA directory (typically
475    /// needs `sudo`).
476    ///
477    /// If auto-trust fails (e.g. due to permissions), it is silently skipped and
478    /// a warning is logged. You can manually install the certificate with:
479    ///   pitchfork proxy trust
480    ///
481    /// Set to `false` to disable auto-trust entirely.
482    #[usage(env = "PITCHFORK_PROXY_AUTO_TRUST", default = true)]
483    pub auto_trust: bool,
484
485    /// Enable the reverse proxy server for daemons
486    ///
487    /// When enabled, pitchfork starts a reverse proxy that routes requests from
488    /// `<slug>.<tld>:<port>` to the daemon's actual listening port.
489    ///
490    /// Only daemons with an explicit `slug` are routable through the proxy.
491    /// No slug = not proxied.
492    ///
493    /// Example: `myapp.localhost:7777` -> `localhost:3000` (daemon with slug = "myapp")
494    #[usage(env = "PITCHFORK_PROXY_ENABLE", default = false)]
495    pub enable: bool,
496
497    /// Bind address for the reverse proxy server
498    ///
499    /// IP address the reverse proxy listens on.
500    ///
501    /// **Security Warning:** The default `127.0.0.1` only allows local connections.
502    /// Setting this to `0.0.0.0` will expose the proxy on every network interface,
503    /// including externally routable ones -- anyone on the same LAN can then reach
504    /// your local daemons.
505    ///
506    /// **Examples:**
507    /// - `"127.0.0.1"` - Local only (default, recommended)
508    /// - `"0.0.0.0"` - All interfaces (use with caution)
509    /// - `"::1"` - IPv6 loopback
510    #[usage(env = "PITCHFORK_PROXY_HOST", default = "127.0.0.1")]
511    pub host: String,
512
513    /// Enable HTTPS for the reverse proxy
514    ///
515    /// When enabled (default), the proxy serves HTTPS instead of HTTP.
516    ///
517    /// You must also configure `proxy.tls_cert` and `proxy.tls_key`, or pitchfork
518    /// will auto-generate a self-signed certificate stored in the state directory.
519    ///
520    /// Set to `false` to use plain HTTP (e.g. for simple local development).
521    #[usage(env = "PITCHFORK_PROXY_HTTPS", default = true)]
522    pub https: bool,
523
524    /// Enable LAN mode for the reverse proxy
525    ///
526    /// When enabled, the proxy switches to the `.local` TLD and publishes slug
527    /// hostnames via mDNS so that other devices on the same network can reach
528    /// your daemons (e.g. `myapp.local` from a phone or another computer).
529    ///
530    /// LAN mode:
531    /// - Forces `proxy.tld` to `local` (mDNS requirement)
532    /// - Publishes each slug as an mDNS address record (`<slug>.local → <LAN-IP>`)
533    /// - Binds the proxy to `0.0.0.0` instead of `127.0.0.1` (overridable via `proxy.host`)
534    /// - Auto-detects your LAN IP and re-publishes mDNS records if it changes
535    ///
536    /// Other devices must trust the pitchfork CA certificate to use HTTPS.
537    /// Run `pitchfork proxy trust` on each device, or use `proxy.https = false`.
538    #[usage(env = "PITCHFORK_PROXY_LAN", default = false)]
539    pub lan: bool,
540
541    /// Pin a specific LAN IP address instead of auto-detecting
542    ///
543    /// When set, skips auto-detection and uses this IP for mDNS publishing.
544    /// Implies `proxy.lan = true` if a non-empty value is provided.
545    #[usage(env = "PITCHFORK_PROXY_LAN_IP", default = "")]
546    pub lan_ip: String,
547
548    /// Port the reverse proxy server listens on
549    ///
550    /// The port pitchfork's reverse proxy binds to. Must be in the range 1-65535.
551    ///
552    /// Default is 443 (standard HTTPS port) since the proxy defaults to HTTPS.
553    /// Users can override this to any port (e.g. 7777) to avoid requiring
554    /// elevated privileges.
555    ///
556    /// Ports below 1024 require the supervisor to be started with elevated
557    /// privileges (e.g. `sudo pitchfork supervisor start`).
558    #[usage(env = "PITCHFORK_PROXY_PORT", default = 443)]
559    pub port: i64,
560
561    /// Automatically sync slug hostnames to /etc/hosts
562    ///
563    /// When enabled (default), pitchfork automatically adds entries to `/etc/hosts`
564    /// for registered slugs (e.g. `127.0.0.1 myapp.localhost`) so that browsers
565    /// can resolve them.
566    ///
567    /// This is needed because Safari does not auto-resolve `.localhost` subdomains,
568    /// and custom TLDs (e.g. `.test`) always require DNS entries.
569    ///
570    /// Entries are managed in a marked block in `/etc/hosts` and cleaned up when
571    /// the proxy shuts down. Writing to `/etc/hosts` may require `sudo`.
572    ///
573    /// Set to `false` to disable automatic hosts file management. You will need to
574    /// configure DNS resolution yourself (e.g. `dnsmasq`, `/etc/resolver/` on macOS).
575    #[usage(env = "PITCHFORK_PROXY_SYNC_HOSTS", default = true)]
576    pub sync_hosts: bool,
577
578    /// Top-level domain used for proxy URLs
579    ///
580    /// The TLD appended to daemon hostnames in proxy URLs.
581    ///
582    /// With the default `localhost`, daemon URLs look like:
583    ///   `myapp.localhost:7777`  (for a daemon with slug = "myapp")
584    ///
585    /// For custom TLDs (e.g. `test`), you need wildcard DNS resolution.
586    /// On macOS, you can use dnsmasq or add entries to `/etc/resolver/`.
587    #[usage(env = "PITCHFORK_PROXY_TLD", default = "localhost")]
588    pub tld: String,
589
590    /// Path to TLS certificate file (PEM format) for HTTPS proxy
591    ///
592    /// Path to a PEM-encoded TLS certificate file used when `proxy.https = true`.
593    ///
594    /// If left empty and `proxy.https = true`, pitchfork will auto-generate a
595    /// self-signed certificate and store it in `$PITCHFORK_STATE_DIR/proxy/cert.pem`.
596    #[usage(env = "PITCHFORK_PROXY_TLS_CERT", default = "")]
597    pub tls_cert: String,
598
599    /// Path to TLS private key file (PEM format) for HTTPS proxy
600    ///
601    /// Path to a PEM-encoded private key file used when `proxy.https = true`.
602    ///
603    /// If left empty and `proxy.https = true`, pitchfork will auto-generate a
604    /// self-signed key and store it in `$PITCHFORK_STATE_DIR/proxy/key.pem`.
605    #[usage(env = "PITCHFORK_PROXY_TLS_KEY", default = "")]
606    pub tls_key: String,
607
608    /// Enable wildcard subdomain matching for proxy routes
609    ///
610    /// When enabled (default), requests for subdomains of a registered slug
611    /// will fall back to the parent slug's daemon.
612    ///
613    /// For example, with slug "myapp":
614    /// - `myapp.localhost` → exact match (always works)
615    /// - `tenant.myapp.localhost` → wildcard fallback to "myapp"
616    ///
617    /// This is useful for multi-tenant apps where each tenant gets a unique
618    /// subdomain (e.g. `acme.myapp.localhost`, `globex.myapp.localhost`) but
619    /// all share the same backend server.
620    ///
621    /// Set to `false` to require exact hostname matches only.
622    #[usage(env = "PITCHFORK_PROXY_WILDCARD", default = true)]
623    pub wildcard: bool,
624}
625
626/// The `supervisor.*` settings.
627#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
628#[usage(prefix = "supervisor")]
629pub struct SettingsSupervisor {
630    /// Automatically start the supervisor when a client command needs it
631    ///
632    /// When enabled (default), commands such as `pitchfork start`, `pitchfork list`,
633    /// the TUI, and shell activation start a background supervisor automatically when
634    /// one is not already running.
635    ///
636    /// Disable this when the supervisor is managed by systemd, launchd, or another
637    /// service manager:
638    ///
639    /// ```toml
640    /// [settings.supervisor]
641    /// auto_start = false
642    /// ```
643    ///
644    /// With auto-start disabled, client commands wait for the configured IPC
645    /// connection attempts and then fail with an actionable error instead of spawning
646    /// an unmanaged supervisor. Explicit `pitchfork supervisor start` and
647    /// `pitchfork supervisor run` commands are unaffected.
648    #[usage(env = "PITCHFORK_SUPERVISOR_AUTO_START", default = true)]
649    pub auto_start: bool,
650
651    /// Reconcile orphaned daemon processes when supervisor starts
652    ///
653    /// When enabled, the supervisor scans the state file on startup for daemon
654    /// processes left behind by a previous supervisor instance that was killed
655    /// unexpectedly (for example, with `kill -9`) and reconciles them according
656    /// to `supervisor.orphan_policy` (re-adopt by default, or terminate).
657    ///
658    /// Before acting, the recorded process identity (PID plus kernel start
659    /// time) is verified so that a PID recycled by the OS to an unrelated process
660    /// is never adopted or killed — in that case only the stale state entry is
661    /// cleared. When terminating, Linux and Windows also pin that identity with a
662    /// pidfd or open process handle, so a recycled PID cannot be signaled. If the
663    /// identity cannot be verified or pinned, reconciliation fails closed: the
664    /// live process and its running state are retained rather than risk acting on
665    /// the wrong process or allowing a duplicate instance to start.
666    ///
667    /// Disabling this leaves orphaned processes and their state entries
668    /// completely untouched. This is a legacy escape hatch; prefer
669    /// `orphan_policy = "adopt"` (the default), which keeps daemons running
670    /// across a supervisor crash while resuming supervision.
671    #[usage(env = "PITCHFORK_CLEANUP_ORPHANS", default = true)]
672    pub cleanup_orphans: bool,
673
674    /// Enable container/PID1 mode for running inside Docker containers
675    ///
676    /// When enabled, pitchfork operates as a proper PID 1 process inside a container:
677    /// - Installs a SIGCHLD handler to reap all orphaned/zombie child processes
678    /// - Routes SIGTERM/SIGINT through the graceful shutdown sequence
679    ///
680    /// This is essential when running pitchfork as the entrypoint of a Docker container,
681    /// where PID 1 must reap zombie processes to prevent process table exhaustion.
682    ///
683    /// Can also be enabled via the `--container` CLI flag on `pitchfork supervisor run`.
684    #[usage(env = "PITCHFORK_CONTAINER", default = false)]
685    pub container: bool,
686
687    /// Consecutive CPU-over-limit samples before killing a daemon
688    ///
689    /// When a daemon has `cpu_limit` configured, the supervisor checks CPU usage at
690    /// each interval tick. To avoid killing daemons during transient spikes (e.g. JIT
691    /// warm-up, burst responses), the process is only killed after this many
692    /// **consecutive** samples exceed the limit. A single sample below the limit
693    /// resets the counter.
694    ///
695    /// **Examples:**
696    /// - `1` - Kill immediately on first over-limit sample (no grace period)
697    /// - `3` - Require 3 consecutive over-limit samples (default)
698    /// - `5` - More tolerant of short bursts
699    ///
700    /// With the default interval of `10s`, a threshold of `3` means a daemon must
701    /// exceed its CPU limit for ~30 seconds before being killed.
702    #[usage(env = "PITCHFORK_CPU_VIOLATION_THRESHOLD", default = 3)]
703    pub cpu_violation_threshold: i64,
704
705    /// Interval for checking cron schedules
706    ///
707    /// How often to check if any cron-scheduled daemons should be triggered.
708    ///
709    /// The default of 10 seconds supports sub-minute cron schedules.
710    /// Increase for lower resource usage if you don't need fine-grained scheduling.
711    #[usage(
712        env = "PITCHFORK_CRON_CHECK_INTERVAL",
713        default = "10s",
714        ty = "duration"
715    )]
716    pub cron_check_interval: String,
717
718    /// File watch debounce duration
719    ///
720    /// When using `watch` patterns to auto-restart daemons on file changes,
721    /// this controls how long to wait after the last change before triggering
722    /// a restart.
723    ///
724    /// This prevents rapid restart cycles when many files change at once
725    /// (e.g., during a build or git checkout).
726    #[usage(env = "PITCHFORK_FILE_WATCH_DEBOUNCE", default = "1s", ty = "duration")]
727    pub file_watch_debounce: String,
728
729    /// Timeout for HTTP ready checks
730    ///
731    /// Maximum time to wait for a response when checking `ready_http` endpoints.
732    ///
733    /// Increase if your services take a while to respond during startup.
734    #[usage(env = "PITCHFORK_HTTP_CLIENT_TIMEOUT", default = "5s", ty = "duration")]
735    pub http_client_timeout: String,
736
737    /// Daemon log buffer flush interval
738    ///
739    /// How often daemon log output is flushed to disk.
740    /// Lower values mean logs appear faster in the UI but may impact performance.
741    #[usage(
742        env = "PITCHFORK_LOG_FLUSH_INTERVAL",
743        default = "500ms",
744        ty = "duration"
745    )]
746    pub log_flush_interval: String,
747
748    /// What to do with live orphaned daemons on supervisor startup: adopt or kill
749    ///
750    /// When the supervisor starts and finds daemons in the state file whose
751    /// processes are still alive from a previous supervisor instance that died
752    /// uncleanly, this policy decides what happens (after the process identity
753    /// is verified via PID plus kernel start time):
754    ///
755    /// - `adopt` (default): keep the process running and resume supervision.
756    ///   The daemon keeps its state (status, ports, proxy routing) and is
757    ///   monitored by polling. Log capture is unaffected, because a daemon's
758    ///   output is read by a sibling sink process rather than by the supervisor,
759    ///   so it continues uninterrupted across the crash. Exit codes of adopted
760    ///   daemons cannot be observed, though;
761    ///   an adopted daemon that dies unexpectedly is marked `errored` with an
762    ///   unknown exit code, which makes it eligible for its configured retries.
763    /// - `kill`: terminate the orphaned process group so the new supervisor
764    ///   starts with a clean slate, matching pre-adoption behavior.
765    ///
766    /// Daemons whose recorded PID is dead, or whose PID now belongs to a
767    /// different process, have their state reset under either policy. If the
768    /// process identity cannot be verified, reconciliation fails closed and
769    /// retains the running state without adopting or killing.
770    ///
771    /// The same policy applies when the interval watcher finds a running daemon
772    /// that has lost its monitor at runtime.
773    ///
774    /// This setting has no effect when `cleanup_orphans` is disabled.
775    #[usage(env = "PITCHFORK_ORPHAN_POLICY", default = "adopt")]
776    pub orphan_policy: String,
777
778    /// Maximum port increment attempts when auto_bump_port is enabled
779    ///
780    /// When `auto_bump_port = true` is set on a daemon, pitchfork will try incrementing
781    /// all of the daemon's ports by the same offset to find a free range. This setting
782    /// controls how many offsets are tried before giving up with an error.
783    ///
784    /// For example, with `port = [3000]` and `port_bump_attempts = 10`, pitchfork will
785    /// try ports 3000, 3001, 3002, ... up to 3009 before reporting failure.
786    ///
787    /// This is a global default; individual daemons can override it with
788    /// `port_bump_attempts` in their daemon configuration.
789    #[usage(env = "PITCHFORK_PORT_BUMP_ATTEMPTS", default = 10)]
790    pub port_bump_attempts: i64,
791
792    /// Interval between ready checks (HTTP, TCP, command)
793    ///
794    /// How often to poll when checking if a daemon is ready using:
795    /// - `ready_http` - HTTP health endpoint
796    /// - `ready_port` - TCP port listening
797    /// - `ready_cmd` - Shell command exit code
798    ///
799    /// Lower values detect readiness faster but use more resources.
800    #[usage(
801        env = "PITCHFORK_READY_CHECK_INTERVAL",
802        default = "500ms",
803        ty = "duration"
804    )]
805    pub ready_check_interval: String,
806
807    /// Delay between stop and start during restart
808    ///
809    /// Brief pause after stopping a daemon before starting it again.
810    /// Helps ensure resources (like ports) are fully released.
811    #[usage(env = "PITCHFORK_RESTART_DELAY", default = "100ms", ty = "duration")]
812    pub restart_delay: String,
813
814    /// Maximum time to wait for daemon to stop gracefully
815    ///
816    /// When stopping a daemon, pitchfork sends SIGTERM and waits this long
817    /// for the process to exit gracefully before sending SIGKILL.
818    ///
819    /// Increase for daemons that need time to clean up (e.g., flush data).
820    #[usage(env = "PITCHFORK_STOP_TIMEOUT", default = "5s", ty = "duration")]
821    pub stop_timeout: String,
822
823    /// Default user to run daemon processes as
824    ///
825    /// Default Unix user for daemon processes spawned by the supervisor.
826    ///
827    /// When set, all daemons run as this user unless an individual daemon sets
828    /// `user = "..."`. The value may be a username (for example `"postgres"`) or
829    /// a numeric UID (for example `"501"`).
830    ///
831    /// If unset and the supervisor is running as root via `sudo`, daemons default to
832    /// the sudo-calling user from `SUDO_UID`/`SUDO_GID` instead of running as root.
833    #[usage(env = "PITCHFORK_USER", default = "")]
834    pub user: String,
835
836    /// File watcher config refresh interval
837    ///
838    /// How often the supervisor refreshes file watch configuration when using `watch` patterns.
839    ///
840    /// This controls how quickly newly started/stopped daemons with watch patterns are reflected
841    /// in the active watcher set.
842    ///
843    /// For polling watcher cadence, use `supervisor.watch_poll_interval`.
844    ///
845    /// Lower values react faster to configuration/runtime changes but use more CPU.
846    /// The default `"10s"` is appropriate for most environments.
847    #[usage(
848        env = "PITCHFORK_WATCH_INTERVAL",
849        deprecated_env("PITCHFORK_WATCH_INTERVAL_MS"),
850        default = "10s",
851        ty = "duration"
852    )]
853    pub watch_interval: String,
854
855    /// Polling watcher filesystem scan interval
856    ///
857    /// How often polling-based file watchers scan for changes.
858    ///
859    /// This applies when daemon `watch_mode` is `poll`, or when `watch_mode = "auto"`
860    /// falls back to polling because native watchers are unavailable.
861    ///
862    /// Lower values detect changes faster but use more CPU and I/O.
863    /// `"100ms"` is useful for highly interactive workflows;
864    /// `"500ms"` is a practical default for remote/networked filesystems.
865    #[usage(
866        env = "PITCHFORK_WATCH_POLL_INTERVAL",
867        default = "500ms",
868        ty = "duration"
869    )]
870    pub watch_poll_interval: String,
871}
872
873/// The `tui.*` (terminal UI) settings.
874#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
875#[usage(prefix = "tui")]
876pub struct SettingsTui {
877    /// Status message display duration
878    ///
879    /// How long status messages (like "Daemon started") remain visible
880    /// in the TUI before automatically clearing.
881    #[usage(
882        env = "PITCHFORK_TUI_MESSAGE_DURATION",
883        default = "3s",
884        ty = "duration"
885    )]
886    pub message_duration: String,
887
888    /// Daemon list refresh interval
889    ///
890    /// How often the TUI refreshes the daemon list and status information.
891    ///
892    /// Lower values provide more responsive updates but may increase CPU usage,
893    /// especially with many daemons.
894    ///
895    /// **Recommended values:**
896    /// - `"1s"` - More responsive
897    /// - `"2s"` - Default, balanced
898    /// - `"5s"` - Lower resource usage
899    #[usage(env = "PITCHFORK_TUI_REFRESH_RATE", default = "2s", ty = "duration")]
900    pub refresh_rate: String,
901
902    /// Number of stat samples to keep for graphs
903    ///
904    /// How many CPU/memory stat samples to keep for each daemon's graph.
905    /// With the default refresh rate of 2s, 60 samples = ~2 minutes of history.
906    ///
907    /// Increase for longer history in graphs, at the cost of more memory.
908    #[usage(env = "PITCHFORK_TUI_STAT_HISTORY", default = 60)]
909    pub stat_history: i64,
910
911    /// Event loop tick rate
912    ///
913    /// How often the TUI checks for keyboard input and other events.
914    /// This affects input responsiveness.
915    ///
916    /// Most users won't need to change this. Lower values make the UI more
917    /// responsive but use more CPU.
918    #[usage(env = "PITCHFORK_TUI_TICK_RATE", default = "100ms", ty = "duration")]
919    pub tick_rate: String,
920}
921
922/// The `web.*` (web UI) settings.
923#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
924#[usage(prefix = "web")]
925pub struct SettingsWeb {
926    /// Automatically start web UI when supervisor starts
927    ///
928    /// When enabled, the web UI server will automatically start alongside the supervisor.
929    ///
930    /// By default, this is disabled. You can also start the web UI manually with:
931    /// ```text
932    /// pitchfork supervisor start --web-port=3120
933    /// ```
934    #[usage(env = "PITCHFORK_WEB_AUTO_START", default = false)]
935    pub auto_start: bool,
936
937    /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
938    ///
939    /// Serves the web UI under a sub-path prefix, useful when running behind a reverse
940    /// proxy that routes a path prefix to pitchfork.
941    ///
942    /// **Examples:**
943    /// - `""` - Serve at root `/` (default)
944    /// - `"ps"` - Serve at `/ps/`
945    /// - `"tools/pitchfork"` - Serve at `/tools/pitchfork/`
946    ///
947    /// Equivalent to the `--web-path` CLI flag. The CLI flag takes priority over this setting.
948    #[usage(env = "PITCHFORK_WEB_PATH", default = "")]
949    pub base_path: String,
950
951    /// Web server bind address
952    ///
953    /// IP address for the web UI to listen on.
954    ///
955    /// **Security Warning:** The default `127.0.0.1` only allows local connections.
956    /// Setting this to `0.0.0.0` will expose the web UI to your network.
957    ///
958    /// **Examples:**
959    /// - `"127.0.0.1"` - Local only (default, recommended)
960    /// - `"0.0.0.0"` - All interfaces (use with caution)
961    /// - `"192.168.1.100"` - Specific interface
962    #[usage(env = "PITCHFORK_WEB_BIND_ADDRESS", default = "127.0.0.1")]
963    pub bind_address: String,
964
965    /// Default web server port
966    ///
967    /// The port number for the web UI. If this port is in use, pitchfork will
968    /// try subsequent ports up to `port_attempts` times.
969    #[usage(env = "PITCHFORK_WEB_BIND_PORT", default = 3120)]
970    pub bind_port: i64,
971
972    /// Initial number of log lines to display
973    ///
974    /// How many lines of logs to show initially when viewing daemon logs in the web UI.
975    /// More lines means slower initial load but more history visible.
976    #[usage(env = "PITCHFORK_WEB_LOG_LINES", default = 100)]
977    pub log_lines: i64,
978
979    /// Number of ports to try if default is in use
980    ///
981    /// If the default port is occupied, pitchfork will try this many consecutive
982    /// ports before giving up.
983    ///
984    /// For example, with `bind_port = 3120` and `port_attempts = 10`,
985    /// it will try ports 3120, 3121, 3122, ... up to 3129.
986    #[usage(env = "PITCHFORK_WEB_PORT_ATTEMPTS", default = 10)]
987    pub port_attempts: i64,
988
989    /// Server-Sent Events poll interval for log streaming
990    ///
991    /// How often the web UI checks for new log lines when streaming logs.
992    /// Lower values provide more real-time updates but use more resources.
993    #[usage(
994        env = "PITCHFORK_WEB_SSE_POLL_INTERVAL",
995        default = "500ms",
996        ty = "duration"
997    )]
998    pub sse_poll_interval: String,
999}
1000
1001/// Every setting pitchfork has.
1002///
1003/// `SETTINGS_PROPS`, `SETTINGS_REGISTRY`, `read`, and `spec_kdl` are generated
1004/// from these fields; the CLI's emitted spec carries the `config` block
1005/// through `#[usage(config = ...)]` on the root.
1006#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
1007// `file(...)` is intentionally repeatable in usage's configuration DSL.
1008#[allow(clippy::duplicated_attributes)]
1009#[usage(
1010    file(path = "/etc/pitchfork/config.toml", scope = "system", format = "toml"),
1011    file(
1012        path = "~/.config/pitchfork/config.toml",
1013        scope = "global",
1014        format = "toml"
1015    ),
1016    file(
1017        path = ".config/pitchfork.toml",
1018        findup,
1019        scope = "project",
1020        format = "toml"
1021    ),
1022    file(
1023        path = ".config/pitchfork.local.toml",
1024        findup,
1025        scope = "project",
1026        format = "toml"
1027    ),
1028    file(path = "pitchfork.toml", findup, scope = "project", format = "toml"),
1029    file(
1030        path = "pitchfork.local.toml",
1031        findup,
1032        scope = "project",
1033        format = "toml"
1034    )
1035)]
1036pub struct Settings {
1037    #[usage(flatten)]
1038    pub api: SettingsApi,
1039    #[usage(flatten)]
1040    pub general: SettingsGeneral,
1041    #[usage(flatten)]
1042    pub ipc: SettingsIpc,
1043    #[usage(flatten)]
1044    pub logs: SettingsLogs,
1045    #[usage(flatten)]
1046    pub proxy: SettingsProxy,
1047    #[usage(flatten)]
1048    pub supervisor: SettingsSupervisor,
1049    #[usage(flatten)]
1050    pub tui: SettingsTui,
1051    #[usage(flatten)]
1052    pub web: SettingsWeb,
1053}
1054
1055impl Default for Settings {
1056    /// The declared defaults, read the same way any other resolution is.
1057    fn default() -> Self {
1058        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1059            .expect("no layers were given, so there is nothing to fail");
1060        Settings::read(&resolved).expect("every pitchfork setting has a declared default")
1061    }
1062}
1063
1064/// Generate the `Duration` convenience getters the rest of the codebase uses
1065/// (e.g. `settings().general_autostop_delay()`), each parsing its humantime
1066/// string field and silently falling back to the schema default. Invalid
1067/// values were already warned about once at load time.
1068macro_rules! duration_getters {
1069    ($($name:ident => $group:ident . $field:ident, $default:literal;)+) => {
1070        impl Settings {
1071            $(
1072                #[doc = concat!("Get `", stringify!($group), ".", stringify!($field), "` as Duration")]
1073                #[allow(dead_code)]
1074                pub fn $name(&self) -> std::time::Duration {
1075                    Self::parse_duration(&self.$group.$field).unwrap_or_else(|| {
1076                        humantime::parse_duration($default)
1077                            .unwrap_or(std::time::Duration::from_secs(1))
1078                    })
1079                }
1080            )+
1081        }
1082    };
1083}
1084
1085duration_getters! {
1086    general_autostop_delay => general.autostop_delay, "1m";
1087    general_interval => general.interval, "10s";
1088    general_ready_delay => general.ready_delay, "3s";
1089    ipc_connect_max_delay => ipc.connect_max_delay, "1s";
1090    ipc_connect_min_delay => ipc.connect_min_delay, "100ms";
1091    ipc_rate_limit_window => ipc.rate_limit_window, "1s";
1092    ipc_request_timeout => ipc.request_timeout, "5s";
1093    logs_time_retention => logs.time_retention, "";
1094    proxy_auto_start_timeout => proxy.auto_start_timeout, "30s";
1095    supervisor_cron_check_interval => supervisor.cron_check_interval, "10s";
1096    supervisor_file_watch_debounce => supervisor.file_watch_debounce, "1s";
1097    supervisor_http_client_timeout => supervisor.http_client_timeout, "5s";
1098    supervisor_log_flush_interval => supervisor.log_flush_interval, "500ms";
1099    supervisor_ready_check_interval => supervisor.ready_check_interval, "500ms";
1100    supervisor_restart_delay => supervisor.restart_delay, "100ms";
1101    supervisor_stop_timeout => supervisor.stop_timeout, "5s";
1102    supervisor_watch_interval => supervisor.watch_interval, "10s";
1103    supervisor_watch_poll_interval => supervisor.watch_poll_interval, "500ms";
1104    tui_message_duration => tui.message_duration, "3s";
1105    tui_refresh_rate => tui.refresh_rate, "2s";
1106    tui_tick_rate => tui.tick_rate, "100ms";
1107    web_sse_poll_interval => web.sse_poll_interval, "500ms";
1108}
1109
1110impl Settings {
1111    /// Resolve `general.ready_delay` as whole seconds.
1112    ///
1113    /// The ready-check pipeline (RunOptions/IPC/supervisor) models the delay
1114    /// in whole seconds. Reject subsecond values that would otherwise be
1115    /// silently truncated to a zero delay by `as_secs()`.
1116    pub fn general_ready_delay_secs(&self) -> Result<u64, String> {
1117        let delay = self.general_ready_delay();
1118        if delay.subsec_nanos() != 0 {
1119            return Err(format!(
1120                "settings.general.ready_delay must be a whole number of seconds, got \"{}\"",
1121                self.general.ready_delay
1122            ));
1123        }
1124        Ok(delay.as_secs())
1125    }
1126}
1127
1128impl Settings {
1129    /// Load settings from pitchfork.toml files, then overlay environment variables.
1130    /// Settings are loaded from all pitchfork.toml files in precedence order:
1131    /// 1. System-level: /etc/pitchfork/config.toml
1132    /// 2. User-level: ~/.config/pitchfork/config.toml
1133    /// 3. Project-level: pitchfork.toml files from root to current directory
1134    ///
1135    /// Environment variables override all file-based settings.
1136    ///
1137    /// The global [`settings()`] accessor resolves through
1138    /// [`Settings::resolve_from_dir`] so it can keep the provenance; this
1139    /// stays as the public one-shot entry point.
1140    #[allow(dead_code)]
1141    pub fn load() -> Self {
1142        Self::load_from_dir(&crate::env::CWD)
1143    }
1144
1145    /// Load settings for a specific project directory, then overlay environment variables.
1146    ///
1147    /// This is used when operating on daemons from registered namespaces whose project
1148    /// settings may differ from those of the invoking process's current directory.
1149    pub fn load_from_dir(start_dir: &Path) -> Self {
1150        Self::resolve_from_dir(start_dir).0
1151    }
1152
1153    /// Resolve settings for `start_dir`, returning both the typed struct and
1154    /// the origin-tracked resolution it was read from (for `pitchfork settings`).
1155    pub(crate) fn resolve_from_dir(start_dir: &Path) -> (Self, Resolved) {
1156        let env_layer = EnvLayer::from_process();
1157        // Highest precedence first, below the environment.
1158        let file_layers = Self::file_layers_from(start_dir);
1159        let mut layers = Layers::new().then(&env_layer);
1160        for layer in &file_layers {
1161            layers = layers.then(layer);
1162        }
1163        let mut resolved = match resolve(Settings::SETTINGS_REGISTRY, layers) {
1164            Ok(resolved) => resolved,
1165            Err(e) => {
1166                // Should not happen: every file was pre-validated above. Fall
1167                // back to env + defaults rather than failing to start.
1168                eprintln!("pitchfork: warning: failed to resolve settings from config files: {e}");
1169                resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env_layer)).unwrap_or_else(
1170                    |_| {
1171                        resolve(Settings::SETTINGS_REGISTRY, Layers::new())
1172                            .expect("resolving only defaults cannot fail")
1173                    },
1174                )
1175            }
1176        };
1177        sanitize_durations(&mut resolved);
1178        for warning in usage_rs::config::explain::warnings(&resolved) {
1179            warn!("{warning}");
1180        }
1181        // Lossy, because the alternative is worse than the problem: `read` is all or nothing,
1182        // so one field the merge could not hand to its type used to cost every *other* setting
1183        // too — `Settings::default()` throws away the environment and every config file over a
1184        // single bad value. Here the offending field falls back to its own declared default and
1185        // nothing else is touched. Warn and keep going is pitchfork's call to make: a
1186        // supervisor that refuses to start because one duration is misspelled is a supervisor
1187        // that took the whole machine's daemons down with it.
1188        let (settings, errors) = Settings::read_lossy(&resolved);
1189        for error in &errors.0 {
1190            warn!("{error}");
1191        }
1192        // Every setting declares a default, so the only way this is `None` is a setting added
1193        // without one — a hole in the declaration rather than anything a user did.
1194        let settings = settings.unwrap_or_else(|| {
1195            warn!("a setting has no value and no default; falling back to built-in defaults");
1196            Settings::default()
1197        });
1198        (settings, resolved)
1199    }
1200
1201    /// The config file layers for `start_dir`, highest precedence first.
1202    ///
1203    /// Project files are found by walking up from `start_dir`; within one
1204    /// directory `pitchfork.local.toml` outranks `pitchfork.toml`, which
1205    /// outranks the same pair under `.config/`, and any file in a nearer
1206    /// directory outranks every file in a farther one. Below the project
1207    /// files come the user-level and system-level configs.
1208    ///
1209    /// Files that exist but cannot be parsed are warned about and skipped,
1210    /// matching the previous loader: a broken file must not stop pitchfork
1211    /// from starting.
1212    fn file_layers_from(start_dir: &Path) -> Vec<FileLayer> {
1213        let mut candidates: Vec<(PathBuf, FileScope)> = xx::file::find_up_all(
1214            start_dir,
1215            &[
1216                "pitchfork.local.toml",
1217                "pitchfork.toml",
1218                ".config/pitchfork.local.toml",
1219                ".config/pitchfork.toml",
1220            ],
1221        )
1222        .into_iter()
1223        .map(|path| (path, FileScope::Project))
1224        .collect();
1225        candidates.push((
1226            crate::env::PITCHFORK_GLOBAL_CONFIG_USER.clone(),
1227            FileScope::Global,
1228        ));
1229        candidates.push((
1230            crate::env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone(),
1231            FileScope::System,
1232        ));
1233        candidates
1234            .into_iter()
1235            .filter(|(path, _)| readable_settings_file(path))
1236            .map(|(path, scope)| FileLayer::at(path, scope).under("settings"))
1237            .collect()
1238    }
1239
1240    /// Parse a duration string (humantime format) to Duration
1241    pub fn parse_duration(s: &str) -> Option<std::time::Duration> {
1242        humantime::parse_duration(s).ok()
1243    }
1244
1245    /// Resolve the mise binary path.
1246    ///
1247    /// If `general.mise_bin` is explicitly set, returns that path.
1248    /// Otherwise, searches well-known install locations:
1249    /// - `~/.local/bin/mise`
1250    /// - `~/.cargo/bin/mise`
1251    /// - `/usr/local/bin/mise`
1252    /// - `/opt/homebrew/bin/mise`
1253    ///
1254    /// Returns `None` if mise cannot be found.
1255    pub fn resolve_mise_bin(&self) -> Option<std::path::PathBuf> {
1256        // Explicit configuration takes priority
1257        if !self.general.mise_bin.is_empty() {
1258            let p = PathBuf::from(&self.general.mise_bin);
1259            if p.is_file() {
1260                return Some(p);
1261            }
1262            warn!(
1263                "mise_bin is set to {:?} but the file does not exist",
1264                self.general.mise_bin
1265            );
1266            return None;
1267        }
1268
1269        // Search well-known install paths
1270        let home = crate::env::HOME_DIR.as_path();
1271        let candidates = [
1272            home.join(".local/bin/mise"),
1273            home.join(".cargo/bin/mise"),
1274            PathBuf::from("/usr/local/bin/mise"),
1275            PathBuf::from("/opt/homebrew/bin/mise"),
1276        ];
1277
1278        candidates.into_iter().find(|p| p.is_file())
1279    }
1280
1281    /// Return `supervisor.port_bump_attempts` as `u32`, clamping out-of-range
1282    /// values to the schema default (10) and zero to 1.
1283    ///
1284    /// This is the single source of truth for the fallback so that call-sites
1285    /// don't each duplicate the hardcoded `10`.
1286    pub fn default_port_bump_attempts(&self) -> u32 {
1287        let v = u32::try_from(self.supervisor.port_bump_attempts).unwrap_or_else(|_| {
1288            warn!(
1289                "supervisor.port_bump_attempts value {} is out of range (0-{}), clamping to 10",
1290                self.supervisor.port_bump_attempts,
1291                u32::MAX
1292            );
1293            10
1294        });
1295        if v == 0 {
1296            warn!("supervisor.port_bump_attempts is 0; defaulting to 1");
1297            1
1298        } else {
1299            v
1300        }
1301    }
1302}
1303
1304/// Whether `path` holds a settings file this loader can hand to a `FileLayer`.
1305///
1306/// Mirrors the previous loader's per-file error handling: a missing file is
1307/// the ordinary case, and a file that exists but cannot be read or parsed —
1308/// or whose `settings` key is not a table — is warned about and skipped
1309/// rather than turned into a startup failure.
1310fn readable_settings_file(path: &Path) -> bool {
1311    if !path.exists() {
1312        return false;
1313    }
1314    let content = match std::fs::read_to_string(path) {
1315        Ok(content) => content,
1316        Err(e) => {
1317            eprintln!(
1318                "pitchfork: warning: failed to read {}: {}",
1319                path.display(),
1320                e
1321            );
1322            return false;
1323        }
1324    };
1325    let table: toml::Table = match content.parse() {
1326        Ok(table) => table,
1327        Err(e) => {
1328            eprintln!(
1329                "pitchfork: warning: failed to parse {}: {}",
1330                path.display(),
1331                e
1332            );
1333            return false;
1334        }
1335    };
1336    match table.get("settings") {
1337        None => true,
1338        Some(toml::Value::Table(_)) => true,
1339        Some(_) => {
1340            eprintln!(
1341                "pitchfork: warning: invalid [settings] in {}: not a table",
1342                path.display()
1343            );
1344            false
1345        }
1346    }
1347}
1348
1349/// Validate every duration-typed setting in a resolution.
1350///
1351/// The registry's `duration` type stores the humantime text as-is, so an
1352/// invalid value would otherwise ride into the struct. This warns once and
1353/// rewrites the value to the schema default through [`Resolved::coerced`],
1354/// so `pitchfork settings get/list` and the typed getters all agree —
1355/// matching the previous loader, which rejected invalid durations at load
1356/// time. A value equal to the declared default is left alone (the
1357/// `logs.time_retention` default is the empty string, meaning "disabled").
1358fn sanitize_durations(resolved: &mut Resolved) {
1359    let registry = Settings::SETTINGS_REGISTRY;
1360    for id in registry.ids() {
1361        let meta = registry.get(id);
1362        if !matches!(meta.ty.inner(), Ty::Duration) {
1363            continue;
1364        }
1365        let Some(Value::String(text)) = resolved.get(id) else {
1366            continue;
1367        };
1368        let default_text = match meta.default {
1369            Some(Const::Str(s)) => s,
1370            _ => "",
1371        };
1372        if text == default_text || humantime::parse_duration(text).is_ok() {
1373            continue;
1374        }
1375        let text = text.clone();
1376        let origin = resolved
1377            .origin(id)
1378            .map(|o| o.describe().to_string())
1379            .unwrap_or_default();
1380        warn!(
1381            "invalid duration {:?} for {} (set by {}), using default",
1382            text, meta.key, origin
1383        );
1384        resolved.coerced(
1385            id,
1386            Value::String(default_text.to_string()),
1387            format!("invalid duration {text:?}; the default stands"),
1388        );
1389    }
1390}
1391
1392/// Global settings instance, kept beside the resolution it was read from
1393/// (RwLock<Arc> to support runtime reload).
1394type SettingsState = (Arc<Settings>, Arc<Resolved>);
1395static SETTINGS: std::sync::RwLock<Option<SettingsState>> = std::sync::RwLock::new(None);
1396
1397fn settings_state() -> SettingsState {
1398    // Fast path: if already initialized, clone the Arc pointers.
1399    {
1400        let lock = SETTINGS.read().unwrap();
1401        if let Some(state) = lock.as_ref() {
1402            return state.clone();
1403        }
1404    }
1405    // Slow path: initialize on first access
1406    let mut lock = SETTINGS.write().unwrap();
1407    if let Some(state) = lock.as_ref() {
1408        return state.clone();
1409    }
1410    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1411    let state = (Arc::new(settings), Arc::new(resolved));
1412    *lock = Some(state.clone());
1413    state
1414}
1415
1416/// Get the global settings instance
1417pub fn settings() -> Arc<Settings> {
1418    settings_state().0
1419}
1420
1421/// The origin-tracked resolution behind [`settings()`], for the settings CLI.
1422pub(crate) fn settings_resolved() -> Arc<Resolved> {
1423    settings_state().1
1424}
1425
1426/// Reload settings from config files.
1427///
1428/// Called when the supervisor receives a ReloadConfig IPC request,
1429/// typically after `pitchfork settings set` modifies a config file.
1430///
1431/// Old Arc references remain valid until all holders drop them,
1432/// so no use-after-free can occur.
1433pub fn reload_settings() {
1434    let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
1435    let mut lock = SETTINGS.write().unwrap();
1436    *lock = Some((Arc::new(settings), Arc::new(resolved)));
1437}
1438
1439// ============================================================================
1440// Partial (all-Option) mirror structs
1441//
1442// These exist for `pitchfork.toml` round-trips: `PitchforkToml` deserializes
1443// its `[settings]` table into `SettingsPartial`, merges per-file overrides,
1444// and serializes it back out (`pitchfork settings set`, `proxy add`, ...).
1445// Settings *resolution* no longer goes through these — usage-config's
1446// origin-tracked merge replaced the apply/merge chain.
1447// ============================================================================
1448
1449macro_rules! settings_partial {
1450    (
1451        $(#[$meta:meta])*
1452        $name:ident {
1453            $(@group $group_field:ident: $group_ty:ty,)*
1454            $($(#[$fdoc:meta])* $field:ident: $ty:ty,)*
1455        }
1456    ) => {
1457        $(#[$meta])*
1458        #[derive(
1459            Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
1460        )]
1461        #[serde(default)]
1462        pub struct $name {
1463            $(
1464                #[serde(default, skip_serializing_if = "is_empty_partial")]
1465                pub $group_field: $group_ty,
1466            )*
1467            $(
1468                $(#[$fdoc])*
1469                #[serde(skip_serializing_if = "Option::is_none", default)]
1470                pub $field: Option<$ty>,
1471            )*
1472        }
1473
1474        #[allow(dead_code)]
1475        impl $name {
1476            /// Whether any field (or nested group field) is set.
1477            pub fn has_any_set(&self) -> bool {
1478                false
1479                $(|| self.$group_field.has_any_set())*
1480                $(|| self.$field.is_some())*
1481            }
1482
1483            pub fn is_empty(&self) -> bool {
1484                !self.has_any_set()
1485            }
1486
1487            /// Merge another partial onto this one.
1488            /// All `Some` values in `other` override the corresponding values in `self`.
1489            pub fn merge_from(&mut self, other: &Self) {
1490                $(self.$group_field.merge_from(&other.$group_field);)*
1491                $(
1492                    if other.$field.is_some() {
1493                        self.$field = other.$field.clone();
1494                    }
1495                )*
1496            }
1497        }
1498    };
1499}
1500
1501/// serde `skip_serializing_if` helper for nested partial groups.
1502fn is_empty_partial<T: HasAnySet>(v: &T) -> bool {
1503    !v.has_any_set()
1504}
1505
1506/// Internal trait so one serde skip helper serves every partial group.
1507trait HasAnySet {
1508    fn has_any_set(&self) -> bool;
1509}
1510
1511macro_rules! impl_has_any_set {
1512    ($($name:ident),+ $(,)?) => {
1513        $(impl HasAnySet for $name {
1514            fn has_any_set(&self) -> bool {
1515                $name::has_any_set(self)
1516            }
1517        })+
1518    };
1519}
1520
1521settings_partial! {
1522    /// Partial mirror of [`SettingsApi`].
1523    SettingsApiPartial {
1524        /// Automatically start the standalone API server
1525        auto_start: bool,
1526        /// IP address the API server binds to
1527        bind_address: String,
1528        /// Port the standalone API server listens on
1529        bind_port: i64,
1530        /// Number of consecutive ports to try if api.bind_port is in use
1531        port_attempts: i64,
1532        /// Authentication token for API access when bound to non-loopback addresses
1533        token: String,
1534    }
1535}
1536
1537settings_partial! {
1538    /// Partial mirror of [`SettingsGeneral`].
1539    SettingsGeneralPartial {
1540        /// Delay before auto-stopping daemons when leaving a directory
1541        autostop_delay: String,
1542        /// Supervisor background task refresh interval
1543        interval: String,
1544        /// File log level (trace, debug, info, warn, error)
1545        log_file_level: String,
1546        /// Console log level (trace, debug, info, warn, error)
1547        log_level: String,
1548        /// Wrap daemon commands with mise x -- globally
1549        mise: bool,
1550        /// Explicit path to the mise binary
1551        mise_bin: String,
1552        /// Shell command used to execute daemon run scripts
1553        shell: String,
1554        /// Show timestamps in startup log output
1555        startup_log_timestamps: bool,
1556        /// Default readiness delay in seconds when a daemon has no ready check configured
1557        ready_delay: String,
1558        /// Enable git worktree / jj workspace auto-discovery
1559        worktree: bool,
1560    }
1561}
1562
1563settings_partial! {
1564    /// Partial mirror of [`SettingsIpc`].
1565    SettingsIpcPartial {
1566        /// Number of connection retry attempts
1567        connect_attempts: i64,
1568        /// Maximum delay between connection retries
1569        connect_max_delay: String,
1570        /// Minimum delay between connection retries
1571        connect_min_delay: String,
1572        /// Maximum IPC requests per second per connection
1573        rate_limit: i64,
1574        /// Rate limit sliding window duration
1575        rate_limit_window: String,
1576        /// Default timeout for IPC requests
1577        request_timeout: String,
1578    }
1579}
1580
1581settings_partial! {
1582    /// Partial mirror of [`SettingsLogsArchiveHook`].
1583    SettingsLogsArchiveHookPartial {
1584        /// Maximum log entries per archive hook invocation
1585        batch_size: i64,
1586        /// Command to run before retention deletes old log entries
1587        command: String,
1588    }
1589}
1590
1591settings_partial! {
1592    /// Partial mirror of [`SettingsLogs`].
1593    SettingsLogsPartial {
1594        @group archive_hook: SettingsLogsArchiveHookPartial,
1595        /// Count-based log retention (e.g. 10000)
1596        line_retention: i64,
1597        /// Default log format for daemons (json | logfmt | text)
1598        log_format: String,
1599        /// Time-based log retention duration (e.g. '7d', '30d')
1600        time_retention: String,
1601        /// Show timestamps in log output
1602        timestamp: bool,
1603        /// strftime format for log timestamps in `pitchfork logs` output
1604        timestamp_format: String,
1605    }
1606}
1607
1608settings_partial! {
1609    /// Partial mirror of [`SettingsProxy`].
1610    SettingsProxyPartial {
1611        /// Automatically start daemons when accessed via proxy URL
1612        auto_start: bool,
1613        /// Maximum time to wait for an auto-started daemon to become ready
1614        auto_start_timeout: String,
1615        /// Automatically install the proxy TLS certificate into the system trust store
1616        auto_trust: bool,
1617        /// Enable the reverse proxy server for daemons
1618        enable: bool,
1619        /// Bind address for the reverse proxy server
1620        host: String,
1621        /// Enable HTTPS for the reverse proxy
1622        https: bool,
1623        /// Enable LAN mode for the reverse proxy
1624        lan: bool,
1625        /// Pin a specific LAN IP address instead of auto-detecting
1626        lan_ip: String,
1627        /// Port the reverse proxy server listens on
1628        port: i64,
1629        /// Automatically sync slug hostnames to /etc/hosts
1630        sync_hosts: bool,
1631        /// Top-level domain used for proxy URLs
1632        tld: String,
1633        /// Path to TLS certificate file (PEM format) for HTTPS proxy
1634        tls_cert: String,
1635        /// Path to TLS private key file (PEM format) for HTTPS proxy
1636        tls_key: String,
1637        /// Enable wildcard subdomain matching for proxy routes
1638        wildcard: bool,
1639        /// Compatibility alias for general.worktree
1640        worktree: bool,
1641    }
1642}
1643
1644settings_partial! {
1645    /// Partial mirror of [`SettingsSupervisor`].
1646    SettingsSupervisorPartial {
1647        /// Automatically start the supervisor when a client command needs it
1648        auto_start: bool,
1649        /// Reconcile orphaned daemon processes when supervisor starts
1650        cleanup_orphans: bool,
1651        /// Enable container/PID1 mode for running inside Docker containers
1652        container: bool,
1653        /// Consecutive CPU-over-limit samples before killing a daemon
1654        cpu_violation_threshold: i64,
1655        /// Interval for checking cron schedules
1656        cron_check_interval: String,
1657        /// File watch debounce duration
1658        file_watch_debounce: String,
1659        /// Timeout for HTTP ready checks
1660        http_client_timeout: String,
1661        /// Daemon log buffer flush interval
1662        log_flush_interval: String,
1663        /// What to do with live orphaned daemons on supervisor startup: adopt or kill
1664        orphan_policy: String,
1665        /// Maximum port increment attempts when auto_bump_port is enabled
1666        port_bump_attempts: i64,
1667        /// Interval between ready checks (HTTP, TCP, command)
1668        ready_check_interval: String,
1669        /// Delay between stop and start during restart
1670        restart_delay: String,
1671        /// Maximum time to wait for daemon to stop gracefully
1672        stop_timeout: String,
1673        /// Default user to run daemon processes as
1674        user: String,
1675        /// File watcher config refresh interval
1676        watch_interval: String,
1677        /// Polling watcher filesystem scan interval
1678        watch_poll_interval: String,
1679    }
1680}
1681
1682settings_partial! {
1683    /// Partial mirror of [`SettingsTui`].
1684    SettingsTuiPartial {
1685        /// Status message display duration
1686        message_duration: String,
1687        /// Daemon list refresh interval
1688        refresh_rate: String,
1689        /// Number of stat samples to keep for graphs
1690        stat_history: i64,
1691        /// Event loop tick rate
1692        tick_rate: String,
1693    }
1694}
1695
1696settings_partial! {
1697    /// Partial mirror of [`SettingsWeb`].
1698    SettingsWebPartial {
1699        /// Automatically start web UI when supervisor starts
1700        auto_start: bool,
1701        /// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
1702        base_path: String,
1703        /// Web server bind address
1704        bind_address: String,
1705        /// Default web server port
1706        bind_port: i64,
1707        /// Initial number of log lines to display
1708        log_lines: i64,
1709        /// Number of ports to try if default is in use
1710        port_attempts: i64,
1711        /// Server-Sent Events poll interval for log streaming
1712        sse_poll_interval: String,
1713    }
1714}
1715
1716settings_partial! {
1717    /// Partial mirror of [`Settings`], for `[settings]` tables in
1718    /// pitchfork.toml files.
1719    SettingsPartial {
1720        @group api: SettingsApiPartial,
1721        @group general: SettingsGeneralPartial,
1722        @group ipc: SettingsIpcPartial,
1723        @group logs: SettingsLogsPartial,
1724        @group proxy: SettingsProxyPartial,
1725        @group supervisor: SettingsSupervisorPartial,
1726        @group tui: SettingsTuiPartial,
1727        @group web: SettingsWebPartial,
1728    }
1729}
1730
1731impl_has_any_set!(
1732    SettingsApiPartial,
1733    SettingsGeneralPartial,
1734    SettingsIpcPartial,
1735    SettingsLogsArchiveHookPartial,
1736    SettingsLogsPartial,
1737    SettingsProxyPartial,
1738    SettingsSupervisorPartial,
1739    SettingsTuiPartial,
1740    SettingsWebPartial,
1741);
1742
1743impl SettingsPartial {
1744    /// Move supported legacy keys to their canonical locations before a
1745    /// read-modify-write cycle serializes this partial again.
1746    pub(crate) fn canonicalize_aliases(&mut self) {
1747        if self.general.worktree.is_none() {
1748            self.general.worktree = self.proxy.worktree.take();
1749        } else {
1750            self.proxy.worktree = None;
1751        }
1752    }
1753}
1754
1755#[cfg(test)]
1756mod tests {
1757    use super::*;
1758    use std::time::Duration;
1759
1760    #[test]
1761    fn test_default_settings() {
1762        let settings = Settings::default();
1763
1764        // Test general settings
1765        assert_eq!(settings.general.autostop_delay, "1m");
1766        assert_eq!(settings.general.interval, "10s");
1767        assert_eq!(settings.general.log_level, "info");
1768        assert_eq!(settings.general.ready_delay, "3s");
1769
1770        // Test IPC settings
1771        assert_eq!(settings.ipc.connect_attempts, 5);
1772        assert_eq!(settings.ipc.request_timeout, "5s");
1773        assert_eq!(settings.ipc.rate_limit, 100);
1774
1775        // Test web settings
1776        assert!(!settings.web.auto_start);
1777        assert_eq!(settings.web.bind_address, "127.0.0.1");
1778        assert_eq!(settings.web.bind_port, 3120);
1779        assert_eq!(settings.web.log_lines, 100);
1780
1781        // Test TUI settings
1782        assert_eq!(settings.tui.refresh_rate, "2s");
1783        assert_eq!(settings.tui.stat_history, 60);
1784
1785        // Test supervisor settings
1786        assert!(settings.supervisor.auto_start);
1787        assert_eq!(settings.supervisor.ready_check_interval, "500ms");
1788        assert_eq!(settings.supervisor.file_watch_debounce, "1s");
1789        assert_eq!(settings.supervisor.user, "");
1790    }
1791
1792    #[test]
1793    fn a_bad_value_costs_only_its_own_setting() {
1794        // `Settings::read` is all or nothing, and the fallback for its failure used to be
1795        // `Settings::default()` — one field the merge could not hand to its type demoting all
1796        // sixty-eight settings and discarding the environment along with them.
1797        let env = EnvLayer::new([("PITCHFORK_LOG".to_string(), "debug".to_string())]);
1798        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
1799
1800        // The one door into a resolution the merge does not check: a post-merge hook, which is
1801        // what `sanitize_durations` is. A bool where an integer belongs is what a buggy one
1802        // could write.
1803        let registry = Settings::SETTINGS_REGISTRY;
1804        let rate_limit = registry.lookup("ipc.rate_limit").unwrap().id;
1805        resolved.coerced(rate_limit, Value::Bool(true), "a hook that got it wrong");
1806
1807        assert!(
1808            Settings::read(&resolved).is_err(),
1809            "the strict read still refuses it"
1810        );
1811
1812        let (settings, errors) = Settings::read_lossy(&resolved);
1813        let settings = settings.expect("every setting declares a default");
1814        assert_eq!(
1815            settings.ipc.rate_limit, 100,
1816            "the bad field takes its declared default"
1817        );
1818        assert_eq!(
1819            settings.general.log_level, "debug",
1820            "and PITCHFORK_LOG is not collateral damage"
1821        );
1822        assert_eq!(errors.0.len(), 1, "{errors}");
1823        assert_eq!(errors.0[0].key, "ipc.rate_limit");
1824    }
1825
1826    #[test]
1827    fn every_setting_declares_a_default() {
1828        // What makes the `None` arm of the lossy read unreachable: a setting with no value and
1829        // no default is a hole in this file, not something a user can cause. Adding one without
1830        // a default should fail here rather than silently demote the whole struct at runtime.
1831        let missing: Vec<&str> = Settings::SETTINGS_PROPS
1832            .iter()
1833            .filter(|meta| meta.default.is_none())
1834            .map(|meta| meta.key)
1835            .collect();
1836        assert!(
1837            missing.is_empty(),
1838            "these settings declare no default: {missing:?}"
1839        );
1840    }
1841
1842    #[test]
1843    fn test_registry_matches_previous_schema() {
1844        // The emitted config block is the settings documentation now; make
1845        // sure the registry still declares what settings.toml used to.
1846        let keys: Vec<&str> = Settings::SETTINGS_PROPS
1847            .iter()
1848            .map(|meta| meta.key)
1849            .collect();
1850        assert_eq!(keys.len(), 69, "{keys:?}");
1851        assert!(keys.contains(&"general.autostop_delay"));
1852        assert!(keys.contains(&"logs.archive_hook.command"));
1853        assert!(keys.contains(&"supervisor.watch_interval"));
1854
1855        let registry = Settings::SETTINGS_REGISTRY;
1856        let interval = registry.get(registry.lookup("general.interval").unwrap().id);
1857        assert_eq!(interval.envs, &["PITCHFORK_INTERVAL"]);
1858        assert_eq!(interval.deprecated_envs, &["PITCHFORK_INTERVAL_SECS"]);
1859        let watch = registry.get(registry.lookup("supervisor.watch_interval").unwrap().id);
1860        assert_eq!(watch.deprecated_envs, &["PITCHFORK_WATCH_INTERVAL_MS"]);
1861        let log_level = registry.get(registry.lookup("general.log_level").unwrap().id);
1862        assert_eq!(log_level.envs, &["PITCHFORK_LOG"]);
1863        let worktree = registry.get(registry.lookup("general.worktree").unwrap().id);
1864        assert_eq!(worktree.envs, &["PITCHFORK_WORKTREE"]);
1865        assert_eq!(worktree.deprecated_envs, &["PITCHFORK_PROXY_WORKTREE"]);
1866        assert_eq!(worktree.aliases, &["proxy.worktree"]);
1867        assert_eq!(
1868            registry.lookup("proxy.worktree").unwrap().id,
1869            registry.lookup("general.worktree").unwrap().id,
1870        );
1871
1872        let spec = Settings::spec_kdl();
1873        let files = [
1874            "file \"/etc/pitchfork/config.toml\" scope=\"system\" format=\"toml\"",
1875            "file \"~/.config/pitchfork/config.toml\" scope=\"global\" format=\"toml\"",
1876            "file \".config/pitchfork.toml\" findup=#true format=\"toml\"",
1877            "file \".config/pitchfork.local.toml\" findup=#true format=\"toml\"",
1878            "file \"pitchfork.toml\" findup=#true format=\"toml\"",
1879            "file \"pitchfork.local.toml\" findup=#true format=\"toml\"",
1880        ];
1881        let positions: Vec<usize> = files
1882            .iter()
1883            .map(|file| spec.find(file).unwrap_or_else(|| panic!("missing {file}")))
1884            .collect();
1885        assert!(
1886            positions.windows(2).all(|pair| pair[0] < pair[1]),
1887            "config files must be documented from lowest to highest precedence:\n{spec}"
1888        );
1889    }
1890
1891    #[test]
1892    fn every_registry_key_round_trips_through_the_partial() {
1893        // A setting added to the derive structs but missed in `settings_partial!`
1894        // makes `pitchfork settings set` report success and write nothing.
1895        for meta in Settings::SETTINGS_PROPS {
1896            let value = match meta.ty.inner() {
1897                Ty::Bool => toml::Value::Boolean(true),
1898                Ty::Int | Ty::Uint => toml::Value::Integer(1),
1899                _ => toml::Value::String("x".to_string()),
1900            };
1901            let parts: Vec<&str> = meta.key.split('.').collect();
1902            let mut table = toml::Table::new();
1903            let mut cursor = &mut table;
1904            for part in &parts[..parts.len() - 1] {
1905                cursor = cursor
1906                    .entry(part.to_string())
1907                    .or_insert_with(|| toml::Value::Table(toml::Table::new()))
1908                    .as_table_mut()
1909                    .unwrap();
1910            }
1911            cursor.insert(parts[parts.len() - 1].to_string(), value);
1912
1913            let partial: SettingsPartial = table.clone().try_into().unwrap();
1914            let back = toml::Table::try_from(&partial).unwrap();
1915            assert_eq!(
1916                back, table,
1917                "{} is declared in the registry but not mirrored in SettingsPartial",
1918                meta.key
1919            );
1920        }
1921    }
1922
1923    #[test]
1924    fn test_parse_duration() {
1925        assert_eq!(Settings::parse_duration("1s"), Some(Duration::from_secs(1)));
1926        assert_eq!(
1927            Settings::parse_duration("500ms"),
1928            Some(Duration::from_millis(500))
1929        );
1930        assert_eq!(
1931            Settings::parse_duration("1m"),
1932            Some(Duration::from_secs(60))
1933        );
1934        assert_eq!(
1935            Settings::parse_duration("2h"),
1936            Some(Duration::from_secs(7200))
1937        );
1938        assert_eq!(Settings::parse_duration("invalid"), None);
1939    }
1940
1941    #[test]
1942    fn test_env_override() {
1943        // The environment is described rather than reached for, so this test
1944        // does not mutate process env vars (the old test needed a mutex).
1945        let env = EnvLayer::new([
1946            ("PITCHFORK_AUTOSTOP_DELAY".to_string(), "10m".to_string()),
1947            ("PITCHFORK_INTERVAL".to_string(), "5s".to_string()),
1948            (
1949                "PITCHFORK_IPC_CONNECT_ATTEMPTS".to_string(),
1950                "20".to_string(),
1951            ),
1952            (
1953                "PITCHFORK_SUPERVISOR_AUTO_START".to_string(),
1954                "false".to_string(),
1955            ),
1956            ("PITCHFORK_WEB_AUTO_START".to_string(), "true".to_string()),
1957        ]);
1958        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
1959        let settings = Settings::read(&resolved).unwrap();
1960
1961        assert_eq!(settings.general.autostop_delay, "10m");
1962        assert_eq!(settings.general.interval, "5s");
1963        assert_eq!(settings.ipc.connect_attempts, 20);
1964        assert!(!settings.supervisor.auto_start);
1965        assert!(settings.web.auto_start);
1966
1967        // Fields with no corresponding env var set remain at defaults
1968        assert_eq!(settings.general.log_level, "info");
1969        assert_eq!(settings.ipc.rate_limit, 100);
1970    }
1971
1972    #[test]
1973    fn test_deprecated_env_still_works_and_warns() {
1974        let env = EnvLayer::new([
1975            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
1976            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
1977        ]);
1978        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
1979        let settings = Settings::read(&resolved).unwrap();
1980        assert_eq!(settings.general.interval, "30s");
1981        assert!(!settings.general.worktree);
1982        let warnings = usage_rs::config::explain::warnings(&resolved);
1983        assert!(
1984            warnings
1985                .iter()
1986                .any(|w| w.contains("PITCHFORK_INTERVAL_SECS is deprecated")),
1987            "{warnings:?}"
1988        );
1989        assert!(
1990            warnings
1991                .iter()
1992                .any(|w| w.contains("PITCHFORK_PROXY_WORKTREE is deprecated")),
1993            "{warnings:?}"
1994        );
1995
1996        // The current name wins over the deprecated alias when both are set.
1997        let env = EnvLayer::new([
1998            ("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
1999            ("PITCHFORK_INTERVAL".to_string(), "7s".to_string()),
2000            ("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
2001            ("PITCHFORK_WORKTREE".to_string(), "true".to_string()),
2002        ]);
2003        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2004        let settings = Settings::read(&resolved).unwrap();
2005        assert_eq!(settings.general.interval, "7s");
2006        assert!(settings.general.worktree);
2007    }
2008
2009    #[test]
2010    fn test_invalid_duration_from_env_falls_back_to_default() {
2011        // The previous loader rejected invalid durations at load time; the
2012        // sanitize pass reproduces that through Resolved::coerced.
2013        let env = EnvLayer::new([(
2014            "PITCHFORK_AUTOSTOP_DELAY".to_string(),
2015            "not_a_duration".to_string(),
2016        )]);
2017        let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
2018        sanitize_durations(&mut resolved);
2019        let settings = Settings::read(&resolved).unwrap();
2020        assert_eq!(settings.general.autostop_delay, "1m");
2021        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2022    }
2023
2024    #[test]
2025    fn test_invalid_duration_fallback() {
2026        let mut settings = Settings::default();
2027
2028        // Set invalid duration values
2029        settings.general.autostop_delay = "invalid".to_string();
2030        settings.general.interval = "not_a_duration".to_string();
2031
2032        // Convenience methods should fallback to default values
2033        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60)); // default "1m"
2034        assert_eq!(settings.general_interval(), Duration::from_secs(10)); // default "10s"
2035    }
2036
2037    #[test]
2038    fn test_duration_methods_all_fields() {
2039        let settings = Settings::default();
2040
2041        assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
2042        assert_eq!(settings.general_interval(), Duration::from_secs(10));
2043        assert_eq!(settings.general_ready_delay(), Duration::from_secs(3));
2044        assert_eq!(settings.ipc_connect_min_delay(), Duration::from_millis(100));
2045        assert_eq!(settings.ipc_connect_max_delay(), Duration::from_secs(1));
2046        assert_eq!(settings.ipc_request_timeout(), Duration::from_secs(5));
2047        assert_eq!(settings.ipc_rate_limit_window(), Duration::from_secs(1));
2048        assert_eq!(settings.web_sse_poll_interval(), Duration::from_millis(500));
2049        assert_eq!(settings.tui_refresh_rate(), Duration::from_secs(2));
2050        assert_eq!(settings.tui_tick_rate(), Duration::from_millis(100));
2051        assert_eq!(settings.tui_message_duration(), Duration::from_secs(3));
2052        assert_eq!(
2053            settings.supervisor_ready_check_interval(),
2054            Duration::from_millis(500)
2055        );
2056        assert_eq!(
2057            settings.supervisor_file_watch_debounce(),
2058            Duration::from_secs(1)
2059        );
2060        assert_eq!(
2061            settings.supervisor_log_flush_interval(),
2062            Duration::from_millis(500)
2063        );
2064        assert_eq!(settings.supervisor_stop_timeout(), Duration::from_secs(5));
2065        assert_eq!(
2066            settings.supervisor_restart_delay(),
2067            Duration::from_millis(100)
2068        );
2069        assert_eq!(
2070            settings.supervisor_cron_check_interval(),
2071            Duration::from_secs(10)
2072        );
2073        assert_eq!(
2074            settings.supervisor_http_client_timeout(),
2075            Duration::from_secs(5)
2076        );
2077    }
2078
2079    #[test]
2080    fn test_general_ready_delay_secs() {
2081        let mut settings = Settings::default();
2082
2083        // Default "3s" resolves to whole seconds.
2084        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2085
2086        // Subsecond values are rejected, not silently truncated by as_secs().
2087        settings.general.ready_delay = "500ms".to_string();
2088        let err = settings.general_ready_delay_secs().unwrap_err();
2089        assert!(err.contains("500ms"), "unexpected error: {err}");
2090        assert!(
2091            err.contains("whole number of seconds"),
2092            "unexpected error: {err}"
2093        );
2094
2095        settings.general.ready_delay = "1.5s".to_string();
2096        let err = settings.general_ready_delay_secs().unwrap_err();
2097        assert!(err.contains("1.5s"), "unexpected error: {err}");
2098
2099        // Empty string falls back to the schema default "3s".
2100        settings.general.ready_delay = String::new();
2101        assert_eq!(settings.general_ready_delay_secs(), Ok(3));
2102
2103        // Whole-second values resolve as seconds.
2104        settings.general.ready_delay = "90s".to_string();
2105        assert_eq!(settings.general_ready_delay_secs(), Ok(90));
2106    }
2107
2108    /// A directory tree, cleaned up when the test ends.
2109    struct Tree(std::path::PathBuf);
2110
2111    impl Tree {
2112        fn new(name: &str) -> Self {
2113            let dir = std::env::temp_dir()
2114                .join(format!("pitchfork_settings_{}_{name}", std::process::id()));
2115            let _ = std::fs::remove_dir_all(&dir);
2116            std::fs::create_dir_all(&dir).unwrap();
2117            Self(dir)
2118        }
2119
2120        fn write(&self, rel: &str, text: &str) -> std::path::PathBuf {
2121            let path = self.0.join(rel);
2122            if let Some(parent) = path.parent() {
2123                std::fs::create_dir_all(parent).unwrap();
2124            }
2125            std::fs::write(&path, text).unwrap();
2126            path
2127        }
2128    }
2129
2130    impl Drop for Tree {
2131        fn drop(&mut self) {
2132            let _ = std::fs::remove_dir_all(&self.0);
2133        }
2134    }
2135
2136    #[test]
2137    fn test_settings_read_from_pitchfork_toml_settings_table() {
2138        let tree = Tree::new("table");
2139        let path = tree.write(
2140            "pitchfork.toml",
2141            r#"
2142[daemons.myapp]
2143run = "node server.js"
2144
2145[settings.general]
2146autostop_delay = "5m"
2147log_level = "debug"
2148
2149[settings.web]
2150auto_start = true
2151bind_port = 8080
2152
2153[settings.supervisor]
2154auto_start = false
2155user = "postgres"
2156"#,
2157        );
2158        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2159        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2160        let settings = Settings::read(&resolved).unwrap();
2161
2162        assert_eq!(settings.general.autostop_delay, "5m");
2163        assert_eq!(settings.general.log_level, "debug");
2164        assert!(settings.web.auto_start);
2165        assert_eq!(settings.web.bind_port, 8080);
2166        assert!(!settings.supervisor.auto_start);
2167        assert_eq!(settings.supervisor.user, "postgres");
2168        // Unset fields fall back to defaults, and [daemons] is not a warning.
2169        assert_eq!(settings.general.interval, "10s");
2170        assert_eq!(settings.ipc.connect_attempts, 5);
2171        assert!(resolved.warnings.is_empty(), "{:?}", resolved.warnings);
2172    }
2173
2174    #[test]
2175    fn test_proxy_worktree_config_alias_still_works() {
2176        let tree = Tree::new("proxy_worktree_alias");
2177        let path = tree.write("pitchfork.toml", "[settings.proxy]\nworktree = false\n");
2178        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2179        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2180        let settings = Settings::read(&resolved).unwrap();
2181
2182        assert!(!settings.general.worktree);
2183        assert_eq!(
2184            resolved.get(
2185                Settings::SETTINGS_REGISTRY
2186                    .lookup("general.worktree")
2187                    .unwrap()
2188                    .id
2189            ),
2190            Some(&Value::Bool(false)),
2191        );
2192    }
2193
2194    #[test]
2195    fn test_explicit_default_value_in_higher_file_still_overrides() {
2196        // "Bug 5": the old merge_from skipped values equal to the default, so
2197        // a higher-precedence file explicitly setting log_level = "info"
2198        // could not override "warn" from a lower one. usage-config's
2199        // origin-tracked merge does this natively; pin it.
2200        let tree = Tree::new("bug5");
2201        let lower = tree.write("lower.toml", "[settings.general]\nlog_level = \"warn\"\n");
2202        let higher = tree.write("higher.toml", "[settings.general]\nlog_level = \"info\"\n");
2203        let lower = FileLayer::at(&lower, FileScope::Global).under("settings");
2204        let higher = FileLayer::at(&higher, FileScope::Project).under("settings");
2205        let resolved = resolve(
2206            Settings::SETTINGS_REGISTRY,
2207            Layers::new().then(&higher).then(&lower),
2208        )
2209        .unwrap();
2210        let settings = Settings::read(&resolved).unwrap();
2211        assert_eq!(settings.general.log_level, "info");
2212
2213        // And the provenance says the higher file set it, not the default.
2214        let id = Settings::SETTINGS_REGISTRY
2215            .lookup("general.log_level")
2216            .unwrap()
2217            .id;
2218        let origin = resolved.origin(id).unwrap().describe();
2219        assert!(origin.contains("higher.toml"), "{origin}");
2220    }
2221
2222    #[test]
2223    fn test_file_precedence_local_over_base_and_nearer_dir_wins() {
2224        let tree = Tree::new("precedence");
2225        tree.write("pitchfork.toml", "[settings.general]\ninterval = \"9s\"\n");
2226        tree.write(
2227            "pitchfork.local.toml",
2228            "[settings.general]\ninterval = \"2s\"\n",
2229        );
2230        tree.write(
2231            ".config/pitchfork.toml",
2232            "[settings.general]\ninterval = \"7s\"\n[settings.web]\nbind_port = 9999\n",
2233        );
2234        let layers = Settings::file_layers_from(&tree.0);
2235        let mut chain = Layers::new();
2236        for layer in &layers {
2237            chain = chain.then(layer);
2238        }
2239        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
2240        let settings = Settings::read(&resolved).unwrap();
2241        // pitchfork.local.toml > pitchfork.toml > .config/pitchfork.toml
2242        assert_eq!(settings.general.interval, "2s");
2243        // A key only the lowest file sets still applies.
2244        assert_eq!(settings.web.bind_port, 9999);
2245
2246        // A nested directory's file outranks everything above it.
2247        let deep = tree.0.join("a").join("b");
2248        std::fs::create_dir_all(&deep).unwrap();
2249        tree.write(
2250            "a/b/pitchfork.toml",
2251            "[settings.general]\ninterval = \"1s\"\n",
2252        );
2253        let layers = Settings::file_layers_from(&deep);
2254        let mut chain = Layers::new();
2255        for layer in &layers {
2256            chain = chain.then(layer);
2257        }
2258        let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
2259        let settings = Settings::read(&resolved).unwrap();
2260        assert_eq!(settings.general.interval, "1s");
2261    }
2262
2263    #[test]
2264    fn test_broken_file_is_skipped_rather_than_fatal() {
2265        let tree = Tree::new("broken");
2266        let broken = tree.write("pitchfork.toml", "[invalid toml [[");
2267        // The broken file is skipped with a warning, so the resolution still
2268        // happens and produces the defaults.
2269        let layers = Settings::file_layers_from(&tree.0);
2270        assert!(
2271            layers.iter().all(|layer| !layer.paths().contains(&broken)),
2272            "the broken project file must not become a settings layer"
2273        );
2274    }
2275
2276    #[test]
2277    fn test_unknown_settings_keys_do_not_fail_the_load() {
2278        // Forward compatibility: a config written for a newer pitchfork must
2279        // still load. Unknown keys are warned about rather than fatal.
2280        let tree = Tree::new("unknown");
2281        let path = tree.write(
2282            "pitchfork.toml",
2283            "[settings.general]\nlog_level = \"debug\"\nfrom_the_future = true\n",
2284        );
2285        let layer = FileLayer::at(&path, FileScope::Project).under("settings");
2286        let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
2287        let settings = Settings::read(&resolved).unwrap();
2288        assert_eq!(settings.general.log_level, "debug");
2289        assert_eq!(resolved.warnings.len(), 1, "{:?}", resolved.warnings);
2290    }
2291
2292    #[test]
2293    fn test_partial_merge_from() {
2294        let mut base = SettingsPartial::default();
2295        base.general.log_level = Some("warn".to_string());
2296        base.web.bind_address = Some("0.0.0.0".to_string());
2297
2298        let mut overlay = SettingsPartial::default();
2299        overlay.general.log_level = Some("debug".to_string());
2300        overlay.tui.refresh_rate = Some("1s".to_string());
2301
2302        base.merge_from(&overlay);
2303        assert_eq!(base.general.log_level.as_deref(), Some("debug"));
2304        assert_eq!(base.web.bind_address.as_deref(), Some("0.0.0.0"));
2305        assert_eq!(base.tui.refresh_rate.as_deref(), Some("1s"));
2306
2307        // An empty partial changes nothing.
2308        let sealed = base.clone();
2309        base.merge_from(&SettingsPartial::default());
2310        assert_eq!(base.general.log_level, sealed.general.log_level);
2311        assert!(SettingsPartial::default().is_empty());
2312        assert!(base.has_any_set());
2313    }
2314
2315    #[test]
2316    fn test_partial_serialization_skips_unset() {
2317        let mut partial = SettingsPartial::default();
2318        partial.general.interval = Some("5s".to_string());
2319        let toml = toml::to_string_pretty(&partial).unwrap();
2320        assert_eq!(toml, "[general]\ninterval = \"5s\"\n");
2321    }
2322}