Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/cg-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod fileflags;
pub mod hash;
pub mod ids;
pub mod kinds;
pub mod path;
pub mod text;

pub use error::{CgError, Result};
Expand Down
185 changes: 185 additions & 0 deletions crates/cg-core/src/path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
//! Path canonicalization helpers shared across crates.
//!
//! On Windows, `std::fs::canonicalize` returns verbatim (`\\?\`) paths such as
//! `\\?\C:\repo` or `\\?\UNC\server\share`. Many downstream consumers (`cmd.exe`,
//! MCP clients, JSON scripts) reject or fail to match verbatim prefixes.
//! [`canonicalize`] strips the verbatim prefix whenever the resulting normal
//! Win32 path has identical semantics, keeping `\\?\` only when required
//! (paths >= `MAX_PATH`, reserved DOS device names, trailing dots/spaces, etc.).

use std::io;
use std::path::{Path, PathBuf};

/// Canonicalize `path`, stripping the Windows verbatim (`\\?\`) prefix when safe.
pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
let p = std::fs::canonicalize(path)?;
#[cfg(windows)]
{
Ok(strip_windows_verbatim(p))
}
#[cfg(not(windows))]
{
Ok(p)
}
}

/// Strip a Windows verbatim prefix (`\\?\C:\...` or `\\?\UNC\...`) if the normal
/// Win32 path refers to the exact same filesystem location.
#[cfg(any(windows, test))]
fn strip_windows_verbatim(path: PathBuf) -> PathBuf {
let Some(s) = path.to_str() else { return path };
match strip_windows_verbatim_str(s) {
Some(clean) => PathBuf::from(clean),
None => path,
}
}

#[cfg(any(windows, test))]
fn strip_windows_verbatim_str(s: &str) -> Option<String> {
const MAX_PATH_UTF16: usize = 260;

let (candidate, tail) = if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
// Must have non-empty `server\share` after `\\?\UNC\`.
let mut parts = rest.split('\\');
let server = parts.next().filter(|p| !p.is_empty())?;
let share = parts.next().filter(|p| !p.is_empty())?;
let _ = (server, share);
(format!(r"\\{rest}"), rest)
} else {
let rest = s.strip_prefix(r"\\?\")?;
let b = rest.as_bytes();
if b.len() < 3 || !b[0].is_ascii_alphabetic() || b[1] != b':' || b[2] != b'\\' {
return None;
}
(rest.to_owned(), &rest[3..])
};

// MAX_PATH (260 UTF-16 code units) includes the terminating NUL.
if candidate.encode_utf16().count() >= MAX_PATH_UTF16 {
return None;
}

if tail.starts_with('\\') || tail.contains('/') || tail.contains(r"\\") {
return None;
}

for seg in tail.split('\\') {
if seg.is_empty() {
// Trailing slash on a drive root (`C:\`) yields a single empty segment.
continue;
}
if !is_safe_win32_component(seg) {
return None;
}
}

Some(candidate)
}

#[cfg(any(windows, test))]
fn is_safe_win32_component(seg: &str) -> bool {
if seg == "." || seg == ".." || seg.ends_with(' ') || seg.ends_with('.') {
return false;
}
if seg.bytes().any(|b| b < 0x20 || matches!(b, b'<' | b'>' | b':' | b'"' | b'|' | b'?' | b'*')) {
return false;
}
// Win32 treats DOS device names as reserved even with extensions (e.g. `NUL.txt`),
// and strips trailing spaces before the first dot (`CON .txt`).
let stem = seg.split('.').next().unwrap_or(seg).trim_end_matches(' ');
!is_reserved_dos_device(stem)
}

