Skip to main content

base/paths/
mod.rs

1//! Data directory path abstraction.
2//!
3//! `ConfigPaths` provides a single source of truth for all persistent
4//! directories used by the AGENT: a flat cross-scene **global** root
5//! (conventionally `~/.agix/`), a **scene**-specific override root nested
6//! under it (`<global>/scenes/<scope>/`), and a **local**/project root
7//! (`<cwd>/<project dir>/`, `.agix` unless the instance's [`Layout`] names
8//! another). The names themselves are in [`layout`].
9//!
10//! **The roots are given, never discovered.** Nothing in this module reads
11//! the environment: the process entry point decides which directory the
12//! instance owns and passes it down. `~/.agix` is what that entry point
13//! usually picks, not something the library assumes — which is what lets a
14//! test, a service account, or a deployment with its state elsewhere work
15//! without every module having to agree separately.
16//!
17//! `scope` identifies which product built on this engine owns the
18//! scene-specific override state (e.g. a coding-agent product might use
19//! `"code"`). The engine never assumes a default — callers must pass one
20//! explicitly. The local/project root is flat and has no scope segment: a
21//! project is assumed to be worked on by one product instance at a time, so
22//! there's no collision to avoid the way there is under a shared `$HOME`.
23//!
24//! The user-level tree is split by resource type:
25//!
26//! - **Global + scene override** (config-shaped, keyed by name): `settings.json`,
27//!   `skills/`, `plugins/`, `agents/`, `rules/`, `hooks/`. Present at both
28//!   `~/.agix/<resource>/` (base) and `~/.agix/scenes/<scope>/<resource>/`
29//!   (override) — a scene-specific entry with the same name wins.
30//! - **Global + project only, no scene tier** (history/state-shaped):
31//!   `memory/`, `sessions/`, `recordings/`. Present at `~/.agix/<resource>/`
32//!   and, for what a project keeps of its own, under the project
33//!   directory's `state/` (`<cwd>/.agix/state/<resource>/`), which holds
34//!   everything the engine writes there for this machine alone and which
35//!   the project's `.gitignore` keeps out whole. Deliberately **not**
36//!   scene-scoped: a scene's tool/system-prompt config has no bearing on
37//!   which project a session or memory file belongs to, so borrowing across
38//!   scenes would be a correctness hazard (e.g. resuming a session recorded
39//!   under a different scene's tool set, or a recording replaying against the
40//!   wrong tool config).
41//!
42//! Project-level skills are **not** under `ConfigPaths` at all — they live in
43//! `.agents/skills/`, a sibling of `.agix/`, because that's the path Codex
44//! and other external agent tools scan. `ConfigPaths` only models Agix's
45//! own private state and extensions, which no other tool reads.
46
47pub mod layout;
48mod sensitive;
49
50pub use layout::{
51    entry, ConfigRoot, EngineNameError, Layout, LayoutError, ProductNameError, StateRoot,
52    WorktreesDirError, AGENTS_DIR, CLAUDE_DIR, DEFAULT_ENGINE, DEFAULT_PRODUCT_NAME,
53    DEFAULT_PRODUCT_URL, DEFAULT_PROJECT_DIR, DEFAULT_STATE_DIR, DEFAULT_WORKTREES_DIR,
54    ENGINE_CONFIG_DIRS, ENGINE_CONFIG_FILES, FOREIGN_CONFIG_ROOTS, GIT_WORKTREES_DIR,
55    LOCAL_CONFIG_FILES, PROJECT_ENGINE_CONFIG_DIRS, PROJECT_SKILLS_DIR, PROJECT_STATE_ENGINE_DIRS,
56    PROJECT_STATE_ENTRIES, SETTINGS_FILE, SETTINGS_LOCAL_FILE, STATE_RESERVED_NAMES,
57    STATE_ROOT_SCENE_FILES, STATE_ROOT_SCRATCHPAD, STATE_ROOT_SESSION_TMP, STATE_ROOT_WORKING_DIRS,
58};
59pub use sensitive::{
60    credential_dir_names, known_state_roots, session_scratch_dir, tool_results_dir, ConfigRootAt,
61    Credential, KeyFileNames, Located, PromptFiles, Scope, Secret, SensitivePaths, CREDENTIALS,
62    GIT_CONTROL_FILES, GIT_HOOKS_DIR, GIT_WORKTREE_CONTROL_FILES, HOME_CREDENTIAL_STORES,
63    REPOSITORY_CONFIG_DIR, SECRET_FILE_NAMES,
64};
65
66use std::path::{Path, PathBuf};
67
68use crate::interface::config_source::Tier;
69
70use serde::{Deserialize, Serialize};
71
72/// This machine's home directory: `HOME`, else `USERPROFILE`; an empty value counts as unset.
73#[expect(
74    clippy::disallowed_methods,
75    reason = "the one place this machine's home is looked up"
76)]
77pub fn home_dir() -> Option<PathBuf> {
78    std::env::var_os("HOME")
79        .or_else(|| std::env::var_os("USERPROFILE"))
80        .filter(|h| !h.is_empty())
81        .map(PathBuf::from)
82}
83
84/// `text` compared without case the way a case-insensitive filesystem
85/// compares names: lowercased, and each character whose full case folding is
86/// ASCII written as that folding.
87///
88/// `to_lowercase` alone is not enough: APFS folds `ſ` to `s`, `ß` to `ss`
89/// and `fi` to `fi`, which lowercasing leaves as they are, so `.agentſ/ſkills`
90/// opens `.agents/skills` there while comparing unequal here.
91pub fn fold_case(text: &str) -> String {
92    let mut folded = String::with_capacity(text.len());
93    for c in text.chars() {
94        match c {
95            '\u{17F}' => folded.push('s'),
96            '\u{DF}' | '\u{1E9E}' => folded.push_str("ss"),
97            '\u{FB00}' => folded.push_str("ff"),
98            '\u{FB01}' => folded.push_str("fi"),
99            '\u{FB02}' => folded.push_str("fl"),
100            '\u{FB03}' => folded.push_str("ffi"),
101            '\u{FB04}' => folded.push_str("ffl"),
102            '\u{FB05}' | '\u{FB06}' => folded.push_str("st"),
103            _ => folded.extend(c.to_lowercase()),
104        }
105    }
106    folded
107}
108
109/// Path configuration for data directories.
110#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
111#[non_exhaustive]
112pub struct PathSettings {
113    /// User-level, scene-specific override root (e.g. `~/.agix/scenes/<scope>/`).
114    pub user_data_dir: PathBuf,
115    /// User-level, cross-scene global root — flat, shared by every scene
116    /// (e.g. `~/.agix/`). Used by resources that don't have a scene tier
117    /// (`memory`/`sessions`/`recordings`/`mcp`) and as the base layer for resources
118    /// that do (`settings.json`/`skills`/`plugins`/`agents`/`rules`/`hooks`).
119    /// See `base::paths::ConfigPaths` module docs for the full breakdown.
120    #[serde(default)]
121    pub global_data_dir: PathBuf,
122    /// The project tier's root: `<project>/<project dir>/` in a project, the state
123    /// root itself (`global_data_dir`) in a session without one.
124    pub local_data_dir: PathBuf,
125    /// Where the session's tools work, and whether there is a project.
126    pub workspace: Workspace,
127    /// Which product instance's user-level state `user_data_dir` was built
128    /// for (see `base::paths::ConfigPaths`). Carried alongside the resolved
129    /// dirs so downstream code (e.g. `FrozenContext::collect_environment`) doesn't have
130    /// to re-derive it from the path.
131    #[serde(default = "default_scope")]
132    pub scope: String,
133    /// The project is not trusted: what its tier holds under a name the user
134    /// tier also holds does not replace the user's.
135    #[serde(skip)]
136    #[schemars(skip)]
137    pub project_untrusted: bool,
138    /// What the instance names its directories; `local_data_dir` is
139    /// [`Layout::project_dir`] of the project.
140    #[serde(skip)]
141    #[schemars(skip)]
142    pub layout: Layout,
143}
144
145/// A linked worktree of the project, and where in the repository's git
146/// directory a commit in it writes.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct LinkedWorktree {
149    pub dir: PathBuf,
150    /// As the engine found it when it made the worktree. Never re-read from
151    /// the worktree's `.git` link or the `commondir` it leads to: a
152    /// sandboxed command may have rewritten both since. `None`: nothing in
153    /// the repository's git directory is writable, so a sandboxed command
154    /// cannot commit there.
155    pub git: Option<WorktreeGit>,
156}
157
158/// The parts of the repository's git directory that a commit in one linked
159/// worktree writes.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct WorktreeGit {
162    /// The repository's git directory.
163    pub dir: PathBuf,
164    /// The worktree's entry under `dir/worktrees/`: its `HEAD`, index and
165    /// `HEAD` reflog.
166    pub admin: PathBuf,
167    /// The branch checked out in it, e.g. `agix/worktree-x`.
168    pub branch: String,
169}
170
171impl WorktreeGit {
172    /// The loose ref of [`Self::branch`]. git rewrites it by renaming
173    /// `<ref>.lock` over it.
174    pub fn branch_ref(&self) -> PathBuf {
175        self.dir.join("refs/heads").join(&self.branch)
176    }
177
178    pub fn branch_ref_lock(&self) -> PathBuf {
179        let mut lock = self.branch_ref().into_os_string();
180        lock.push(".lock");
181        PathBuf::from(lock)
182    }
183
184    /// What a commit writes: the object store, the worktree's entry, the
185    /// branch's ref, its lock and its reflog. Nothing else in `dir` — not
186    /// the other refs, `packed-refs`, `info/` or the main worktree's files.
187    /// `objects/info/` and the entry's control files are held read-only on
188    /// top by the sandbox.
189    pub fn writable(&self) -> Vec<PathBuf> {
190        vec![
191            self.dir.join("objects"),
192            self.admin.clone(),
193            self.branch_ref(),
194            self.branch_ref_lock(),
195            self.dir.join("logs/refs/heads").join(&self.branch),
196        ]
197    }
198}
199
200/// Placeholder directories for settings that were not loaded from any — the
201/// ones [`LoadedSettings::new`] is commonly given in tests.
202impl Default for PathSettings {
203    fn default() -> Self {
204        let state = PathBuf::from("~").join(DEFAULT_STATE_DIR);
205        Self {
206            user_data_dir: StateRoot::new(state.clone()).scene_dir("agent"),
207            global_data_dir: state,
208            local_data_dir: PathBuf::from("."),
209            workspace: Workspace::Project(PathBuf::new()),
210            scope: default_scope(),
211            project_untrusted: false,
212            layout: Layout::default(),
213        }
214    }
215}
216
217fn default_scope() -> String {
218    "code".to_string()
219}
220
221/// What a session works in (docs/ARCHITECTURE.md §3.2).
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
223#[serde(rename_all = "snake_case")]
224pub enum Workspace {
225    /// A project: the tools work in it, and its project directory is the
226    /// project tier.
227    Project(PathBuf),
228    /// No project (`project_root: null`): no project tier, no git or
229    /// `AGENTS.md` context, and the tools work in this directory of the
230    /// session's own under the state root's scratchpad
231    /// ([`crate::paths::session_scratch_dir`]) — never in the state root's
232    /// parent, which for `~/.agix` is the user's home.
233    Scratch(PathBuf),
234}
235
236impl Workspace {
237    /// The project whose project directory is `local_data_dir`.
238    pub fn project_of(local_data_dir: &Path) -> Self {
239        Self::Project(
240            local_data_dir
241                .parent()
242                .map(Path::to_path_buf)
243                .unwrap_or_else(|| local_data_dir.to_path_buf()),
244        )
245    }
246
247    /// The project, `None` without one.
248    pub fn project_root(&self) -> Option<&Path> {
249        match self {
250            Self::Project(root) => Some(root),
251            Self::Scratch(_) => None,
252        }
253    }
254}
255
256impl PathSettings {
257    pub fn new(
258        user_data_dir: PathBuf,
259        global_data_dir: PathBuf,
260        local_data_dir: PathBuf,
261        workspace: Workspace,
262        scope: String,
263        layout: Layout,
264    ) -> Self {
265        Self {
266            user_data_dir,
267            global_data_dir,
268            local_data_dir,
269            workspace,
270            scope,
271            project_untrusted: false,
272            layout,
273        }
274    }
275
276    /// The derived paths of these roots.
277    pub fn config_paths(&self) -> ConfigPaths {
278        ConfigPaths::from_settings(self)
279    }
280
281    /// The project, `None` in a session without one.
282    pub fn project_root(&self) -> Option<&Path> {
283        self.workspace.project_root()
284    }
285
286    /// The workspace's directory: the project, or the scratch directory. A
287    /// session given a worktree works there instead
288    /// (`settings::SessionConfig::working_dir`).
289    pub fn workspace_dir(&self) -> &Path {
290        match &self.workspace {
291            Workspace::Project(dir) | Workspace::Scratch(dir) => dir,
292        }
293    }
294
295    /// `git`, resolved, when its git directory is the project's own
296    /// `<project>/.git` — the only git directory the sandbox guards for a
297    /// worktree — its entry lies directly under that directory's
298    /// `worktrees/`, and its branch stays below `refs/heads/`.
299    pub fn project_worktree_git(&self, git: &WorktreeGit) -> Option<WorktreeGit> {
300        let own = self
301            .project_root()?
302            .join(REPOSITORY_CONFIG_DIR)
303            .canonicalize()
304            .ok()?;
305        if git.dir.canonicalize().ok()? != own || !own.is_dir() {
306            return None;
307        }
308        let admin = git.admin.canonicalize().ok()?;
309        let branch_is_plain = git.branch.split('/').all(|part| {
310            !part.is_empty() && part != "." && part != ".." && !part.ends_with(".lock")
311        });
312        (admin.parent() == Some(own.join(GIT_WORKTREES_DIR).as_path()) && branch_is_plain).then(
313            || WorktreeGit {
314                dir: own,
315                admin,
316                branch: git.branch.clone(),
317            },
318        )
319    }
320
321    /// The project tier's `settings.local.json` — the file the interactive
322    /// permission prompt's "always allow, this project" writes to.
323    ///
324    /// Inside `local_data_dir` (the project directory), not beside it: the
325    /// Bash sandbox's deny-file-write rules (`tools::bash::sandbox`) protect
326    /// exactly this path to stop a sandboxed command from granting itself
327    /// permissions, and a copy written anywhere else would sit outside that
328    /// protection while still being loaded by `LoadedSettings::load`.
329    ///
330    /// `None` without a project: "this project" means nothing there, and its
331    /// `local_data_dir` is the state root, whose `settings.local.json` is the
332    /// global tier — a rule written there would allow the call everywhere.
333    pub fn local_settings_file(&self) -> Option<PathBuf> {
334        self.project_root()
335            .map(|_| self.local_data_dir.join(SETTINGS_LOCAL_FILE))
336    }
337
338    /// The project directory's `state/` ([`Layout::project_state_dir`]),
339    /// `None` without a project.
340    pub fn project_state_dir(&self) -> Option<PathBuf> {
341        self.project_root()
342            .map(|_| self.local_data_dir.join(entry::STATE))
343    }
344}
345
346/// What a data directory's `.gitignore` keeps out of the repository the
347/// directory sits in, one line each: `state/` and the
348/// [`LOCAL_CONFIG_FILES`].
349pub fn local_data_gitignore() -> Vec<String> {
350    std::iter::once(format!("{}/", entry::STATE))
351        .chain(LOCAL_CONFIG_FILES.iter().map(|file| file.to_string()))
352        .collect()
353}
354
355/// Make sure `dir`'s `.gitignore` has every [`local_data_gitignore`] entry,
356/// appending the ones it lacks and touching nothing else in it: in a cloned
357/// repository the file is the repository author's, and the keys and
358/// recordings the engine writes here must stay out of it all the same. A
359/// `.gitignore` that is a symlink is left alone, as is what it points at.
360pub fn ensure_local_data_gitignore(dir: &std::path::Path) {
361    use std::io::{Read, Write};
362    let mut options = std::fs::OpenOptions::new();
363    options.read(true).append(true).create(true);
364    #[cfg(unix)]
365    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW);
366    let Ok(mut file) = options.open(dir.join(".gitignore")) else {
367        return;
368    };
369    let mut bytes = Vec::new();
370    if file.read_to_end(&mut bytes).is_err() {
371        return;
372    }
373    let existing = String::from_utf8_lossy(&bytes);
374    let lacking: Vec<String> = local_data_gitignore()
375        .into_iter()
376        .filter(|entry| !existing.lines().any(|line| line.trim() == entry))
377        .collect();
378    if lacking.is_empty() {
379        return;
380    }
381    let mut added = String::new();
382    if !existing.is_empty() && !existing.ends_with('\n') {
383        added.push('\n');
384    }
385    for entry in lacking {
386        added.push_str(&entry);
387        added.push('\n');
388    }
389    let _ = file.write_all(added.as_bytes());
390}
391
392/// [`ensure_local_data_gitignore`] for a project's directory, which a cloned
393/// repository supplies: only where `dir` is a directory of its own, not a
394/// symlink, and lies inside `project`.
395pub fn ensure_project_data_gitignore(dir: &std::path::Path, project: &std::path::Path) {
396    let own_dir = dir.symlink_metadata().is_ok_and(|m| m.is_dir());
397    let inside = match (dir.canonicalize(), project.canonicalize()) {
398        (Ok(dir), Ok(project)) => dir.starts_with(project),
399        _ => false,
400    };
401    if own_dir && inside {
402        ensure_local_data_gitignore(dir);
403    }
404}
405
406/// Unified management of AGENT persistent directory paths: the three tiers'
407/// roots and every path derived from them. A caller asks for the path here
408/// rather than joining a name onto a root.
409///
410/// Usually `global_data_dir = $HOME/.agix/`,
411/// `user_data_dir = <global>/scenes/<scope>/`,
412/// `local_data_dir = <project>/<layout's project dir>/`.
413#[derive(Debug, Clone)]
414pub struct ConfigPaths {
415    /// User-level, scene-specific override root.
416    pub user_data_dir: PathBuf,
417    /// User-level, cross-scene global root (flat, shared by every scene).
418    pub global_data_dir: PathBuf,
419    /// The project tier's root; the state root in a session without a project.
420    pub local_data_dir: PathBuf,
421    /// The project, `None` for a session without one
422    /// ([`crate::paths::PathSettings::project_root`]).
423    pub project_root: Option<PathBuf>,
424    /// See [`PathSettings::project_untrusted`].
425    pub project_untrusted: bool,
426    pub layout: Layout,
427}
428
429impl ConfigPaths {
430    /// Build from explicit roots.
431    ///
432    /// There is no constructor that consults the environment, and that is the
433    /// point: a process serves one instance, and which directory that
434    /// instance owns is the caller's to decide. Reading `$HOME` here would
435    /// make every downstream module silently agree on the invoking user's
436    /// home, which is wrong for a test, wrong for a service account, and
437    /// wrong for any deployment that keeps its state somewhere else.
438    ///
439    /// `scope` identifies the product instance whose scene-specific override
440    /// tree lives under `global_data_dir/scenes/<scope>/`.
441    pub fn new(
442        global_data_dir: PathBuf,
443        local_data_dir: PathBuf,
444        scope: &str,
445        layout: Layout,
446    ) -> Self {
447        let project_root = Workspace::project_of(&local_data_dir)
448            .project_root()
449            .map(PathBuf::from);
450        Self {
451            user_data_dir: StateRoot::new(global_data_dir.clone()).scene_dir(scope),
452            global_data_dir,
453            local_data_dir,
454            project_root,
455            project_untrusted: false,
456            layout,
457        }
458    }
459
460    /// The paths of a session of `scene_dir` in `project`, or in none: the
461    /// project tier is `layout`'s directory in the project, and without a
462    /// project it is the state root, as `LoadedSettings` makes it.
463    pub fn of(
464        global_data_dir: PathBuf,
465        scene_dir: PathBuf,
466        project: Option<&Path>,
467        layout: Layout,
468    ) -> Self {
469        Self {
470            user_data_dir: scene_dir,
471            local_data_dir: project
472                .map(|root| layout.project_dir(root))
473                .unwrap_or_else(|| global_data_dir.clone()),
474            global_data_dir,
475            project_root: project.map(Path::to_path_buf),
476            project_untrusted: false,
477            layout,
478        }
479    }
480
481    /// The same roots [`crate::settings::Settings`] already
482    /// carries — for the call sites that hold `Settings` and want these
483    /// accessors without re-deriving anything.
484    pub fn from_settings(paths: &crate::paths::PathSettings) -> Self {
485        Self {
486            user_data_dir: paths.user_data_dir.clone(),
487            global_data_dir: paths.global_data_dir.clone(),
488            local_data_dir: paths.local_data_dir.clone(),
489            project_root: paths.project_root().map(PathBuf::from),
490            project_untrusted: paths.project_untrusted,
491            layout: paths.layout.clone(),
492        }
493    }
494
495    pub fn state_root(&self) -> StateRoot {
496        StateRoot::new(self.global_data_dir.clone())
497    }
498
499    pub fn scene_dir(&self) -> &Path {
500        &self.user_data_dir
501    }
502
503    /// The project's own directory, `None` without a project.
504    pub fn project_dir(&self) -> Option<&Path> {
505        self.project_root
506            .as_ref()
507            .map(|_| self.local_data_dir.as_path())
508    }
509
510    /// The directory of a settings tier: the state root, the scene
511    /// directory, the project directory. `None` for the project tier
512    /// without a project, the `cli` and session ones, and the managed one, which is a file.
513    pub fn tier_dir(&self, tier: Tier) -> Option<PathBuf> {
514        match tier {
515            Tier::Global => Some(self.global_data_dir.clone()),
516            Tier::Scene => Some(self.user_data_dir.clone()),
517            Tier::Project => self.project_dir().map(Path::to_path_buf),
518            Tier::Cli | Tier::Session | Tier::Managed => None,
519        }
520    }
521
522    /// `name`, one of [`entry`], in a tier's directory.
523    pub fn tier_entry(&self, tier: Tier, name: &str) -> Option<PathBuf> {
524        self.tier_dir(tier).map(|dir| dir.join(name))
525    }
526
527    pub fn settings_file(&self, tier: Tier) -> Option<PathBuf> {
528        self.tier_entry(tier, entry::SETTINGS)
529    }
530
531    pub fn settings_local_file(&self, tier: Tier) -> Option<PathBuf> {
532        self.tier_entry(tier, entry::SETTINGS_LOCAL)
533    }
534
535    pub fn global_skills_dir(&self) -> PathBuf {
536        self.global_data_dir.join(entry::SKILLS)
537    }
538
539    pub fn user_skills_dir(&self) -> PathBuf {
540        self.user_data_dir.join(entry::SKILLS)
541    }
542
543    /// `<project>/.agents/skills`: beside the project directory, not in it.
544    pub fn project_skills_dir(&self) -> Option<PathBuf> {
545        self.project_root
546            .as_ref()
547            .map(|root| root.join(PROJECT_SKILLS_DIR))
548    }
549
550    pub fn global_agents_dir(&self) -> PathBuf {
551        self.global_data_dir.join(entry::AGENTS)
552    }
553
554    pub fn user_agents_dir(&self) -> PathBuf {
555        self.user_data_dir.join(entry::AGENTS)
556    }
557
558    pub fn project_agents_dir(&self) -> Option<PathBuf> {
559        self.tier_entry(Tier::Project, entry::AGENTS)
560    }
561
562    pub fn global_hooks_dir(&self) -> PathBuf {
563        self.global_data_dir.join(entry::HOOKS)
564    }
565
566    pub fn user_hooks_dir(&self) -> PathBuf {
567        self.user_data_dir.join(entry::HOOKS)
568    }
569
570    pub fn project_hooks_dir(&self) -> Option<PathBuf> {
571        self.tier_entry(Tier::Project, entry::HOOKS)
572    }
573
574    pub fn global_rules_dir(&self) -> PathBuf {
575        self.global_data_dir.join(entry::RULES)
576    }
577
578    pub fn user_rules_dir(&self) -> PathBuf {
579        self.user_data_dir.join(entry::RULES)
580    }
581
582    pub fn project_rules_dir(&self) -> Option<PathBuf> {
583        self.tier_entry(Tier::Project, entry::RULES)
584    }
585
586    pub fn user_output_styles_dir(&self) -> PathBuf {
587        self.user_data_dir.join(entry::OUTPUT_STYLES)
588    }
589
590    pub fn project_output_styles_dir(&self) -> Option<PathBuf> {
591        self.tier_entry(Tier::Project, entry::OUTPUT_STYLES)
592    }
593
594    pub fn global_plugins_dir(&self) -> PathBuf {
595        self.global_data_dir.join(entry::PLUGINS)
596    }
597
598    pub fn user_plugins_dir(&self) -> PathBuf {
599        self.user_data_dir.join(entry::PLUGINS)
600    }
601
602    /// The state root's memory, the user's across every project.
603    pub fn global_memory_dir(&self) -> PathBuf {
604        self.global_data_dir.join(entry::MEMORY)
605    }
606
607    pub fn global_recordings_dir(&self) -> PathBuf {
608        self.global_data_dir.join(entry::RECORDINGS)
609    }
610
611    /// The project directory's `state/`, `None` without a project.
612    pub fn project_state_dir(&self) -> Option<PathBuf> {
613        self.project_dir().map(|dir| dir.join(entry::STATE))
614    }
615
616    /// Where this machine's data of the session's place is: the project
617    /// directory's `state/`, and without a project the state root, which
618    /// has no `state/` of its own.
619    pub fn local_state_dir(&self) -> PathBuf {
620        self.project_state_dir()
621            .unwrap_or_else(|| self.local_data_dir.clone())
622    }
623
624    pub fn local_memory_dir(&self) -> PathBuf {
625        self.local_state_dir().join(entry::MEMORY)
626    }
627
628    pub fn scratchpad_dir(&self) -> PathBuf {
629        self.local_state_dir().join(entry::SCRATCHPAD)
630    }
631
632    pub fn telemetry_dir(&self) -> PathBuf {
633        self.local_state_dir().join(entry::TELEMETRY)
634    }
635
636    /// [`tool_results_dir`] under [`Self::local_state_dir`].
637    pub fn tool_results_dir(&self, session_id: &str) -> PathBuf {
638        tool_results_dir(&self.local_state_dir(), session_id)
639    }
640
641    /// The scene's `scheduled_tasks.json`.
642    pub fn scheduled_tasks_file(&self) -> PathBuf {
643        self.user_data_dir.join(entry::SCHEDULED_TASKS)
644    }
645
646    pub fn mcp_oauth_dir(&self) -> PathBuf {
647        self.user_data_dir.join(entry::MCP).join(entry::OAUTH)
648    }
649
650    /// Where the import records that its question was answered, `None`
651    /// without a project.
652    pub fn imported_marker(&self) -> Option<PathBuf> {
653        self.project_state_dir()
654            .map(|dir| dir.join(entry::IMPORTED_MARKER))
655    }
656
657    /// The teams of a session working in `cwd` ([`Layout::teams_dir`]).
658    pub fn teams_dir(&self, cwd: &Path) -> PathBuf {
659        self.layout.teams_dir(cwd)
660    }
661
662    /// The engine's worktrees of the project ([`Layout::worktrees_dir`]).
663    pub fn worktrees_dir(&self) -> Option<PathBuf> {
664        self.project_root
665            .as_ref()
666            .map(|root| self.layout.worktrees_dir(root))
667    }
668}
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673
674    fn paths() -> ConfigPaths {
675        ConfigPaths::new(
676            PathBuf::from("/state/.agix"),
677            PathBuf::from("/tmp/test-project/.agix"),
678            "code",
679            Layout::default(),
680        )
681    }
682
683    #[test]
684    fn roots_are_exactly_what_the_caller_passed() {
685        let p = paths();
686        assert_eq!(p.global_data_dir, PathBuf::from("/state/.agix"));
687        assert_eq!(p.local_data_dir, PathBuf::from("/tmp/test-project/.agix"));
688    }
689
690    #[test]
691    fn scene_dir_nests_under_global_dir() {
692        let p = paths();
693        assert_eq!(
694            p.user_data_dir,
695            p.global_data_dir.join("scenes").join("code")
696        );
697    }
698
699    #[test]
700    fn different_scopes_get_different_user_roots_but_same_global_root() {
701        let global = PathBuf::from("/state/.agix");
702        let local = PathBuf::from("/tmp/p/.agix");
703        let code = ConfigPaths::new(global.clone(), local.clone(), "code", Layout::default());
704        let ops = ConfigPaths::new(global, local, "ops", Layout::default());
705        assert_ne!(code.user_data_dir, ops.user_data_dir);
706        assert_eq!(code.global_data_dir, ops.global_data_dir);
707        // Local root is scope-independent (project-level is flat).
708        assert_eq!(code.local_data_dir, ops.local_data_dir);
709    }
710
711    /// The roots must survive the trip through `Settings` unchanged —
712    /// `PathSettings` is how they actually reach most call sites.
713    #[test]
714    fn settings_roots_round_trip() {
715        let p = paths();
716        let carried = PathSettings {
717            user_data_dir: p.user_data_dir.clone(),
718            global_data_dir: p.global_data_dir.clone(),
719            workspace: Workspace::project_of(&p.local_data_dir),
720            local_data_dir: p.local_data_dir.clone(),
721            scope: "code".into(),
722            project_untrusted: false,
723            layout: Layout::new(".codix").unwrap(),
724        };
725        let back = ConfigPaths::from_settings(&carried);
726        assert_eq!(back.layout, carried.layout);
727        assert_eq!(back.user_data_dir, p.user_data_dir);
728        assert_eq!(back.global_data_dir, p.global_data_dir);
729        assert_eq!(back.local_data_dir, p.local_data_dir);
730    }
731
732    #[test]
733    fn convenience_methods_derive_from_roots() {
734        let p = paths();
735        assert_eq!(p.user_skills_dir(), p.user_data_dir.join("skills"));
736        assert_eq!(p.global_skills_dir(), p.global_data_dir.join("skills"));
737        assert_eq!(p.global_memory_dir(), p.global_data_dir.join("memory"));
738        assert_eq!(
739            p.global_recordings_dir(),
740            p.global_data_dir.join("recordings")
741        );
742        assert_eq!(p.local_memory_dir(), p.local_data_dir.join("state/memory"));
743    }
744
745    #[test]
746    fn the_project_tiers_paths_are_in_the_layouts_directory() {
747        for layout in layout::test_layouts() {
748            let name = layout.project_dir_name().to_string();
749            let layout_worktrees = layout.worktrees_dir_name().to_string();
750            let project = Path::new("/repo");
751            let p = ConfigPaths::of(
752                PathBuf::from("/state"),
753                PathBuf::from("/state/scenes/code"),
754                Some(project),
755                layout,
756            );
757            let own = project.join(&name);
758            assert_eq!(p.project_dir(), Some(own.as_path()));
759            assert_eq!(
760                p.settings_file(Tier::Project),
761                Some(own.join("settings.json"))
762            );
763            assert_eq!(p.project_agents_dir(), Some(own.join("agents")));
764            assert_eq!(p.project_hooks_dir(), Some(own.join("hooks")));
765            assert_eq!(p.project_rules_dir(), Some(own.join("rules")));
766            assert_eq!(
767                p.project_output_styles_dir(),
768                Some(own.join("output-styles"))
769            );
770            assert_eq!(p.project_state_dir(), Some(own.join("state")));
771            assert_eq!(p.imported_marker(), Some(own.join("state/.imported.json")));
772            assert_eq!(
773                p.worktrees_dir(),
774                Some(project.join(layout_worktrees.as_str()))
775            );
776            assert_eq!(p.telemetry_dir(), own.join("state/telemetry"));
777            assert_eq!(p.scratchpad_dir(), own.join("state/scratchpad"));
778            assert_eq!(p.local_memory_dir(), own.join("state/memory"));
779            assert_eq!(p.tool_results_dir("s"), own.join("state/tool-results/s"));
780            assert_eq!(p.project_skills_dir(), Some(project.join(".agents/skills")));
781            assert_eq!(
782                p.settings_local_file(Tier::Scene),
783                Some(PathBuf::from("/state/scenes/code/settings.local.json"))
784            );
785            assert_eq!(p.tier_dir(Tier::Managed), None);
786        }
787        let none = ConfigPaths::of(
788            PathBuf::from("/state"),
789            PathBuf::from("/state/scenes/code"),
790            None,
791            Layout::default(),
792        );
793        assert_eq!(none.project_dir(), None);
794        assert_eq!(none.settings_file(Tier::Project), None);
795        assert_eq!(none.local_data_dir, PathBuf::from("/state"));
796        assert_eq!(none.project_state_dir(), None);
797        assert_eq!(none.imported_marker(), None);
798        assert_eq!(none.local_state_dir(), PathBuf::from("/state"));
799        assert_eq!(none.scratchpad_dir(), PathBuf::from("/state/scratchpad"));
800        assert_eq!(none.local_memory_dir(), PathBuf::from("/state/memory"));
801        assert_eq!(
802            none.tool_results_dir("s"),
803            PathBuf::from("/state/tool-results/s")
804        );
805    }
806
807    #[test]
808    fn a_projects_state_dir_is_only_there_with_a_project() {
809        let mut settings = PathSettings {
810            local_data_dir: PathBuf::from("/repo/.agix"),
811            workspace: Workspace::Project(PathBuf::from("/repo")),
812            ..PathSettings::default()
813        };
814        assert_eq!(
815            settings.project_state_dir(),
816            Some(PathBuf::from("/repo/.agix/state"))
817        );
818        settings.local_data_dir = PathBuf::from("/state");
819        settings.workspace = Workspace::Scratch(PathBuf::from("/state/scratchpad/sessions/s"));
820        assert_eq!(settings.project_state_dir(), None);
821    }
822}
823
824#[cfg(test)]
825mod local_data_gitignore_tests {
826    use super::*;
827
828    #[test]
829    fn a_gitignore_the_repository_ships_gets_the_engines_entries_appended() {
830        let dir = tempfile::tempdir().unwrap();
831        let file = dir.path().join(".gitignore");
832        std::fs::write(&file, "").unwrap();
833        ensure_local_data_gitignore(dir.path());
834        let lines: Vec<String> = std::fs::read_to_string(&file)
835            .unwrap()
836            .lines()
837            .map(String::from)
838            .collect();
839        for entry in local_data_gitignore() {
840            assert!(lines.contains(&entry), "{entry} missing: {lines:?}");
841        }
842
843        std::fs::write(&file, "build/\nsettings.local.json").unwrap();
844        ensure_local_data_gitignore(dir.path());
845        let text = std::fs::read_to_string(&file).unwrap();
846        assert!(
847            text.starts_with("build/\nsettings.local.json\n"),
848            "{text:?}"
849        );
850        assert_eq!(text.matches("settings.local.json").count(), 1, "{text:?}");
851        assert!(text.contains("mcp.local.json\n") && text.contains("state/\n"));
852        assert_eq!(
853            local_data_gitignore(),
854            ["state/", "settings.local.json", "mcp.local.json"]
855        );
856
857        let before = text.clone();
858        ensure_local_data_gitignore(dir.path());
859        assert_eq!(std::fs::read_to_string(&file).unwrap(), before);
860    }
861
862    #[cfg(unix)]
863    #[test]
864    fn a_gitignore_that_is_a_symlink_is_not_written_through() {
865        let dir = tempfile::tempdir().unwrap();
866        let victim = dir.path().join("victim");
867        std::fs::write(&victim, "keep\n").unwrap();
868        let data = dir.path().join(".agix");
869        std::fs::create_dir(&data).unwrap();
870        std::os::unix::fs::symlink(&victim, data.join(".gitignore")).unwrap();
871        ensure_local_data_gitignore(&data);
872        ensure_project_data_gitignore(&data, dir.path());
873        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep\n");
874    }
875
876    #[cfg(unix)]
877    #[test]
878    fn a_project_directory_elsewhere_gets_no_gitignore() {
879        let project = tempfile::tempdir().unwrap();
880        let elsewhere = tempfile::tempdir().unwrap();
881        let linked = project.path().join(".agix");
882        std::os::unix::fs::symlink(elsewhere.path(), &linked).unwrap();
883        ensure_project_data_gitignore(&linked, project.path());
884        assert!(!elsewhere.path().join(".gitignore").exists());
885
886        let outside = project
887            .path()
888            .join("..")
889            .join(elsewhere.path().file_name().unwrap());
890        ensure_project_data_gitignore(&outside, project.path());
891        assert!(!elsewhere.path().join(".gitignore").exists());
892
893        let real = project.path().join(".codix");
894        std::fs::create_dir(&real).unwrap();
895        ensure_project_data_gitignore(&real, project.path());
896        let text = std::fs::read_to_string(real.join(".gitignore")).unwrap();
897        for entry in local_data_gitignore() {
898            assert!(text.lines().any(|l| l == entry), "{entry}: {text:?}");
899        }
900    }
901}