diff --git a/CHANGELOG.md b/CHANGELOG.md index 8da38a18..1d76cd5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Fixed +- Build on Windows: read the file identity for spec transactions through a stable API, and keep the dependencies that every platform needs out of the Unix-only target table. +- Install a deck on Windows: write manifest keys, provenance paths, and snapshot entries with `/`, and read a manifest that an earlier tool wrote with `\`. `rune install` stopped with `source path has an ambiguous separator or control character`. +- Record the module name as the provenance source for a single-module source in `.rune`. The source was empty, and every install ended with `source snapshot remains unverified`. - Step aside when Cursor runs a Claude hook entry: answer `{}` with exit 0, run no handler, and log `borrowed by cursor`. Every Cursor tool call was denied under `--on-failure deny`. - Abandon the run workspace's initial working copy under jj 0.47, which names the caller's workspace on its creation. The run kept it and reported `outside_changes`. diff --git a/Cargo.toml b/Cargo.toml index 0c3783b3..41c2d39b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,9 +80,6 @@ ureq = { version = "3", default-features = false, features = ["rustls", "platfor webpki-root-certs = "1" signal-hook = "=0.3.18" -[target.'cfg(unix)'.dependencies] -nix = { version = "0.30", features = ["fs", "process", "resource", "signal"] } - # git gix = { version = "0.66", default-features = false, features = ["blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation"] } @@ -105,6 +102,11 @@ ansi-to-tui = { version = "8.0.1", optional = true } unicode-width = { version = "0.2", optional = true } edtui = { version = "0.11", default-features = false, optional = true } +# A target table runs to the next table header, so it sits after every +# dependency that all platforms share. +[target.'cfg(unix)'.dependencies] +nix = { version = "0.30", features = ["fs", "process", "resource", "signal"] } + [build-dependencies] sha2 = "0.10" diff --git a/docs/decisions/RUST-0015 Portable Path Text.md b/docs/decisions/RUST-0015 Portable Path Text.md new file mode 100644 index 00000000..44804d9f --- /dev/null +++ b/docs/decisions/RUST-0015 Portable Path Text.md @@ -0,0 +1,76 @@ +--- +title: "Portable Path Text" +description: "Every path that becomes text is written with forward slashes, so manifests, snapshots, and provenance read the same on Windows, macOS, and Linux" +type: adr +category: rust +tags: + - rust + - windows + - paths + - manifest +status: proposed +created: 2026-11-15 +updated: 2026-11-15 +author: "@LangrMartin" +project: rune-cli +related: + - "RUST-0003 Code Style and Tooling" + - "RUST-0010 Dependency and Lint Configuration" +responsible: ["@N4M3Z"] +accountable: ["@N4M3Z"] +consulted: [] +informed: [] +upstream: [] +--- + +# Portable Path Text + +## Context and Problem Statement + +Rune stores and compares relative paths as text. Manifest keys, provenance paths, source snapshot entries, bundle entries, and the keys that `doctor` and `drift` compare are all strings, and the code splits and matches them on `/` (`strip_prefix("rules/")`, `split_once('/')`). + +On Windows a `Path` turned into text carries `\`. Two things then go wrong: + +- Matching fails. A rule at `rules\Name.md` is not recognized as a rule, so it deploys under `rules/rules/` and the manifest gets backslash keys. +- Validation refuses the path. `source_snapshot` and `bundle` reject any text that contains `\` as an ambiguous separator. On macOS and Linux that check catches a suspicious file name. On Windows it rejects every nested path and the deck root itself, so `rune install` stops with `source path has an ambiguous separator or control character`. + +The same build had two blockers before any of this ran: `rune-docs` read the Windows file identity through the unstable `windows_by_handle` feature, and a `[target.'cfg(unix)'.dependencies]` header in `Cargo.toml` sat above dependencies that every platform needs. + +## Considered Options + +1. **Convert at each call site**: add `.replace('\\', "/")` wherever a failure shows up, as `assemble/sources.rs` and `graph/mod.rs` already do in one place each. +2. **One helper at the boundary**: every relative path that becomes text passes through `services::paths::slash_text` or `slash_separators`. +3. **Never compare paths as text**: carry `PathBuf` and components through the manifest, snapshot, and provenance code. +4. **Declare Windows unsupported**: keep the Unix-only assumption and say so. + +## Decision Outcome + +Option 2. The text form of a relative path is `/`-separated on every platform. + +- Convert where a `Path` becomes a `String` that is stored, compared, or split. Use `rune::services::paths::slash_text` for a `Path` and `slash_separators` for text that came from `to_str()`. Do not call `to_string_lossy()` directly on such a path. +- On Windows the helper rewrites `\` to `/`. No Windows file name can contain `\`, so the rewrite loses nothing. On other platforms the helper returns the text unchanged. +- The ambiguous separator check runs after the conversion. It keeps rejecting a literal backslash in a name on macOS and Linux and no longer rejects ordinary Windows paths. +- Text read back from disk gets the same conversion. `manifest::read` converts keys and provenance paths, so a manifest written with `\` keys by an earlier deploy tool names the same files and its entries are not pruned as stale. +- Slash text may be joined back onto a `Path`. `Path::join` accepts `/` on Windows. +- An absolute path that is only shown to the user keeps the native form. + +Option 1 leaves the next unconverted site to fail in the field. Option 3 is the larger and safer design, and it can follow later without changing the stored format this record fixes. Option 4 contradicts the Windows entry that the release workflow already carries. + +### Consequences + +A manifest written on Windows has the same keys as one written on macOS or Linux for the same content, so a deployment can be compared across machines. + +File identity on Windows comes from the open handle through `winapi-util`, a safe wrapper, because stable `std` does not expose the volume serial number and file index. `unsafe_code = "forbid"` stays in force. + +Directory syncing in the spec transaction is skipped on Windows, where `File::open` cannot open a directory. + +Still open on Windows: + +- Symlink assembly and deployment return an explicit error. +- Integration tests isolate the home directory through `HOME`. `dirs::home_dir` ignores `HOME` on Windows, so those tests would write to the real home directory and must not run there until rune has a home override. +- `target::Scope::Project` derives its key by replacing `/` only. +- Three library tests assert on the native text of an absolute path and fail on Windows. + +## More Information + +Verified on Windows 11 with the `stable-x86_64-pc-windows-gnu` toolchain: `rune install`, a repeated install, `rune doctor`, `rune drift`, and `rune provenance` against the runedeck deck in an isolated target; the `rune-docs` test suite; the library unit tests apart from the three named above. diff --git a/rune-docs/Cargo.toml b/rune-docs/Cargo.toml index 60f5b273..de3ffd43 100644 --- a/rune-docs/Cargo.toml +++ b/rune-docs/Cargo.toml @@ -15,7 +15,7 @@ default = [] # The whole spec module: lifecycle commands, the read-only scans, tree # validation, and OpenSpec interop. links, adr, and the support helpers are # always compiled. -lifecycle = ["dep:clap", "dep:sha2"] +lifecycle = ["dep:clap", "dep:sha2", "dep:winapi-util"] [dependencies] clap = { version = "4", features = ["derive"], optional = true } @@ -27,6 +27,12 @@ serde_json = "1" serde_yaml = "0.9" sha2 = { version = "0.10", optional = true } +# Stable std keeps the Windows volume serial number and file index behind an +# unstable feature; this is the safe wrapper the spec transaction reads them +# through. +[target.'cfg(windows)'.dependencies] +winapi-util = { version = "0.1", optional = true } + [dev-dependencies] tempfile = "3" diff --git a/rune-docs/src/spec/transaction/confine.rs b/rune-docs/src/spec/transaction/confine.rs index 2cec207f..6583d4f6 100644 --- a/rune-docs/src/spec/transaction/confine.rs +++ b/rune-docs/src/spec/transaction/confine.rs @@ -18,34 +18,61 @@ pub(super) struct FileIdentity { #[cfg(windows)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct FileIdentity { - volume: Option, - index: Option, + volume: u64, + index: u64, } #[cfg(not(any(unix, windows)))] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct FileIdentity; -#[cfg(any(unix, windows))] +#[cfg(unix)] pub(super) fn metadata_identity(metadata: &fs::Metadata) -> FileIdentity { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - FileIdentity { - device: metadata.dev(), - inode: metadata.ino(), - } - } - #[cfg(windows)] - { - use std::os::windows::fs::MetadataExt as _; - FileIdentity { - volume: metadata.volume_serial_number(), - index: metadata.file_index(), - } + use std::os::unix::fs::MetadataExt as _; + FileIdentity { + device: metadata.dev(), + inode: metadata.ino(), } } +/// Stable std keeps the volume serial number and file index of +/// `fs::Metadata` behind an unstable feature on Windows, so the identity is +/// read from the open handle. +#[cfg(windows)] +pub(super) fn handle_identity(file: &fs::File) -> io::Result { + let information = winapi_util::file::information(file)?; + Ok(FileIdentity { + volume: information.volume_serial_number(), + index: information.file_index(), + }) +} + +/// Metadata and identity of `path` itself, taken from one inspection so the +/// two cannot describe different files. A symlink is never followed. +#[cfg(unix)] +fn inspect_without_following(path: &Path) -> io::Result<(fs::Metadata, FileIdentity)> { + let metadata = fs::symlink_metadata(path)?; + let identity = metadata_identity(&metadata); + Ok((metadata, identity)) +} + +#[cfg(windows)] +fn inspect_without_following(path: &Path) -> io::Result<(fs::Metadata, FileIdentity)> { + use std::os::windows::fs::OpenOptionsExt as _; + // The reparse-point flag opens a symlink itself rather than its target; + // backup semantics lets a directory open so the caller rejects it by kind + // instead of by an access error. + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; + let file = fs::OpenOptions::new() + .access_mode(0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS) + .open(path)?; + let metadata = file.metadata()?; + let identity = handle_identity(&file)?; + Ok((metadata, identity)) +} + pub(super) fn file_identity(path: &Path) -> Result { #[cfg(not(any(unix, windows)))] { @@ -57,15 +84,15 @@ pub(super) fn file_identity(path: &Path) -> Result { } #[cfg(any(unix, windows))] { - let metadata = - fs::symlink_metadata(path).map_err(|error| io_error("inspect", path, error))?; + let (metadata, identity) = + inspect_without_following(path).map_err(|error| io_error("inspect", path, error))?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err(Error::new( ErrorKind::Io, format!("transaction path is not a regular file: {}", path.display()), )); } - Ok(metadata_identity(&metadata)) + Ok(identity) } } diff --git a/rune-docs/src/spec/transaction/conversion.rs b/rune-docs/src/spec/transaction/conversion.rs index f3e0a83e..635fbc35 100644 --- a/rune-docs/src/spec/transaction/conversion.rs +++ b/rune-docs/src/spec/transaction/conversion.rs @@ -256,10 +256,7 @@ impl Transaction { fs::hard_link(&install, &destination) .map_err(|error| io_error("install create-only destination", &destination, error))?; verify_file_hash(&destination, &write.intended_sha256)?; - let directory = File::open(parent).map_err(|error| io_error("open", parent, error))?; - directory - .sync_all() - .map_err(|error| io_error("sync", parent, error)) + super::staging::sync_directory(parent) } fn create_conversion_destination_directories( diff --git a/rune-docs/src/spec/transaction/staging.rs b/rune-docs/src/spec/transaction/staging.rs index 4d2d36bb..8e50f5da 100644 --- a/rune-docs/src/spec/transaction/staging.rs +++ b/rune-docs/src/spec/transaction/staging.rs @@ -120,10 +120,20 @@ pub(super) fn write_file_atomic(path: &Path, content: &[u8]) -> Result<(), Error io_error("replace", path, error), )); } - let directory = File::open(parent).map_err(|error| io_error("open", parent, error))?; - directory + sync_directory(parent) +} + +/// Flush a directory after an entry in it changed. Windows cannot open a +/// directory through `File::open`, so the change is left to the filesystem +/// journal there. +pub(super) fn sync_directory(directory: &Path) -> Result<(), Error> { + if cfg!(windows) { + return Ok(()); + } + let handle = File::open(directory).map_err(|error| io_error("open", directory, error))?; + handle .sync_all() - .map_err(|error| io_error("sync", parent, error)) + .map_err(|error| io_error("sync", directory, error)) } pub(super) fn replace_file_from_backup( diff --git a/rune-docs/src/spec/transaction/verify.rs b/rune-docs/src/spec/transaction/verify.rs index 9c9ae1c6..f5a50c4f 100644 --- a/rune-docs/src/spec/transaction/verify.rs +++ b/rune-docs/src/spec/transaction/verify.rs @@ -2,7 +2,11 @@ //! a deterministic tree digest (sorted entries, kind- and length-prefixed) //! that proves a copied archive matches its source byte for byte. -use super::confine::{FileIdentity, metadata_identity, reject_symlink}; +#[cfg(windows)] +use super::confine::handle_identity; +#[cfg(unix)] +use super::confine::metadata_identity; +use super::confine::{FileIdentity, reject_symlink}; use super::io_error; use crate::error::{Error, ErrorKind}; use sha2::{Digest, Sha256}; @@ -45,7 +49,10 @@ pub(super) fn hash_file_with_identity(path: &Path) -> Result<(String, FileIdenti format!("transaction path is not a regular file: {}", path.display()), )); } + #[cfg(unix)] let identity = metadata_identity(&metadata); + #[cfg(windows)] + let identity = handle_identity(&file).map_err(|error| io_error("inspect", path, error))?; Ok((hash_open_file(&mut file, path)?, identity)) } } diff --git a/src/cli/assemble/sources.rs b/src/cli/assemble/sources.rs index 78245ae0..5e659446 100644 --- a/src/cli/assemble/sources.rs +++ b/src/cli/assemble/sources.rs @@ -363,12 +363,9 @@ fn collect_pending(dir: &Path, module_root: &Path, pending: &mut Vec) { effective_review_state(&path, module_root), AdoptReviewState::Deployable ) { - pending.push( - path.strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(), - ); + pending.push(rune::services::paths::slash_text( + path.strip_prefix(module_root).unwrap_or(&path), + )); } } } @@ -440,11 +437,8 @@ fn walk_content_dir( base_filenames.insert(filename); - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(&path)); let Some(content) = read_source_text(&path)? else { continue; @@ -512,11 +506,8 @@ fn walk_hook_dir( let Some(content) = read_source_text(&path)? else { continue; }; - let relative_path = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative_path = + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(&path)); sources.push(SourceFile { relative_path, full_path: path.to_string_lossy().to_string(), @@ -655,11 +646,8 @@ fn walk_qualifier_dir( if base_filenames.contains(&filename) { continue; } - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(&path)); let Some(content) = read_source_text(&path)? else { continue; }; diff --git a/src/cli/dashboard/routes/artifact.rs b/src/cli/dashboard/routes/artifact.rs index cc2995dc..c2eb048b 100644 --- a/src/cli/dashboard/routes/artifact.rs +++ b/src/cli/dashboard/routes/artifact.rs @@ -543,11 +543,7 @@ fn resolve_effective_content( use rune::assemble::variants; match variant_path { Some(path) => { - let label = path - .strip_prefix(repo) - .unwrap_or(path) - .to_string_lossy() - .to_string(); + let label = rune::services::paths::slash_text(path.strip_prefix(repo).unwrap_or(path)); let variant_content = match std::fs::read_to_string(path) { Ok(content) => content, Err(error) => { diff --git a/src/cli/deploy/mod.rs b/src/cli/deploy/mod.rs index cbf07238..c61d9af6 100644 --- a/src/cli/deploy/mod.rs +++ b/src/cli/deploy/mod.rs @@ -492,11 +492,9 @@ fn deploy_provider_kind_files( continue; } - let relative = build_path - .strip_prefix(kind_dir) - .unwrap_or(&build_path) - .to_string_lossy() - .to_string(); + let relative = rune::services::paths::slash_text( + build_path.strip_prefix(kind_dir).unwrap_or(&build_path), + ); let manifest_key = format!("{kind}/{relative}"); if only.is_some_and(|prefix| !only_matches(&manifest_key, prefix)) { continue; diff --git a/src/cli/doctor.rs b/src/cli/doctor.rs index 558838cd..56d2f485 100644 --- a/src/cli/doctor.rs +++ b/src/cli/doctor.rs @@ -632,7 +632,7 @@ fn collect_managed_files_recursive( format!("cannot relativize {}: {error}", entry_path.display()), ) })?; - files.push(relative.to_string_lossy().into_owned()); + files.push(rune::services::paths::slash_text(relative)); } } Ok(()) diff --git a/src/cli/dotrune/resolve.rs b/src/cli/dotrune/resolve.rs index aa98532d..5491af66 100644 --- a/src/cli/dotrune/resolve.rs +++ b/src/cli/dotrune/resolve.rs @@ -50,12 +50,12 @@ pub fn resolve_sources( ), )); } - filter_to_requested( - sources::collect(module_root, valid_qualifiers)?, - rune_list, - source_label, - module_root, - )? + let module_source_uri = crate::cli::config::load_source_uri(module_root); + let mut files = sources::collect(module_root, valid_qualifiers)?; + for file in &mut files { + file.source_uri = Some(module_source_uri.clone()); + } + filter_to_requested(files, rune_list, source_label, module_root)? } CanonicalSource::Deck(deck) => { let mut files = Vec::new(); diff --git a/src/cli/drift/mod.rs b/src/cli/drift/mod.rs index e53bcd0c..0ba3bb8f 100644 --- a/src/cli/drift/mod.rs +++ b/src/cli/drift/mod.rs @@ -666,11 +666,9 @@ fn collect_provenance_sidecars( .map(|stem| stem.to_string_lossy().into_owned()) .unwrap_or_default(); let local_md = parent.join(format!("{stem}.md")); - let local_relative = local_md - .strip_prefix(base_directory) - .unwrap_or(&local_md) - .to_string_lossy() - .to_string(); + let local_relative = rune::services::paths::slash_text( + local_md.strip_prefix(base_directory).unwrap_or(&local_md), + ); let source = sidecar .provenance @@ -735,11 +733,9 @@ fn collect_text_recursive( if path.is_dir() { collect_text_recursive(base_directory, &path, files); } else if let Ok(content) = fs::read_to_string(&path) { - let relative = path - .strip_prefix(base_directory) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = rune::services::paths::slash_text( + path.strip_prefix(base_directory).unwrap_or(&path), + ); files.insert(relative, content); } } @@ -767,11 +763,9 @@ fn collect_markdown_recursive( if path.is_dir() { collect_markdown_recursive(base_directory, &path, files); } else if path.extension().is_some_and(|extension| extension == "md") { - let relative = path - .strip_prefix(base_directory) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = rune::services::paths::slash_text( + path.strip_prefix(base_directory).unwrap_or(&path), + ); if let Ok(content) = fs::read_to_string(&path) { files.insert(relative, content); diff --git a/src/cli/drift/scope.rs b/src/cli/drift/scope.rs index 5dd40633..dd823052 100644 --- a/src/cli/drift/scope.rs +++ b/src/cli/drift/scope.rs @@ -461,11 +461,8 @@ fn collect_recursive(base: &Path, current: &Path, files: &mut BTreeMap String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(path)) } fn skill_variant_files( diff --git a/src/cli/validate/plugin.rs b/src/cli/validate/plugin.rs index 5b8654f7..7910686d 100644 --- a/src/cli/validate/plugin.rs +++ b/src/cli/validate/plugin.rs @@ -133,8 +133,5 @@ fn push_diagnostics(diagnostics: Vec, result: &mut rune::result::Act } fn relative_path(module_root: &Path, path: &Path) -> String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(path)) } diff --git a/src/cli/validate/tools.rs b/src/cli/validate/tools.rs index e81e0eb9..da2e3145 100644 --- a/src/cli/validate/tools.rs +++ b/src/cli/validate/tools.rs @@ -129,15 +129,12 @@ fn check_json_syntax( } pub(super) fn is_excluded(path: &Path, module_root: &Path, patterns: &[String]) -> bool { - let relative = path - .strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy(); + let relative = relative_path(path, module_root); patterns.iter().any(|pattern| { if let Some(prefix) = pattern.strip_suffix("/*") { relative.starts_with(prefix) } else { - relative.as_ref() == pattern.as_str() + relative == pattern.as_str() } }) } @@ -155,12 +152,7 @@ fn check_shellcheck(module_root: &Path, report: &mut ValidationReport) { let mut arguments = vec!["-S", "warning"]; let paths: Vec = shell_files .iter() - .map(|path| { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() - }) + .map(|path| relative_path(path, module_root)) .collect(); for path in &paths { arguments.push(path); @@ -314,10 +306,7 @@ fn run_command_with_env( } fn relative_path(path: &Path, module_root: &Path) -> String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::services::paths::slash_text(path.strip_prefix(module_root).unwrap_or(path)) } fn find_text_files(module_root: &Path) -> Vec { diff --git a/src/manifest/bundle.rs b/src/manifest/bundle.rs index 14aeec61..1c9e6f11 100644 --- a/src/manifest/bundle.rs +++ b/src/manifest/bundle.rs @@ -153,6 +153,7 @@ impl Inventory { )); continue; }; + let path_text = crate::services::paths::slash_separators(path_text); if path_text.contains('\\') || path_text.chars().any(char::is_control) { self.problems.push(BundleProblem::new( BundleProblemKind::InvalidPath, @@ -516,7 +517,7 @@ fn check_references( match result { Ok(target) if target.as_os_str().is_empty() - || entries.contains_key(target.to_string_lossy().as_ref()) => {} + || entries.contains_key(&crate::services::paths::slash_text(&target)) => {} Ok(_) => problems.push(BundleProblem::new( BundleProblemKind::BrokenReference, Path::new(document), diff --git a/src/manifest/mod.rs b/src/manifest/mod.rs index fe5d284e..8b1b3b2f 100644 --- a/src/manifest/mod.rs +++ b/src/manifest/mod.rs @@ -62,10 +62,9 @@ pub fn provenance_path(manifest_key: &str) -> String { let file_name = path.file_name().unwrap_or_default().to_string_lossy(); let provenance_dir = parent.join(PROVENANCE_DIRECTORY); - provenance_dir - .join(format!("{file_name}.{SIDECAR_EXTENSION}")) - .to_string_lossy() - .to_string() + crate::services::paths::slash_text( + &provenance_dir.join(format!("{file_name}.{SIDECAR_EXTENSION}")), + ) } /// The stem-named sidecar location written by earlier versions @@ -77,10 +76,7 @@ pub fn legacy_provenance_path(manifest_key: &str) -> String { let stem = path.file_stem().unwrap_or_default().to_string_lossy(); let provenance_dir = parent.join(PROVENANCE_DIRECTORY); - provenance_dir - .join(format!("{stem}.{SIDECAR_EXTENSION}")) - .to_string_lossy() - .to_string() + crate::services::paths::slash_text(&provenance_dir.join(format!("{stem}.{SIDECAR_EXTENSION}"))) } /// Sidecar path beside a file on disk, full-filename encoded. diff --git a/src/manifest/read.rs b/src/manifest/read.rs index 2e4b30a5..e8b7521d 100644 --- a/src/manifest/read.rs +++ b/src/manifest/read.rs @@ -36,6 +36,9 @@ fn flatten_tree( let Some(key_string) = key.as_str() else { continue; }; + // A manifest written on Windows by an earlier deploy tool carries + // `\` inside its keys; read it as the same file the `/` key names. + let key_string = crate::services::paths::slash_separators(key_string); let full_path = if prefix.is_empty() { key_string.to_string() @@ -49,7 +52,9 @@ fn flatten_tree( if child_map.contains_key("fingerprint") { let fingerprint = super::extract::string_field(value, "fingerprint", &full_path)?; - let provenance = super::extract::string_field(value, "provenance", &full_path).ok(); + let provenance = super::extract::string_field(value, "provenance", &full_path) + .ok() + .map(|path| crate::services::paths::slash_separators(&path).into_owned()); entries.insert( full_path, diff --git a/src/manifest/source_snapshot.rs b/src/manifest/source_snapshot.rs index d8f4df8a..33d43034 100644 --- a/src/manifest/source_snapshot.rs +++ b/src/manifest/source_snapshot.rs @@ -299,10 +299,11 @@ fn validate_symlink(relative: &Path, target: &Path) -> Result<(), String> { fn path_text(path: &Path) -> Result { let text = path.to_str().ok_or("source paths must be valid UTF-8")?; + let text = crate::services::paths::slash_separators(text); if text.contains('\\') || text.chars().any(char::is_control) { return Err("source path has an ambiguous separator or control character".into()); } - Ok(text.into()) + Ok(text.into_owned()) } fn valid_label(label: &str) -> bool { diff --git a/src/manifest/tests.rs b/src/manifest/tests.rs index 12f43ab8..8f156989 100644 --- a/src/manifest/tests.rs +++ b/src/manifest/tests.rs @@ -158,6 +158,22 @@ fn read_parses_all_entries() { assert!(entries.contains_key("rules/CodeStyle.md")); } +#[cfg(windows)] +#[test] +fn read_treats_windows_separators_in_keys_as_slashes() { + let manifest = "skills:\n Explain\\SKILL.md:\n fingerprint: abc\n provenance: skills/Explain\\.provenance\\SKILL.md.yaml\n"; + + let entries = read(manifest).unwrap(); + + let entry = entries + .get("skills/Explain/SKILL.md") + .expect("the key reads with slashes"); + assert_eq!( + entry.provenance.as_deref(), + Some("skills/Explain/.provenance/SKILL.md.yaml") + ); +} + #[test] fn read_ignores_entries_without_fingerprint() { let entries = read(MANIFEST_INVALID).unwrap(); diff --git a/src/provider/detection.rs b/src/provider/detection.rs index 5472294a..46b862cc 100644 --- a/src/provider/detection.rs +++ b/src/provider/detection.rs @@ -1180,7 +1180,7 @@ fn inspect_build_kind( let Ok(relative) = build_path.strip_prefix(&kind_root) else { continue; }; - let key = format!("{kind}/{}", relative.to_string_lossy()); + let key = format!("{kind}/{}", crate::services::paths::slash_text(relative)); build_keys.insert((target.clone(), key.clone())); inspect_build_file( &build_path, diff --git a/src/services/atomic.rs b/src/services/atomic.rs index 4e51141a..5229f037 100644 --- a/src/services/atomic.rs +++ b/src/services/atomic.rs @@ -118,6 +118,7 @@ mod tests { assert_eq!(fs::read(&path).unwrap(), b"\x00\xff binary"); } + #[cfg(unix)] #[test] fn refuses_a_symlinked_destination() { let root = tempfile::tempdir().unwrap(); diff --git a/src/services/confine.rs b/src/services/confine.rs index 30a84894..f360cbe4 100644 --- a/src/services/confine.rs +++ b/src/services/confine.rs @@ -202,6 +202,7 @@ mod tests { assert!(matches!(future, Violation::Escape { .. }), "{future:?}"); } + #[cfg(unix)] #[test] fn symlink_escape_is_rejected() { let root = tempfile::tempdir().unwrap(); @@ -242,6 +243,7 @@ mod tests { assert!(matches!(error, Violation::Escape { .. }), "{error:?}"); } + #[cfg(unix)] #[test] fn dangling_symlink_destination_is_rejected() { let root = tempfile::tempdir().unwrap(); diff --git a/src/services/discovery.rs b/src/services/discovery.rs index 7b283a48..ed9be385 100644 --- a/src/services/discovery.rs +++ b/src/services/discovery.rs @@ -192,11 +192,7 @@ fn scan_hook_kind(root: &Path) -> Vec { if !file_type.is_file() { continue; } - let relative_path = path - .strip_prefix(root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative_path = super::paths::slash_text(path.strip_prefix(root).unwrap_or(&path)); let Some(name) = relative_path .strip_prefix("hooks/") .map(Path::new) diff --git a/src/services/mod.rs b/src/services/mod.rs index 0393703c..4c7050ec 100644 --- a/src/services/mod.rs +++ b/src/services/mod.rs @@ -13,6 +13,7 @@ mod discovery; pub mod editing; pub mod files; mod history; +pub mod paths; mod provenance; mod references; mod sidecar; @@ -809,11 +810,7 @@ pub(super) fn collect_variants( } pub(super) fn make_variant(repo: &Path, provider: &str, model: &str, file: &Path) -> Variant { - let relative_path = file - .strip_prefix(repo) - .unwrap_or(file) - .to_string_lossy() - .to_string(); + let relative_path = paths::slash_text(file.strip_prefix(repo).unwrap_or(file)); let content = fs::read_to_string(file).unwrap_or_default(); let mode = match extract_frontmatter_field(&content, "mode") { mode if mode.is_empty() => "replace".to_string(), diff --git a/src/services/paths.rs b/src/services/paths.rs new file mode 100644 index 00000000..91e4ed80 --- /dev/null +++ b/src/services/paths.rs @@ -0,0 +1,63 @@ +//! Path text that reads the same on every platform. +//! +//! Manifest keys, snapshot entries, and source-relative paths are compared +//! and split as `/`-separated text, so every path that becomes text passes +//! through here first. + +use std::borrow::Cow; +use std::path::Path; + +/// `text` with `/` between path components. +/// +/// Windows spells the separator `\`, a character no Windows file name can +/// hold, so rewriting it loses nothing. Elsewhere `\` is an ordinary name +/// character and stays for the caller to judge. +#[must_use] +pub fn slash_separators(text: &str) -> Cow<'_, str> { + if cfg!(windows) && text.contains('\\') { + Cow::Owned(text.replace('\\', "/")) + } else { + Cow::Borrowed(text) + } +} + +/// `path` as `/`-separated text; bytes that are not UTF-8 are replaced. +#[must_use] +pub fn slash_text(path: &Path) -> String { + slash_separators(&path.to_string_lossy()).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn joined_components_read_with_slashes_on_every_platform() { + let joined = Path::new("skills").join("Explain").join("SKILL.md"); + + assert_eq!(slash_text(&joined), "skills/Explain/SKILL.md"); + } + + #[test] + fn slash_separated_text_is_returned_unchanged() { + assert!(matches!( + slash_separators("rules/NoItemCounts.md"), + Cow::Borrowed("rules/NoItemCounts.md") + )); + } + + #[cfg(windows)] + #[test] + fn windows_separators_become_slashes() { + assert_eq!( + slash_separators(r"rules\.provenance\NoItemCounts.md.yaml"), + "rules/.provenance/NoItemCounts.md.yaml" + ); + } + + #[cfg(not(windows))] + #[test] + fn a_backslash_in_a_name_survives_where_it_is_not_a_separator() { + assert_eq!(slash_separators(r"rules\odd.md"), r"rules\odd.md"); + } +} diff --git a/src/skill_readiness.rs b/src/skill_readiness.rs index 42b08b46..4a14c935 100644 --- a/src/skill_readiness.rs +++ b/src/skill_readiness.rs @@ -360,7 +360,7 @@ fn owned_source(root: &Path, bundle: &BundleInspection) -> Result { let path = logical.to_str().ok_or("source paths must be valid UTF-8")?; - files.insert(path.into(), content.replace("\r\n", "\n")); + let path = crate::services::paths::slash_separators(path); + files.insert(path.into_owned(), content.replace("\r\n", "\n")); } _ if required_text(&logical) => { report.problem( "CSI008_LAYER_SOURCE", "generic", - &logical.display().to_string(), + &crate::services::paths::slash_text(&logical), "", "instruction text is not valid UTF-8 text", ); @@ -277,7 +278,7 @@ fn collect_text( report.problem( "CSI008_LAYER_SOURCE", "generic", - &relative.display().to_string(), + &crate::services::paths::slash_text(relative), "", &message, );