1use std::path::{Component, Path, PathBuf};
19use std::sync::Arc;
20
21pub const DEFAULT_ENGINE: &str = "agix";
23
24pub const DEFAULT_PROJECT_DIR: &str = ".agix";
26
27pub const DEFAULT_STATE_DIR: &str = ".agix";
30
31pub const FOREIGN_CONFIG_ROOTS: &[&str] = &[DEFAULT_PROJECT_DIR, CLAUDE_DIR];
36
37pub const CLAUDE_DIR: &str = ".claude";
39
40pub const CLAUDE_CREDENTIALS: &str = ".claude/.credentials.json";
42
43pub const AGENTS_DIR: &str = ".agents";
47
48pub const PROJECT_SKILLS_DIR: &str = ".agents/skills";
50
51pub const DEFAULT_PRODUCT_NAME: &str = "Agix";
53
54pub const DEFAULT_PRODUCT_URL: &str = "https://github.com/harnixai/agix";
56
57pub const GIT_WORKTREES_DIR: &str = "worktrees";
59
60pub const DEFAULT_WORKTREES_DIR: &str = ".wkts";
63
64pub 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
112pub const SETTINGS_FILE: &str = entry::SETTINGS;
114
115pub const SETTINGS_LOCAL_FILE: &str = entry::SETTINGS_LOCAL;
118
119pub const STATE_ROOT_WORKING_DIRS: &[&str] = &[STATE_ROOT_SCRATCHPAD, entry::MEMORY];
124
125pub const STATE_ROOT_SCRATCHPAD: &str = entry::SCRATCHPAD;
127
128pub const STATE_ROOT_SESSION_TMP: &str = entry::TMP;
132
133pub const ENGINE_CONFIG_FILES: &[&str] =
137 &[entry::SETTINGS, entry::SETTINGS_LOCAL, entry::MCP_LOCAL];
138
139pub 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
158pub const PROJECT_ENGINE_CONFIG_DIRS: &[&str] = &[PROJECT_SKILLS_DIR];
164
165pub const STATE_ROOT_SCENE_FILES: &[&str] =
169 &[entry::SETTINGS, entry::SCENE_FILE, entry::SCENE_PROMPT];
170
171pub const LOCAL_CONFIG_FILES: &[&str] = &[entry::SETTINGS_LOCAL, entry::MCP_LOCAL];
177
178pub 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
190pub const PROJECT_STATE_ENGINE_DIRS: &[&str] = &[entry::TOOL_RESULTS, entry::HISTORY];
194
195pub 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
211pub 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#[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#[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#[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#[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#[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
279fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct ConfigRoot<'a> {
304 pub name: &'a str,
305 pub own: bool,
307}
308
309impl Layout {
310 pub fn new(project_dir: &str) -> Result<Self, LayoutError> {
313 Self::default().with_project_dir(project_dir)
314 }
315
316 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 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 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 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 pub fn engine(&self) -> &str {
467 &self.engine
468 }
469
470 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 pub fn worktrees_dir_name(&self) -> &str {
485 &self.worktrees
486 }
487
488 pub fn product_name(&self) -> &str {
491 &self.product
492 }
493
494 pub fn product_id(&self) -> String {
496 self.product.to_ascii_lowercase()
497 }
498
499 pub fn user_agent(&self) -> String {
501 format!("{}/{}", self.product_id(), env!("CARGO_PKG_VERSION"))
502 }
503
504 pub fn worktree_branch_prefix(&self) -> String {
507 format!("{}/worktree-", self.product_id())
508 }
509
510 pub fn quarantine_prefix(&self) -> String {
513 format!(".git.{}-quarantine-", self.product_id())
514 }
515
516 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 pub fn managed_settings_file(&self) -> PathBuf {
545 self.machine_dir().join(entry::MANAGED_SETTINGS)
546 }
547
548 pub fn mcp_policy_file(&self) -> PathBuf {
550 self.machine_dir().join(entry::MCP_POLICY)
551 }
552
553 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 pub fn project_dir(&self, project_root: &Path) -> PathBuf {
565 project_root.join(&*self.project_dir)
566 }
567
568 pub fn worktrees_dir(&self, repo_root: &Path) -> PathBuf {
570 repo_root.join(&*self.worktrees)
571 }
572
573 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 pub fn project_state_dir(&self, project_root: &Path) -> PathBuf {
585 self.project_dir(project_root).join(entry::STATE)
586 }
587
588 pub fn host_state_dir(&self, project_root: &Path) -> PathBuf {
592 self.project_state_dir(project_root).join(self.product_id())
593 }
594
595 pub fn teams_dir(&self, dir: &Path) -> PathBuf {
597 self.project_state_dir(dir).join(entry::TEAMS)
598 }
599
600 pub fn gitignore_entry(&self) -> String {
602 format!("{}/", self.worktrees)
603 }
604
605 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 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 pub fn is_own_dir_component(&self, component: &str) -> bool {
631 super::fold_case(component) == *self.project_dir
632 }
633
634 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 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#[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 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 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#[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(¬_one)).is_empty(),
1160 "{not_one}"
1161 );
1162 assert_eq!(layout.worktree_of(Path::new(¬_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}