1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::sync::Mutex;
4use std::time::Duration;
5
6use crate::backend::{BackendKind, BackendPath, ExecutionBackend, ExecutionRequest};
7use std::sync::LazyLock;
8
9pub use crate::DEFAULT_IGNORE_DIRS;
11
12pub const PROJECT_ROOT_MARKERS: &[&str] = &[
14 ".git",
15 "Cargo.toml",
16 "package.json",
17 "package-lock.json",
18 "pnpm-lock.yaml",
19 "pnpm-workspace.yaml",
20 "yarn.lock",
21 "pyproject.toml",
22 "requirements.txt",
23 "go.mod",
24 "pom.xml",
25 "build.gradle",
26 "build.gradle.kts",
27 "Gemfile",
28 "composer.json",
29 "CMakeLists.txt",
30 "deno.json",
31 "deno.jsonc",
32 "bun.lockb",
33 "wrangler.toml",
34 "mix.exs",
35 "pubspec.yaml",
36 "Package.swift",
37];
38
39pub fn validate_path(backend: &dyn ExecutionBackend, path: &str) -> anyhow::Result<PathBuf> {
41 if backend.kind() != BackendKind::Local {
42 return Ok(PathBuf::from(
43 crate::backend::normalize_path_lexically(backend, path)?.as_str(),
44 ));
45 }
46
47 let expanded = shellexpand::tilde(path).to_string();
48 let p = PathBuf::from(&expanded);
49
50 let joined = if p.is_absolute() {
51 p.clone()
52 } else {
53 std::env::current_dir()?.join(&p)
54 };
55
56 let normalized: PathBuf = joined.components().collect();
59
60 let normalized_str = normalized.to_string_lossy();
63 if normalized_str.contains("/../") || normalized_str.ends_with("/..") {
64 anyhow::bail!("Path traversal detected: {}", path);
65 }
66
67 Ok(normalized)
68}
69
70pub fn first_dir_component_exists(path: &Path) -> bool {
74 use std::path::Component;
75 let mut components = path.components();
76 match components.next() {
77 Some(Component::RootDir) => {}
78 _ => return true, }
80 match components.next() {
81 Some(comp) => Path::new("/").join(comp).exists(),
82 None => true, }
84}
85
86pub fn path_points_to_file(raw_path: &str) -> bool {
88 Path::new(raw_path)
89 .file_name()
90 .and_then(|s| s.to_str())
91 .is_some_and(|name| name.contains('.') && !name.starts_with('.') && !name.ends_with('.'))
92}
93
94fn path_root_looks_like_project(dir: &Path) -> bool {
95 PROJECT_ROOT_MARKERS
96 .iter()
97 .any(|marker| dir.join(marker).exists())
98}
99
100pub fn find_nearest_project_root(path: &Path) -> Option<PathBuf> {
102 let mut current = if path.is_dir() {
103 path.to_path_buf()
104 } else {
105 path.parent()?.to_path_buf()
106 };
107 if !current.exists() {
108 return None;
109 }
110
111 loop {
112 if path_root_looks_like_project(¤t) {
113 return Some(current);
114 }
115 if !current.pop() {
116 return None;
117 }
118 }
119}
120
121pub fn normalize_project_scope_path(
125 backend: &dyn ExecutionBackend,
126 path: &str,
127) -> anyhow::Result<PathBuf> {
128 if backend.kind() != BackendKind::Local {
129 let mut normalized = validate_path(backend, path)?;
130 if path_points_to_file(path.trim_end_matches('/'))
131 && let Some(parent) = normalized.parent()
132 {
133 normalized = parent.to_path_buf();
134 }
135 return Ok(normalized);
136 }
137
138 let mut normalized = validate_path(backend, path)?;
139 if !first_dir_component_exists(&normalized) {
140 anyhow::bail!(
141 "Path does not look like a real filesystem location: {}",
142 path
143 );
144 }
145
146 let trimmed = path.trim_end_matches('/');
147 if (normalized.is_file() || (!normalized.exists() && path_points_to_file(trimmed)))
148 && let Some(parent) = normalized.parent()
149 {
150 normalized = parent.to_path_buf();
151 }
152
153 if normalized.exists()
154 && let Some(root) = find_nearest_project_root(&normalized)
155 {
156 normalized = root;
157 }
158
159 Ok(normalized)
160}
161
162pub fn token_is_absolute_like(token: &str) -> bool {
163 let bytes = token.as_bytes();
164 let looks_windows_abs = bytes.len() >= 3
165 && bytes[0].is_ascii_alphabetic()
166 && bytes[1] == b':'
167 && (bytes[2] == b'\\' || bytes[2] == b'/');
168 token.starts_with('/')
169 || token.starts_with("~/")
170 || token.starts_with("./")
171 || token.starts_with("../")
172 || looks_windows_abs
173}
174
175fn join_normalized(base: &Path, token: &str) -> Option<PathBuf> {
178 let expanded = shellexpand::tilde(token).to_string();
179 let path = PathBuf::from(expanded);
180 let joined = if path.is_absolute() {
181 path
182 } else {
183 base.join(path)
184 };
185 let mut normalized = PathBuf::new();
186 for component in joined.components() {
187 match component {
188 std::path::Component::CurDir => {}
189 std::path::Component::ParentDir => {
190 if !normalized.pop() {
191 return None;
192 }
193 }
194 value => normalized.push(value.as_os_str()),
195 }
196 }
197 Some(normalized)
198}
199
200fn relative_reference_base(workspace_anchor: Option<&Path>) -> Option<PathBuf> {
203 match workspace_anchor {
204 Some(anchor) => Some(anchor.to_path_buf()),
205 None => std::env::current_dir().ok(),
206 }
207}
208
209pub fn resolve_structural_filesystem_reference(
224 backend: &dyn ExecutionBackend,
225 raw: &str,
226 alias_roots: &[String],
227) -> Option<PathBuf> {
228 resolve_structural_filesystem_reference_from(backend, raw, alias_roots, None)
229}
230
231pub fn resolve_structural_filesystem_reference_from(
241 backend: &dyn ExecutionBackend,
242 raw: &str,
243 alias_roots: &[String],
244 workspace_anchor: Option<&Path>,
245) -> Option<PathBuf> {
246 let token = raw.trim();
247 if token.is_empty() || token.contains("://") || token.contains('?') || token.contains('*') {
248 return None;
249 }
250
251 let explicit = token_is_absolute_like(token)
252 || token.starts_with("\\\\")
253 || (token.starts_with('.') && (token.contains('/') || token.contains('\\')));
254 let has_separator = token.contains('/') || token.contains('\\');
255
256 if backend.kind() != BackendKind::Local {
257 if explicit {
258 return validate_path(backend, token).ok();
259 }
260 return resolve_projects_folder_alias(backend, token, alias_roots);
261 }
262
263 if workspace_anchor.is_none() && !explicit {
269 return if has_separator {
270 resolve_under_alias_roots(backend, token, alias_roots)
271 } else {
272 None
273 };
274 }
275 let base = relative_reference_base(workspace_anchor)?;
276 let direct = join_normalized(&base, token)?;
277 if explicit && !direct.exists() && !reaches_existing_directory(&direct) {
284 return None;
285 }
286 if explicit || (direct.exists() && (has_separator || direct.is_file())) {
291 return Some(direct);
292 }
293 if !has_separator {
294 return None;
295 }
296
297 if let Some(alias_path) = resolve_projects_folder_alias(backend, token, alias_roots) {
298 return Some(alias_path);
299 }
300
301 let first_component = Path::new(token)
302 .components()
303 .find_map(|component| match component {
304 std::path::Component::Normal(value) => Some(value),
305 _ => None,
306 })?;
307 if base.join(first_component).exists() {
308 return Some(direct);
309 }
310 if workspace_anchor.is_some() {
314 return None;
315 }
316
317 resolve_under_alias_roots(backend, token, alias_roots)
318}
319
320fn resolve_under_alias_roots(
323 backend: &dyn ExecutionBackend,
324 token: &str,
325 alias_roots: &[String],
326) -> Option<PathBuf> {
327 if let Some(alias_path) = resolve_projects_folder_alias(backend, token, alias_roots) {
328 return Some(alias_path);
329 }
330 let first_component = Path::new(token)
331 .components()
332 .find_map(|component| match component {
333 std::path::Component::Normal(value) => Some(value),
334 _ => None,
335 })?;
336 for raw_root in alias_roots {
337 let Ok(root) = validate_path(backend, raw_root) else {
338 continue;
339 };
340 if !root.is_dir() || !root.join(first_component).exists() {
341 continue;
342 }
343 return Some(root.join(token.replace('\\', "/")));
344 }
345 None
346}
347
348fn reaches_existing_directory(path: &Path) -> bool {
350 path.ancestors()
351 .skip(1)
352 .filter(|ancestor| ancestor.parent().is_some())
353 .any(Path::is_dir)
354}
355
356fn push_unique_search_root(roots: &mut Vec<PathBuf>, candidate: PathBuf) {
357 if candidate.is_dir() && !roots.iter().any(|existing| existing == &candidate) {
358 roots.push(candidate);
359 }
360}
361
362const PROJECT_ROOT_CATALOG_TTL: Duration = Duration::from_secs(30);
363
364#[derive(Clone)]
365struct CachedProjectRootCatalog {
366 scanned_at: std::time::Instant,
367 entries: Vec<(String, PathBuf)>,
368}
369
370static PROJECT_ROOT_CATALOG_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedProjectRootCatalog>>> =
371 LazyLock::new(|| Mutex::new(HashMap::new()));
372
373fn project_root_directory_entries(root: &Path) -> Vec<(String, PathBuf)> {
374 if let Ok(cache) = PROJECT_ROOT_CATALOG_CACHE.lock()
375 && let Some(cached) = cache.get(root)
376 && cached.scanned_at.elapsed() <= PROJECT_ROOT_CATALOG_TTL
377 {
378 return cached.entries.clone();
379 }
380
381 let mut entries = Vec::new();
382 let Ok(dir_entries) = std::fs::read_dir(root) else {
383 return entries;
384 };
385 for entry in dir_entries.flatten() {
386 let path = entry.path();
387 if !path.is_dir() {
388 continue;
389 }
390 entries.push((
391 entry.file_name().to_string_lossy().to_ascii_lowercase(),
392 path,
393 ));
394 }
395
396 if let Ok(mut cache) = PROJECT_ROOT_CATALOG_CACHE.lock() {
397 cache.insert(
398 root.to_path_buf(),
399 CachedProjectRootCatalog {
400 scanned_at: std::time::Instant::now(),
401 entries: entries.clone(),
402 },
403 );
404 }
405
406 entries
407}
408
409pub fn project_search_roots(
410 backend: &dyn ExecutionBackend,
411 alias_roots: &[String],
412) -> Vec<PathBuf> {
413 if backend.kind() != BackendKind::Local {
414 let mut roots = Vec::new();
415 for raw_root in alias_roots {
416 if let Ok(root) = validate_path(backend, raw_root)
417 && !roots.iter().any(|existing| existing == &root)
418 {
419 roots.push(root);
420 }
421 }
422 let workspace = PathBuf::from(backend.workspace_root().as_str());
423 if !roots.iter().any(|existing| existing == &workspace) {
424 roots.push(workspace);
425 }
426 return roots;
427 }
428
429 let mut roots = Vec::new();
430 for raw_root in alias_roots {
431 let Ok(root) = validate_path(backend, raw_root) else {
432 continue;
433 };
434 push_unique_search_root(&mut roots, root);
435 }
436
437 if let Ok(cwd) = std::env::current_dir() {
438 if cwd.file_name().is_some_and(|name| name == "projects") {
439 push_unique_search_root(&mut roots, cwd.clone());
440 }
441 push_unique_search_root(&mut roots, cwd.join("projects"));
442 }
443
444 if let Some(home) = dirs::home_dir() {
445 push_unique_search_root(&mut roots, home.join("projects"));
446 }
447
448 roots
449}
450
451pub fn resolve_projects_folder_alias(
452 backend: &dyn ExecutionBackend,
453 raw_path: &str,
454 alias_roots: &[String],
455) -> Option<PathBuf> {
456 let trimmed = raw_path.trim();
457 if token_is_absolute_like(trimmed) {
458 return None;
459 }
460 let relative = trimmed
461 .strip_prefix("./")
462 .unwrap_or(trimmed)
463 .trim_start_matches('/');
464 let starts_with_projects =
465 relative.starts_with("projects/") || relative.starts_with("projects\\");
466 if !starts_with_projects {
467 return None;
468 }
469
470 let suffix = relative
471 .strip_prefix("projects/")
472 .or_else(|| relative.strip_prefix("projects\\"))
473 .unwrap_or("");
474 for root in project_search_roots(backend, alias_roots) {
475 let candidate = if suffix.is_empty() {
476 root
477 } else {
478 root.join(suffix.replace('\\', "/"))
479 };
480 if backend.kind() != BackendKind::Local {
481 return normalize_project_scope_path(backend, candidate.to_string_lossy().as_ref())
482 .ok();
483 }
484 if candidate.parent().is_some_and(|parent| parent.is_dir()) {
485 return Some(candidate);
486 }
487 }
488 None
489}
490
491fn is_single_path_component(token: &str) -> bool {
495 !token.is_empty()
496 && token != "."
497 && token != ".."
498 && !token.contains("://")
499 && !token.contains(['/', '\\'])
500}
501
502pub fn resolve_named_project_root(
503 backend: &dyn ExecutionBackend,
504 raw_name: &str,
505 alias_roots: &[String],
506) -> Option<PathBuf> {
507 let token = raw_name
508 .trim_matches(|c: char| c.is_ascii_whitespace() || c == '`' || c == '\'' || c == '"')
509 .trim_matches(|c: char| matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';' | ':'))
510 .trim_end_matches(['.', '!', '?'])
511 .trim();
512 if !is_single_path_component(token) {
513 return None;
514 }
515
516 let target = token.to_ascii_lowercase();
517 if backend.kind() != BackendKind::Local {
518 return project_search_roots(backend, alias_roots)
519 .into_iter()
520 .find_map(|root| {
521 root.file_name()
522 .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(&target))
523 .then_some(root)
524 });
525 }
526
527 for root in project_search_roots(backend, alias_roots) {
528 let direct = root.join(token);
529 if direct.is_dir()
530 && let Ok(normalized) =
531 normalize_project_scope_path(backend, direct.to_string_lossy().as_ref())
532 {
533 return Some(normalized);
534 }
535
536 for (name, path) in project_root_directory_entries(&root) {
537 if name != target {
538 continue;
539 }
540 if let Ok(normalized) =
541 normalize_project_scope_path(backend, path.to_string_lossy().as_ref())
542 {
543 return Some(normalized);
544 }
545 }
546 }
547 None
548}
549
550#[cfg(test)]
551fn explicit_project_search_roots(
552 backend: &dyn ExecutionBackend,
553 alias_roots: &[String],
554) -> Vec<PathBuf> {
555 if backend.kind() != BackendKind::Local {
556 return alias_roots
557 .iter()
558 .filter_map(|root| validate_path(backend, root).ok())
559 .collect();
560 }
561
562 let mut roots = Vec::new();
563 for raw_root in alias_roots {
564 let Ok(root) = validate_path(backend, raw_root) else {
565 continue;
566 };
567 push_unique_search_root(&mut roots, root);
568 }
569 roots
570}
571
572#[cfg(test)]
573fn resolve_contextual_project_nickname_across_roots(
574 backend: &dyn ExecutionBackend,
575 raw_name: &str,
576 roots: Vec<PathBuf>,
577) -> Option<PathBuf> {
578 let token = raw_name
579 .trim_matches(|c: char| c.is_ascii_whitespace() || c == '`' || c == '\'' || c == '"')
580 .trim_matches(|c: char| matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';' | ':'))
581 .trim_end_matches(['.', '!', '?'])
582 .trim()
583 .to_ascii_lowercase();
584 if token.len() < 3
585 || token.contains("://")
586 || token.contains('/')
587 || token.contains('\\')
588 || !token.chars().any(|c| c.is_ascii_alphabetic())
589 || token.chars().all(|c| c.is_ascii_digit())
590 {
591 return None;
592 }
593
594 if backend.kind() != BackendKind::Local {
595 return roots.into_iter().find(|root| {
596 root.file_name()
597 .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(&token))
598 });
599 }
600
601 let mut matches = Vec::new();
602 let dotted = format!("{token}.");
603 let dashed = format!("{token}-");
604 let underscored = format!("{token}_");
605 for root in roots {
606 for (name, path) in project_root_directory_entries(&root) {
607 if name != token
608 && !name.starts_with(&dotted)
609 && !name.starts_with(&dashed)
610 && !name.starts_with(&underscored)
611 {
612 continue;
613 }
614 let Ok(normalized) =
615 normalize_project_scope_path(backend, path.to_string_lossy().as_ref())
616 else {
617 continue;
618 };
619 if find_nearest_project_root(&normalized).is_none_or(|root| root != normalized) {
620 continue;
621 }
622 if !matches.iter().any(|existing| existing == &normalized) {
623 matches.push(normalized);
624 }
625 }
626 }
627
628 if matches.len() == 1 {
629 matches.into_iter().next()
630 } else {
631 None
632 }
633}
634
635#[cfg(test)]
636pub fn resolve_contextual_project_nickname(
637 backend: &dyn ExecutionBackend,
638 raw_name: &str,
639 alias_roots: &[String],
640) -> Option<PathBuf> {
641 resolve_contextual_project_nickname_across_roots(
642 backend,
643 raw_name,
644 project_search_roots(backend, alias_roots),
645 )
646}
647
648#[cfg(test)]
649pub fn resolve_contextual_project_nickname_in_explicit_roots(
650 backend: &dyn ExecutionBackend,
651 raw_name: &str,
652 alias_roots: &[String],
653) -> Option<PathBuf> {
654 let explicit_roots = explicit_project_search_roots(backend, alias_roots);
655 if explicit_roots.is_empty() {
656 return resolve_contextual_project_nickname(backend, raw_name, alias_roots);
657 }
658 resolve_contextual_project_nickname_across_roots(backend, raw_name, explicit_roots)
659}
660
661#[cfg(test)]
665pub fn resolve_project_scope_reference(
666 backend: &dyn ExecutionBackend,
667 raw: &str,
668 alias_roots: &[String],
669) -> Option<PathBuf> {
670 resolve_project_scope_reference_from(backend, raw, alias_roots, None)
671}
672
673pub fn resolve_project_scope_reference_from(
682 backend: &dyn ExecutionBackend,
683 raw: &str,
684 alias_roots: &[String],
685 workspace_anchor: Option<&Path>,
686) -> Option<PathBuf> {
687 let trimmed = raw.trim();
688 if trimmed.is_empty() {
689 return None;
690 }
691
692 let looks_path_like =
693 token_is_absolute_like(trimmed) || trimmed.contains('/') || trimmed.contains('\\');
694 if looks_path_like {
695 if backend.kind() != BackendKind::Local {
696 return normalize_project_scope_path(backend, trimmed).ok();
697 }
698 let path_for_resolution = if token_is_absolute_like(trimmed) {
699 trimmed.to_string()
700 } else {
701 let base = relative_reference_base(workspace_anchor);
702 let base_relative = base.and_then(|base| join_normalized(&base, trimmed));
703 if let Some(candidate) = base_relative {
704 if candidate.exists() {
705 candidate.to_string_lossy().to_string()
706 } else if let Some(alias_candidate) =
707 resolve_projects_folder_alias(backend, trimmed, alias_roots)
708 {
709 alias_candidate.to_string_lossy().to_string()
710 } else {
711 candidate.to_string_lossy().to_string()
712 }
713 } else if let Some(alias_candidate) =
714 resolve_projects_folder_alias(backend, trimmed, alias_roots)
715 {
716 alias_candidate.to_string_lossy().to_string()
717 } else {
718 trimmed.to_string()
719 }
720 };
721 return normalize_project_scope_path(backend, &path_for_resolution).ok();
722 }
723
724 resolve_named_project_root(backend, trimmed, alias_roots)
725}
726
727pub fn local_backup_path(backup_root: &Path, path: &Path) -> Option<PathBuf> {
734 use sha2::{Digest, Sha256};
735 let digest = Sha256::digest(path.to_string_lossy().as_bytes());
736 let tag: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
737 let name = path.file_name()?.to_string_lossy();
738 Some(backup_root.join(format!("{tag}-{name}")))
739}
740
741pub async fn backup_before_overwrite(
747 backend: &crate::backend::SharedExecutionBackend,
748 path: &BackendPath,
749 backup_root: Option<&Path>,
750) {
751 if backend.kind() == BackendKind::Local
752 && let Some(backup) =
753 backup_root.and_then(|root| local_backup_path(root, Path::new(path.as_str())))
754 {
755 if let Some(dir) = backup.parent() {
756 let _ = tokio::fs::create_dir_all(dir).await;
757 }
758 let _ = tokio::fs::copy(path.as_str(), &backup).await;
759 return;
760 }
761 let backup = path.with_extension(&format!("{}.bak", path.extension().unwrap_or_default()));
762 let _ = backend.copy(path, &backup).await;
763}
764
765pub fn is_protected_host_data_path(path: &Path) -> bool {
775 if !path.is_absolute() {
776 return false;
777 }
778
779 #[cfg(unix)]
780 {
781 const PROTECTED_ROOTS: &[&str] = &[
782 "/System",
783 "/Library",
784 "/bin",
785 "/sbin",
786 "/usr",
787 "/etc",
788 "/private/etc",
789 "/private/var/root",
790 "/var/root",
791 "/dev",
792 "/proc",
793 "/sys",
794 ];
795 if PROTECTED_ROOTS
796 .iter()
797 .any(|root| path == Path::new(root) || path.starts_with(root))
798 {
799 return true;
800 }
801 }
802
803 #[cfg(windows)]
804 {
805 let normalized = path
806 .to_string_lossy()
807 .replace('/', "\\")
808 .to_ascii_lowercase();
809 if [
810 "c:\\windows",
811 "c:\\program files",
812 "c:\\program files (x86)",
813 ]
814 .iter()
815 .any(|root| normalized == *root || normalized.starts_with(&format!("{root}\\")))
816 {
817 return true;
818 }
819 }
820
821 false
822}
823
824#[cfg_attr(not(test), allow(dead_code))]
826pub async fn is_binary_file(path: &Path) -> anyhow::Result<bool> {
827 use tokio::io::AsyncReadExt;
828 let mut file = tokio::fs::File::open(path).await?;
829 let mut buf = vec![0u8; 8192];
830 let n = file.read(&mut buf).await?;
831 Ok(buf[..n].contains(&0))
832}
833
834#[derive(Debug)]
836pub struct CommandOutput {
837 pub exit_code: i32,
838 pub stdout: String,
839 pub stderr: String,
840 pub duration_ms: u64,
841}
842
843pub async fn run_cmd(
845 backend: &dyn ExecutionBackend,
846 cmd: &str,
847 working_dir: Option<&Path>,
848 timeout_secs: u64,
849) -> anyhow::Result<CommandOutput> {
850 let working_dir = match working_dir {
851 Some(dir) => Some(backend.resolve_path(&dir.to_string_lossy()).await?),
852 None => None,
853 };
854 run_cmd_backend(backend, cmd, working_dir.as_ref(), timeout_secs).await
855}
856
857pub async fn run_cmd_backend(
860 backend: &dyn ExecutionBackend,
861 cmd: &str,
862 working_dir: Option<&BackendPath>,
863 timeout_secs: u64,
864) -> anyhow::Result<CommandOutput> {
865 let mut request = ExecutionRequest::shell(cmd);
866 request.cwd = working_dir.cloned();
867 let output = backend
868 .execute(request, Duration::from_secs(timeout_secs))
869 .await?;
870 if output.timed_out {
871 return Err(
872 crate::ToolTimedOut(format!("Command timed out after {}s", timeout_secs)).into(),
873 );
874 }
875 Ok(CommandOutput {
876 exit_code: output.exit_code,
877 stdout: output.stdout_lossy(),
878 stderr: output.stderr_lossy(),
879 duration_ms: output.duration_ms,
880 })
881}
882
883pub fn should_skip_dir(name: &str) -> bool {
885 DEFAULT_IGNORE_DIRS.contains(&name)
886}
887
888pub fn is_test_file(path: &Path) -> bool {
890 let name = path
891 .file_name()
892 .map(|n| n.to_string_lossy().to_string())
893 .unwrap_or_default();
894 let lower = name.to_lowercase();
895 (lower.starts_with("test_") && lower.ends_with(".py"))
896 || (lower.ends_with("_test.py"))
897 || (lower.starts_with("test_") && lower.ends_with(".js"))
898 || (lower.ends_with(".test.js"))
899 || (lower.ends_with(".test.ts"))
900 || (lower.ends_with(".spec.js"))
901 || (lower.ends_with(".spec.ts"))
902}
903
904pub async fn validate_python_syntax(backend: &dyn ExecutionBackend, path: &Path) -> Option<String> {
907 if path.extension().map(|e| e == "py").unwrap_or(false) {
908 let path_str = path.to_string_lossy();
909 let cmd = format!(
910 "python3 -c \"import py_compile; py_compile.compile('{}', doraise=True)\"",
911 path_str.replace('\'', "'\\''")
912 );
913 match run_cmd(backend, &cmd, None, 5).await {
914 Ok(output) if output.exit_code != 0 => {
915 let error = if !output.stderr.is_empty() {
916 output.stderr.trim().to_string()
917 } else {
918 output.stdout.trim().to_string()
919 };
920 let relevant: String = error
922 .lines()
923 .filter(|l| {
924 l.contains("SyntaxError")
925 || l.contains("IndentationError")
926 || l.contains("TabError")
927 || l.trim().starts_with("File ")
928 || l.trim().starts_with('^')
929 })
930 .collect::<Vec<_>>()
931 .join("\n");
932 if relevant.is_empty() {
933 Some(error)
934 } else {
935 Some(relevant)
936 }
937 }
938 _ => None,
939 }
940 } else {
941 None
942 }
943}
944
945pub async fn post_write_diagnostics(backend: &dyn ExecutionBackend, path: &Path) -> String {
948 let mut notes = Vec::new();
949
950 if let Some(syntax_err) = validate_python_syntax(backend, path).await {
952 notes.push(format!(
953 "\n⚠ SYNTAX ERROR detected in written file:\n{}\nFix the syntax error before proceeding.",
954 syntax_err
955 ));
956 }
957
958 if is_test_file(path) {
960 notes.push(
961 "\n⚠ WARNING: You modified a test file. If your task is to implement code that passes tests, \
962you should NOT modify the test file — implement the module to pass the tests as-is."
963 .to_string(),
964 );
965 }
966
967 notes.join("")
968}
969
970#[cfg(test)]
971mod tests {
972 use super::*;
973 #[allow(unused_imports)]
974 use crate::backend::{BackendKind, BackendPath, ExecutionBackend};
975 use std::io::Write;
976 #[allow(unused_imports)]
977 use std::path::{Path, PathBuf};
978 #[allow(unused_imports)]
979 use std::time::Duration;
980
981 #[test]
982 fn test_validate_path_home() {
983 let result = validate_path(&*crate::testing::active_execution_backend(), "~/test.txt");
984 assert!(result.is_ok());
985 let p = result.unwrap();
986 assert!(p.is_absolute());
987 assert!(!p.to_string_lossy().contains('~'));
988 }
989
990 #[test]
991 fn test_validate_path_traversal() {
992 let result = validate_path(
993 &*crate::testing::active_execution_backend(),
994 "/tmp/../../etc/passwd",
995 );
996 assert!(result.is_err());
997 }
998
999 #[test]
1000 fn test_validate_path_absolute() {
1001 let result = validate_path(
1002 &*crate::testing::active_execution_backend(),
1003 "/tmp/test.txt",
1004 );
1005 assert!(result.is_ok());
1006 }
1007
1008 #[test]
1009 fn test_validate_path_dot_normalized() {
1010 let result = validate_path(&*crate::testing::active_execution_backend(), ".").unwrap();
1012 let result_str = result.to_string_lossy();
1013 assert!(
1014 !result_str.ends_with("/."),
1015 "validate_path(\".\") should not end with trailing dot, got: {}",
1016 result_str
1017 );
1018 assert_eq!(result, std::env::current_dir().unwrap());
1019 }
1020
1021 #[test]
1022 fn test_validate_path_subdir_dot_normalized() {
1023 let result = validate_path(&*crate::testing::active_execution_backend(), "src/.").unwrap();
1025 let result_str = result.to_string_lossy();
1026 assert!(
1027 !result_str.ends_with("/."),
1028 "validate_path(\"src/.\") should not end with trailing dot, got: {}",
1029 result_str
1030 );
1031 }
1032
1033 #[test]
1034 fn test_first_dir_component_exists() {
1035 assert!(first_dir_component_exists(Path::new("/tmp/test")));
1036 assert!(!first_dir_component_exists(Path::new("/api/notes")));
1037 assert!(first_dir_component_exists(Path::new("src/main.rs")));
1038 }
1039
1040 #[test]
1041 fn test_path_points_to_file() {
1042 assert!(path_points_to_file("src/main.rs"));
1043 assert!(path_points_to_file("/tmp/app/package.json"));
1044 assert!(!path_points_to_file("/tmp/app/src"));
1045 assert!(!path_points_to_file(".hidden"));
1046 }
1047
1048 #[test]
1049 fn test_find_nearest_project_root_prefers_nearest_marker() {
1050 let dir = tempfile::tempdir().unwrap();
1051 let root = dir.path().join("repo");
1052 let app = root.join("apps").join("web");
1053 let src = app.join("src");
1054 std::fs::create_dir_all(&src).unwrap();
1055 std::fs::write(root.join("pnpm-workspace.yaml"), "packages:\n - apps/*\n").unwrap();
1056 std::fs::write(app.join("package.json"), r#"{"name":"web"}"#).unwrap();
1057
1058 let found = find_nearest_project_root(&src).expect("nearest project root");
1059 assert_eq!(found, app);
1060 }
1061
1062 #[test]
1063 fn test_normalize_project_scope_path_promotes_existing_subdir_to_project_root() {
1064 let dir = tempfile::tempdir().unwrap();
1065 let root = dir.path().join("repo");
1066 let src = root.join("src");
1067 std::fs::create_dir_all(&src).unwrap();
1068 std::fs::write(root.join("package.json"), r#"{"name":"demo"}"#).unwrap();
1069
1070 let normalized = normalize_project_scope_path(
1071 &*crate::testing::active_execution_backend(),
1072 src.to_string_lossy().as_ref(),
1073 )
1074 .expect("normalized");
1075 assert_eq!(normalized, root);
1076 }
1077
1078 #[test]
1079 fn test_normalize_project_scope_path_keeps_non_project_target_dir() {
1080 let dir = tempfile::tempdir().unwrap();
1081 let target = dir.path().join("new-site");
1082 let normalized = normalize_project_scope_path(
1083 &*crate::testing::active_execution_backend(),
1084 target.to_string_lossy().as_ref(),
1085 )
1086 .expect("normalized");
1087 assert_eq!(normalized, target);
1088 }
1089
1090 #[test]
1091 fn test_normalize_project_scope_path_preserves_existing_dotted_directory() {
1092 let dir = tempfile::tempdir().unwrap();
1093 let target = dir.path().join("blog.aidaemon.ai");
1094 std::fs::create_dir_all(&target).unwrap();
1095 std::fs::write(target.join("wrangler.toml"), "name = \"blog\"\n").unwrap();
1096
1097 let normalized = normalize_project_scope_path(
1098 &*crate::testing::active_execution_backend(),
1099 target.to_string_lossy().as_ref(),
1100 )
1101 .expect("normalized");
1102 assert_eq!(normalized, target);
1103 }
1104
1105 #[test]
1106 fn test_resolve_named_project_root_from_alias_roots() {
1107 let dir = tempfile::tempdir().unwrap();
1108 let alias_root = dir.path().join("projects");
1109 let project = alias_root.join("blog.aidaemon.ai");
1110 std::fs::create_dir_all(&project).unwrap();
1111 std::fs::write(project.join("wrangler.toml"), "name = \"blog\"\n").unwrap();
1112
1113 let resolved = resolve_named_project_root(
1114 &*crate::testing::active_execution_backend(),
1115 "blog.aidaemon.ai",
1116 &[alias_root.to_string_lossy().to_string()],
1117 )
1118 .expect("resolved");
1119 assert_eq!(resolved, project);
1120 }
1121
1122 #[test]
1123 fn a_plain_project_name_resolves_by_the_folders_that_exist() {
1124 let dir = tempfile::tempdir().unwrap();
1127 let alias_root = dir.path().join("projects");
1128 let project = alias_root.join("widget");
1129 std::fs::create_dir_all(&project).unwrap();
1130 let roots = [alias_root.to_string_lossy().to_string()];
1131 let backend = crate::testing::active_execution_backend();
1132 let resolved = resolve_named_project_root(&*backend, "widget", &roots).expect("resolved");
1133 assert_eq!(
1134 std::fs::canonicalize(resolved).unwrap(),
1135 std::fs::canonicalize(&project).unwrap()
1136 );
1137 assert!(
1138 resolve_named_project_root(&*backend, "synthetic-missing-project-7f3", &roots)
1139 .is_none()
1140 );
1141 assert!(resolve_named_project_root(&*backend, "a/widget", &roots).is_none());
1142 }
1143
1144 #[test]
1145 fn test_resolve_contextual_project_nickname_in_explicit_roots_prefers_alias_roots() {
1146 let dir = tempfile::tempdir().unwrap();
1147 let alias_root = dir.path().join("projects");
1148 let project = alias_root.join("springfield-il-site");
1149 std::fs::create_dir_all(&project).unwrap();
1150 std::fs::write(project.join("wrangler.toml"), "name = \"springfield\"\n").unwrap();
1151
1152 let resolved = resolve_contextual_project_nickname_in_explicit_roots(
1153 &*crate::testing::active_execution_backend(),
1154 "springfield",
1155 &[alias_root.to_string_lossy().to_string()],
1156 )
1157 .expect("resolved");
1158 assert_eq!(resolved, project);
1159 }
1160
1161 #[test]
1162 fn test_resolve_project_scope_reference_handles_named_and_projects_alias_inputs() {
1163 let dir = tempfile::tempdir().unwrap();
1164 let alias_root = dir.path().join("projects");
1165 let project = alias_root.join("blog.aidaemon.ai");
1166 std::fs::create_dir_all(&project).unwrap();
1167 std::fs::write(project.join("wrangler.toml"), "name = \"blog\"\n").unwrap();
1168 let alias_roots = vec![alias_root.to_string_lossy().to_string()];
1169
1170 let named = resolve_project_scope_reference(
1171 &*crate::testing::active_execution_backend(),
1172 "blog.aidaemon.ai",
1173 &alias_roots,
1174 )
1175 .expect("named project");
1176 assert_eq!(named, project);
1177
1178 let aliased = resolve_project_scope_reference(
1179 &*crate::testing::active_execution_backend(),
1180 "projects/blog.aidaemon.ai",
1181 &alias_roots,
1182 )
1183 .expect("aliased project");
1184 assert_eq!(aliased, project);
1185 }
1186
1187 #[test]
1188 fn structural_filesystem_references_require_path_evidence() {
1189 let dir = tempfile::tempdir().unwrap();
1190 let alias_root = dir.path().join("projects");
1191 let source = alias_root.join("synthetic-project").join("src");
1192 std::fs::create_dir_all(&source).unwrap();
1193 let alias_roots = vec![alias_root.to_string_lossy().to_string()];
1194
1195 for prose in [
1196 "Pros/cons",
1197 "input/output",
1198 "client/server",
1199 "read/write",
1200 "pass/fail",
1201 "alpha/beta/gamma",
1202 ] {
1203 assert_eq!(
1204 resolve_structural_filesystem_reference(
1205 &*crate::testing::active_execution_backend(),
1206 prose,
1207 &alias_roots
1208 ),
1209 None,
1210 "unanchored prose compound must not become a path: {prose}"
1211 );
1212 }
1213
1214 assert_eq!(
1215 resolve_structural_filesystem_reference(
1216 &*crate::testing::active_execution_backend(),
1217 "synthetic-project/src/new_module.rs",
1218 &alias_roots
1219 ),
1220 Some(source.join("new_module.rs"))
1221 );
1222
1223 let explicit_new_target = dir.path().join("not-created-yet").join("result.md");
1224 assert_eq!(
1225 resolve_structural_filesystem_reference(
1226 &*crate::testing::active_execution_backend(),
1227 explicit_new_target.to_string_lossy().as_ref(),
1228 &alias_roots
1229 ),
1230 Some(explicit_new_target)
1231 );
1232 }
1233
1234 #[test]
1235 fn protected_host_data_is_separate_from_workspace_and_temporary_data() {
1236 #[cfg(unix)]
1237 {
1238 assert!(is_protected_host_data_path(Path::new("/etc/hosts")));
1239 assert!(is_protected_host_data_path(Path::new(
1240 "/private/var/root/result.txt"
1241 )));
1242 assert!(!is_protected_host_data_path(Path::new(
1243 "/tmp/synthetic-result.txt"
1244 )));
1245 assert!(!is_protected_host_data_path(Path::new(
1246 "/workspace/synthetic-project/src/main.rs"
1247 )));
1248 }
1249 }
1250
1251 #[tokio::test]
1252 async fn test_is_binary_file_text() {
1253 let mut f = tempfile::NamedTempFile::new().unwrap();
1254 write!(f, "Hello, world!\nLine 2\n").unwrap();
1255 assert!(!is_binary_file(f.path()).await.unwrap());
1256 }
1257
1258 #[tokio::test]
1259 async fn test_is_binary_file_binary() {
1260 let mut f = tempfile::NamedTempFile::new().unwrap();
1261 f.write_all(&[0xFF, 0xD8, 0xFF, 0x00, 0x10]).unwrap();
1262 assert!(is_binary_file(f.path()).await.unwrap());
1263 }
1264
1265 #[test]
1266 fn test_format_with_line_numbers() {
1267 let result = crate::format_with_line_numbers("foo\nbar\nbaz", 0);
1268 assert!(result.contains(" 1 | foo"));
1269 assert!(result.contains(" 2 | bar"));
1270 assert!(result.contains(" 3 | baz"));
1271 }
1272
1273 #[test]
1274 fn test_format_with_line_numbers_offset() {
1275 let result = crate::format_with_line_numbers("line10\nline11", 9);
1276 assert!(result.contains("10 | line10"));
1277 assert!(result.contains("11 | line11"));
1278 }
1279
1280 #[tokio::test]
1281 async fn test_run_cmd_echo() {
1282 let out = run_cmd(
1283 &*crate::testing::active_execution_backend(),
1284 "echo hello",
1285 None,
1286 5,
1287 )
1288 .await
1289 .unwrap();
1290 assert_eq!(out.exit_code, 0);
1291 assert_eq!(out.stdout.trim(), "hello");
1292 }
1293
1294 #[tokio::test]
1295 async fn test_run_cmd_timeout() {
1296 let result = run_cmd(
1297 &*crate::testing::active_execution_backend(),
1298 "sleep 10",
1299 None,
1300 1,
1301 )
1302 .await;
1303 assert!(result.is_err());
1304 assert!(result.unwrap_err().to_string().contains("timed out"));
1305 }
1306
1307 #[cfg(unix)]
1308 #[tokio::test]
1309 async fn test_run_cmd_timeout_kills_child_process_group() {
1310 let dir = tempfile::tempdir().unwrap();
1311 let marker = dir.path().join("leaked.txt");
1312 let cmd = format!(
1313 "(sleep 2; echo leaked > \"{}\") & wait",
1314 marker.to_string_lossy()
1315 );
1316
1317 let result = run_cmd(&*crate::testing::active_execution_backend(), &cmd, None, 1).await;
1318 assert!(result.is_err());
1319 assert!(result.unwrap_err().to_string().contains("timed out"));
1320
1321 tokio::time::sleep(Duration::from_secs(3)).await;
1322 assert!(
1323 !marker.exists(),
1324 "timed out command should not leave detached child writing files"
1325 );
1326 }
1327
1328 #[tokio::test]
1329 async fn test_run_cmd_working_dir() {
1330 let dir = tempfile::tempdir().unwrap();
1331 let out = run_cmd(
1332 &*crate::testing::active_execution_backend(),
1333 "pwd",
1334 Some(dir.path()),
1335 5,
1336 )
1337 .await
1338 .unwrap();
1339 assert_eq!(out.exit_code, 0);
1340 }
1341
1342 #[test]
1343 fn test_should_skip_dir() {
1344 assert!(should_skip_dir(".git"));
1345 assert!(should_skip_dir("node_modules"));
1346 assert!(should_skip_dir("target"));
1347 assert!(!should_skip_dir("src"));
1348 assert!(!should_skip_dir("lib"));
1349 }
1350
1351 #[test]
1354 fn anchored_relative_reference_resolves_inside_workspace_not_cwd() {
1355 let dir = tempfile::tempdir().unwrap();
1356 let workspace = dir.path().join("blog-site");
1357 std::fs::create_dir_all(workspace.join("src").join("content").join("posts")).unwrap();
1358 let cwd = std::env::current_dir().unwrap();
1359 assert!(
1360 cwd.join("src").is_dir(),
1361 "test precondition: the daemon cwd has a competing src/ directory"
1362 );
1363
1364 let resolved = resolve_structural_filesystem_reference_from(
1365 &*crate::testing::active_execution_backend(),
1366 "src/content/posts",
1367 &[],
1368 Some(&workspace),
1369 )
1370 .expect("workspace-anchored reference");
1371 assert_eq!(resolved, workspace.join("src/content/posts"));
1372 assert!(!resolved.starts_with(&cwd));
1373
1374 let unanchored = resolve_structural_filesystem_reference(
1377 &*crate::testing::active_execution_backend(),
1378 "src/content/posts",
1379 &[],
1380 );
1381 assert_eq!(unanchored, None);
1382 }
1383
1384 #[test]
1388 fn anchored_reference_never_relocates_to_alias_roots() {
1389 let dir = tempfile::tempdir().unwrap();
1390 let alias_root = dir.path().join("projects");
1391 std::fs::create_dir_all(alias_root.join("other-project").join("src")).unwrap();
1392 let workspace = dir.path().join("workspace-without-src");
1393 std::fs::create_dir_all(&workspace).unwrap();
1394 let alias_roots = vec![alias_root.to_string_lossy().to_string()];
1395
1396 assert_eq!(
1397 resolve_structural_filesystem_reference_from(
1398 &*crate::testing::active_execution_backend(),
1399 "src/content/posts",
1400 &alias_roots,
1401 Some(&workspace)
1402 ),
1403 None
1404 );
1405
1406 assert_eq!(
1409 resolve_structural_filesystem_reference_from(
1410 &*crate::testing::active_execution_backend(),
1411 "./src/content/posts",
1412 &alias_roots,
1413 Some(&workspace)
1414 ),
1415 Some(workspace.join("src/content/posts"))
1416 );
1417 assert_eq!(
1418 resolve_structural_filesystem_reference_from(
1419 &*crate::testing::active_execution_backend(),
1420 "../escape",
1421 &alias_roots,
1422 Some(&workspace)
1423 ),
1424 Some(dir.path().join("escape"))
1425 );
1426 }
1427
1428 #[test]
1429 fn anchored_project_scope_reference_promotes_to_workspace_root() {
1430 let dir = tempfile::tempdir().unwrap();
1431 let workspace = dir.path().join("blog-site");
1432 std::fs::create_dir_all(workspace.join(".git")).unwrap();
1433 std::fs::create_dir_all(workspace.join("src").join("content").join("posts")).unwrap();
1434
1435 let scope = resolve_project_scope_reference_from(
1436 &*crate::testing::active_execution_backend(),
1437 "src/content/posts",
1438 &[],
1439 Some(&workspace),
1440 )
1441 .expect("anchored project scope");
1442 assert_eq!(scope, workspace);
1443
1444 let cwd = std::env::current_dir().unwrap();
1448 let unanchored = resolve_project_scope_reference(
1449 &*crate::testing::active_execution_backend(),
1450 "src/content/posts",
1451 &[],
1452 )
1453 .expect("unanchored project scope resolves against the process cwd");
1454 assert!(
1455 unanchored.starts_with(&cwd),
1456 "{unanchored:?} should be rooted in {cwd:?}"
1457 );
1458 assert!(!unanchored.starts_with(&workspace));
1459 }
1460}