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/// A list from the global config alone, for what only the operator may set
326pub fn get_global_list(key: &str) -> Vec<String> {
327    global_config_path()
328        .ok()
329        .filter(|file| file.exists())
330        .and_then(|file| resolve_list(&file, key).ok())
331        .unwrap_or_default()
332}
333
334/// A list from the project's `.orch.yml` and the global config, both, since each names its own needs
335pub fn get_list_for_project(project_dir: &Path, key: &str) -> Vec<String> {
336    let project = project_dir.join(".orch.yml");
337    let mut found = if project.exists() {
338        resolve_list(&project, key).unwrap_or_default()
339    } else {
340        Vec::new()
341    };
342
343    for item in get_global_list(key) {
344        if !found.contains(&item) {
345            found.push(item);
346        }
347    }
348
349    found
350}
351
352/// Resolve a dot-separated key as a list from a YAML file.
353fn resolve_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
354    watch_file(path);
355
356    let root = load_cached_root(path)?;
357
358    Ok(extract_list(&root, key))
359}
360
361/// Extract a list of strings from a YAML tree by dot-separated key.
362fn extract_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
363    let mut current = root;
364    for part in key.split('.') {
365        match current.get(part) {
366            Some(v) => current = v,
367            None => return vec![],
368        }
369    }
370
371    match current {
372        serde_norway::Value::Sequence(seq) => seq
373            .iter()
374            .filter_map(|item| item.as_str().map(String::from))
375            .collect(),
376        serde_norway::Value::String(s) => {
377            // Support comma-separated string format
378            s.split(',')
379                .map(|s| s.trim().to_string())
380                .filter(|s| !s.is_empty())
381                .collect()
382        }
383        _ => vec![],
384    }
385}
386
387/// Get a config value by dot-separated key (e.g. "agents.claude.model").
388///
389/// Lookup order:
390/// 1. `.orch.yml` in the current directory (project config)
391/// 2. `~/.orch/config.yml` (global config)
392///
393/// Returns the first match as a string.
394/// Files are parsed once and cached for the process lifetime.
395pub fn get(key: &str) -> anyhow::Result<String> {
396    // Try project config first
397    // Use an absolute path so the cache key is stable across tests/processes
398    // that change the current working directory.
399    let project_path = env::current_dir()
400        .unwrap_or_else(|_| PathBuf::from("."))
401        .join(".orch.yml");
402    if project_path.exists()
403        && let Ok(val) = resolve_key(&project_path, key)
404    {
405        return Ok(val);
406    }
407
408    // Fall back to global config
409    let global_path = global_config_path()?;
410    if global_path.exists() {
411        return resolve_key(&global_path, key);
412    }
413
414    anyhow::bail!("config key not found: {key}")
415}
416
417/// Like [`get`], but reads the `.orch.yml` in `project_dir`, since the service runs from `/`
418pub fn get_for_project(project_dir: &Path, key: &str) -> anyhow::Result<String> {
419    let project_path = project_dir.join(".orch.yml");
420    if project_path.exists()
421        && let Ok(val) = resolve_key(&project_path, key)
422    {
423        return Ok(val);
424    }
425
426    let global_path = global_config_path()?;
427    if global_path.exists() {
428        return resolve_key(&global_path, key);
429    }
430
431    anyhow::bail!("config key not found: {key}")
432}
433
434/// The project's `.orch.yml` alone, without the global fallback of [`get_for_project`]
435pub fn get_project_only(project_dir: &Path, key: &str) -> anyhow::Result<String> {
436    let project_path = project_dir.join(".orch.yml");
437    if project_path.exists() {
438        return resolve_key(&project_path, key);
439    }
440
441    anyhow::bail!("config key not found: {key}")
442}
443
444/// The global config alone, for a setting no project file may override
445pub fn get_global(key: &str) -> anyhow::Result<String> {
446    let global_path = global_config_path()?;
447    if global_path.exists() {
448        return resolve_key(&global_path, key);
449    }
450
451    anyhow::bail!("config key not found: {key}")
452}
453
454/// Get all project paths from the global config `projects:` list.
455///
456/// Returns a list of absolute paths to project directories.
457/// Each directory should contain a `.orch.yml` with `gh.repo`.
458pub fn get_project_paths() -> anyhow::Result<Vec<String>> {
459    let global_path = global_config_path()?;
460
461    if global_path.exists()
462        && let Ok(paths) = resolve_projects_list(&global_path, "projects")
463        && !paths.is_empty()
464    {
465        return Ok(paths);
466    }
467
468    Ok(vec![])
469}
470
471/// Like `get_projects()` but also returns the project directory path.
472///
473/// Returns `(repo_slug, project_dir)` pairs. Used by the engine to resolve
474/// per-project config (e.g., jobs from each project's `.orch.yml`).
475pub fn get_projects_with_paths() -> anyhow::Result<Vec<(String, PathBuf)>> {
476    let paths = get_project_paths()?;
477
478    if !paths.is_empty() {
479        let mut results = Vec::new();
480        for path_str in &paths {
481            let path = PathBuf::from(path_str);
482            let orch_yml = path.join(".orch.yml");
483
484            let config_file = if orch_yml.exists() {
485                orch_yml
486            } else {
487                let legacy = path.join(".orchestrator.yml");
488                if legacy.exists() {
489                    legacy
490                } else {
491                    continue;
492                }
493            };
494
495            if let Ok(content) = fs::read_to_string(&config_file)
496                && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
497                && let Some(repo) = doc
498                    .get("gh")
499                    .and_then(|gh| gh.get("repo"))
500                    .and_then(|r| r.as_str())
501            {
502                results.push((repo.to_string(), path));
503            }
504        }
505
506        if !results.is_empty() {
507            return Ok(results);
508        }
509    }
510
511    // Fall back to global gh.repo (no project dir available)
512    if let Ok(repo) = get("gh.repo")
513        && !repo.is_empty()
514    {
515        return Ok(vec![(repo, PathBuf::from("."))]);
516    }
517
518    Ok(vec![])
519}
520
521/// Resolve the repo slug for a specific project path.
522///
523/// Reads `gh.repo` from the project's `.orch.yml`.
524pub fn get_repo_for_project(project_path: &Path) -> anyhow::Result<String> {
525    let orch_yml = project_path.join(".orch.yml");
526    let config_file = if orch_yml.exists() {
527        orch_yml
528    } else {
529        let legacy = project_path.join(".orchestrator.yml");
530        if legacy.exists() {
531            legacy
532        } else {
533            anyhow::bail!("no .orch.yml found in {}", project_path.display());
534        }
535    };
536
537    let content = fs::read_to_string(&config_file)?;
538    let doc: serde_norway::Value = serde_norway::from_str(&content)?;
539
540    doc.get("gh")
541        .and_then(|gh| gh.get("repo"))
542        .and_then(|r| r.as_str())
543        .map(String::from)
544        .ok_or_else(|| anyhow::anyhow!("gh.repo not set in {}", config_file.display()))
545}
546
547/// Resolve project path from CWD by finding the nearest `.orch.yml`.
548///
549/// Walks up from the current directory looking for `.orch.yml` or legacy `.orchestrator.yml`.
550pub fn find_project_root() -> anyhow::Result<PathBuf> {
551    let mut dir = env::current_dir()?;
552
553    loop {
554        if dir.join(".orch.yml").exists() || dir.join(".orchestrator.yml").exists() {
555            return Ok(dir);
556        }
557
558        if !dir.pop() {
559            break;
560        }
561    }
562
563    anyhow::bail!("no .orch.yml found in current directory or parents — run `orch init`")
564}
565
566/// Resolve the repo slug for the current project (from CWD).
567///
568/// Walks up from CWD to find `.orch.yml`, reads `gh.repo` from it.
569/// Falls back to global `gh.repo` for backward compatibility.
570pub fn get_current_repo() -> anyhow::Result<String> {
571    // Try to find project root from CWD
572    if let Ok(project_root) = find_project_root()
573        && let Ok(repo) = get_repo_for_project(&project_root)
574    {
575        return Ok(repo);
576    }
577
578    // Fall back to per-project config in CWD (.orch.yml)
579    if let Ok(repo) = get("gh.repo")
580        && !repo.is_empty()
581    {
582        return Ok(repo);
583    }
584
585    // Legacy fallback
586    if let Ok(repo) = get("repo")
587        && !repo.is_empty()
588    {
589        return Ok(repo);
590    }
591
592    anyhow::bail!("could not determine repo — ensure .orch.yml has gh.repo set")
593}
594
595/// Resolve a projects list from a config file.
596fn resolve_projects_list(path: &PathBuf, key: &str) -> anyhow::Result<Vec<String>> {
597    // First, ensure we're watching this file for changes
598    watch_file(path);
599
600    let root = load_cached_root(path)?;
601
602    Ok(extract_projects_list(&root, key))
603}
604
605/// Extract a projects list from a YAML tree.
606fn extract_projects_list(root: &serde_norway::Value, key: &str) -> Vec<String> {
607    let mut current = root;
608    for part in key.split('.') {
609        // If key doesn't exist, return empty vector
610        let Some(next) = current.get(part) else {
611            return vec![];
612        };
613        current = next;
614    }
615
616    match current {
617        serde_norway::Value::Sequence(seq) => {
618            let mut projects = Vec::new();
619            for item in seq {
620                if let serde_norway::Value::String(s) = item {
621                    projects.push(s.clone());
622                } else if let serde_norway::Value::Mapping(map) = item {
623                    // Support map format: { repo: "owner/repo", project_dir: "/path" }
624                    if let Some(serde_norway::Value::String(repo)) = map.get("repo") {
625                        projects.push(repo.clone());
626                    }
627                }
628            }
629            projects
630        }
631        _ => vec![],
632    }
633}
634
635/// Resolve a dot-separated key from a YAML file.
636///
637/// Caches the parsed YAML so repeated lookups don't re-read disk.
638/// Sets up file watching for hot reload when first loading.
639fn resolve_key(path: &PathBuf, key: &str) -> anyhow::Result<String> {
640    // First, ensure we're watching this file for changes
641    watch_file(path);
642
643    let root = load_cached_root(path)?;
644
645    extract_value(&root, key)
646}
647
648/// Extract a value from a YAML tree by dot-separated key.
649fn extract_value(root: &serde_norway::Value, key: &str) -> anyhow::Result<String> {
650    let mut current = root;
651    for part in key.split('.') {
652        current = current
653            .get(part)
654            .with_context(|| format!("key not found: {key}"))?;
655    }
656
657    match current {
658        serde_norway::Value::String(s) => Ok(s.clone()),
659        serde_norway::Value::Number(n) => Ok(n.to_string()),
660        serde_norway::Value::Bool(b) => Ok(b.to_string()),
661        serde_norway::Value::Null => Ok(String::new()),
662        _ => Ok(serde_norway::to_string(current)?),
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use std::io::Write;
670
671    use notify::event::AccessKind;
672    use notify::event::AccessMode;
673    use notify::event::CreateKind;
674    use notify::event::DataChange;
675    use notify::event::ModifyKind;
676    use tokio::sync::broadcast::Receiver;
677
678    use std::fs::File;
679
680    fn write_yaml(dir: &Path, name: &str, content: &str) -> PathBuf {
681        let path = dir.join(name);
682        let mut f = File::create(&path).unwrap();
683        f.write_all(content.as_bytes()).unwrap();
684        path
685    }
686
687    #[test]
688    fn resolve_simple_key() {
689        let dir = tempfile::tempdir().unwrap();
690        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
691        let val = resolve_key(&path, "repo").unwrap();
692        assert_eq!(val, "owner/repo");
693    }
694
695    #[test]
696    fn resolve_nested_key() {
697        let dir = tempfile::tempdir().unwrap();
698        let path = write_yaml(
699            dir.path(),
700            "config.yml",
701            "agents:\n  claude:\n    model: opus\n",
702        );
703        let val = resolve_key(&path, "agents.claude.model").unwrap();
704        assert_eq!(val, "opus");
705    }
706
707    #[test]
708    fn resolve_boolean_value() {
709        let dir = tempfile::tempdir().unwrap();
710        let path = write_yaml(dir.path(), "config.yml", "enabled: true\n");
711        let val = resolve_key(&path, "enabled").unwrap();
712        assert_eq!(val, "true");
713    }
714
715    #[test]
716    fn resolve_number_value() {
717        let dir = tempfile::tempdir().unwrap();
718        let path = write_yaml(dir.path(), "config.yml", "timeout: 300\n");
719        let val = resolve_key(&path, "timeout").unwrap();
720        assert_eq!(val, "300");
721    }
722
723    #[test]
724    fn resolve_missing_key_errors() {
725        let dir = tempfile::tempdir().unwrap();
726        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
727        let result = resolve_key(&path, "missing.key");
728        assert!(result.is_err());
729    }
730
731    #[test]
732    fn resolve_missing_file_errors() {
733        let path = PathBuf::from("/nonexistent/config.yml");
734        let result = resolve_key(&path, "repo");
735        assert!(result.is_err());
736    }
737
738    #[test]
739    fn resolve_projects_list_string_array() {
740        let dir = tempfile::tempdir().unwrap();
741        let path = write_yaml(
742            dir.path(),
743            "config.yml",
744            "projects:\n  - owner/repo1\n  - owner/repo2\n",
745        );
746        let projects = resolve_projects_list(&path, "projects").unwrap();
747        assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
748    }
749
750    #[test]
751    fn resolve_projects_list_map_array() {
752        let dir = tempfile::tempdir().unwrap();
753        let path = write_yaml(
754            dir.path(),
755            "config.yml",
756            "projects:\n  - repo: owner/repo1\n    project_dir: /path/to/repo1\n  - repo: owner/repo2\n    project_dir: /path/to/repo2\n",
757        );
758        let projects = resolve_projects_list(&path, "projects").unwrap();
759        assert_eq!(projects, vec!["owner/repo1", "owner/repo2"]);
760    }
761
762    #[test]
763    fn resolve_projects_list_fallback_to_repo() {
764        let dir = tempfile::tempdir().unwrap();
765        let path = write_yaml(dir.path(), "config.yml", "repo: owner/single-repo\n");
766        let projects = resolve_projects_list(&path, "projects").unwrap();
767        assert!(projects.is_empty(), "{projects:?}");
768    }
769
770    #[test]
771    fn extract_projects_list_from_sequence() {
772        let yaml =
773            serde_norway::from_str::<serde_norway::Value>("projects:\n  - a\n  - b\n  - c\n")
774                .unwrap();
775        let projects = extract_projects_list(&yaml, "projects");
776        assert_eq!(projects, vec!["a", "b", "c"]);
777    }
778
779    #[test]
780    fn extract_projects_list_from_mapping_sequence() {
781        let yaml =
782            serde_norway::from_str::<serde_norway::Value>("projects:\n  - repo: a\n  - repo: b\n")
783                .unwrap();
784        let projects = extract_projects_list(&yaml, "projects");
785        assert_eq!(projects, vec!["a", "b"]);
786    }
787
788    #[test]
789    fn extract_projects_list_empty_for_missing() {
790        let yaml = serde_norway::from_str::<serde_norway::Value>("foo: bar").unwrap();
791        let projects = extract_projects_list(&yaml, "projects");
792        assert!(projects.is_empty(), "{projects:?}");
793    }
794
795    #[test]
796    fn subscribe_receives_change_notifications() {
797        let mut rx = subscribe();
798        let dir = tempfile::tempdir().unwrap();
799        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
800
801        // Simulate the watcher firing on a file change
802        assert!(!reload_file(&path));
803
804        // Drain until we find our path (other tests may send on the shared channel)
805        loop {
806            match rx.try_recv() {
807                Ok(received_path) if received_path == path => break,
808                Ok(_) => {} // skip notifications from other tests
809                Err(e) => panic!("expected config change notification, got error: {e:?}"),
810            }
811        }
812    }
813
814    #[test]
815    fn subscribe_multiple_receivers() {
816        let mut rx1 = subscribe();
817        let mut rx2 = subscribe();
818        let dir = tempfile::tempdir().unwrap();
819        let path = write_yaml(dir.path(), "config.yml", "repo: owner/repo\n");
820
821        assert!(!reload_file(&path));
822
823        // Drain until we find our path on both receivers
824        let find_path = |rx: &mut Receiver<PathBuf>, expected: &PathBuf| loop {
825            match rx.try_recv() {
826                Ok(p) if &p == expected => return,
827                Ok(_) => {}
828                Err(e) => panic!("expected config change notification, got error: {e:?}"),
829            }
830        };
831        find_path(&mut rx1, &path);
832        find_path(&mut rx2, &path);
833    }
834
835    #[test]
836    fn resolve_list_from_sequence() {
837        let dir = tempfile::tempdir().unwrap();
838        let path = write_yaml(
839            dir.path(),
840            "config.yml",
841            "workflow:\n  allowed_tools:\n    - Edit\n    - Write\n    - git\n    - npm\n",
842        );
843        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
844        assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
845    }
846
847    #[test]
848    fn resolve_list_from_comma_string() {
849        let dir = tempfile::tempdir().unwrap();
850        let path = write_yaml(
851            dir.path(),
852            "config.yml",
853            "workflow:\n  allowed_tools: \"Edit,Write,git,npm\"\n",
854        );
855        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
856        assert_eq!(list, vec!["Edit", "Write", "git", "npm"]);
857    }
858
859    #[test]
860    fn resolve_list_missing_key_returns_empty() {
861        let dir = tempfile::tempdir().unwrap();
862        let path = write_yaml(dir.path(), "config.yml", "foo: bar\n");
863        let list = resolve_list(&path, "workflow.allowed_tools").unwrap();
864        assert!(list.is_empty(), "{list:?}");
865    }
866
867    /**
868     * Read a key straight out of the cache. The reload tests must not call `resolve_key` or
869     * `resolve_projects_list`: those register the file with the real notify watcher, whose thread
870     * then races the test for the first `reload_file` call on a broken edit
871     **/
872    fn cached_value(path: &PathBuf, key: &str) -> String {
873        extract_value(&load_cached_root(path).unwrap(), key).unwrap()
874    }
875
876    fn cached_projects(path: &PathBuf) -> Vec<String> {
877        extract_projects_list(&load_cached_root(path).unwrap(), "projects")
878    }
879
880    #[test]
881    fn reading_a_config_file_does_not_trigger_a_reload() {
882        assert!(!is_content_change(notify::EventKind::Access(
883            AccessKind::Open(AccessMode::Read)
884        )));
885        assert!(!is_content_change(notify::EventKind::Access(
886            AccessKind::Close(AccessMode::Read)
887        )));
888        assert!(is_content_change(notify::EventKind::Modify(
889            ModifyKind::Data(DataChange::Content)
890        )));
891        assert!(is_content_change(notify::EventKind::Create(
892            CreateKind::File
893        )));
894    }
895
896    #[test]
897    fn invalid_edit_keeps_last_good_values_and_sends_no_notification() {
898        let dir = tempfile::tempdir().unwrap();
899        let path = write_yaml(dir.path(), "config.yml", "engine:\n  max_parallel: 8\n");
900        assert!(!reload_file(&path));
901        assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
902
903        let mut rx = subscribe();
904        fs::write(&path, "engine:\n  max_parallel: [unclosed\n").unwrap();
905        assert!(reload_file(&path));
906
907        assert_eq!(cached_value(&path, "engine.max_parallel"), "8");
908        assert!(rx.try_recv().is_err(), "a broken edit must not notify");
909
910        // A later good edit is picked up again
911        fs::write(&path, "engine:\n  max_parallel: 12\n").unwrap();
912        assert!(!reload_file(&path));
913        assert_eq!(cached_value(&path, "engine.max_parallel"), "12");
914    }
915
916    #[test]
917    fn adding_a_project_is_visible_after_reload() {
918        let dir = tempfile::tempdir().unwrap();
919        let path = write_yaml(dir.path(), "config.yml", "projects:\n  - /srv/one\n");
920        assert_eq!(cached_projects(&path), vec!["/srv/one"]);
921
922        fs::write(&path, "projects:\n  - /srv/one\n  - /srv/two\n").unwrap();
923        assert!(!reload_file(&path));
924
925        assert_eq!(cached_projects(&path), vec!["/srv/one", "/srv/two"]);
926    }
927
928    #[test]
929    fn repeated_watcher_events_for_one_breakage_log_once() {
930        let dir = tempfile::tempdir().unwrap();
931        let path = write_yaml(dir.path(), "config.yml", "engine:\n  max_parallel: 4\n");
932        reload_file(&path);
933
934        fs::write(&path, "engine: [broken\n").unwrap();
935        assert!(reload_file(&path), "first bad read logs");
936        assert!(!reload_file(&path), "same breakage does not log again");
937    }
938
939    #[test]
940    #[serial_test::serial(orch_home)]
941    fn a_project_setting_overrides_the_global_one() {
942        let (home, with, without) = (
943            tempfile::tempdir().unwrap(),
944            tempfile::tempdir().unwrap(),
945            tempfile::tempdir().unwrap(),
946        );
947        write_yaml(home.path(), "config.yml", "workflow:\n  sandbox: os\n");
948        write_yaml(with.path(), ".orch.yml", "workflow:\n  sandbox: false\n");
949        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
950        unsafe { env::set_var("ORCH_HOME", home.path()) };
951
952        let got = (
953            get_for_project(with.path(), "workflow.sandbox").unwrap(),
954            get_for_project(without.path(), "workflow.sandbox").unwrap(),
955        );
956        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
957        unsafe { env::remove_var("ORCH_HOME") };
958        assert_eq!(got, ("false".to_string(), "os".to_string()));
959    }
960}