use std::path::{Path, PathBuf};
use anyhow::Result;
use crate::domain::{FileClassification, LanguageId};
#[derive(Debug, Clone)]
pub struct DiscoveredFile {
pub relative_path: String,
pub absolute_path: PathBuf,
pub language: LanguageId,
pub classification: FileClassification,
}
#[derive(Debug, Clone)]
pub struct DiscoveredEntry {
pub relative_path: String,
pub absolute_path: PathBuf,
pub file_size: u64,
pub language: Option<LanguageId>,
pub classification: FileClassification,
}
const MAX_INDEX_FILES_ENV: &str = "SYMFORGE_MAX_INDEX_FILES";
const MAX_INDEX_BYTES_ENV: &str = "SYMFORGE_MAX_INDEX_BYTES";
const DEFAULT_MAX_INDEX_FILES: u64 = 200_000;
const DEFAULT_MAX_INDEX_BYTES: u64 = 16 * 1024 * 1024 * 1024;
#[derive(Debug, Clone, Copy)]
pub struct DiscoveryLimits {
pub max_files: u64,
pub max_bytes: u64,
}
impl DiscoveryLimits {
pub fn from_env() -> Self {
let max_files = parse_positive_env(MAX_INDEX_FILES_ENV).unwrap_or(DEFAULT_MAX_INDEX_FILES);
let max_bytes = parse_positive_env(MAX_INDEX_BYTES_ENV).unwrap_or(DEFAULT_MAX_INDEX_BYTES);
Self {
max_files,
max_bytes,
}
}
}
impl Default for DiscoveryLimits {
fn default() -> Self {
Self {
max_files: DEFAULT_MAX_INDEX_FILES,
max_bytes: DEFAULT_MAX_INDEX_BYTES,
}
}
}
fn parse_positive_env(name: &str) -> Option<u64> {
std::env::var(name)
.ok()?
.trim()
.parse::<u64>()
.ok()
.filter(|&value| value > 0)
}
const CARGO_TARGET_DIR_ENV: &str = "CARGO_TARGET_DIR";
fn is_cargo_build_dir_name(name: &str) -> bool {
let Some(rest) = name.strip_prefix("target") else {
return false;
};
match rest.strip_prefix('-') {
None if rest.is_empty() => true,
None => false,
Some(suffix) => {
!suffix.is_empty()
&& suffix
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
}
}
fn cargo_target_dir_root_child(root: &Path) -> Option<String> {
let raw = std::env::var_os(CARGO_TARGET_DIR_ENV)?;
if raw.is_empty() {
return None;
}
let target = PathBuf::from(&raw);
let target_abs = if target.is_absolute() {
target
} else {
root.join(&target)
};
let canon_target = std::fs::canonicalize(&target_abs).unwrap_or(target_abs);
let parent = canon_target.parent()?;
if parent != root {
return None;
}
canon_target
.file_name()
.and_then(|n| n.to_str())
.map(|s| s.to_string())
}
fn is_under_repo_root_build_dir(relative_path: &str, target_dir_child: Option<&str>) -> bool {
let Some(first) = relative_path.split('/').next() else {
return false;
};
if first == relative_path {
return false;
}
if is_cargo_build_dir_name(first) {
return true;
}
matches!(target_dir_child, Some(child) if child == first)
}
pub fn path_has_hidden_component(relative_path: &str) -> bool {
relative_path
.split('/')
.any(|component| component.starts_with('.') && component != "." && component != "..")
}
fn tree_too_large_error(files: u64, bytes: u64, limits: &DiscoveryLimits) -> anyhow::Error {
anyhow::anyhow!(
"tree too large to index ({files} files / {bytes} bytes exceeds limit of \
{max_files} files / {max_bytes} bytes); set {MAX_INDEX_FILES_ENV} or \
{MAX_INDEX_BYTES_ENV} to override",
max_files = limits.max_files,
max_bytes = limits.max_bytes,
)
}
pub fn discover_files(root: &Path) -> Result<Vec<DiscoveredFile>> {
use ignore::WalkBuilder;
let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let limits = DiscoveryLimits::from_env();
let target_dir_child = cargo_target_dir_root_child(&root);
let mut files: Vec<DiscoveredFile> = Vec::new();
for entry_result in WalkBuilder::new(&root).build() {
let Ok(entry) = entry_result else { continue };
let path =
std::fs::canonicalize(entry.path()).unwrap_or_else(|_| entry.path().to_path_buf());
if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
continue;
}
let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
continue;
};
let Some(language) = LanguageId::from_extension(ext) else {
continue;
};
let Ok(relative) = path.strip_prefix(&root) else {
continue;
};
let relative_path = relative.to_string_lossy().replace('\\', "/");
if is_under_repo_root_build_dir(&relative_path, target_dir_child.as_deref()) {
continue;
}
if files.len() as u64 >= limits.max_files {
return Err(tree_too_large_error(files.len() as u64 + 1, 0, &limits));
}
files.push(DiscoveredFile {
classification: FileClassification::for_code_path(&relative_path),
relative_path,
absolute_path: path,
language,
});
}
files.sort_by_cached_key(|file| file.relative_path.to_lowercase());
Ok(files)
}
pub fn discover_all_files(root: &Path) -> Result<Vec<DiscoveredEntry>> {
use ignore::WalkBuilder;
let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let limits = DiscoveryLimits::from_env();
let target_dir_child = cargo_target_dir_root_child(&root);
let mut total_bytes: u64 = 0;
let mut entries: Vec<DiscoveredEntry> = Vec::new();
let mut tracked_for_build_dirs: Option<Option<std::collections::HashSet<String>>> = None;
for entry_result in WalkBuilder::new(&root).build() {
let Ok(entry) = entry_result else { continue };
let path =
std::fs::canonicalize(entry.path()).unwrap_or_else(|_| entry.path().to_path_buf());
if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
continue;
}
let file_size = entry
.metadata()
.ok()
.map(|m| m.len())
.unwrap_or_else(|| std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0));
let Ok(relative) = path.strip_prefix(&root) else {
continue;
};
let relative_path = relative.to_string_lossy().replace('\\', "/");
if is_under_repo_root_build_dir(&relative_path, target_dir_child.as_deref()) {
let tracked = tracked_for_build_dirs
.get_or_insert_with(|| tracked_path_set_for_build_dir_rescue(&root));
let rescued = tracked
.as_ref()
.is_some_and(|set| set.contains(relative_path.as_str()));
if !rescued {
continue;
}
}
let language = path
.extension()
.and_then(|e| e.to_str())
.and_then(LanguageId::from_extension);
let classification = FileClassification::for_code_path(&relative_path);
let projected_files = entries.len() as u64 + 1;
let projected_bytes = total_bytes.saturating_add(file_size);
if projected_files > limits.max_files || projected_bytes > limits.max_bytes {
return Err(tree_too_large_error(
projected_files,
projected_bytes,
&limits,
));
}
total_bytes = projected_bytes;
entries.push(DiscoveredEntry {
relative_path,
absolute_path: path,
file_size,
language,
classification,
});
}
entries.sort_by_cached_key(|entry| entry.relative_path.to_lowercase());
Ok(entries)
}
pub fn load_gitignore(root: &Path) -> Option<ignore::gitignore::Gitignore> {
use ignore::gitignore::GitignoreBuilder;
use std::collections::VecDeque;
let root_gitignore = root.join(".gitignore");
if !root_gitignore.exists() {
return None;
}
let mut builder = GitignoreBuilder::new(root);
let max_depth: usize = 6;
let mut queue: VecDeque<(PathBuf, usize)> = VecDeque::new();
queue.push_back((root.to_path_buf(), 0));
while let Some((dir, depth)) = queue.pop_front() {
let gitignore_path = dir.join(".gitignore");
if gitignore_path.is_file()
&& let Some(err) = builder.add(&gitignore_path)
{
tracing::debug!("failed to load {:?}: {}", gitignore_path, err);
}
if depth < max_depth
&& let Ok(entries) = std::fs::read_dir(&dir)
{
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with('.') && name_str != ".github" {
continue;
}
queue.push_back((path, depth + 1));
}
}
}
}
match builder.build() {
Ok(gi) => {
if gi.is_empty() { None } else { Some(gi) }
}
Err(e) => {
tracing::debug!("failed to build gitignore matcher: {}", e);
None
}
}
}
pub const WORKSPACE_ROOT_ENV: &str = "SYMFORGE_WORKSPACE_ROOT";
pub fn find_project_root() -> Option<PathBuf> {
if let Some(root) = workspace_root_env_override() {
return Some(root);
}
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut current = cwd.clone();
loop {
if current.join(".git").exists() && !is_forbidden_root(¤t) {
return Some(current);
}
match current.parent() {
Some(parent) => current = parent.to_path_buf(),
None => break,
}
}
if is_forbidden_root(&cwd) {
tracing::warn!(
path = %cwd.display(),
"refusing to auto-index: directory is too broad (home dir, drive root, or system path)"
);
None
} else {
Some(cwd)
}
}
pub(crate) fn git_root_above(start: &Path) -> Option<PathBuf> {
let mut current = start.parent()?.to_path_buf();
loop {
if current.join(".git").exists() && !is_forbidden_root(¤t) {
return Some(current);
}
match current.parent() {
Some(parent) => current = parent.to_path_buf(),
None => return None,
}
}
}
pub fn workspace_root_env_override() -> Option<PathBuf> {
let raw = std::env::var(WORKSPACE_ROOT_ENV).ok()?;
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
validate_workspace_candidate(Path::new(trimmed), WORKSPACE_ROOT_ENV)
}
fn validate_workspace_candidate(candidate: &Path, source: &str) -> Option<PathBuf> {
if !candidate.is_dir() {
tracing::warn!(
path = %candidate.display(),
"ignoring {source}: not an existing directory"
);
return None;
}
if is_forbidden_root(candidate) {
tracing::warn!(
path = %candidate.display(),
"ignoring {source}: directory is too broad (home dir, drive root, or system path)"
);
return None;
}
Some(candidate.to_path_buf())
}
pub(crate) fn percent_decode_path(s: &str) -> Option<String> {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
let hi = bytes.get(i + 1).copied()?;
let lo = bytes.get(i + 2).copied()?;
let decode = |b: u8| -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
};
out.push(decode(hi)? << 4 | decode(lo)?);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
pub fn parse_root_uri(uri: &str) -> Option<PathBuf> {
let trimmed = uri.trim();
if trimmed.is_empty() {
return None;
}
if let Some(scheme_end) = trimmed.find("://") {
let scheme = &trimmed[..scheme_end];
if !scheme.eq_ignore_ascii_case("file") {
if scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
{
return None;
}
}
}
let rest = if let Some(after) = trimmed.strip_prefix("file://") {
match after.find('/') {
Some(idx) => {
let authority = &after[..idx];
if authority.is_empty() || authority.eq_ignore_ascii_case("localhost") {
&after[idx..]
} else {
return None;
}
}
None => return None,
}
} else {
trimmed
};
let decoded = percent_decode_path(rest)?;
let cleaned = {
let bytes = decoded.as_bytes();
if bytes.len() >= 3
&& bytes[0] == b'/'
&& bytes[1].is_ascii_alphabetic()
&& bytes[2] == b':'
{
decoded[1..].to_string()
} else {
decoded
}
};
Some(PathBuf::from(cleaned))
}
pub fn resolve_workspace_root(
env_root: Option<PathBuf>,
root_uris: &[String],
cwd_root: Option<PathBuf>,
) -> Option<PathBuf> {
if let Some(root) = env_root {
return Some(root);
}
for uri in root_uris {
let Some(candidate) = parse_root_uri(uri) else {
continue;
};
if let Some(root) = validate_workspace_candidate(&candidate, "MCP client root") {
return Some(root);
}
}
cwd_root
}
fn is_forbidden_root(path: &Path) -> bool {
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if crate::paths::is_sensitive_path(&path) {
return true;
}
if path.parent().is_none() {
return true;
}
#[cfg(target_os = "windows")]
{
let path_str = path.to_string_lossy();
if path_str.len() <= 7 && path_str.ends_with('\\') {
return true;
}
}
if let Some(home) = home_dir() {
let home = home.canonicalize().unwrap_or(home);
if path == home {
return true;
}
}
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let lower = name.to_lowercase();
const SYSTEM_NAMES: &[&str] = &[
"windows",
"system32",
"program files",
"program files (x86)",
"programdata",
"node_modules",
".npm",
".cargo",
];
if SYSTEM_NAMES.contains(&lower.as_str()) {
return true;
}
}
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let lower = name.to_lowercase();
const CONTAINER_NAMES: &[&str] = &["users", "home", "tmp", "temp", "var", "appdata"];
if CONTAINER_NAMES.contains(&lower.as_str())
&& path
.parent()
.map(|p| {
p.parent().is_none() || {
#[cfg(target_os = "windows")]
{
let pstr = p.to_string_lossy();
pstr.len() <= 7 && pstr.ends_with('\\')
}
#[cfg(not(target_os = "windows"))]
{
false
}
}
})
.unwrap_or(false)
{
return true;
}
}
#[cfg(not(target_os = "windows"))]
{
if is_running_under_wsl() && is_wsl_windows_container_path(&path) {
return true;
}
}
if let Some(home) = home_dir() {
let home = home.canonicalize().unwrap_or(home);
if let Some(parent) = home.parent() {
let parent = parent
.canonicalize()
.unwrap_or_else(|_| parent.to_path_buf());
if path == parent {
return true;
}
}
}
false
}
fn home_dir() -> Option<PathBuf> {
#[cfg(target_os = "windows")]
{
std::env::var("USERPROFILE").ok().map(PathBuf::from)
}
#[cfg(not(target_os = "windows"))]
{
std::env::var("HOME").ok().map(PathBuf::from)
}
}
#[cfg(not(target_os = "windows"))]
fn is_running_under_wsl() -> bool {
use std::sync::OnceLock;
static IS_WSL: OnceLock<bool> = OnceLock::new();
*IS_WSL.get_or_init(|| {
std::fs::read_to_string("/proc/version")
.map(|v| {
let v = v.to_ascii_lowercase();
v.contains("microsoft") || v.contains("wsl")
})
.unwrap_or(false)
})
}
#[cfg(not(target_os = "windows"))]
fn is_wsl_windows_container_path(path: &Path) -> bool {
let mut comps: Vec<&str> = Vec::new();
for component in path.components() {
match component {
std::path::Component::Normal(os) => {
if let Some(s) = os.to_str() {
comps.push(s);
}
}
std::path::Component::ParentDir if comps.pop().is_none() => return false,
std::path::Component::ParentDir => {}
_ => {}
}
}
if comps.first() != Some(&"mnt") {
return false;
}
let is_drive_letter =
|s: &str| s.len() == 1 && s.chars().next().is_some_and(|c| c.is_ascii_alphabetic());
let is_users = |s: &str| s.eq_ignore_ascii_case("Users");
match comps.as_slice() {
[_mnt, drive] => is_drive_letter(drive),
[_mnt, drive, users] => is_drive_letter(drive) && is_users(users),
[_mnt, drive, users, _name] => is_drive_letter(drive) && is_users(users),
_ => false,
}
}
pub fn is_binary_content(content: &[u8]) -> bool {
if content.is_empty() {
return false;
}
let check_len = content.len().min(crate::domain::index::BINARY_SNIFF_BYTES);
let window = &content[..check_len];
if window.contains(&0) {
return true;
}
if std::str::from_utf8(window).is_err() {
return true;
}
let suspicious_controls = window
.iter()
.filter(|&&b| matches!(b, 0x01..=0x08 | 0x0E..=0x1F | 0x7F))
.count();
let ratio = suspicious_controls as f64 / window.len() as f64;
if ratio > 0.30 {
return true;
}
false
}
use crate::domain::index::{
AdmissionDecision, AdmissionTier, HARD_SKIP_BYTES, METADATA_ONLY_BYTES, SkipReason,
};
pub fn classify_admission(
path: &std::path::Path,
file_size: u64,
content_sample: Option<&[u8]>,
) -> AdmissionDecision {
use crate::domain::index::{is_denylisted_extension, is_dependency_lockfile};
if file_size > HARD_SKIP_BYTES {
return AdmissionDecision::skip(AdmissionTier::HardSkip, SkipReason::SizeCeiling);
}
if is_dependency_lockfile(path) {
return AdmissionDecision::skip(
AdmissionTier::MetadataOnly,
SkipReason::DependencyLockfile,
);
}
if let Some(ext) = path.extension().and_then(|e| e.to_str())
&& is_denylisted_extension(ext)
{
return AdmissionDecision::skip(
AdmissionTier::MetadataOnly,
SkipReason::DenylistedExtension,
);
}
let size_threshold = path
.extension()
.and_then(|e| e.to_str())
.and_then(crate::domain::LanguageId::from_extension)
.filter(crate::domain::LanguageId::is_code_language)
.map_or(METADATA_ONLY_BYTES, |_| {
crate::domain::index::METADATA_ONLY_CODE_BYTES
});
if file_size > size_threshold {
return AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::SizeThreshold);
}
if let Some(content) = content_sample
&& is_binary_content(content)
{
return AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::BinaryContent);
}
AdmissionDecision::normal()
}
pub fn unsupported_language_decision(decision: AdmissionDecision) -> AdmissionDecision {
if decision.tier == AdmissionTier::Normal {
AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::UnsupportedLanguage)
} else {
decision
}
}
pub const EXCLUDE_UNTRACKED_ENV: &str = "SYMFORGE_EXCLUDE_UNTRACKED";
pub fn exclude_untracked_enabled() -> bool {
std::env::var(EXCLUDE_UNTRACKED_ENV)
.map(|v| {
let v = v.trim().to_ascii_lowercase();
matches!(v.as_str(), "1" | "true" | "yes" | "on")
})
.unwrap_or(false)
}
pub fn tracked_path_set_for_exclusion(root: &Path) -> Option<std::collections::HashSet<String>> {
if !exclude_untracked_enabled() {
return None;
}
let git_repo = crate::git::GitRepo::open(root).ok()?;
let tracked = git_repo.tracked_paths().ok()?;
if tracked.is_empty() {
return None;
}
Some(tracked.into_iter().collect())
}
fn tracked_path_set_for_build_dir_rescue(root: &Path) -> Option<std::collections::HashSet<String>> {
let git_repo = crate::git::GitRepo::open(root).ok()?;
let tracked = git_repo.tracked_paths().ok()?;
if tracked.is_empty() {
return None;
}
Some(tracked.into_iter().collect())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
fn create_file(dir: &Path, name: &str, content: &str) {
let path = dir.join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, content).unwrap();
}
#[test]
fn test_discover_files_finds_rs_py_js() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "main.rs", "fn main() {}");
create_file(tmp.path(), "script.py", "def foo(): pass");
create_file(tmp.path(), "app.js", "function bar() {}");
let files = discover_files(tmp.path()).unwrap();
let extensions: Vec<&str> = files
.iter()
.map(|f| f.relative_path.rsplit('.').next().unwrap())
.collect();
assert!(extensions.contains(&"rs"), "should find .rs");
assert!(extensions.contains(&"py"), "should find .py");
assert!(extensions.contains(&"js"), "should find .js");
assert_eq!(files.len(), 3);
}
#[test]
fn test_discover_files_includes_config_files() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "config.json", "{}");
create_file(tmp.path(), "README.md", "# readme");
create_file(tmp.path(), "Cargo.toml", "[package]");
create_file(tmp.path(), "main.rs", "fn main() {}");
let files = discover_files(tmp.path()).unwrap();
assert_eq!(files.len(), 4, "should discover .rs + .json + .md + .toml");
let paths: Vec<&str> = files.iter().map(|f| f.relative_path.as_str()).collect();
assert!(paths.contains(&"config.json"), "should find .json");
assert!(paths.contains(&"README.md"), "should find .md");
assert!(paths.contains(&"Cargo.toml"), "should find .toml");
assert!(paths.contains(&"main.rs"), "should find .rs");
}
#[test]
fn test_discover_files_respects_gitignore() {
let tmp = TempDir::new().unwrap();
fs::create_dir(tmp.path().join(".git")).unwrap();
fs::write(tmp.path().join(".gitignore"), "ignored.rs\n").unwrap();
create_file(tmp.path(), "main.rs", "fn main() {}");
create_file(tmp.path(), "ignored.rs", "fn ignored() {}");
let files = discover_files(tmp.path()).unwrap();
assert_eq!(files.len(), 1, "ignored.rs should be excluded");
assert_eq!(files[0].relative_path, "main.rs");
}
#[test]
fn test_discover_files_normalizes_backslashes() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "src/lib.rs", "pub fn lib() {}");
let files = discover_files(tmp.path()).unwrap();
assert_eq!(files.len(), 1);
assert!(
!files[0].relative_path.contains('\\'),
"should have no backslashes: {:?}",
files[0].relative_path
);
assert!(files[0].relative_path.contains('/') || files[0].relative_path == "src/lib.rs");
}
#[test]
fn test_discover_files_deterministic_sorted_order() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "Zoo.rs", "fn zoo() {}");
create_file(tmp.path(), "apple.rs", "fn apple() {}");
create_file(tmp.path(), "Mango.rs", "fn mango() {}");
let files = discover_files(tmp.path()).unwrap();
assert_eq!(files.len(), 3);
let names: Vec<&str> = files.iter().map(|f| f.relative_path.as_str()).collect();
let lower: Vec<String> = names.iter().map(|n| n.to_lowercase()).collect();
let mut sorted = lower.clone();
sorted.sort();
assert_eq!(
lower, sorted,
"files should be in case-insensitive sorted order"
);
}
#[test]
fn test_discover_files_assigns_classification_tags_from_path() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "tests/unit_spec.rs", "fn spec_case() {}");
create_file(tmp.path(), "vendor/pkg/lib.rs", "fn vendored() {}");
create_file(
tmp.path(),
"src/generated/client.generated.rs",
"fn generated() {}",
);
let files = discover_files(tmp.path()).unwrap();
let by_path: std::collections::HashMap<&str, &DiscoveredFile> = files
.iter()
.map(|file| (file.relative_path.as_str(), file))
.collect();
assert!(
by_path["tests/unit_spec.rs"].classification.is_test,
"tests path should set is_test"
);
assert!(
by_path["vendor/pkg/lib.rs"].classification.is_vendor,
"vendor path should set is_vendor"
);
assert!(
by_path["src/generated/client.generated.rs"]
.classification
.is_generated,
"generated path should set is_generated"
);
}
mod cargo_build_dir_skip {
use super::*;
#[test]
fn build_dir_name_matcher_classifies_correctly() {
assert!(is_cargo_build_dir_name("target"));
assert!(is_cargo_build_dir_name("target-wsl"));
assert!(is_cargo_build_dir_name("target-debug"));
assert!(is_cargo_build_dir_name("target-x86_64"));
assert!(is_cargo_build_dir_name("target-CI_2"));
assert!(!is_cargo_build_dir_name("targets"));
assert!(!is_cargo_build_dir_name("target_dir"));
assert!(!is_cargo_build_dir_name("target-"));
assert!(!is_cargo_build_dir_name("target-foo/bar"));
assert!(!is_cargo_build_dir_name("my-target"));
assert!(!is_cargo_build_dir_name("src"));
}
#[test]
fn under_repo_root_build_dir_only_matches_root_child() {
assert!(is_under_repo_root_build_dir("target/debug/foo.rs", None));
assert!(is_under_repo_root_build_dir(
"target-wsl/release/x.rs",
None
));
assert!(!is_under_repo_root_build_dir("src/target/mod.rs", None));
assert!(!is_under_repo_root_build_dir("target", None));
assert!(!is_under_repo_root_build_dir("src/lib.rs", None));
assert!(is_under_repo_root_build_dir(
"build-out/app.rs",
Some("build-out")
));
assert!(!is_under_repo_root_build_dir(
"src/build-out/app.rs",
Some("build-out")
));
}
#[test]
fn discover_files_skips_target_wsl_keeps_source() {
let tmp = TempDir::new().unwrap();
create_file(
tmp.path(),
"target-wsl/debug/build_artifact.rs",
"fn a() {}",
);
create_file(tmp.path(), "target/debug/other.rs", "fn b() {}");
create_file(tmp.path(), "src/lib.rs", "pub fn lib() {}");
create_file(tmp.path(), "targets/config.rs", "fn cfg() {}");
create_file(tmp.path(), "src/target/mod.rs", "fn nested() {}");
let files = discover_files(tmp.path()).unwrap();
let paths: Vec<&str> = files.iter().map(|f| f.relative_path.as_str()).collect();
assert!(
!paths.contains(&"target-wsl/debug/build_artifact.rs"),
"target-wsl/ build output must be skipped: {paths:?}"
);
assert!(
!paths.contains(&"target/debug/other.rs"),
"target/ build output must be skipped: {paths:?}"
);
assert!(
paths.contains(&"src/lib.rs"),
"normal source must be indexed: {paths:?}"
);
assert!(
paths.contains(&"targets/config.rs"),
"non-build dir `targets/` must not be over-skipped: {paths:?}"
);
assert!(
paths.contains(&"src/target/mod.rs"),
"nested source dir `src/target/` must be preserved: {paths:?}"
);
}
#[test]
fn discover_all_files_skips_target_wsl_keeps_source() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "target-wsl/debug/artifact.rs", "fn a() {}");
create_file(tmp.path(), "src/main.rs", "fn main() {}");
create_file(tmp.path(), "targets/x.rs", "fn x() {}");
let entries = discover_all_files(tmp.path()).unwrap();
let paths: Vec<&str> = entries.iter().map(|e| e.relative_path.as_str()).collect();
assert!(
!paths.contains(&"target-wsl/debug/artifact.rs"),
"target-wsl/ build output must be skipped in full discovery: {paths:?}"
);
assert!(
paths.contains(&"src/main.rs"),
"normal source must be discovered: {paths:?}"
);
assert!(
paths.contains(&"targets/x.rs"),
"non-build dir `targets/` must not be over-skipped: {paths:?}"
);
}
}
mod unsupported_language {
use super::*;
#[test]
fn unsupported_language_decision_demotes_normal_to_metadata_only() {
let normal = AdmissionDecision::normal();
let demoted = unsupported_language_decision(normal);
assert_eq!(demoted.tier, AdmissionTier::MetadataOnly);
assert_eq!(demoted.reason, Some(SkipReason::UnsupportedLanguage));
}
#[test]
fn unsupported_language_decision_preserves_specific_skip_reasons() {
for original in [
AdmissionDecision::skip(AdmissionTier::HardSkip, SkipReason::SizeCeiling),
AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::SizeThreshold),
AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::BinaryContent),
AdmissionDecision::skip(
AdmissionTier::MetadataOnly,
SkipReason::DependencyLockfile,
),
] {
assert_eq!(
unsupported_language_decision(original),
original,
"non-Normal decision must be returned unchanged"
);
}
}
#[test]
fn unsupported_language_reason_renders_honestly() {
assert_eq!(
SkipReason::UnsupportedLanguage.to_string(),
"unsupported language"
);
}
}
mod hidden_path {
use super::*;
#[test]
fn detects_hidden_directory_component() {
assert!(path_has_hidden_component(".github/workflows/ci.yml"));
assert!(path_has_hidden_component(
"deps/hiredis/.github/release.yml"
));
assert!(path_has_hidden_component(".travis.yml"));
assert!(path_has_hidden_component("a/b/.hidden"));
}
#[test]
fn allows_visible_paths_and_traversal_segments() {
assert!(!path_has_hidden_component("src/main.rs"));
assert!(!path_has_hidden_component("README.md"));
assert!(!path_has_hidden_component("./src/main.rs"));
assert!(!path_has_hidden_component("../sibling/main.rs"));
assert!(!path_has_hidden_component("src/a.b.c/main.rs"));
}
#[test]
fn discover_all_files_skips_hidden_supported_extension_files() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), ".github/workflows/ci.yml", "name: ci\n");
create_file(tmp.path(), ".travis.yml", "language: rust\n");
create_file(tmp.path(), "src/main.rs", "fn main() {}");
let entries = discover_all_files(tmp.path()).unwrap();
let paths: Vec<&str> = entries.iter().map(|e| e.relative_path.as_str()).collect();
assert!(
!paths.contains(&".github/workflows/ci.yml"),
"hidden-dir file must not be discovered by the bulk walk: {paths:?}"
);
assert!(
!paths.contains(&".travis.yml"),
"hidden dotfile must not be discovered by the bulk walk: {paths:?}"
);
assert!(
paths.contains(&"src/main.rs"),
"visible source must be discovered: {paths:?}"
);
}
}
mod build_dir_tracked_rescue {
use super::*;
use std::process::Command;
#[test]
fn discover_all_files_rescues_tracked_target_specs_dir() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let run = |args: &[&str]| {
Command::new("git")
.args(args)
.current_dir(root)
.output()
.expect("git command");
};
run(&["init"]);
run(&["config", "user.email", "test@test.com"]);
run(&["config", "user.name", "Test"]);
create_file(root, "target-specs/i686.json", "{}\n");
create_file(root, "target-specs/README.md", "# specs\n");
create_file(root, "src/main.rs", "fn main() {}");
run(&["add", "target-specs", "src"]);
run(&["commit", "-m", "initial"]);
create_file(root, "target/debug/artifact.rs", "fn a() {}");
let entries = discover_all_files(root).unwrap();
let paths: Vec<&str> = entries.iter().map(|e| e.relative_path.as_str()).collect();
assert!(
paths.contains(&"target-specs/i686.json"),
"tracked target-specs/ source must be rescued: {paths:?}"
);
assert!(
paths.contains(&"target-specs/README.md"),
"tracked target-specs/ source must be rescued: {paths:?}"
);
assert!(
paths.contains(&"src/main.rs"),
"normal source must be discovered: {paths:?}"
);
assert!(
!paths.contains(&"target/debug/artifact.rs"),
"untracked build output must still be skipped: {paths:?}"
);
}
#[test]
fn discover_all_files_without_git_keeps_conservative_build_dir_skip() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "target-wsl/debug/artifact.rs", "fn a() {}");
create_file(tmp.path(), "src/main.rs", "fn main() {}");
let entries = discover_all_files(tmp.path()).unwrap();
let paths: Vec<&str> = entries.iter().map(|e| e.relative_path.as_str()).collect();
assert!(
!paths.contains(&"target-wsl/debug/artifact.rs"),
"non-git tree must still skip target-* build dirs: {paths:?}"
);
assert!(
paths.contains(&"src/main.rs"),
"normal source must be discovered: {paths:?}"
);
}
}
#[test]
fn test_is_forbidden_root_blocks_home_dir() {
let home = home_dir();
if let Some(h) = home {
assert!(is_forbidden_root(&h), "home directory should be forbidden");
}
}
#[test]
fn test_is_forbidden_root_blocks_drive_root() {
#[cfg(target_os = "windows")]
assert!(is_forbidden_root(Path::new("C:\\")));
#[cfg(not(target_os = "windows"))]
assert!(is_forbidden_root(Path::new("/")));
}
#[test]
fn test_is_forbidden_root_blocks_system_dirs() {
assert!(is_forbidden_root(Path::new("/tmp")));
assert!(is_forbidden_root(Path::new("/home")));
}
#[test]
fn test_is_forbidden_root_allows_project_dirs() {
let tmp = TempDir::new().unwrap();
assert!(
!is_forbidden_root(tmp.path()),
"temp project dir should be allowed"
);
}
#[test]
fn test_is_forbidden_root_allows_project_named_tmp() {
let tmp = TempDir::new().unwrap();
let project = tmp.path().join("projects").join("tmp");
std::fs::create_dir_all(&project).unwrap();
assert!(
!is_forbidden_root(&project),
"project at C:\\projects\\tmp must not be rejected by basename"
);
}
#[test]
fn test_is_forbidden_root_allows_project_named_var() {
let tmp = TempDir::new().unwrap();
let project = tmp.path().join("workspace").join("var");
std::fs::create_dir_all(&project).unwrap();
assert!(
!is_forbidden_root(&project),
"project at workspace/var must not be rejected by basename"
);
}
#[test]
fn test_is_forbidden_root_still_blocks_top_level_tmp_on_unix() {
#[cfg(unix)]
{
let path = std::path::Path::new("/tmp");
if path.exists() {
assert!(
is_forbidden_root(path),
"/tmp must still be blocked as system path"
);
}
}
}
#[test]
fn test_is_forbidden_root_still_blocks_windows_system_paths() {
#[cfg(target_os = "windows")]
{
let path = std::path::Path::new(r"C:\Windows\System32");
if path.exists() {
assert!(
is_forbidden_root(path),
"C:\\Windows\\System32 must remain blocked"
);
}
}
}
#[test]
fn test_binary_sniff_detects_null_bytes() {
let content = b"hello\x00world";
assert!(is_binary_content(content));
}
#[test]
fn test_binary_sniff_allows_pure_utf8() {
let content = b"fn main() { println!(\"hello\"); }";
assert!(!is_binary_content(content));
}
#[test]
fn test_binary_sniff_empty_file() {
assert!(!is_binary_content(b""));
}
#[test]
fn test_binary_sniff_detects_invalid_utf8() {
let content: &[u8] = &[0x80, 0x81, 0x82, 0x83, 0x84];
assert!(is_binary_content(content));
}
#[test]
fn test_binary_sniff_detects_high_control_ratio() {
let mut content = Vec::new();
content.extend(std::iter::repeat_n(0x01, 80)); content.extend(std::iter::repeat_n(b'A', 20)); assert!(is_binary_content(&content));
}
#[test]
fn test_binary_sniff_allows_low_control_ratio() {
let content = b"line1\tvalue1\nline2\tvalue2\nline3\tvalue3\n";
assert!(!is_binary_content(content));
}
#[test]
fn test_binary_sniff_allows_common_whitespace_controls() {
let content = b"col1\tcol2\tcol3\r\nval1\tval2\tval3\r\n";
assert!(!is_binary_content(content));
}
use crate::domain::index::{AdmissionDecision, AdmissionTier, SkipReason};
#[test]
fn test_huge_text_file_is_hard_skip() {
let decision =
classify_admission(std::path::Path::new("huge.txt"), 150 * 1024 * 1024, None);
assert_eq!(decision.tier, AdmissionTier::HardSkip);
assert_eq!(decision.reason, Some(SkipReason::SizeCeiling));
}
#[test]
fn test_small_ckpt_is_metadata_only() {
let decision = classify_admission(std::path::Path::new("model.ckpt"), 50 * 1024, None);
assert_eq!(decision.tier, AdmissionTier::MetadataOnly);
assert_eq!(decision.reason, Some(SkipReason::DenylistedExtension));
}
#[test]
fn test_huge_ckpt_is_hard_skip() {
let decision = classify_admission(std::path::Path::new("big.ckpt"), 4_200_000_000, None);
assert_eq!(decision.tier, AdmissionTier::HardSkip);
assert_eq!(decision.reason, Some(SkipReason::SizeCeiling));
}
#[test]
fn test_large_json_is_metadata_only() {
let decision = classify_admission(std::path::Path::new("big.json"), 2 * 1024 * 1024, None);
assert_eq!(decision.tier, AdmissionTier::MetadataOnly);
assert_eq!(decision.reason, Some(SkipReason::SizeThreshold));
}
#[test]
fn test_small_txt_is_normal() {
let decision = classify_admission(std::path::Path::new("readme.txt"), 50 * 1024, None);
assert_eq!(decision, AdmissionDecision::normal());
}
#[test]
fn test_medium_rust_source_is_normal() {
let decision = classify_admission(std::path::Path::new("big_module.rs"), 500 * 1024, None);
assert_eq!(decision, AdmissionDecision::normal());
}
#[test]
fn test_oversized_code_file_under_4mb_is_normal() {
for name in ["orchestrator.rs", "big.py", "huge.ts", "large.pm"] {
let decision = classify_admission(std::path::Path::new(name), 1_200_000, None);
assert_eq!(
decision,
AdmissionDecision::normal(),
"1.2MB code file {name} must stay Tier-1"
);
}
}
#[test]
fn test_code_file_above_4mb_is_metadata_only() {
let decision =
classify_admission(std::path::Path::new("generated.rs"), 5 * 1024 * 1024, None);
assert_eq!(decision.tier, AdmissionTier::MetadataOnly);
assert_eq!(decision.reason, Some(SkipReason::SizeThreshold));
}
#[test]
fn test_data_formats_keep_1mb_threshold() {
for name in ["big.yaml", "big.toml", "big.md", "big.html"] {
let decision = classify_admission(std::path::Path::new(name), 1_200_000, None);
assert_eq!(
decision.tier,
AdmissionTier::MetadataOnly,
"1.2MB data file {name} must stay Tier-2"
);
assert_eq!(decision.reason, Some(SkipReason::SizeThreshold));
}
}
#[test]
fn test_binary_content_is_metadata_only() {
let content = b"ELF\x00\x00\x00binary";
let decision =
classify_admission(std::path::Path::new("unknown_file"), 1024, Some(content));
assert_eq!(decision.tier, AdmissionTier::MetadataOnly);
assert_eq!(decision.reason, Some(SkipReason::BinaryContent));
}
#[test]
fn test_svg_not_denylisted() {
let decision = classify_admission(std::path::Path::new("icon.svg"), 50 * 1024, None);
assert_eq!(decision, AdmissionDecision::normal());
}
#[test]
fn test_large_svg_is_metadata_only_by_size() {
let decision = classify_admission(std::path::Path::new("huge.svg"), 2 * 1024 * 1024, None);
assert_eq!(decision.tier, AdmissionTier::MetadataOnly);
assert_eq!(decision.reason, Some(SkipReason::SizeThreshold));
}
#[test]
fn test_discovery_skips_denylisted_extension() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "main.rs", "fn main() {}");
fs::write(tmp.path().join("model.safetensors"), b"fake model bytes").unwrap();
let entries = discover_all_files(tmp.path()).unwrap();
let mut rs_found = false;
let mut safetensors_skipped = false;
let mut safetensors_reason = None;
for entry in &entries {
let size = entry.file_size;
let decision = classify_admission(&entry.absolute_path, size, None);
if entry.relative_path == "main.rs" {
assert_eq!(
decision.tier,
AdmissionTier::Normal,
".rs file should be Normal"
);
rs_found = true;
}
if entry.relative_path == "model.safetensors" {
assert_eq!(
decision.tier,
AdmissionTier::MetadataOnly,
".safetensors should be MetadataOnly"
);
safetensors_skipped = true;
safetensors_reason = decision.reason;
}
}
assert!(rs_found, ".rs file must appear in discovered entries");
assert!(
safetensors_skipped,
".safetensors must appear in discovered entries and be skipped"
);
assert_eq!(
safetensors_reason,
Some(SkipReason::DenylistedExtension),
".safetensors skip reason must be DenylistedExtension"
);
}
#[test]
fn test_discovery_deferred_binary_sniff_reclassifies() {
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "lib.rs", "pub fn hello() {}");
let mut binary_content = vec![0u8; 512]; binary_content.extend_from_slice(b"some trailing text");
fs::write(tmp.path().join("custom.dat"), &binary_content).unwrap();
let entries = discover_all_files(tmp.path()).unwrap();
let mut rs_normal = false;
let mut dat_skipped = false;
let mut dat_reason = None;
for entry in &entries {
let size = entry.file_size;
let pre = classify_admission(&entry.absolute_path, size, None);
if entry.relative_path == "lib.rs" {
assert_eq!(pre.tier, AdmissionTier::Normal);
rs_normal = true;
}
if entry.relative_path == "custom.dat" {
assert_eq!(
pre.tier,
AdmissionTier::Normal,
"custom.dat should be Normal before binary sniff"
);
let content = fs::read(&entry.absolute_path).unwrap();
let post = classify_admission(&entry.absolute_path, size, Some(&content));
assert_eq!(
post.tier,
AdmissionTier::MetadataOnly,
"custom.dat should be MetadataOnly after binary sniff"
);
dat_skipped = true;
dat_reason = post.reason;
}
}
assert!(rs_normal, "lib.rs must be Normal");
assert!(
dat_skipped,
"custom.dat must be discovered and reclassified"
);
assert_eq!(
dat_reason,
Some(SkipReason::BinaryContent),
"custom.dat skip reason must be BinaryContent"
);
}
mod bounded_discovery {
use super::*;
use std::ffi::OsString;
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
struct LimitEnvGuard {
files_prev: Option<OsString>,
bytes_prev: Option<OsString>,
}
#[allow(unsafe_code)] impl LimitEnvGuard {
fn set(max_files: Option<&str>, max_bytes: Option<&str>) -> Self {
let files_prev = std::env::var_os(MAX_INDEX_FILES_ENV);
let bytes_prev = std::env::var_os(MAX_INDEX_BYTES_ENV);
unsafe {
match max_files {
Some(v) => std::env::set_var(MAX_INDEX_FILES_ENV, v),
None => std::env::remove_var(MAX_INDEX_FILES_ENV),
}
match max_bytes {
Some(v) => std::env::set_var(MAX_INDEX_BYTES_ENV, v),
None => std::env::remove_var(MAX_INDEX_BYTES_ENV),
}
}
Self {
files_prev,
bytes_prev,
}
}
}
#[allow(unsafe_code)] impl Drop for LimitEnvGuard {
fn drop(&mut self) {
unsafe {
match &self.files_prev {
Some(v) => std::env::set_var(MAX_INDEX_FILES_ENV, v),
None => std::env::remove_var(MAX_INDEX_FILES_ENV),
}
match &self.bytes_prev {
Some(v) => std::env::set_var(MAX_INDEX_BYTES_ENV, v),
None => std::env::remove_var(MAX_INDEX_BYTES_ENV),
}
}
}
}
#[test]
fn default_limits_are_generous() {
let limits = DiscoveryLimits::default();
assert_eq!(limits.max_files, DEFAULT_MAX_INDEX_FILES);
assert_eq!(limits.max_bytes, DEFAULT_MAX_INDEX_BYTES);
assert!(limits.max_files >= 200_000);
}
#[test]
fn parse_positive_env_rejects_zero_empty_and_garbage() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = LimitEnvGuard::set(Some("0"), Some("not-a-number"));
assert_eq!(parse_positive_env(MAX_INDEX_FILES_ENV), None);
assert_eq!(parse_positive_env(MAX_INDEX_BYTES_ENV), None);
let limits = DiscoveryLimits::from_env();
assert_eq!(limits.max_files, DEFAULT_MAX_INDEX_FILES);
assert_eq!(limits.max_bytes, DEFAULT_MAX_INDEX_BYTES);
}
#[test]
fn from_env_honors_valid_override() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = LimitEnvGuard::set(Some("5"), Some("4096"));
let limits = DiscoveryLimits::from_env();
assert_eq!(limits.max_files, 5);
assert_eq!(limits.max_bytes, 4096);
}
#[test]
fn normal_repo_indexes_under_default_cap() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = LimitEnvGuard::set(None, None);
let tmp = TempDir::new().unwrap();
create_file(tmp.path(), "main.rs", "fn main() {}");
create_file(tmp.path(), "lib.rs", "pub fn f() {}");
create_file(tmp.path(), "README.md", "# hi");
let files = discover_files(tmp.path()).expect("normal repo indexes fine");
assert_eq!(files.len(), 3);
let entries = discover_all_files(tmp.path()).expect("normal repo full-discovery fine");
assert!(entries.len() >= 3);
}
#[test]
fn over_file_cap_yields_graceful_error_not_panic() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = LimitEnvGuard::set(Some("2"), None);
let tmp = TempDir::new().unwrap();
for i in 0..5 {
create_file(tmp.path(), &format!("f{i}.rs"), "fn x() {}");
}
let err = discover_files(tmp.path()).expect_err("over file cap must error");
let msg = err.to_string();
assert!(
msg.contains("tree too large to index"),
"error must be the graceful over-cap message: {msg}"
);
assert!(
msg.contains(MAX_INDEX_FILES_ENV),
"error must name the override knob: {msg}"
);
let err2 = discover_all_files(tmp.path()).expect_err("full discovery over cap errors");
assert!(err2.to_string().contains("tree too large to index"));
}
#[test]
fn over_byte_cap_yields_graceful_error() {
let _lock = ENV_LOCK.lock().unwrap();
let _guard = LimitEnvGuard::set(Some("1000000"), Some("8"));
let tmp = TempDir::new().unwrap();
create_file(
tmp.path(),
"big.rs",
"fn this_is_more_than_eight_bytes() {}",
);
let err = discover_all_files(tmp.path()).expect_err("over byte cap must error");
let msg = err.to_string();
assert!(
msg.contains("tree too large to index"),
"error must be the graceful over-cap message: {msg}"
);
assert!(
msg.contains(MAX_INDEX_BYTES_ENV),
"error must name the byte override knob: {msg}"
);
}
#[test]
fn raised_cap_lets_a_previously_over_cap_tree_index() {
let _lock = ENV_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
for i in 0..4 {
create_file(tmp.path(), &format!("f{i}.rs"), "fn x() {}");
}
{
let _guard = LimitEnvGuard::set(Some("2"), None);
assert!(discover_files(tmp.path()).is_err());
}
{
let _guard = LimitEnvGuard::set(Some("100"), None);
let files = discover_files(tmp.path()).expect("raised cap indexes the tree");
assert_eq!(files.len(), 4);
}
}
}
mod git_fast_path_guard {
use super::*;
#[test]
fn ordinary_project_with_git_is_not_forbidden() {
let tmp = TempDir::new().unwrap();
fs::create_dir_all(tmp.path().join(".git")).unwrap();
assert!(
!is_forbidden_root(tmp.path()),
"an ordinary project dir must remain selectable as a git root"
);
}
#[cfg(not(target_os = "windows"))]
#[test]
fn sensitive_unix_root_with_git_is_forbidden() {
assert!(
is_forbidden_root(Path::new("/etc")),
"/etc must be forbidden even if a `.git` is planted there"
);
assert!(crate::paths::is_sensitive_path(Path::new("/etc")));
}
#[cfg(target_os = "windows")]
#[test]
fn sensitive_windows_root_with_git_is_forbidden() {
assert!(is_forbidden_root(Path::new("C:\\Windows")));
assert!(crate::paths::is_sensitive_path(Path::new("C:\\Windows")));
}
}
#[cfg(not(target_os = "windows"))]
mod wsl_drvfs {
use super::*;
#[test]
fn blocks_bare_drive_root() {
assert!(is_wsl_windows_container_path(Path::new("/mnt/c")));
assert!(is_wsl_windows_container_path(Path::new("/mnt/d")));
}
#[test]
fn blocks_users_container() {
assert!(is_wsl_windows_container_path(Path::new("/mnt/c/Users")));
}
#[test]
fn blocks_bare_profile_root() {
assert!(is_wsl_windows_container_path(Path::new(
"/mnt/c/Users/poslj"
)));
}
#[test]
fn blocks_other_drive_profile() {
assert!(is_wsl_windows_container_path(Path::new(
"/mnt/d/Users/alice"
)));
}
#[test]
fn blocks_case_insensitive_users_segment() {
assert!(is_wsl_windows_container_path(Path::new("/mnt/c/users")));
assert!(is_wsl_windows_container_path(Path::new(
"/mnt/c/USERS/poslj"
)));
assert!(is_wsl_windows_container_path(Path::new(
"/mnt/c/UsErS/poslj"
)));
}
#[test]
fn allows_deep_project_under_profile() {
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/Users/poslj/dev/my-lib"
)));
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/Users/poslj/Documents/project"
)));
}
#[test]
fn allows_non_users_mount_project() {
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/code/proj"
)));
}
#[test]
fn allows_users_named_deeper() {
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/code/Users"
)));
}
#[test]
fn allows_non_mnt_paths() {
assert!(!is_wsl_windows_container_path(Path::new("/srv/Users/bob")));
assert!(!is_wsl_windows_container_path(Path::new("/home/robert")));
}
#[test]
fn allows_multichar_second_segment() {
assert!(!is_wsl_windows_container_path(Path::new("/mnt/cc/Users/x")));
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/wsl/Users/x"
)));
}
#[test]
fn allows_lookalike_prefixes() {
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/Users-data/proj"
)));
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/UserStuff/proj"
)));
}
#[test]
fn allows_bare_mnt() {
assert!(!is_wsl_windows_container_path(Path::new("/mnt")));
}
#[test]
fn parent_dir_escape_does_not_misfire() {
assert!(!is_wsl_windows_container_path(Path::new(
"/mnt/c/Users/../code/proj"
)));
assert!(!is_wsl_windows_container_path(Path::new("/mnt/c/../..")));
}
}
mod workspace_root_override {
use super::*;
use std::ffi::OsString;
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
struct RootEnvGuard {
prev: Option<OsString>,
}
#[allow(unsafe_code)] impl RootEnvGuard {
fn set(value: Option<&str>) -> Self {
let prev = std::env::var_os(WORKSPACE_ROOT_ENV);
unsafe {
match value {
Some(v) => std::env::set_var(WORKSPACE_ROOT_ENV, v),
None => std::env::remove_var(WORKSPACE_ROOT_ENV),
}
}
Self { prev }
}
}
#[allow(unsafe_code)] impl Drop for RootEnvGuard {
fn drop(&mut self) {
unsafe {
match &self.prev {
Some(v) => std::env::set_var(WORKSPACE_ROOT_ENV, v),
None => std::env::remove_var(WORKSPACE_ROOT_ENV),
}
}
}
}
#[test]
fn honors_a_real_workspace_directory() {
let _lock = ENV_LOCK.lock().unwrap();
let workspace = TempDir::new().unwrap();
let _guard = RootEnvGuard::set(Some(&workspace.path().display().to_string()));
let resolved = workspace_root_env_override().expect("real dir must resolve");
let resolved = resolved.canonicalize().unwrap_or(resolved);
let expected = workspace.path().canonicalize().unwrap();
assert_eq!(resolved, expected);
}
#[test]
fn ignores_empty_and_missing_paths() {
let _lock = ENV_LOCK.lock().unwrap();
let _empty = RootEnvGuard::set(Some(" "));
assert!(workspace_root_env_override().is_none());
let _missing = RootEnvGuard::set(Some("/no/such/symforge/workspace/xyzzy"));
assert!(workspace_root_env_override().is_none());
let _unset = RootEnvGuard::set(None);
assert!(workspace_root_env_override().is_none());
}
#[test]
fn rejects_a_forbidden_home_dir_override() {
let _lock = ENV_LOCK.lock().unwrap();
let Some(home) = home_dir() else {
return; };
let _guard = RootEnvGuard::set(Some(&home.display().to_string()));
assert!(
workspace_root_env_override().is_none(),
"the forbidden home dir must be rejected by the shared trust-boundary guard"
);
}
}
mod roots_workspace_resolution {
use super::*;
fn file_uri(path: &std::path::Path) -> String {
let s = path.display().to_string().replace('\\', "/");
if s.starts_with('/') {
format!("file://{s}")
} else {
format!("file:///{s}")
}
}
#[test]
fn client_root_wins_over_forbidden_cwd_and_no_env() {
let workspace = TempDir::new().unwrap();
let uri = file_uri(workspace.path());
let resolved = resolve_workspace_root(None, std::slice::from_ref(&uri), None)
.expect("a valid client root must resolve the workspace with no env and no CWD");
let resolved = resolved.canonicalize().unwrap_or(resolved);
let expected = workspace.path().canonicalize().unwrap();
assert_eq!(
resolved, expected,
"client root must drive workspace resolution when CWD is unusable"
);
}
#[test]
fn env_override_beats_client_roots() {
let env_ws = TempDir::new().unwrap();
let client_ws = TempDir::new().unwrap();
let client_uri = file_uri(client_ws.path());
let resolved = resolve_workspace_root(
Some(env_ws.path().to_path_buf()),
std::slice::from_ref(&client_uri),
None,
)
.expect("env override must resolve");
assert_eq!(
resolved,
env_ws.path().to_path_buf(),
"SYMFORGE_WORKSPACE_ROOT must take precedence over client roots"
);
}
#[test]
fn cwd_used_only_when_env_and_roots_absent() {
let cwd_ws = TempDir::new().unwrap();
let resolved = resolve_workspace_root(None, &[], Some(cwd_ws.path().to_path_buf()))
.expect("CWD fallback must resolve");
assert_eq!(resolved, cwd_ws.path().to_path_buf());
}
#[test]
fn forbidden_client_root_is_skipped_not_fatal() {
let Some(home) = home_dir() else {
return; };
let valid = TempDir::new().unwrap();
let roots = vec![file_uri(&home), file_uri(valid.path())];
let resolved = resolve_workspace_root(None, &roots, None)
.expect("a valid later root must resolve after a forbidden one is skipped");
let resolved = resolved.canonicalize().unwrap_or(resolved);
let expected = valid.path().canonicalize().unwrap();
assert_eq!(resolved, expected);
}
#[test]
fn all_forbidden_roots_yield_none_when_no_other_source() {
let Some(home) = home_dir() else {
return;
};
let roots = vec![file_uri(&home)];
assert!(
resolve_workspace_root(None, &roots, None).is_none(),
"no env, all-forbidden roots, no CWD -> no workspace (must not widen trust)"
);
}
#[test]
fn parse_root_uri_handles_file_scheme_and_raw_path() {
let ws = TempDir::new().unwrap();
let native = ws.path().to_path_buf();
let from_uri = parse_root_uri(&file_uri(ws.path())).expect("file:// URI must parse");
assert_eq!(
from_uri.canonicalize().unwrap(),
native.canonicalize().unwrap()
);
let raw = native.display().to_string();
assert_eq!(parse_root_uri(&raw), Some(native.clone()));
assert_eq!(parse_root_uri(" "), None);
}
#[test]
fn parse_root_uri_rejects_non_file_scheme() {
assert_eq!(parse_root_uri("http://example.com/repo"), None);
assert_eq!(parse_root_uri("https://example.com/repo"), None);
}
#[test]
fn parse_root_uri_percent_decodes() {
let decoded = parse_root_uri("file:///tmp/a%20b/c%2Bd").expect("must parse");
assert_eq!(
decoded.to_string_lossy().replace('\\', "/"),
"/tmp/a b/c+d",
"percent escapes must decode to literal bytes"
);
}
}
}