aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,19 @@
//! Functions for environment detection that need to be shared across crates.
/// Returns true if the current process is running under Windows Subsystem for Linux.
pub fn is_wsl() -> bool {
#[cfg(target_os = "linux")]
{
if std::env::var_os("WSL_DISTRO_NAME").is_some() {
return true;
}
match std::fs::read_to_string("/proc/version") {
Ok(version) => version.to_lowercase().contains("microsoft"),
Err(_) => false,
}
}
#[cfg(not(target_os = "linux"))]
{
false
}
}

View File

@@ -0,0 +1,252 @@
//! Path normalization, replacement, metadata inspection, symlink resolution, and atomic writes.
pub(crate) mod env;
pub use env::is_wsl;
mod system_commands;
pub use system_commands::system_executable;
pub use system_commands::system_path;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashSet;
use std::hash::Hash;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use tempfile::NamedTempFile;
/// Read metadata without following the final symlink, returning `None` for a missing path.
/// Other I/O errors are returned to the caller.
pub fn symlink_metadata_if_exists(path: &Path) -> io::Result<Option<std::fs::Metadata>> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
pub fn normalize_for_path_comparison(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
let canonical = path.as_ref().canonicalize()?;
Ok(normalize_for_wsl(canonical))
}
/// Compare paths after applying Codex's filesystem normalization.
///
/// If either path cannot be normalized, this falls back to direct path equality.
pub fn paths_match_after_normalization(left: impl AsRef<Path>, right: impl AsRef<Path>) -> bool {
if let (Ok(left), Ok(right)) = (
normalize_for_path_comparison(left.as_ref()),
normalize_for_path_comparison(right.as_ref()),
) {
return left == right;
}
left.as_ref() == right.as_ref()
}
/// Replace paths equal to `old_path` and remove duplicates, preserving their order.
///
/// Other paths, including descendants of `old_path`, remain unchanged. This uses
/// path equality without filesystem access or normalization; callers validate paths.
pub fn replace_path_and_deduplicate<P>(mut paths: Vec<P>, old_path: &Path, new_path: P) -> Vec<P>
where
P: AsRef<Path> + Clone + Eq + Hash,
{
for path in &mut paths {
if path.as_ref() == old_path {
*path = new_path.clone();
}
}
let mut seen = HashSet::new();
paths.retain(|path| seen.insert(path.clone()));
paths
}
pub fn normalize_for_native_workdir(path: impl AsRef<Path>) -> PathBuf {
normalize_for_native_workdir_with_flag(path.as_ref().to_path_buf(), cfg!(windows))
}
pub struct SymlinkWritePaths {
pub read_path: Option<PathBuf>,
pub write_path: PathBuf,
}
/// Resolve the final filesystem target for `path` while retaining a safe write path.
///
/// This follows symlink chains (including relative symlink targets) until it reaches a
/// non-symlink path. If the chain cycles or any metadata/link resolution fails, it
/// returns `read_path: None` and uses the original absolute path as `write_path`.
/// There is no fixed max-resolution count; cycles are detected via a visited set.
pub fn resolve_symlink_write_paths(path: &Path) -> io::Result<SymlinkWritePaths> {
let root = AbsolutePathBuf::from_absolute_path(path)
.map(AbsolutePathBuf::into_path_buf)
.unwrap_or_else(|_| path.to_path_buf());
let mut current = root.clone();
let mut visited = HashSet::new();
// Follow symlink chains while guarding against cycles.
loop {
let meta = match std::fs::symlink_metadata(&current) {
Ok(meta) => meta,
Err(err) if err.kind() == io::ErrorKind::NotFound => {
return Ok(SymlinkWritePaths {
read_path: Some(current.clone()),
write_path: current,
});
}
Err(_) => {
return Ok(SymlinkWritePaths {
read_path: None,
write_path: root,
});
}
};
if !meta.file_type().is_symlink() {
return Ok(SymlinkWritePaths {
read_path: Some(current.clone()),
write_path: current,
});
}
// If we've already seen this path, the chain cycles.
if !visited.insert(current.clone()) {
return Ok(SymlinkWritePaths {
read_path: None,
write_path: root,
});
}
let target = match std::fs::read_link(&current) {
Ok(target) => target,
Err(_) => {
return Ok(SymlinkWritePaths {
read_path: None,
write_path: root,
});
}
};
let next = if target.is_absolute() {
AbsolutePathBuf::from_absolute_path(&target)
} else if let Some(parent) = current.parent() {
Ok(AbsolutePathBuf::resolve_path_against_base(&target, parent))
} else {
return Ok(SymlinkWritePaths {
read_path: None,
write_path: root,
});
};
let next = match next {
Ok(path) => path.into_path_buf(),
Err(_) => {
return Ok(SymlinkWritePaths {
read_path: None,
write_path: root,
});
}
};
current = next;
}
}
pub fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
let parent = write_path.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("path {} has no parent directory", write_path.display()),
)
})?;
std::fs::create_dir_all(parent)?;
let mut tmp = NamedTempFile::new_in(parent)?;
tmp.write_all(contents.as_bytes())?;
tmp.persist(write_path)?;
Ok(())
}
fn normalize_for_wsl(path: PathBuf) -> PathBuf {
normalize_for_wsl_with_flag(path, env::is_wsl())
}
fn normalize_for_native_workdir_with_flag(path: PathBuf, is_windows: bool) -> PathBuf {
if is_windows {
dunce::simplified(&path).to_path_buf()
} else {
path
}
}
fn normalize_for_wsl_with_flag(path: PathBuf, is_wsl: bool) -> PathBuf {
if !is_wsl {
return path;
}
if !is_wsl_case_insensitive_path(&path) {
return path;
}
lower_ascii_path(path)
}
fn is_wsl_case_insensitive_path(path: &Path) -> bool {
#[cfg(target_os = "linux")]
{
use std::os::unix::ffi::OsStrExt;
use std::path::Component;
let mut components = path.components();
let Some(Component::RootDir) = components.next() else {
return false;
};
let Some(Component::Normal(mnt)) = components.next() else {
return false;
};
if !ascii_eq_ignore_case(mnt.as_bytes(), b"mnt") {
return false;
}
let Some(Component::Normal(drive)) = components.next() else {
return false;
};
let drive_bytes = drive.as_bytes();
drive_bytes.len() == 1 && drive_bytes[0].is_ascii_alphabetic()
}
#[cfg(not(target_os = "linux"))]
{
let _ = path;
false
}
}
#[cfg(target_os = "linux")]
fn ascii_eq_ignore_case(left: &[u8], right: &[u8]) -> bool {
left.len() == right.len()
&& left
.iter()
.zip(right)
.all(|(lhs, rhs)| lhs.to_ascii_lowercase() == *rhs)
}
#[cfg(target_os = "linux")]
fn lower_ascii_path(path: PathBuf) -> PathBuf {
use std::ffi::OsString;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
// WSL mounts Windows drives under /mnt/<drive>, which are case-insensitive.
let bytes = path.as_os_str().as_bytes();
let mut lowered = Vec::with_capacity(bytes.len());
for byte in bytes {
lowered.push(byte.to_ascii_lowercase());
}
PathBuf::from(OsString::from_vec(lowered))
}
#[cfg(not(target_os = "linux"))]
fn lower_ascii_path(path: PathBuf) -> PathBuf {
path
}
#[cfg(test)]
#[path = "path_utils_tests.rs"]
mod tests;

