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::path::{Path, PathBuf};
39
40use serde::{Deserialize, Serialize};
41use thiserror::Error;
42
43use crate::Environment;
44
45/// Default project-local path, relative to the CWD.
46pub const DEFAULT_CONFIG_PATH: &str = ".taskfast/config.json";
47
48/// Current on-disk schema version. Bump when a field changes shape in a
49/// way a reader needs to special-case; additive fields don't need a bump
50/// because serde `#[serde(default)]` already handles missing keys.
51///
52/// v2: dropped `api_base` and `network` — both derived from `environment`
53/// at runtime via [`crate::Environment::api_base`] and
54/// [`crate::Environment::network`]. Files at v1 with either key present
55/// hard-error in [`Config::load`] with a migration hint.
56pub const CURRENT_SCHEMA_VERSION: u32 = 2;
57
58/// Keys removed at schema v2. Loading a file that still carries any of
59/// these triggers [`ConfigError::LegacyFields`] so a stale config never
60/// silently misroutes traffic post-migration.
61const LEGACY_REMOVED_KEYS: &[&str] = &["api_base", "network"];
62
63#[derive(Debug, Error)]
64pub enum ConfigError {
65    #[error("I/O on {path}: {source}")]
66    Io {
67        path: PathBuf,
68        #[source]
69        source: std::io::Error,
70    },
71    #[error("parse {path}: {source}")]
72    Parse {
73        path: PathBuf,
74        #[source]
75        source: serde_json::Error,
76    },
77    #[error(
78        "config {path} carries removed key(s) {fields:?} — derived from `environment` since \
79         schema v2. Run `taskfast config migrate` (or remove the keys + bump `schema_version` \
80         to 2 manually) and re-run."
81    )]
82    LegacyFields { path: PathBuf, fields: Vec<String> },
83}
84
85/// On-disk config. Every runtime field is `Option` so the file stays
86/// small and a partially-configured project can still round-trip.
87#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
88#[serde(default)]
89pub struct Config {
90    /// On-disk schema version (`CURRENT_SCHEMA_VERSION` for fresh
91    /// writes). A `0` value means "not set" and is normalized to
92    /// `CURRENT_SCHEMA_VERSION` on save.
93    #[serde(skip_serializing_if = "is_zero")]
94    pub schema_version: u32,
95
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub environment: Option<Environment>,
98
99    /// Agent API key. Secret — the file is written `0600`.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub api_key: Option<String>,
102
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub wallet_address: Option<String>,
105
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub keystore_path: Option<PathBuf>,
108
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub agent_id: Option<String>,
111
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub webhook_url: Option<String>,
114
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub webhook_secret_path: Option<PathBuf>,
117
118    /// Fail-closed confirmation gate for mutating commands. When the
119    /// requested budget on `post` (or task budget on `settle`) exceeds
120    /// this stablecoin-units threshold, the command refuses to proceed
121    /// without an explicit `--yes`. Decimal string in the same units
122    /// as `--budget` (e.g. `"1000"` = 1000 USDC). `None` = gate off.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub confirm_above_budget: Option<String>,
125
126    /// Default `--verbose` log encoding. Accepts `"json"` or `"text"`.
127    /// `None` = `"text"`. CLI flag and env var (`TASKFAST_LOG_FORMAT`)
128    /// still win over this.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub log_format: Option<String>,
131
132    /// Receipt-polling ceiling for `escrow sign`. Human-readable
133    /// duration. `None` = network-aware default (3min mainnet,
134    /// 1min testnet). Flag `--receipt-timeout` and env var
135    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub receipt_timeout: Option<String>,
138}
139
140// `skip_serializing_if` is required by serde to take `&T`, so clippy's
141// pass-by-value lint is a false positive here.
142#[allow(clippy::trivially_copy_pass_by_ref)]
143fn is_zero(v: &u32) -> bool {
144    *v == 0
145}
146
147impl Config {
148    /// Parse the JSON at `path`. Missing file → `Config::default()`
149    /// (callers treat absence the same as an empty config). Newer
150    /// `schema_version` values log a warning via `tracing::warn!` and
151    /// load what they recognise.
152    ///
153    /// Hard-errors with [`ConfigError::LegacyFields`] when the on-disk
154    /// JSON still carries any key removed at the current schema version
155    /// (currently `api_base` and `network`). Stale values would otherwise
156    /// silently outrank the `Environment`-derived defaults.
157    pub fn load(path: &Path) -> Result<Self, ConfigError> {
158        let src = match std::fs::read_to_string(path) {
159            Ok(s) => s,
160            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
161            Err(source) => {
162                return Err(ConfigError::Io {
163                    path: path.to_path_buf(),
164                    source,
165                });
166            }
167        };
168        // Peek raw JSON before strict deserialization so the migration error
169        // wins over a generic parse error and so removed-key detection does
170        // not depend on `Config` carrying the field.
171        let raw: serde_json::Value =
172            serde_json::from_str(&src).map_err(|source| ConfigError::Parse {
173                path: path.to_path_buf(),
174                source,
175            })?;
176        if let Some(obj) = raw.as_object() {
177            let legacy: Vec<String> = LEGACY_REMOVED_KEYS
178                .iter()
179                .filter(|k| obj.contains_key(**k))
180                .map(|k| (*k).to_string())
181                .collect();
182            if !legacy.is_empty() {
183                return Err(ConfigError::LegacyFields {
184                    path: path.to_path_buf(),
185                    fields: legacy,
186                });
187            }
188        }
189        let cfg: Config = serde_json::from_value(raw).map_err(|source| ConfigError::Parse {
190            path: path.to_path_buf(),
191            source,
192        })?;
193        if cfg.schema_version > CURRENT_SCHEMA_VERSION {
194            tracing::warn!(
195                file = %path.display(),
196                file_version = cfg.schema_version,
197                current_version = CURRENT_SCHEMA_VERSION,
198                "config schema_version is newer than this CLI — loading recognised fields only"
199            );
200        }
201        Ok(cfg)
202    }
203
204    /// Atomic write: JSON-serialize, chmod `0600` on unix from creation, rename into place.
205    /// Creates the parent directory if it doesn't exist and tightens to `0700`.
206    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
207        if let Some(parent) = path.parent() {
208            if !parent.as_os_str().is_empty() {
209                crate::state_store::StateStore::ensure_dir_path(parent).map_err(|source| {
210                    ConfigError::Io {
211                        path: parent.to_path_buf(),
212                        source,
213                    }
214                })?;
215            }
216        }
217        let mut to_write = self.clone();
218        if to_write.schema_version == 0 {
219            to_write.schema_version = CURRENT_SCHEMA_VERSION;
220        }
221        let body = serde_json::to_vec_pretty(&to_write).map_err(|source| ConfigError::Parse {
222            path: path.to_path_buf(),
223            source,
224        })?;
225
226        crate::state_store::StateStore::atomic_write_file(path, &body).map_err(|source| {
227            ConfigError::Io {
228                path: path.to_path_buf(),
229                source,
230            }
231        })?;
232        Ok(())
233    }
234
235    /// Default file path, rooted in the caller's current working
236    /// directory. Used when neither `--config` nor `TASKFAST_CONFIG`
237    /// is supplied.
238    pub fn default_path() -> PathBuf {
239        PathBuf::from(DEFAULT_CONFIG_PATH)
240    }
241}
242
243// Serde support for `Environment` — declared here (not in lib.rs) so the
244// config module owns its serialization contract. If the enum ever grows
245// a runtime variant that shouldn't be persisted, the mapping stays
246// local.
247impl Serialize for Environment {
248    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
249        ser.serialize_str(match self {
250            Self::Prod => "prod",
251            Self::Staging => "staging",
252            Self::Local => "local",
253        })
254    }
255}
256
257impl<'de> Deserialize<'de> for Environment {
258    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
259        let s = String::deserialize(de)?;
260        match s.as_str() {
261            "prod" | "production" => Ok(Self::Prod),
262            "staging" => Ok(Self::Staging),
263            "local" => Ok(Self::Local),
264            other => Err(serde::de::Error::custom(format!(
265                "unknown environment {other:?}; expected prod | staging | local"
266            ))),
267        }
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use std::fs;
275    use tempfile::TempDir;
276
277    fn sample() -> Config {
278        Config {
279            schema_version: CURRENT_SCHEMA_VERSION,
280            environment: Some(Environment::Local),
281            api_key: Some("am_live_secret".into()),
282            wallet_address: Some("0xabc".into()),
283            keystore_path: Some(PathBuf::from("/tmp/keystore.json")),
284            agent_id: Some("agent_123".into()),
285            webhook_url: Some("https://example.com/hook".into()),
286            webhook_secret_path: Some(PathBuf::from("/tmp/hook.secret")),
287            confirm_above_budget: Some("1000".into()),
288            log_format: Some("json".into()),
289            receipt_timeout: Some("3min".into()),
290        }
291    }
292
293    #[test]
294    fn load_missing_file_returns_default() {
295        let tmp = TempDir::new().unwrap();
296        let missing = tmp.path().join("nope.json");
297        let cfg = Config::load(&missing).expect("missing file is default, not error");
298        assert_eq!(cfg, Config::default());
299    }
300
301    #[test]
302    fn roundtrip_preserves_every_field() {
303        let tmp = TempDir::new().unwrap();
304        let path = tmp.path().join("sub").join("config.json");
305        let original = sample();
306        original.save(&path).expect("save");
307        let loaded = Config::load(&path).expect("load");
308        assert_eq!(loaded, original);
309    }
310
311    #[test]
312    fn save_zero_schema_version_is_normalized_to_current() {
313        let tmp = TempDir::new().unwrap();
314        let path = tmp.path().join("config.json");
315        let cfg = Config {
316            wallet_address: Some("0xabc".into()),
317            ..Config::default()
318        };
319        assert_eq!(cfg.schema_version, 0);
320        cfg.save(&path).expect("save");
321        let loaded = Config::load(&path).expect("load");
322        assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
323    }
324
325    #[test]
326    fn save_creates_missing_parent_dir() {
327        let tmp = TempDir::new().unwrap();
328        let nested = tmp.path().join("a").join("b").join("config.json");
329        sample().save(&nested).expect("save into nested path");
330        assert!(nested.exists());
331    }
332
333    #[cfg(unix)]
334    #[test]
335    fn save_tightens_parent_directory_to_0700() {
336        use std::os::unix::fs::PermissionsExt;
337        let tmp = TempDir::new().unwrap();
338        let cfg_dir = tmp.path().join(".taskfast");
339        let path = cfg_dir.join("config.json");
340        sample().save(&path).expect("save");
341        let mode = fs::metadata(&cfg_dir).unwrap().permissions().mode() & 0o777;
342        assert_eq!(
343            mode, 0o700,
344            ".taskfast/ must be 0700 so other users on the host can't \
345             list the keystore + webhook secret + API key"
346        );
347    }
348
349    #[test]
350    fn save_writes_gitignore_star_in_config_dir() {
351        // gh#78: the dir holding the plaintext api_key must be git-ignored
352        // by default so a `taskfast init` inside a repo can't leak it.
353        let tmp = TempDir::new().unwrap();
354        let cfg_dir = tmp.path().join(".taskfast");
355        let path = cfg_dir.join("config.json");
356        sample().save(&path).expect("save");
357        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).expect(".gitignore written");
358        assert_eq!(gi.trim(), "*");
359    }
360
361    #[test]
362    fn save_to_overridden_path_does_not_write_gitignore() {
363        // gh#78 review: `--config ./config.json` must NOT drop a `.gitignore`
364        // of `*` into an arbitrary dir (e.g. the repo root, which would
365        // ignore the whole tree). Only the conventional `.taskfast/` dir is
366        // auto-ignored.
367        let tmp = TempDir::new().unwrap();
368        let dir = tmp.path().join("some-project");
369        let path = dir.join("config.json");
370        sample().save(&path).expect("save");
371        assert!(path.exists(), "config still written");
372        assert!(
373            !dir.join(".gitignore").exists(),
374            "no .gitignore in a non-.taskfast dir"
375        );
376    }
377
378    #[test]
379    fn save_does_not_clobber_existing_gitignore() {
380        // A user who customized .gitignore keeps it — we only create when absent.
381        let tmp = TempDir::new().unwrap();
382        let cfg_dir = tmp.path().join(".taskfast");
383        fs::create_dir_all(&cfg_dir).unwrap();
384        fs::write(cfg_dir.join(".gitignore"), "# mine\nconfig.json\n").unwrap();
385        sample().save(&cfg_dir.join("config.json")).expect("save");
386        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).unwrap();
387        assert_eq!(gi, "# mine\nconfig.json\n", "existing .gitignore preserved");
388    }
389
390    #[test]
391    fn unknown_fields_are_tolerated() {
392        let tmp = TempDir::new().unwrap();
393        let path = tmp.path().join("config.json");
394        let body = r#"{
395            "schema_version": 2,
396            "wallet_address": "0xabc",
397            "future_field": "ignored",
398            "another": {"nested": true}
399        }"#;
400        fs::write(&path, body).unwrap();
401        let cfg = Config::load(&path).expect("unknown fields should not fail load");
402        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
403    }
404
405    #[test]
406    fn newer_schema_version_loads_with_warning() {
407        let tmp = TempDir::new().unwrap();
408        let path = tmp.path().join("config.json");
409        let body = format!(
410            r#"{{ "schema_version": {}, "wallet_address": "0xabc" }}"#,
411            CURRENT_SCHEMA_VERSION + 5
412        );
413        fs::write(&path, body).unwrap();
414        let cfg = Config::load(&path).expect("newer version still loads");
415        assert_eq!(cfg.schema_version, CURRENT_SCHEMA_VERSION + 5);
416        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
417    }
418
419    #[test]
420    fn legacy_api_base_field_hard_errors() {
421        let tmp = TempDir::new().unwrap();
422        let path = tmp.path().join("config.json");
423        let body = r#"{ "schema_version": 1, "api_base": "https://attacker.example" }"#;
424        fs::write(&path, body).unwrap();
425        let err = Config::load(&path).expect_err("legacy api_base must be rejected");
426        let ConfigError::LegacyFields { fields, .. } = err else {
427            panic!("expected LegacyFields, got {err:?}");
428        };
429        assert_eq!(fields, vec!["api_base".to_string()]);
430    }
431
432    #[test]
433    fn legacy_network_field_hard_errors() {
434        let tmp = TempDir::new().unwrap();
435        let path = tmp.path().join("config.json");
436        let body = r#"{ "schema_version": 1, "network": "mainnet" }"#;
437        fs::write(&path, body).unwrap();
438        let err = Config::load(&path).expect_err("legacy network must be rejected");
439        let ConfigError::LegacyFields { fields, .. } = err else {
440            panic!("expected LegacyFields, got {err:?}");
441        };
442        assert_eq!(fields, vec!["network".to_string()]);
443    }
444
445    #[test]
446    fn legacy_error_lists_both_fields_when_present() {
447        let tmp = TempDir::new().unwrap();
448        let path = tmp.path().join("config.json");
449        let body = r#"{ "api_base": "https://x", "network": "testnet" }"#;
450        fs::write(&path, body).unwrap();
451        let err = Config::load(&path).expect_err("both legacy fields must be flagged");
452        let ConfigError::LegacyFields { fields, .. } = err else {
453            panic!("expected LegacyFields, got {err:?}");
454        };
455        assert!(fields.contains(&"api_base".to_string()));
456        assert!(fields.contains(&"network".to_string()));
457    }
458
459    #[test]
460    fn legacy_error_message_names_migration_command() {
461        let tmp = TempDir::new().unwrap();
462        let path = tmp.path().join("config.json");
463        fs::write(&path, r#"{ "api_base": "https://x" }"#).unwrap();
464        let msg = Config::load(&path).unwrap_err().to_string();
465        assert!(
466            msg.contains("taskfast config migrate"),
467            "remediation hint must name the migrate command: {msg}"
468        );
469    }
470
471    #[test]
472    fn empty_config_serializes_compactly() {
473        // A default config has no runtime fields set — the JSON should
474        // be close to `{}` (just an empty object after skip_if).
475        let body = serde_json::to_string(&Config::default()).unwrap();
476        assert_eq!(body, "{}", "default config should serialize to {{}}");
477    }
478
479    #[test]
480    fn environment_roundtrip() {
481        for env in [Environment::Prod, Environment::Staging, Environment::Local] {
482            let cfg = Config {
483                environment: Some(env),
484                ..Config::default()
485            };
486            let body = serde_json::to_string(&cfg).unwrap();
487            let back: Config = serde_json::from_str(&body).unwrap();
488            assert_eq!(back.environment.map(|e| e.as_str()), Some(env.as_str()));
489        }
490    }
491
492    #[test]
493    fn environment_accepts_production_alias() {
494        let body = r#"{ "environment": "production" }"#;
495        let cfg: Config = serde_json::from_str(body).unwrap();
496        assert!(matches!(cfg.environment, Some(Environment::Prod)));
497    }
498
499    #[test]
500    fn environment_rejects_unknown() {
501        let body = r#"{ "environment": "moon" }"#;
502        let err = serde_json::from_str::<Config>(body).unwrap_err();
503        assert!(err.to_string().contains("moon"));
504    }
505
506    #[cfg(unix)]
507    #[test]
508    fn save_writes_mode_0600_on_unix() {
509        use std::os::unix::fs::PermissionsExt;
510        let tmp = TempDir::new().unwrap();
511        let path = tmp.path().join("config.json");
512        sample().save(&path).expect("save");
513        let meta = fs::metadata(&path).unwrap();
514        let mode = meta.permissions().mode() & 0o777;
515        assert_eq!(mode, 0o600, "expected mode 0600, got {mode:o}");
516    }
517
518    #[test]
519    fn parse_error_includes_path() {
520        let tmp = TempDir::new().unwrap();
521        let path = tmp.path().join("bad.json");
522        fs::write(&path, "{ not json").unwrap();
523        let err = Config::load(&path).unwrap_err();
524        let msg = err.to_string();
525        assert!(msg.contains("bad.json"), "error mentions path: {msg}");
526    }
527}