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
157impl Config {
158    /// Parse the JSON at `path`. Missing file → `Config::default()`
159    /// (callers treat absence the same as an empty config). Newer
160    /// `schema_version` values log a warning via `tracing::warn!` and
161    /// load what they recognise.
162    ///
163    /// Hard-errors with [`ConfigError::LegacyFields`] when the on-disk
164    /// JSON still carries any key removed at the current schema version
165    /// (currently `api_base` and `network`). Stale values would otherwise
166    /// silently outrank the `Environment`-derived defaults.
167    pub fn load(path: &Path) -> Result<Self, ConfigError> {
168        let src = match fs::read_to_string(path) {
169            Ok(s) => s,
170            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
171            Err(source) => {
172                return Err(ConfigError::Io {
173                    path: path.to_path_buf(),
174                    source,
175                });
176            }
177        };
178        // Peek raw JSON before strict deserialization so the migration error
179        // wins over a generic parse error and so removed-key detection does
180        // not depend on `Config` carrying the field.
181        let raw: serde_json::Value =
182            serde_json::from_str(&src).map_err(|source| ConfigError::Parse {
183                path: path.to_path_buf(),
184                source,
185            })?;
186        if let Some(obj) = raw.as_object() {
187            let legacy: Vec<String> = LEGACY_REMOVED_KEYS
188                .iter()
189                .filter(|k| obj.contains_key(**k))
190                .map(|k| (*k).to_string())
191                .collect();
192            if !legacy.is_empty() {
193                return Err(ConfigError::LegacyFields {
194                    path: path.to_path_buf(),
195                    fields: legacy,
196                });
197            }
198        }
199        let cfg: Config = serde_json::from_value(raw).map_err(|source| ConfigError::Parse {
200            path: path.to_path_buf(),
201            source,
202        })?;
203        if cfg.schema_version > CURRENT_SCHEMA_VERSION {
204            tracing::warn!(
205                file = %path.display(),
206                file_version = cfg.schema_version,
207                current_version = CURRENT_SCHEMA_VERSION,
208                "config schema_version is newer than this CLI — loading recognised fields only"
209            );
210        }
211        Ok(cfg)
212    }
213
214    /// Atomic(ish) write: JSON-serialize to a sibling `.tmp`, chmod
215    /// `0600` on unix, rename into place. Creates the parent directory
216    /// if it doesn't exist.
217    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
218        if let Some(parent) = path.parent() {
219            if !parent.as_os_str().is_empty() {
220                fs::create_dir_all(parent).map_err(|source| ConfigError::Io {
221                    path: parent.to_path_buf(),
222                    source,
223                })?;
224                // F4: tighten the `.taskfast/` dir to 0700. `create_dir_all`
225                // honors umask (typically 022 → 0755), leaving the keystore
226                // + webhook secret + API key config readable by anyone on
227                // the host. 0700 scopes them to the owning UID. Idempotent
228                // on subsequent saves.
229                #[cfg(unix)]
230                {
231                    use std::os::unix::fs::PermissionsExt;
232                    let perms = fs::Permissions::from_mode(0o700);
233                    fs::set_permissions(parent, perms).map_err(|source| ConfigError::Io {
234                        path: parent.to_path_buf(),
235                        source,
236                    })?;
237                }
238            }
239        }
240        let mut to_write = self.clone();
241        if to_write.schema_version == 0 {
242            to_write.schema_version = CURRENT_SCHEMA_VERSION;
243        }
244        let body = serde_json::to_vec_pretty(&to_write).map_err(|source| ConfigError::Parse {
245            path: path.to_path_buf(),
246            source,
247        })?;
248
249        let tmp = path.with_extension("json.tmp");
250        {
251            let mut f = fs::File::create(&tmp).map_err(|source| ConfigError::Io {
252                path: tmp.clone(),
253                source,
254            })?;
255            f.write_all(&body).map_err(|source| ConfigError::Io {
256                path: tmp.clone(),
257                source,
258            })?;
259            f.write_all(b"\n").map_err(|source| ConfigError::Io {
260                path: tmp.clone(),
261                source,
262            })?;
263            f.flush().map_err(|source| ConfigError::Io {
264                path: tmp.clone(),
265                source,
266            })?;
267        }
268        #[cfg(unix)]
269        {
270            use std::os::unix::fs::PermissionsExt;
271            let perms = fs::Permissions::from_mode(0o600);
272            fs::set_permissions(&tmp, perms).map_err(|source| ConfigError::Io {
273                path: tmp.clone(),
274                source,
275            })?;
276        }
277        fs::rename(&tmp, path).map_err(|source| ConfigError::Io {
278            path: path.to_path_buf(),
279            source,
280        })?;
281        Ok(())
282    }
283
284    /// Default file path, rooted in the caller's current working
285    /// directory. Used when neither `--config` nor `TASKFAST_CONFIG`
286    /// is supplied.
287    pub fn default_path() -> PathBuf {
288        PathBuf::from(DEFAULT_CONFIG_PATH)
289    }
290}
291
292// Serde support for `Environment` — declared here (not in lib.rs) so the
293// config module owns its serialization contract. If the enum ever grows
294// a runtime variant that shouldn't be persisted, the mapping stays
295// local.
296impl Serialize for Environment {
297    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
298        ser.serialize_str(match self {
299            Self::Prod => "prod",
300            Self::Staging => "staging",
301            Self::Local => "local",
302        })
303    }
304}
305
306impl<'de> Deserialize<'de> for Environment {
307    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
308        let s = String::deserialize(de)?;
309        match s.as_str() {
310            "prod" | "production" => Ok(Self::Prod),
311            "staging" => Ok(Self::Staging),
312            "local" => Ok(Self::Local),
313            other => Err(serde::de::Error::custom(format!(
314                "unknown environment {other:?}; expected prod | staging | local"
315            ))),
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use tempfile::TempDir;
324
325    fn sample() -> Config {
326        Config {
327            schema_version: CURRENT_SCHEMA_VERSION,
328            environment: Some(Environment::Local),
329            api_key: Some("am_live_secret".into()),
330            wallet_address: Some("0xabc".into()),
331            keystore_path: Some(PathBuf::from("/tmp/keystore.json")),
332            agent_id: Some("agent_123".into()),
333            webhook_url: Some("https://example.com/hook".into()),
334            webhook_secret_path: Some(PathBuf::from("/tmp/hook.secret")),
335            confirm_above_budget: Some("1000".into()),
336            log_format: Some("json".into()),
337            approval_horizon: Some("7d".into()),
338            receipt_timeout: Some("3min".into()),
339        }
340    }
341
342    #[test]
343    fn load_missing_file_returns_default() {
344        let tmp = TempDir::new().unwrap();
345        let missing = tmp.path().join("nope.json");
346        let cfg = Config::load(&missing).expect("missing file is default, not error");
347        assert_eq!(cfg, Config::default());
348    }
349
350    #[test]
351    fn roundtrip_preserves_every_field() {
352        let tmp = TempDir::new().unwrap();
353        let path = tmp.path().join("sub").join("config.json");
354        let original = sample();
355        original.save(&path).expect("save");
356        let loaded = Config::load(&path).expect("load");
357        assert_eq!(loaded, original);
358    }
359
360    #[test]
361    fn save_zero_schema_version_is_normalized_to_current() {
362        let tmp = TempDir::new().unwrap();
363        let path = tmp.path().join("config.json");
364        let cfg = Config {
365            wallet_address: Some("0xabc".into()),
366            ..Config::default()
367        };
368        assert_eq!(cfg.schema_version, 0);
369        cfg.save(&path).expect("save");
370        let loaded = Config::load(&path).expect("load");
371        assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
372    }
373
374    #[test]
375    fn save_creates_missing_parent_dir() {
376        let tmp = TempDir::new().unwrap();
377        let nested = tmp.path().join("a").join("b").join("config.json");
378        sample().save(&nested).expect("save into nested path");
379        assert!(nested.exists());
380    }
381
382    #[cfg(unix)]
383    #[test]
384    fn save_tightens_parent_directory_to_0700() {
385        use std::os::unix::fs::PermissionsExt;
386        let tmp = TempDir::new().unwrap();
387        let cfg_dir = tmp.path().join(".taskfast");
388        let path = cfg_dir.join("config.json");
389        sample().save(&path).expect("save");
390        let mode = fs::metadata(&cfg_dir).unwrap().permissions().mode() & 0o777;
391        assert_eq!(
392            mode, 0o700,
393            ".taskfast/ must be 0700 so other users on the host can't \
394             list the keystore + webhook secret + API key"
395        );
396    }
397
398    #[test]
399    fn unknown_fields_are_tolerated() {
400        let tmp = TempDir::new().unwrap();
401        let path = tmp.path().join("config.json");
402        let body = r#"{
403            "schema_version": 2,
404            "wallet_address": "0xabc",
405            "future_field": "ignored",
406            "another": {"nested": true}
407        }"#;
408        fs::write(&path, body).unwrap();
409        let cfg = Config::load(&path).expect("unknown fields should not fail load");
410        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
411    }
412
413    #[test]
414    fn newer_schema_version_loads_with_warning() {
415        let tmp = TempDir::new().unwrap();
416        let path = tmp.path().join("config.json");
417        let body = format!(
418            r#"{{ "schema_version": {}, "wallet_address": "0xabc" }}"#,
419            CURRENT_SCHEMA_VERSION + 5
420        );
421        fs::write(&path, body).unwrap();
422        let cfg = Config::load(&path).expect("newer version still loads");
423        assert_eq!(cfg.schema_version, CURRENT_SCHEMA_VERSION + 5);
424        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
425    }
426
427    #[test]
428    fn legacy_api_base_field_hard_errors() {
429        let tmp = TempDir::new().unwrap();
430        let path = tmp.path().join("config.json");
431        let body = r#"{ "schema_version": 1, "api_base": "https://attacker.example" }"#;
432        fs::write(&path, body).unwrap();
433        let err = Config::load(&path).expect_err("legacy api_base must be rejected");
434        let ConfigError::LegacyFields { fields, .. } = err else {
435            panic!("expected LegacyFields, got {err:?}");
436        };
437        assert_eq!(fields, vec!["api_base".to_string()]);
438    }
439
440    #[test]
441    fn legacy_network_field_hard_errors() {
442        let tmp = TempDir::new().unwrap();
443        let path = tmp.path().join("config.json");
444        let body = r#"{ "schema_version": 1, "network": "mainnet" }"#;
445        fs::write(&path, body).unwrap();
446        let err = Config::load(&path).expect_err("legacy network must be rejected");
447        let ConfigError::LegacyFields { fields, .. } = err else {
448            panic!("expected LegacyFields, got {err:?}");
449        };
450        assert_eq!(fields, vec!["network".to_string()]);
451    }
452
453    #[test]
454    fn legacy_error_lists_both_fields_when_present() {
455        let tmp = TempDir::new().unwrap();
456        let path = tmp.path().join("config.json");
457        let body = r#"{ "api_base": "https://x", "network": "testnet" }"#;
458        fs::write(&path, body).unwrap();
459        let err = Config::load(&path).expect_err("both legacy fields must be flagged");
460        let ConfigError::LegacyFields { fields, .. } = err else {
461            panic!("expected LegacyFields, got {err:?}");
462        };
463        assert!(fields.contains(&"api_base".to_string()));
464        assert!(fields.contains(&"network".to_string()));
465    }
466
467    #[test]
468    fn legacy_error_message_names_migration_command() {
469        let tmp = TempDir::new().unwrap();
470        let path = tmp.path().join("config.json");
471        fs::write(&path, r#"{ "api_base": "https://x" }"#).unwrap();
472        let msg = Config::load(&path).unwrap_err().to_string();
473        assert!(
474            msg.contains("taskfast config migrate"),
475            "remediation hint must name the migrate command: {msg}"
476        );
477    }
478
479    #[test]
480    fn empty_config_serializes_compactly() {
481        // A default config has no runtime fields set — the JSON should
482        // be close to `{}` (just an empty object after skip_if).
483        let body = serde_json::to_string(&Config::default()).unwrap();
484        assert_eq!(body, "{}", "default config should serialize to {{}}");
485    }
486
487    #[test]
488    fn environment_roundtrip() {
489        for env in [Environment::Prod, Environment::Staging, Environment::Local] {
490            let cfg = Config {
491                environment: Some(env),
492                ..Config::default()
493            };
494            let body = serde_json::to_string(&cfg).unwrap();
495            let back: Config = serde_json::from_str(&body).unwrap();
496            assert_eq!(back.environment.map(|e| e.as_str()), Some(env.as_str()));
497        }
498    }
499
500    #[test]
501    fn environment_accepts_production_alias() {
502        let body = r#"{ "environment": "production" }"#;
503        let cfg: Config = serde_json::from_str(body).unwrap();
504        assert!(matches!(cfg.environment, Some(Environment::Prod)));
505    }
506
507    #[test]
508    fn environment_rejects_unknown() {
509        let body = r#"{ "environment": "moon" }"#;
510        let err = serde_json::from_str::<Config>(body).unwrap_err();
511        assert!(err.to_string().contains("moon"));
512    }
513
514    #[cfg(unix)]
515    #[test]
516    fn save_writes_mode_0600_on_unix() {
517        use std::os::unix::fs::PermissionsExt;
518        let tmp = TempDir::new().unwrap();
519        let path = tmp.path().join("config.json");
520        sample().save(&path).expect("save");
521        let meta = fs::metadata(&path).unwrap();
522        let mode = meta.permissions().mode() & 0o777;
523        assert_eq!(mode, 0o600, "expected mode 0600, got {mode:o}");
524    }
525
526    #[test]
527    fn parse_error_includes_path() {
528        let tmp = TempDir::new().unwrap();
529        let path = tmp.path().join("bad.json");
530        fs::write(&path, "{ not json").unwrap();
531        let err = Config::load(&path).unwrap_err();
532        let msg = err.to_string();
533        assert!(msg.contains("bad.json"), "error mentions path: {msg}");
534    }
535}