1use std::fs;
39use std::io::Write;
40use std::path::{Path, PathBuf};
41
42use serde::{Deserialize, Serialize};
43use thiserror::Error;
44
45use crate::Environment;
46
47pub const DEFAULT_CONFIG_PATH: &str = ".taskfast/config.json";
49
50pub const CURRENT_SCHEMA_VERSION: u32 = 2;
59
60const 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#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
90#[serde(default)]
91pub struct Config {
92 #[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 #[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 #[serde(skip_serializing_if = "Option::is_none")]
126 pub confirm_above_budget: Option<String>,
127
128 #[serde(skip_serializing_if = "Option::is_none")]
132 pub log_format: Option<String>,
133
134 #[serde(skip_serializing_if = "Option::is_none")]
139 pub receipt_timeout: Option<String>,
140}
141
142#[allow(clippy::trivially_copy_pass_by_ref)]
145fn is_zero(v: &u32) -> bool {
146 *v == 0
147}
148
149fn ensure_dir_gitignore(dir: &Path) {
160 let expected = Path::new(DEFAULT_CONFIG_PATH)
161 .parent()
162 .and_then(Path::file_name);
163 if dir.file_name() != expected {
164 return;
165 }
166 let gitignore = dir.join(".gitignore");
167 match fs::OpenOptions::new()
168 .write(true)
169 .create_new(true)
170 .open(&gitignore)
171 {
172 Ok(mut f) => {
173 if let Err(e) = f.write_all(b"*\n") {
174 tracing::warn!(path = %gitignore.display(), error = %e, "could not write .taskfast/.gitignore");
175 }
176 }
177 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
178 Err(e) => {
179 tracing::warn!(path = %gitignore.display(), error = %e, "could not create .taskfast/.gitignore");
180 }
181 }
182}
183
184impl Config {
185 pub fn load(path: &Path) -> Result<Self, ConfigError> {
195 let src = match fs::read_to_string(path) {
196 Ok(s) => s,
197 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
198 Err(source) => {
199 return Err(ConfigError::Io {
200 path: path.to_path_buf(),
201 source,
202 });
203 }
204 };
205 let raw: serde_json::Value =
209 serde_json::from_str(&src).map_err(|source| ConfigError::Parse {
210 path: path.to_path_buf(),
211 source,
212 })?;
213 if let Some(obj) = raw.as_object() {
214 let legacy: Vec<String> = LEGACY_REMOVED_KEYS
215 .iter()
216 .filter(|k| obj.contains_key(**k))
217 .map(|k| (*k).to_string())
218 .collect();
219 if !legacy.is_empty() {
220 return Err(ConfigError::LegacyFields {
221 path: path.to_path_buf(),
222 fields: legacy,
223 });
224 }
225 }
226 let cfg: Config = serde_json::from_value(raw).map_err(|source| ConfigError::Parse {
227 path: path.to_path_buf(),
228 source,
229 })?;
230 if cfg.schema_version > CURRENT_SCHEMA_VERSION {
231 tracing::warn!(
232 file = %path.display(),
233 file_version = cfg.schema_version,
234 current_version = CURRENT_SCHEMA_VERSION,
235 "config schema_version is newer than this CLI — loading recognised fields only"
236 );
237 }
238 Ok(cfg)
239 }
240
241 pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
245 if let Some(parent) = path.parent() {
246 if !parent.as_os_str().is_empty() {
247 fs::create_dir_all(parent).map_err(|source| ConfigError::Io {
248 path: parent.to_path_buf(),
249 source,
250 })?;
251 #[cfg(unix)]
257 {
258 use std::os::unix::fs::PermissionsExt;
259 let perms = fs::Permissions::from_mode(0o700);
260 fs::set_permissions(parent, perms).map_err(|source| ConfigError::Io {
261 path: parent.to_path_buf(),
262 source,
263 })?;
264 }
265 ensure_dir_gitignore(parent);
269 }
270 }
271 let mut to_write = self.clone();
272 if to_write.schema_version == 0 {
273 to_write.schema_version = CURRENT_SCHEMA_VERSION;
274 }
275 let body = serde_json::to_vec_pretty(&to_write).map_err(|source| ConfigError::Parse {
276 path: path.to_path_buf(),
277 source,
278 })?;
279
280 let tmp = path.with_extension("json.tmp");
281 {
282 #[cfg(unix)]
286 let create = {
287 use std::os::unix::fs::OpenOptionsExt;
288 fs::OpenOptions::new()
289 .write(true)
290 .create(true)
291 .truncate(true)
292 .mode(0o600)
293 .open(&tmp)
294 };
295 #[cfg(not(unix))]
296 let create = fs::File::create(&tmp);
297 let mut f = create.map_err(|source| ConfigError::Io {
298 path: tmp.clone(),
299 source,
300 })?;
301 f.write_all(&body).map_err(|source| ConfigError::Io {
302 path: tmp.clone(),
303 source,
304 })?;
305 f.write_all(b"\n").map_err(|source| ConfigError::Io {
306 path: tmp.clone(),
307 source,
308 })?;
309 f.flush().map_err(|source| ConfigError::Io {
310 path: tmp.clone(),
311 source,
312 })?;
313 }
314 #[cfg(unix)]
315 {
316 use std::os::unix::fs::PermissionsExt;
317 let perms = fs::Permissions::from_mode(0o600);
318 fs::set_permissions(&tmp, perms).map_err(|source| ConfigError::Io {
319 path: tmp.clone(),
320 source,
321 })?;
322 }
323 fs::rename(&tmp, path).map_err(|source| ConfigError::Io {
324 path: path.to_path_buf(),
325 source,
326 })?;
327 Ok(())
328 }
329
330 pub fn default_path() -> PathBuf {
334 PathBuf::from(DEFAULT_CONFIG_PATH)
335 }
336}
337
338impl Serialize for Environment {
343 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
344 ser.serialize_str(match self {
345 Self::Prod => "prod",
346 Self::Staging => "staging",
347 Self::Local => "local",
348 })
349 }
350}
351
352impl<'de> Deserialize<'de> for Environment {
353 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
354 let s = String::deserialize(de)?;
355 match s.as_str() {
356 "prod" | "production" => Ok(Self::Prod),
357 "staging" => Ok(Self::Staging),
358 "local" => Ok(Self::Local),
359 other => Err(serde::de::Error::custom(format!(
360 "unknown environment {other:?}; expected prod | staging | local"
361 ))),
362 }
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369 use tempfile::TempDir;
370
371 fn sample() -> Config {
372 Config {
373 schema_version: CURRENT_SCHEMA_VERSION,
374 environment: Some(Environment::Local),
375 api_key: Some("am_live_secret".into()),
376 wallet_address: Some("0xabc".into()),
377 keystore_path: Some(PathBuf::from("/tmp/keystore.json")),
378 agent_id: Some("agent_123".into()),
379 webhook_url: Some("https://example.com/hook".into()),
380 webhook_secret_path: Some(PathBuf::from("/tmp/hook.secret")),
381 confirm_above_budget: Some("1000".into()),
382 log_format: Some("json".into()),
383 receipt_timeout: Some("3min".into()),
384 }
385 }
386
387 #[test]
388 fn load_missing_file_returns_default() {
389 let tmp = TempDir::new().unwrap();
390 let missing = tmp.path().join("nope.json");
391 let cfg = Config::load(&missing).expect("missing file is default, not error");
392 assert_eq!(cfg, Config::default());
393 }
394
395 #[test]
396 fn roundtrip_preserves_every_field() {
397 let tmp = TempDir::new().unwrap();
398 let path = tmp.path().join("sub").join("config.json");
399 let original = sample();
400 original.save(&path).expect("save");
401 let loaded = Config::load(&path).expect("load");
402 assert_eq!(loaded, original);
403 }
404
405 #[test]
406 fn save_zero_schema_version_is_normalized_to_current() {
407 let tmp = TempDir::new().unwrap();
408 let path = tmp.path().join("config.json");
409 let cfg = Config {
410 wallet_address: Some("0xabc".into()),
411 ..Config::default()
412 };
413 assert_eq!(cfg.schema_version, 0);
414 cfg.save(&path).expect("save");
415 let loaded = Config::load(&path).expect("load");
416 assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
417 }
418
419 #[test]
420 fn save_creates_missing_parent_dir() {
421 let tmp = TempDir::new().unwrap();
422 let nested = tmp.path().join("a").join("b").join("config.json");
423 sample().save(&nested).expect("save into nested path");
424 assert!(nested.exists());
425 }
426
427 #[cfg(unix)]
428 #[test]
429 fn save_tightens_parent_directory_to_0700() {
430 use std::os::unix::fs::PermissionsExt;
431 let tmp = TempDir::new().unwrap();
432 let cfg_dir = tmp.path().join(".taskfast");
433 let path = cfg_dir.join("config.json");
434 sample().save(&path).expect("save");
435 let mode = fs::metadata(&cfg_dir).unwrap().permissions().mode() & 0o777;
436 assert_eq!(
437 mode, 0o700,
438 ".taskfast/ must be 0700 so other users on the host can't \
439 list the keystore + webhook secret + API key"
440 );
441 }
442
443 #[test]
444 fn save_writes_gitignore_star_in_config_dir() {
445 let tmp = TempDir::new().unwrap();
448 let cfg_dir = tmp.path().join(".taskfast");
449 let path = cfg_dir.join("config.json");
450 sample().save(&path).expect("save");
451 let gi = fs::read_to_string(cfg_dir.join(".gitignore")).expect(".gitignore written");
452 assert_eq!(gi.trim(), "*");
453 }
454
455 #[test]
456 fn save_to_overridden_path_does_not_write_gitignore() {
457 let tmp = TempDir::new().unwrap();
462 let dir = tmp.path().join("some-project");
463 let path = dir.join("config.json");
464 sample().save(&path).expect("save");
465 assert!(path.exists(), "config still written");
466 assert!(
467 !dir.join(".gitignore").exists(),
468 "no .gitignore in a non-.taskfast dir"
469 );
470 }
471
472 #[test]
473 fn save_does_not_clobber_existing_gitignore() {
474 let tmp = TempDir::new().unwrap();
476 let cfg_dir = tmp.path().join(".taskfast");
477 fs::create_dir_all(&cfg_dir).unwrap();
478 fs::write(cfg_dir.join(".gitignore"), "# mine\nconfig.json\n").unwrap();
479 sample().save(&cfg_dir.join("config.json")).expect("save");
480 let gi = fs::read_to_string(cfg_dir.join(".gitignore")).unwrap();
481 assert_eq!(gi, "# mine\nconfig.json\n", "existing .gitignore preserved");
482 }
483
484 #[test]
485 fn unknown_fields_are_tolerated() {
486 let tmp = TempDir::new().unwrap();
487 let path = tmp.path().join("config.json");
488 let body = r#"{
489 "schema_version": 2,
490 "wallet_address": "0xabc",
491 "future_field": "ignored",
492 "another": {"nested": true}
493 }"#;
494 fs::write(&path, body).unwrap();
495 let cfg = Config::load(&path).expect("unknown fields should not fail load");
496 assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
497 }
498
499 #[test]
500 fn newer_schema_version_loads_with_warning() {
501 let tmp = TempDir::new().unwrap();
502 let path = tmp.path().join("config.json");
503 let body = format!(
504 r#"{{ "schema_version": {}, "wallet_address": "0xabc" }}"#,
505 CURRENT_SCHEMA_VERSION + 5
506 );
507 fs::write(&path, body).unwrap();
508 let cfg = Config::load(&path).expect("newer version still loads");
509 assert_eq!(cfg.schema_version, CURRENT_SCHEMA_VERSION + 5);
510 assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
511 }
512
513 #[test]
514 fn legacy_api_base_field_hard_errors() {
515 let tmp = TempDir::new().unwrap();
516 let path = tmp.path().join("config.json");
517 let body = r#"{ "schema_version": 1, "api_base": "https://attacker.example" }"#;
518 fs::write(&path, body).unwrap();
519 let err = Config::load(&path).expect_err("legacy api_base must be rejected");
520 let ConfigError::LegacyFields { fields, .. } = err else {
521 panic!("expected LegacyFields, got {err:?}");
522 };
523 assert_eq!(fields, vec!["api_base".to_string()]);
524 }
525
526 #[test]
527 fn legacy_network_field_hard_errors() {
528 let tmp = TempDir::new().unwrap();
529 let path = tmp.path().join("config.json");
530 let body = r#"{ "schema_version": 1, "network": "mainnet" }"#;
531 fs::write(&path, body).unwrap();
532 let err = Config::load(&path).expect_err("legacy network must be rejected");
533 let ConfigError::LegacyFields { fields, .. } = err else {
534 panic!("expected LegacyFields, got {err:?}");
535 };
536 assert_eq!(fields, vec!["network".to_string()]);
537 }
538
539 #[test]
540 fn legacy_error_lists_both_fields_when_present() {
541 let tmp = TempDir::new().unwrap();
542 let path = tmp.path().join("config.json");
543 let body = r#"{ "api_base": "https://x", "network": "testnet" }"#;
544 fs::write(&path, body).unwrap();
545 let err = Config::load(&path).expect_err("both legacy fields must be flagged");
546 let ConfigError::LegacyFields { fields, .. } = err else {
547 panic!("expected LegacyFields, got {err:?}");
548 };
549 assert!(fields.contains(&"api_base".to_string()));
550 assert!(fields.contains(&"network".to_string()));
551 }
552
553 #[test]
554 fn legacy_error_message_names_migration_command() {
555 let tmp = TempDir::new().unwrap();
556 let path = tmp.path().join("config.json");
557 fs::write(&path, r#"{ "api_base": "https://x" }"#).unwrap();
558 let msg = Config::load(&path).unwrap_err().to_string();
559 assert!(
560 msg.contains("taskfast config migrate"),
561 "remediation hint must name the migrate command: {msg}"
562 );
563 }
564
565 #[test]
566 fn empty_config_serializes_compactly() {
567 let body = serde_json::to_string(&Config::default()).unwrap();
570 assert_eq!(body, "{}", "default config should serialize to {{}}");
571 }
572
573 #[test]
574 fn environment_roundtrip() {
575 for env in [Environment::Prod, Environment::Staging, Environment::Local] {
576 let cfg = Config {
577 environment: Some(env),
578 ..Config::default()
579 };
580 let body = serde_json::to_string(&cfg).unwrap();
581 let back: Config = serde_json::from_str(&body).unwrap();
582 assert_eq!(back.environment.map(|e| e.as_str()), Some(env.as_str()));
583 }
584 }
585
586 #[test]
587 fn environment_accepts_production_alias() {
588 let body = r#"{ "environment": "production" }"#;
589 let cfg: Config = serde_json::from_str(body).unwrap();
590 assert!(matches!(cfg.environment, Some(Environment::Prod)));
591 }
592
593 #[test]
594 fn environment_rejects_unknown() {
595 let body = r#"{ "environment": "moon" }"#;
596 let err = serde_json::from_str::<Config>(body).unwrap_err();
597 assert!(err.to_string().contains("moon"));
598 }
599
600 #[cfg(unix)]
601 #[test]
602 fn save_writes_mode_0600_on_unix() {
603 use std::os::unix::fs::PermissionsExt;
604 let tmp = TempDir::new().unwrap();
605 let path = tmp.path().join("config.json");
606 sample().save(&path).expect("save");
607 let meta = fs::metadata(&path).unwrap();
608 let mode = meta.permissions().mode() & 0o777;
609 assert_eq!(mode, 0o600, "expected mode 0600, got {mode:o}");
610 }
611
612 #[test]
613 fn parse_error_includes_path() {
614 let tmp = TempDir::new().unwrap();
615 let path = tmp.path().join("bad.json");
616 fs::write(&path, "{ not json").unwrap();
617 let err = Config::load(&path).unwrap_err();
618 let msg = err.to_string();
619 assert!(msg.contains("bad.json"), "error mentions path: {msg}");
620 }
621}