View File

@@ -0,0 +1,180 @@
use super::replace_path_and_deduplicate;
use super::symlink_metadata_if_exists;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn symlink_metadata_if_exists_distinguishes_files_directories_and_missing_paths()
-> std::io::Result<()> {
let directory = tempfile::tempdir()?;
let file = directory.path().join("file");
std::fs::write(&file, "contents")?;
let directory_metadata =
symlink_metadata_if_exists(directory.path())?.expect("directory exists");
let file_metadata = symlink_metadata_if_exists(&file)?.expect("file exists");
assert_eq!(
(directory_metadata.is_dir(), file_metadata.is_file()),
(true, true)
);
assert!(symlink_metadata_if_exists(&directory.path().join("missing"))?.is_none());
Ok(())
}
#[test]
fn symlink_metadata_if_exists_preserves_io_errors() {
let error = symlink_metadata_if_exists(Path::new("invalid\0path"))
.expect_err("an invalid path must not be treated as missing");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
}
#[test]
fn replace_path_and_deduplicate_preserves_other_paths_and_order() {
let old_path = Path::new("old");
let new_path = Path::new("new");
let extra = Path::new("extra");
let descendant = Path::new("old/child");
assert_eq!(
replace_path_and_deduplicate(
vec![old_path, extra, descendant, new_path, extra],
old_path,
new_path,
),
vec![new_path, extra, descendant]
);
}
#[cfg(unix)]
mod symlinks {
use super::super::resolve_symlink_write_paths;
use super::super::symlink_metadata_if_exists;
use pretty_assertions::assert_eq;
use std::os::unix::fs::symlink;
#[test]
fn symlink_metadata_if_exists_preserves_links_with_and_without_targets() -> std::io::Result<()>
{
let directory = tempfile::tempdir()?;
let target = directory.path().join("target");
let link = directory.path().join("link");
std::fs::write(&target, "contents")?;
symlink(&target, &link)?;
let linked_metadata = symlink_metadata_if_exists(&link)?.expect("symlink exists");
std::fs::remove_file(target)?;
let dangling_metadata = symlink_metadata_if_exists(&link)?.expect("symlink still exists");
assert!(linked_metadata.is_symlink());
assert_eq!(dangling_metadata.file_type(), linked_metadata.file_type());
Ok(())
}
#[test]
fn symlink_cycles_fall_back_to_root_write_path() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let a = dir.path().join("a");
let b = dir.path().join("b");
symlink(&b, &a)?;
symlink(&a, &b)?;
let resolved = resolve_symlink_write_paths(&a)?;
assert_eq!(resolved.read_path, None);
assert_eq!(resolved.write_path, a);
Ok(())
}
}
#[cfg(target_os = "linux")]
mod wsl {
use super::super::normalize_for_wsl_with_flag;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[test]
fn wsl_mnt_drive_paths_lowercase() {
let normalized =
normalize_for_wsl_with_flag(PathBuf::from("/mnt/C/Users/Dev"), /*is_wsl*/ true);
assert_eq!(normalized, PathBuf::from("/mnt/c/users/dev"));
}
#[test]
fn wsl_non_drive_paths_unchanged() {
let path = PathBuf::from("/mnt/cc/Users/Dev");
let normalized = normalize_for_wsl_with_flag(path.clone(), /*is_wsl*/ true);
assert_eq!(normalized, path);
}
#[test]
fn wsl_non_mnt_paths_unchanged() {
let path = PathBuf::from("/home/Dev");
let normalized = normalize_for_wsl_with_flag(path.clone(), /*is_wsl*/ true);
assert_eq!(normalized, path);
}
}
mod native_workdir {
use super::super::normalize_for_native_workdir_with_flag;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[cfg(target_os = "windows")]
#[test]
fn windows_verbatim_paths_are_simplified() {
let path = PathBuf::from(r"\\?\D:\c\x\worktrees\2508\swift-base");
let normalized = normalize_for_native_workdir_with_flag(path, /*is_windows*/ true);
assert_eq!(
normalized,
PathBuf::from(r"D:\c\x\worktrees\2508\swift-base")
);
}
#[test]
fn non_windows_paths_are_unchanged() {
let path = PathBuf::from(r"\\?\D:\c\x\worktrees\2508\swift-base");
let normalized =
normalize_for_native_workdir_with_flag(path.clone(), /*is_windows*/ false);
assert_eq!(normalized, path);
}
}
mod path_comparison {
use super::super::paths_match_after_normalization;
use std::path::PathBuf;
#[test]
fn matches_identical_existing_paths() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
assert!(paths_match_after_normalization(dir.path(), dir.path()));
Ok(())
}
#[test]
fn falls_back_to_raw_equality_when_paths_cannot_be_normalized() {
assert!(paths_match_after_normalization(
PathBuf::from("missing"),
PathBuf::from("missing"),
));
assert!(!paths_match_after_normalization(
PathBuf::from("missing-a"),
PathBuf::from("missing-b"),
));
}
#[cfg(windows)]
#[test]
fn matches_windows_verbatim_paths() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let verbatim_dir = PathBuf::from(format!(r"\\?\{}", dir.path().display()));
assert!(paths_match_after_normalization(verbatim_dir, dir.path()));
Ok(())
}
}

