| 1 | //! Utility helpers shared across the `DeepSeek` CLI. |
| 2 | |
| 3 | use std::fs; |
| 4 | #[cfg(unix)] |
| 5 | use std::os::unix::fs::MetadataExt; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::process::Command; |
| 8 | |
| 9 | use codewhale_models::{ContentBlock, Message}; |
| 10 | use ignore::WalkBuilder; |
| 11 | use std::io; |
| 12 | |
| 13 | // Split out so the integration harness can `#[path]`-include it with |
| 14 | // `skills/install.rs`, which reads registry downloads through it. |
| 15 | mod response_body; |
| 16 | pub use response_body::read_response_body_capped; |
| 17 | |
| 18 | /// A writer that counts bytes written without storing them. |
| 19 | #[derive(Default)] |
| 20 | pub struct CountingWriter { |
| 21 | count: usize, |
| 22 | } |
| 23 | |
| 24 | impl CountingWriter { |
| 25 | pub fn new() -> Self { |
| 26 | Self { count: 0 } |
| 27 | } |
| 28 | |
| 29 | pub fn count(&self) -> usize { |
| 30 | self.count |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl io::Write for CountingWriter { |
| 35 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 36 | self.count += buf.len(); |
| 37 | Ok(buf.len()) |
| 38 | } |
| 39 | |
| 40 | fn flush(&mut self) -> io::Result<()> { |
| 41 | Ok(()) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | const LOG_FINGERPRINT_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; |
| 46 | const LOG_FINGERPRINT_PRIME: u64 = 0x0000_0100_0000_01b3; |
| 47 | |
| 48 | /// Compact token-count label for a model's context or output window: |
| 49 | /// `1M`, `1.05M`, `262K`, `500`. Shared by the model picker and the fleet |
| 50 | /// capability badges. Not the same scale as `agent_roster::format_tokens` |
| 51 | /// (`1.2k`), which labels usage rather than window size. |
| 52 | pub fn format_context_window(tokens: u64) -> String { |
| 53 | if tokens >= 1_000_000 { |
| 54 | if tokens.is_multiple_of(1_000_000) { |
| 55 | format!("{}M", tokens / 1_000_000) |
| 56 | } else { |
| 57 | let millions = format!("{:.2}", tokens as f64 / 1_000_000.0); |
| 58 | format!("{}M", millions.trim_end_matches('0').trim_end_matches('.')) |
| 59 | } |
| 60 | } else if tokens >= 1_000 { |
| 61 | format!("{}K", tokens / 1_000) |
| 62 | } else { |
| 63 | tokens.to_string() |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// Return a stable, non-reversible log label for an identifier. |
| 68 | /// |
| 69 | /// This is meant for correlation in diagnostics where the raw value may be a |
| 70 | /// session token, remote protocol session id, or other bearer-like handle. |
| 71 | #[must_use] |
| 72 | pub fn redacted_identifier_for_log(identifier: &str) -> String { |
| 73 | if identifier.is_empty() { |
| 74 | return "<redacted:empty>".to_string(); |
| 75 | } |
| 76 | |
| 77 | let mut hash = LOG_FINGERPRINT_OFFSET_BASIS; |
| 78 | for byte in identifier.as_bytes() { |
| 79 | hash ^= u64::from(*byte); |
| 80 | hash = hash.wrapping_mul(LOG_FINGERPRINT_PRIME); |
| 81 | } |
| 82 | hash ^= identifier.len() as u64; |
| 83 | hash = hash.wrapping_mul(LOG_FINGERPRINT_PRIME); |
| 84 | |
| 85 | format!("<redacted:{hash:016x}>") |
| 86 | } |
| 87 | |
| 88 | #[cfg(windows)] |
| 89 | pub fn suppress_console_window(cmd: &mut Command) { |
| 90 | use std::os::windows::process::CommandExt; |
| 91 | |
| 92 | const CREATE_NO_WINDOW: u32 = 0x0800_0000; |
| 93 | cmd.creation_flags(CREATE_NO_WINDOW); |
| 94 | } |
| 95 | |
| 96 | #[cfg(not(windows))] |
| 97 | pub fn suppress_console_window(_cmd: &mut Command) {} |
| 98 | |
| 99 | #[cfg(windows)] |
| 100 | pub fn suppress_tokio_console_window(cmd: &mut tokio::process::Command) { |
| 101 | const CREATE_NO_WINDOW: u32 = 0x0800_0000; |
| 102 | cmd.creation_flags(CREATE_NO_WINDOW); |
| 103 | } |
| 104 | |
| 105 | #[cfg(not(windows))] |
| 106 | pub fn suppress_tokio_console_window(_cmd: &mut tokio::process::Command) {} |
| 107 | |
| 108 | // === Project Mapping Helpers === |
| 109 | |
| 110 | /// Identify if a file is a "key" file for project identification. |
| 111 | #[must_use] |
| 112 | pub fn is_key_file(path: &Path) -> bool { |
| 113 | let Some(file_name) = path.file_name().and_then(|n| n.to_str()) else { |
| 114 | return false; |
| 115 | }; |
| 116 | |
| 117 | matches!( |
| 118 | file_name.to_lowercase().as_str(), |
| 119 | "cargo.toml" |
| 120 | | "package.json" |
| 121 | | "requirements.txt" |
| 122 | | "build.gradle" |
| 123 | | "pom.xml" |
| 124 | | "readme.md" |
| 125 | | "agents.md" |
| 126 | | "claude.md" |
| 127 | | "makefile" |
| 128 | | "dockerfile" |
| 129 | | "main.rs" |
| 130 | | "lib.rs" |
| 131 | | "index.js" |
| 132 | | "index.ts" |
| 133 | | "app.py" |
| 134 | ) |
| 135 | } |
| 136 | |
| 137 | /// Generate a high-level summary of the project based on key files. |
| 138 | /// |
| 139 | /// Output is byte-stable across calls: `WalkBuilder` doesn't sort siblings |
| 140 | /// (the OS readdir order leaks through), so the joined `key_files` list |
| 141 | /// would otherwise reorder run-to-run on filesystems that don't pre-sort. |
| 142 | /// Only matters when the workspace has no `AGENTS.md` / `CLAUDE.md`, since |
| 143 | /// the system prompt routes through `ProjectContext::as_system_block` first |
| 144 | /// and only falls back here when no project-context document exists. |
| 145 | #[must_use] |
| 146 | pub fn summarize_project(root: &Path) -> String { |
| 147 | let mut key_files = Vec::new(); |
| 148 | |
| 149 | let mut builder = WalkBuilder::new(root); |
| 150 | builder.hidden(false).follow_links(false).max_depth(Some(2)); |
| 151 | let walker = builder.build(); |
| 152 | |
| 153 | for entry in walker { |
| 154 | let entry = match entry { |
| 155 | Ok(entry) => entry, |
| 156 | Err(_) => continue, |
| 157 | }; |
| 158 | if entry.file_type().is_some_and(|ft| ft.is_symlink()) { |
| 159 | continue; |
| 160 | } |
| 161 | if is_key_file(entry.path()) |
| 162 | && let Ok(rel) = entry.path().strip_prefix(root) |
| 163 | { |
| 164 | key_files.push(rel.to_string_lossy().to_string()); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | key_files.sort(); |
| 169 | |
| 170 | if key_files.is_empty() { |
| 171 | return "Unknown project type".to_string(); |
| 172 | } |
| 173 | |
| 174 | let mut types = Vec::new(); |
| 175 | if key_files |
| 176 | .iter() |
| 177 | .any(|f| f.to_lowercase().contains("cargo.toml")) |
| 178 | { |
| 179 | types.push("Rust"); |
| 180 | } |
| 181 | if key_files |
| 182 | .iter() |
| 183 | .any(|f| f.to_lowercase().contains("package.json")) |
| 184 | { |
| 185 | types.push("JavaScript/Node.js"); |
| 186 | } |
| 187 | if key_files |
| 188 | .iter() |
| 189 | .any(|f| f.to_lowercase().contains("requirements.txt")) |
| 190 | { |
| 191 | types.push("Python"); |
| 192 | } |
| 193 | |
| 194 | if types.is_empty() { |
| 195 | format!("Project with key files: {}", key_files.join(", ")) |
| 196 | } else { |
| 197 | format!("A {} project", types.join(" and ")) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /// Generate a tree-like view of the project structure. |
| 202 | /// |
| 203 | /// Sibling order is fixed by sorting collected paths — the underlying |
| 204 | /// `WalkBuilder` follows the OS readdir order, which is non-deterministic |
| 205 | /// across filesystems. Sorting by full path preserves the tree shape (a |
| 206 | /// directory still precedes its children because `"src" < "src/lib.rs"`) |
| 207 | /// while making the rendered output byte-stable across runs. |
| 208 | #[must_use] |
| 209 | pub fn project_tree(root: &Path, max_depth: usize, follow_symlinks: bool) -> String { |
| 210 | let mut entries: Vec<(PathBuf, bool)> = Vec::new(); |
| 211 | |
| 212 | let mut builder = WalkBuilder::new(root); |
| 213 | builder |
| 214 | .hidden(false) |
| 215 | .follow_links(follow_symlinks) |
| 216 | .max_depth(Some(max_depth + 1)); |
| 217 | |
| 218 | for entry in builder.build().flatten() { |
| 219 | if entry.file_type().is_some_and(|ft| ft.is_symlink()) && !follow_symlinks { |
| 220 | continue; |
| 221 | } |
| 222 | let depth = entry.depth(); |
| 223 | if depth == 0 || depth > max_depth { |
| 224 | continue; |
| 225 | } |
| 226 | let rel_path = entry |
| 227 | .path() |
| 228 | .strip_prefix(root) |
| 229 | .unwrap_or(entry.path()) |
| 230 | .to_path_buf(); |
| 231 | let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir()); |
| 232 | entries.push((rel_path, is_dir)); |
| 233 | } |
| 234 | |
| 235 | entries.sort_by(|a, b| a.0.cmp(&b.0)); |
| 236 | |
| 237 | let mut tree_lines = Vec::with_capacity(entries.len()); |
| 238 | for (rel_path, is_dir) in entries { |
| 239 | let depth = rel_path.components().count(); |
| 240 | let indent = " ".repeat(depth.saturating_sub(1)); |
| 241 | let prefix = if is_dir { "DIR: " } else { "FILE: " }; |
| 242 | tree_lines.push(format!( |
| 243 | "{}{}{}", |
| 244 | indent, |
| 245 | prefix, |
| 246 | rel_path.file_name().unwrap_or_default().to_string_lossy() |
| 247 | )); |
| 248 | } |
| 249 | |
| 250 | tree_lines.join("\n") |
| 251 | } |
| 252 | |
| 253 | // === Filesystem Helpers === |
| 254 | |
| 255 | /// Permission policy for atomic writes. |
| 256 | /// |
| 257 | /// - [`AtomicWritePermissions::Private`]: keep tempfile's owner-only defaults |
| 258 | /// (used for CodeWhale internal persistence such as session/history/trust). |
| 259 | /// - [`AtomicWritePermissions::Workspace`]: match ordinary workspace file |
| 260 | /// semantics — new files request mode `0666` (kernel applies umask); existing |
| 261 | /// files retain ordinary `rwx` bits (not setuid/setgid/sticky). |
| 262 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 263 | enum AtomicWritePermissions { |
| 264 | Private, |
| 265 | Workspace, |
| 266 | } |
| 267 | |
| 268 | /// Atomically write `contents` to `path` using a temporary file + fsync + rename. |
| 269 | /// |
| 270 | /// Uses a **private** permission policy (Unix tempfile default `0600`). Prefer |
| 271 | /// [`write_atomic_workspace`] for user workspace source/config files. |
| 272 | /// |
| 273 | /// 1. Creates a `NamedTempFile` in the same directory as `path` (same filesystem). |
| 274 | /// 2. Writes `contents` to the temp file. |
| 275 | /// 3. Calls `sync_all()` on the temp file for durability. |
| 276 | /// 4. Atomically renames (persists) the temp file over `path`. |
| 277 | /// |
| 278 | /// On filesystems that support it (`ext4`, `apfs`, `ntfs`), the rename is |
| 279 | /// atomic — a concurrent reader sees either the old content or the new, never |
| 280 | /// a partial write. `sync_all` ensures the data is on stable storage before |
| 281 | /// the metadata change so an OS crash mid-rename doesn't lose data. |
| 282 | /// |
| 283 | /// # Errors |
| 284 | /// Returns `io::Error` if the parent directory cannot be determined, the temp |
| 285 | /// file cannot be created, the write fails, or the rename fails. |
| 286 | pub fn write_atomic(path: &Path, contents: &[u8]) -> std::io::Result<()> { |
| 287 | write_atomic_with_permissions(path, contents, AtomicWritePermissions::Private) |
| 288 | } |
| 289 | |
| 290 | /// Atomically write `contents` to a **user workspace** path. |
| 291 | /// |
| 292 | /// On Unix: |
| 293 | /// - New files request creation mode `0666`; the OS applies the process umask |
| 294 | /// (same candidate mode as ordinary `std::fs::write`). |
| 295 | /// - Existing files keep ordinary permission bits (`mode & 0o777`), including |
| 296 | /// executable bits. setuid/setgid/sticky are intentionally not restored. |
| 297 | /// |
| 298 | /// On Windows this matches [`write_atomic`] (no POSIX mode simulation). |
| 299 | /// |
| 300 | /// # Errors |
| 301 | /// Same failure modes as [`write_atomic`]. |
| 302 | pub fn write_atomic_workspace(path: &Path, contents: &[u8]) -> std::io::Result<()> { |
| 303 | // Hard-link guard (issue #5569): a workspace path that shares its inode |
| 304 | // with another name cannot be proven to stay inside the writable root by |
| 305 | // path checks. Atomic rename would replace the directory entry (leaving |
| 306 | // the outside link on the old inode), but that silently splits the pair |
| 307 | // and would not block a future non-atomic writer. Fail closed on both |
| 308 | // platforms that can count links. |
| 309 | if let Some(links) = hard_link_count(path) |
| 310 | && links > 1 |
| 311 | { |
| 312 | return Err(std::io::Error::new( |
| 313 | std::io::ErrorKind::InvalidData, |
| 314 | format!( |
| 315 | "refusing to rewrite {}: the file has {links} hard links and path checks cannot prove the other links stay inside the workspace; copy it to a new name to break the link", |
| 316 | path.display(), |
| 317 | ), |
| 318 | )); |
| 319 | } |
| 320 | write_atomic_with_permissions(path, contents, AtomicWritePermissions::Workspace) |
| 321 | } |
| 322 | |
| 323 | /// Hard-link count for an existing regular file, or `None` when the platform |
| 324 | /// cannot answer or the path is not a regular file. |
| 325 | /// |
| 326 | /// `None` means "unknown", never "one". A caller guarding against link |
| 327 | /// escapes must treat an unknown count as unguarded, not as safe. |
| 328 | #[cfg(unix)] |
| 329 | fn hard_link_count(path: &Path) -> Option<u64> { |
| 330 | let metadata = std::fs::metadata(path).ok()?; |
| 331 | metadata.is_file().then(|| metadata.nlink()) |
| 332 | } |
| 333 | |
| 334 | /// Windows counts links too — `std` does not expose it, but the Win32 call |
| 335 | /// that does is already used for the workspace `.env` guard in `lib.rs`. |
| 336 | /// Leaving this side unguarded meant a hard-linked file outside the |
| 337 | /// workspace was rewritable on Windows and refused on Unix, which is the |
| 338 | /// worse half of the platform to leave open. |
| 339 | /// |
| 340 | /// The handle is opened read-only and closed by `File`'s Drop, so this adds |
| 341 | /// one open/close on a path that is about to be rewritten anyway. |
| 342 | #[cfg(windows)] |
| 343 | fn hard_link_count(path: &Path) -> Option<u64> { |
| 344 | use std::os::windows::io::AsRawHandle; |
| 345 | use windows::Win32::Foundation::HANDLE; |
| 346 | use windows::Win32::Storage::FileSystem::{ |
| 347 | BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle, |
| 348 | }; |
| 349 | |
| 350 | let metadata = std::fs::metadata(path).ok()?; |
| 351 | if !metadata.is_file() { |
| 352 | return None; |
| 353 | } |
| 354 | let file = std::fs::File::open(path).ok()?; |
| 355 | let mut information = BY_HANDLE_FILE_INFORMATION::default(); |
| 356 | // SAFETY: `file` owns a live kernel handle for the duration of the call |
| 357 | // and `information` stays writable across it. The call is synchronous and |
| 358 | // performs no path lookup or re-open. |
| 359 | unsafe { |
| 360 | GetFileInformationByHandle(HANDLE(file.as_raw_handle()), &mut information).ok()?; |
| 361 | } |
| 362 | Some(u64::from(information.nNumberOfLinks)) |
| 363 | } |
| 364 | |
| 365 | #[cfg(not(any(unix, windows)))] |
| 366 | fn hard_link_count(_path: &Path) -> Option<u64> { |
| 367 | None |
| 368 | } |
| 369 | |
| 370 | /// Backoff before re-attempting a Windows atomic publication, or `None` when |
| 371 | /// `error` must be surfaced to the caller. |
| 372 | /// |
| 373 | /// Windows can briefly deny the rename that publishes a temporary file while |
| 374 | /// Defender, the indexer, or a concurrent reader still holds the source or the |
| 375 | /// destination without delete sharing. `MoveFileExW` then reports a sharing or |
| 376 | /// lock violation that clears on its own, while a real permission failure |
| 377 | /// repeats until the attempts run out. |
| 378 | /// |
| 379 | /// The Fleet writers, the plugin state writer and plugin snapshot publication |
| 380 | /// share this classification and schedule, to tolerate brief sharing conflicts |
| 381 | /// without letting any path invent a broader retry of its own. Only the rename is |
| 382 | /// re-attempted: callers keep the temporary they already wrote and synced, so a |
| 383 | /// retry never rewrites bytes or widens the window in which data can be lost. |
| 384 | /// |
| 385 | /// The classification stays deliberately narrow. `ERROR_ALREADY_EXISTS` in |
| 386 | /// particular is a real answer for no-clobber publication — Fleet artifact |
| 387 | /// immutability depends on receiving it — so it is returned unchanged. |
| 388 | #[cfg(windows)] |
| 389 | pub fn windows_publish_retry_delay( |
| 390 | error: &std::io::Error, |
| 391 | attempt: usize, |
| 392 | ) -> Option<std::time::Duration> { |
| 393 | const MAX_PERSIST_ATTEMPTS: usize = 12; |
| 394 | // 5 ERROR_ACCESS_DENIED, 32 ERROR_SHARING_VIOLATION, 33 ERROR_LOCK_VIOLATION. |
| 395 | let transient = error.kind() == std::io::ErrorKind::PermissionDenied |
| 396 | || matches!(error.raw_os_error(), Some(5 | 32 | 33)); |
| 397 | if !transient || attempt + 1 >= MAX_PERSIST_ATTEMPTS { |
| 398 | return None; |
| 399 | } |
| 400 | Some(std::time::Duration::from_millis( |
| 401 | 10u64.saturating_mul(1u64 << attempt.min(6)), |
| 402 | )) |
| 403 | } |
| 404 | |
| 405 | fn write_atomic_with_permissions( |
| 406 | path: &Path, |
| 407 | contents: &[u8], |
| 408 | #[cfg_attr(not(unix), allow(unused_variables))] permission_policy: AtomicWritePermissions, |
| 409 | ) -> std::io::Result<()> { |
| 410 | write_atomic_scoped(path, contents, permission_policy, AtomicWriteScope::Single) |
| 411 | } |
| 412 | |
| 413 | /// Whether one write also pays its directory's costs, or a batch pays them |
| 414 | /// once for the whole set — see [`write_atomic_batch`]. |
| 415 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 416 | enum AtomicWriteScope { |
| 417 | /// Sweep this directory for stale temp files (at most once per |
| 418 | /// `STALE_AFTER`) and fsync it: what a single write should do, and what |
| 419 | /// every caller of `write_atomic` gets. |
| 420 | Single, |
| 421 | /// Leave both to the caller. Used only by [`write_atomic_batch`]. |
| 422 | Batch, |
| 423 | } |
| 424 | |
| 425 | /// Write many files, and pay each directory's costs once. |
| 426 | /// |
| 427 | /// Every [`write_atomic`] call fsyncs its directory, which is exactly right |
| 428 | /// for one record at a time. A caller publishing a thousand records into one |
| 429 | /// directory pays that thousand times, though. The stale-temp sweep is |
| 430 | /// already throttled to once per directory per `STALE_AFTER`, because |
| 431 | /// scanning a store directory of tens of thousands of entries per file is |
| 432 | /// minutes of work that buys nothing (measured before the throttle: 22 ms per |
| 433 | /// item write, 34 s for one fork's clone). |
| 434 | /// |
| 435 | /// The batch goes through the same throttled sweep once per directory, writes |
| 436 | /// every file with the same atomic replace and per-file data sync, and fsyncs |
| 437 | /// each directory once at the end. Per-file durability is unchanged; only the |
| 438 | /// per-file directory work is hoisted out of the loop. |
| 439 | /// |
| 440 | /// Ordering is still the caller's job: a batch that publishes a graph of |
| 441 | /// records must write its commit record last, as the single-write callers do. |
| 442 | pub fn write_atomic_batch(files: &[(PathBuf, Vec<u8>)]) -> std::io::Result<()> { |
| 443 | let mut parents: Vec<&Path> = Vec::new(); |
| 444 | for (path, _) in files { |
| 445 | if let Some(parent) = path.parent() |
| 446 | && !parents.contains(&parent) |
| 447 | { |
| 448 | parents.push(parent); |
| 449 | } |
| 450 | } |
| 451 | for parent in &parents { |
| 452 | sweep_owned_dir_if_due(parent); |
| 453 | } |
| 454 | for (path, contents) in files { |
| 455 | write_atomic_scoped( |
| 456 | path, |
| 457 | contents, |
| 458 | AtomicWritePermissions::Private, |
| 459 | AtomicWriteScope::Batch, |
| 460 | )?; |
| 461 | } |
| 462 | for parent in &parents { |
| 463 | sync_directory(parent); |
| 464 | } |
| 465 | Ok(()) |
| 466 | } |
| 467 | |
| 468 | /// The file name Windows will create for `path`. The native rename used by |
| 469 | /// `write_atomic_scoped` takes the name literally, while Win32 path APIs drop |
| 470 | /// trailing dots and spaces and map device names (`CON`); refuse a name that |
| 471 | /// Windows would rewrite instead of creating a file nothing else can open. |
| 472 | /// A `:` names an NTFS alternate data stream (`notes:private`, `con:x`), so |
| 473 | /// the write would land in a hidden stream rather than a file; refuse it too. |
| 474 | #[cfg(windows)] |
| 475 | fn windows_atomic_target_name(path: &Path) -> std::io::Result<std::ffi::OsString> { |
| 476 | let invalid = || { |
| 477 | std::io::Error::new( |
| 478 | std::io::ErrorKind::InvalidInput, |
| 479 | format!( |
| 480 | "Windows would not write this file name as given: {}", |
| 481 | path.display() |
| 482 | ), |
| 483 | ) |
| 484 | }; |
| 485 | let name = path.file_name().ok_or_else(invalid)?; |
| 486 | if name.to_string_lossy().contains(':') { |
| 487 | return Err(invalid()); |
| 488 | } |
| 489 | // Path normalization alone can leave a reserved DOS basename unchanged. |
| 490 | // Reject them explicitly, including extensions and the documented |
| 491 | // superscript port digits, before the native rename can create one. |
| 492 | let stem = name |
| 493 | .to_string_lossy() |
| 494 | .split('.') |
| 495 | .next() |
| 496 | .unwrap_or_default() |
| 497 | .trim_end_matches(' ') |
| 498 | .to_ascii_uppercase(); |
| 499 | let reserved_port = stem |
| 500 | .strip_prefix("COM") |
| 501 | .or_else(|| stem.strip_prefix("LPT")) |
| 502 | .is_some_and(|port| { |
| 503 | matches!( |
| 504 | port, |
| 505 | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" |
| 506 | ) |
| 507 | }); |
| 508 | if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || reserved_port { |
| 509 | return Err(invalid()); |
| 510 | } |
| 511 | let absolute = std::path::absolute(path)?; |
| 512 | if absolute.file_name() != Some(name) |
| 513 | || absolute.as_os_str().to_string_lossy().starts_with(r"\\.\") |
| 514 | { |
| 515 | return Err(invalid()); |
| 516 | } |
| 517 | Ok(name.to_owned()) |
| 518 | } |
| 519 | |
| 520 | fn write_atomic_scoped( |
| 521 | path: &Path, |
| 522 | contents: &[u8], |
| 523 | #[cfg_attr(not(unix), allow(unused_variables))] permission_policy: AtomicWritePermissions, |
| 524 | scope: AtomicWriteScope, |
| 525 | ) -> std::io::Result<()> { |
| 526 | let parent = path.parent().ok_or_else(|| { |
| 527 | std::io::Error::new( |
| 528 | std::io::ErrorKind::InvalidInput, |
| 529 | format!("path has no parent directory: {}", path.display()), |
| 530 | ) |
| 531 | })?; |
| 532 | |
| 533 | // Capture ordinary rwx bits before replacement. Use symlink_metadata so we |
| 534 | // do not follow links: an inaccessible or dangling symlink target must not |
| 535 | // abort the write — rename still replaces the directory entry, matching |
| 536 | // the pre-#4606 private write_atomic behavior. Symlink entries themselves |
| 537 | // are treated as "no mode to preserve" (new ordinary file after rename); |
| 538 | // only regular-file modes are restored. Mask with 0o777 so setuid/setgid/ |
| 539 | // sticky are never restored after rewriting content. |
| 540 | #[cfg(unix)] |
| 541 | let existing_workspace_mode = if permission_policy == AtomicWritePermissions::Workspace { |
| 542 | match fs::symlink_metadata(path) { |
| 543 | Ok(metadata) if metadata.file_type().is_symlink() => None, |
| 544 | Ok(metadata) => { |
| 545 | use std::os::unix::fs::PermissionsExt; |
| 546 | Some(metadata.permissions().mode() & 0o777) |
| 547 | } |
| 548 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, |
| 549 | Err(err) => return Err(err), |
| 550 | } |
| 551 | } else { |
| 552 | None |
| 553 | }; |
| 554 | |
| 555 | // Use parent directory so the rename is on the same filesystem. |
| 556 | #[cfg(unix)] |
| 557 | let mut builder = tempfile::Builder::new(); |
| 558 | #[cfg(not(unix))] |
| 559 | let builder = tempfile::Builder::new(); |
| 560 | |
| 561 | // New workspace files should behave like ordinary files opened with |
| 562 | // creation mode 0666. The kernel applies the inherited process umask. |
| 563 | // Do NOT chmod after create: set_permissions bypasses umask. |
| 564 | #[cfg(unix)] |
| 565 | if permission_policy == AtomicWritePermissions::Workspace && existing_workspace_mode.is_none() { |
| 566 | use std::os::unix::fs::PermissionsExt; |
| 567 | builder.permissions(fs::Permissions::from_mode(0o666)); |
| 568 | } |
| 569 | |
| 570 | // Reclaim our own strays before adding another, at most once per |
| 571 | // directory per `STALE_AFTER` (see `sweep_stale_atomic_write_temps`). |
| 572 | // Private permission policy is also used for user-chosen destinations |
| 573 | // such as `/save <path>`; only sweep Codewhale-owned state/config dirs. |
| 574 | if permission_policy == AtomicWritePermissions::Private && scope == AtomicWriteScope::Single { |
| 575 | sweep_owned_dir_if_due(parent); |
| 576 | } |
| 577 | |
| 578 | // Validated before any temp exists, so a refused name leaves nothing. |
| 579 | #[cfg(windows)] |
| 580 | let target_name = windows_atomic_target_name(path)?; |
| 581 | #[cfg(not(windows))] |
| 582 | let mut tmp = builder.tempfile_in(parent)?; |
| 583 | // DELETE on the temp handle lets Windows rename through that handle. |
| 584 | #[cfg(windows)] |
| 585 | let mut tmp = { |
| 586 | use std::os::windows::fs::OpenOptionsExt; |
| 587 | use windows_sys::Win32::Storage::FileSystem::{ |
| 588 | DELETE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ, |
| 589 | }; |
| 590 | builder.make_in(parent, |temp| { |
| 591 | fs::OpenOptions::new() |
| 592 | .write(true) |
| 593 | .create_new(true) |
| 594 | .access_mode(FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE) |
| 595 | .share_mode(FILE_SHARE_READ) |
| 596 | .open(temp) |
| 597 | })? |
| 598 | }; |
| 599 | |
| 600 | #[cfg(not(windows))] |
| 601 | { |
| 602 | std::io::Write::write_all(&mut tmp, contents)?; |
| 603 | |
| 604 | // Atomic replacement creates a new inode. Restore ordinary access / |
| 605 | // executable bits of an existing workspace file before persisting. |
| 606 | #[cfg(unix)] |
| 607 | if let Some(mode) = existing_workspace_mode { |
| 608 | // Restoring the access bits of the file this replaces. A mount that |
| 609 | // assigns modes itself (HarmonyOS hmdfs) returns EPERM for every |
| 610 | // `chmod`; `tighten_mode` tolerates only that, so the write lands |
| 611 | // and a real permission failure is still reported. |
| 612 | codewhale_config::private_directory::tighten_mode_of(tmp.as_file(), tmp.path(), mode) |
| 613 | .map_err(|error| std::io::Error::other(error.to_string()))?; |
| 614 | } |
| 615 | |
| 616 | tmp.as_file().sync_all()?; |
| 617 | tmp.persist(path)?; |
| 618 | } |
| 619 | #[cfg(windows)] |
| 620 | { |
| 621 | // MoveFileExW (tempfile::persist) reopens the destination directory |
| 622 | // with FILE_ADD_FILE, which conflicts with Fleet's read-only-shared |
| 623 | // ancestor pins (fleet/files.rs). Rename through the synced temp handle |
| 624 | // with a bare file name, so the parent is never reopened; the rename |
| 625 | // retries transient sharing/lock failures itself. |
| 626 | let result = (|| { |
| 627 | std::io::Write::write_all(&mut tmp, contents)?; |
| 628 | tmp.as_file().sync_all()?; |
| 629 | crate::files::rename_windows_opened(tmp.as_file(), &target_name, true) |
| 630 | })(); |
| 631 | match result { |
| 632 | // The temp name is vacant now; never unlink a later entry. |
| 633 | Ok(()) => tmp.disable_cleanup(true), |
| 634 | Err(err) => { |
| 635 | // Close the delete-denying handle before deleting the temp. |
| 636 | let _ = tmp.into_temp_path().close(); |
| 637 | return Err(std::io::Error::new( |
| 638 | err.kind(), |
| 639 | format!("replace {}: {err}", path.display()), |
| 640 | )); |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | // Fsync the parent directory so the rename (the new directory entry) is |
| 645 | // itself durable — otherwise a power loss right after the rename can lose |
| 646 | // it even though the file data was synced, silently dropping a |
| 647 | // crash-recovery checkpoint. Best-effort: not all platforms permit |
| 648 | // opening a directory for sync, so a failure here is not fatal. A batch |
| 649 | // hoists this to one sync per directory (see `write_atomic_batch`). |
| 650 | if scope == AtomicWriteScope::Single { |
| 651 | sync_directory(parent); |
| 652 | } |
| 653 | Ok(()) |
| 654 | } |
| 655 | |
| 656 | /// Best-effort directory sync: not all platforms or filesystems (for example |
| 657 | /// Windows, network shares, or FUSE mounts) permit opening or fsyncing a |
| 658 | /// directory handle, so a failure here is never fatal. A missing directory, an |
| 659 | /// open failure outside unix and a filesystem that refuses directory sync are |
| 660 | /// ignored; any other failure is logged at warn. |
| 661 | pub fn sync_directory(parent: &Path) { |
| 662 | match std::fs::File::open(parent) { |
| 663 | Ok(dir) => report_directory_sync(parent, dir.sync_all()), |
| 664 | Err(error) if cfg!(unix) && error.kind() != io::ErrorKind::NotFound => { |
| 665 | tracing::warn!( |
| 666 | path = %parent.display(), |
| 667 | "directory sync skipped: could not open directory: {error}" |
| 668 | ); |
| 669 | } |
| 670 | Err(_) => {} |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | pub fn report_directory_sync(dir: &Path, result: io::Result<()>) { |
| 675 | if let Err(error) = result |
| 676 | && !is_directory_sync_refusal(&error) |
| 677 | { |
| 678 | tracing::warn!(path = %dir.display(), "directory sync failed: {error}"); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | pub fn is_directory_sync_refusal(error: &io::Error) -> bool { |
| 683 | if matches!( |
| 684 | error.kind(), |
| 685 | io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput |
| 686 | ) { |
| 687 | return true; |
| 688 | } |
| 689 | #[cfg(unix)] |
| 690 | let refusals = [ |
| 691 | libc::EINVAL, |
| 692 | libc::ENOTSUP, |
| 693 | libc::EOPNOTSUPP, |
| 694 | libc::ENOSYS, |
| 695 | libc::EISDIR, |
| 696 | libc::EBADF, |
| 697 | libc::EROFS, |
| 698 | ]; |
| 699 | #[cfg(windows)] |
| 700 | let refusals = [ |
| 701 | windows_sys::Win32::Foundation::ERROR_INVALID_FUNCTION, |
| 702 | windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED, |
| 703 | windows_sys::Win32::Foundation::ERROR_INVALID_HANDLE, |
| 704 | windows_sys::Win32::Foundation::ERROR_NOT_SUPPORTED, |
| 705 | windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER, |
| 706 | ] |
| 707 | .map(|code| code as i32); |
| 708 | #[cfg(not(any(unix, windows)))] |
| 709 | let refusals: [i32; 0] = []; |
| 710 | error |
| 711 | .raw_os_error() |
| 712 | .is_some_and(|code| refusals.contains(&code)) |
| 713 | } |
| 714 | |
| 715 | /// True when `dir` is under `$CODEWHALE_HOME` / `~/.codewhale`, or the ambient |
| 716 | /// `~/.deepseek` legacy root when that root is still in play. |
| 717 | fn is_codewhale_owned_state_dir(dir: &Path) -> bool { |
| 718 | if dir.as_os_str().is_empty() { |
| 719 | return false; |
| 720 | } |
| 721 | let primary = codewhale_paths::codewhale_home().ok().flatten(); |
| 722 | let legacy = (!codewhale_paths::codewhale_home_is_explicit()) |
| 723 | .then(codewhale_paths::legacy_deepseek_home) |
| 724 | .flatten(); |
| 725 | [primary, legacy].into_iter().flatten().any(|root| { |
| 726 | if root.as_os_str().is_empty() { |
| 727 | return false; |
| 728 | } |
| 729 | let Ok(physical_root) = std::fs::canonicalize(root) else { |
| 730 | return false; |
| 731 | }; |
| 732 | let Ok(physical_dir) = std::fs::canonicalize(dir) else { |
| 733 | return false; |
| 734 | }; |
| 735 | physical_dir.starts_with(physical_root) |
| 736 | }) |
| 737 | } |
| 738 | |
| 739 | const STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(60 * 60); |
| 740 | |
| 741 | fn sweep_owned_dir_if_due(dir: &Path) { |
| 742 | use std::collections::HashMap; |
| 743 | use std::sync::{Mutex, OnceLock, PoisonError}; |
| 744 | use std::time::Instant; |
| 745 | |
| 746 | static LAST_SWEPT: OnceLock<Mutex<HashMap<PathBuf, Instant>>> = OnceLock::new(); |
| 747 | let now = Instant::now(); |
| 748 | { |
| 749 | let mut last_swept = LAST_SWEPT |
| 750 | .get_or_init(Default::default) |
| 751 | .lock() |
| 752 | .unwrap_or_else(PoisonError::into_inner); |
| 753 | if last_swept |
| 754 | .get(dir) |
| 755 | .is_some_and(|swept| now.saturating_duration_since(*swept) < STALE_AFTER) |
| 756 | { |
| 757 | return; |
| 758 | } |
| 759 | last_swept.retain(|_, swept| now.saturating_duration_since(*swept) < STALE_AFTER); |
| 760 | last_swept.insert(dir.to_path_buf(), now); |
| 761 | } |
| 762 | if is_codewhale_owned_state_dir(dir) { |
| 763 | sweep_stale_atomic_write_temps(dir); |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | /// Remove `.tmpXXXXXX` files this writer stranded in `dir` on an earlier run. |
| 768 | /// |
| 769 | /// `NamedTempFile` deletes itself on drop, so an ordinary failure — or an |
| 770 | /// ordinary exit — leaves nothing behind. A `SIGKILL` between `tempfile_in` |
| 771 | /// and `persist` cannot run a destructor, so the partial file survives, and |
| 772 | /// nothing ever collected it: five such strays (46 KB each, mode 0600) were |
| 773 | /// sitting in a real `~/.codewhale/` from a single day three weeks earlier. |
| 774 | /// They accumulate silently in the user's config directory forever. |
| 775 | /// |
| 776 | /// Deliberately conservative, because this deletes files under `$HOME`: |
| 777 | /// |
| 778 | /// - **Product directories only** — parent must be under `$CODEWHALE_HOME` |
| 779 | /// (or `~/.codewhale`) or the ambient `~/.deepseek` legacy root. User-chosen |
| 780 | /// destinations such as `/save <path>` keep the private permission policy |
| 781 | /// but are not swept (enforced at the call site). |
| 782 | /// - **Exact shape only** — `tempfile`'s default naming is the literal prefix |
| 783 | /// `.tmp` followed by exactly six alphanumerics and nothing else. A user file |
| 784 | /// called `.tmp`, `.tmpfile`, or `.tmp-backup` does not match. |
| 785 | /// - **Older than an hour** — so a concurrent write by another Codewhale |
| 786 | /// process is never raced. Same threshold and reasoning as |
| 787 | /// `shell_dispatcher::sweep_stale_temp_ps1`. |
| 788 | /// - **Best effort** — every failure is ignored; this must never turn a |
| 789 | /// successful write into an error. |
| 790 | fn sweep_stale_atomic_write_temps(dir: &Path) { |
| 791 | let Ok(entries) = fs::read_dir(dir) else { |
| 792 | return; |
| 793 | }; |
| 794 | for entry in entries.flatten() { |
| 795 | let name = entry.file_name(); |
| 796 | let Some(name) = name.to_str() else { |
| 797 | continue; |
| 798 | }; |
| 799 | if !is_stray_atomic_write_temp_name(name) { |
| 800 | continue; |
| 801 | } |
| 802 | // Only regular files; never follow or remove a symlink or directory. |
| 803 | let Ok(metadata) = entry.metadata() else { |
| 804 | continue; |
| 805 | }; |
| 806 | if !metadata.is_file() { |
| 807 | continue; |
| 808 | } |
| 809 | let stale = metadata |
| 810 | .modified() |
| 811 | .ok() |
| 812 | .and_then(|modified| modified.elapsed().ok()) |
| 813 | .is_some_and(|age| age > STALE_AFTER); |
| 814 | if stale { |
| 815 | let _ = fs::remove_file(entry.path()); |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | /// `tempfile`'s default name: `.tmp` + exactly six ASCII alphanumerics. |
| 821 | fn is_stray_atomic_write_temp_name(name: &str) -> bool { |
| 822 | let Some(random) = name.strip_prefix(".tmp") else { |
| 823 | return false; |
| 824 | }; |
| 825 | random.len() == 6 && random.chars().all(|c| c.is_ascii_alphanumeric()) |
| 826 | } |
| 827 | |
| 828 | /// Spawn a tokio task with panic supervision. |
| 829 | /// |
| 830 | /// Wraps the future in `AssertUnwindSafe` + `catch_unwind`. On panic: |
| 831 | /// 1. Logs the panic with the task name and caller location via `tracing::error!`. |
| 832 | /// 2. Writes a crash dump to the selected profile's `crashes/` directory. |
| 833 | /// |
| 834 | /// The returned `JoinHandle` resolves to `()` — the panic is caught and |
| 835 | /// handled internally so the parent process stays alive. |
| 836 | pub fn spawn_supervised<F>( |
| 837 | name: &'static str, |
| 838 | location: &'static std::panic::Location<'static>, |
| 839 | future: F, |
| 840 | ) -> tokio::task::JoinHandle<()> |
| 841 | where |
| 842 | F: std::future::Future<Output = ()> + Send + 'static, |
| 843 | { |
| 844 | tokio::spawn(async move { |
| 845 | use futures_util::FutureExt; |
| 846 | let result = std::panic::AssertUnwindSafe(future).catch_unwind().await; |
| 847 | if let Err(panic_info) = result { |
| 848 | let msg = panic_message(&*panic_info); |
| 849 | tracing::error!( |
| 850 | target: "panic", |
| 851 | "Task '{name}' panicked at {}: {msg}", |
| 852 | location, |
| 853 | ); |
| 854 | // Write crash dump (best-effort) |
| 855 | let _ = write_panic_dump(name, location, &msg); |
| 856 | } |
| 857 | }) |
| 858 | } |
| 859 | |
| 860 | /// Extract a human-readable message from a caught panic payload (the `Err` |
| 861 | /// value of `catch_unwind`). Mirrors how the panic hook formats `&str` and |
| 862 | /// `String` payloads so crash dumps stay consistent across call sites. |
| 863 | #[must_use] |
| 864 | pub fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { |
| 865 | if let Some(s) = panic.downcast_ref::<&str>() { |
| 866 | (*s).to_string() |
| 867 | } else if let Some(s) = panic.downcast_ref::<String>() { |
| 868 | s.clone() |
| 869 | } else { |
| 870 | "unknown panic".to_string() |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | /// Record a panic that was caught at a call site (via `catch_unwind`) rather |
| 875 | /// than by a task supervisor. Logs it on the `panic` target and writes a |
| 876 | /// best-effort crash dump to the selected profile's `crashes/`, so diagnostics land in |
| 877 | /// the same place `spawn_supervised` writes them even when the caller recovers |
| 878 | /// and keeps running. |
| 879 | #[track_caller] |
| 880 | pub fn record_caught_panic(name: &'static str, message: &str) { |
| 881 | let location = std::panic::Location::caller(); |
| 882 | tracing::error!(target: "panic", "Task '{name}' panicked at {location}: {message}"); |
| 883 | let _ = write_panic_dump(name, location, message); |
| 884 | // A caught panic is still a panic. The site is allowlist-reduced to |
| 885 | // `crates/…` or the literal `<dep>`, and `message` is deliberately not |
| 886 | // read: a slicing panic embeds the entire string being sliced. The exit |
| 887 | // class is left alone — the caller recovered, so this process is not |
| 888 | // ending here. A no-op unless this process was armed. |
| 889 | codewhale_telemetry::record_blocking(codewhale_telemetry::Event::Panic { |
| 890 | site: codewhale_telemetry::reduce_panic_site( |
| 891 | location.file(), |
| 892 | location.line(), |
| 893 | location.column(), |
| 894 | ), |
| 895 | }); |
| 896 | } |
| 897 | |
| 898 | /// Write a panic dump file to the selected profile's `crashes/` directory. |
| 899 | /// |
| 900 | /// Creates the directory if needed and writes a timestamped log |
| 901 | /// with the task name, caller location, and panic message. |
| 902 | /// Best-effort — failures are silently ignored. |
| 903 | fn write_panic_dump( |
| 904 | name: &str, |
| 905 | location: &std::panic::Location<'_>, |
| 906 | message: &str, |
| 907 | ) -> std::io::Result<()> { |
| 908 | let crash_dir = codewhale_config::codewhale_home() |
| 909 | .map_err(std::io::Error::other)? |
| 910 | .join("crashes"); |
| 911 | write_panic_dump_to(&crash_dir, name, location, message) |
| 912 | } |
| 913 | |
| 914 | fn write_panic_dump_to( |
| 915 | crash_dir: &Path, |
| 916 | name: &str, |
| 917 | location: &std::panic::Location<'_>, |
| 918 | message: &str, |
| 919 | ) -> std::io::Result<()> { |
| 920 | use chrono::Utc; |
| 921 | std::fs::create_dir_all(crash_dir)?; |
| 922 | let timestamp = Utc::now().format("%Y%m%dT%H%M%S%.3fZ"); |
| 923 | let filename = format!("{timestamp}-{name}.log"); |
| 924 | let path = crash_dir.join(&filename); |
| 925 | let contents = |
| 926 | format!("Task: {name}\nLocation: {location}\nTimestamp: {timestamp}\nPanic: {message}\n"); |
| 927 | std::fs::write(&path, contents)?; |
| 928 | Ok(()) |
| 929 | } |
| 930 | |
| 931 | /// Fire-and-forget `spawn_blocking` with panic dump protection. |
| 932 | /// |
| 933 | /// In contrast to `spawn_supervised` (which wraps `tokio::spawn` for async |
| 934 | /// tasks), this helper wraps `tokio::task::spawn_blocking`. Use it when a |
| 935 | /// CPU-bound or blocking-I/O task must run off the async runtime and its |
| 936 | /// completion is *not* awaited — for example a post-turn disk snapshot or a |
| 937 | /// file-tree build polled later via a shared data structure. If the closure |
| 938 | /// panics, a crash dump is written to the selected profile's `crashes/` and the panic |
| 939 | /// is logged at ERROR level rather than being silently swallowed. |
| 940 | #[track_caller] |
| 941 | pub fn spawn_blocking_supervised<F>(name: &'static str, f: F) -> tokio::task::JoinHandle<()> |
| 942 | where |
| 943 | F: FnOnce() + Send + 'static, |
| 944 | { |
| 945 | let location = std::panic::Location::caller(); |
| 946 | #[cfg(any(test, feature = "test-support"))] |
| 947 | let env_ticket = crate::test_env_lock::env_scope_ticket(); |
| 948 | tokio::task::spawn_blocking(move || { |
| 949 | #[cfg(any(test, feature = "test-support"))] |
| 950 | let _membership = crate::test_env_lock::join_env_scope(env_ticket); |
| 951 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); |
| 952 | if let Err(panic_info) = result { |
| 953 | let msg = panic_message(&*panic_info); |
| 954 | tracing::error!( |
| 955 | target: "panic", |
| 956 | "Blocking task '{name}' panicked at {location}: {msg}", |
| 957 | ); |
| 958 | let _ = write_panic_dump(name, location, &msg); |
| 959 | } |
| 960 | }) |
| 961 | } |
| 962 | |
| 963 | /// Truncate a string to a maximum length, adding an ellipsis if truncated. |
| 964 | /// |
| 965 | /// Uses char boundaries to avoid panicking on multi-byte UTF-8 characters. |
| 966 | #[must_use] |
| 967 | pub fn truncate_with_ellipsis(s: &str, max_len: usize, ellipsis: &str) -> String { |
| 968 | if s.len() <= max_len { |
| 969 | return s.to_string(); |
| 970 | } |
| 971 | let budget = max_len.saturating_sub(ellipsis.len()); |
| 972 | // Find the last char boundary that fits within the byte budget. |
| 973 | let safe_end = s |
| 974 | .char_indices() |
| 975 | .map(|(i, _)| i) |
| 976 | .take_while(|&i| i <= budget) |
| 977 | .last() |
| 978 | .unwrap_or(0); |
| 979 | format!("{}{}", &s[..safe_end], ellipsis) |
| 980 | } |
| 981 | |
| 982 | /// Percent-encode a string for use in URL query parameters. |
| 983 | /// |
| 984 | /// Encodes all characters except unreserved characters (A-Z, a-z, 0-9, `-`, `_`, `.`, `~`). |
| 985 | /// Spaces are encoded as `+`. |
| 986 | #[must_use] |
| 987 | pub fn url_encode(input: &str) -> String { |
| 988 | let mut encoded = String::new(); |
| 989 | for ch in input.bytes() { |
| 990 | match ch { |
| 991 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 992 | encoded.push(ch as char) |
| 993 | } |
| 994 | b' ' => encoded.push('+'), |
| 995 | _ => encoded.push_str(&format!("%{ch:02X}")), |
| 996 | } |
| 997 | } |
| 998 | encoded |
| 999 | } |
| 1000 | |
| 1001 | /// Show `value` relative to `workspace` when it is an absolute path inside |
| 1002 | /// it, so a card never spends a row on the workspace prefix. |
| 1003 | pub fn workspace_relative(value: &str, workspace: &Path) -> String { |
| 1004 | let path = Path::new(value); |
| 1005 | if workspace.as_os_str().is_empty() || !path.is_absolute() { |
| 1006 | return value.to_string(); |
| 1007 | } |
| 1008 | match path.strip_prefix(workspace) { |
| 1009 | Ok(relative) if relative.as_os_str().is_empty() => ".".to_string(), |
| 1010 | Ok(relative) => relative.display().to_string(), |
| 1011 | Err(_) => value.to_string(), |
| 1012 | } |
| 1013 | } |
| 1014 | |
| 1015 | /// Render a path for **user-facing display** with the home directory |
| 1016 | /// contracted to `~`. Use this in the TUI, doctor/setup stdout, and any |
| 1017 | /// other place a viewer might see the output (screenshot, video, |
| 1018 | /// pasted-into-issue help). On macOS/Linux the absolute path |
| 1019 | /// `/Users/<name>/...` or `/home/<name>/...` reveals the OS account name, |
| 1020 | /// which is often the same as a public handle — undesirable for users |
| 1021 | /// who share their terminal. |
| 1022 | /// |
| 1023 | /// **Do not use** this for paths that get persisted (sessions, audit log) |
| 1024 | /// or sent to the LLM provider — those want full fidelity so they |
| 1025 | /// resolve correctly across processes. |
| 1026 | #[must_use] |
| 1027 | pub fn display_path(path: &Path) -> String { |
| 1028 | display_path_with_home(path, codewhale_paths::user_home().as_deref()) |
| 1029 | } |
| 1030 | |
| 1031 | /// Like [`display_path`] but takes an explicit home directory instead of |
| 1032 | /// reading `$HOME` / `codewhale_paths::user_home()`. Used in tests and anywhere the |
| 1033 | /// caller already has the home path available. |
| 1034 | /// |
| 1035 | /// The home-relative suffix is rejoined with the platform separator |
| 1036 | /// (`\` on Windows, `/` elsewhere) by walking the path's components, so |
| 1037 | /// inputs that carried foreign separators don't leak through. |
| 1038 | pub use codewhale_protocol::display::display_path_with_home; |
| 1039 | |
| 1040 | /// Estimate the total character count across message content blocks. |
| 1041 | #[must_use] |
| 1042 | pub fn estimate_message_chars(messages: &[Message]) -> usize { |
| 1043 | let mut total = 0; |
| 1044 | for msg in messages { |
| 1045 | for block in &msg.content { |
| 1046 | match block { |
| 1047 | ContentBlock::Text { text, .. } => total += text.len(), |
| 1048 | ContentBlock::Thinking { thinking, .. } => total += thinking.len(), |
| 1049 | ContentBlock::ToolUse { input, .. } => { |
| 1050 | let mut cw = CountingWriter::new(); |
| 1051 | let _ = serde_json::to_writer(&mut cw, input); |
| 1052 | total += cw.count(); |
| 1053 | } |
| 1054 | ContentBlock::ToolResult { content, .. } => total += content.len(), |
| 1055 | ContentBlock::ServerToolUse { .. } |
| 1056 | | ContentBlock::ToolSearchToolResult { .. } |
| 1057 | | ContentBlock::CodeExecutionToolResult { .. } |
| 1058 | | ContentBlock::WebSearchToolResult { .. } |
| 1059 | | ContentBlock::WebFetchToolResult { .. } |
| 1060 | | ContentBlock::WebSearchCall { .. } |
| 1061 | | ContentBlock::ServerToolCalls { .. } |
| 1062 | | ContentBlock::File { .. } |
| 1063 | | ContentBlock::ImageUrl { .. } => {} |
| 1064 | } |
| 1065 | } |
| 1066 | } |
| 1067 | total |
| 1068 | } |
| 1069 | |
| 1070 | // Tests use `display_path_with_home` so they never mutate the global `HOME` |
| 1071 | // env var. Mutating `HOME` via `std::env::set_var` is not thread-safe; Cargo |
| 1072 | // runs tests in parallel by default and CI runners are multi-core, so any test |
| 1073 | // that stomps `HOME` will race with tests that *read* it. Using the injected |
| 1074 | // helper avoids the race entirely and makes the tests portable to Windows |
| 1075 | // without additional platform scaffolding. |
| 1076 | #[cfg(test)] |
| 1077 | mod tests { |
| 1078 | use super::{display_path_with_home, format_context_window, redacted_identifier_for_log}; |
| 1079 | use std::path::PathBuf; |
| 1080 | |
| 1081 | fn home(s: &str) -> Option<PathBuf> { |
| 1082 | Some(PathBuf::from(s)) |
| 1083 | } |
| 1084 | |
| 1085 | #[test] |
| 1086 | fn format_context_window_drops_trailing_zeros() { |
| 1087 | assert_eq!(format_context_window(1_500_000), "1.5M"); |
| 1088 | assert_eq!(format_context_window(2_100_000), "2.1M"); |
| 1089 | assert_eq!(format_context_window(1_050_000), "1.05M"); |
| 1090 | assert_eq!(format_context_window(1_000_000), "1M"); |
| 1091 | assert_eq!(format_context_window(262_144), "262K"); |
| 1092 | assert_eq!(format_context_window(500), "500"); |
| 1093 | } |
| 1094 | |
| 1095 | #[test] |
| 1096 | fn redacted_identifier_for_log_hides_value_and_stays_stable() { |
| 1097 | let identifier = "session-secret-1234567890"; |
| 1098 | let redacted = redacted_identifier_for_log(identifier); |
| 1099 | |
| 1100 | assert!(redacted.starts_with("<redacted:")); |
| 1101 | assert!(redacted.ends_with('>')); |
| 1102 | assert!(!redacted.contains(identifier)); |
| 1103 | assert_eq!(redacted, redacted_identifier_for_log(identifier)); |
| 1104 | assert_ne!(redacted, redacted_identifier_for_log("another-session")); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn redacted_identifier_for_log_marks_empty_values() { |
| 1109 | assert_eq!(redacted_identifier_for_log(""), "<redacted:empty>"); |
| 1110 | } |
| 1111 | |
| 1112 | #[test] |
| 1113 | fn display_path_contracts_home_prefix() { |
| 1114 | let h = home("/Users/alice"); |
| 1115 | assert_eq!( |
| 1116 | display_path_with_home(&PathBuf::from("/Users/alice/projects/foo"), h.as_deref()), |
| 1117 | format!( |
| 1118 | "~{}projects{}foo", |
| 1119 | std::path::MAIN_SEPARATOR, |
| 1120 | std::path::MAIN_SEPARATOR |
| 1121 | ), |
| 1122 | ); |
| 1123 | } |
| 1124 | |
| 1125 | #[test] |
| 1126 | fn display_path_returns_bare_tilde_for_home_itself() { |
| 1127 | let h = home("/Users/alice"); |
| 1128 | assert_eq!( |
| 1129 | display_path_with_home(&PathBuf::from("/Users/alice"), h.as_deref()), |
| 1130 | "~" |
| 1131 | ); |
| 1132 | } |
| 1133 | |
| 1134 | #[test] |
| 1135 | fn display_path_leaves_unrelated_paths_alone() { |
| 1136 | let h = home("/Users/alice"); |
| 1137 | // Different user — must not get rewritten or share the tilde. |
| 1138 | assert_eq!( |
| 1139 | display_path_with_home(&PathBuf::from("/Users/bob/Code"), h.as_deref()), |
| 1140 | "/Users/bob/Code".to_string() |
| 1141 | ); |
| 1142 | // System path must stay absolute. |
| 1143 | assert_eq!( |
| 1144 | display_path_with_home(&PathBuf::from("/etc/hosts"), h.as_deref()), |
| 1145 | "/etc/hosts" |
| 1146 | ); |
| 1147 | } |
| 1148 | |
| 1149 | #[test] |
| 1150 | fn display_path_does_not_match_username_prefix() { |
| 1151 | // Regression guard: a directory named like the user's home |
| 1152 | // *prefix* but not under it must not get rewritten. |
| 1153 | let h = home("/Users/alice"); |
| 1154 | assert_eq!( |
| 1155 | display_path_with_home(&PathBuf::from("/Users/alice2/work"), h.as_deref()), |
| 1156 | "/Users/alice2/work" |
| 1157 | ); |
| 1158 | } |
| 1159 | |
| 1160 | #[test] |
| 1161 | fn display_path_with_no_home_returns_full_path() { |
| 1162 | assert_eq!( |
| 1163 | display_path_with_home(&PathBuf::from("/some/path"), None), |
| 1164 | "/some/path" |
| 1165 | ); |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | #[cfg(test)] |
| 1170 | mod atomic_write_tests { |
| 1171 | use super::*; |
| 1172 | use std::fs; |
| 1173 | use tempfile::tempdir; |
| 1174 | |
| 1175 | #[test] |
| 1176 | fn write_atomic_writes_content() { |
| 1177 | let tmp = tempdir().expect("tempdir"); |
| 1178 | let path = tmp.path().join("test.json"); |
| 1179 | let content = b"hello atomic world"; |
| 1180 | |
| 1181 | write_atomic(&path, content).expect("write_atomic"); |
| 1182 | assert!(path.exists()); |
| 1183 | let read = fs::read_to_string(&path).expect("read"); |
| 1184 | assert_eq!(read.as_bytes(), content); |
| 1185 | } |
| 1186 | |
| 1187 | /// A batch writes every file, and pays the directory's hygiene once. |
| 1188 | /// |
| 1189 | /// The per-file path fsyncs the directory on every call, and used to sweep |
| 1190 | /// it for stale temp files on every call too; a fork publishing hundreds |
| 1191 | /// of cloned items paid that hundreds of times (22 ms of directory scan |
| 1192 | /// each, 34 s for one fork). |
| 1193 | /// What must not change: every file lands with its content, a stray temp |
| 1194 | /// file is still reclaimed, and none of ours is left behind. |
| 1195 | #[test] |
| 1196 | fn write_atomic_batch_writes_every_file_and_sweeps_the_directory() { |
| 1197 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1198 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1199 | let (product, _guards) = seal_product_home(tmp.path()); |
| 1200 | |
| 1201 | let stray = product.join(".tmpCCCCCC"); |
| 1202 | std::fs::write(&stray, b"stranded by a SIGKILL").expect("write stray"); |
| 1203 | age_past_the_threshold(&stray); |
| 1204 | |
| 1205 | let files: Vec<(PathBuf, Vec<u8>)> = (0..5) |
| 1206 | .map(|index| { |
| 1207 | ( |
| 1208 | product.join(format!("item_{index}.json")), |
| 1209 | format!("{{\"index\":{index}}}").into_bytes(), |
| 1210 | ) |
| 1211 | }) |
| 1212 | .collect(); |
| 1213 | super::write_atomic_batch(&files).expect("batch write"); |
| 1214 | |
| 1215 | for (path, contents) in &files { |
| 1216 | assert_eq!( |
| 1217 | std::fs::read(path).expect("read back"), |
| 1218 | *contents, |
| 1219 | "{}", |
| 1220 | path.display() |
| 1221 | ); |
| 1222 | } |
| 1223 | assert!( |
| 1224 | !stray.exists(), |
| 1225 | "the batch sweeps the directory it writes into" |
| 1226 | ); |
| 1227 | let leftovers: Vec<String> = std::fs::read_dir(&product) |
| 1228 | .expect("read dir") |
| 1229 | .flatten() |
| 1230 | .map(|entry| entry.file_name().to_string_lossy().into_owned()) |
| 1231 | .filter(|name| super::is_stray_atomic_write_temp_name(name)) |
| 1232 | .collect(); |
| 1233 | assert!(leftovers.is_empty(), "stray temp files: {leftovers:?}"); |
| 1234 | } |
| 1235 | |
| 1236 | #[test] |
| 1237 | fn write_atomic_replaces_existing_file() { |
| 1238 | let tmp = tempdir().expect("tempdir"); |
| 1239 | let path = tmp.path().join("existing.json"); |
| 1240 | fs::write(&path, b"old content").expect("write old"); |
| 1241 | write_atomic(&path, b"new content").expect("write_atomic"); |
| 1242 | let read = fs::read_to_string(&path).expect("read"); |
| 1243 | assert_eq!(read, "new content"); |
| 1244 | } |
| 1245 | |
| 1246 | #[cfg(windows)] |
| 1247 | #[test] |
| 1248 | fn write_atomic_retries_windows_replace_contention() { |
| 1249 | use std::os::windows::fs::OpenOptionsExt; |
| 1250 | |
| 1251 | let tmp = tempdir().expect("tempdir"); |
| 1252 | let path = tmp.path().join("contended.json"); |
| 1253 | fs::write(&path, b"old content").expect("write old"); |
| 1254 | |
| 1255 | // FILE_SHARE_READ | FILE_SHARE_WRITE deliberately omits |
| 1256 | // FILE_SHARE_DELETE, reproducing the short-lived handle contention |
| 1257 | // that makes MoveFileExW report access denied during replacement. |
| 1258 | let held = fs::OpenOptions::new() |
| 1259 | .read(true) |
| 1260 | .share_mode(0x1 | 0x2) |
| 1261 | .open(&path) |
| 1262 | .expect("hold destination without delete sharing"); |
| 1263 | let release = std::thread::spawn(move || { |
| 1264 | std::thread::sleep(std::time::Duration::from_millis(50)); |
| 1265 | drop(held); |
| 1266 | }); |
| 1267 | |
| 1268 | write_atomic(&path, b"new content").expect("retry contended atomic replacement"); |
| 1269 | release.join().expect("release destination handle"); |
| 1270 | assert_eq!(fs::read(&path).expect("read replacement"), b"new content"); |
| 1271 | } |
| 1272 | |
| 1273 | #[cfg(windows)] |
| 1274 | #[test] |
| 1275 | fn write_atomic_writes_beside_live_fleet_pins_and_refuses_rewritten_names() { |
| 1276 | // A live Fleet ledger keeps every ancestor of its files open with |
| 1277 | // read-only sharing, so MoveFileExW could not add an entry there |
| 1278 | // (hosted os error 32 writing mcp.json). |
| 1279 | let workspace = tempdir().expect("tempdir"); |
| 1280 | let _pins = crate::files::WorkspaceFile::open( |
| 1281 | workspace.path(), |
| 1282 | Path::new(".codewhale/fleet.jsonl"), |
| 1283 | true, |
| 1284 | ) |
| 1285 | .expect("pin workspace ancestors"); |
| 1286 | let created = workspace.path().join("created.json"); |
| 1287 | write_atomic(&created, b"new").expect("create beside pins"); |
| 1288 | assert_eq!(fs::read(&created).expect("read created"), b"new"); |
| 1289 | write_atomic(&created, b"replaced").expect("replace beside pins"); |
| 1290 | assert_eq!(fs::read(&created).expect("read replaced"), b"replaced"); |
| 1291 | for name in [ |
| 1292 | "trailing.", |
| 1293 | "trailing ", |
| 1294 | "CON", |
| 1295 | "con.txt", |
| 1296 | "PRN", |
| 1297 | "AUX.log", |
| 1298 | "nul.tar.gz", |
| 1299 | "COM1", |
| 1300 | "com9.cfg", |
| 1301 | "LPT1", |
| 1302 | "lpt9.log", |
| 1303 | "COM¹", |
| 1304 | "COM².log", |
| 1305 | "COM³", |
| 1306 | "LPT¹", |
| 1307 | "LPT².log", |
| 1308 | "LPT³", |
| 1309 | "notes:private", |
| 1310 | "config.json:stream", |
| 1311 | "con:stream", |
| 1312 | "file::$DATA", |
| 1313 | ] { |
| 1314 | assert!( |
| 1315 | write_atomic(&workspace.path().join(name), b"x").is_err(), |
| 1316 | "{name}" |
| 1317 | ); |
| 1318 | } |
| 1319 | for name in ["console.json", "CON-file", "COM10.txt", "LPT10.txt"] { |
| 1320 | let path = workspace.path().join(name); |
| 1321 | write_atomic(&path, b"ordinary").expect("write ordinary name"); |
| 1322 | assert_eq!(fs::read(&path).expect("read ordinary name"), b"ordinary"); |
| 1323 | } |
| 1324 | let strays: Vec<_> = fs::read_dir(workspace.path()) |
| 1325 | .expect("read_dir") |
| 1326 | .filter_map(Result::ok) |
| 1327 | .filter(|entry| entry.file_name().to_string_lossy().starts_with(".tmp")) |
| 1328 | .collect(); |
| 1329 | assert!(strays.is_empty(), "{strays:?}"); |
| 1330 | } |
| 1331 | |
| 1332 | #[test] |
| 1333 | fn write_atomic_no_temp_left_behind_on_success() { |
| 1334 | let tmp = tempdir().expect("tempdir"); |
| 1335 | let path = tmp.path().join("clean.json"); |
| 1336 | write_atomic(&path, b"clean").expect("write_atomic"); |
| 1337 | // List files in dir — there should be no .tmp files left |
| 1338 | let entries: Vec<_> = fs::read_dir(tmp.path()) |
| 1339 | .expect("read_dir") |
| 1340 | .filter_map(|e| e.ok()) |
| 1341 | .collect(); |
| 1342 | let tmp_files: Vec<_> = entries |
| 1343 | .iter() |
| 1344 | .filter(|e| e.file_name().to_str().is_some_and(|n| n.starts_with('.'))) |
| 1345 | .collect(); |
| 1346 | assert!( |
| 1347 | tmp_files.is_empty(), |
| 1348 | "temp files left behind: {tmp_files:?}" |
| 1349 | ); |
| 1350 | } |
| 1351 | |
| 1352 | #[cfg(any(unix, windows))] |
| 1353 | fn assert_workspace_hard_link_is_refused() { |
| 1354 | let dir = tempdir().expect("tempdir"); |
| 1355 | let workspace = dir.path().join("workspace"); |
| 1356 | let outside = dir.path().join("outside"); |
| 1357 | fs::create_dir_all(&workspace).expect("create workspace"); |
| 1358 | fs::create_dir_all(&outside).expect("create outside directory"); |
| 1359 | let outside = outside.join("outside.txt"); |
| 1360 | fs::write(&outside, b"outside").expect("outside state"); |
| 1361 | let linked = workspace.join("linked.txt"); |
| 1362 | fs::hard_link(&outside, &linked).expect("hard link"); |
| 1363 | |
| 1364 | let err = write_atomic_workspace(&linked, b"new").expect_err("must refuse"); |
| 1365 | assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); |
| 1366 | assert!( |
| 1367 | err.to_string().contains("hard links"), |
| 1368 | "the refusal must name the hard-link reason: {err}" |
| 1369 | ); |
| 1370 | assert_eq!( |
| 1371 | fs::read_to_string(&outside).expect("outside read"), |
| 1372 | "outside", |
| 1373 | "the outside file must stay untouched" |
| 1374 | ); |
| 1375 | assert_eq!( |
| 1376 | fs::read_to_string(&linked).expect("linked read"), |
| 1377 | "outside", |
| 1378 | "the workspace entry must stay untouched too" |
| 1379 | ); |
| 1380 | // Breaking the link re-enables normal writes. |
| 1381 | fs::remove_file(&linked).expect("break link"); |
| 1382 | write_atomic_workspace(&linked, b"fresh").expect("single-link write"); |
| 1383 | assert_eq!(fs::read_to_string(&linked).expect("fresh read"), "fresh"); |
| 1384 | assert_eq!( |
| 1385 | fs::read_to_string(&outside).expect("outside read"), |
| 1386 | "outside" |
| 1387 | ); |
| 1388 | } |
| 1389 | |
| 1390 | #[cfg(unix)] |
| 1391 | #[test] |
| 1392 | fn write_atomic_workspace_refuses_a_hard_linked_target() { |
| 1393 | assert_workspace_hard_link_is_refused(); |
| 1394 | } |
| 1395 | |
| 1396 | #[cfg(windows)] |
| 1397 | #[test] |
| 1398 | fn windows_write_atomic_workspace_refuses_a_hard_linked_target() { |
| 1399 | assert_workspace_hard_link_is_refused(); |
| 1400 | } |
| 1401 | |
| 1402 | #[cfg(windows)] |
| 1403 | #[test] |
| 1404 | fn windows_hard_link_count_detects_multiple_links() { |
| 1405 | let dir = tempdir().expect("tempdir"); |
| 1406 | let first = dir.path().join("first.txt"); |
| 1407 | let second = dir.path().join("second.txt"); |
| 1408 | fs::write(&first, b"linked").expect("write fixture"); |
| 1409 | fs::hard_link(&first, &second).expect("hard link"); |
| 1410 | |
| 1411 | assert_eq!(hard_link_count(&second), Some(2)); |
| 1412 | } |
| 1413 | |
| 1414 | #[cfg(unix)] |
| 1415 | #[test] |
| 1416 | fn write_atomic_workspace_new_file_matches_standard_creation_mode() { |
| 1417 | use std::os::unix::fs::PermissionsExt; |
| 1418 | |
| 1419 | let dir = tempdir().expect("tempdir"); |
| 1420 | let control = dir.path().join("control.txt"); |
| 1421 | let actual = dir.path().join("actual.txt"); |
| 1422 | |
| 1423 | fs::write(&control, b"control").expect("write control"); |
| 1424 | write_atomic_workspace(&actual, b"actual").expect("atomic workspace write"); |
| 1425 | |
| 1426 | let control_mode = fs::metadata(&control) |
| 1427 | .expect("control metadata") |
| 1428 | .permissions() |
| 1429 | .mode() |
| 1430 | & 0o777; |
| 1431 | let actual_mode = fs::metadata(&actual) |
| 1432 | .expect("actual metadata") |
| 1433 | .permissions() |
| 1434 | .mode() |
| 1435 | & 0o777; |
| 1436 | |
| 1437 | assert_eq!(actual_mode, control_mode); |
| 1438 | assert_eq!(fs::read(&actual).expect("read"), b"actual"); |
| 1439 | } |
| 1440 | |
| 1441 | #[cfg(unix)] |
| 1442 | #[test] |
| 1443 | fn write_atomic_workspace_preserves_existing_mode() { |
| 1444 | use std::os::unix::fs::PermissionsExt; |
| 1445 | |
| 1446 | let dir = tempdir().expect("tempdir"); |
| 1447 | let path = dir.path().join("shared.txt"); |
| 1448 | fs::write(&path, b"before").expect("initial write"); |
| 1449 | fs::set_permissions(&path, fs::Permissions::from_mode(0o664)) |
| 1450 | .expect("set shared permissions"); |
| 1451 | |
| 1452 | write_atomic_workspace(&path, b"after").expect("atomic workspace write"); |
| 1453 | |
| 1454 | let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777; |
| 1455 | assert_eq!(mode, 0o664); |
| 1456 | assert_eq!(fs::read(&path).expect("read"), b"after"); |
| 1457 | } |
| 1458 | |
| 1459 | #[cfg(unix)] |
| 1460 | #[test] |
| 1461 | fn write_atomic_workspace_preserves_executable_bits() { |
| 1462 | use std::os::unix::fs::PermissionsExt; |
| 1463 | |
| 1464 | let dir = tempdir().expect("tempdir"); |
| 1465 | let path = dir.path().join("script.sh"); |
| 1466 | fs::write(&path, b"#!/bin/sh\nexit 0\n").expect("initial write"); |
| 1467 | fs::set_permissions(&path, fs::Permissions::from_mode(0o755)) |
| 1468 | .expect("set executable permissions"); |
| 1469 | |
| 1470 | write_atomic_workspace(&path, b"#!/bin/sh\nexit 1\n").expect("atomic workspace write"); |
| 1471 | |
| 1472 | let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777; |
| 1473 | assert_eq!(mode, 0o755); |
| 1474 | assert_eq!(fs::read(&path).expect("read"), b"#!/bin/sh\nexit 1\n"); |
| 1475 | } |
| 1476 | |
| 1477 | #[cfg(unix)] |
| 1478 | #[test] |
| 1479 | fn write_atomic_workspace_does_not_restore_special_bits() { |
| 1480 | use std::os::unix::fs::PermissionsExt; |
| 1481 | |
| 1482 | let dir = tempdir().expect("tempdir"); |
| 1483 | let path = dir.path().join("special.sh"); |
| 1484 | fs::write(&path, b"#!/bin/sh\n").expect("initial write"); |
| 1485 | // Request sticky + setgid + rwxr-xr-x. Filesystems may clear some |
| 1486 | // special bits; we only assert that after rewrite we never keep |
| 1487 | // bits outside the ordinary 0o777 mask. |
| 1488 | let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o6755)); |
| 1489 | let before = fs::metadata(&path) |
| 1490 | .expect("metadata before") |
| 1491 | .permissions() |
| 1492 | .mode(); |
| 1493 | let expected_ordinary = before & 0o777; |
| 1494 | |
| 1495 | write_atomic_workspace(&path, b"#!/bin/sh\necho rewritten\n") |
| 1496 | .expect("atomic workspace write"); |
| 1497 | |
| 1498 | let after = fs::metadata(&path) |
| 1499 | .expect("metadata after") |
| 1500 | .permissions() |
| 1501 | .mode(); |
| 1502 | assert_eq!(after & 0o777, expected_ordinary); |
| 1503 | // `PermissionsExt::mode()` also contains the regular-file type bit on |
| 1504 | // macOS/BSD. Check only the Unix special permission bits rather than |
| 1505 | // treating every non-rwx bit as a restored permission. |
| 1506 | assert_eq!(after & 0o7000, 0, "special bits must not be restored"); |
| 1507 | } |
| 1508 | |
| 1509 | #[cfg(unix)] |
| 1510 | #[test] |
| 1511 | fn write_atomic_workspace_replaces_symlink_without_following_target() { |
| 1512 | use std::os::unix::fs::{PermissionsExt, symlink}; |
| 1513 | |
| 1514 | let dir = tempdir().expect("tempdir"); |
| 1515 | let target = dir.path().join("target.txt"); |
| 1516 | let link = dir.path().join("link.txt"); |
| 1517 | fs::write(&target, b"target-body").expect("write target"); |
| 1518 | fs::set_permissions(&target, fs::Permissions::from_mode(0o600)) |
| 1519 | .expect("lock down target mode"); |
| 1520 | symlink(&target, &link).expect("create symlink"); |
| 1521 | |
| 1522 | write_atomic_workspace(&link, b"replaced-link") |
| 1523 | .expect("workspace write must replace symlink directory entry"); |
| 1524 | |
| 1525 | let link_meta = fs::symlink_metadata(&link).expect("link metadata"); |
| 1526 | assert!( |
| 1527 | link_meta.file_type().is_file() && !link_meta.file_type().is_symlink(), |
| 1528 | "rename should replace the symlink with a regular file" |
| 1529 | ); |
| 1530 | assert_eq!(fs::read(&link).expect("read link path"), b"replaced-link"); |
| 1531 | // Target inode must remain untouched (old private write_atomic semantics). |
| 1532 | assert_eq!(fs::read(&target).expect("read target"), b"target-body"); |
| 1533 | assert_eq!( |
| 1534 | fs::metadata(&target) |
| 1535 | .expect("target metadata") |
| 1536 | .permissions() |
| 1537 | .mode() |
| 1538 | & 0o777, |
| 1539 | 0o600 |
| 1540 | ); |
| 1541 | } |
| 1542 | |
| 1543 | #[cfg(unix)] |
| 1544 | #[test] |
| 1545 | fn write_atomic_workspace_replaces_self_referential_symlink_without_following() { |
| 1546 | use std::os::unix::fs::symlink; |
| 1547 | |
| 1548 | let dir = tempdir().expect("tempdir"); |
| 1549 | let link = dir.path().join("self-link.txt"); |
| 1550 | symlink(&link, &link).expect("create self-referential symlink"); |
| 1551 | |
| 1552 | assert!( |
| 1553 | fs::symlink_metadata(&link) |
| 1554 | .expect("lstat self-referential symlink") |
| 1555 | .file_type() |
| 1556 | .is_symlink() |
| 1557 | ); |
| 1558 | let follow_error = fs::metadata(&link).expect_err("following the symlink must fail"); |
| 1559 | assert_ne!( |
| 1560 | follow_error.kind(), |
| 1561 | std::io::ErrorKind::NotFound, |
| 1562 | "the fixture must catch a metadata-following regression" |
| 1563 | ); |
| 1564 | |
| 1565 | let result = write_atomic_workspace(&link, b"new-content"); |
| 1566 | result.expect("workspace write must not follow a self-referential symlink"); |
| 1567 | let link_meta = fs::symlink_metadata(&link).expect("link metadata"); |
| 1568 | assert!(link_meta.file_type().is_file() && !link_meta.file_type().is_symlink()); |
| 1569 | assert_eq!(fs::read(&link).expect("read"), b"new-content"); |
| 1570 | } |
| 1571 | |
| 1572 | #[cfg(unix)] |
| 1573 | #[test] |
| 1574 | fn write_atomic_private_new_file_does_not_gain_group_or_other_access() { |
| 1575 | use std::os::unix::fs::PermissionsExt; |
| 1576 | |
| 1577 | let dir = tempdir().expect("tempdir"); |
| 1578 | let path = dir.path().join("private.json"); |
| 1579 | |
| 1580 | write_atomic(&path, b"{}").expect("private atomic write"); |
| 1581 | |
| 1582 | let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777; |
| 1583 | assert_eq!(mode & 0o077, 0); |
| 1584 | } |
| 1585 | |
| 1586 | #[test] |
| 1587 | fn write_atomic_workspace_rewrites_a_single_link_file() { |
| 1588 | let tmp = tempdir().expect("tempdir"); |
| 1589 | let path = tmp.path().join("workspace.txt"); |
| 1590 | fs::write(&path, b"before").expect("write initial content"); |
| 1591 | write_atomic_workspace(&path, b"workspace").expect("write_atomic_workspace"); |
| 1592 | assert_eq!(fs::read(&path).expect("read"), b"workspace"); |
| 1593 | } |
| 1594 | |
| 1595 | // === stray atomic-write temp files === |
| 1596 | |
| 1597 | /// Backdate a file's mtime past the sweeper's one-hour threshold, using |
| 1598 | /// std rather than pulling in a dev-dependency just to age a fixture. |
| 1599 | fn age_past_the_threshold(path: &std::path::Path) { |
| 1600 | let two_hours_ago = |
| 1601 | std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60); |
| 1602 | let file = std::fs::File::options() |
| 1603 | .write(true) |
| 1604 | .open(path) |
| 1605 | .expect("open fixture"); |
| 1606 | file.set_times(std::fs::FileTimes::new().set_modified(two_hours_ago)) |
| 1607 | .expect("age the fixture"); |
| 1608 | } |
| 1609 | |
| 1610 | #[test] |
| 1611 | fn stray_temp_names_match_only_tempfiles_default_shape() { |
| 1612 | // What `tempfile` actually produces. |
| 1613 | assert!(super::is_stray_atomic_write_temp_name(".tmp0dqfST")); |
| 1614 | assert!(super::is_stray_atomic_write_temp_name(".tmpBcX9dY")); |
| 1615 | assert!(super::is_stray_atomic_write_temp_name(".tmpABC123")); |
| 1616 | |
| 1617 | // User files that must never be swept. |
| 1618 | for safe in [ |
| 1619 | ".tmp", |
| 1620 | ".tmpfile", |
| 1621 | ".tmp-backup", |
| 1622 | ".tmp12345", // five |
| 1623 | ".tmp1234567", // seven |
| 1624 | ".tmpABC12_", // underscore is not alphanumeric |
| 1625 | "tmpABC123", // no leading dot |
| 1626 | ".temp123456", |
| 1627 | "config.toml", |
| 1628 | ] { |
| 1629 | assert!( |
| 1630 | !super::is_stray_atomic_write_temp_name(safe), |
| 1631 | "{safe} must not be treated as ours to delete" |
| 1632 | ); |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | #[test] |
| 1637 | fn sweeping_removes_only_old_strays_and_leaves_everything_else() { |
| 1638 | let dir = tempfile::TempDir::new().expect("tempdir"); |
| 1639 | let old_stray = dir.path().join(".tmpAAAAAA"); |
| 1640 | let fresh_stray = dir.path().join(".tmpBBBBBB"); |
| 1641 | let user_file = dir.path().join(".tmp-please-keep"); |
| 1642 | let real_file = dir.path().join("config.toml"); |
| 1643 | for path in [&old_stray, &fresh_stray, &user_file, &real_file] { |
| 1644 | std::fs::write(path, b"x").expect("write fixture"); |
| 1645 | } |
| 1646 | |
| 1647 | age_past_the_threshold(&old_stray); |
| 1648 | |
| 1649 | super::sweep_stale_atomic_write_temps(dir.path()); |
| 1650 | |
| 1651 | assert!( |
| 1652 | !old_stray.exists(), |
| 1653 | "an hour-old stray of ours is collected" |
| 1654 | ); |
| 1655 | assert!( |
| 1656 | fresh_stray.exists(), |
| 1657 | "a fresh stray may belong to a concurrent write and must be left alone" |
| 1658 | ); |
| 1659 | assert!(user_file.exists(), "a user file must never be swept"); |
| 1660 | assert!(real_file.exists()); |
| 1661 | } |
| 1662 | |
| 1663 | /// Seal HOME / CODEWHALE_HOME to `tmp` so sweep policy is deterministic |
| 1664 | /// and never inspects the developer's real `~/.codewhale`. |
| 1665 | fn seal_product_home( |
| 1666 | tmp: &std::path::Path, |
| 1667 | ) -> (std::path::PathBuf, Vec<crate::test_env_lock::EnvVarGuard>) { |
| 1668 | use crate::test_env_lock::EnvVarGuard; |
| 1669 | |
| 1670 | let product = tmp.join("product-home"); |
| 1671 | std::fs::create_dir_all(&product).expect("create product home"); |
| 1672 | let guards = vec![ |
| 1673 | EnvVarGuard::set("HOME", tmp), |
| 1674 | EnvVarGuard::set("USERPROFILE", tmp), |
| 1675 | EnvVarGuard::set("CODEWHALE_HOME", &product), |
| 1676 | EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"), |
| 1677 | EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"), |
| 1678 | EnvVarGuard::remove("DEEPSEEK_HOME"), |
| 1679 | ]; |
| 1680 | (product, guards) |
| 1681 | } |
| 1682 | |
| 1683 | #[test] |
| 1684 | fn a_private_atomic_write_in_a_product_dir_collects_strays() { |
| 1685 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1686 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1687 | let (product, _guards) = seal_product_home(tmp.path()); |
| 1688 | |
| 1689 | assert!( |
| 1690 | super::is_codewhale_owned_state_dir(&product), |
| 1691 | "sealed CODEWHALE_HOME must count as a product dir" |
| 1692 | ); |
| 1693 | |
| 1694 | let stray = product.join(".tmpCCCCCC"); |
| 1695 | std::fs::write(&stray, b"stranded by a SIGKILL").expect("write stray"); |
| 1696 | age_past_the_threshold(&stray); |
| 1697 | |
| 1698 | let target = product.join("state.json"); |
| 1699 | super::write_atomic(&target, b"{\"ok\":true}").expect("atomic write"); |
| 1700 | |
| 1701 | assert_eq!(std::fs::read(&target).expect("read back"), b"{\"ok\":true}"); |
| 1702 | assert!(!stray.exists(), "the write reclaimed the earlier stray"); |
| 1703 | } |
| 1704 | |
| 1705 | #[test] |
| 1706 | fn a_private_atomic_write_to_a_user_chosen_dest_does_not_sweep() { |
| 1707 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1708 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1709 | let (_product, _guards) = seal_product_home(tmp.path()); |
| 1710 | let user_dir = tmp.path().join("user-chosen"); |
| 1711 | std::fs::create_dir_all(&user_dir).expect("create user dest"); |
| 1712 | |
| 1713 | assert!( |
| 1714 | !super::is_codewhale_owned_state_dir(&user_dir), |
| 1715 | "user-chosen dest must not count as a product dir: {}", |
| 1716 | user_dir.display() |
| 1717 | ); |
| 1718 | |
| 1719 | let stray = user_dir.join(".tmpDDDDDD"); |
| 1720 | std::fs::write(&stray, b"user or concurrent tempfile").expect("write stray"); |
| 1721 | age_past_the_threshold(&stray); |
| 1722 | |
| 1723 | let target = user_dir.join("session.json"); |
| 1724 | super::write_atomic(&target, b"{\"ok\":true}").expect("atomic write"); |
| 1725 | |
| 1726 | assert_eq!(std::fs::read(&target).expect("read back"), b"{\"ok\":true}"); |
| 1727 | assert!( |
| 1728 | stray.exists(), |
| 1729 | "/save <path> and other user-chosen dests must not sweep the parent" |
| 1730 | ); |
| 1731 | } |
| 1732 | |
| 1733 | #[test] |
| 1734 | fn atomic_write_product_dir_detection_matches_codewhale_home_not_siblings() { |
| 1735 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1736 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1737 | let (product, explicit_guards) = seal_product_home(tmp.path()); |
| 1738 | let sessions = product.join("sessions"); |
| 1739 | std::fs::create_dir_all(&sessions).expect("create sessions"); |
| 1740 | let sibling = tmp.path().join("product-home-extra"); |
| 1741 | std::fs::create_dir_all(&sibling).expect("create sibling"); |
| 1742 | |
| 1743 | assert!(super::is_codewhale_owned_state_dir(&product)); |
| 1744 | assert!(super::is_codewhale_owned_state_dir(&sessions)); |
| 1745 | assert!(!super::is_codewhale_owned_state_dir(&sibling)); |
| 1746 | assert!(!super::is_codewhale_owned_state_dir(tmp.path())); |
| 1747 | drop(explicit_guards); |
| 1748 | |
| 1749 | use crate::test_env_lock::EnvVarGuard; |
| 1750 | let _home = EnvVarGuard::set("HOME", tmp.path()); |
| 1751 | let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path()); |
| 1752 | let _no_explicit = EnvVarGuard::remove("CODEWHALE_HOME"); |
| 1753 | let _no_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 1754 | let _no_legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 1755 | let _no_legacy_home = EnvVarGuard::remove("DEEPSEEK_HOME"); |
| 1756 | let primary_sessions = tmp.path().join(".codewhale").join("sessions"); |
| 1757 | let legacy_home = tmp.path().join(".deepseek"); |
| 1758 | std::fs::create_dir_all(&primary_sessions).expect("create primary sessions"); |
| 1759 | std::fs::create_dir_all(&legacy_home).expect("create legacy home"); |
| 1760 | |
| 1761 | assert!(super::is_codewhale_owned_state_dir(&primary_sessions)); |
| 1762 | assert!(super::is_codewhale_owned_state_dir(&legacy_home)); |
| 1763 | assert!(!super::is_codewhale_owned_state_dir( |
| 1764 | &tmp.path().join("user-chosen") |
| 1765 | )); |
| 1766 | } |
| 1767 | |
| 1768 | #[cfg(unix)] |
| 1769 | #[test] |
| 1770 | fn symlinked_product_subdir_cannot_sweep_an_external_directory() { |
| 1771 | use std::os::unix::fs::symlink; |
| 1772 | |
| 1773 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1774 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1775 | let (product, _guards) = seal_product_home(tmp.path()); |
| 1776 | let external = tmp.path().join("external"); |
| 1777 | std::fs::create_dir_all(&external).expect("create external dir"); |
| 1778 | let linked = product.join("exports"); |
| 1779 | symlink(&external, &linked).expect("link product subdir outside"); |
| 1780 | |
| 1781 | let stray = external.join(".tmpEEEEEE"); |
| 1782 | std::fs::write(&stray, b"external tempfile").expect("write external fixture"); |
| 1783 | age_past_the_threshold(&stray); |
| 1784 | |
| 1785 | assert!( |
| 1786 | !super::is_codewhale_owned_state_dir(&linked), |
| 1787 | "physical containment must reject a nested symlink escape" |
| 1788 | ); |
| 1789 | super::write_atomic(&linked.join("state.json"), b"{\"ok\":true}") |
| 1790 | .expect("atomic write through link remains non-sweeping"); |
| 1791 | |
| 1792 | assert!( |
| 1793 | stray.exists(), |
| 1794 | "external temp-shaped files must not be swept" |
| 1795 | ); |
| 1796 | } |
| 1797 | } |
| 1798 | |
| 1799 | #[cfg(test)] |
| 1800 | mod spawn_supervised_tests { |
| 1801 | use super::*; |
| 1802 | use std::sync::Arc; |
| 1803 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 1804 | |
| 1805 | /// A spawned task that panics does not propagate the panic to the |
| 1806 | /// parent task — `spawn_supervised` catches it. Verified in isolation |
| 1807 | /// from the on-disk crash-dump path so the test is portable across |
| 1808 | /// macOS / Linux / Windows (where `codewhale_paths::user_home()` reads |
| 1809 | /// `USERPROFILE`, not `HOME`, so env-mutation tricks don't redirect |
| 1810 | /// the dump on Windows). |
| 1811 | #[tokio::test] |
| 1812 | async fn panicking_task_does_not_propagate_to_parent() { |
| 1813 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1814 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1815 | let _profile = crate::test_env_lock::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 1816 | let parent_alive = Arc::new(AtomicBool::new(false)); |
| 1817 | let parent_alive_clone = parent_alive.clone(); |
| 1818 | |
| 1819 | let handle = spawn_supervised( |
| 1820 | "panic-test-fixture", |
| 1821 | std::panic::Location::caller(), |
| 1822 | async move { |
| 1823 | parent_alive_clone.store(true, Ordering::SeqCst); |
| 1824 | panic!("deliberate panic for catch-unwind test"); |
| 1825 | }, |
| 1826 | ); |
| 1827 | |
| 1828 | let result = handle.await; |
| 1829 | assert!( |
| 1830 | result.is_ok(), |
| 1831 | "spawn_supervised must convert panic to a normal completion" |
| 1832 | ); |
| 1833 | assert!( |
| 1834 | parent_alive.load(Ordering::SeqCst), |
| 1835 | "fixture task must have run before panicking" |
| 1836 | ); |
| 1837 | } |
| 1838 | |
| 1839 | #[tokio::test] |
| 1840 | async fn panicking_blocking_task_does_not_propagate_to_parent() { |
| 1841 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1842 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1843 | let _profile = crate::test_env_lock::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 1844 | let parent_alive = Arc::new(AtomicBool::new(false)); |
| 1845 | let parent_alive_clone = parent_alive.clone(); |
| 1846 | |
| 1847 | let handle = spawn_blocking_supervised("blocking-panic-test-fixture", move || { |
| 1848 | parent_alive_clone.store(true, Ordering::SeqCst); |
| 1849 | panic!("deliberate panic for spawn_blocking catch-unwind test"); |
| 1850 | }); |
| 1851 | |
| 1852 | let result = handle.await; |
| 1853 | assert!( |
| 1854 | result.is_ok(), |
| 1855 | "spawn_blocking_supervised must convert panic to a normal completion" |
| 1856 | ); |
| 1857 | assert!( |
| 1858 | parent_alive.load(Ordering::SeqCst), |
| 1859 | "fixture blocking task must have run before panicking" |
| 1860 | ); |
| 1861 | } |
| 1862 | |
| 1863 | /// The public writer keeps its named log in the selected profile even |
| 1864 | /// when another supervised task also writes a crash there. |
| 1865 | #[test] |
| 1866 | fn write_panic_dump_writes_named_log() { |
| 1867 | let _lock = crate::test_env_lock::lock_test_env(); |
| 1868 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1869 | let _profile = crate::test_env_lock::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 1870 | let crash_dir = tmp.path().join("crashes"); |
| 1871 | let location = std::panic::Location::caller(); |
| 1872 | |
| 1873 | // Crash directories hold multiple tasks' logs. |
| 1874 | write_panic_dump("another-task", location, "other boom").expect("write other dump"); |
| 1875 | let other_entries: Vec<_> = std::fs::read_dir(&crash_dir) |
| 1876 | .expect("crashes dir exists") |
| 1877 | .collect::<std::io::Result<Vec<_>>>() |
| 1878 | .expect("read crash entries") |
| 1879 | .into_iter() |
| 1880 | .filter(|entry| { |
| 1881 | entry |
| 1882 | .file_name() |
| 1883 | .to_string_lossy() |
| 1884 | .ends_with("-another-task.log") |
| 1885 | }) |
| 1886 | .collect(); |
| 1887 | assert_eq!( |
| 1888 | other_entries.len(), |
| 1889 | 1, |
| 1890 | "exactly one other-task log expected" |
| 1891 | ); |
| 1892 | let other_path = other_entries[0].path(); |
| 1893 | let other_dump = std::fs::read(&other_path).expect("read other dump"); |
| 1894 | |
| 1895 | write_panic_dump("panic-fixture", location, "boom").expect("write dump"); |
| 1896 | let entries: Vec<_> = std::fs::read_dir(&crash_dir) |
| 1897 | .expect("crashes dir exists") |
| 1898 | .collect::<std::io::Result<Vec<_>>>() |
| 1899 | .expect("read crash entries") |
| 1900 | .into_iter() |
| 1901 | .filter(|entry| { |
| 1902 | entry |
| 1903 | .file_name() |
| 1904 | .to_string_lossy() |
| 1905 | .ends_with("-panic-fixture.log") |
| 1906 | }) |
| 1907 | .collect(); |
| 1908 | assert_eq!(entries.len(), 1, "exactly one panic-fixture log expected"); |
| 1909 | let dump = std::fs::read_to_string(entries[0].path()).expect("read dump"); |
| 1910 | assert!(dump.lines().any(|line| line == "Task: panic-fixture")); |
| 1911 | assert!( |
| 1912 | dump.lines() |
| 1913 | .any(|line| line == format!("Location: {location}")) |
| 1914 | ); |
| 1915 | assert!(dump.lines().any(|line| line == "Panic: boom")); |
| 1916 | assert_eq!( |
| 1917 | std::fs::read(other_path).expect("other dump remains"), |
| 1918 | other_dump, |
| 1919 | "writing a named crash must preserve other tasks' logs" |
| 1920 | ); |
| 1921 | } |
| 1922 | } |
| 1923 | |
| 1924 | #[cfg(test)] |
| 1925 | mod project_mapping_tests { |
| 1926 | use super::{project_tree, summarize_project}; |
| 1927 | use std::fs; |
| 1928 | use tempfile::tempdir; |
| 1929 | |
| 1930 | #[test] |
| 1931 | fn project_tree_sorts_siblings_alphabetically() { |
| 1932 | // Cross-platform readdir doesn't guarantee alphabetical order — on |
| 1933 | // ext4 with htree it's hash order, on APFS it's roughly insertion |
| 1934 | // order, on ZFS it's storage-class dependent. The system prompt |
| 1935 | // embeds this string in the cached prefix when a workspace has no |
| 1936 | // AGENTS.md / CLAUDE.md, so the function has to be byte-stable |
| 1937 | // across runs regardless of host filesystem. |
| 1938 | let tmp = tempdir().expect("tempdir"); |
| 1939 | let root = tmp.path(); |
| 1940 | // Create files in a deliberately scrambled order to make the |
| 1941 | // hosting filesystem's pre-sort (if any) less likely to mask a |
| 1942 | // missing sort in our code. |
| 1943 | fs::write(root.join("zebra.txt"), "z").expect("write zebra"); |
| 1944 | fs::write(root.join("apple.txt"), "a").expect("write apple"); |
| 1945 | fs::write(root.join("mango.txt"), "m").expect("write mango"); |
| 1946 | |
| 1947 | let tree = project_tree(root, 1, false); |
| 1948 | let lines: Vec<&str> = tree.lines().collect(); |
| 1949 | let apple_pos = lines |
| 1950 | .iter() |
| 1951 | .position(|l| l.contains("apple.txt")) |
| 1952 | .expect("apple line"); |
| 1953 | let mango_pos = lines |
| 1954 | .iter() |
| 1955 | .position(|l| l.contains("mango.txt")) |
| 1956 | .expect("mango line"); |
| 1957 | let zebra_pos = lines |
| 1958 | .iter() |
| 1959 | .position(|l| l.contains("zebra.txt")) |
| 1960 | .expect("zebra line"); |
| 1961 | |
| 1962 | assert!(apple_pos < mango_pos); |
| 1963 | assert!(mango_pos < zebra_pos); |
| 1964 | } |
| 1965 | |
| 1966 | #[test] |
| 1967 | fn project_tree_keeps_directory_before_its_children() { |
| 1968 | // Sorting siblings by full path is enough to preserve tree shape: |
| 1969 | // `"src" < "src/lib.rs"` because the shorter string compares less. |
| 1970 | let tmp = tempdir().expect("tempdir"); |
| 1971 | let root = tmp.path(); |
| 1972 | let src = root.join("src"); |
| 1973 | fs::create_dir_all(&src).expect("mkdir src"); |
| 1974 | fs::write(src.join("lib.rs"), "lib").expect("write lib"); |
| 1975 | fs::write(src.join("main.rs"), "main").expect("write main"); |
| 1976 | |
| 1977 | let tree = project_tree(root, 2, false); |
| 1978 | let src_pos = tree.find("DIR: src").expect("src dir line"); |
| 1979 | let lib_pos = tree.find("FILE: lib.rs").expect("lib file line"); |
| 1980 | let main_pos = tree.find("FILE: main.rs").expect("main file line"); |
| 1981 | |
| 1982 | assert!(src_pos < lib_pos, "directory must precede its children"); |
| 1983 | assert!(lib_pos < main_pos, "siblings sorted by name"); |
| 1984 | } |
| 1985 | |
| 1986 | #[test] |
| 1987 | fn project_tree_is_byte_stable_across_calls() { |
| 1988 | let tmp = tempdir().expect("tempdir"); |
| 1989 | let root = tmp.path(); |
| 1990 | fs::write(root.join("z.txt"), "z").expect("write"); |
| 1991 | fs::write(root.join("a.txt"), "a").expect("write"); |
| 1992 | |
| 1993 | assert_eq!(project_tree(root, 1, false), project_tree(root, 1, false)); |
| 1994 | } |
| 1995 | |
| 1996 | #[test] |
| 1997 | #[cfg(unix)] |
| 1998 | fn project_mapping_does_not_follow_symlinked_key_files() { |
| 1999 | let tmp = tempdir().expect("tempdir"); |
| 2000 | let root = tmp.path().join("workspace"); |
| 2001 | let outside = tmp.path().join("outside"); |
| 2002 | fs::create_dir_all(&root).expect("mkdir workspace"); |
| 2003 | fs::create_dir_all(&outside).expect("mkdir outside"); |
| 2004 | let outside_file = outside.join("Cargo.toml"); |
| 2005 | fs::write(&outside_file, "[package]\nname = \"outside\"\n").expect("write outside"); |
| 2006 | std::os::unix::fs::symlink(&outside_file, root.join("Cargo.toml")).expect("symlink"); |
| 2007 | |
| 2008 | assert_eq!(summarize_project(&root), "Unknown project type"); |
| 2009 | assert!(!project_tree(&root, 1, false).contains("Cargo.toml")); |
| 2010 | } |
| 2011 | |
| 2012 | #[test] |
| 2013 | fn summarize_project_sorts_key_files_in_fallback() { |
| 2014 | // When `summarize_project` can't classify a project type it falls |
| 2015 | // back to listing the discovered key files. That joined list must |
| 2016 | // be deterministic so the system prompt that embeds it doesn't |
| 2017 | // drift between runs on filesystems that emit readdir in a |
| 2018 | // non-alphabetical order. |
| 2019 | let tmp = tempdir().expect("tempdir"); |
| 2020 | let root = tmp.path(); |
| 2021 | // Use key files that don't trigger any of the type detectors |
| 2022 | // (Cargo.toml / package.json / requirements.txt) so the function |
| 2023 | // hits the `Project with key files: …` branch. |
| 2024 | fs::write(root.join("Makefile"), "all:").expect("write makefile"); |
| 2025 | fs::write(root.join("README.md"), "# x").expect("write readme"); |
| 2026 | |
| 2027 | let summary = summarize_project(root); |
| 2028 | assert!( |
| 2029 | summary.starts_with("Project with key files: "), |
| 2030 | "expected fallback branch; got: {summary}" |
| 2031 | ); |
| 2032 | let suffix = summary |
| 2033 | .strip_prefix("Project with key files: ") |
| 2034 | .expect("prefix"); |
| 2035 | assert_eq!(suffix, "Makefile, README.md"); |
| 2036 | } |
| 2037 | |
| 2038 | #[test] |
| 2039 | fn sync_directory_is_best_effort_for_existing_and_missing_dirs() { |
| 2040 | let tmp = tempdir().expect("tempdir"); |
| 2041 | super::sync_directory(tmp.path()); |
| 2042 | super::sync_directory(&tmp.path().join("does-not-exist")); |
| 2043 | } |
| 2044 | |
| 2045 | #[test] |
| 2046 | fn directory_sync_refusals_are_distinguished_from_real_failures() { |
| 2047 | use std::io::{Error, ErrorKind}; |
| 2048 | assert!(super::is_directory_sync_refusal(&Error::from( |
| 2049 | ErrorKind::Unsupported |
| 2050 | ))); |
| 2051 | assert!(super::is_directory_sync_refusal(&Error::from( |
| 2052 | ErrorKind::InvalidInput |
| 2053 | ))); |
| 2054 | assert!(!super::is_directory_sync_refusal(&Error::other( |
| 2055 | "disk failure" |
| 2056 | ))); |
| 2057 | #[cfg(unix)] |
| 2058 | { |
| 2059 | for code in [libc::EINVAL, libc::ENOTSUP, libc::EOPNOTSUPP, libc::EBADF] { |
| 2060 | assert!(super::is_directory_sync_refusal(&Error::from_raw_os_error( |
| 2061 | code |
| 2062 | ))); |
| 2063 | } |
| 2064 | for code in [libc::EIO, libc::ENOSPC, libc::EDQUOT] { |
| 2065 | assert!(!super::is_directory_sync_refusal( |
| 2066 | &Error::from_raw_os_error(code) |
| 2067 | )); |
| 2068 | } |
| 2069 | } |
| 2070 | } |
| 2071 | } |
| 2072 |