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