View File

@@ -0,0 +1,166 @@
//! Installed helper discovery for automatic work before workspace trust.
//!
//! Only OS and conventional package-manager locations are trusted, never ambient
//! PATH or the working directory. Nix system profiles must resolve into the
//! trusted store. Custom installations fall back to no helper.
//! This assumes the installed software directories themselves are trusted; it
//! does not defend against an attacker who can modify system installations.
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
/// Finds an installed helper without consulting PATH, PATHEXT, or the working directory.
pub fn system_executable(name: &str) -> Option<PathBuf> {
executable_in_directories(name, &system_directories())
}
/// Child-process PATH for automatic helpers, not for user-requested tools.
pub fn system_path() -> std::io::Result<OsString> {
let directories = system_directories();
if directories.is_empty() {
return Err(std::io::Error::other("no trusted executable directories"));
}
std::env::join_paths(directories).map_err(std::io::Error::other)
}
fn executable_in_directories(name: &str, directories: &[PathBuf]) -> Option<PathBuf> {
// Do not allow callers to accidentally escape the installation directories.
if Path::new(name).file_name() != Some(std::ffi::OsStr::new(name)) {
return None;
}
let name = format!("{name}{}", std::env::consts::EXE_SUFFIX);
directories.iter().find_map(|directory| {
let executable = dunce::canonicalize(directory.join(&name)).ok()?;
// A symlink into a workspace is not an installed executable. Package
// manager links may target sibling libexec/Cellar directories.
let installed = directories.iter().any(|root| executable.starts_with(root))
|| installation_roots()
.iter()
.any(|root| executable.starts_with(root));
if !installed || !executable.is_file() {
return None;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if executable.metadata().ok()?.permissions().mode() & 0o111 == 0 {
return None;
}
}
Some(executable)
})
}
#[cfg(unix)]
fn installation_roots() -> Vec<PathBuf> {
[
"/usr/bin",
"/bin",
"/usr/sbin",
"/sbin",
"/usr/local",
"/opt/homebrew",
"/opt/local",
"/Library/Developer/CommandLineTools",
"/Applications/Xcode.app/Contents/Developer",
"/nix/store",
"/mnt/c/Windows/System32",
]
.into_iter()
.map(PathBuf::from)
.collect()
}
fn system_directories() -> Vec<PathBuf> {
#[cfg(unix)]
let directories = [
"/opt/homebrew/bin",
"/usr/local/bin",
"/opt/local/bin",
"/run/current-system/sw/bin",
"/nix/var/nix/profiles/default/bin",
"/Library/Developer/CommandLineTools/usr/bin",
"/Applications/Xcode.app/Contents/Developer/usr/bin",
"/usr/bin",
"/bin",
"/usr/sbin",
"/sbin",
]
.into_iter()
.map(PathBuf::from);
#[cfg(target_os = "linux")]
let directories = directories.chain(
crate::is_wsl()
.then_some([
PathBuf::from("/mnt/c/Windows/System32"),
PathBuf::from("/mnt/c/Windows/System32/WindowsPowerShell/v1.0"),
])
.into_iter()
.flatten(),
);
#[cfg(windows)]
let directories = installation_roots().into_iter().flat_map(|root| {
vec![
root.join("Git/cmd"),
root.join("Git/mingw64/bin"),
root.join("Git/usr/bin"),
root,
]
});
let roots = installation_roots();
directories
.filter_map(|directory| dunce::canonicalize(directory).ok())
.filter(|directory| roots.iter().any(|root| directory.starts_with(root)))
.collect()
}
#[cfg(windows)]
fn installation_roots() -> Vec<PathBuf> {
use std::os::windows::ffi::OsStringExt;
use windows_sys::Win32::System::Com::CoTaskMemFree;
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFiles;
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFilesX86;
use windows_sys::Win32::UI::Shell::FOLDERID_System;
use windows_sys::Win32::UI::Shell::KF_FLAG_DEFAULT_PATH;
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
[
FOLDERID_ProgramFiles,
FOLDERID_ProgramFilesX86,
FOLDERID_System,
]
.iter()
.filter_map(|id| {
let mut path = std::ptr::null_mut();
// SAFETY: the API writes a CoTaskMem-allocated, NUL-terminated UTF-16 path.
let result = unsafe {
SHGetKnownFolderPath(
id,
KF_FLAG_DEFAULT_PATH as u32,
std::ptr::null_mut(),
&mut path,
)
};
if result != 0 || path.is_null() {
return None;
}
// SAFETY: success guarantees the string; free it after copying.
let directory = unsafe {
let mut len = 0;
while *path.add(len) != 0 {
len += 1;
}
let directory =
PathBuf::from(OsString::from_wide(std::slice::from_raw_parts(path, len)));
CoTaskMemFree(path.cast());
directory
};
dunce::canonicalize(directory).ok()
})
.collect()
}
#[cfg(test)]
#[path = "system_commands_tests.rs"]
mod tests;

View File

@@ -0,0 +1,31 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn resolves_only_executables_inside_installation_directories() {
let root = tempfile::tempdir().unwrap();
let bin = root.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let executable = bin.join(format!("helper{}", std::env::consts::EXE_SUFFIX));
std::fs::write(&executable, "installed helper").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(/*mode*/ 0o755))
.unwrap();
}
let directories = vec![dunce::canonicalize(bin).unwrap()];
assert_eq!(
executable_in_directories("helper", &directories),
Some(dunce::canonicalize(&executable).unwrap())
);
assert_eq!(executable_in_directories("../helper", &directories), None);
assert_eq!(executable_in_directories("missing", &directories), None);
#[cfg(unix)]
{
let outside = root.path().join("outside");
std::fs::rename(&executable, &outside).unwrap();
std::os::unix::fs::symlink(&outside, &executable).unwrap();
assert_eq!(executable_in_directories("helper", &directories), None);
}
}