Skip to main content

taskfast_cli/
config.rs

1// SPDX-License-Identifier: MIT
2//! JSON config file for the `taskfast` CLI.
3//!
4//! Persistent state written by `taskfast init` (and edited via
5//! `taskfast config set`) so subsequent subcommands work in a fresh
6//! shell without sourcing anything.
7//!
8//! # Layout
9//!
10//! Default path: `./.taskfast/config.json` (project-local). Override via
11//! the global `--config <path>` flag or `TASKFAST_CONFIG` env var.
12//!
13//! # Precedence
14//!
15//! `Ctx::from_cli_and_config` (see `cmd/mod.rs`) layers values as:
16//!
17//! ```text
18//! clap flag > env var > config file > default
19//! ```
20//!
21//! Clap already folds flag > env via `env = "..."`. The config file sits
22//! one rung under that, so omitting a field in JSON never surprises a
23//! caller who passed the flag.
24//!
25//! # Forward-compat
26//!
27//! `schema_version` is a `u32` that starts at `CURRENT_SCHEMA_VERSION`.
28//! Unknown fields are tolerated (default serde behaviour). A file with a
29//! newer `schema_version` logs a warning and loads what it recognises —
30//! it does not fail, so an older CLI doesn't brick a newer config dir.
31//!
32//! # Secrets
33//!
34//! `api_key` lives in this file. The file is written mode `0600` on unix
35//! (atomic temp + rename) and the containing `.taskfast/` directory is
36//! intended to be git-ignored.
37
38use std::fs;
39use std::io::Write;
40use std::path::{Path, PathBuf};
41
42use serde::{Deserialize, Serialize};
43use thiserror::Error;
44
45use crate::Environment;
46
47/// Default project-local path, relative to the CWD.
48pub const DEFAULT_CONFIG_PATH: &str = ".taskfast/config.json";
49
50/// Current on-disk schema version. Bump when a field changes shape in a
51/// way a reader needs to special-case; additive fields don't need a bump
52/// because serde `#[serde(default)]` already handles missing keys.
53///
54/// v2: dropped `api_base` and `network` — both derived from `environment`
55/// at runtime via [`crate::Environment::api_base`] and
56/// [`crate::Environment::network`]. Files at v1 with either key present
57/// hard-error in [`Config::load`] with a migration hint.
58pub const CURRENT_SCHEMA_VERSION: u32 = 2;
59
60/// Keys removed at schema v2. Loading a file that still carries any of
61/// these triggers [`ConfigError::LegacyFields`] so a stale config never
62/// silently misroutes traffic post-migration.
63const LEGACY_REMOVED_KEYS: &[&str] = &["api_base", "network"];
64
65#[derive(Debug, Error)]
66pub enum ConfigError {
67    #[error("I/O on {path}: {source}")]
68    Io {
69        path: PathBuf,
70        #[source]
71        source: std::io::Error,
72    },
73    #[error("parse {path}: {source}")]
74    Parse {
75        path: PathBuf,
76        #[source]
77        source: serde_json::Error,
78    },
79    #[error(
80        "config {path} carries removed key(s) {fields:?} — derived from `environment` since \
81         schema v2. Run `taskfast config migrate` (or remove the keys + bump `schema_version` \
82         to 2 manually) and re-run."
83    )]
84    LegacyFields { path: PathBuf, fields: Vec<String> },
85}
86
87/// On-disk config. Every runtime field is `Option` so the file stays
88/// small and a partially-configured project can still round-trip.
89#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
90#[serde(default)]
91pub struct Config {
92    /// On-disk schema version (`CURRENT_SCHEMA_VERSION` for fresh
93    /// writes). A `0` value means "not set" and is normalized to
94    /// `CURRENT_SCHEMA_VERSION` on save.
95    #[serde(skip_serializing_if = "is_zero")]
96    pub schema_version: u32,
97
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub environment: Option<Environment>,
100
101    /// Agent API key. Secret — the file is written `0600`.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub api_key: Option<String>,
104
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub wallet_address: Option<String>,
107
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub keystore_path: Option<PathBuf>,
110
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub agent_id: Option<String>,
113
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub webhook_url: Option<String>,
116
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub webhook_secret_path: Option<PathBuf>,
119
120    /// Fail-closed confirmation gate for mutating commands. When the
121    /// requested budget on `post` (or task budget on `settle`) exceeds
122    /// this stablecoin-units threshold, the command refuses to proceed
123    /// without an explicit `--yes`. Decimal string in the same units
124    /// as `--budget` (e.g. `"1000"` = 1000 USDC). `None` = gate off.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub confirm_above_budget: Option<String>,
127
128    /// Default `--verbose` log encoding. Accepts `"json"` or `"text"`.
129    /// `None` = `"text"`. CLI flag and env var (`TASKFAST_LOG_FORMAT`)
130    /// still win over this.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub log_format: Option<String>,
133
134    /// Poster approval deadline for `escrow sign`. Human-readable
135    /// duration string (e.g. `"7d"`, `"24h"`). `None` = built-in
136    /// default (7 days). Flag `--approval-horizon` and env var
137    /// `TASKFAST_APPROVAL_HORIZON` still win over this. Malformed
138    /// values are rejected at CLI startup, not mid-escrow.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub approval_horizon: Option<String>,
141
142    /// Receipt-polling ceiling for `escrow sign`. Human-readable
143    /// duration. `None` = network-aware default (3min mainnet,
144    /// 1min testnet). Flag `--receipt-timeout` and env var
145    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub receipt_timeout: Option<String>,
148}
149
150// `skip_serializing_if` is required by serde to take `&T`, so clippy's
151// pass-by-value lint is a false positive here.
152#[allow(clippy::trivially_copy_pass_by_ref)]
153fn is_zero(v: &u32) -> bool {
154    *v == 0
155}
156
157/// Drop a `.gitignore` of `*` into the config dir so its plaintext secrets
158/// (`api_key`, keystore path, webhook secret) can't be committed by accident.
159/// `create_new` makes this idempotent and non-destructive: an existing
160/// `.gitignore` (user-customized) is left untouched. Best-effort — any other
161/// I/O error is logged, not propagated, so it never fails the config write.
162///
163/// Scoped to the conventional `.taskfast` secrets dir only: a caller who
164/// overrides `--config ./config.json` (or `TASKFAST_CONFIG`) must not have a
165/// `.gitignore` of `*` dropped into an arbitrary directory — into the repo
166/// root that would ignore the entire working tree.
167fn ensure_dir_gitignore(dir: &Path) {
168    let expected = Path::new(DEFAULT_CONFIG_PATH)
169        .parent()
170        .and_then(Path::file_name);
171    if dir.file_name() != expected {
172        return;
173    }
174    let gitignore = dir.join(".gitignore");
175    match fs::OpenOptions::new()
176        .write(true)
177        .create_new(true)
178        .open(&gitignore)
179    {
180        Ok(mut f) => {
181            if let Err(e) = f.write_all(b"*\n") {
182                tracing::warn!(path = %gitignore.display(), error = %e, "could not write .taskfast/.gitignore");
183            }
184        }
185        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
186        Err(e) => {
187            tracing::warn!(path = %gitignore.display(), error = %e, "could not create .taskfast/.gitignore");
188        }
189    }
190}
191
192impl Config {
193    /// Parse the JSON at `path`. Missing file → `Config::default()`
194    /// (callers treat absence the same as an empty config). Newer
195    /// `schema_version` values log a warning via `tracing::warn!` and
196    /// load what they recognise.
197    ///
198    /// Hard-errors with [`ConfigError::LegacyFields`] when the on-disk
199    /// JSON still carries any key removed at the current schema version
200    /// (currently `api_base` and `network`). Stale values would otherwise
201    /// silently outrank the `Environment`-derived defaults.
202    pub fn load(path: &Path) -> Result<Self, ConfigError> {
203        let src = match fs::read_to_string(path) {
204            Ok(s) => s,
205            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
206            Err(source) => {
207                return Err(ConfigError::Io {
208                    path: path.to_path_buf(),
209                    source,
210                });
211            }
212        };
213        // Peek raw JSON before strict deserialization so the migration error
214        // wins over a generic parse error and so removed-key detection does
215        // not depend on `Config` carrying the field.
216        let raw: serde_json::Value =
217            serde_json::from_str(&src).map_err(|source| ConfigError::Parse {
218                path: path.to_path_buf(),
219                source,
220            })?;
221        if let Some(obj) = raw.as_object() {
222            let legacy: Vec<String> = LEGACY_REMOVED_KEYS
223                .iter()
224                .filter(|k| obj.contains_key(**k))
225                .map(|k| (*k).to_string())
226                .collect();
227            if !legacy.is_empty() {
228                return Err(ConfigError::LegacyFields {
229                    path: path.to_path_buf(),
230                    fields: legacy,
231                });
232            }
233        }
234        let cfg: Config = serde_json::from_value(raw).map_err(|source| ConfigError::Parse {
235            path: path.to_path_buf(),
236            source,
237        })?;
238        if cfg.schema_version > CURRENT_SCHEMA_VERSION {
239            tracing::warn!(
240                file = %path.display(),
241                file_version = cfg.schema_version,
242                current_version = CURRENT_SCHEMA_VERSION,
243                "config schema_version is newer than this CLI — loading recognised fields only"
244            );
245        }
246        Ok(cfg)
247    }
248
249    /// Atomic(ish) write: JSON-serialize to a sibling `.tmp`, chmod
250    /// `0600` on unix, rename into place. Creates the parent directory
251    /// if it doesn't exist.
252    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
253        if let Some(parent) = path.parent() {
254            if !parent.as_os_str().is_empty() {
255                fs::create_dir_all(parent).map_err(|source| ConfigError::Io {
256                    path: parent.to_path_buf(),
257                    source,
258                })?;
259                // F4: tighten the `.taskfast/` dir to 0700. `create_dir_all`
260                // honors umask (typically 022 → 0755), leaving the keystore
261                // + webhook secret + API key config readable by anyone on
262                // the host. 0700 scopes them to the owning UID. Idempotent
263                // on subsequent saves.
264                #[cfg(unix)]
265                {
266                    use std::os::unix::fs::PermissionsExt;
267                    let perms = fs::Permissions::from_mode(0o700);
268                    fs::set_permissions(parent, perms).map_err(|source| ConfigError::Io {
269                        path: parent.to_path_buf(),
270                        source,
271                    })?;
272                }
273                // Git-ignore the whole config dir so the plaintext `api_key`
274                // can't be committed by accident from inside a repo (gh#78).
275                // Best-effort: a failure here must not fail the config write.
276                ensure_dir_gitignore(parent);
277            }
278        }
279        let mut to_write = self.clone();
280        if to_write.schema_version == 0 {
281            to_write.schema_version = CURRENT_SCHEMA_VERSION;
282        }
283        let body = serde_json::to_vec_pretty(&to_write).map_err(|source| ConfigError::Parse {
284            path: path.to_path_buf(),
285            source,
286        })?;
287
288        let tmp = path.with_extension("json.tmp");
289        {
290            // Create the temp at 0600 from the start (not umask-default then
291            // chmod) so the api_key is never momentarily world-readable
292            // before the rename. gh#78.
293            #[cfg(unix)]
294            let create = {
295                use std::os::unix::fs::OpenOptionsExt;
296                fs::OpenOptions::new()
297                    .write(true)
298                    .create(true)
299                    .truncate(true)
300                    .mode(0o600)
301                    .open(&tmp)
302            };
303            #[cfg(not(unix))]
304            let create = fs::File::create(&tmp);
305            let mut f = create.map_err(|source| ConfigError::Io {
306                path: tmp.clone(),
307                source,
308            })?;
309            f.write_all(&body).map_err(|source| ConfigError::Io {
310                path: tmp.clone(),
311                source,
312            })?;
313            f.write_all(b"\n").map_err(|source| ConfigError::Io {
314                path: tmp.clone(),
315                source,
316            })?;
317            f.flush().map_err(|source| ConfigError::Io {
318                path: tmp.clone(),
319                source,
320            })?;
321        }
322        #[cfg(unix)]
323        {
324            use std::os::unix::fs::PermissionsExt;
325            let perms = fs::Permissions::from_mode(0o600);
326            fs::set_permissions(&tmp, perms).map_err(|source| ConfigError::Io {
327                path: tmp.clone(),
328                source,
329            })?;
330        }
331        fs::rename(&tmp, path).map_err(|source| ConfigError::Io {
332            path: path.to_path_buf(),
333            source,
334        })?;
335        Ok(())
336    }
337
338    /// Default file path, rooted in the caller's current working
339    /// directory. Used when neither `--config` nor `TASKFAST_CONFIG`
340    /// is supplied.
341    pub fn default_path() -> PathBuf {
342        PathBuf::from(DEFAULT_CONFIG_PATH)
343    }
344}
345
346// Serde support for `Environment` — declared here (not in lib.rs) so the
347// config module owns its serialization contract. If the enum ever grows
348// a runtime variant that shouldn't be persisted, the mapping stays
349// local.
350impl Serialize for Environment {
351    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
352        ser.serialize_str(match self {
353            Self::Prod => "prod",
354            Self::Staging => "staging",
355            Self::Local => "local",
356        })
357    }
358}
359
360impl<'de> Deserialize<'de> for Environment {
361    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
362        let s = String::deserialize(de)?;
363        match s.as_str() {
364            "prod" | "production" => Ok(Self::Prod),
365            "staging" => Ok(Self::Staging),
366            "local" => Ok(Self::Local),
367            other => Err(serde::de::Error::custom(format!(
368                "unknown environment {other:?}; expected prod | staging | local"
369            ))),
370        }
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use tempfile::TempDir;
378
379    fn sample() -> Config {
380        Config {
381            schema_version: CURRENT_SCHEMA_VERSION,
382            environment: Some(Environment::Local),
383            api_key: Some("am_live_secret".into()),
384            wallet_address: Some("0xabc".into()),
385            keystore_path: Some(PathBuf::from("/tmp/keystore.json")),
386            agent_id: Some("agent_123".into()),
387            webhook_url: Some("https://example.com/hook".into()),
388            webhook_secret_path: Some(PathBuf::from("/tmp/hook.secret")),
389            confirm_above_budget: Some("1000".into()),
390            log_format: Some("json".into()),
391            approval_horizon: Some("7d".into()),
392            receipt_timeout: Some("3min".into()),
393        }
394    }
395
396    #[test]
397    fn load_missing_file_returns_default() {
398        let tmp = TempDir::new().unwrap();
399        let missing = tmp.path().join("nope.json");
400        let cfg = Config::load(&missing).expect("missing file is default, not error");
401        assert_eq!(cfg, Config::default());
402    }
403
404    #[test]
405    fn roundtrip_preserves_every_field() {
406        let tmp = TempDir::new().unwrap();
407        let path = tmp.path().join("sub").join("config.json");
408        let original = sample();
409        original.save(&path).expect("save");
410        let loaded = Config::load(&path).expect("load");
411        assert_eq!(loaded, original);
412    }
413
414    #[test]
415    fn save_zero_schema_version_is_normalized_to_current() {
416        let tmp = TempDir::new().unwrap();
417        let path = tmp.path().join("config.json");
418        let cfg = Config {
419            wallet_address: Some("0xabc".into()),
420            ..Config::default()
421        };
422        assert_eq!(cfg.schema_version, 0);
423        cfg.save(&path).expect("save");
424        let loaded = Config::load(&path).expect("load");
425        assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
426    }
427
428    #[test]
429    fn save_creates_missing_parent_dir() {
430        let tmp = TempDir::new().unwrap();
431        let nested = tmp.path().join("a").join("b").join("config.json");
432        sample().save(&nested).expect("save into nested path");
433        assert!(nested.exists());
434    }
435
436    #[cfg(unix)]
437    #[test]
438    fn save_tightens_parent_directory_to_0700() {
439        use std::os::unix::fs::PermissionsExt;
440        let tmp = TempDir::new().unwrap();
441        let cfg_dir = tmp.path().join(".taskfast");
442        let path = cfg_dir.join("config.json");
443        sample().save(&path).expect("save");
444        let mode = fs::metadata(&cfg_dir).unwrap().permissions().mode() & 0o777;
445        assert_eq!(
446            mode, 0o700,
447            ".taskfast/ must be 0700 so other users on the host can't \
448             list the keystore + webhook secret + API key"
449        );
450    }
451
452    #[test]
453    fn save_writes_gitignore_star_in_config_dir() {
454        // gh#78: the dir holding the plaintext api_key must be git-ignored
455        // by default so a `taskfast init` inside a repo can't leak it.
456        let tmp = TempDir::new().unwrap();
457        let cfg_dir = tmp.path().join(".taskfast");
458        let path = cfg_dir.join("config.json");
459        sample().save(&path).expect("save");
460        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).expect(".gitignore written");
461        assert_eq!(gi.trim(), "*");
462    }
463
464    #[test]
465    fn save_to_overridden_path_does_not_write_gitignore() {
466        // gh#78 review: `--config ./config.json` must NOT drop a `.gitignore`
467        // of `*` into an arbitrary dir (e.g. the repo root, which would
468        // ignore the whole tree). Only the conventional `.taskfast/` dir is
469        // auto-ignored.
470        let tmp = TempDir::new().unwrap();
471        let dir = tmp.path().join("some-project");
472        let path = dir.join("config.json");
473        sample().save(&path).expect("save");
474        assert!(path.exists(), "config still written");
475        assert!(
476            !dir.join(".gitignore").exists(),
477            "no .gitignore in a non-.taskfast dir"
478        );
479    }
480
481    #[test]
482    fn save_does_not_clobber_existing_gitignore() {
483        // A user who customized .gitignore keeps it — we only create when absent.
484        let tmp = TempDir::new().unwrap();
485        let cfg_dir = tmp.path().join(".taskfast");
486        fs::create_dir_all(&cfg_dir).unwrap();
487        fs::write(cfg_dir.join(".gitignore"), "# mine\nconfig.json\n").unwrap();
488        sample().save(&cfg_dir.join("config.json")).expect("save");
489        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).unwrap();
490        assert_eq!(gi, "# mine\nconfig.json\n", "existing .gitignore preserved");
491    }
492
493    #[test]
494    fn unknown_fields_are_tolerated() {
495        let tmp = TempDir::new().unwrap();
496        let path = tmp.path().join("config.json");
497        let body = r#"{
498            "schema_version": 2,
499            "wallet_address": "0xabc",
500            "future_field": "ignored",
501            "another": {"nested": true}
502        }"#;
503        fs::write(&path, body).unwrap();
504        let cfg = Config::load(&path).expect("unknown fields should not fail load");
505        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
506    }
507
508    #[test]
509    fn newer_schema_version_loads_with_warning() {
510        let tmp = TempDir::new().unwrap();
511        let path = tmp.path().join("config.json");
512        let body = format!(
513            r#"{{ "schema_version": {}, "wallet_address": "0xabc" }}"#,
514            CURRENT_SCHEMA_VERSION + 5
515        );
516        fs::write(&path, body).unwrap();
517        let cfg = Config::load(&path).expect("newer version still loads");
518        assert_eq!(cfg.schema_version, CURRENT_SCHEMA_VERSION + 5);
519        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
520    }
521
522    #[test]
523    fn legacy_api_base_field_hard_errors() {
524        let tmp = TempDir::new().unwrap();
525        let path = tmp.path().join("config.json");
526        let body = r#"{ "schema_version": 1, "api_base": "https://attacker.example" }"#;
527        fs::write(&path, body).unwrap();
528        let err = Config::load(&path).expect_err("legacy api_base must be rejected");
529        let ConfigError::LegacyFields { fields, .. } = err else {
530            panic!("expected LegacyFields, got {err:?}");
531        };
532        assert_eq!(fields, vec!["api_base".to_string()]);
533    }
534
535    #[test]
536    fn legacy_network_field_hard_errors() {
537        let tmp = TempDir::new().unwrap();
538        let path = tmp.path().join("config.json");
539        let body = r#"{ "schema_version": 1, "network": "mainnet" }"#;
540        fs::write(&path, body).unwrap();
541        let err = Config::load(&path).expect_err("legacy network must be rejected");
542        let ConfigError::LegacyFields { fields, .. } = err else {
543            panic!("expected LegacyFields, got {err:?}");
544        };
545        assert_eq!(fields, vec!["network".to_string()]);
546    }
547
548    #[test]
549    fn legacy_error_lists_both_fields_when_present() {
550        let tmp = TempDir::new().unwrap();
551        let path = tmp.path().join("config.json");
552        let body = r#"{ "api_base": "https://x", "network": "testnet" }"#;
553        fs::write(&path, body).unwrap();
554        let err = Config::load(&path).expect_err("both legacy fields must be flagged");
555        let ConfigError::LegacyFields { fields, .. } = err else {
556            panic!("expected LegacyFields, got {err:?}");
557        };
558        assert!(fields.contains(&"api_base".to_string()));
559        assert!(fields.contains(&"network".to_string()));
560    }
561
562    #[test]
563    fn legacy_error_message_names_migration_command() {
564        let tmp = TempDir::new().unwrap();
565        let path = tmp.path().join("config.json");
566        fs::write(&path, r#"{ "api_base": "https://x" }"#).unwrap();
567        let msg = Config::load(&path).unwrap_err().to_string();
568        assert!(
569            msg.contains("taskfast config migrate"),
570            "remediation hint must name the migrate command: {msg}"
571        );
572    }
573
574    #[test]
575    fn empty_config_serializes_compactly() {
576        // A default config has no runtime fields set — the JSON should
577        // be close to `{}` (just an empty object after skip_if).
578        let body = serde_json::to_string(&Config::default()).unwrap();
579        assert_eq!(body, "{}", "default config should serialize to {{}}");
580    }
581
582    #[test]
583    fn environment_roundtrip() {
584        for env in [Environment::Prod, Environment::Staging, Environment::Local] {
585            let cfg = Config {
586                environment: Some(env),
587                ..Config::default()
588            };
589            let body = serde_json::to_string(&cfg).unwrap();
590            let back: Config = serde_json::from_str(&body).unwrap();
591            assert_eq!(back.environment.map(|e| e.as_str()), Some(env.as_str()));
592        }
593    }
594
595    #[test]
596    fn environment_accepts_production_alias() {
597        let body = r#"{ "environment": "production" }"#;
598        let cfg: Config = serde_json::from_str(body).unwrap();
599        assert!(matches!(cfg.environment, Some(Environment::Prod)));
600    }
601
602    #[test]
603    fn environment_rejects_unknown() {
604        let body = r#"{ "environment": "moon" }"#;
605        let err = serde_json::from_str::<Config>(body).unwrap_err();
606        assert!(err.to_string().contains("moon"));
607    }
608
609    #[cfg(unix)]
610    #[test]
611    fn save_writes_mode_0600_on_unix() {
612        use std::os::unix::fs::PermissionsExt;
613        let tmp = TempDir::new().unwrap();
614        let path = tmp.path().join("config.json");
615        sample().save(&path).expect("save");
616        let meta = fs::metadata(&path).unwrap();
617        let mode = meta.permissions().mode() & 0o777;
618        assert_eq!(mode, 0o600, "expected mode 0600, got {mode:o}");
619    }
620
621    #[test]
622    fn parse_error_includes_path() {
623        let tmp = TempDir::new().unwrap();
624        let path = tmp.path().join("bad.json");
625        fs::write(&path, "{ not json").unwrap();
626        let err = Config::load(&path).unwrap_err();
627        let msg = err.to_string();
628        assert!(msg.contains("bad.json"), "error mentions path: {msg}");
629    }
630}