#[cfg(any(windows, test))]
fn is_reserved_dos_device(stem: &str) -> bool {
if stem.eq_ignore_ascii_case("CON")
|| stem.eq_ignore_ascii_case("PRN")
|| stem.eq_ignore_ascii_case("AUX")
|| stem.eq_ignore_ascii_case("NUL")
|| stem.eq_ignore_ascii_case("CONIN$")
|| stem.eq_ignore_ascii_case("CONOUT$")
{
return true;
}
let mut chars = stem.chars();
let (Some(a), Some(b), Some(c), Some(d), None) = (chars.next(), chars.next(), chars.next(), chars.next(), chars.next()) else {
return false;
};
let prefix_ok = (a.eq_ignore_ascii_case(&'c') && b.eq_ignore_ascii_case(&'o') && c.eq_ignore_ascii_case(&'m'))
|| (a.eq_ignore_ascii_case(&'l') && b.eq_ignore_ascii_case(&'p') && c.eq_ignore_ascii_case(&'t'));
prefix_ok && matches!(d, '1'..='9' | '\u{00B9}' | '\u{00B2}' | '\u{00B3}')
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn strips_normal_drive_and_unc_verbatim_paths() {
assert_eq!(strip_windows_verbatim_str(r"\\?\C:\Users\alice\repo").as_deref(), Some(r"C:\Users\alice\repo"));
assert_eq!(strip_windows_verbatim_str(r"\\?\D:\").as_deref(), Some(r"D:\"));
assert_eq!(strip_windows_verbatim_str(r"\\?\UNC\fileserver\share\repo").as_deref(), Some(r"\\fileserver\share\repo"));
assert_eq!(strip_windows_verbatim(PathBuf::from(r"\\?\C:\Users\alice\repo")), PathBuf::from(r"C:\Users\alice\repo"));
assert_eq!(strip_windows_verbatim(PathBuf::from(r"\\?\C:\repo\nul")), PathBuf::from(r"\\?\C:\repo\nul"));
}

#[test]
fn leaves_non_verbatim_and_special_prefixes_untouched() {
assert_eq!(strip_windows_verbatim_str(r"C:\Users\alice\repo"), None);
assert_eq!(strip_windows_verbatim_str("/usr/local/bin/cgr"), None);
assert_eq!(strip_windows_verbatim_str(r"\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\repo"), None);
assert_eq!(strip_windows_verbatim_str(r"\\?\GLOBALROOT\Device\HarddiskVolume1\repo"), None);
assert_eq!(strip_windows_verbatim_str(r"\\?\C:"), None);
assert_eq!(strip_windows_verbatim_str(r"\\?\UNC\onlyserver"), None);
}

#[test]
fn preserves_verbatim_when_path_exceeds_max_path() {
let deep = format!(r"\\?\C:\{}", "a".repeat(257)); // candidate length 260 UTF-16 code units
assert_eq!(strip_windows_verbatim_str(&deep), None);

let just_under = format!(r"\\?\C:\{}", "a".repeat(256)); // candidate length 259
assert!(strip_windows_verbatim_str(&just_under).is_some());
}

#[test]
fn preserves_verbatim_for_reserved_or_unsafe_win32_components() {
for p in [
r"\\?\C:\repo\nul",
r"\\?\C:\repo\CON.txt",
r"\\?\C:\repo\CON .txt",
r"\\?\C:\repo\CONIN$",
r"\\?\C:\repo\conout$.log",
r"\\?\C:\repo\COM1\file.rs",
r"\\?\C:\repo\COM¹\file.rs",
r"\\?\C:\repo\lpt9.log",
r"\\?\C:\repo\lpt³.log",
r"\\?\C:\repo\trailing.",
r"\\?\C:\repo\trailing ",
r"\\?\C:\repo\..\other",
r"\\?\C:\repo\with/slash",
r"\\?\C:\\double_after_root",
r"\\?\C:\\",
r"\\?\C:\repo\\double",
r"\\?\C:\repo\bad:name",
] {
assert_eq!(strip_windows_verbatim_str(p), None, "should preserve verbatim for {p}");
}
// Names that merely look similar to reserved devices are safe.
assert_eq!(strip_windows_verbatim_str(r"\\?\C:\repo\console\null_ptr.rs").as_deref(), Some(r"C:\repo\console\null_ptr.rs"));
assert_eq!(strip_windows_verbatim_str(r"\\?\C:\repo\com0\lpt0.rs").as_deref(), Some(r"C:\repo\com0\lpt0.rs"));
}

#[test]
fn canonicalize_returns_clean_path_for_existing_dir() {
let dir = std::env::temp_dir();
let canon = canonicalize(&dir).expect("temp_dir should canonicalize");
assert!(canon.is_absolute());
#[cfg(windows)]
if let Some(s) = canon.to_str() {
if s.encode_utf16().count() < 260 {
assert!(!s.starts_with(r"\\?\"), "unexpected verbatim prefix: {s}");
}
}
}
}
14 changes: 11 additions & 3 deletions crates/cg-mcp/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,14 @@ impl Server {
ToolOutput::ok(text)
}

fn locate_store(start: &Path) -> Option<Store> {
let normalized = cg_core::path::canonicalize(start).unwrap_or_else(|_| start.to_path_buf());
Store::locate(&normalized).map(|s| {
let root = cg_core::path::canonicalize(&s.root).unwrap_or(s.root);
Store::at(&root)
})
}

/// Open (or refresh) the project for a tool call.
fn project_for(&self, project_path: Option<&str>) -> Result<ProjectHandles, ToolOutput> {
let default = self.default_root();
Expand All @@ -336,7 +344,7 @@ impl Server {
}
None => (default, false),
};
let Some(store) = Store::locate(&start) else { return Err(self.guidance(&start, explicit)) };
let Some(store) = Self::locate_store(&start) else { return Err(self.guidance(&start, explicit)) };
let root = store.root.clone();
// Keep open/evict callbacks in cache mutation order. Otherwise a later eviction
// could stop a watcher before an earlier open callback has actually started it.
Expand Down Expand Up @@ -463,7 +471,7 @@ impl Server {
}
None => default,
};
if let Some(store) = Store::locate(&start) {
if let Some(store) = Self::locate_store(&start) {
sync_checked = true;
sync_res = hook(&store.root, is_explicit_sync);
}
Expand Down Expand Up @@ -517,7 +525,7 @@ impl Server {
// --------------------------------------------------------------- dispatch
fn instructions(&self) -> String {
let root = self.default_root();
if Store::locate(&root).is_some() {
if Self::locate_store(&root).is_some() {
strings::server_instructions()
} else {
strings::server_instructions_no_root_index()
Expand Down
45 changes: 45 additions & 0 deletions crates/cg-mcp/tests/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,48 @@ fn explore_compact_max_chars_and_session_dedup() {
assert!(!t10.contains("Already sent earlier"), "{t10}");
server.shutdown();
}

#[test]
fn alternate_path_spellings_share_cache_watcher_and_dedup_history() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(
src.join("greet.ts"),
"export function greet(name: string): string {\n const normalized = name.trim();\n const prefix = 'hello';\n return `${prefix} ${normalized}`;\n}\n",
)
.unwrap();
cg_resolve::index_project(dir.path(), &Default::default()).unwrap();

// Intentionally seed `Config::path` with raw `std::fs::canonicalize` (which carries `\\?\` on Windows).
let raw_canon = std::fs::canonicalize(dir.path()).unwrap();
let server = Server::new(Config { path: Some(raw_canon), tools: Some(vec!["explore".into()]), dedup: true, auto_sync: false });
let open_roots = Arc::new(std::sync::Mutex::new(Vec::<std::path::PathBuf>::new()));
let opened = open_roots.clone();
server.set_open_hook(Arc::new(move |root| {
opened.lock().unwrap().push(root.to_path_buf());
}));
let out = Arc::new(Collect::default());
server.set_outbound(out.clone());

call(&server, &out, 1, "codegraph-rust_explore", json!({"query": "greet"}));
server.drain(Duration::from_secs(20));
let t1 = text_of(&out.by_id(1).unwrap());
assert!(t1.contains("const normalized = name.trim();"), "{t1}");

// Query the same project through a non-canonical spelling (`src/..`, and normal non-verbatim path on Windows).
let alt_path = dir.path().join("src").join("..");
call(&server, &out, 2, "codegraph-rust_explore", json!({"query": "greet", "projectPath": alt_path.to_string_lossy()}));
server.drain(Duration::from_secs(20));
let t2 = text_of(&out.by_id(2).unwrap());
assert!(t2.contains("Already sent earlier in this conversation"), "expected shared dedup history across path spellings: {t2}");
let opened = open_roots.lock().unwrap();
assert_eq!(opened.len(), 1, "same project must not open duplicate cache/watcher entries");
#[cfg(windows)]
if let Some(s) = opened[0].to_str() {
if s.encode_utf16().count() < 260 {
assert!(!s.starts_with(r"\\?\"), "open_hook should receive clean Win32 path: {s}");
}
}
server.shutdown();
}
2 changes: 1 addition & 1 deletion crates/cgr/src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Rng {

fn project_root(path: Option<PathBuf>) -> Result<PathBuf> {
let p = path.unwrap_or_else(|| PathBuf::from("."));
p.canonicalize().with_context(|| format!("cannot open {}", p.display()))
cg_core::path::canonicalize(&p).with_context(|| format!("cannot open {}", p.display()))
}

// ---------------------------------------------------------------- queries
Expand Down
8 changes: 4 additions & 4 deletions crates/cgr/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub struct NodeArgs {

fn start_dir(p: Option<PathBuf>) -> Result<PathBuf> {
let p = p.unwrap_or_else(|| PathBuf::from("."));
p.canonicalize().with_context(|| format!("cannot open {}", p.display()))
cg_core::path::canonicalize(&p).with_context(|| format!("cannot open {}", p.display()))
}

fn open(p: Option<PathBuf>) -> Result<Project> {
Expand Down Expand Up @@ -841,7 +841,7 @@ pub fn serve(base: Option<PathBuf>, http: Option<String>, token: Option<String>,
dedup = false;
}
let auto_sync = !no_auto_sync && !env_falsy(brand::env::AUTO_SYNC);
let cfg_path = base.map(|p| p.canonicalize().unwrap_or(p));
let cfg_path = base.map(|p| cg_core::path::canonicalize(&p).unwrap_or(p));
let cfg = cg_mcp::Config { path: cfg_path.clone(), tools: cg_mcp::defs::allowlist_from_env(), dedup, auto_sync };
let server = cg_mcp::Server::new(cfg);
server.set_rebuild_hook(std::sync::Arc::new(|root: &Path| {
Expand Down Expand Up @@ -914,14 +914,14 @@ pub fn install(
use cg_install::{targets, Action, Env, Request};
let env = Env::from_process();
let project = match base {
Some(p) => p.canonicalize().unwrap_or(p),
Some(p) => cg_core::path::canonicalize(&p).unwrap_or(p),
None => env.cwd.clone(),
};
let bin = match bin {
Some(b) => b,
None => std::env::current_exe()
.ok()
.and_then(|p| p.canonicalize().ok())
.and_then(|p| cg_core::path::canonicalize(&p).ok())
.ok_or_else(|| anyhow!("cannot determine the path of this executable; pass --bin"))?,
};
let req = Request { bin, local, project, hook, permissions, dry_run };
Expand Down