1use std::path::{Path, PathBuf};
16
17use super::layout::{
18 entry, Layout, CLAUDE_CREDENTIALS, ENGINE_CONFIG_FILES, PROJECT_ENGINE_CONFIG_DIRS,
19 STATE_ROOT_SCRATCHPAD, STATE_ROOT_SESSION_TMP, STATE_ROOT_WORKING_DIRS,
20};
21use super::ConfigPaths;
22
23mod config_root;
24mod spellings;
25pub use config_root::ConfigRootAt;
26use spellings::{absolute_lexically, lowered_components, Spellings};
27
28pub const REPOSITORY_CONFIG_DIR: &str = ".git";
33
34pub const GIT_CONTROL_FILES: &[&str] = &["config", "config.worktree", "commondir"];
37
38pub const GIT_WORKTREE_CONTROL_FILES: &[&str] =
42 &["config", "config.worktree", "commondir", "gitdir"];
43
44pub const GIT_HOOKS_DIR: &str = "hooks";
46
47pub const SECRET_FILE_NAMES: &[&str] = &[
50 ".env",
51 ".env.local",
52 ".env.production",
53 "id_rsa",
54 "id_ed25519",
55 ".netrc",
56 ".pypirc",
57 ".npmrc",
58 ".pgpass",
59];
60
61pub const HOME_CREDENTIAL_STORES: &[&str] = &[
65 ".ssh",
66 ".aws",
67 ".gnupg",
68 ".docker/config.json",
69 ".kube",
70 ".azure",
71 ".config/gh",
72 ".netrc",
73 ".npmrc",
74 ".pypirc",
75 ".gem/credentials",
76 ".git-credentials",
77 ".config/git/credentials",
78 ".config/gcloud",
79 ".cargo/credentials",
80 ".cargo/credentials.toml",
81 ".vault-token",
82 ".terraform.d/credentials.tfrc.json",
83 ".config/glab-cli",
84 ".config/hub",
85 ".config/doctl",
86 ".oci",
87 ".boto",
88 ".s3cfg",
89 ".databrickscfg",
90 ".config/rclone",
91 ".huggingface/token",
92 ".cache/huggingface/token",
93 CLAUDE_CREDENTIALS,
94 ".codex/auth.json",
95];
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct Credential {
101 pub scope: Scope,
102 pub secret: Secret,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum Scope {
108 StateRoot,
110 EachSceneDir,
112 AnyEngineDir,
116 Anywhere,
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum Secret {
124 KeyFiles(KeyFileNames),
126 Tree(&'static str),
128 DirName(&'static str),
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum KeyFileNames {
135 StateRoot,
138 Project,
140}
141
142impl KeyFileNames {
143 pub fn stems(self) -> &'static [&'static str] {
144 match self {
145 Self::StateRoot => &["settings", "mcp.local"],
146 Self::Project => &[entry::SETTINGS_LOCAL, entry::MCP_LOCAL],
147 }
148 }
149
150 pub fn admits(self, name: &str) -> bool {
155 let name = name.strip_prefix('.').unwrap_or(name);
156 let stem = self.stems().iter().any(|stem| name.starts_with(stem));
157 match self {
158 Self::StateRoot => stem && name.contains(".json"),
159 Self::Project => stem,
160 }
161 }
162}
163
164impl Secret {
165 fn holds(self, rest: &[String]) -> bool {
168 match self {
169 Self::KeyFiles(names) => rest.first().is_some_and(|name| names.admits(name)),
170 Self::Tree(path) | Self::DirName(path) => {
171 let path: Vec<&str> = path.split('/').collect();
172 rest.len() >= path.len() && path.iter().zip(rest).all(|(p, c)| p == c)
173 }
174 }
175 }
176}
177
178pub const CREDENTIALS: &[Credential] = &[
180 Credential {
181 scope: Scope::StateRoot,
182 secret: Secret::KeyFiles(KeyFileNames::StateRoot),
183 },
184 Credential {
185 scope: Scope::EachSceneDir,
186 secret: Secret::KeyFiles(KeyFileNames::StateRoot),
187 },
188 Credential {
189 scope: Scope::StateRoot,
190 secret: Secret::Tree("mcp/oauth"),
191 },
192 Credential {
193 scope: Scope::EachSceneDir,
194 secret: Secret::Tree("mcp/oauth"),
195 },
196 Credential {
197 scope: Scope::StateRoot,
198 secret: Secret::Tree("daemon/auth"),
199 },
200 Credential {
201 scope: Scope::AnyEngineDir,
202 secret: Secret::KeyFiles(KeyFileNames::Project),
203 },
204 Credential {
205 scope: Scope::Anywhere,
206 secret: Secret::DirName(".ssh"),
207 },
208 Credential {
209 scope: Scope::Anywhere,
210 secret: Secret::DirName(".aws"),
211 },
212 Credential {
213 scope: Scope::Anywhere,
214 secret: Secret::DirName(".gnupg"),
215 },
216];
217
218pub fn credential_dir_names() -> impl Iterator<Item = &'static str> {
220 CREDENTIALS.iter().filter_map(|c| match c.secret {
221 Secret::DirName(name) if c.scope == Scope::Anywhere => Some(name),
222 _ => None,
223 })
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct Located {
229 pub base: PathBuf,
231 pub under_each_scene: bool,
233 pub secret: Secret,
234}
235
236impl Located {
237 pub fn dirs(&self) -> Vec<PathBuf> {
240 if self.under_each_scene {
241 scene_dirs_in(&self.base)
242 .into_iter()
243 .map(|scene| scene.path)
244 .collect()
245 } else {
246 vec![self.base.clone()]
247 }
248 }
249
250 pub fn linked_dirs_resolved(&self) -> Vec<PathBuf> {
254 if !self.under_each_scene {
255 return Vec::new();
256 }
257 scene_dirs_in(&self.base)
258 .into_iter()
259 .filter(|scene| scene.resolved != scene.path)
260 .map(|scene| scene.resolved)
261 .collect()
262 }
263
264 pub fn existing(&self) -> Vec<PathBuf> {
266 let mut found = Vec::new();
267 for dir in self.dirs() {
268 match self.secret {
269 Secret::KeyFiles(names) => {
270 let Ok(entries) = std::fs::read_dir(&dir) else {
271 continue;
272 };
273 found.extend(
274 entries
275 .flatten()
276 .filter(|e| {
277 e.file_name()
278 .to_str()
279 .is_some_and(|n| names.admits(&super::fold_case(n)))
280 })
281 .map(|e| e.path()),
282 );
283 }
284 Secret::Tree(path) | Secret::DirName(path) => found.push(dir.join(path)),
285 }
286 }
287 found.retain(|p| p.symlink_metadata().is_ok());
288 found.sort();
289 found
290 }
291}
292
293pub fn known_state_roots(layout: &Layout) -> Vec<PathBuf> {
298 let home = super::home_dir().into_iter();
299 home.flat_map(|home| layout.state_dir_names().map(move |n| home.join(n)))
300 .collect()
301}
302
303#[derive(Debug, Clone, Default)]
306pub struct SensitivePaths {
307 state_root: Option<Spellings>,
308 foreign_state_roots: Vec<Spellings>,
311 project: Option<Spellings>,
312 linked_scenes: Vec<PathBuf>,
316 read_denials: Vec<Spellings>,
317 read_exemptions: Vec<Spellings>,
318 layout: Layout,
319}
320
321impl SensitivePaths {
322 pub fn new(state_root: Option<&Path>, project: Option<&Path>, layout: Layout) -> Self {
323 let state_root = state_root.map(Spellings::of);
324 let linked_scenes = state_root.iter().flat_map(linked_scenes_of).collect();
325 Self {
326 state_root,
327 foreign_state_roots: Vec::new(),
328 project: project.map(Spellings::of),
329 linked_scenes,
330 read_denials: Vec::new(),
331 read_exemptions: Vec::new(),
332 layout,
333 }
334 }
335
336 pub fn with_foreign_state_roots(mut self, roots: &[PathBuf]) -> Self {
340 for root in roots {
341 let root = Spellings::of(root);
342 let own = self
343 .state_root
344 .as_ref()
345 .is_some_and(|s| s.real == root.real);
346 let known = self.foreign_state_roots.iter().any(|f| f.real == root.real);
347 if !own && !known {
348 self.linked_scenes.extend(linked_scenes_of(&root));
349 self.foreign_state_roots.push(root);
350 }
351 }
352 self
353 }
354
355 pub fn foreign_state_roots(&self) -> Vec<PathBuf> {
357 self.foreign_state_roots
358 .iter()
359 .map(|root| root.given.clone())
360 .collect()
361 }
362
363 fn every_state_root(&self) -> impl Iterator<Item = &Spellings> {
365 self.state_root.iter().chain(&self.foreign_state_roots)
366 }
367
368 pub fn layout(&self) -> &Layout {
370 &self.layout
371 }
372
373 pub fn with_read_denials(mut self, denied: &[PathBuf], allowed: &[PathBuf]) -> Self {
377 self.read_denials = denied.iter().map(|p| Spellings::of(p)).collect();
378 self.read_exemptions = allowed.iter().map(|p| Spellings::of(p)).collect();
379 self
380 }
381
382 fn read_denied(&self, components: &[String]) -> bool {
383 let depth_in = |roots: &[Spellings]| {
384 roots
385 .iter()
386 .flat_map(|root| &root.lowered)
387 .filter(|root| components.starts_with(root))
388 .map(Vec::len)
389 .max()
390 };
391 match (
392 depth_in(&self.read_denials),
393 depth_in(&self.read_exemptions),
394 ) {
395 (Some(denied), Some(allowed)) => denied > allowed,
396 (Some(_), None) => true,
397 _ => false,
398 }
399 }
400
401 pub fn linked_scene_dirs_resolved(&self) -> &[PathBuf] {
404 &self.linked_scenes
405 }
406
407 pub fn for_paths(paths: &ConfigPaths) -> Self {
411 Self::new(
412 Some(&paths.global_data_dir),
413 paths.project_root.as_deref(),
414 paths.layout.clone(),
415 )
416 .with_foreign_state_roots(&known_state_roots(&paths.layout))
417 }
418
419 pub fn state_root(&self) -> Option<&Path> {
420 self.state_root.as_ref().map(|s| s.given.as_path())
421 }
422
423 pub fn is_credential(&self, abs: &Path) -> bool {
427 let components = lowered_components(abs);
428 self.read_denied(&components)
429 || CREDENTIALS
430 .iter()
431 .any(|credential| self.holds(credential, &components))
432 }
433
434 fn holds(&self, credential: &Credential, components: &[String]) -> bool {
435 let secret = credential.secret;
436 if credential.scope == Scope::EachSceneDir
437 && self.linked_scenes.iter().any(|scene| {
438 components
439 .strip_prefix(lowered_components(scene).as_slice())
440 .is_some_and(|rest| secret.holds(rest))
441 })
442 {
443 return true;
444 }
445 match credential.scope {
446 Scope::Anywhere => (0..components.len()).any(|i| secret.holds(&components[i..])),
447 Scope::AnyEngineDir => components.iter().enumerate().any(|(i, c)| {
448 self.layout.engine_dir_names().any(|dir| c == dir)
449 && secret.holds(&components[i + 1..])
450 }),
451 Scope::StateRoot | Scope::EachSceneDir => self
452 .every_state_root()
453 .flat_map(|root| &root.lowered)
454 .any(|root| {
455 let Some(rest) = components.strip_prefix(root.as_slice()) else {
456 return false;
457 };
458 match (credential.scope, rest) {
459 (Scope::StateRoot, _) => secret.holds(rest),
460 (_, [scenes, _, inner @ ..]) => {
461 scenes == entry::SCENES && secret.holds(inner)
462 }
463 _ => false,
464 }
465 }),
466 }
467 }
468
469 pub fn credential_locations(&self, engine_dirs: &[PathBuf]) -> Vec<Located> {
476 let mut located = Vec::new();
477 for credential in CREDENTIALS {
478 let at = |base: &Path| Located {
479 base: base.to_path_buf(),
480 under_each_scene: credential.scope == Scope::EachSceneDir,
481 secret: credential.secret,
482 };
483 match credential.scope {
484 Scope::StateRoot | Scope::EachSceneDir => {
485 located.extend(self.every_state_root().map(|root| at(&root.real)));
486 }
487 Scope::AnyEngineDir => located.extend(engine_dirs.iter().map(|dir| at(dir))),
488 Scope::Anywhere => {}
489 }
490 }
491 located
492 }
493
494 pub fn engine_dirs_in(&self, dir: &Path) -> Vec<PathBuf> {
498 let mut dirs = Vec::new();
499 for name in self.layout.engine_dir_names() {
500 let given = dir.join(name);
501 let real = crate::path::resolve_physically(&given);
502 dirs.push(given.clone());
503 if real != given {
504 dirs.push(real);
505 }
506 }
507 dirs
508 }
509
510 pub fn config_roots_in(&self, dir: &Path) -> Vec<ConfigRootAt> {
513 self.layout
514 .config_roots()
515 .map(|root| {
516 let path = dir.join(root.name);
517 ConfigRootAt {
518 resolved: crate::path::resolve_physically(&path),
519 path,
520 own: root.own,
521 }
522 })
523 .collect()
524 }
525
526 pub fn worktree_dirs_in(&self, dir: &Path) -> Vec<PathBuf> {
529 self.layout
530 .worktrees_dir_names()
531 .map(|name| dir.join(name))
532 .collect()
533 }
534
535 pub fn names_configuration(&self, text: &str) -> bool {
552 let lowered = super::fold_case(text);
553 let components: Vec<&str> = lowered.split('/').collect();
554 let name_in = |component: &str| {
556 component
557 .split(|c: char| !(c.is_alphanumeric() || "._-".contains(c)))
558 .next()
559 .unwrap_or_default()
560 .to_string()
561 };
562 let opens_dir = |rest: &[&str], dir: &str| {
563 let dir: Vec<&str> = dir.split('/').collect();
564 let Some((last, above)) = dir.split_last() else {
565 return false;
566 };
567 rest.len() >= dir.len()
568 && above.iter().zip(rest).all(|(d, c)| d == c)
569 && name_in(rest[above.len()]) == *last
570 };
571 let working_at = |at: usize| {
572 components
573 .get(at)
574 .is_some_and(|next| self.is_engine_working_entry(&name_in(next)))
575 };
576 let working_below = |i: usize| {
577 (self.state_root_ends_at(&components[..=i]) && working_at(i + 1))
578 || (components.get(i + 1) == Some(&entry::STATE) && working_at(i + 2))
579 };
580 lowered.contains('/')
581 && components.iter().enumerate().any(|(i, component)| {
582 let config_root = *component == REPOSITORY_CONFIG_DIR
583 || self
584 .layout
585 .config_roots()
586 .any(|root| *component == root.name && !(root.own && working_below(i)));
587 config_root
588 || PROJECT_ENGINE_CONFIG_DIRS
589 .iter()
590 .any(|dir| opens_dir(&components[i..], dir))
591 })
592 }
593
594 fn state_root_ends_at(&self, spelled: &[&str]) -> bool {
599 let name_char = |c: char| c.is_alphanumeric() || "._-".contains(c);
600 let ends_with = |root: &[String], before_ok: &dyn Fn(&str) -> bool| {
601 let Some(at) = spelled.len().checked_sub(root.len() + 1) else {
602 return false;
603 };
604 !root.is_empty()
605 && before_ok(spelled[at])
606 && spelled[at + 1..].iter().zip(root).all(|(s, r)| s == r)
607 };
608 let from_home = |before: &str| {
609 ["~", "$home", "${home}"].iter().any(|home| {
610 before
611 .strip_suffix(home)
612 .is_some_and(|rest| !rest.ends_with(name_char))
613 })
614 };
615 self.state_root.iter().any(|root| {
616 root.lowered
617 .iter()
618 .any(|spelling| ends_with(spelling, &|before| !before.ends_with(name_char)))
619 || root
620 .below_home
621 .iter()
622 .any(|spelling| ends_with(spelling, &from_home))
623 })
624 }
625
626 pub fn is_engine_settings_file(&self, abs: &Path) -> bool {
631 let components = lowered_components(abs);
632 let Some((name, dirs)) = components.split_last() else {
633 return false;
634 };
635 ENGINE_CONFIG_FILES.contains(&name.as_str())
636 && dirs
637 .iter()
638 .any(|d| self.layout.config_roots().any(|root| *d == root.name))
639 }
640
641 pub fn is_engine_working_entry(&self, name: &str) -> bool {
647 is_working_entry(name)
648 }
649
650 pub fn state_working_dirs(&self) -> Vec<PathBuf> {
653 self.state_root
654 .iter()
655 .flat_map(|root| STATE_ROOT_WORKING_DIRS.iter().map(|d| root.given.join(d)))
656 .collect()
657 }
658
659 pub fn readable_state_root(&self) -> Option<PathBuf> {
661 self.state_root().map(Path::to_path_buf)
662 }
663
664 pub fn session_tmp_dir(&self, session_id: &str) -> Option<PathBuf> {
666 self.state_root().map(|root| {
667 root.join(STATE_ROOT_SESSION_TMP)
668 .join(session_dir_name(session_id))
669 })
670 }
671
672 pub fn session_scratch_dir(&self, session_id: &str) -> Option<PathBuf> {
674 self.state_root()
675 .map(|root| session_scratch_dir(root, session_id))
676 }
677
678 pub fn scene_dirs(&self) -> Vec<PathBuf> {
682 self.state_root
683 .as_ref()
684 .map(|root| scene_dirs_in(&root.real))
685 .unwrap_or_default()
686 .into_iter()
687 .map(|scene| scene.path)
688 .collect()
689 }
690
691 pub fn prompt_files(&self) -> PromptFiles {
693 PromptFiles {
694 paths: self.clone(),
695 root: self.project.clone(),
696 }
697 }
698
699 pub fn prompt_files_within(&self, dir: &Path) -> PromptFiles {
701 PromptFiles {
702 paths: self.clone(),
703 root: Some(Spellings::of(dir)),
704 }
705 }
706}
707
708pub fn session_scratch_dir(state_root: &Path, session_id: &str) -> PathBuf {
712 state_root
713 .join(STATE_ROOT_SCRATCHPAD)
714 .join(entry::SESSIONS)
715 .join(session_dir_name(session_id))
716}
717
718pub fn tool_results_dir(dir: &Path, session_id: &str) -> PathBuf {
722 dir.join(entry::TOOL_RESULTS)
723 .join(session_dir_name(session_id))
724}
725
726fn session_dir_name(session_id: &str) -> String {
727 session_id
728 .chars()
729 .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
730 .collect()
731}
732
733#[derive(Debug, Clone)]
743pub struct PromptFiles {
744 paths: SensitivePaths,
745 root: Option<Spellings>,
746}
747
748impl PromptFiles {
749 pub fn unscoped() -> Self {
752 SensitivePaths::default().prompt_files()
753 }
754
755 pub fn for_project(paths: &ConfigPaths) -> Self {
759 SensitivePaths::for_paths(paths).prompt_files()
760 }
761
762 pub fn resolve(&self, path: &Path) -> std::io::Result<PathBuf> {
765 let resolved = std::fs::canonicalize(path)?;
766 self.admit(path, &resolved)
767 .map_err(|why| std::io::Error::new(std::io::ErrorKind::PermissionDenied, why))?;
768 Ok(resolved)
769 }
770
771 pub fn read_to_string(&self, path: &Path) -> std::io::Result<String> {
773 std::fs::read_to_string(self.resolve(path)?)
774 }
775
776 pub fn admit(&self, path: &Path, resolved: &Path) -> Result<(), String> {
779 let spelled = absolute_lexically(path);
780 let refusal = if self.paths.is_credential(&spelled) || self.paths.is_credential(resolved) {
781 Some("is a credential location".to_string())
782 } else {
783 self.root.as_ref().and_then(|root| {
784 let user_owned = self
785 .paths
786 .state_root
787 .as_ref()
788 .is_some_and(|s| s.spell(&spelled));
789 (root.spell(&spelled) && !user_owned && !resolved.starts_with(&root.real))
790 .then(|| format!("is outside {}", root.given.display()))
791 })
792 };
793 match refusal {
794 None => Ok(()),
795 Some(why) => {
796 let message = format!(
797 "not reading {} for the model: it resolves to {}, which {why}",
798 path.display(),
799 resolved.display()
800 );
801 tracing::warn!("{message}");
802 Err(message)
803 }
804 }
805 }
806}
807
808fn is_working_entry(name: &str) -> bool {
809 STATE_ROOT_WORKING_DIRS.contains(&name)
810}
811
812fn linked_scenes_of(root: &Spellings) -> Vec<PathBuf> {
814 scene_dirs_in(&root.real)
815 .into_iter()
816 .filter(|scene| scene.resolved != scene.path)
817 .map(|scene| scene.resolved)
818 .collect()
819}
820
821struct SceneDir {
824 path: PathBuf,
825 resolved: PathBuf,
826}
827
828fn scene_dirs_in(base: &Path) -> Vec<SceneDir> {
831 let Ok(entries) = std::fs::read_dir(base.join(entry::SCENES)) else {
832 return Vec::new();
833 };
834 let mut dirs: Vec<SceneDir> = entries
835 .flatten()
836 .map(|e| e.path())
837 .filter(|path| path.is_dir())
838 .map(|path| SceneDir {
839 resolved: path.canonicalize().unwrap_or_else(|_| path.clone()),
840 path,
841 })
842 .collect();
843 dirs.sort_by(|a, b| a.path.cmp(&b.path));
844 dirs
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850 use crate::paths::layout::test_layouts;
851 use crate::paths::{ENGINE_CONFIG_DIRS, STATE_RESERVED_NAMES};
852
853 fn sensitive(state_root: &str) -> SensitivePaths {
854 SensitivePaths::new(Some(Path::new(state_root)), None, Layout::default())
855 }
856
857 #[test]
858 fn the_known_state_roots_are_the_engines_and_agixds() {
859 let Some(home) = crate::paths::home_dir() else {
860 return;
861 };
862 assert_eq!(known_state_roots(&Layout::default()), [home.join(".agix")]);
863 let foo = Layout::default().with_engine("foo").unwrap();
864 assert_eq!(
865 known_state_roots(&foo),
866 [home.join(".foo"), home.join(".agix")]
867 );
868 }
869
870 fn in_layout(layout: &Layout) -> SensitivePaths {
871 SensitivePaths::new(Some(Path::new("/state/home")), None, layout.clone())
872 }
873
874 fn own(p: &str, layout: &Layout) -> String {
876 p.replace("{own}", layout.project_dir_name())
877 .replace("{wk}", layout.worktrees_dir_name())
878 }
879
880 #[test]
881 fn saved_tool_results_are_outside_what_sandboxed_commands_may_write() {
882 let root = Path::new("/repo/.agix");
883 let saved = tool_results_dir(root, "s");
884 assert!(
885 !sensitive("/repo/.agix")
886 .state_working_dirs()
887 .iter()
888 .any(|w| saved.starts_with(w)),
889 "{}",
890 saved.display()
891 );
892 }
893
894 #[test]
895 fn another_instances_state_root_holds_credentials_as_the_own_one_does() {
896 let paths = sensitive("/state/codix").with_foreign_state_roots(&[
897 PathBuf::from("/home/u/.agix"),
898 PathBuf::from("/state/codix"),
899 ]);
900 assert_eq!(
901 paths.foreign_state_roots(),
902 [PathBuf::from("/home/u/.agix")]
903 );
904 for p in [
905 "/home/u/.agix/settings.json",
906 "/home/u/.agix/Settings.local.JSON",
907 "/home/u/.agix/scenes/code/settings.json",
908 "/home/u/.agix/mcp/oauth/x.json",
909 "/home/u/.agix/daemon/auth/desktop.token",
910 "/state/codix/settings.json",
911 ] {
912 assert!(paths.is_credential(Path::new(p)), "{p}");
913 }
914 for p in [
915 "/home/u/.agix/skills/s/SKILL.md",
916 "/home/u/.agix/daemon/instances.d/x.json",
917 ] {
918 assert!(!paths.is_credential(Path::new(p)), "{p}");
919 }
920 let bases: Vec<PathBuf> = paths
921 .credential_locations(&[])
922 .into_iter()
923 .map(|l| l.base)
924 .collect();
925 assert!(bases.contains(&PathBuf::from("/home/u/.agix")), "{bases:?}");
926 assert!(!sensitive("/state/codix").is_credential(Path::new("/home/u/.agix/settings.json")));
927 }
928
929 #[test]
930 fn credentials_are_the_state_roots_keys_and_tokens_and_a_projects_keys() {
931 let paths = sensitive("/state/home");
932 for p in [
933 "/state/home/settings.json",
934 "/state/home/settings.local.json",
935 "/state/home/.settings.json.tmp-1",
936 "/state/home/mcp.local.json",
937 "/state/home/Settings.JSON",
938 "/state/home/mcp/oauth",
939 "/state/home/mcp/oauth/x.json",
940 "/state/home/scenes/code/settings.json",
941 "/state/home/scenes/code/mcp/oauth/x.json",
942 "/state/home/daemon/auth/desktop.token",
943 "/repo/.agix/settings.local.json",
944 "/repo/.agix/mcp.local.json",
945 "/home/u/.ssh/id_rsa",
946 "/home/u/.aws",
947 ] {
948 assert!(paths.is_credential(Path::new(p)), "{p}");
949 }
950 for p in [
951 "/state/home",
952 "/state/home/mcp",
953 "/state/home/mcp.json",
954 "/state/home/skills/x/SKILL.md",
955 "/state/home/memory/settings.json",
956 "/state/home/scenes/code/scene.json",
957 "/state/home/scenes/settings.json/x",
958 "/state/home/daemon/instances.d/x.json",
959 "/state/homework/settings.json",
960 "/repo/.agix/settings.json",
961 "/repo/settings.local.json",
962 "/repo/.github/x",
963 ] {
964 assert!(!paths.is_credential(Path::new(p)), "{p}");
965 }
966 assert!(!SensitivePaths::default().is_credential(Path::new("/state/home/settings.json")));
967
968 for layout in test_layouts() {
969 let paths = in_layout(&layout);
970 for p in [
971 "/repo/{own}/settings.local.json",
972 "/repo/{own}/mcp.local.json",
973 "/repo/.agix/settings.local.json",
974 ] {
975 assert!(paths.is_credential(Path::new(&own(p, &layout))), "{p}");
976 }
977 for p in [
978 "/repo/{own}/settings.json",
979 "/repo/.claude/settings.local.json",
980 ] {
981 assert!(!paths.is_credential(Path::new(&own(p, &layout))), "{p}");
982 }
983 }
984 assert!(!sensitive("/state/home").is_credential(Path::new("/repo/.codix/mcp.local.json")));
985 }
986
987 fn example(credential: &Credential, layout: &Layout) -> (String, String) {
990 let name = match credential.secret {
991 Secret::KeyFiles(KeyFileNames::StateRoot) => "settings.json",
992 Secret::KeyFiles(KeyFileNames::Project) => "settings.local.json",
993 Secret::Tree(path) | Secret::DirName(path) => path,
994 };
995 match credential.scope {
996 Scope::StateRoot => (format!("/state/home/{name}"), format!("/elsewhere/{name}")),
997 Scope::EachSceneDir => (
998 format!("/state/home/scenes/triage/{name}"),
999 format!("/state/home/scenes/{name}"),
1000 ),
1001 Scope::AnyEngineDir => (
1002 format!("/repo/{}/{name}", layout.project_dir_name()),
1003 format!("/repo/{name}"),
1004 ),
1005 Scope::Anywhere => (format!("/home/u/{name}/x"), format!("/home/u/{name}-not/x")),
1006 }
1007 }
1008
1009 #[test]
1010 fn every_credential_is_recognized_and_every_scope_has_a_near_miss() {
1011 let mut scopes = Vec::new();
1012 for layout in test_layouts() {
1013 let paths = in_layout(&layout);
1014 for credential in CREDENTIALS {
1015 let (hit, miss) = example(credential, &layout);
1016 assert!(
1017 paths.is_credential(Path::new(&hit)),
1018 "{credential:?}: {hit}"
1019 );
1020 assert!(
1021 !paths.is_credential(Path::new(&miss)),
1022 "{credential:?}: {miss}"
1023 );
1024 if !scopes.contains(&credential.scope) {
1025 scopes.push(credential.scope);
1026 }
1027 }
1028 }
1029 for scope in [
1030 Scope::StateRoot,
1031 Scope::EachSceneDir,
1032 Scope::AnyEngineDir,
1033 Scope::Anywhere,
1034 ] {
1035 assert!(scopes.contains(&scope), "no credential in {scope:?}");
1036 }
1037 }
1038
1039 #[test]
1040 fn a_read_denial_is_a_credential_unless_a_more_specific_allow_lifts_it() {
1041 let paths = SensitivePaths::default().with_read_denials(
1042 &[PathBuf::from("/h/.config/gh"), PathBuf::from("/h/.npmrc")],
1043 &[PathBuf::from("/h/.config/gh/public"), PathBuf::from("/h")],
1044 );
1045 assert!(paths.is_credential(Path::new("/h/.config/gh/hosts.yml")));
1046 assert!(!paths.is_credential(Path::new("/h/.config/gh/public/x")));
1047 assert!(paths.is_credential(Path::new("/h/.npmrc")));
1048 assert!(!paths.is_credential(Path::new("/h/notes")));
1049 }
1050
1051 #[test]
1052 fn a_backend_gets_every_credential_but_the_ones_it_reaches_through_deny_read() {
1053 let paths = sensitive("/state/home");
1054 let agix = [PathBuf::from("/repo/.agix")];
1055 let located = paths.credential_locations(&agix);
1056 let expected = CREDENTIALS
1057 .iter()
1058 .filter(|c| c.scope != Scope::Anywhere)
1059 .count();
1060 assert_eq!(located.len(), expected, "{located:?}");
1061 assert!(located
1062 .iter()
1063 .all(|l| l.base == Path::new("/state/home") || l.base == Path::new("/repo/.agix")));
1064 assert!(SensitivePaths::default()
1065 .credential_locations(&[])
1066 .is_empty());
1067 }
1068
1069 #[cfg(unix)]
1073 #[test]
1074 fn a_scene_linked_in_from_elsewhere_has_its_key_files_located() {
1075 let dir = tempfile::tempdir().unwrap();
1076 let root = dir.path().join("state");
1077 let elsewhere = dir.path().join("dotfiles/scene");
1078 std::fs::create_dir_all(root.join("scenes")).unwrap();
1079 std::fs::create_dir_all(&elsewhere).unwrap();
1080 std::fs::write(elsewhere.join("settings.json"), "").unwrap();
1081 std::os::unix::fs::symlink(&elsewhere, root.join("scenes/linked")).unwrap();
1082 let root = root.canonicalize().unwrap();
1083 let located =
1084 SensitivePaths::new(Some(&root), None, Layout::default()).credential_locations(&[]);
1085 let keys = located
1086 .iter()
1087 .find(|l| l.under_each_scene && matches!(l.secret, Secret::KeyFiles(_)))
1088 .unwrap();
1089 assert!(
1090 keys.existing()
1091 .contains(&root.join("scenes/linked/settings.json")),
1092 "{:?}",
1093 keys.existing()
1094 );
1095 assert_eq!(
1096 keys.linked_dirs_resolved(),
1097 vec![elsewhere.canonicalize().unwrap()]
1098 );
1099 }
1100
1101 #[cfg(unix)]
1102 #[test]
1103 fn a_linked_scenes_secrets_are_credentials_under_their_real_path() {
1104 let dir = tempfile::tempdir().unwrap();
1105 let root = dir.path().join("state");
1106 let elsewhere = dir.path().join("dotfiles/scene");
1107 std::fs::create_dir_all(root.join("scenes")).unwrap();
1108 std::fs::create_dir_all(&elsewhere).unwrap();
1109 std::os::unix::fs::symlink(&elsewhere, root.join("scenes/linked")).unwrap();
1110 let paths = SensitivePaths::new(Some(&root), None, Layout::default());
1111 let real = elsewhere.canonicalize().unwrap();
1112 assert_eq!(
1113 paths.linked_scene_dirs_resolved(),
1114 std::slice::from_ref(&real)
1115 );
1116 assert!(paths.is_credential(&real.join("settings.json")));
1117 assert!(paths.is_credential(&real.join("mcp/oauth/token.json")));
1118 assert!(paths.is_credential(&root.join("scenes/linked/settings.json")));
1119 assert!(!paths.is_credential(&real.join("scene.json")));
1120 assert!(!paths.is_credential(&real.parent().unwrap().join("settings.json")));
1121 }
1122
1123 #[test]
1124 fn the_existing_secrets_of_a_location_are_found_on_disk() {
1125 let dir = tempfile::tempdir().unwrap();
1126 let root = dir.path().canonicalize().unwrap();
1127 for scene in ["code", "triage"] {
1128 std::fs::create_dir_all(root.join("scenes").join(scene).join("mcp/oauth")).unwrap();
1129 std::fs::write(root.join("scenes").join(scene).join("settings.json"), "").unwrap();
1130 }
1131 std::fs::write(root.join("scenes/code/scene.json"), "").unwrap();
1132 let located =
1133 SensitivePaths::new(Some(&root), None, Layout::default()).credential_locations(&[]);
1134 let keys = located
1135 .iter()
1136 .find(|l| l.under_each_scene && matches!(l.secret, Secret::KeyFiles(_)))
1137 .unwrap();
1138 assert_eq!(
1139 keys.existing(),
1140 vec![
1141 root.join("scenes/code/settings.json"),
1142 root.join("scenes/triage/settings.json")
1143 ]
1144 );
1145 let daemon = located
1146 .iter()
1147 .find(|l| l.secret == Secret::Tree("daemon/auth"))
1148 .unwrap();
1149 assert!(daemon.existing().is_empty());
1150 }
1151
1152 #[test]
1153 fn the_roots_derive_from_the_state_root() {
1154 let paths = sensitive("/state/home");
1155 assert_eq!(
1156 paths.state_working_dirs(),
1157 vec![
1158 PathBuf::from("/state/home/scratchpad"),
1159 PathBuf::from("/state/home/memory")
1160 ]
1161 );
1162 assert_eq!(
1163 paths.session_tmp_dir("s-1/../x"),
1164 Some(PathBuf::from("/state/home/tmp/s-1x"))
1165 );
1166 assert_eq!(
1167 paths.session_scratch_dir("s-1/../x"),
1168 Some(PathBuf::from("/state/home/scratchpad/sessions/s-1x"))
1169 );
1170 assert_eq!(
1171 paths.readable_state_root(),
1172 Some(PathBuf::from("/state/home"))
1173 );
1174 let none = SensitivePaths::default();
1175 assert!(none.state_working_dirs().is_empty());
1176 assert_eq!(none.session_tmp_dir("s"), None);
1177 }
1178
1179 #[test]
1182 fn credential_dirs_are_whole_components_anywhere() {
1183 let paths = SensitivePaths::default();
1184 for p in [
1185 "~/.ssh/id_rsa",
1186 "cat ~/.ssh/id_rsa",
1187 "/home/u/.ssh/config",
1188 "~/.aws/credentials",
1189 "/Users/me/.gnupg/secring.gpg",
1190 "/repo/.github/workflows/../.ssh/id_rsa",
1191 "/a/b/c/d/e/f/.aws/credentials",
1192 ] {
1193 assert!(paths.is_credential(Path::new(p)), "{p}");
1194 }
1195 for p in ["/home/u/.sshx/config", "/repo/.github/x", "/repo/.awsome"] {
1196 assert!(!paths.is_credential(Path::new(p)), "{p}");
1197 }
1198 }
1199
1200 #[test]
1203 fn config_dirs_require_confirmation() {
1204 for layout in test_layouts() {
1205 let paths = in_layout(&layout);
1206 for p in [
1207 "repo/.git/config",
1208 "/Users/me/{own}/settings.json",
1209 "/Users/me/.agix/settings.json",
1210 "/a/b/.claude/settings.local.json",
1211 ] {
1212 assert!(paths.names_configuration(&own(p, &layout)), "{p}");
1213 }
1214 assert!(!paths.names_configuration("/repo/.github/workflows/ci.yml"));
1215 assert!(!paths.names_configuration("/repo/src/main.rs"));
1216 }
1217 assert!(!sensitive("/s").names_configuration("/repo/.codix/settings.json"));
1218 }
1219
1220 #[test]
1221 fn a_projects_skills_are_configuration() {
1222 for layout in test_layouts() {
1223 let paths = in_layout(&layout);
1224 for p in [
1225 "/repo/.agents/skills/x/SKILL.md",
1226 "/repo/.agents/skills",
1227 ".agents/skills;",
1228 "/repo/.Agents/Skills/x/SKILL.md",
1229 ] {
1230 assert!(paths.names_configuration(p), "{p}");
1231 }
1232 for p in [
1233 "/repo/.agents/notes.md",
1234 "/repo/.agents/skills2/x",
1235 "/repo/skills/x",
1236 "/repo/AGENTS.md",
1237 ] {
1238 assert!(!paths.names_configuration(p), "{p}");
1239 }
1240 }
1241 }
1242
1243 #[test]
1244 fn names_a_case_insensitive_filesystem_folds_onto_configuration_are_configuration() {
1245 let ops = in_layout(&Layout::new(".ops").unwrap());
1246 for p in [
1247 "/repo/.agent\u{17F}/\u{17F}kills/x/SKILL.md",
1248 "/repo/.agents/\u{17F}kills/x/SKILL.md",
1249 "/repo/.op\u{17F}/hooks/h.sh",
1250 ] {
1251 assert!(ops.names_configuration(p), "{p}");
1252 }
1253 for p in [
1254 "/repo/.op\u{17F}/\u{17F}ettings.json",
1255 "/repo/.claude/\u{17F}ettings.j\u{17F}on",
1256 "/repo/.agix/\u{17F}etting\u{17F}.json",
1257 ] {
1258 assert!(ops.is_engine_settings_file(Path::new(p)), "{p}");
1259 }
1260 assert!(Layout::new(".ops")
1261 .unwrap()
1262 .is_own_dir_component(".op\u{17F}"));
1263 assert!(!ops.names_configuration("/repo/stra\u{DF}e/x.md"));
1264 assert_eq!(
1265 super::super::fold_case("Gi\u{FB06}/CON\u{FB01}G/\u{1E9E}"),
1266 "gist/config/ss"
1267 );
1268 }
1269
1270 #[test]
1271 fn the_agents_working_space_in_its_own_directory_is_not_configuration() {
1272 for layout in test_layouts() {
1273 let paths = in_layout(&layout);
1274 for p in [
1275 "/repo/{own}/state/scratchpad/cases.txt",
1276 "/repo/{own}/state/memory/MEMORY.md",
1277 "/repo/{wk}/a/{own}/state/scratchpad/x",
1278 "cd /repo\nS=/repo/{own}/state/scratchpad\nmkdir -p \"$S\"",
1279 "printf x > \"$d/{own}/state/scratchpad\"",
1280 "/repo/{wk}/feat-a/feature.txt",
1281 "cd /repo/{wk}/feat-a && git add -A",
1282 ] {
1283 assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
1284 }
1285 for p in [
1286 "/repo/{own}/scratchpad/cases.txt",
1287 "/repo/{own}/memory/MEMORY.md",
1288 "/Users/me/{own}/memory/MEMORY.md",
1289 "/repo/{own}/state",
1290 "/repo/{own}/state/",
1291 "/repo/{own}/state/notes.md",
1292 "/repo/{own}/state/scratchpad.md",
1293 "/repo/{own}/state/tool-results/s/r.txt",
1294 "/repo/{own}/state/telemetry/s.jsonl",
1295 "/repo/{own}/state/teams/t/team.json",
1296 "/repo/{own}/state/history/s/transcript.jsonl",
1297 "/repo/{own}/state/.imported.json",
1298 "/repo/{own}/state/codix/x",
1299 "/repo/{own}/state/agix/x",
1300 "echo x > \"$d/{own}/state\";x/scratchpad",
1301 "/repo/{own}/agents/reviewer.md",
1302 "/repo/{own}/scratchpad.md",
1303 "/repo/{own}/worktrees/feat-a/feature.txt",
1304 "/repo/{wk}/feat-a/{own}/agents/reviewer.md",
1305 "/repo/{wk}/feat-a/.agix/agents/reviewer.md",
1306 "/repo/{wk}/feat-a/.claude/settings.json",
1307 "/repo/{wk}/feat-a/.git",
1308 "/repo/.claude/scratchpad/x",
1309 ] {
1310 assert!(paths.names_configuration(&own(p, &layout)), "{p}");
1311 }
1312 }
1313 let codix = in_layout(&Layout::new(".codix").unwrap());
1314 for p in [
1315 "/repo/.agix/scratchpad/x",
1316 "/repo/.agix/state/scratchpad/x",
1317 "/repo/.agix/worktrees/a/f.txt",
1318 ] {
1319 assert!(
1320 codix.names_configuration(p),
1321 "a foreign .agix has no working space: {p}"
1322 );
1323 }
1324 }
1325
1326 #[test]
1327 fn the_state_roots_working_space_is_directly_in_it() {
1328 for layout in test_layouts() {
1329 let root = own("/Users/me/{own}", &layout);
1330 let paths = SensitivePaths::new(Some(Path::new(&root)), None, layout.clone());
1331 for p in [
1332 "/Users/me/{own}/memory/MEMORY.md",
1333 "/Users/me/{own}/scratchpad/sessions/s/x",
1334 "/Users/me/{own}/state/scratchpad/x",
1335 "S=/Users/me/{own}/scratchpad/x",
1336 "echo x > \"/Users/ME/{own}/memory/a.md\"",
1337 ] {
1338 assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
1339 }
1340 for p in [
1341 "/Users/me/{own}/settings.json",
1342 "/Users/me/{own}/tool-results/s/x",
1343 "/Users/you/{own}/memory/MEMORY.md",
1344 "/x/Users/me/{own}/memory/MEMORY.md",
1345 "x/Users/me/{own}/memory/MEMORY.md",
1346 "/repo/{own}/memory/MEMORY.md",
1347 ] {
1348 assert!(paths.names_configuration(&own(p, &layout)), "{p}");
1349 }
1350 }
1351 }
1352
1353 #[test]
1354 fn the_state_roots_working_space_spelled_from_home_is_not_configuration() {
1355 for layout in test_layouts() {
1356 let root = own("/Users/me/{own}", &layout);
1357 let paths = SensitivePaths {
1358 state_root: Some(Spellings::of_with_home(
1359 Path::new(&root),
1360 Some(Path::new("/Users/me")),
1361 )),
1362 ..SensitivePaths::new(None, None, layout.clone())
1363 };
1364 for p in [
1365 "cat ~/{own}/memory/MEMORY.md",
1366 "echo x > $HOME/{own}/memory/a.md",
1367 "ls \"${HOME}/{own}/scratchpad/sessions\"",
1368 "S=~/{own}/scratchpad/x",
1369 ] {
1370 assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
1371 }
1372 for p in [
1373 "cat ~/{own}/settings.json",
1374 "cat ~/{own}/tool-results/s/x",
1375 "cat x~/{own}/memory/MEMORY.md",
1376 "cat $HOMEX/{own}/memory/MEMORY.md",
1377 "cat ~/other/{own}/memory/MEMORY.md",
1378 ] {
1379 assert!(paths.names_configuration(&own(p, &layout)), "{p}");
1380 }
1381 }
1382 }
1383
1384 #[test]
1387 fn only_scratchpad_and_memory_in_state_are_writable() {
1388 let codix = Layout::new(".codix")
1389 .unwrap()
1390 .with_product_name("Codix")
1391 .unwrap();
1392 let roots = SensitivePaths::new(None, None, codix.clone())
1393 .config_roots_in(Path::new("/nowhere/repo"));
1394 let own = roots.iter().find(|r| r.own).unwrap();
1395 assert_eq!(own.state_dir(), Path::new("/nowhere/repo/.codix/state"));
1396 assert_eq!(
1397 own.working_entries(),
1398 [
1399 PathBuf::from("/nowhere/repo/.codix/state/scratchpad"),
1400 PathBuf::from("/nowhere/repo/.codix/state/memory")
1401 ]
1402 );
1403 let mut writable: Vec<&str> = STATE_RESERVED_NAMES
1404 .iter()
1405 .copied()
1406 .chain([entry::IMPORTED_MARKER, entry::STATE, "codix", "notes.md"])
1407 .filter(|name| own.writable_state_entry(name))
1408 .collect();
1409 writable.sort_unstable();
1410 assert_eq!(writable, [entry::MEMORY, entry::SCRATCHPAD]);
1411 for foreign in roots.iter().filter(|r| !r.own) {
1412 assert!(foreign.working_entries().is_empty(), "{:?}", foreign.path);
1413 assert!(STATE_ROOT_WORKING_DIRS
1414 .iter()
1415 .all(|name| !foreign.writable_state_entry(name)));
1416 }
1417 }
1418
1419 #[test]
1420 fn what_the_gate_treats_as_working_space_the_sandbox_leaves_writable() {
1421 let paths = SensitivePaths::default();
1422 for name in STATE_ROOT_WORKING_DIRS {
1423 assert!(paths.is_engine_working_entry(name), "{name}");
1424 assert!(
1425 !ENGINE_CONFIG_DIRS.contains(name) && !ENGINE_CONFIG_FILES.contains(name),
1426 "{name}"
1427 );
1428 }
1429 }
1430
1431 #[test]
1432 fn engine_settings_files_are_known_by_name_under_a_config_root() {
1433 for layout in test_layouts() {
1434 let paths = in_layout(&layout);
1435 for p in [
1436 "/repo/{own}/settings.json",
1437 "/repo/.agix/settings.json",
1438 "/repo/.claude/settings.local.json",
1439 "/repo/{wk}/a/{own}/mcp.local.json",
1440 "/repo/{own}/agents/settings.json",
1441 "/repo/{OWN}/Settings.json",
1442 "/repo/.Agix/SETTINGS.LOCAL.JSON",
1443 "/repo/.CLAUDE/settings.json",
1444 ] {
1445 let p = &p.replace("{OWN}", &layout.project_dir_name().to_uppercase());
1446 assert!(
1447 paths.is_engine_settings_file(Path::new(&own(p, &layout))),
1448 "{p}"
1449 );
1450 }
1451 for p in [
1452 "/repo/settings.json",
1453 "/repo/{own}/scene.json",
1454 "/repo/{own}",
1455 ] {
1456 assert!(
1457 !paths.is_engine_settings_file(Path::new(&own(p, &layout))),
1458 "{p}"
1459 );
1460 }
1461 }
1462 assert!(!sensitive("/s").is_engine_settings_file(Path::new("/repo/.codix/settings.json")));
1463 }
1464
1465 #[test]
1466 fn the_sandbox_is_told_the_engine_directories_of_a_project() {
1467 let codix = Layout::new(".codix")
1468 .unwrap()
1469 .with_worktrees_dir(".trees")
1470 .unwrap();
1471 let paths = SensitivePaths::new(None, None, codix.clone());
1472 let at: Vec<(PathBuf, bool)> = paths
1473 .config_roots_in(Path::new("/nowhere/repo"))
1474 .into_iter()
1475 .map(|r| (r.path, r.own))
1476 .collect();
1477 assert_eq!(
1478 at,
1479 [
1480 (PathBuf::from("/nowhere/repo/.codix"), true),
1481 (PathBuf::from("/nowhere/repo/.agix"), false),
1482 (PathBuf::from("/nowhere/repo/.claude"), false)
1483 ]
1484 );
1485 assert_eq!(
1486 paths.engine_dirs_in(Path::new("/nowhere/repo")),
1487 [
1488 PathBuf::from("/nowhere/repo/.codix"),
1489 PathBuf::from("/nowhere/repo/.agix")
1490 ]
1491 );
1492 assert_eq!(
1493 paths.worktree_dirs_in(Path::new("/nowhere/repo")),
1494 [
1495 PathBuf::from("/nowhere/repo/.trees"),
1496 PathBuf::from("/nowhere/repo/.wkts")
1497 ]
1498 );
1499 assert_eq!(
1500 SensitivePaths::default().engine_dirs_in(Path::new("/nowhere/repo")),
1501 [PathBuf::from("/nowhere/repo/.agix")]
1502 );
1503 assert_eq!(
1504 SensitivePaths::default().worktree_dirs_in(Path::new("/nowhere/repo")),
1505 [PathBuf::from("/nowhere/repo/.wkts")]
1506 );
1507 }
1508
1509 #[test]
1510 fn a_prompt_file_is_neither_a_credential_nor_a_link_out_of_the_root() {
1511 use std::os::unix::fs::symlink;
1512 let tmp = tempfile::tempdir().unwrap();
1513 let (state, project, elsewhere) = (
1514 tmp.path().join("state"),
1515 tmp.path().join("project"),
1516 tmp.path().join("elsewhere"),
1517 );
1518 for dir in [
1519 &state,
1520 &project.join(".agix"),
1521 &project.join("docs"),
1522 &elsewhere,
1523 ] {
1524 std::fs::create_dir_all(dir).unwrap();
1525 }
1526 std::fs::write(state.join("settings.json"), "state key").unwrap();
1527 std::fs::write(project.join(".agix/settings.local.json"), "project key").unwrap();
1528 std::fs::write(project.join("docs/guide.md"), "guide").unwrap();
1529 std::fs::write(elsewhere.join("notes.md"), "notes").unwrap();
1530 symlink("docs/guide.md", project.join("AGENTS.md")).unwrap();
1531 symlink(".agix/settings.local.json", project.join("KEY.md")).unwrap();
1532 symlink("../elsewhere/notes.md", project.join("OUT.md")).unwrap();
1533 symlink(
1534 "../project/.agix/settings.local.json",
1535 elsewhere.join("key.md"),
1536 )
1537 .unwrap();
1538 symlink("../state/settings.json", elsewhere.join("state.md")).unwrap();
1539
1540 let files =
1541 SensitivePaths::new(Some(&state), Some(&project), Layout::default()).prompt_files();
1542 let read = |p: PathBuf| files.read_to_string(&p).map_err(|e| e.kind());
1543 let denied = Err(std::io::ErrorKind::PermissionDenied);
1544 assert_eq!(read(project.join("AGENTS.md")), Ok("guide".into()));
1545 assert_eq!(read(project.join("KEY.md")), denied);
1546 assert_eq!(read(project.join(".agix/settings.local.json")), denied);
1547 assert_eq!(read(project.join("OUT.md")), denied);
1548 assert_eq!(read(elsewhere.join("notes.md")), Ok("notes".into()));
1549 assert_eq!(read(elsewhere.join("key.md")), denied);
1550 assert_eq!(read(elsewhere.join("state.md")), denied);
1551 assert_eq!(
1552 read(project.join("missing.md")),
1553 Err(std::io::ErrorKind::NotFound)
1554 );
1555
1556 let nested_state = project.join("home-state");
1557 std::fs::create_dir_all(&nested_state).unwrap();
1558 symlink("../../elsewhere/notes.md", nested_state.join("skill.md")).unwrap();
1559 let files = SensitivePaths::new(Some(&nested_state), None, Layout::default())
1560 .prompt_files_within(&project);
1561 assert_eq!(
1562 files
1563 .read_to_string(&nested_state.join("skill.md"))
1564 .map_err(|e| e.kind()),
1565 Ok("notes".into()),
1566 "the state root's files are the user's, wherever it sits"
1567 );
1568 }
1569}