Skip to main content

orch/sys/
home.rs

1//! Home directory utilities.
2//!
3//! All orch state lives under `~/.orch/`. This is completely separate from
4//! the legacy bash orchestrator's `~/.orchestrator/` directory — both tools can
5//! run side by side without conflicts.
6
7use anyhow::Context;
8use std::env;
9use std::fs as std_fs;
10use std::path;
11use std::path::{Path, PathBuf};
12use std::process;
13use std::process::Command;
14use std::thread;
15use std::time::Duration;
16use std::time::Instant;
17use tokio::fs;
18use tokio::runtime::Handle;
19use tokio::runtime::RuntimeFlavor;
20use tokio::task;
21
22/// The home directory name.
23const HOME_DIR: &str = ".orch";
24
25fn ensure_dir(path: &Path) -> anyhow::Result<()> {
26    match Handle::try_current() {
27        Ok(handle) if handle.runtime_flavor() == RuntimeFlavor::MultiThread => {
28            task::block_in_place(|| std_fs::create_dir_all(path))?;
29        }
30        _ => std_fs::create_dir_all(path)?,
31    }
32
33    Ok(())
34}
35
36/// Get the orch home directory path (~/.orch/).
37///
38/// Can be overridden via the `ORCH_HOME` environment variable. This is useful
39/// in tests and CI environments to avoid reading/writing the real state directory.
40pub fn orch_home() -> anyhow::Result<PathBuf> {
41    if let Ok(dir) = env::var("ORCH_HOME") {
42        let path = PathBuf::from(dir);
43        ensure_dir(&path)?;
44        return Ok(path);
45    }
46    let home =
47        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home directory"))?;
48    let path = home.join(HOME_DIR);
49    ensure_dir(&path)?;
50    Ok(path)
51}
52
53fn home_subdir(name: &str) -> anyhow::Result<PathBuf> {
54    let dir = orch_home()?.join(name);
55    ensure_dir(&dir)?;
56    Ok(dir)
57}
58
59/// Get the orch state directory path (~/.orch/state/).
60///
61/// This is where runtime state like logs, prompts, and PID files are stored.
62/// Used across the codebase for runtime state file resolution.
63pub fn state_dir() -> anyhow::Result<PathBuf> {
64    home_subdir("state")
65}
66
67/// Legacy state directories for backward-compatible reads.
68///
69/// Checks legacy `~/.orchestrator/state/` first, then `~/.orchestrator/.orchestrator/`.
70/// Never writes to these locations.
71fn legacy_state_dir() -> Option<PathBuf> {
72    let home = dirs::home_dir()?;
73    // Check legacy ~/.orchestrator/state/ (intermediate migration path)
74    let mid = home.join(".orchestrator").join("state");
75    if mid.is_dir() {
76        return Some(mid);
77    }
78    // Check legacy ~/.orchestrator/.orchestrator/ (original nested path)
79    let old = home.join(".orchestrator").join(".orchestrator");
80    if old.is_dir() {
81        return Some(old);
82    }
83    None
84}
85
86/// Resolve a file inside the state directory, falling back to the legacy
87/// location when the file doesn't exist at the new path yet.
88pub fn state_file(name: &str) -> anyhow::Result<PathBuf> {
89    let new_path = state_dir()?.join(name);
90    if new_path.exists() {
91        return Ok(new_path);
92    }
93    // Check legacy location
94    if let Some(legacy) = legacy_state_dir() {
95        let old_path = legacy.join(name);
96        if old_path.exists() {
97            return Ok(old_path);
98        }
99    }
100    // Return new path even if it doesn't exist yet (for writes)
101    Ok(new_path)
102}
103
104/// Get the path to the global config file (~/.orch/config.yml).
105pub fn config_path() -> anyhow::Result<PathBuf> {
106    Ok(orch_home()?.join("config.yml"))
107}
108
109/// Get the path to the tasks database file (~/.orch/orch.db).
110///
111/// Also migrates legacy `orchestrator.db` → `orch.db` transparently if the old file
112/// exists and the new one does not.
113pub async fn db_path() -> anyhow::Result<PathBuf> {
114    let home = orch_home()?;
115    let new_path = home.join("orch.db");
116    let old_path = home.join("orchestrator.db");
117    if old_path.exists() && !new_path.exists() {
118        fs::rename(&old_path, &new_path).await.with_context(|| {
119            format!(
120                "migrating database from {} to {}",
121                old_path.display(),
122                new_path.display()
123            )
124        })?;
125        tracing::info!("migrated database: legacy orchestrator.db -> orch.db");
126    }
127    Ok(new_path)
128}
129
130/// Get the path to the service version file (~/.orch/state/service.version).
131///
132/// Written by the engine at startup, deleted on graceful shutdown.
133/// Format: "{pid}\t{version}" — the PID lets readers verify the owning process is alive.
134/// Used by service status and diagnostics to detect CLI/service drift.
135pub fn service_version_path() -> anyhow::Result<PathBuf> {
136    Ok(state_dir()?.join("service.version"))
137}
138
139/// Returns `true` if the given PID is alive and is an `orch serve` process.
140pub fn pid_is_orch_serve(pid: u32) -> bool {
141    process_args(pid)
142        .as_deref()
143        .is_some_and(command_line_is_orch_serve)
144}
145
146/// Find all PIDs of running `orch serve` processes.
147pub fn find_orch_serve_pids(exclude_self: bool) -> Vec<u32> {
148    let output = Command::new("pgrep").args(["-x", "orch"]).output().ok();
149
150    let self_pid = process::id();
151    match output {
152        Some(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
153            .lines()
154            .filter_map(|line| line.trim().parse::<u32>().ok())
155            .filter(|pid| !exclude_self || *pid != self_pid)
156            .filter(|pid| pid_is_orch_serve(*pid))
157            .collect(),
158        _ => Vec::new(),
159    }
160}
161
162/// Make this process the only `orch serve`: stop the others, then create the orch directories.
163/// Returns how many other processes it stopped
164pub async fn prepare_serve(kill_timeout: Duration) -> u32 {
165    let killed = kill_other_orch_serve_processes(kill_timeout);
166    if let Err(e) = init_dirs().await {
167        tracing::warn!("failed to initialize orch directories: {e}");
168    }
169    killed
170}
171
172/// Send SIGTERM to other running `orch serve` processes, then SIGKILL stragglers.
173pub fn kill_other_orch_serve_processes(timeout: Duration) -> u32 {
174    let others = find_orch_serve_pids(true);
175    if others.is_empty() {
176        return 0;
177    }
178
179    for pid in &others {
180        tracing::info!(pid, "sending SIGTERM to stale orch serve process");
181        send_signal(*pid, "TERM");
182    }
183
184    let mut remaining = wait_for_orch_serve_exit(others.clone(), timeout);
185    for pid in &remaining {
186        tracing::warn!(pid, "stale orch serve ignored SIGTERM; sending SIGKILL");
187        send_signal(*pid, "KILL");
188    }
189
190    remaining = wait_for_orch_serve_exit(remaining, Duration::from_secs(1));
191    for pid in &remaining {
192        tracing::error!(pid, "stale orch serve survived SIGKILL");
193    }
194
195    u32::try_from(others.len() - remaining.len()).unwrap_or(u32::MAX)
196}
197
198fn process_args(pid: u32) -> Option<String> {
199    let output = Command::new("ps")
200        .args(["-p", &pid.to_string(), "-o", "args="])
201        .output()
202        .ok()?;
203    output
204        .status
205        .success()
206        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
207        .filter(|args| !args.is_empty())
208}
209
210fn command_line_is_orch_serve(cmdline: &str) -> bool {
211    let mut args = cmdline.split_whitespace();
212    let Some(program) = args.next() else {
213        return false;
214    };
215    Path::new(program)
216        .file_name()
217        .and_then(|name| name.to_str())
218        .is_some_and(|name| name == "orch")
219        && args.any(|arg| arg == "serve")
220}
221
222fn send_signal(pid: u32, signal: &str) {
223    let _ = Command::new("kill")
224        .args([format!("-{signal}"), pid.to_string()])
225        .output();
226}
227
228fn wait_for_orch_serve_exit(mut pids: Vec<u32>, timeout: Duration) -> Vec<u32> {
229    let start = Instant::now();
230    while start.elapsed() < timeout && !pids.is_empty() {
231        thread::sleep(Duration::from_millis(200));
232        pids.retain(|pid| pid_is_orch_serve(*pid));
233    }
234    pids
235}
236
237/// Get the path to the worktrees directory (~/.orch/worktrees/).
238pub fn worktrees_dir() -> anyhow::Result<PathBuf> {
239    home_subdir("worktrees")
240}
241
242/// Get the path to the contexts directory (~/.orch/contexts/).
243pub fn contexts_dir() -> anyhow::Result<PathBuf> {
244    home_subdir("contexts")
245}
246
247/// Get the path to the projects directory (~/.orch/projects/).
248pub fn projects_dir() -> anyhow::Result<PathBuf> {
249    home_subdir("projects")
250}
251
252/// Get the per-repo state directory: `~/.orch/state/{owner}/{repo}/`.
253///
254/// Falls back to the flat `~/.orch/state/` if no repo is configured.
255pub fn repo_state_dir(repo: &str) -> anyhow::Result<PathBuf> {
256    let state = state_dir()?;
257    let dir = state.join(repo.replace('/', path::MAIN_SEPARATOR_STR));
258    ensure_dir(&dir)?;
259    Ok(dir)
260}
261
262fn task_dir_path(state: &Path, repo: &str, task_id: &str) -> PathBuf {
263    state
264        .join(repo.replace('/', path::MAIN_SEPARATOR_STR))
265        .join("tasks")
266        .join(task_id)
267}
268
269fn task_attempt_dir_path(state: &Path, repo: &str, task_id: &str, attempt: u32) -> PathBuf {
270    task_dir_path(state, repo, task_id)
271        .join("attempts")
272        .join(attempt.to_string())
273}
274
275/// Get the per-task directory: `~/.orch/state/{owner}/{repo}/tasks/{id}/`.
276///
277/// Creates the directory on demand.
278pub fn task_dir(repo: &str, task_id: &str) -> anyhow::Result<PathBuf> {
279    let dir = task_dir_path(&state_dir()?, repo, task_id);
280    ensure_dir(&dir)?;
281    Ok(dir)
282}
283
284/// Async version of [`task_dir`] — uses `tokio::fs::create_dir_all` to avoid
285/// blocking the Tokio executor when creating a new directory.
286pub async fn task_dir_async(repo: &str, task_id: &str) -> anyhow::Result<PathBuf> {
287    let dir = task_dir_path(&state_dir()?, repo, task_id);
288    fs::create_dir_all(&dir).await?;
289    Ok(dir)
290}
291
292/// Get the per-task attempt directory: `~/.orch/state/{owner}/{repo}/tasks/{id}/attempts/{n}/`.
293///
294/// Creates the directory on demand.
295pub fn task_attempt_dir(repo: &str, task_id: &str, attempt: u32) -> anyhow::Result<PathBuf> {
296    let dir = task_attempt_dir_path(&state_dir()?, repo, task_id, attempt);
297    ensure_dir(&dir)?;
298    Ok(dir)
299}
300
301/// Async version of [`task_attempt_dir`] — uses `tokio::fs::create_dir_all` to
302/// avoid blocking the Tokio executor when creating a new directory.
303pub async fn task_attempt_dir_async(
304    repo: &str,
305    task_id: &str,
306    attempt: u32,
307) -> anyhow::Result<PathBuf> {
308    let dir = task_attempt_dir_path(&state_dir()?, repo, task_id, attempt);
309    fs::create_dir_all(&dir).await?;
310    Ok(dir)
311}
312
313/// Pre-create all standard orch directories using async I/O.
314///
315/// Call once at engine startup before the Tokio thread pool is busy so that
316/// subsequent synchronous callers of [`orch_home`], [`state_dir`], etc. find
317/// the directories already present and their `create_dir_all` calls become
318/// fast no-ops (a single `stat` syscall on an existing path).
319pub async fn init_dirs() -> anyhow::Result<()> {
320    let home = orch_home()?;
321    fs::create_dir_all(&home).await?;
322    for name in ["state", "worktrees", "contexts", "projects"] {
323        fs::create_dir_all(home.join(name)).await?;
324    }
325    Ok(())
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use tempfile::TempDir;
332
333    /// Helper to set ORCH_HOME to a temp dir for the duration of a test.
334    ///
335    /// Returns the temp dir (keep alive for the test) and the previous value of
336    /// ORCH_HOME so the caller can restore it in the test teardown.
337    fn with_temp_orch_home() -> (TempDir, Option<String>) {
338        let temp = TempDir::new().unwrap();
339        let orch_home = temp.path().join(".orch");
340        std_fs::create_dir_all(&orch_home).unwrap();
341        let prev = env::var("ORCH_HOME").ok();
342        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
343        unsafe { env::set_var("ORCH_HOME", &orch_home) };
344        (temp, prev)
345    }
346
347    fn restore_orch_home(prev: Option<String>) {
348        match prev {
349            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
350            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
351            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
352            None => unsafe { env::remove_var("ORCH_HOME") },
353        }
354    }
355
356    #[test]
357    fn test_orch_home_env_override() {
358        let temp = TempDir::new().unwrap();
359        let custom_dir = temp.path().join(".orch-custom");
360        let prev = env::var("ORCH_HOME").ok();
361        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
362        unsafe { env::set_var("ORCH_HOME", &custom_dir) };
363
364        let result = orch_home().unwrap();
365        assert_eq!(result, custom_dir);
366        assert!(result.exists());
367
368        restore_orch_home(prev);
369    }
370
371    #[test]
372    fn test_task_dir_creates_path() {
373        // Use ORCH_HOME so we don't touch the developer's real home dir.
374        let (_temp, prev) = with_temp_orch_home();
375
376        let dir = task_dir("test-owner/test-repo", "42").unwrap();
377        assert!(dir.exists());
378        assert!(dir.ends_with("test-owner/test-repo/tasks/42"));
379
380        restore_orch_home(prev);
381    }
382
383    #[test]
384    fn test_task_attempt_dir_creates_path() {
385        // Use ORCH_HOME so we don't touch the developer's real home dir.
386        let (_temp, prev) = with_temp_orch_home();
387
388        let dir = task_attempt_dir("test-owner/test-repo", "42", 1).unwrap();
389        assert!(dir.exists());
390        assert!(dir.ends_with("test-owner/test-repo/tasks/42/attempts/1"));
391
392        restore_orch_home(prev);
393    }
394
395    #[test]
396    fn test_repo_state_dir_separates_repos() {
397        let (_temp, prev) = with_temp_orch_home();
398
399        let dir_a = repo_state_dir("owner/repo-a").unwrap();
400        let dir_b = repo_state_dir("owner/repo-b").unwrap();
401        assert_ne!(dir_a, dir_b);
402
403        restore_orch_home(prev);
404    }
405
406    #[test]
407    fn home_subdirs_live_under_orch_home_and_are_created() {
408        let (_temp, prev) = with_temp_orch_home();
409        let home = orch_home().unwrap();
410        let dirs = [
411            ("state", state_dir().unwrap()),
412            ("worktrees", worktrees_dir().unwrap()),
413            ("contexts", contexts_dir().unwrap()),
414            ("projects", projects_dir().unwrap()),
415        ];
416        for (name, dir) in dirs {
417            assert_eq!(dir, home.join(name), "{name}");
418            assert!(dir.is_dir(), "{name}");
419        }
420        restore_orch_home(prev);
421    }
422
423    #[tokio::test]
424    async fn init_dirs_creates_the_standard_subdirectories() {
425        let (_temp, prev) = with_temp_orch_home();
426        init_dirs().await.unwrap();
427        let home = orch_home().unwrap();
428        for name in ["state", "worktrees", "contexts", "projects"] {
429            assert!(home.join(name).is_dir(), "{name}");
430        }
431        restore_orch_home(prev);
432    }
433
434    #[tokio::test]
435    async fn task_dir_async_matches_task_dir() {
436        let (_temp, prev) = with_temp_orch_home();
437        let sync = task_dir("owner/repo", "9").unwrap();
438        let async_dir = task_dir_async("owner/repo", "9").await.unwrap();
439        assert_eq!(sync, async_dir);
440        assert!(async_dir.ends_with("owner/repo/tasks/9"));
441        restore_orch_home(prev);
442    }
443
444    #[tokio::test]
445    async fn task_attempt_dir_async_matches_task_attempt_dir() {
446        let (_temp, prev) = with_temp_orch_home();
447        let sync = task_attempt_dir("owner/repo", "9", 2).unwrap();
448        let async_dir = task_attempt_dir_async("owner/repo", "9", 2).await.unwrap();
449        assert_eq!(sync, async_dir);
450        assert!(async_dir.ends_with("owner/repo/tasks/9/attempts/2"));
451        restore_orch_home(prev);
452    }
453
454    #[test]
455    fn pid_is_orch_serve_returns_false_for_nonexistent_pid() {
456        assert!(!pid_is_orch_serve(99999));
457    }
458
459    #[test]
460    fn command_line_is_orch_serve_matches_real_invocations() {
461        assert!(command_line_is_orch_serve("/opt/homebrew/bin/orch serve"));
462        assert!(command_line_is_orch_serve(
463            "/opt/homebrew/Cellar/orch/0.73.18/bin/orch serve --foreground"
464        ));
465        assert!(!command_line_is_orch_serve("/opt/homebrew/bin/orch -V"));
466        assert!(!command_line_is_orch_serve("/bin/sh -c orch serve"));
467        assert!(!command_line_is_orch_serve("/tmp/not-orch serve"));
468    }
469
470    #[test]
471    fn find_orch_serve_pids_does_not_panic() {
472        let pids = find_orch_serve_pids(false);
473        assert!(pids.iter().all(|pid| pid_is_orch_serve(*pid)));
474    }
475
476    #[test]
477    fn find_orch_serve_pids_excludes_self() {
478        let self_pid = process::id();
479        let pids = find_orch_serve_pids(true);
480        assert!(!pids.contains(&self_pid));
481    }
482}