Skip to main content

base/paths/
layout.rs

1//! The names of the engine's directories and of what is in them, and the
2//! values that vary between instances: what the engine is called in scripts
3//! and file names, what a project's directory is called, what the product is
4//! called, and what the repository directory the engine's worktrees go in is
5//! called ([`Layout`]: `agix`, `.agix`, `Agix` and `.wkts` unless the
6//! embedder or the user's settings name others).
7//!
8//! Every other module takes these names from here — the derived paths from
9//! [`super::ConfigPaths`], [`Layout`] and [`StateRoot`], the security
10//! decisions from [`super::SensitivePaths`], the engine's name wherever a
11//! script finds it, the product's name wherever a person or the model reads
12//! it — so that renaming any of them is one value
13//! carried through, not a search for literals. A `Layout` is carried by value
14//! from the pool's paths into every session's settings; there is no
15//! process-wide one, since two pools in one process may name these
16//! differently.
17
18use std::path::{Component, Path, PathBuf};
19use std::sync::Arc;
20
21/// The engine's name when the embedder names none.
22pub const DEFAULT_ENGINE: &str = "agix";
23
24/// The project directory's name under [`DEFAULT_ENGINE`]: `.<engine>`.
25pub const DEFAULT_PROJECT_DIR: &str = ".agix";
26
27/// `$HOME/<this>` is agixd's state root when nothing names one, and the
28/// state directory's name under [`DEFAULT_ENGINE`].
29pub const DEFAULT_STATE_DIR: &str = ".agix";
30
31/// Configuration roots of other agents, or of this engine under its default
32/// name, guarded beside the instance's own: a model that rewrote one would be
33/// granting a later session of that agent, or the import, what it was not
34/// granted.
35pub const FOREIGN_CONFIG_ROOTS: &[&str] = &[DEFAULT_PROJECT_DIR, CLAUDE_DIR];
36
37/// Claude Code's directory, which the engine imports from.
38pub const CLAUDE_DIR: &str = ".claude";
39
40/// Claude Code's login, in the user's home.
41pub const CLAUDE_CREDENTIALS: &str = ".claude/.credentials.json";
42
43/// The cross-tool directory beside the project directory; its `skills` is
44/// [`PROJECT_SKILLS_DIR`]. Its name belongs to that convention, not to the
45/// instance, and does not follow [`Layout`].
46pub const AGENTS_DIR: &str = ".agents";
47
48/// A project's skills, where Codex and other agent tools look for them too.
49pub const PROJECT_SKILLS_DIR: &str = ".agents/skills";
50
51/// The product's name when the embedder names none.
52pub const DEFAULT_PRODUCT_NAME: &str = "Agix";
53
54/// Where the product of that name is published.
55pub const DEFAULT_PRODUCT_URL: &str = "https://github.com/harnixai/agix";
56
57/// The directory in a git directory holding the linked worktrees' entries.
58pub const GIT_WORKTREES_DIR: &str = "worktrees";
59
60/// The directory at a repository's root that the engine's worktrees go in
61/// when the settings name none.
62pub const DEFAULT_WORKTREES_DIR: &str = ".wkts";
63
64/// Entries of an engine directory: the state root, a scene directory, a
65/// project directory.
66pub mod entry {
67    pub const SETTINGS: &str = "settings.json";
68    pub const SETTINGS_LOCAL: &str = "settings.local.json";
69    pub const MCP_LOCAL: &str = "mcp.local.json";
70    pub const SCENE_FILE: &str = "scene.json";
71    pub const SCENE_PROMPT: &str = "prompt.md";
72    pub const SCHEDULED_TASKS: &str = "scheduled_tasks.json";
73    pub const IMPORTED_MARKER: &str = ".imported.json";
74
75    pub const SKILLS: &str = "skills";
76    pub const AGENTS: &str = "agents";
77    pub const HOOKS: &str = "hooks";
78    pub const COMMANDS: &str = "commands";
79    pub const RULES: &str = "rules";
80    pub const OUTPUT_STYLES: &str = "output-styles";
81    pub const PLUGINS: &str = "plugins";
82    pub const CACHE: &str = "cache";
83    pub const SCENES: &str = "scenes";
84    pub const MCP: &str = "mcp";
85    pub const OAUTH: &str = "oauth";
86    pub const POLICY: &str = "policy";
87    pub const SCRIPTS: &str = "scripts";
88
89    pub const MEMORY: &str = "memory";
90    pub const SCRATCHPAD: &str = "scratchpad";
91    pub const TMP: &str = "tmp";
92    pub const TEAMS: &str = "teams";
93    pub const TELEMETRY: &str = "telemetry";
94    pub const TOOL_RESULTS: &str = "tool-results";
95    pub const STATE: &str = "state";
96    pub const HISTORY: &str = "history";
97    pub const SESSIONS: &str = "sessions";
98    pub const PROJECTS: &str = "projects";
99    pub const RECORDINGS: &str = "recordings";
100    pub const QUOTA: &str = "quota";
101
102    pub const DAEMON: &str = "daemon";
103    pub const INSTANCES: &str = "instances.d";
104    pub const AUTH: &str = "auth";
105    pub const GROUPS: &str = "groups";
106    pub const CRASHES: &str = "crashes";
107
108    pub const MANAGED_SETTINGS: &str = "managed-settings.json";
109    pub const MCP_POLICY: &str = "mcp-policy.json";
110}
111
112/// The shared, committed settings file present in every tier.
113pub const SETTINGS_FILE: &str = entry::SETTINGS;
114
115/// The gitignored per-machine overlay sitting beside `SETTINGS_FILE` in the
116/// same tier, overriding it.
117pub const SETTINGS_LOCAL_FILE: &str = entry::SETTINGS_LOCAL;
118
119/// The subdirectories of the state root, and of a project directory's
120/// `state/`, that are the agent's own working space rather than
121/// configuration: the only parts of them the agent's tools and its sandboxed
122/// commands may write.
123pub const STATE_ROOT_WORKING_DIRS: &[&str] = &[STATE_ROOT_SCRATCHPAD, entry::MEMORY];
124
125/// The state root's scratchpad, one of [`STATE_ROOT_WORKING_DIRS`].
126pub const STATE_ROOT_SCRATCHPAD: &str = entry::SCRATCHPAD;
127
128/// Under the state root, one temporary directory per session,
129/// `<state root>/tmp/<session>`: the session's sandboxed commands may write
130/// their own and no other.
131pub const STATE_ROOT_SESSION_TMP: &str = entry::TMP;
132
133/// Files in a configuration root that configure the engine. The write tools
134/// refuse them anywhere under such a directory, a sandboxed command directly
135/// in it.
136pub const ENGINE_CONFIG_FILES: &[&str] =
137    &[entry::SETTINGS, entry::SETTINGS_LOCAL, entry::MCP_LOCAL];
138
139/// Directories directly in a configuration root that configure the engine or
140/// that it acts on unsandboxed, guarded with everything under them. With
141/// `commands`, which the engine does not read but Claude Code reads its slash
142/// commands from.
143pub const ENGINE_CONFIG_DIRS: &[&str] = &[
144    entry::MCP,
145    entry::HOOKS,
146    entry::COMMANDS,
147    entry::AGENTS,
148    entry::SKILLS,
149    entry::PLUGINS,
150    entry::RULES,
151    entry::SCENES,
152    entry::POLICY,
153    entry::SCRIPTS,
154    entry::OUTPUT_STYLES,
155    entry::TOOL_RESULTS,
156];
157
158/// Directories in a project, outside the configuration roots, that the
159/// engine loads configuration from: the project's skills, whose
160/// `allowed-tools` grant permissions. Guarded like a configuration
161/// directory in those roots: a write tool asks, a sandboxed command cannot
162/// write, and the directories above one cannot be moved aside.
163pub const PROJECT_ENGINE_CONFIG_DIRS: &[&str] = &[PROJECT_SKILLS_DIR];
164
165/// The files in the state root and in each `scenes/<scene>/` under it that a
166/// sandboxed command must not rewrite: the settings, and — for a
167/// declarative scene — the files that define it.
168pub const STATE_ROOT_SCENE_FILES: &[&str] =
169    &[entry::SETTINGS, entry::SCENE_FILE, entry::SCENE_PROMPT];
170
171/// The files of a project directory outside its `state/` that its
172/// `.gitignore` keeps out of the repository along with `state/`: one user's
173/// own configuration and keys, which stay beside the shared settings where
174/// people look for them. Only what a project's collaborators share is
175/// committed.
176pub const LOCAL_CONFIG_FILES: &[&str] = &[entry::SETTINGS_LOCAL, entry::MCP_LOCAL];
177
178/// What the engine keeps in a project directory's `state/` and an older
179/// engine kept directly in the project directory: opening the project moves
180/// each found there into `state/`.
181pub const PROJECT_STATE_ENTRIES: &[&str] = &[
182    entry::MEMORY,
183    entry::SCRATCHPAD,
184    entry::TEAMS,
185    entry::TELEMETRY,
186    entry::TOOL_RESULTS,
187    entry::IMPORTED_MARKER,
188];
189
190/// The directories in a project's `state/` the engine acts on unsandboxed —
191/// it exports, forks and resumes from them — guarded with everything under
192/// them even inside a writable root the sandbox policy names there.
193pub const PROJECT_STATE_ENGINE_DIRS: &[&str] = &[entry::TOOL_RESULTS, entry::HISTORY];
194
195/// The names the engine has, or keeps for itself, in a project's `state/`.
196/// No product's id may be one: `state/<product id>/` is the embedder's
197/// ([`Layout::host_state_dir`]).
198pub const STATE_RESERVED_NAMES: &[&str] = &[
199    entry::MEMORY,
200    entry::SCRATCHPAD,
201    entry::TEAMS,
202    entry::TELEMETRY,
203    entry::TOOL_RESULTS,
204    entry::HISTORY,
205    "imported",
206    entry::SESSIONS,
207    entry::CACHE,
208    entry::TMP,
209];
210
211/// Project directories other tools own, which an instance's cannot be: git's,
212/// the cross-tool skills directory, the other agents' configuration roots,
213/// and the editors' and forges' settings, whose files would collide with the
214/// engine's or become unwritable under its protection.
215pub const OTHER_TOOLS_DIRS: &[&str] = &[
216    super::REPOSITORY_CONFIG_DIR,
217    AGENTS_DIR,
218    CLAUDE_DIR,
219    ".codex",
220    ".cursor",
221    ".github",
222    ".vscode",
223    ".idea",
224];
225
226/// Why a name cannot be a project directory's.
227#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
228#[error("`{name}` cannot name the project directory: {reason}")]
229pub struct LayoutError {
230    pub name: String,
231    pub reason: &'static str,
232}
233
234/// Why a name cannot be the worktrees directory's.
235#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
236#[error("`{name}` cannot name the worktrees directory: {reason}")]
237pub struct WorktreesDirError {
238    pub name: String,
239    pub reason: &'static str,
240}
241
242/// Why a name cannot be the engine's.
243#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
244#[error("`{name}` cannot name the engine: {reason}")]
245pub struct EngineNameError {
246    pub name: String,
247    pub reason: &'static str,
248}
249
250/// Why a name cannot be the product's.
251#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
252#[error("`{name}` cannot name the product: {reason}")]
253pub struct ProductNameError {
254    pub name: String,
255    pub reason: &'static str,
256}
257
258/// The names an instance gives its directories and itself. One per pool,
259/// carried in the pool's paths and every session's settings.
260#[derive(Debug, Clone, PartialEq, Eq, Hash)]
261pub struct Layout {
262    engine: Arc<str>,
263    project_dir: Arc<str>,
264    product: Arc<str>,
265    worktrees: Arc<str>,
266}
267
268impl Default for Layout {
269    fn default() -> Self {
270        Self {
271            engine: Arc::from(DEFAULT_ENGINE),
272            project_dir: Arc::from(DEFAULT_PROJECT_DIR),
273            product: Arc::from(DEFAULT_PRODUCT_NAME),
274            worktrees: Arc::from(DEFAULT_WORKTREES_DIR),
275        }
276    }
277}
278
279/// Why `name` is not one path component of at most 64 characters, each
280/// `allowed` (else `charset` says why), that starts with `.`.
281fn not_hidden_component(
282    name: &str,
283    allowed: fn(char) -> bool,
284    charset: &'static str,
285) -> Option<&'static str> {
286    if name.is_empty() {
287        Some("it is empty")
288    } else if name.len() > 64 {
289        Some("it is longer than 64 characters")
290    } else if !name.chars().all(allowed) {
291        Some(charset)
292    } else if name == "." || name == ".." {
293        Some("it is not a directory of its own")
294    } else if !name.starts_with('.') {
295        Some("it must start with `.`, as a directory a project does not use for its own files")
296    } else {
297        None
298    }
299}
300
301/// One configuration root as [`Layout::config_roots`] lists it.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct ConfigRoot<'a> {
304    pub name: &'a str,
305    /// The instance's own project directory, rather than a foreign root.
306    pub own: bool,
307}
308
309impl Layout {
310    /// The default layout with its project directory `project_dir`
311    /// ([`Self::with_project_dir`]).
312    pub fn new(project_dir: &str) -> Result<Self, LayoutError> {
313        Self::default().with_project_dir(project_dir)
314    }
315
316    /// This layout with its project directory `<project>/<name>`: one path
317    /// component of `[a-z0-9._-]`, at most 64 long — the configuration
318    /// checks split shell text on any other character, and a lowercase-only
319    /// name is the same directory on every filesystem. It starts with `.`:
320    /// the engine refuses writes to its configuration subdirectories, which
321    /// a project's own `src` or `docs` must never be subject to, and a
322    /// hidden directory is where tools keep their state. Not `.`, `..`, a
323    /// directory that is another tool's ([`OTHER_TOOLS_DIRS`]), nor where
324    /// the worktrees go.
325    pub fn with_project_dir(self, name: &str) -> Result<Self, LayoutError> {
326        match self.refuse_project_dir(name) {
327            Some(reason) => Err(LayoutError {
328                name: name.to_string(),
329                reason,
330            }),
331            None => Ok(Self {
332                project_dir: Arc::from(name),
333                ..self
334            }),
335        }
336    }
337
338    fn refuse_project_dir(&self, name: &str) -> Option<&'static str> {
339        let lowercase = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || "._-".contains(c);
340        not_hidden_component(
341            name,
342            lowercase,
343            "only lowercase letters, digits, `.`, `_` and `-` are allowed",
344        )
345        .or_else(|| {
346            OTHER_TOOLS_DIRS
347                .contains(&name)
348                .then_some("that directory belongs to another tool")
349        })
350        .or_else(|| {
351            (name == DEFAULT_WORKTREES_DIR || super::fold_case(&self.worktrees) == name)
352                .then_some("that is where the engine's worktrees go")
353        })
354    }
355
356    /// This layout under the engine name `name`, with its project directory
357    /// `.<name>`: name another with [`Self::with_project_dir`] after this.
358    /// `[a-z][a-z0-9]*`, at most 16 long, and a name a script can be given
359    /// as a new global ([`crate::interface::script::check_global_name`]):
360    /// the base library is installed under it. `.<name>` must be a project
361    /// directory [`Self::with_project_dir`] accepts.
362    pub fn with_engine(self, name: &str) -> Result<Self, EngineNameError> {
363        let refuse = |reason| {
364            Err(EngineNameError {
365                name: name.to_string(),
366                reason,
367            })
368        };
369        if name.len() > 16 {
370            return refuse("it is longer than 16 characters");
371        }
372        if let Err(reason) = crate::interface::script::check_global_name(name) {
373            return refuse(reason);
374        }
375        let project_dir = format!(".{name}");
376        if self.refuse_project_dir(&project_dir).is_some() {
377            return refuse("its project directory would be another tool's, or the worktrees'");
378        }
379        Ok(Self {
380            engine: Arc::from(name),
381            project_dir: Arc::from(project_dir),
382            ..self
383        })
384    }
385
386    /// This layout with its worktrees in `<repository>/<name>/`: one path
387    /// component of ASCII letters, digits, `.`, `_` and `-`, at most 64 long,
388    /// starting with `.` — the repository's `.gitignore` ignores it, every
389    /// entry in it counts as a copy of the main checkout, and the sandbox
390    /// keeps commands from adding, renaming or removing those entries, none
391    /// of which a project's own `src` must be subject to. Not `.`, `..`, a
392    /// configuration root ([`Self::config_roots`]), a directory another tool
393    /// owns ([`OTHER_TOOLS_DIRS`]) nor anything starting with `.git`, which
394    /// git and the forges keep their files under, compared without case: a
395    /// worktree in one would sit inside configuration the sandbox shuts.
396    pub fn with_worktrees_dir(self, name: &str) -> Result<Self, WorktreesDirError> {
397        let ascii = |c: char| c.is_ascii_alphanumeric() || "._-".contains(c);
398        let folded = super::fold_case(name);
399        let reason = not_hidden_component(
400            name,
401            ascii,
402            "only ASCII letters, digits, `.`, `_` and `-` are allowed",
403        )
404        .or_else(|| {
405            self.config_roots()
406                .any(|root| root.name == folded)
407                .then_some("that directory is a configuration root")
408        })
409        .or_else(|| {
410            (OTHER_TOOLS_DIRS.contains(&folded.as_str())
411                || folded.starts_with(super::REPOSITORY_CONFIG_DIR))
412            .then_some("that directory belongs to another tool")
413        });
414        match reason {
415            Some(reason) => Err(WorktreesDirError {
416                name: name.to_string(),
417                reason,
418            }),
419            None => Ok(Self {
420                worktrees: Arc::from(name),
421                ..self
422            }),
423        }
424    }
425
426    /// This layout under the product name `name`: an ASCII letter, then up
427    /// to 31 ASCII letters, digits, `-` or `_`. Its lowercase form is a path
428    /// component (`/etc/<name>`, `state/<name>`), a git ref component
429    /// (`<name>/worktree-`) and an HTTP token (`<name>/<version>`), all of
430    /// which these characters are safe in, and none of
431    /// [`STATE_RESERVED_NAMES`].
432    pub fn with_product_name(self, name: &str) -> Result<Self, ProductNameError> {
433        let refuse = |reason| {
434            Err(ProductNameError {
435                name: name.to_string(),
436                reason,
437            })
438        };
439        let mut chars = name.chars();
440        match chars.next() {
441            None => return refuse("it is empty"),
442            Some(c) if !c.is_ascii_alphabetic() => {
443                return refuse("it must start with an ASCII letter")
444            }
445            Some(_) => {}
446        }
447        if name.len() > 32 {
448            return refuse("it is longer than 32 characters");
449        }
450        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
451            return refuse("only ASCII letters, digits, `-` and `_` are allowed");
452        }
453        if STATE_RESERVED_NAMES.contains(&name.to_ascii_lowercase().as_str()) {
454            return refuse(
455                "the engine keeps its own state under that name in a project's `state/`",
456            );
457        }
458        Ok(Self {
459            product: Arc::from(name),
460            ..self
461        })
462    }
463
464    /// The engine's name in scripts and file names: the base library's
465    /// global, the start of its errors' name.
466    pub fn engine(&self) -> &str {
467        &self.engine
468    }
469
470    /// The directories under `$HOME` instances keep their state in unless
471    /// told otherwise: `.<engine>` for this engine's, then agixd's
472    /// [`DEFAULT_STATE_DIR`] when that is not it.
473    pub fn state_dir_names(&self) -> impl Iterator<Item = String> {
474        let own = format!(".{}", self.engine);
475        let agixd = (own != DEFAULT_STATE_DIR).then(|| DEFAULT_STATE_DIR.to_string());
476        std::iter::once(own).chain(agixd)
477    }
478
479    pub fn project_dir_name(&self) -> &str {
480        &self.project_dir
481    }
482
483    /// The name of the repository directory the engine's worktrees go in.
484    pub fn worktrees_dir_name(&self) -> &str {
485        &self.worktrees
486    }
487
488    /// The product's name as people read it: in prompts, messages, a
489    /// consent page, a notification.
490    pub fn product_name(&self) -> &str {
491        &self.product
492    }
493
494    /// The product's name where a machine reads it: lowercase.
495    pub fn product_id(&self) -> String {
496        self.product.to_ascii_lowercase()
497    }
498
499    /// `<product id>/<version>`, the `User-Agent` of the engine's requests.
500    pub fn user_agent(&self) -> String {
501        format!("{}/{}", self.product_id(), env!("CARGO_PKG_VERSION"))
502    }
503
504    /// The branch a worktree the engine makes is checked out on, before its
505    /// name: `<product id>/worktree-`.
506    pub fn worktree_branch_prefix(&self) -> String {
507        format!("{}/worktree-", self.product_id())
508    }
509
510    /// The name a nested repository's `.git` is moved aside to, before its
511    /// date: `.git.<product id>-quarantine-`.
512    pub fn quarantine_prefix(&self) -> String {
513        format!(".git.{}-quarantine-", self.product_id())
514    }
515
516    /// The product's machine-wide directory, where a deployment puts what
517    /// stands above every user and project: macOS `/Library/Application
518    /// Support/<name>`, Windows `%ProgramData%\<name>`, elsewhere
519    /// `/etc/<id>`. Only this product's: a renamed product has no reason to
520    /// read another's, and its name cannot spell a path out of the parent.
521    pub fn machine_dir(&self) -> PathBuf {
522        #[cfg(target_os = "macos")]
523        {
524            PathBuf::from("/Library/Application Support").join(self.product_name())
525        }
526        #[cfg(windows)]
527        {
528            #[expect(
529                clippy::disallowed_methods,
530                reason = "where Windows keeps machine-wide program data is a fact about this machine"
531            )]
532            let root = std::env::var_os("ProgramData")
533                .map(PathBuf::from)
534                .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"));
535            root.join(self.product_name())
536        }
537        #[cfg(not(any(target_os = "macos", windows)))]
538        {
539            PathBuf::from("/etc").join(self.product_id())
540        }
541    }
542
543    /// `<machine dir>/managed-settings.json`: the managed settings layer.
544    pub fn managed_settings_file(&self) -> PathBuf {
545        self.machine_dir().join(entry::MANAGED_SETTINGS)
546    }
547
548    /// `<machine dir>/mcp-policy.json`: which MCP servers may connect.
549    pub fn mcp_policy_file(&self) -> PathBuf {
550        self.machine_dir().join(entry::MCP_POLICY)
551    }
552
553    /// The product as a commit or pull request the model writes credits it:
554    /// a link where it is published, else its name.
555    pub fn attribution(&self) -> String {
556        if &*self.product == DEFAULT_PRODUCT_NAME {
557            format!("[{DEFAULT_PRODUCT_NAME}]({DEFAULT_PRODUCT_URL})")
558        } else {
559            self.product.to_string()
560        }
561    }
562
563    /// `<project_root>/<name>`.
564    pub fn project_dir(&self, project_root: &Path) -> PathBuf {
565        project_root.join(&*self.project_dir)
566    }
567
568    /// `<repo_root>/<worktrees dir>`: where the engine makes its worktrees.
569    pub fn worktrees_dir(&self, repo_root: &Path) -> PathBuf {
570        repo_root.join(&*self.worktrees)
571    }
572
573    /// The directories at a repository's root that hold the engine's
574    /// worktrees: this layout's, then [`DEFAULT_WORKTREES_DIR`] when that is
575    /// not it — where the worktrees made before the settings named another
576    /// directory, or by an instance whose settings name none, are.
577    pub fn worktrees_dir_names(&self) -> impl Iterator<Item = &str> {
578        let own: &str = &self.worktrees;
579        std::iter::once(own).chain((own != DEFAULT_WORKTREES_DIR).then_some(DEFAULT_WORKTREES_DIR))
580    }
581
582    /// `<project_root>/<name>/state`: what the engine keeps in the project
583    /// for this machine alone, all of it out of the repository.
584    pub fn project_state_dir(&self, project_root: &Path) -> PathBuf {
585        self.project_dir(project_root).join(entry::STATE)
586    }
587
588    /// `<project_root>/<name>/state/<product id>`: the embedder's own state
589    /// in the project, which the engine never writes and guards as it
590    /// guards its own.
591    pub fn host_state_dir(&self, project_root: &Path) -> PathBuf {
592        self.project_state_dir(project_root).join(self.product_id())
593    }
594
595    /// `<dir>/<name>/state/teams`.
596    pub fn teams_dir(&self, dir: &Path) -> PathBuf {
597        self.project_state_dir(dir).join(entry::TEAMS)
598    }
599
600    /// The repository `.gitignore` line keeping the worktrees directory out.
601    pub fn gitignore_entry(&self) -> String {
602        format!("{}/", self.worktrees)
603    }
604
605    /// The configuration roots the engine guards in a directory: its own
606    /// name first, then each of [`FOREIGN_CONFIG_ROOTS`] that is not it.
607    pub fn config_roots(&self) -> impl Iterator<Item = ConfigRoot<'_>> {
608        let own: &str = &self.project_dir;
609        std::iter::once(ConfigRoot {
610            name: own,
611            own: true,
612        })
613        .chain(
614            FOREIGN_CONFIG_ROOTS
615                .iter()
616                .filter(move |name| **name != own)
617                .map(|name| ConfigRoot { name, own: false }),
618        )
619    }
620
621    /// The directories an engine of this family writes a project's keys to:
622    /// the instance's own, and `.agix` when that is not it.
623    pub fn engine_dir_names(&self) -> impl Iterator<Item = &str> {
624        let own: &str = &self.project_dir;
625        std::iter::once(own).chain((own != DEFAULT_PROJECT_DIR).then_some(DEFAULT_PROJECT_DIR))
626    }
627
628    /// Whether a path component, compared without case, is the instance's
629    /// own project directory.
630    pub fn is_own_dir_component(&self, component: &str) -> bool {
631        super::fold_case(component) == *self.project_dir
632    }
633
634    /// What `path` names inside a git worktree an engine made,
635    /// `<repo>/<worktrees dir>/<w>/<rest>` for any of
636    /// [`Self::worktrees_dir_names`], as the main checkout holds it:
637    /// `<repo>/<rest>`, and for a worktree made inside another, each checkout
638    /// out to the main one. Nothing is read from disk: without case.
639    pub fn main_checkout_copies(&self, path: &Path) -> Vec<PathBuf> {
640        let mut copies = Vec::new();
641        let mut current: Vec<Component<'_>> = path.components().collect();
642        while let Some(at) = current.windows(2).rposition(|w| self.opens_a_worktree(w)) {
643            current.drain(at..at + 2);
644            copies.push(current.iter().collect());
645        }
646        copies
647    }
648
649    /// `<repo>/<worktrees dir>/<w>` when `path` is in one of the engine's
650    /// worktrees, the outermost when they nest.
651    pub fn worktree_of(&self, path: &Path) -> Option<PathBuf> {
652        let parts: Vec<Component<'_>> = path.components().collect();
653        let at = parts.windows(2).position(|w| self.opens_a_worktree(w))?;
654        Some(parts.get(..at + 2)?.iter().collect())
655    }
656
657    fn opens_a_worktree(&self, pair: &[Component<'_>]) -> bool {
658        let [Component::Normal(dir), Component::Normal(_)] = pair else {
659            return false;
660        };
661        let dir = super::fold_case(&dir.to_string_lossy());
662        self.worktrees_dir_names()
663            .any(|name| super::fold_case(name) == dir)
664    }
665}
666
667/// An instance's state root: global settings, scenes, transcripts, plugins,
668/// the daemon's files. The names under it do not follow [`Layout`].
669#[derive(Debug, Clone, PartialEq, Eq, Hash)]
670pub struct StateRoot(PathBuf);
671
672impl StateRoot {
673    pub fn new(root: impl Into<PathBuf>) -> Self {
674        Self(root.into())
675    }
676
677    pub fn path(&self) -> &Path {
678        &self.0
679    }
680
681    pub fn into_path(self) -> PathBuf {
682        self.0
683    }
684
685    pub fn settings_file(&self) -> PathBuf {
686        self.0.join(entry::SETTINGS)
687    }
688
689    pub fn settings_local_file(&self) -> PathBuf {
690        self.0.join(entry::SETTINGS_LOCAL)
691    }
692
693    pub fn scenes_dir(&self) -> PathBuf {
694        self.0.join(entry::SCENES)
695    }
696
697    pub fn scene_dir(&self, scene: &str) -> PathBuf {
698        self.scenes_dir().join(scene)
699    }
700
701    /// `<scene dir>/scheduled_tasks.json`.
702    pub fn scheduled_tasks_file(&self, scene: &str) -> PathBuf {
703        self.scene_dir(scene).join(entry::SCHEDULED_TASKS)
704    }
705
706    pub fn plugins_dir(&self) -> PathBuf {
707        self.0.join(entry::PLUGINS)
708    }
709
710    pub fn plugin_cache_dir(&self) -> PathBuf {
711        self.plugins_dir().join(entry::CACHE)
712    }
713
714    pub fn tmp_dir(&self) -> PathBuf {
715        self.0.join(entry::TMP)
716    }
717
718    pub fn projects_dir(&self) -> PathBuf {
719        self.0.join(entry::PROJECTS)
720    }
721
722    pub fn sessions_dir(&self) -> PathBuf {
723        self.0.join(entry::SESSIONS)
724    }
725
726    pub fn recordings_dir(&self) -> PathBuf {
727        self.0.join(entry::RECORDINGS)
728    }
729
730    pub fn daemon_dir(&self) -> PathBuf {
731        self.0.join(entry::DAEMON)
732    }
733
734    pub fn instances_dir(&self) -> PathBuf {
735        self.daemon_dir().join(entry::INSTANCES)
736    }
737
738    pub fn auth_dir(&self) -> PathBuf {
739        self.daemon_dir().join(entry::AUTH)
740    }
741
742    pub fn groups_dir(&self) -> PathBuf {
743        self.daemon_dir().join(entry::GROUPS)
744    }
745
746    /// `daemon/groups/<instance>.json`.
747    pub fn groups_file(&self, instance: &str) -> PathBuf {
748        self.groups_dir().join(format!("{instance}.json"))
749    }
750
751    pub fn crashes_dir(&self) -> PathBuf {
752        self.daemon_dir().join(entry::CRASHES)
753    }
754}
755
756impl AsRef<Path> for StateRoot {
757    fn as_ref(&self) -> &Path {
758        &self.0
759    }
760}
761
762/// The two layouts every test of a security decision runs under: the
763/// default, where `.agix` is both the instance's own and the foreign root,
764/// and a renamed one, where they differ and the worktrees are elsewhere.
765#[cfg(test)]
766pub(crate) fn test_layouts() -> [Layout; 2] {
767    [
768        Layout::default(),
769        Layout::new(".codix")
770            .unwrap()
771            .with_worktrees_dir(".trees")
772            .unwrap(),
773    ]
774}
775
776#[cfg(test)]
777mod tests {
778    use super::*;
779
780    #[test]
781    fn a_name_is_one_hidden_lowercase_component_of_no_other_tool() {
782        for good in [".agix", ".codix", ".agent-state", ".x_1.d"] {
783            assert_eq!(Layout::new(good).unwrap().project_dir_name(), good);
784        }
785        for bad in [
786            "",
787            ".",
788            "..",
789            "a/b",
790            "../x",
791            ".Agix",
792            ".git",
793            ".agents",
794            ".claude",
795            "a b",
796            "a\\b",
797            "x$y",
798            "src",
799            "docs",
800            "node_modules",
801            "agent-state",
802            ".github",
803            ".vscode",
804            ".idea",
805            ".codex",
806            ".cursor",
807        ] {
808            assert!(Layout::new(bad).is_err(), "{bad:?}");
809        }
810        assert!(Layout::new(&"a".repeat(65)).is_err());
811        assert!(Layout::new(DEFAULT_WORKTREES_DIR).is_err());
812        assert_eq!(Layout::default().project_dir_name(), DEFAULT_PROJECT_DIR);
813    }
814
815    #[test]
816    fn a_worktrees_dir_is_one_hidden_component_of_no_configuration_root() {
817        for good in [
818            ".wkts",
819            ".trees",
820            ".Trees",
821            ".work_trees-2",
822            &format!(".{}", "a".repeat(63)),
823        ] {
824            let layout = Layout::default().with_worktrees_dir(good).unwrap();
825            assert_eq!(layout.worktrees_dir_name(), good);
826            assert_eq!(layout.project_dir_name(), DEFAULT_PROJECT_DIR);
827        }
828        let codix = Layout::new(".codix").unwrap();
829        for bad in [
830            "",
831            ".",
832            "..",
833            "wkts",
834            "a/b",
835            ".a/b",
836            "../x",
837            ".a b",
838            ".a\\b",
839            ".x$y",
840            ".tr\u{e9}es",
841            ".git",
842            ".GIT",
843            ".gitignore",
844            ".gitmodules",
845            ".GitAttributes",
846            ".git-blame-ignore-revs",
847            ".gitlab",
848            ".agix",
849            ".AGIX",
850            ".claude",
851            ".Claude",
852            ".agents",
853            ".github",
854            ".vscode",
855            ".idea",
856            ".codex",
857            ".cursor",
858            &format!(".{}", "a".repeat(64)),
859        ] {
860            assert!(
861                Layout::default().with_worktrees_dir(bad).is_err(),
862                "{bad:?}"
863            );
864            assert!(codix.clone().with_worktrees_dir(bad).is_err(), "{bad:?}");
865        }
866        assert!(codix.clone().with_worktrees_dir(".codix").is_err());
867        assert!(codix.clone().with_worktrees_dir(".Codix").is_err());
868        assert!(Layout::default().with_worktrees_dir(".codix").is_ok());
869        assert_eq!(
870            Layout::default().worktrees_dir_name(),
871            DEFAULT_WORKTREES_DIR
872        );
873        let named = Layout::new(".codix")
874            .unwrap()
875            .with_product_name("Codix")
876            .unwrap()
877            .with_worktrees_dir(".trees")
878            .unwrap();
879        assert_eq!(
880            (named.project_dir_name(), named.product_name()),
881            (".codix", "Codix")
882        );
883        assert_eq!(
884            named
885                .with_product_name("Other")
886                .unwrap()
887                .worktrees_dir_name(),
888            ".trees"
889        );
890    }
891
892    #[test]
893    fn a_product_name_is_a_letter_then_letters_digits_dashes_underscores() {
894        for good in ["Agix", "Codix", "x", "My-Agent_2", &"A".repeat(32)] {
895            let layout = Layout::default().with_product_name(good).unwrap();
896            assert_eq!(layout.product_name(), good);
897            assert_eq!(layout.project_dir_name(), DEFAULT_PROJECT_DIR);
898        }
899        for bad in [
900            "",
901            "1x",
902            "-x",
903            "a b",
904            "a/b",
905            "a.b",
906            "a..b",
907            "a@b",
908            "Ägix",
909            &"A".repeat(33),
910        ] {
911            assert!(Layout::default().with_product_name(bad).is_err(), "{bad:?}");
912        }
913        assert_eq!(Layout::default().product_name(), DEFAULT_PRODUCT_NAME);
914    }
915
916    #[test]
917    fn a_product_id_is_none_of_the_names_the_engine_keeps_in_state() {
918        for reserved in STATE_RESERVED_NAMES
919            .iter()
920            .filter(|n| !n.starts_with('.') && !n.contains('-'))
921        {
922            let capitalised = format!("{}{}", reserved[..1].to_uppercase(), &reserved[1..]);
923            for name in [reserved.to_string(), capitalised, reserved.to_uppercase()] {
924                assert!(
925                    Layout::default().with_product_name(&name).is_err(),
926                    "{name}"
927                );
928            }
929        }
930        for name in ["Tool-Results", "History", "Imported"] {
931            assert!(Layout::default().with_product_name(name).is_err(), "{name}");
932        }
933        for entry in PROJECT_STATE_ENTRIES
934            .iter()
935            .chain(PROJECT_STATE_ENGINE_DIRS)
936        {
937            let id = entry.trim_start_matches('.').trim_end_matches(".json");
938            assert!(STATE_RESERVED_NAMES.contains(&id), "{entry}");
939        }
940        assert!(!STATE_RESERVED_NAMES.contains(&DEFAULT_PRODUCT_NAME.to_ascii_lowercase().as_str()));
941        let codix = Layout::default().with_product_name("Codix").unwrap();
942        assert_eq!(
943            codix.host_state_dir(Path::new("/repo")),
944            Path::new("/repo/.agix/state/codix")
945        );
946    }
947
948    #[test]
949    fn an_engine_name_is_a_lowercase_script_global_and_names_the_project_directory() {
950        let agix = Layout::default();
951        assert_eq!(agix.engine(), DEFAULT_ENGINE);
952        assert_eq!(format!(".{DEFAULT_ENGINE}"), DEFAULT_PROJECT_DIR);
953        assert_eq!(agix.state_dir_names().collect::<Vec<_>>(), [".agix"]);
954        for good in ["foo", "x", "codix2", &"a".repeat(16)] {
955            let layout = Layout::default().with_engine(good).unwrap();
956            assert_eq!(layout.engine(), good);
957            assert_eq!(layout.project_dir_name(), format!(".{good}"));
958            assert_eq!(layout.product_name(), DEFAULT_PRODUCT_NAME);
959        }
960        let foo = Layout::default().with_engine("foo").unwrap();
961        assert_eq!(foo.state_dir_names().collect::<Vec<_>>(), [".foo", ".agix"]);
962        assert_eq!(
963            foo.config_roots().map(|r| r.name).collect::<Vec<_>>(),
964            [".foo", ".agix", ".claude"]
965        );
966        let named = foo.with_project_dir(".codix").unwrap();
967        assert_eq!(
968            (named.engine(), named.project_dir_name()),
969            ("foo", ".codix")
970        );
971        for bad in [
972            "",
973            "Foo",
974            "1x",
975            "a-b",
976            "a_b",
977            "a.b",
978            "f\u{f6}o",
979            "class",
980            "new",
981            "tools",
982            "console",
983            "escape",
984            "constructor",
985            "git",
986            "claude",
987            "codex",
988            "wkts",
989            &"a".repeat(17),
990        ] {
991            assert!(Layout::default().with_engine(bad).is_err(), "{bad:?}");
992        }
993        let trees = Layout::default().with_worktrees_dir(".foo").unwrap();
994        assert!(trees.clone().with_engine("foo").is_err());
995        assert!(trees.with_project_dir(".foo").is_err());
996    }
997
998    #[test]
999    fn what_a_product_name_names_follows_it() {
1000        let codix = Layout::new(".codix")
1001            .unwrap()
1002            .with_product_name("Codix")
1003            .unwrap();
1004        assert_eq!(codix.project_dir_name(), ".codix");
1005        assert_eq!(codix.product_id(), "codix");
1006        assert_eq!(
1007            codix.user_agent(),
1008            format!("codix/{}", env!("CARGO_PKG_VERSION"))
1009        );
1010        assert_eq!(codix.worktree_branch_prefix(), "codix/worktree-");
1011        assert_eq!(codix.quarantine_prefix(), ".git.codix-quarantine-");
1012        assert_eq!(codix.attribution(), "Codix");
1013        let agix = Layout::default();
1014        assert_eq!(agix.worktree_branch_prefix(), "agix/worktree-");
1015        assert_eq!(agix.quarantine_prefix(), ".git.agix-quarantine-");
1016        assert_eq!(
1017            agix.user_agent(),
1018            format!("agix/{}", env!("CARGO_PKG_VERSION"))
1019        );
1020        assert_eq!(
1021            agix.attribution(),
1022            "[Agix](https://github.com/harnixai/agix)"
1023        );
1024        for layout in [&agix, &codix] {
1025            assert!(layout.machine_dir().is_absolute());
1026            assert_eq!(
1027                layout.managed_settings_file(),
1028                layout.machine_dir().join("managed-settings.json")
1029            );
1030            assert_eq!(
1031                layout.mcp_policy_file(),
1032                layout.machine_dir().join("mcp-policy.json")
1033            );
1034        }
1035        assert!(codix
1036            .machine_dir()
1037            .to_string_lossy()
1038            .to_lowercase()
1039            .ends_with("codix"));
1040        assert!(!codix
1041            .machine_dir()
1042            .to_string_lossy()
1043            .to_lowercase()
1044            .contains("agix"));
1045    }
1046
1047    #[test]
1048    fn its_own_root_comes_first_and_the_foreign_ones_follow_without_it() {
1049        let roots = |l: &Layout| -> Vec<(String, bool)> {
1050            l.config_roots()
1051                .map(|r| (r.name.to_string(), r.own))
1052                .collect()
1053        };
1054        assert_eq!(
1055            roots(&Layout::default()),
1056            [(".agix".into(), true), (".claude".into(), false)]
1057        );
1058        assert_eq!(
1059            roots(&Layout::new(".codix").unwrap()),
1060            [
1061                (".codix".into(), true),
1062                (".agix".into(), false),
1063                (".claude".into(), false)
1064            ]
1065        );
1066        assert_eq!(
1067            Layout::new(".codix")
1068                .unwrap()
1069                .engine_dir_names()
1070                .collect::<Vec<_>>(),
1071            [".codix", ".agix"]
1072        );
1073        assert_eq!(
1074            Layout::default().engine_dir_names().collect::<Vec<_>>(),
1075            [".agix"]
1076        );
1077    }
1078
1079    #[test]
1080    fn the_derived_paths_follow_the_name() {
1081        for layout in test_layouts() {
1082            let name = layout.project_dir_name().to_string();
1083            let worktrees = layout.worktrees_dir_name().to_string();
1084            let root = Path::new("/repo");
1085            assert_eq!(layout.project_dir(root), root.join(&name));
1086            assert_eq!(layout.worktrees_dir(root), root.join(&worktrees));
1087            assert_eq!(
1088                layout.project_state_dir(root),
1089                root.join(&name).join("state")
1090            );
1091            assert_eq!(layout.teams_dir(root), root.join(&name).join("state/teams"));
1092            assert_eq!(
1093                layout.host_state_dir(root),
1094                root.join(&name).join("state").join(layout.product_id())
1095            );
1096            assert_eq!(layout.gitignore_entry(), format!("{worktrees}/"));
1097            assert!(layout.is_own_dir_component(&name.to_uppercase()));
1098        }
1099        assert_eq!(
1100            Layout::default().worktrees_dir(Path::new("/repo")),
1101            Path::new("/repo/.wkts")
1102        );
1103        assert_eq!(Layout::default().gitignore_entry(), ".wkts/");
1104        assert_eq!(
1105            Layout::default().worktrees_dir_names().collect::<Vec<_>>(),
1106            [".wkts"]
1107        );
1108        assert_eq!(
1109            Layout::default()
1110                .with_worktrees_dir(".trees")
1111                .unwrap()
1112                .worktrees_dir_names()
1113                .collect::<Vec<_>>(),
1114            [".trees", ".wkts"]
1115        );
1116    }
1117
1118    #[test]
1119    fn a_path_in_a_worktree_has_its_main_checkout_copies() {
1120        for layout in test_layouts() {
1121            let wk = layout.worktrees_dir_name();
1122            let nested = format!("/repo/{wk}/a/{wk}/b/src/x.rs");
1123            assert_eq!(
1124                layout.main_checkout_copies(Path::new(&nested)),
1125                [
1126                    PathBuf::from(format!("/repo/{wk}/a/src/x.rs")),
1127                    PathBuf::from("/repo/src/x.rs")
1128                ]
1129            );
1130            assert_eq!(
1131                layout.worktree_of(Path::new(&nested)),
1132                Some(PathBuf::from(format!("/repo/{wk}/a")))
1133            );
1134            let upper = format!("/repo/{}/a/src/x.rs", wk.to_uppercase());
1135            assert_eq!(
1136                layout.main_checkout_copies(Path::new(&upper)),
1137                [PathBuf::from("/repo/src/x.rs")]
1138            );
1139            assert_eq!(
1140                layout.worktree_of(Path::new(&upper)),
1141                Some(PathBuf::from(format!("/repo/{}/a", wk.to_uppercase())))
1142            );
1143            assert!(layout
1144                .main_checkout_copies(Path::new(&format!("/repo/{wk}")))
1145                .is_empty());
1146            assert_eq!(layout.worktree_of(Path::new("/repo/src/x.rs")), None);
1147            assert_eq!(
1148                layout.main_checkout_copies(Path::new(&format!("/repo/{wk}/wt"))),
1149                [PathBuf::from("/repo")]
1150            );
1151            let own = layout.project_dir_name();
1152            for not_one in [
1153                format!("/repo/{own}/sessions/s/x"),
1154                format!("/repo/{own}/worktrees/a/x"),
1155                "/repo/src/a".to_string(),
1156                "/repo/wkts/a/x".to_string(),
1157            ] {
1158                assert!(
1159                    layout.main_checkout_copies(Path::new(&not_one)).is_empty(),
1160                    "{not_one}"
1161                );
1162                assert_eq!(layout.worktree_of(Path::new(&not_one)), None, "{not_one}");
1163            }
1164        }
1165        let trees = Layout::new(".codix")
1166            .unwrap()
1167            .with_worktrees_dir(".trees")
1168            .unwrap();
1169        assert_eq!(
1170            trees.main_checkout_copies(Path::new("/repo/.wkts/a/.trees/b/x")),
1171            [PathBuf::from("/repo/.wkts/a/x"), PathBuf::from("/repo/x")],
1172            "a worktree made under the default directory is still an alias of the main checkout"
1173        );
1174        assert_eq!(
1175            trees.worktree_of(Path::new("/repo/.wkts/a/x")),
1176            Some(PathBuf::from("/repo/.wkts/a"))
1177        );
1178        assert!(Layout::default()
1179            .main_checkout_copies(Path::new("/repo/.trees/a/x"))
1180            .is_empty());
1181    }
1182
1183    #[test]
1184    fn the_state_roots_entries_are_under_it() {
1185        let root = StateRoot::new("/state");
1186        assert_eq!(root.scene_dir("code"), Path::new("/state/scenes/code"));
1187        assert_eq!(
1188            root.scheduled_tasks_file("code"),
1189            Path::new("/state/scenes/code/scheduled_tasks.json")
1190        );
1191        assert_eq!(
1192            root.groups_file("desktop"),
1193            Path::new("/state/daemon/groups/desktop.json")
1194        );
1195        assert_eq!(root.instances_dir(), Path::new("/state/daemon/instances.d"));
1196        assert_eq!(root.plugin_cache_dir(), Path::new("/state/plugins/cache"));
1197    }
1198}