Skip to main content

orch/config/
mod.rs

1//! Config reader — loads YAML config files and resolves dot-separated keys.
2//!
3//! Reads `~/.orch/config.yml` (global) and `.orch.yml` (project).
4//! Project config overrides global config for the same key.
5//!
6//! Features:
7//! - In-memory cache: parsed YAML is cached for the process lifetime
8//! - File watching: uses notify crate to watch for config file changes
9//! - Hot reload: a changed file is re-parsed into the cache; one that does not
10//!   parse leaves the last good values in place
11//! - Change notifications: subscribers receive events when config files change
12
13pub mod projects_yaml;
14
15use anyhow::Context;
16use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
17use std::collections::{HashMap, HashSet};
18use std::env;
19use std::fs;
20use std::path::{Path, PathBuf};
21use std::sync::LazyLock;
22use std::sync::PoisonError;
23use std::sync::{Arc, Mutex, RwLock};
24use std::time::Duration;
25use tokio::sync::broadcast;
26
27use crate::home;
28
29use tokio::fs as tokio_fs;
30use tokio::runtime::Handle;
31use tokio::runtime::RuntimeFlavor;
32use tokio::task;
33
34/// Cached YAML values — parsed once per file, reused for all key lookups.
35/// Protected by RwLock for concurrent read access.
36static CACHE: LazyLock<RwLock<HashMap<PathBuf, serde_norway::Value>>> =
37    LazyLock::new(|| RwLock::new(HashMap::new()));
38
39/// Files currently being watched for changes.
40static WATCHER: LazyLock<RwLock<HashSet<PathBuf>>> = LazyLock::new(|| RwLock::new(HashSet::new()));
41
42/// Global file watcher instance (started on first use).
43static FILE_WATCHER: LazyLock<Arc<Mutex<Option<RecommendedWatcher>>>> =
44    LazyLock::new(|| Arc::new(Mutex::new(None)));
45
46/// Config files whose content on disk does not read or parse right now.
47/// Tracked so the parse error is logged once per breakage, not once per
48/// watcher event.
49static BAD_FILES: LazyLock<RwLock<HashSet<PathBuf>>> =
50    LazyLock::new(|| RwLock::new(HashSet::new()));
51
52/// Broadcast sender for config change notifications.
53/// Sends the path of the changed config file.
54static CHANGE_TX: LazyLock<broadcast::Sender<PathBuf>> = LazyLock::new(|| {
55    let (tx, _) = broadcast::channel(16);
56    tx
57});
58
59/// Subscribe to config change notifications.
60///
61/// Returns a receiver that fires whenever a watched config file changes.
62/// The receiver yields the path of the changed file.
63pub fn subscribe() -> broadcast::Receiver<PathBuf> {
64    CHANGE_TX.subscribe()
65}
66
67/// Pre-populate the config cache using async I/O.
68///
69/// Call once at engine startup so subsequent synchronous [`get`] / [`get_list`]
70/// calls always hit the in-memory cache and never block a Tokio thread with
71/// `std::fs::read_to_string`.
72pub async fn warm_cache() -> anyhow::Result<()> {
73    let global_path = global_config_path()?;
74    if global_path.exists() {
75        match tokio_fs::read_to_string(&global_path).await {
76            Ok(content) => {
77                if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
78                    if let Ok(mut cache) = CACHE.write() {
79                        cache.insert(global_path.clone(), parsed);
80                    }
81                    watch_file(&global_path);
82                }
83            }
84            Err(e) => tracing::warn!("failed to warm global config cache: {e}"),
85        }
86    }
87
88    let project_path = env::current_dir()
89        .unwrap_or_else(|_| PathBuf::from("."))
90        .join(".orch.yml");
91    if project_path.exists() {
92        match tokio_fs::read_to_string(&project_path).await {
93            Ok(content) => {
94                if let Ok(parsed) = serde_norway::from_str::<serde_norway::Value>(&content) {
95                    if let Ok(mut cache) = CACHE.write() {
96                        cache.insert(project_path.clone(), parsed);
97                    }
98                    watch_file(&project_path);
99                }
100            }
101            Err(e) => tracing::warn!("failed to warm project config cache: {e}"),
102        }
103    }
104
105    Ok(())
106}
107
108/// Clear the entire config cache. Exposed for use by integration tests that
109/// need to run in an isolated config environment (e.g. a temp dir with no
110/// project `.orch.yml`).
111#[cfg(test)]
112pub fn clear_test_cache() {
113    if let Ok(mut cache) = CACHE.write() {
114        cache.clear();
115    }
116}
117
118/// Re-read a changed config file and notify subscribers.
119///
120/// A file that cannot be read or parsed leaves the last good value in the
121/// cache and sends no notification, so a broken or half-written edit cannot
122/// reset the running config to defaults.
123///
124/// Returns true when this call logged a newly invalid file, so repeated
125/// watcher events for one breakage produce one error line
126/// Read a config file written in this process and tell subscribers, the way the watcher does for
127/// an edit. A first-run config did not exist at startup, so nothing watched it yet
128pub fn reloaded(path: &Path) {
129    let path = path.to_path_buf();
130    watch_file(&path);
131    reload_file(&path);
132}
133
134fn reload_file(path: &PathBuf) -> bool {
135    let parsed = fs::read_to_string(path)
136        .map_err(|e| e.to_string())
137        .and_then(|content| {
138            serde_norway::from_str::<serde_norway::Value>(&content).map_err(|e| e.to_string())
139        });
140
141    match parsed {
142        Ok(value) => {
143            if let Ok(mut cache) = CACHE.write() {
144                cache.insert(path.clone(), value);
145            }
146            if let Ok(mut bad) = BAD_FILES.write()
147                && bad.remove(path)
148            {
149                tracing::info!(path = %path.display(), "config file parses again, reloaded");
150            }
151            tracing::debug!("config cache refreshed for: {}", path.display());
152            // Notify subscribers (ignore error if no active receivers)
153            let _ = CHANGE_TX.send(path.clone());
154            false
155        }
156        Err(err) => {
157            let first_failure = BAD_FILES
158                .write()
159                .is_ok_and(|mut bad| bad.insert(path.clone()));
160            if first_failure {
161                tracing::error!(
162                    path = %path.display(),
163                    %err,
164                    "config file is invalid, keeping the last good values"
165                );
166            }
167            first_failure
168        }
169    }
170}
171
172/// Start the file watcher if not already running.
173fn ensure_watcher() {
174    let mut watcher_guard = FILE_WATCHER.lock().unwrap_or_else(PoisonError::into_inner);
175    if watcher_guard.is_some() {
176        return;
177    }
178
179    // Create the watcher
180    let watcher = RecommendedWatcher::new(
181        move |res: Result<notify::Event, notify::Error>| {
182            if let Ok(event) = res {
183                if !is_content_change(event.kind) {
184                    return;
185                }
186                for path in event.paths {
187                    // Check if it's a config file we care about
188                    let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
189
190                    if filename == "config.yml" || filename == ".orch.yml" {
191                        let _ = reload_file(&path);
192                    }
193                }
194            }
195        },
196        Config::default().with_poll_interval(Duration::from_secs(2)),
197    );
198
199    if let Ok(w) = watcher {
200        *watcher_guard = Some(w);
201    }
202}
203
204// inotify reports every read as an access event, and reload_file reads the file, so reacting to
205// access events reloads forever on Linux
206fn is_content_change(kind: notify::EventKind) -> bool {
207    kind.is_create() || kind.is_modify() || kind.is_remove()
208}
209
210/**
211 * Register a config file for change watching. `get` / `get_list` watch the files they read, but a
212 * project's `.orch.yml` is read directly by `get_projects_with_paths`, so the caller that knows the
213 * project list registers it here. A missing path is skipped: notify cannot watch one, and a project
214 * may be configured through the legacy `.orchestrator.yml` name or the global `gh.repo` fallback,
215 * which has no project directory at all
216 **/
217pub fn watch(path: &Path) {
218    if !path.exists() {
219        tracing::debug!(path = %path.display(), "no config file to watch here");
220        return;
221    }
222    watch_file(&path.to_path_buf());
223}
224
225/// Watch a config file for changes.
226fn watch_file(path: &PathBuf) {
227    // First ensure watcher is running
228    ensure_watcher();
229
230    // Track that we want to watch this file
231    if let Ok(mut watched) = WATCHER.write()
232        && !watched.contains(path)
233    {
234        watched.insert(path.clone());
235
236        // Add to notify watcher
237        if let Ok(mut guard) = FILE_WATCHER.lock()
238            && let Some(ref mut watcher) = *guard
239        {
240            match watcher.watch(path, RecursiveMode::NonRecursive) {
241                Ok(()) => tracing::debug!("now watching config file: {}", path.display()),
242                Err(e) => tracing::warn!(
243                    "failed to register config file watcher for {}: {}",
244                    path.display(),
245                    e
246                ),
247            }
248        }
249    }
250}
251
252fn read_file_to_string(path: &Path) -> anyhow::Result<String> {
253    match Handle::try_current() {
254        Ok(handle) if handle.runtime_flavor() == RuntimeFlavor::MultiThread => {
255            Ok(task::block_in_place(|| fs::read_to_string(path))?)
256        }
257        _ => Ok(fs::read_to_string(path)?),
258    }
259}
260
261fn load_cached_root(path: &PathBuf) -> anyhow::Result<serde_norway::Value> {
262    if let Ok(cache) = CACHE.read()
263        && let Some(cached) = cache.get(path)
264    {
265        return Ok(cached.clone());
266    }
267
268    let content =
269        read_file_to_string(path).with_context(|| format!("reading {}", path.display()))?;
270    let parsed: serde_norway::Value =
271        serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?;
272
273    if let Ok(mut cache) = CACHE.write() {
274        cache.insert(path.clone(), parsed.clone());
275    }
276
277    Ok(parsed)
278}
279
280/// Resolve the global config path: `~/.orch/config.yml`
281fn global_config_path() -> anyhow::Result<PathBuf> {
282    home::config_path()
283}
284
285/// Get a config value as a list of strings by dot-separated key.
286///
287/// Supports both YAML sequences and comma-separated strings:
288/// ```yaml
289/// workflow:
290///   allowed_tools:
291///     - Edit
292///     - Write
293///     - git
294/// ```
295/// or:
296/// ```yaml
297/// workflow:
298///   allowed_tools: "Edit,Write,git"
299/// ```
300///
301/// Returns empty vec if key not found.
302pub fn get_list(key: &str) -> anyhow::Result<Vec<String>> {
303    // Try project config first
304    // Use an absolute path so the cache key is stable across tests/processes
305    // that change the current working directory.
306    let project_path = env::current_dir()
307        .unwrap_or_else(|_| PathBuf::from("."))
308        .join(".orch.yml");
309    if project_path.exists()
310        && let Ok(val) = resolve_list(&project_path, key)
311        && !val.is_empty()
312    {
313        return Ok(val);
314    }
315
316    // Fall back to global config
317    let global_path = global_config_path()?;
318    if global_path.exists() {
319        return resolve_list(&global_path, key);
320    }
321
322    Ok(vec![])
323}
324
325/// Resolve a dot-separated key as a list from a YAML file.
326fn resolve_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
327    watch_file(path);
328
329    let root = load_cached_root(path)?;
330
331    Ok(extract_list(&root, key))
332}
333
334/// Extract a list of strings from a YAML tree by dot-separated key.
335fn extract_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
336    let mut current = root;
337    for part in key.split('.') {
338        match current.get(part) {
339            Some(v) => current = v,
340            None => return vec![],
341        }
342    }
343
344    match current {
345        serde_norway::Value::Sequence(seq) => seq
346            .iter()
347            .filter_map(|item| item.as_str().map(String::from))
348            .collect(),
349        serde_norway::Value::String(s) => {
350            // Support comma-separated string format
351            s.split(',')
352                .map(|s| s.trim().to_string())
353                .filter(|s| !s.is_empty())
354                .collect()
355        }
356        _ => vec![],
357    }
358}
359
360/// Get a config value by dot-separated key (e.g. "agents.claude.model").
361///
362/// Lookup order:
363/// 1. `.orch.yml` in the current directory (project config)
364/// 2. `~/.orch/config.yml` (global config)
365///
366/// Returns the first match as a string.
367/// Files are parsed once and cached for the process lifetime.
368pub fn get(key: &str) -> anyhow::Result<String> {
369    // Try project config first
370    // Use an absolute path so the cache key is stable across tests/processes
371    // that change the current working directory.
372    let project_path = env::current_dir()
373        .unwrap_or_else(|_| PathBuf::from("."))
374        .join(".orch.yml");
375    if project_path.exists()
376        && let Ok(val) = resolve_key(&project_path, key)
377    {
378        return Ok(val);
379    }
380
381    // Fall back to global config
382    let global_path = global_config_path()?;
383    if global_path.exists() {
384        return resolve_key(&global_path, key);
385    }
386
387    anyhow::bail!("config key not found: {key}")
388}
389
390/// Like [`get`], but reads the `.orch.yml` in `project_dir`, since the service runs from `/`
391pub fn get_for_project(project_dir: &Path, key: &str) -> anyhow::Result<String> {
392    let project_path = project_dir.join(".orch.yml");
393    if project_path.exists()
394        && let Ok(val) = resolve_key(&project_path, key)
395    {
396        return Ok(val);
397    }
398
399    let global_path = global_config_path()?;
400    if global_path.exists() {
401        return resolve_key(&global_path, key);
402    }
403
404    anyhow::bail!("config key not found: {key}")
405}
406
407/// The project's `.orch.yml` alone, without the global fallback of [`get_for_project`]
408pub fn get_project_only(project_dir: &Path, key: &str) -> anyhow::Result<String> {
409    let project_path = project_dir.join(".orch.yml");
410    if project_path.exists() {
411        return resolve_key(&project_path, key);
412    }
413
414    anyhow::bail!("config key not found: {key}")
415}
416
417/// The global config alone, for a setting no project file may override
418pub fn get_global(key: &str) -> anyhow::Result<String> {
419    let global_path = global_config_path()?;
420    if global_path.exists() {
421        return resolve_key(&global_path, key);
422    }
423
424    anyhow::bail!("config key not found: {key}")
425}
426
427/// Get all project paths from the global config `projects:` list.
428///
429/// Returns a list of absolute paths to project directories.
430/// Each directory should contain a `.orch.yml` with `gh.repo`.
431pub fn get_project_paths() -> anyhow::Result<Vec<String>> {
432    let global_path = global_config_path()?;
433
434    if global_path.exists()
435        && let Ok(paths) = resolve_projects_list(&global_path, "projects")
436        && !paths.is_empty()
437    {
438        return Ok(paths);
439    }
440
441    Ok(vec![])
442}
443
444/// Like `get_projects()` but also returns the project directory path.
445///
446/// Returns `(repo_slug, project_dir)` pairs. Used by the engine to resolve
447/// per-project config (e.g., jobs from each project's `.orch.yml`).
448pub fn get_projects_with_paths() -> anyhow::Result<Vec<(String, PathBuf)>> {
449    let paths = get_project_paths()?;
450
451    if !paths.is_empty() {
452        let mut results = Vec::new();
453        for path_str in &paths {
454            let path = PathBuf::from(path_str);
455            let orch_yml = path.join(".orch.yml");
456
457            let config_file = if orch_yml.exists() {
458                orch_yml
459            } else {
460                let legacy = path.join(".orchestrator.yml");
461                if legacy.exists() {
462                    legacy
463                } else {
464                    continue;
465                }
466            };
467
468            if let Ok(content) = fs::read_to_string(&config_file)
469                && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
470                && let Some(repo) = doc
471                    .get("gh")
472                    .and_then(|gh| gh.get("repo"))
473                    .and_then(|r| r.as_str())
474            {
475                results.push((repo.to_string(), path));
476            }
477        }
478
479        if !results.is_empty() {
480            return Ok(results);
481        }
482    }
483
484    // Fall back to global gh.repo (no project dir available)
485    if let Ok(repo) = get("gh.repo")
486        && !repo.is_empty()
487    {
488        return Ok(vec![(repo, PathBuf::from("."))]);
489    }
490
491    Ok(vec![])
492}
493
494/// Resolve the repo slug for a specific project path.
495///
496/// Reads `gh.repo` from the project's `.orch.yml`.
497pub fn get_repo_for_project(project_path: &Path) -> anyhow::Result<String> {
498    let orch_yml = project_path.join(".orch.yml");
499    let config_file = if orch_yml.exists() {
500        orch_yml
501    } else {
502        let legacy = project_path.join(".orchestrator.yml");
503        if legacy.exists() {
504            legacy
505        } else {
506            anyhow::bail!("no .orch.yml found in {}", project_path.display());
507        }
508    };
509
510    let content = fs::read_to_string(&config_file)?;
511    let doc: serde_norway::Value = serde_norway::from_str(&content)?;
512
513    doc.get("gh")
514        .and_then(|gh| gh.get("repo"))
515        .and_then(|r| r.as_str())
516        .map(String::from)
517        .ok_or_else(|| anyhow::anyhow!("gh.repo not set in {}", config_file.display()))
518}
519
520/// Resolve project path from CWD by finding the nearest `.orch.yml`.
521///
522/// Walks up from the current directory looking for `.orch.yml` or legacy `.orchestrator.yml`.
523pub fn find_project_root() -> anyhow::Result<PathBuf> {
524    let mut dir = env::current_dir()?;
525
526    loop {
527        if dir.join(".orch.yml").exists() || dir.join(".orchestrator.yml").exists() {
528            return Ok(dir);
529        }
530
531        if !dir.pop() {
532            break;
533        }
534    }
535
536    anyhow::bail!("no .orch.yml found in current directory or parents — run `orch init`")
537}
538
539/// Resolve the repo slug for the current project (from CWD).
540///
541/// Walks up from CWD to find `.orch.yml`, reads `gh.repo` from it.
542/// Falls back to global `gh.repo` for backward compatibility.
543pub fn get_current_repo() -> anyhow::Result<String> {
544    // Try to find project root from CWD
545    if let Ok(project_root) = find_project_root()
546        && let Ok(repo) = get_repo_for_project(&project_root)
547    {
548        return Ok(repo);
549    }
550
551    // Fall back to per-project config in CWD (.orch.yml)
552    if let Ok(repo) = get("gh.repo")
553        && !repo.is_empty()
554    {
555        return Ok(repo);
556    }
557
558    // Legacy fallback
559    if let Ok(repo) = get("repo")
560        && !repo.is_empty()
561    {
562        return Ok(repo);
563    }
564
565    anyhow::bail!("could not determine repo — ensure .orch.yml has gh.repo set")
566}
567
568/// Resolve a projects list from a config file.
569fn resolve_projects_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
570    // First, ensure we're watching this file for changes
571    watch_file(path);
572
573    let root = load_cached_root(path)?;
574
575    Ok(extract_projects_list(&root, key))
576}
577
578/// Extract a projects list from a YAML tree.
579fn extract_projects_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
580    let mut current = root;
581    for part in key.split('.') {
582        // If key doesn't exist, return empty vector
583        let Some(next) = current.get(part) else {
584            return vec![];
585        };
586        current = next;
587    }
588
589    match current {
590        serde_norway::Value::Sequence(seq) => {
591            let mut projects = Vec::new();
592            for item in seq {
593                if let serde_norway::Value::String(s) = item {
594                    projects.push(s.clone());
595                } else if let serde_norway::Value::Mapping(map) = item {
596                    // Support map format: { repo: "owner/repo", project_dir: "/path" }
597                    if let Some(serde_norway::Value::String(repo)) = map.get("repo") {
598                        projects.push(repo.clone());
599                    }
600                }
601            }
602            projects
603        }
604        _ => vec![],
605    }
606}
607
608/// Resolve a dot-separated key from a YAML file.
609///
610/// Caches the parsed YAML so repeated lookups don't re-read disk.
611/// Sets up file watching for hot reload when first loading.
612fn resolve_key(path: &PathBuf, key: &str) -> anyhow::Result<String> {
613    // First, ensure we're watching this file for changes
614    watch_file(path);
615
616    let root = load_cached_root(path)?;
617
618    extract_value(&root, key)
619}
620
621/// Extract a value from a YAML tree by dot-separated key.
622fn extract_value(root: &serde_norway::Value, key: &str) -> anyhow::Result<String> {
623    let mut current = root;
624    for part in key.split('.') {
625        current = current
626            .get(part)
627            .with_context(|| format!("key not found: {key}"))?;
628    }
629
630    match current {
631        serde_norway::Value::String(s) => Ok(s.clone()),
632        serde_norway::Value::Number(n) => Ok(n.to_string()),
633        serde_norway::Value::Bool(b) => Ok(b.to_string()),
634        serde_norway::Value::Null => Ok(String::new()),
635        _ => Ok(serde_norway::to_string(current)?),
636    }
637}
638
639#[cfg(test)]
640mod tests {
641    use super::*;
642    use std::io::Write;
643
644    use notify::event::AccessKind;
645    use notify::event::AccessMode;
646    use notify::event::CreateKind;
647    use notify::event::DataChange;
648    use notify::event::ModifyKind;
649    use tokio::sync::broadcast::Receiver;
650
651    use std::fs::File;
652
653    fn write_yaml(dir: &Path, name: &str, content: &str) -> PathBuf {
654        let path = dir.join(name);
655        let mut f = File::create(&path).unwrap();
656        f.write_all(content.as_bytes()).unwrap();
657        path
658    }
659
660    #[test]
661    fn resolve_simple_key() {
662        let dir = tempfile::tempdir().unwrap();
663        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
664        let val = resolve_key(&path, "repo").unwrap();
665        assert_eq!(val, "owner/repo");
666    }
667
668    #[test]
669    fn resolve_nested_key() {
670        let dir = tempfile::tempdir().unwrap();
671        let path = write_yaml(
672            dir.path(),
673            "config.yml",
674            "agents:\n  claude:\n    model: opus\n",
675        );
676        let val = resolve_key(&path, "agents.claude.model").unwrap();
677        assert_eq!(val, "opus");
678    }
679
680    #[test]
681    fn resolve_boolean_value() {
682        let dir = tempfile::tempdir().unwrap();
683        let path = write_yaml(dir.path(), "config.yml", "enabled: true\n");
684        let val = resolve_key(&path, "enabled").unwrap();
685        assert_eq!(val, "true");
686    }
687
688    #[test]
689    fn resolve_number_value() {
690        let dir = tempfile::tempdir().unwrap();
691        let path = write_yaml(dir.path(), "config.yml", "timeout: 300\n");
692        let val = resolve_key(&path, "timeout").unwrap();
693        assert_eq!(val, "300");
694    }
695
696    #[test]
697    fn resolve_missing_key_errors() {
698        let dir = tempfile::tempdir().unwrap();
699        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
700        let result = resolve_key(&path, "missing.key");
701        assert!(result.is_err());
702    }
703
704    #[test]
705    fn resolve_missing_file_errors() {
706        let path = PathBuf::from("/nonexistent/config.yml");
707        let result = resolve_key(&path, "repo");
708        assert!(result.is_err());
709    }
710
711    #[test]
712    fn resolve_projects_list_string_array() {
713        let dir = tempfile::tempdir().unwrap();
714        let path = write_yaml(
715            dir.path(),
716            "config.yml",
717            "projects:\n  - owner/repo1\n  - owner/repo2\n",
718        );
719        let projects = resolve_projects_list(&path, "projects").unwrap();
720        assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
721    }
722
723    #[test]
724    fn resolve_projects_list_map_array() {
725        let dir = tempfile::tempdir().unwrap();
726        let path = write_yaml(
727            dir.path(),
728            "config.yml",
729            "projects:\n  - repo: owner/repo1\n    project_dir: /path/to/repo1\n  - repo: owner/repo2\n    project_dir: /path/to/repo2\n",
730        );
731        let projects = resolve_projects_list(&path, "projects").unwrap();
732        assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
733    }
734
735    #[test]
736    fn resolve_projects_list_fallback_to_repo() {
737        let dir = tempfile::tempdir().unwrap();
738        let path = write_yaml(dir.path(), "config.yml", "repo: owner/single-repo\n");
739        let projects = resolve_projects_list(&path, "projects").unwrap();
740        assert!(projects.is_empty(), "{projects:?}");
741    }
742
743    #[test]
744    fn extract_projects_list_from_sequence() {
745        let yaml =
746            serde_norway::from_str::<serde_norway::Value>("projects:\n  - a\n  - b\n  - c\n")
747                .unwrap();
748        let projects = extract_projects_list(&yaml, "projects");
749        assert_eq!(projects, vec!["a", "b", "c"]);
750    }
751
752    #[test]
753    fn extract_projects_list_from_mapping_sequence() {
754        let yaml =
755            serde_norway::from_str::<serde_norway::Value>("projects:\n  - repo: a\n  - repo: b\n")
756                .unwrap();
757        let projects = extract_projects_list(&yaml, "projects");
758        assert_eq!(projects, vec!["a", "b"]);
759    }
760
761    #[test]
762    fn extract_projects_list_empty_for_missing() {
763        let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
764        let projects = extract_projects_list(&yaml, "projects");
765        assert!(projects.is_empty(), "{projects:?}");
766    }
767
768    #[test]
769    fn subscribe_receives_change_notifications() {
770        let mut rx = subscribe();
771        let dir = tempfile::tempdir().unwrap();
772        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
773
774        // Simulate the watcher firing on a file change
775        assert!(!reload_file(&path));
776
777        // Drain until we find our path (other tests may send on the shared channel)
778        loop {
779            match rx.try_recv() {
780                Ok(received_path) if received_path == path => break,
781                Ok(_) => {} // skip notifications from other tests
782                Err(e) => panic!("expected config change notification, got error: {e:?}"),
783            }
784        }
785    }
786
787    #[test]
788    fn subscribe_multiple_receivers() {
789        let mut rx1 = subscribe();
790        let mut rx2 = subscribe();
791        let dir = tempfile::tempdir().unwrap();
792        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
793
794        assert!(!reload_file(&path));
795
796        // Drain until we find our path on both receivers
797        let find_path = |rx: &mut Receiver<PathBuf>, expected: &PathBuf| loop {
798            match rx.try_recv() {
799                Ok(p) if &p == expected => return,
800                Ok(_) => {}
801                Err(e) => panic!("expected config change notification, got error: {e:?}"),
802            }
803        };
804        find_path(&mut rx1, &path);
805        find_path(&mut rx2, &path);
806    }
807
808    #[test]
809    fn resolve_list_from_sequence() {
810        let dir = tempfile::tempdir().unwrap();
811        let path = write_yaml(
812            dir.path(),
813            "config.yml",
814            "workflow:\n  allowed_tools:\n    - Edit\n    - Write\n    - git\n    - npm\n",
815        );
816        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
817        assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
818    }
819
820    #[test]
821    fn resolve_list_from_comma_string() {
822        let dir = tempfile::tempdir().unwrap();
823        let path = write_yaml(
824            dir.path(),
825            "config.yml",
826            "workflow:\n  allowed_tools: \"Edit,Write,git,npm\"\n",
827        );
828        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
829        assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
830    }
831
832    #[test]
833    fn resolve_list_missing_key_returns_empty() {
834        let dir = tempfile::tempdir().unwrap();
835        let path = write_yaml(dir.path(), "config.yml", "foo: bar\n");
836        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
837        assert!(list.is_empty(), "{list:?}");
838    }
839
840    /**
841     * Read a key straight out of the cache. The reload tests must not call `resolve_key` or
842     * `resolve_projects_list`: those register the file with the real notify watcher, whose thread
843     * then races the test for the first `reload_file` call on a broken edit
844     **/
845    fn cached_value(path: &PathBuf, key: &str) -> String {
846        extract_value(&load_cached_root(path).unwrap(), key).unwrap()
847    }
848
849    fn cached_projects(path: &PathBuf) -> Vec<String> {
850        extract_projects_list(&load_cached_root(path).unwrap(), "projects")
851    }
852
853    #[test]
854    fn reading_a_config_file_does_not_trigger_a_reload() {
855        assert!(!is_content_change(notify::EventKind::Access(
856            AccessKind::Open(AccessMode::Read)
857        )));
858        assert!(!is_content_change(notify::EventKind::Access(
859            AccessKind::Close(AccessMode::Read)
860        )));
861        assert!(is_content_change(notify::EventKind::Modify(
862            ModifyKind::Data(DataChange::Content)
863        )));
864        assert!(is_content_change(notify::EventKind::Create(
865            CreateKind::File
866        )));
867    }
868
869    #[test]
870    fn invalid_edit_keeps_last_good_values_and_sends_no_notification() {
871        let dir = tempfile::tempdir().unwrap();
872        let path = write_yaml(dir.path(), "config.yml", "engine:\n  max_parallel: 8\n");
873        assert!(!reload_file(&path));
874        assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
875
876        let mut rx = subscribe();
877        fs::write(&path, "engine:\n  max_parallel: [unclosed\n").unwrap();
878        assert!(reload_file(&path));
879
880        assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
881        assert!(rx.try_recv().is_err(), "a broken edit must not notify");
882
883        // A later good edit is picked up again
884        fs::write(&path, "engine:\n  max_parallel: 12\n").unwrap();
885        assert!(!reload_file(&path));
886        assert_eq!(cached_value(&path, "engine.max_parallel"), "12");
887    }
888
889    #[test]
890    fn adding_a_project_is_visible_after_reload() {
891        let dir = tempfile::tempdir().unwrap();
892        let path = write_yaml(dir.path(), "config.yml", "projects:\n  - /srv/one\n");
893        assert_eq!(cached_projects(&path), vec!["/srv/one"]);
894
895        fs::write(&path, "projects:\n  - /srv/one\n  - /srv/two\n").unwrap();
896        assert!(!reload_file(&path));
897
898        assert_eq!(cached_projects(&path), vec!["/srv/one", "/srv/two"]);
899    }
900
901    #[test]
902    fn repeated_watcher_events_for_one_breakage_log_once() {
903        let dir = tempfile::tempdir().unwrap();
904        let path = write_yaml(dir.path(), "config.yml", "engine:\n  max_parallel: 4\n");
905        reload_file(&path);
906
907        fs::write(&path, "engine: [broken\n").unwrap();
908        assert!(reload_file(&path), "first bad read logs");
909        assert!(!reload_file(&path), "same breakage does not log again");
910    }
911
912    #[test]
913    #[serial_test::serial(orch_home)]
914    fn a_project_setting_overrides_the_global_one() {
915        let (home, with, without) = (
916            tempfile::tempdir().unwrap(),
917            tempfile::tempdir().unwrap(),
918            tempfile::tempdir().unwrap(),
919        );
920        write_yaml(home.path(), "config.yml", "workflow:\n  sandbox: os\n");
921        write_yaml(with.path(), ".orch.yml", "workflow:\n  sandbox: false\n");
922        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
923        unsafe { env::set_var("ORCH_HOME", home.path()) };
924
925        let got = (
926            get_for_project(with.path(), "workflow.sandbox").unwrap(),
927            get_for_project(without.path(), "workflow.sandbox").unwrap(),
928        );
929        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
930        unsafe { env::remove_var("ORCH_HOME") };
931        assert_eq!(got, ("false".to_string(), "os".to_string()));
932    }
933}