Skip to main content

ralph/config/
resolution.rs

1//! Configuration resolution for Ralph.
2//!
3//! Responsibilities:
4//! - Resolve configuration from multiple layers: global, project, and defaults.
5//! - Discover repository root via `.ralph/` directory or `.git/`.
6//! - Resolve queue/done file paths and ID generation settings.
7//! - Apply profile patches after base config resolution.
8//!
9//! Not handled here:
10//! - Config file loading/parsing (see `super::layer`).
11//! - Config validation (see `super::validation`).
12//!
13//! Invariants/assumptions:
14//! - Config layers are applied in order: defaults, global, project (later overrides earlier).
15//! - Paths are resolved relative to repo root unless absolute.
16//! - Global config resolves from `~/.config/ralph/config.jsonc`.
17//! - Project config resolves from `.ralph/config.jsonc`.
18
19use crate::constants::defaults::DEFAULT_ID_WIDTH;
20use crate::constants::queue::{DEFAULT_DONE_FILE, DEFAULT_ID_PREFIX, DEFAULT_QUEUE_FILE};
21use crate::contracts::Config;
22use crate::fsutil;
23use crate::prompts_internal::validate_instruction_file_paths;
24use anyhow::{Context, Result, bail};
25use std::env;
26use std::path::{Path, PathBuf};
27
28use super::Resolved;
29use super::layer::{ConfigLayer, apply_layer, load_layer};
30use super::trust::load_repo_trust;
31use super::validation::{
32    validate_config, validate_project_execution_trust, validate_queue_done_file_override,
33    validate_queue_file_override, validate_queue_id_prefix_override,
34    validate_queue_id_width_override,
35};
36
37/// Resolve configuration from the current working directory.
38pub fn resolve_from_cwd() -> Result<Resolved> {
39    resolve_from_cwd_internal(true, true, None)
40}
41
42/// Resolve config with an optional profile selection.
43///
44/// The profile is applied after base config resolution but before instruction_files validation.
45pub fn resolve_from_cwd_with_profile(profile: Option<&str>) -> Result<Resolved> {
46    resolve_from_cwd_internal(true, true, profile)
47}
48
49/// Resolve config for the doctor command, skipping instruction_files validation.
50/// This allows doctor to diagnose and warn about missing files without failing early.
51pub fn resolve_from_cwd_for_doctor() -> Result<Resolved> {
52    resolve_from_cwd_internal(false, false, None)
53}
54
55fn resolve_from_cwd_internal(
56    validate_instruction_files: bool,
57    validate_execution_trust: bool,
58    profile: Option<&str>,
59) -> Result<Resolved> {
60    let cwd = env::current_dir().context("resolve current working directory")?;
61    log::debug!("resolving configuration from cwd: {}", cwd.display());
62    let repo_root = find_repo_root(&cwd);
63
64    let global_path = global_config_path();
65    let project_path = project_config_path(&repo_root);
66    let repo_trust = load_repo_trust(&repo_root)?;
67
68    let mut cfg = Config::default();
69    let mut project_layer: Option<ConfigLayer> = None;
70
71    if let Some(path) = global_path.as_ref() {
72        log::debug!("checking global config at: {}", path.display());
73        if path.exists() {
74            log::debug!("loading global config: {}", path.display());
75            let layer = load_layer(path)
76                .with_context(|| format!("load global config {}", path.display()))?;
77            cfg = apply_layer(cfg, layer)
78                .with_context(|| format!("apply global config {}", path.display()))?;
79        }
80    }
81
82    log::debug!("checking project config at: {}", project_path.display());
83    if project_path.exists() {
84        log::debug!("loading project config: {}", project_path.display());
85        let layer = load_layer(&project_path)
86            .with_context(|| format!("load project config {}", project_path.display()))?;
87        project_layer = Some(layer.clone());
88        cfg = apply_layer(cfg, layer)
89            .with_context(|| format!("apply project config {}", project_path.display()))?;
90    }
91
92    if validate_execution_trust {
93        validate_project_execution_trust(project_layer.as_ref(), &repo_trust)?;
94    }
95    validate_config(&cfg)?;
96
97    // Apply selected profile if specified
98    if let Some(name) = profile {
99        apply_profile_patch(&mut cfg, name)?;
100        validate_config(&cfg)?;
101    }
102
103    // Validate instruction_files early for fast feedback (before runtime prompt rendering)
104    if validate_instruction_files {
105        validate_instruction_file_paths(&repo_root, &cfg)
106            .with_context(|| "validate instruction_files from config")?;
107    }
108
109    let id_prefix = resolve_id_prefix(&cfg)?;
110    let id_width = resolve_id_width(&cfg)?;
111    let queue_path = resolve_queue_path(&repo_root, &cfg)?;
112    let done_path = resolve_done_path(&repo_root, &cfg)?;
113
114    log::debug!("resolved repo_root: {}", repo_root.display());
115    log::debug!("resolved queue_path: {}", queue_path.display());
116    log::debug!("resolved done_path: {}", done_path.display());
117
118    Ok(Resolved {
119        config: cfg,
120        repo_root,
121        queue_path,
122        done_path,
123        id_prefix,
124        id_width,
125        global_config_path: global_path,
126        project_config_path: Some(project_path),
127    })
128}
129
130/// Apply a named profile patch to the resolved config.
131///
132/// Profile values are merged into `cfg.agent` using leaf-wise merge semantics.
133fn apply_profile_patch(cfg: &mut Config, name: &str) -> Result<()> {
134    let name = name.trim();
135    if name.is_empty() {
136        bail!("Invalid --profile: name cannot be empty");
137    }
138
139    let patch =
140        crate::agent::resolve_profile_patch(name, cfg.profiles.as_ref()).ok_or_else(|| {
141            let names = crate::agent::all_profile_names(cfg.profiles.as_ref());
142            if names.is_empty() {
143                anyhow::anyhow!(
144                    "Unknown profile: {name:?}. No profiles are configured. Define profiles under the `profiles` key in .ralph/config.jsonc or ~/.config/ralph/config.jsonc."
145                )
146            } else {
147                anyhow::anyhow!(
148                    "Unknown profile: {name:?}. Available configured profiles: {}",
149                    names.into_iter().collect::<Vec<_>>().join(", ")
150                )
151            }
152        })?;
153
154    cfg.agent.merge_from(patch);
155    Ok(())
156}
157
158/// Resolve the queue ID prefix from config.
159pub fn resolve_id_prefix(cfg: &Config) -> Result<String> {
160    validate_queue_id_prefix_override(cfg.queue.id_prefix.as_deref())?;
161    let raw = cfg.queue.id_prefix.as_deref().unwrap_or(DEFAULT_ID_PREFIX);
162    Ok(raw.trim().to_uppercase())
163}
164
165/// Resolve the queue ID width from config.
166pub fn resolve_id_width(cfg: &Config) -> Result<usize> {
167    validate_queue_id_width_override(cfg.queue.id_width)?;
168    Ok(cfg.queue.id_width.unwrap_or(DEFAULT_ID_WIDTH as u8) as usize)
169}
170
171/// Resolve the queue file path from config.
172pub fn resolve_queue_path(repo_root: &Path, cfg: &Config) -> Result<PathBuf> {
173    validate_queue_file_override(cfg.queue.file.as_deref())?;
174
175    // Get the raw path, using default if not specified
176    let raw = cfg
177        .queue
178        .file
179        .clone()
180        .unwrap_or_else(|| PathBuf::from(DEFAULT_QUEUE_FILE));
181
182    let value = fsutil::expand_tilde(&raw);
183    Ok(if value.is_absolute() {
184        value
185    } else {
186        repo_root.join(value)
187    })
188}
189
190/// Resolve the done file path from config.
191pub fn resolve_done_path(repo_root: &Path, cfg: &Config) -> Result<PathBuf> {
192    validate_queue_done_file_override(cfg.queue.done_file.as_deref())?;
193
194    // Get the raw path, using default if not specified
195    let raw = cfg
196        .queue
197        .done_file
198        .clone()
199        .unwrap_or_else(|| PathBuf::from(DEFAULT_DONE_FILE));
200
201    let value = fsutil::expand_tilde(&raw);
202    Ok(if value.is_absolute() {
203        value
204    } else {
205        repo_root.join(value)
206    })
207}
208
209/// Get the path to the global config file.
210pub fn global_config_path() -> Option<PathBuf> {
211    let base = if let Some(value) = env::var_os("XDG_CONFIG_HOME") {
212        PathBuf::from(value)
213    } else {
214        let home = env::var_os("HOME")?;
215        PathBuf::from(home).join(".config")
216    };
217    let ralph_dir = base.join("ralph");
218    Some(ralph_dir.join("config.jsonc"))
219}
220
221/// Get the path to the project config file for a given repo root.
222pub fn project_config_path(repo_root: &Path) -> PathBuf {
223    let ralph_dir = repo_root.join(".ralph");
224    ralph_dir.join("config.jsonc")
225}
226
227/// Find the repository root starting from a given path.
228///
229/// Searches upward for a `.ralph/` directory with marker files
230/// or a `.git/` directory.
231pub fn find_repo_root(start: &Path) -> PathBuf {
232    log::debug!("searching for repo root starting from: {}", start.display());
233    for dir in start.ancestors() {
234        log::debug!("checking directory: {}", dir.display());
235        let ralph_dir = dir.join(".ralph");
236        if ralph_dir.is_dir() {
237            let has_ralph_marker = ["queue.jsonc", "config.jsonc", "done.jsonc"]
238                .iter()
239                .any(|name| ralph_dir.join(name).is_file());
240            if has_ralph_marker {
241                log::debug!("found repo root at: {} (via .ralph/)", dir.display());
242                return dir.to_path_buf();
243            }
244        }
245        if dir.join(".git").exists() {
246            log::debug!("found repo root at: {} (via .git/)", dir.display());
247            return dir.to_path_buf();
248        }
249    }
250    log::debug!(
251        "no repo root found, using start directory: {}",
252        start.display()
253    );
254    start.to_path_buf()
255}