返回 CodeWhale
state_dirs.rs
根目录 / crates / config / src / state_dirs.rs
1 use crate::config_migration::default_config_path;
2 use crate::external_credentials::quote_os_path;
3 use crate::path_io::{
4 checked_path_exists, normalize_config_file_path, normalize_project_workspace,
5 };
6 use crate::provider_toml::CONFIG_FILE_NAME;
7 use anyhow::Context as _;
8 use anyhow::{Result, bail};
9 use codewhale_paths::{CODEWHALE_APP_DIR, LEGACY_APP_DIR};
10 use std::ffi::{OsStr, OsString};
11 use std::path::{Path, PathBuf};
12
13 /// Resolve the primary CodeWhale home directory.
14 ///
15 /// `$CODEWHALE_HOME` takes precedence when set. Otherwise defaults to
16 /// `$HOME/.codewhale`. This is the write target for new product state.
17 pub fn codewhale_home() -> Result<PathBuf> {
18 codewhale_paths::codewhale_home()
19 .map_err(anyhow::Error::new)?
20 .context("failed to resolve home directory")
21 }
22
23 /// Whether `$CODEWHALE_HOME` is set to a non-empty value.
24 ///
25 /// An explicit CodeWhale home is an isolation boundary: state/config resolvers
26 /// must not fall back to ambient legacy `~/.deepseek` data outside that root.
27 pub fn codewhale_home_is_explicit() -> bool {
28 codewhale_paths::codewhale_home_is_explicit()
29 }
30
31 /// Resolve the legacy DeepSeek home directory (`$HOME/.deepseek`).
32 ///
33 /// Always returns the legacy path regardless of whether it exists.
34 pub fn legacy_deepseek_home() -> Result<PathBuf> {
35 codewhale_paths::legacy_deepseek_home().context("failed to resolve home directory")
36 }
37
38 /// Reject state subdirs that could escape the state root via path injection.
39 ///
40 /// `ensure_state_dir` / `resolve_state_dir` are public APIs taking an arbitrary
41 /// subdir string; every in-tree caller passes a hardcoded single component
42 /// (e.g. `"sessions"`, `"."`). This validates defensively so a future caller
43 /// can never traverse out of the state root via `..` components or an absolute
44 /// path. Nested relative paths such as `"a/b"` are permitted.
45 pub(crate) fn ensure_safe_state_subdir(subdir: &str) -> Result<()> {
46 if subdir.is_empty() {
47 bail!("state subdir must not be empty");
48 }
49 let path = std::path::Path::new(subdir);
50 if path.is_absolute() {
51 bail!("state subdir must not be an absolute path: {subdir}");
52 }
53 if path.components().any(|c| {
54 matches!(
55 c,
56 std::path::Component::RootDir | std::path::Component::Prefix(_)
57 )
58 }) {
59 bail!("state subdir must not contain a root or prefix: {subdir}");
60 }
61 if path
62 .components()
63 .any(|c| matches!(c, std::path::Component::ParentDir))
64 {
65 bail!("state subdir must not contain parent-dir (..) components: {subdir}");
66 }
67 Ok(())
68 }
69
70 /// Resolve a state subdirectory, preferring the CodeWhale root if
71 /// it already exists, otherwise falling back to the legacy root.
72 ///
73 /// This is the read-path resolver: it returns the primary path when
74 /// migration has occurred or on a fresh install, but keeps reading
75 /// from the legacy path for users who haven't migrated yet.
76 pub fn resolve_state_dir(subdir: &str) -> Result<PathBuf> {
77 ensure_safe_state_subdir(subdir)?;
78 let explicit_codewhale_home = codewhale_home_is_explicit();
79 let primary = codewhale_home()?.join(subdir);
80 if explicit_codewhale_home || primary.exists() {
81 return Ok(primary);
82 }
83 let legacy = legacy_deepseek_home()?.join(subdir);
84 if legacy.exists() {
85 return Ok(legacy);
86 }
87 // Neither exists — return primary for first-write creation.
88 Ok(primary)
89 }
90
91 /// Ensure a state subdirectory exists under the primary CodeWhale root,
92 /// creating it if necessary. This is the write-path resolver.
93 ///
94 /// On the first creation of a real subdirectory (not the root sentinel `"."`),
95 /// if a legacy `~/.deepseek/<subdir>` exists but the primary
96 /// `~/.codewhale/<subdir>` does not, the legacy directory is relocated into
97 /// the primary location so the user keeps their data and the legacy tree
98 /// stops growing (#3240). After migration, [`resolve_state_dir`] finds the
99 /// data in the primary location; the read resolver itself is unchanged.
100 pub fn ensure_state_dir(subdir: &str) -> Result<PathBuf> {
101 let (dir, migration) = ensure_state_dir_with_migration(subdir)?;
102 if let Some(migration) = migration {
103 eprintln!("{}", migration.user_notice());
104 }
105 Ok(dir)
106 }
107
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 pub enum StateMigrationKind {
110 Relocated,
111 Copied,
112 }
113
114 #[derive(Debug, Clone, PartialEq, Eq)]
115 pub struct StateMigration {
116 pub subdir: String,
117 pub legacy_path: PathBuf,
118 pub primary_path: PathBuf,
119 pub kind: StateMigrationKind,
120 }
121
122 impl StateMigration {
123 pub fn user_notice(&self) -> String {
124 let action = match self.kind {
125 StateMigrationKind::Relocated => "relocated",
126 StateMigrationKind::Copied => "copied",
127 };
128 let legacy_detail = match self.kind {
129 StateMigrationKind::Relocated => {
130 "The legacy .deepseek copy for this state path was removed by the move."
131 }
132 StateMigrationKind::Copied => {
133 "The legacy .deepseek copy was left in place because a direct move failed."
134 }
135 };
136
137 format!(
138 "Codewhale migrated legacy state ({action}):\n {} -> {}\nYour data was preserved. Use .codewhale as the canonical state location from now on.\n{legacy_detail}\nIf no other apps use it, you can remove the legacy .deepseek tree after confirming everything looks right.",
139 self.legacy_path.display(),
140 self.primary_path.display(),
141 )
142 }
143 }
144
145 /// Variant of [`ensure_state_dir`] that exposes whether a legacy state path was
146 /// migrated. Most callers should use [`ensure_state_dir`]; this is kept for
147 /// tests and future UI surfaces that want to render the notice themselves.
148 pub fn ensure_state_dir_with_migration(subdir: &str) -> Result<(PathBuf, Option<StateMigration>)> {
149 ensure_safe_state_subdir(subdir)?;
150 let explicit_codewhale_home = codewhale_home_is_explicit();
151 let dir = codewhale_home()?.join(subdir);
152 let migration = if explicit_codewhale_home {
153 None
154 } else {
155 match migrate_legacy_state_dir(&dir, subdir)? {
156 LegacyStateMigration::NotNeeded => None,
157 LegacyStateMigration::Migrated(migration) => Some(migration),
158 // Creating an empty primary here would make it authoritative and
159 // hide the legacy data for good. Keep using the legacy directory
160 // (the read resolver does the same) and retry on the next call.
161 LegacyStateMigration::Failed { legacy } => return Ok((legacy, None)),
162 }
163 };
164 std::fs::create_dir_all(&dir)
165 .with_context(|| format!("failed to create {}/", dir.display()))?;
166 Ok((dir, migration))
167 }
168
169 pub(crate) enum LegacyStateMigration {
170 NotNeeded,
171 Migrated(StateMigration),
172 /// Neither the move nor the copy completed. The primary was left absent,
173 /// so the legacy directory stays authoritative and migration retries.
174 Failed {
175 legacy: PathBuf,
176 },
177 }
178
179 /// One-time relocation of a legacy `~/.deepseek/<subdir>` state directory into
180 /// the primary `~/.codewhale/<subdir>` location (#3240). No-op once the primary
181 /// exists, for the root sentinel `"."` (a whole-tree move is owned by the
182 /// config-file migration), or when no legacy directory is present.
183 pub(crate) fn migrate_legacy_state_dir(
184 primary: &Path,
185 subdir: &str,
186 ) -> Result<LegacyStateMigration> {
187 if primary.exists() || subdir == "." || subdir.is_empty() {
188 return Ok(LegacyStateMigration::NotNeeded);
189 }
190 let legacy = match legacy_deepseek_home() {
191 Ok(home) => home.join(subdir),
192 Err(_) => return Ok(LegacyStateMigration::NotNeeded),
193 };
194 if !legacy.exists() {
195 return Ok(LegacyStateMigration::NotNeeded);
196 }
197 // The primary's parent (the ~/.codewhale root) must exist for the rename.
198 if let Some(parent) = primary.parent()
199 && let Err(err) = std::fs::create_dir_all(parent)
200 {
201 tracing::warn!(
202 target: "config::migration",
203 "Could not create {} for state migration ({}); writing to primary anyway",
204 parent.display(),
205 err
206 );
207 }
208 match std::fs::rename(&legacy, primary) {
209 Ok(()) => {
210 tracing::info!(
211 target: "config::migration",
212 "Migrated legacy state directory {} -> {} (relocated). The .deepseek copy was removed.",
213 legacy.display(),
214 primary.display()
215 );
216 return Ok(LegacyStateMigration::Migrated(StateMigration {
217 subdir: subdir.to_string(),
218 legacy_path: legacy,
219 primary_path: primary.to_path_buf(),
220 kind: StateMigrationKind::Relocated,
221 }));
222 }
223 Err(err) => {
224 // Cross-device rename or permission issue: fall back to a
225 // recursive copy so the user keeps their data. The legacy tree is
226 // left in place; it stops growing because writes now target the
227 // primary path.
228 match copy_dir_into_place(&legacy, primary) {
229 Ok(()) => {
230 tracing::info!(
231 target: "config::migration",
232 "Migrated legacy state directory {} -> {} (copied; rename failed: {err}). \
233 The legacy .deepseek copy was left in place.",
234 legacy.display(),
235 primary.display()
236 );
237 return Ok(LegacyStateMigration::Migrated(StateMigration {
238 subdir: subdir.to_string(),
239 legacy_path: legacy,
240 primary_path: primary.to_path_buf(),
241 kind: StateMigrationKind::Copied,
242 }));
243 }
244 Err(copy_err) => {
245 // A concurrent process may have completed the move/copy
246 // after our initial check. Use that completed primary,
247 // rather than resuming writes to the legacy tree.
248 if primary.is_dir() {
249 return Ok(LegacyStateMigration::NotNeeded);
250 }
251 tracing::warn!(
252 target: "config::migration",
253 "Could not migrate legacy state {} -> {} (rename: {err}; copy: {copy_err:#}). \
254 The legacy path stays in use and migration retries next time.",
255 legacy.display(),
256 primary.display()
257 );
258 }
259 }
260 }
261 }
262 Ok(LegacyStateMigration::Failed { legacy })
263 }
264
265 /// Copy `src` to a staging sibling of `dst` and rename it into place, so a
266 /// copy that fails midway never leaves a partial `dst` that later runs would
267 /// treat as a completed migration.
268 pub(crate) fn copy_dir_into_place(src: &Path, dst: &Path) -> Result<()> {
269 let mut staging_name = OsString::from(".");
270 staging_name.push(dst.file_name().unwrap_or_default());
271 staging_name.push(".migrating-");
272 // Each attempt owns only its unique private directory. A fixed sibling
273 // could be another process's active copy and must never be cleared.
274 let staging = tempfile::Builder::new().prefix(&staging_name).tempdir_in(
275 dst.parent()
276 .context("migration destination has no parent")?,
277 )?;
278 copy_dir_recursive(src, staging.path())?;
279 std::fs::rename(staging.path(), dst).with_context(|| {
280 format!(
281 "failed to move {} into place at {}",
282 staging.path().display(),
283 dst.display()
284 )
285 })
286 }
287
288 /// Recursively copy a directory tree from `src` to `dst`, creating `dst`.
289 /// Symlinks and other non-file/non-dir entries are skipped (rare in state dirs).
290 pub(crate) fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
291 std::fs::create_dir_all(dst).with_context(|| format!("failed to create {}", dst.display()))?;
292 for entry in
293 std::fs::read_dir(src).with_context(|| format!("failed to read {}", src.display()))?
294 {
295 let entry = entry.with_context(|| format!("failed to read entry in {}", src.display()))?;
296 let path = entry.path();
297 let target = dst.join(entry.file_name());
298 let file_type = entry
299 .file_type()
300 .with_context(|| format!("failed to read file type for {}", path.display()))?;
301 if file_type.is_dir() {
302 copy_dir_recursive(&path, &target)?;
303 } else if file_type.is_file() {
304 std::fs::copy(&path, &target).with_context(|| {
305 format!("failed to copy {} -> {}", path.display(), target.display())
306 })?;
307 }
308 }
309 Ok(())
310 }
311
312 /// Resolve a project-local state subdirectory, preferring `.codewhale/`
313 /// when it exists, falling back to `.deepseek/` for legacy projects.
314 ///
315 /// Returns `(true, path)` when the primary `.codewhale/` path is used,
316 /// `(false, path)` for the legacy fallback. The boolean helps callers
317 /// emit a deprecation notice on legacy paths.
318 pub fn resolve_project_state_dir(workspace: &Path, subdir: &str) -> Result<(bool, PathBuf)> {
319 ensure_safe_state_subdir(subdir)?;
320 let workspace = normalize_project_workspace(workspace)?;
321 let primary = workspace.join(CODEWHALE_APP_DIR).join(subdir);
322 if primary.exists() {
323 return Ok((true, primary));
324 }
325 let legacy = workspace.join(LEGACY_APP_DIR).join(subdir);
326 Ok((false, legacy))
327 }
328
329 /// Ensure a project-local state subdirectory exists under `.codewhale/`,
330 /// creating it if necessary. Returns the directory path.
331 pub fn ensure_project_state_dir(workspace: &Path, subdir: &str) -> Result<PathBuf> {
332 ensure_safe_state_subdir(subdir)?;
333 let workspace = normalize_project_workspace(workspace)?;
334 let dir = workspace.join(CODEWHALE_APP_DIR).join(subdir);
335 std::fs::create_dir_all(&dir)
336 .with_context(|| format!("failed to create {}/", dir.display()))?;
337 Ok(dir)
338 }
339
340 pub fn resolve_config_path(explicit: Option<PathBuf>) -> Result<PathBuf> {
341 if let Some(path) = explicit {
342 return normalize_config_file_path(path);
343 }
344 if let Some(path) = codewhale_paths::config_path_override().map_err(anyhow::Error::new)? {
345 return normalize_config_file_path(path);
346 }
347 default_config_path()
348 }
349
350 pub fn require_explicit_config_exists(explicit: Option<PathBuf>) -> Result<()> {
351 if let Some(path) = explicit {
352 let path = normalize_config_file_path(path)?;
353 if !checked_path_exists(&path)? {
354 bail!("config file does not exist: {}", quote_os_path(&path));
355 }
356 }
357 Ok(())
358 }
359
360 /// Whether `path` names a workspace-scoped config document —
361 /// `<repo>/.codewhale/config.toml` (or the legacy `.deepseek` layout) inside a
362 /// checkout — rather than a user-global config file.
363 ///
364 /// Credential writes (api_key values, `auth_mode` markers, oauth/external
365 /// credential pointers) must never target such a document: a key saved while
366 /// working in one repo would be invisible from every other repo, and the repo
367 /// file stores it in plaintext where it is easy to commit by accident (#5045,
368 /// #5193).
369 ///
370 /// A path is classified workspace-scoped only when its parent directory is a
371 /// `.codewhale`/`.deepseek` app dir outside the user's home AND the document
372 /// belongs to a workspace: it is relative (resolves against the process cwd),
373 /// its base directory contains the process cwd, or its base directory is a
374 /// checkout (has a `.git` entry). An explicit `$CODEWHALE_HOME` config is
375 /// user-global wherever that home points, even when the directory itself
376 /// happens to be named `.codewhale`; other custom locations (for example
377 /// `CODEWHALE_CONFIG_PATH=~/team.toml` or an isolated test directory) stay
378 /// honored as deliberate user-scoped choices.
379 #[must_use]
380 pub fn config_path_is_workspace_scoped(path: &Path) -> bool {
381 config_path_is_workspace_scoped_with_context(
382 path,
383 codewhale_paths::codewhale_home_override()
384 .ok()
385 .flatten()
386 .as_deref(),
387 codewhale_paths::user_home().as_deref(),
388 std::env::current_dir().ok().as_deref(),
389 )
390 }
391
392 /// Environment-free core of [`config_path_is_workspace_scoped`], split out so
393 /// scope classification is testable without mutating process-global state.
394 pub(crate) fn config_path_is_workspace_scoped_with_context(
395 path: &Path,
396 explicit_codewhale_home: Option<&Path>,
397 user_home: Option<&Path>,
398 current_dir: Option<&Path>,
399 ) -> bool {
400 if let Some(home) = explicit_codewhale_home
401 && same_lexical_or_canonical_path(path, &home.join(CONFIG_FILE_NAME))
402 {
403 return false;
404 }
405 let Some(parent) = path.parent() else {
406 return false;
407 };
408 let parent_is_app_dir = parent
409 .file_name()
410 .and_then(OsStr::to_str)
411 .is_some_and(|name| name == CODEWHALE_APP_DIR || name == LEGACY_APP_DIR);
412 if !parent_is_app_dir {
413 return false;
414 }
415 let Some(base) = parent.parent() else {
416 return true;
417 };
418 if let Some(home) = user_home
419 && same_lexical_or_canonical_path(base, home)
420 {
421 return false;
422 }
423 if path.is_relative() {
424 // Resolves against the process cwd: repo-scoped by construction.
425 return true;
426 }
427 // The document belongs to the workspace the process is sitting in…
428 if let Some(cwd) = current_dir
429 && canonicalize_or_keep(cwd).starts_with(canonicalize_or_keep(base))
430 {
431 return true;
432 }
433 // …or to some other checkout (a `.git` entry beside the app dir).
434 base.join(".git").exists()
435 }
436
437 /// Lexical equality first, canonical equality as a fallback so an existing
438 /// path still matches through symlinked parents (e.g. `/tmp` on macOS).
439 pub(crate) fn same_lexical_or_canonical_path(a: &Path, b: &Path) -> bool {
440 a == b || canonicalize_or_keep(a) == canonicalize_or_keep(b)
441 }
442
443 pub(crate) fn canonicalize_or_keep(path: &Path) -> PathBuf {
444 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
445 }
446
447 #[cfg(test)]
448 mod credential_scope_tests {
449 use super::config_path_is_workspace_scoped_with_context;
450 use std::path::Path;
451
452 #[test]
453 fn config_inside_current_workspace_is_workspace_scoped() {
454 let temp = tempfile::tempdir().expect("tempdir");
455 let repo = temp.path().join("repo");
456 let cwd = repo.join("nested/dir");
457 for app_dir in [".codewhale", ".deepseek"] {
458 let config = repo.join(app_dir).join("config.toml");
459 assert!(
460 config_path_is_workspace_scoped_with_context(
461 &config,
462 None,
463 Some(Path::new("/home/user")),
464 Some(&cwd),
465 ),
466 "{} should be workspace-scoped when cwd sits inside the repo",
467 config.display()
468 );
469 }
470 }
471
472 #[test]
473 fn relative_app_dir_config_is_workspace_scoped() {
474 assert!(config_path_is_workspace_scoped_with_context(
475 Path::new(".codewhale/config.toml"),
476 None,
477 Some(Path::new("/home/user")),
478 Some(Path::new("/somewhere/else")),
479 ));
480 }
481
482 #[test]
483 fn checkout_config_outside_cwd_is_workspace_scoped_via_git_marker() {
484 let temp = tempfile::tempdir().expect("tempdir");
485 let repo = temp.path().join("repo");
486 std::fs::create_dir_all(repo.join(".git")).expect("git marker");
487 std::fs::create_dir_all(repo.join(".codewhale")).expect("app dir");
488 assert!(config_path_is_workspace_scoped_with_context(
489 &repo.join(".codewhale/config.toml"),
490 None,
491 Some(Path::new("/home/user")),
492 Some(Path::new("/somewhere/else")),
493 ));
494 }
495
496 #[test]
497 fn user_global_and_custom_locations_are_not_workspace_scoped() {
498 let home = Path::new("/home/user");
499 let elsewhere = Some(Path::new("/somewhere/else"));
500 for global_config in [
501 "/home/user/.codewhale/config.toml",
502 "/home/user/.deepseek/config.toml",
503 "/home/user/team-config.toml",
504 "/etc/codewhale/config.toml",
505 ] {
506 assert!(
507 !config_path_is_workspace_scoped_with_context(
508 Path::new(global_config),
509 None,
510 Some(home),
511 elsewhere,
512 ),
513 "{global_config} should stay user-global"
514 );
515 }
516 // An isolated app-dir-shaped location with no workspace relationship
517 // (no cwd ancestry, no checkout marker) stays honored: test harnesses
518 // and deliberate overrides point there.
519 let temp = tempfile::tempdir().expect("tempdir");
520 assert!(!config_path_is_workspace_scoped_with_context(
521 &temp.path().join(".codewhale/config.toml"),
522 None,
523 Some(home),
524 elsewhere,
525 ));
526 }
527
528 #[test]
529 fn explicit_codewhale_home_config_is_user_global_even_when_dir_is_app_named() {
530 let temp = tempfile::tempdir().expect("tempdir");
531 let repo = temp.path().join("repo");
532 let explicit = repo.join(".codewhale");
533 // Even with cwd inside the repo, the explicit CODEWHALE_HOME config is
534 // the user-global scope by definition.
535 assert!(!config_path_is_workspace_scoped_with_context(
536 &explicit.join("config.toml"),
537 Some(&explicit),
538 Some(Path::new("/home/user")),
539 Some(&repo),
540 ));
541 // A different repo-scoped document is still workspace-scoped.
542 assert!(config_path_is_workspace_scoped_with_context(
543 &repo.join("other/.codewhale/config.toml"),
544 Some(&explicit),
545 Some(Path::new("/home/user")),
546 Some(&repo.join("other")),
547 ));
548 }
549 }
550
550 lines RUST