返回 CodeWhale
doctor_fix.rs
根目录 / crates / tui / src / doctor_fix.rs
1 //! `codewhale doctor --fix` repair planning and application (#5552, v1).
2 //!
3 //! The doctor is a read-only diagnostic by default. `--fix` computes a
4 //! concrete repair plan first — pure detection, no mutation — shows it, and
5 //! applies it only after explicit consent (or `--yes`). Every v1 action is
6 //! narrowly scoped and reversible:
7 //!
8 //! - delete stale `.tmp*` files left behind by interrupted atomic writes in
9 //! the Codewhale home, only when last modified more than an hour ago;
10 //! - tighten secret-store file permissions to `0600` on Unix when group or
11 //! world bits are set (the secret store writes private files, but a file
12 //! restored from backup or moved from another machine may have drifted);
13 //! - disable MCP entries whose structural check reports `Error` (no command
14 //! and no URL, or an empty command) by writing `enabled: false` through the
15 //! same atomic save path the MCP editor uses;
16 //! - scaffold the user-global `skills`, `tools`, and `plugins` directories
17 //! when they are missing so discovery surfaces stop reporting them absent.
18
19 use std::path::{Path, PathBuf};
20
21 use anyhow::{Context, Result};
22
23 use crate::McpServerDoctorStatus;
24 use codewhale_engine::mcp;
25
26 /// One concrete, reversible repair the doctor can apply.
27 #[derive(Debug, Clone, PartialEq, Eq)]
28 pub(crate) enum DoctorFixAction {
29 /// Delete an interrupted-atomic-write leftover. Only ever a regular file
30 /// whose name starts with `.tmp` directly inside the Codewhale home and
31 /// whose last modification was more than an hour ago.
32 DeleteStaleTempFile {
33 path: PathBuf,
34 },
35 /// Restrict a secret-store file to owner-only on Unix.
36 #[cfg(unix)]
37 TightenSecretPermissions {
38 path: PathBuf,
39 from_mode: u32,
40 },
41 /// Disable a structurally broken MCP entry by name in the given config.
42 DisableMcpServer {
43 config_path: PathBuf,
44 server: String,
45 },
46 /// Create a missing user-global discovery directory.
47 ScaffoldDirectory {
48 path: PathBuf,
49 },
50 MoveInstallLeftover {
51 path: PathBuf,
52 bytes: u64,
53 },
54 AlignAlias {
55 alias: PathBuf,
56 primary: PathBuf,
57 sha256: String,
58 },
59 AdoptInstall {
60 dir: PathBuf,
61 sha256: String,
62 },
63 PruneRecovery {
64 stamps: Vec<String>,
65 bytes: u64,
66 },
67 MigrateConfigApiKey {
68 config_path: PathBuf,
69 provider: codewhale_config::ProviderKind,
70 table: String,
71 },
72 }
73
74 /// The full repair plan for one doctor run.
75 #[derive(Debug, Clone, Default, PartialEq, Eq)]
76 pub(crate) struct DoctorFixPlan {
77 pub(crate) actions: Vec<DoctorFixAction>,
78 }
79
80 impl DoctorFixPlan {
81 pub(crate) fn is_empty(&self) -> bool {
82 self.actions.is_empty()
83 }
84
85 pub(crate) fn len(&self) -> usize {
86 self.actions.len()
87 }
88
89 /// One human-readable line per action, in a stable order.
90 pub(crate) fn describe(&self) -> Vec<String> {
91 self.actions
92 .iter()
93 .map(|action| match action {
94 DoctorFixAction::DeleteStaleTempFile { path } => {
95 format!(
96 "delete stale temp file {}",
97 codewhale_util::utils::display_path(path)
98 )
99 }
100 #[cfg(unix)]
101 DoctorFixAction::TightenSecretPermissions { path, from_mode } => format!(
102 "restrict {} to 0600 (currently {:o})",
103 codewhale_util::utils::display_path(path),
104 from_mode & 0o7777
105 ),
106 DoctorFixAction::DisableMcpServer {
107 config_path,
108 server,
109 } => format!(
110 "disable broken MCP server entry '{server}' in {}",
111 codewhale_util::utils::display_path(config_path)
112 ),
113 DoctorFixAction::ScaffoldDirectory { path } => {
114 format!(
115 "create missing directory {}",
116 codewhale_util::utils::display_path(path)
117 )
118 }
119 DoctorFixAction::MoveInstallLeftover { path, bytes } => format!(
120 "move old Codewhale backup {} ({}) to the recovery folder (kept {} days)",
121 codewhale_util::utils::display_path(path),
122 codewhale_release::installs::human_bytes(*bytes),
123 codewhale_release::installs::RECOVERY_RETENTION_DAYS
124 ),
125 DoctorFixAction::AlignAlias { alias, primary, .. } => format!(
126 "make {} match {} (v{}); the old copy goes to the recovery folder",
127 codewhale_util::utils::display_path(alias),
128 codewhale_util::utils::display_path(primary),
129 env!("CARGO_PKG_VERSION")
130 ),
131 DoctorFixAction::AdoptInstall { dir, .. } => format!(
132 "record an install receipt in {} so `codewhale update` and `codewhale uninstall` own it",
133 codewhale_util::utils::display_path(dir)
134 ),
135 DoctorFixAction::PruneRecovery { stamps, bytes } => format!(
136 "delete {} recovery folder(s) older than {} days ({}): {}",
137 stamps.len(),
138 codewhale_release::installs::RECOVERY_RETENTION_DAYS,
139 codewhale_release::installs::human_bytes(*bytes),
140 stamps.join(", ")
141 ),
142 DoctorFixAction::MigrateConfigApiKey {
143 config_path, table, ..
144 } => {
145 if table.is_empty() {
146 format!(
147 "move the plaintext `api_key` from {} into the secret store and remove it from the file",
148 codewhale_util::utils::display_path(config_path)
149 )
150 } else {
151 format!(
152 "move the plaintext `[providers.{table}].api_key` from {} into the secret store and remove it from the file",
153 codewhale_util::utils::display_path(config_path)
154 )
155 }
156 }
157 })
158 .collect()
159 }
160 }
161
162 fn is_stale_temp_file(path: &Path) -> bool {
163 path.file_name()
164 .and_then(|name| name.to_str())
165 .is_some_and(|name| name.starts_with(".tmp"))
166 && std::fs::symlink_metadata(path).is_ok_and(|meta| {
167 meta.is_file()
168 && meta.modified().is_ok_and(|modified| {
169 modified
170 .elapsed()
171 .is_ok_and(|age| age > std::time::Duration::from_secs(60 * 60))
172 })
173 })
174 }
175
176 /// Stale `.tmp*` regular files directly inside the Codewhale home.
177 /// Recent files and files with unknown or future modification times are kept.
178 fn stale_temp_files() -> Vec<PathBuf> {
179 let Ok(home) = codewhale_config::codewhale_home() else {
180 return Vec::new();
181 };
182 let Ok(entries) = std::fs::read_dir(&home) else {
183 return Vec::new();
184 };
185 let mut files = entries
186 .flatten()
187 .map(|entry| entry.path())
188 .filter(|path| is_stale_temp_file(path))
189 .collect::<Vec<_>>();
190 files.sort();
191 files
192 }
193
194 /// Secret-store files whose Unix permissions are looser than 0600.
195 #[cfg(unix)]
196 fn secret_files_needing_tightening() -> Vec<(PathBuf, u32)> {
197 use std::os::unix::fs::PermissionsExt;
198
199 let Ok(paths) = codewhale_secrets::FileKeyringStore::default_paths_read_only() else {
200 return Vec::new();
201 };
202 let candidates = std::iter::once(paths.0).chain(paths.1);
203 candidates
204 .filter_map(|path| {
205 let metadata = std::fs::metadata(&path).ok()?;
206 if !metadata.is_file() {
207 return None;
208 }
209 let mode = metadata.permissions().mode();
210 (mode & 0o077 != 0).then_some((path, mode))
211 })
212 .collect()
213 }
214
215 /// MCP entries whose structural check reports `Error`, by config file.
216 fn broken_mcp_entries(
217 config: &codewhale_runtime::config::Config,
218 workspace: &Path,
219 plugins: &codewhale_plugins::PluginRegistry,
220 ) -> Vec<(PathBuf, Vec<String>)> {
221 let global_path = config.mcp_config_path();
222 let project_path = mcp::workspace_mcp_config_path(workspace);
223 let mut broken = Vec::new();
224 for path in [global_path, project_path] {
225 let Ok(cfg) = mcp::load_config_with_workspace_and_plugins(&path, workspace, plugins) else {
226 continue;
227 };
228 let names = cfg
229 .servers
230 .iter()
231 .filter(|(_, server)| {
232 server.is_enabled()
233 && matches!(
234 crate::doctor_check_mcp_server(server),
235 McpServerDoctorStatus::Error(_)
236 )
237 })
238 .map(|(name, _)| name.clone())
239 .collect::<Vec<_>>();
240 if !names.is_empty() {
241 broken.push((path, names));
242 }
243 }
244 broken
245 }
246
247 /// User-global discovery directories the product expects to exist.
248 fn missing_user_directories(config: &codewhale_runtime::config::Config) -> Vec<PathBuf> {
249 let candidates = [
250 config.skills_dir(),
251 crate::default_tools_dir(),
252 crate::default_plugins_dir(),
253 ];
254 let mut missing = candidates
255 .into_iter()
256 .filter(|dir| !dir.exists())
257 .collect::<Vec<_>>();
258 missing.sort();
259 missing
260 }
261
262 /// Compute the repair plan. Pure: reads state, mutates nothing.
263 #[cfg(test)]
264 pub(crate) fn plan_fixes(
265 config: &codewhale_runtime::config::Config,
266 workspace: &Path,
267 plugins: &codewhale_plugins::PluginRegistry,
268 ) -> DoctorFixPlan {
269 plan_fixes_for_config(config, workspace, None, plugins)
270 }
271
272 pub(crate) fn plan_fixes_for_config(
273 config: &codewhale_runtime::config::Config,
274 workspace: &Path,
275 config_path_override: Option<&Path>,
276 plugins: &codewhale_plugins::PluginRegistry,
277 ) -> DoctorFixPlan {
278 let mut actions = Vec::new();
279 actions.extend(
280 stale_temp_files()
281 .into_iter()
282 .map(|path| DoctorFixAction::DeleteStaleTempFile { path }),
283 );
284 #[cfg(unix)]
285 actions.extend(
286 secret_files_needing_tightening()
287 .into_iter()
288 .map(|(path, from_mode)| DoctorFixAction::TightenSecretPermissions { path, from_mode }),
289 );
290 for (config_path, servers) in broken_mcp_entries(config, workspace, plugins) {
291 actions.extend(
292 servers
293 .into_iter()
294 .map(|server| DoctorFixAction::DisableMcpServer {
295 config_path: config_path.clone(),
296 server,
297 }),
298 );
299 }
300 actions.extend(
301 missing_user_directories(config)
302 .into_iter()
303 .map(|path| DoctorFixAction::ScaffoldDirectory { path }),
304 );
305 actions.extend(install_actions());
306 actions.extend(config_api_key_migrations(config, config_path_override));
307 DoctorFixPlan { actions }
308 }
309
310 fn literal_api_key_value(value: Option<&toml::Value>) -> Option<String> {
311 value
312 .and_then(toml::Value::as_str)
313 .filter(|key| {
314 codewhale_config::classify_config_api_key_value(key)
315 == codewhale_config::ConfigApiKeyValueKind::Literal
316 })
317 .map(str::to_string)
318 }
319
320 fn read_toml_doc(config_path: &Path) -> Option<toml::Value> {
321 let raw = std::fs::read_to_string(config_path).ok()?;
322 toml::from_str(&raw).ok()
323 }
324
325 fn file_api_key(config_path: &Path, table: &str) -> Option<String> {
326 let doc = read_toml_doc(config_path)?;
327 if table.is_empty() {
328 return literal_api_key_value(doc.get("api_key"));
329 }
330 literal_api_key_value(
331 doc.get("providers")
332 .and_then(|providers| providers.get(table))
333 .and_then(|entry| entry.get("api_key")),
334 )
335 }
336
337 fn entry_disallows_api_key_migration(
338 entry: Option<&toml::Value>,
339 disk_config: &codewhale_runtime::config::Config,
340 identity: &codewhale_runtime::config::ProviderIdentity,
341 ) -> bool {
342 if disk_config.should_skip_secret_store_for_provider(identity) {
343 return true;
344 }
345 if let Some(table) = entry.and_then(toml::Value::as_table) {
346 if table.contains_key("api_key_env")
347 || table.contains_key("oauth_credential_generation")
348 || table
349 .get("external_credentials")
350 .and_then(toml::Value::as_bool)
351 == Some(true)
352 {
353 return true;
354 }
355 if table
356 .get("auth_mode")
357 .and_then(toml::Value::as_str)
358 .is_some_and(|mode| !mode.trim().eq_ignore_ascii_case("api_key"))
359 {
360 return true;
361 }
362 }
363 if disk_config
364 .auth_mode_for_provider(identity)
365 .as_deref()
366 .is_some_and(|mode| !mode.trim().eq_ignore_ascii_case("api_key"))
367 {
368 return true;
369 }
370 disk_config
371 .provider_config_for(identity)
372 .is_some_and(|cfg| {
373 cfg.api_key_env.is_some()
374 || cfg.external_credentials.is_some()
375 || cfg.oauth_credential_generation.is_some()
376 })
377 }
378
379 fn config_api_key_migrations(
380 config: &codewhale_runtime::config::Config,
381 config_path_override: Option<&Path>,
382 ) -> Vec<DoctorFixAction> {
383 let config_path = match config_path_override {
384 Some(path) => path.to_path_buf(),
385 None => match config.loaded_config_path.as_ref() {
386 Some(path) => path.clone(),
387 None => match codewhale_runtime::config::credential_config_path() {
388 Ok(path) => path,
389 Err(_) => return Vec::new(),
390 },
391 },
392 };
393 let Some(doc) = read_toml_doc(&config_path) else {
394 return Vec::new();
395 };
396 let Ok(disk_config) = codewhale_runtime::config::Config::load_with(
397 Some(config_path.clone()),
398 None,
399 codewhale_runtime::config::ConfigEnvironmentPolicy::Runtime,
400 &mut |_| Ok(()),
401 ) else {
402 return Vec::new();
403 };
404
405 let conflicted_tables: std::collections::HashSet<&str> = disk_config
406 .legacy_root
407 .notes
408 .iter()
409 .filter_map(|note| match note {
410 codewhale_config::legacy_root::LegacyRootNote::Conflict {
411 scope: None,
412 field: codewhale_config::legacy_root::LegacyRootField::ApiKey,
413 table,
414 ..
415 } => Some(table.strip_prefix("providers.").unwrap_or(table.as_str())),
416 _ => None,
417 })
418 .collect();
419
420 struct Candidate {
421 slot: &'static str,
422 provider: codewhale_config::ProviderKind,
423 table: String,
424 key: String,
425 }
426
427 let mut candidates: Vec<Candidate> = Vec::new();
428
429 if let Some(root_key) = literal_api_key_value(doc.get("api_key"))
430 && conflicted_tables.is_empty()
431 {
432 let root_owner = disk_config
433 .legacy_root
434 .notes
435 .iter()
436 .find_map(|note| match note {
437 codewhale_config::legacy_root::LegacyRootNote::Moved {
438 scope: None,
439 field: codewhale_config::legacy_root::LegacyRootField::ApiKey,
440 to,
441 }
442 | codewhale_config::legacy_root::LegacyRootNote::Merged {
443 scope: None,
444 field: codewhale_config::legacy_root::LegacyRootField::ApiKey,
445 to,
446 } => Some(to.strip_prefix("providers.").unwrap_or(to.as_str())),
447 _ => None,
448 })
449 .unwrap_or("deepseek");
450 if let Ok(identity) = disk_config.resolve_provider_identity(root_owner)
451 && !matches!(
452 identity.provider,
453 codewhale_config::ProviderKind::Custom
454 | codewhale_config::ProviderKind::OpenaiCodex
455 | codewhale_config::ProviderKind::Antigravity
456 )
457 && !entry_disallows_api_key_migration(None, &disk_config, &identity)
458 {
459 candidates.push(Candidate {
460 slot: codewhale_runtime::config::provider_secret_store_slot(identity.provider),
461 provider: identity.provider,
462 table: String::new(),
463 key: root_key,
464 });
465 }
466 }
467
468 if let Some(providers_table) = doc.get("providers").and_then(toml::Value::as_table) {
469 for (raw_table, entry_val) in providers_table {
470 let Some(literal) = literal_api_key_value(entry_val.get("api_key")) else {
471 continue;
472 };
473 let Ok(identity) = disk_config.resolve_provider_identity(raw_table) else {
474 continue;
475 };
476 if matches!(
477 identity.provider,
478 codewhale_config::ProviderKind::Custom
479 | codewhale_config::ProviderKind::OpenaiCodex
480 | codewhale_config::ProviderKind::Antigravity
481 ) {
482 continue;
483 }
484 let canonical_table = identity
485 .config_table_key()
486 .ok()
487 .unwrap_or(raw_table.as_str());
488 if conflicted_tables.contains(raw_table.as_str())
489 || conflicted_tables.contains(canonical_table)
490 {
491 continue;
492 }
493 if entry_disallows_api_key_migration(Some(entry_val), &disk_config, &identity) {
494 continue;
495 }
496 candidates.push(Candidate {
497 slot: codewhale_runtime::config::provider_secret_store_slot(identity.provider),
498 provider: identity.provider,
499 table: raw_table.clone(),
500 key: literal,
501 });
502 }
503 }
504
505 let mut slot_keys: std::collections::HashMap<&'static str, Option<String>> =
506 std::collections::HashMap::new();
507 for candidate in &candidates {
508 slot_keys
509 .entry(candidate.slot)
510 .and_modify(|existing| {
511 if existing.as_deref() != Some(candidate.key.as_str()) {
512 *existing = None;
513 }
514 })
515 .or_insert_with(|| Some(candidate.key.clone()));
516 }
517
518 candidates
519 .into_iter()
520 .filter(|candidate| slot_keys.get(candidate.slot).is_some_and(Option::is_some))
521 .map(|candidate| DoctorFixAction::MigrateConfigApiKey {
522 config_path: config_path.clone(),
523 provider: candidate.provider,
524 table: candidate.table,
525 })
526 .collect()
527 }
528
529 fn migrate_config_api_key(
530 _config: &codewhale_runtime::config::Config,
531 config_path: &Path,
532 provider: codewhale_config::ProviderKind,
533 table: &str,
534 ) -> Result<()> {
535 let Some(api_key) = file_api_key(config_path, table) else {
536 return Ok(());
537 };
538 let Some(secrets) = codewhale_runtime::config::credential_secret_store() else {
539 anyhow::bail!(
540 "no durable secret store is available, so the key stays in {}; check `codewhale doctor --all` under Secret Backend",
541 codewhale_util::utils::display_path(config_path)
542 );
543 };
544 let normalized = codewhale_secrets::normalize_api_key(&api_key);
545 let api_key = normalized.as_str();
546 anyhow::ensure!(!api_key.is_empty(), "refusing to migrate an empty API key");
547 let slot = codewhale_runtime::config::provider_secret_store_slot(provider);
548 let disk_config = codewhale_runtime::config::Config::load_with(
549 Some(config_path.to_path_buf()),
550 None,
551 codewhale_runtime::config::ConfigEnvironmentPolicy::Runtime,
552 &mut |_| Ok(()),
553 )?;
554 let identity = disk_config
555 .resolve_provider_identity(if table.is_empty() {
556 provider.as_str()
557 } else {
558 table
559 })
560 .map_err(anyhow::Error::msg)?;
561 if disk_config.should_skip_secret_store_for_provider(&identity) {
562 anyhow::bail!(
563 "secret-store migration is skipped for {}; keeping plaintext in {}",
564 identity.key,
565 codewhale_util::utils::display_path(config_path)
566 );
567 }
568 let active_provider = disk_config
569 .active_provider_identity()
570 .ok()
571 .map(|id| id.provider);
572
573 codewhale_runtime::credentials::store::with_provider_write_lock(slot, || {
574 let prior = secrets
575 .get(slot)
576 .map_err(|err| anyhow::anyhow!("failed to read secret-store slot `{slot}`: {err}"))?;
577 if let Some(existing) = prior.as_deref()
578 && existing != api_key
579 {
580 anyhow::bail!(
581 "secret-store slot `{slot}` already holds a different key for a sibling route; keeping plaintext in {}",
582 codewhale_util::utils::display_path(config_path)
583 );
584 }
585 let wrote_secret = prior.as_deref() != Some(api_key);
586 if wrote_secret {
587 secrets.set(slot, api_key).map_err(|err| {
588 anyhow::anyhow!("failed to write secret-store slot `{slot}`: {err}")
589 })?;
590 }
591 let dest_table = identity
592 .config_table_key()
593 .unwrap_or(provider.as_str())
594 .to_string();
595 let doc_result =
596 codewhale_runtime::config_persistence::mutate_config_document(config_path, |doc| {
597 if table.is_empty() {
598 if active_provider == Some(provider) {
599 codewhale_runtime::config_persistence::set_document_value(
600 doc,
601 &["auth_mode"],
602 "api_key",
603 )?;
604 }
605 codewhale_runtime::config_persistence::unset_document_value(doc, &["api_key"])?;
606 if doc
607 .get("providers")
608 .and_then(|item| item.as_table())
609 .and_then(|providers| providers.get(&dest_table))
610 .and_then(|entry| entry.as_table())
611 .and_then(|entry| entry.get("api_key"))
612 .and_then(|item| item.as_str())
613 .is_some_and(|val| codewhale_secrets::normalize_api_key(val) == api_key)
614 {
615 codewhale_runtime::config_persistence::unset_document_value(
616 doc,
617 &["providers", &dest_table, "api_key"],
618 )?;
619 }
620 } else {
621 codewhale_runtime::config_persistence::set_document_value(
622 doc,
623 &["providers", table, "auth_mode"],
624 "api_key",
625 )?;
626 codewhale_runtime::config_persistence::unset_document_value(
627 doc,
628 &["providers", table, "api_key"],
629 )?;
630 }
631 Ok(())
632 });
633 if let Err(error) = doc_result {
634 if wrote_secret {
635 let _ = match prior.as_deref() {
636 Some(previous) => secrets.set(slot, previous),
637 None => secrets.delete(slot),
638 };
639 }
640 return Err(error);
641 }
642 codewhale_config::scrub_plaintext_api_keys_from_config_backup(config_path)?;
643 Ok(())
644 })
645 }
646
647 fn install_actions() -> Vec<DoctorFixAction> {
648 use codewhale_release::installs::{self, InstallClass};
649 let running = std::env::current_exe().ok();
650 let inventory = installs::inventory(running.as_deref());
651 let mut actions: Vec<DoctorFixAction> = inventory
652 .leftovers()
653 .map(|entry| DoctorFixAction::MoveInstallLeftover {
654 path: entry.path.clone(),
655 bytes: entry.bytes,
656 })
657 .collect();
658 let canonical =
659 |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
660 if let Some(exe) = &running
661 && codewhale_release::InstallMethod::detect(exe).supports_self_update()
662 && let Some(dir) = exe.parent().map(canonical)
663 && std::fs::symlink_metadata(dir.join(installs::RECEIPT_FILE)).is_err()
664 && let Some(entry) = inventory
665 .entries
666 .iter()
667 .find(|entry| canonical(&entry.path) == canonical(exe))
668 && entry.class == InstallClass::OursUnreceipted
669 && let Ok(sha256) = installs::file_sha256(exe)
670 {
671 for alias in inventory.entries.iter().filter(|other| {
672 other.class == InstallClass::OursUnreceipted
673 && !other.same_as_running
674 && other.path.parent().map(canonical).as_deref() == Some(dir.as_path())
675 && installs::RECEIPT_COMMANDS
676 .iter()
677 .any(|name| other.path.file_name().and_then(|n| n.to_str()) == Some(name))
678 }) {
679 actions.push(DoctorFixAction::AlignAlias {
680 alias: alias.path.clone(),
681 primary: exe.clone(),
682 sha256: sha256.clone(),
683 });
684 }
685 if installs::directory_is_private(&dir) {
686 actions.push(DoctorFixAction::AdoptInstall { dir, sha256 });
687 }
688 }
689 if let Ok(home) = codewhale_config::codewhale_home() {
690 let now = codewhale_release::check::now_unix();
691 let expired: Vec<_> = installs::recovery_folders(&home)
692 .into_iter()
693 .filter(|folder| folder.expires_in_days(now) == Some(0))
694 .collect();
695 if !expired.is_empty() {
696 actions.push(DoctorFixAction::PruneRecovery {
697 bytes: expired.iter().map(|folder| folder.bytes()).sum(),
698 stamps: expired.into_iter().map(|folder| folder.stamp).collect(),
699 });
700 }
701 }
702 actions
703 }
704
705 /// Outcome of applying one action.
706 #[derive(Debug, Clone, PartialEq, Eq)]
707 pub(crate) enum DoctorFixOutcome {
708 Applied,
709 Failed(String),
710 }
711
712 /// Apply a plan. Each action reports its own outcome; one failure never
713 /// blocks the rest. Actions are idempotent, so a re-run converges.
714 pub(crate) fn apply_fixes(
715 plan: &DoctorFixPlan,
716 config: &codewhale_runtime::config::Config,
717 ) -> Vec<(DoctorFixAction, DoctorFixOutcome)> {
718 let mut batch = None;
719 let results = plan
720 .actions
721 .iter()
722 .cloned()
723 .map(|action| {
724 let outcome = match apply_install_action(&action, &mut batch) {
725 Some(Ok(())) => DoctorFixOutcome::Applied,
726 Some(Err(error)) => DoctorFixOutcome::Failed(format!("{error:#}")),
727 None => match &action {
728 DoctorFixAction::MigrateConfigApiKey {
729 config_path,
730 provider,
731 table,
732 } => match migrate_config_api_key(config, config_path, *provider, table) {
733 Ok(()) => DoctorFixOutcome::Applied,
734 Err(error) => DoctorFixOutcome::Failed(format!("{error:#}")),
735 },
736 _ => apply_one(&action),
737 },
738 };
739 (action, outcome)
740 })
741 .collect();
742 if let Some(batch) = batch {
743 let batch: codewhale_release::installs::RecoveryBatch = batch;
744 let stamp = batch.stamp.clone();
745 let dir = batch.dir.clone();
746 let moves = batch.finish();
747 if !moves.is_empty() {
748 println!(
749 "Moved {} item(s) ({}) to {}. Undo all: codewhale doctor --restore {stamp}",
750 moves.len(),
751 codewhale_release::installs::human_bytes(moves.iter().map(|m| m.bytes).sum()),
752 dir.display()
753 );
754 }
755 }
756 results
757 }
758
759 fn recovery_batch(
760 batch: &mut Option<codewhale_release::installs::RecoveryBatch>,
761 ) -> Result<&mut codewhale_release::installs::RecoveryBatch> {
762 if batch.is_none() {
763 let home = codewhale_config::codewhale_home()?;
764 *batch = Some(codewhale_release::installs::RecoveryBatch::open(&home)?);
765 }
766 Ok(batch.as_mut().expect("recovery batch was just opened"))
767 }
768
769 fn apply_install_action(
770 action: &DoctorFixAction,
771 batch: &mut Option<codewhale_release::installs::RecoveryBatch>,
772 ) -> Option<Result<()>> {
773 use codewhale_release::installs;
774 Some(match action {
775 DoctorFixAction::MoveInstallLeftover { path, .. } => (|| {
776 let meta = std::fs::symlink_metadata(path)?;
777 anyhow::ensure!(!meta.is_symlink(), "it became a symlink; not moved");
778 let moved = recovery_batch(batch)?.move_in(path)?;
779 println!(
780 " moved {} -> {}\n undo: {}",
781 path.display(),
782 moved.to.display(),
783 moved.undo_command()
784 );
785 Ok(())
786 })(),
787 DoctorFixAction::AlignAlias {
788 alias,
789 primary,
790 sha256,
791 } => (|| {
792 let bytes = std::fs::read(primary)?;
793 anyhow::ensure!(
794 &installs::sha256_hex(&bytes) == sha256,
795 "{} changed since the plan; not aligned",
796 primary.display()
797 );
798 let dir = alias.parent().context("alias has no parent")?;
799 let name = alias
800 .file_name()
801 .and_then(|name| name.to_str())
802 .context("alias name is not UTF-8")?;
803 let moved = recovery_batch(batch)?.move_in(alias)?;
804 if let Err(error) =
805 codewhale_release::installs::write_file_atomically(dir, name, &bytes, true)
806 {
807 let _ = std::fs::rename(&moved.to, alias);
808 return Err(error);
809 }
810 println!(
811 " replaced {} with v{}; old copy at {}\n undo: rm {} && {}",
812 alias.display(),
813 env!("CARGO_PKG_VERSION"),
814 moved.to.display(),
815 alias.display(),
816 moved.undo_command()
817 );
818 Ok(())
819 })(),
820 DoctorFixAction::AdoptInstall { dir, sha256 } => (|| {
821 let entries: Vec<(String, String)> = installs::RECEIPT_COMMANDS
822 .iter()
823 .filter(|name| {
824 installs::file_sha256(&dir.join(name)).is_ok_and(|hash| &hash == sha256)
825 })
826 .map(|name| ((*name).to_string(), sha256.clone()))
827 .collect();
828 if installs::adopt_receipt(dir, &entries)? {
829 println!(
830 " recorded {}\n undo: rm {}",
831 dir.join(installs::RECEIPT_FILE).display(),
832 dir.join(installs::RECEIPT_FILE).display()
833 );
834 }
835 Ok(())
836 })(),
837 DoctorFixAction::PruneRecovery { .. } => (|| {
838 let home = codewhale_config::codewhale_home()?;
839 for (stamp, bytes) in installs::prune_expired(&home) {
840 println!(
841 " deleted expired recovery folder {stamp} ({})",
842 installs::human_bytes(bytes)
843 );
844 }
845 Ok(())
846 })(),
847 _ => return None,
848 })
849 }
850
851 fn apply_one(action: &DoctorFixAction) -> DoctorFixOutcome {
852 match action {
853 DoctorFixAction::DeleteStaleTempFile { path } => {
854 // Re-verify the deletion guard at apply time: the plan was
855 // computed before consent, so the file may have changed.
856 if !is_stale_temp_file(path) {
857 return DoctorFixOutcome::Applied;
858 }
859 match std::fs::remove_file(path) {
860 Ok(()) => DoctorFixOutcome::Applied,
861 Err(error) => DoctorFixOutcome::Failed(error.to_string()),
862 }
863 }
864 #[cfg(unix)]
865 DoctorFixAction::TightenSecretPermissions { path, .. } => {
866 use std::os::unix::fs::PermissionsExt;
867 match std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) {
868 Ok(()) => DoctorFixOutcome::Applied,
869 Err(error) => DoctorFixOutcome::Failed(error.to_string()),
870 }
871 }
872 DoctorFixAction::DisableMcpServer {
873 config_path,
874 server,
875 } => match disable_mcp_server(config_path, server) {
876 Ok(()) => DoctorFixOutcome::Applied,
877 Err(error) => DoctorFixOutcome::Failed(format!("{error:#}")),
878 },
879 DoctorFixAction::ScaffoldDirectory { path } => match std::fs::create_dir_all(path) {
880 Ok(()) => DoctorFixOutcome::Applied,
881 Err(error) => DoctorFixOutcome::Failed(error.to_string()),
882 },
883 DoctorFixAction::MoveInstallLeftover { .. }
884 | DoctorFixAction::AlignAlias { .. }
885 | DoctorFixAction::AdoptInstall { .. }
886 | DoctorFixAction::PruneRecovery { .. }
887 | DoctorFixAction::MigrateConfigApiKey { .. } => DoctorFixOutcome::Applied,
888 }
889 }
890
891 /// Disable one server entry in an MCP config file through the atomic save
892 /// path the MCP editor uses. A missing file or missing server is a no-op
893 /// (the plan may be stale after consent).
894 fn disable_mcp_server(config_path: &Path, server_name: &str) -> Result<()> {
895 mcp::mutate_config(config_path, None, |cfg| {
896 if let Some(server) = cfg.servers.get_mut(server_name) {
897 server.enabled = false;
898 server.disabled = true;
899 }
900 Ok(())
901 })
902 .map(|_| ())
903 }
904
905 /// Print the repair plan the way the human doctor report presents it.
906 pub(crate) fn print_fix_plan(plan: &DoctorFixPlan) {
907 use colored::Colorize;
908
909 let (sky_r, sky_g, sky_b) = codewhale_palette::WHALE_ACTION_RGB;
910 println!("{}", "Repair plan (--fix):".bold());
911 if plan.is_empty() {
912 println!(" {} nothing to repair", "✓".truecolor(sky_r, sky_g, sky_b));
913 return;
914 }
915 for line in plan.describe() {
916 println!(" · {line}");
917 }
918 println!(
919 " {} pass --yes to apply without prompting",
920 "!".truecolor(sky_r, sky_g, sky_b)
921 );
922 }
923
924 /// Ask for consent on stdin. Only used by the human (non-JSON) doctor path.
925 pub(crate) fn confirm_fix(plan: &DoctorFixPlan) -> bool {
926 use std::io::{BufRead, Write};
927
928 println!();
929 print!("Apply these {} repair(s) now? [Y/n] ", plan.len());
930 let mut answer = String::new();
931 let _ = std::io::stdout().flush();
932 match std::io::stdin().lock().read_line(&mut answer) {
933 Ok(0) | Err(_) => false,
934 Ok(_) => matches!(
935 answer.trim().to_ascii_lowercase().as_str(),
936 "" | "y" | "yes"
937 ),
938 }
939 }
940
941 /// Print apply results and return whether every action succeeded.
942 pub(crate) fn print_apply_results(results: &[(DoctorFixAction, DoctorFixOutcome)]) -> bool {
943 use colored::Colorize;
944
945 let (aqua_r, aqua_g, aqua_b) = codewhale_palette::WHALE_ACTION_RGB;
946 let (red_r, red_g, red_b) = codewhale_palette::WHALE_ERROR_RGB;
947 println!("{}", "Repair results:".bold());
948 let mut all_applied = true;
949 for (action, outcome) in results {
950 match outcome {
951 DoctorFixOutcome::Applied => println!(
952 " {} {}",
953 "✓".truecolor(aqua_r, aqua_g, aqua_b),
954 plan_action_line(action)
955 ),
956 DoctorFixOutcome::Failed(error) => {
957 all_applied = false;
958 println!(
959 " {} {} — {error}",
960 "✗".truecolor(red_r, red_g, red_b),
961 plan_action_line(action)
962 );
963 }
964 }
965 }
966 all_applied
967 }
968
969 fn plan_action_line(action: &DoctorFixAction) -> String {
970 DoctorFixPlan {
971 actions: vec![action.clone()],
972 }
973 .describe()
974 .pop()
975 .unwrap_or_else(|| "repair".to_string())
976 }
977
978 #[cfg(test)]
979 mod tests {
980 use super::*;
981
982 /// Scoped `CODEWHALE_HOME` override under the process-wide env barrier.
983 /// `EnvVarGuard` restores the prior value even on panic.
984 struct ScratchHome {
985 dir: tempfile::TempDir,
986 _env: crate::test_support::EnvVarGuard,
987 _lock: crate::test_support::TestEnvLock,
988 }
989
990 impl ScratchHome {
991 fn new() -> (Self, codewhale_runtime::config::Config) {
992 let lock = crate::test_support::lock_test_env();
993 let dir = tempfile::tempdir().expect("home tempdir");
994 let env = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", dir.path());
995 (
996 Self {
997 dir,
998 _env: env,
999 _lock: lock,
1000 },
1001 codewhale_runtime::config::Config::default(),
1002 )
1003 }
1004
1005 fn path(&self) -> &Path {
1006 self.dir.path()
1007 }
1008 }
1009
1010 fn adv_plan_and_apply(
1011 home: &ScratchHome,
1012 body: &str,
1013 ) -> (
1014 Vec<String>,
1015 Vec<(DoctorFixAction, DoctorFixOutcome)>,
1016 String,
1017 ) {
1018 let config_path = home.path().join("config.toml");
1019 std::fs::write(&config_path, body).expect("write config");
1020 let config = codewhale_runtime::config::Config::load(Some(config_path.clone()), None)
1021 .expect("load config");
1022 let workspace = tempfile::tempdir().expect("workspace");
1023 let registry = codewhale_plugins::PluginRegistry::default();
1024 let plan = DoctorFixPlan {
1025 actions: plan_fixes(&config, workspace.path(), &registry)
1026 .actions
1027 .into_iter()
1028 .filter(|action| matches!(action, DoctorFixAction::MigrateConfigApiKey { .. }))
1029 .collect(),
1030 };
1031 let described = plan.describe();
1032 let results = apply_fixes(&plan, &config);
1033 let raw = std::fs::read_to_string(&config_path).expect("read config");
1034 (described, results, raw)
1035 }
1036
1037 #[test]
1038 fn adv_xai_oauth_route_is_not_flipped_to_api_key() {
1039 let (home, _) = ScratchHome::new();
1040 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1041 let body = "provider = \"xai\"\n[providers.xai]\nauth_mode = \"oauth\"\napi_key = \"xai-advreviewleftover0123456789\"\n";
1042 let (plan, _results, raw) = adv_plan_and_apply(&home, body);
1043 assert!(
1044 plan.is_empty(),
1045 "oauth provider must not be migrated: {plan:?}"
1046 );
1047 assert!(
1048 raw.contains("auth_mode = \"oauth\""),
1049 "xAI OAuth route flipped: {raw}"
1050 );
1051 }
1052
1053 #[test]
1054 fn adv_anthropic_oauth_route_is_not_flipped_to_api_key() {
1055 let (home, _) = ScratchHome::new();
1056 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1057 let body = "provider = \"anthropic\"\n[providers.anthropic]\nauth_mode = \"oauth\"\noauth_credential_generation = \"gen-1\"\napi_key = \"sk-ant-advreviewleftover0123456789\"\n";
1058 let (plan, _results, raw) = adv_plan_and_apply(&home, body);
1059 assert!(
1060 plan.is_empty(),
1061 "oauth provider must not be migrated: {plan:?}"
1062 );
1063 assert!(
1064 raw.contains("auth_mode = \"oauth\""),
1065 "Anthropic OAuth route flipped: {raw}"
1066 );
1067 }
1068
1069 #[test]
1070 fn adv_shared_slot_keys_are_not_lost() {
1071 let (home, _) = ScratchHome::new();
1072 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1073 let global = "sk-advglobalsiliconflow0123456789";
1074 let china = "sk-advchinasiliconflow0123456789";
1075 let body = format!(
1076 "provider = \"siliconflow\"\n[providers.siliconflow]\napi_key = \"{global}\"\n[providers.siliconflow_cn]\napi_key = \"{china}\"\n"
1077 );
1078 let (plan, _results, raw) = adv_plan_and_apply(&home, &body);
1079 let stored = codewhale_runtime::config::credential_secret_store()
1080 .and_then(|store| store.get("siliconflow").ok().flatten());
1081 let survives = |key: &str| raw.contains(key) || stored.as_deref() == Some(key);
1082 assert!(
1083 plan.is_empty(),
1084 "conflicting shared slot must not migrate: {plan:?}"
1085 );
1086 assert!(
1087 survives(global) && survives(china),
1088 "a key was lost: stored={stored:?} raw={raw}"
1089 );
1090 }
1091
1092 #[test]
1093 fn adv_deepseek_root_key_side_effects() {
1094 let (home, _) = ScratchHome::new();
1095 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1096 let body = "provider = \"zai\"\napi_key = \"sk-advdeepseekroot0123456789abcd\"\n[providers.zai]\nmodel = \"glm-5\"\n";
1097 let (plan, results, raw) = adv_plan_and_apply(&home, body);
1098 assert_eq!(plan.len(), 1, "{plan:?}");
1099 assert_eq!(results[0].1, DoctorFixOutcome::Applied, "{results:?}");
1100 assert!(!raw.contains("sk-advdeepseekroot"), "{raw}");
1101 assert!(!raw.contains("auth_mode = \"api_key\""), "{raw}");
1102 assert!(!raw.contains("reasoning_effort = \"auto\""), "{raw}");
1103 }
1104
1105 #[test]
1106 fn fix_honors_explicit_config_path_and_skips_legacy_root_conflict() {
1107 let (home, _) = ScratchHome::new();
1108 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1109 let default_path = home.path().join("config.toml");
1110 std::fs::write(
1111 &default_path,
1112 "[providers.openai]\napi_key = \"sk-defaultfile0123456789abcdef\"\n",
1113 )
1114 .expect("write default");
1115
1116 let custom_dir = tempfile::tempdir().expect("custom dir");
1117 let custom_path = custom_dir.path().join("other.toml");
1118 std::fs::write(
1119 &custom_path,
1120 "[providers.stepfun]\napi_key = \"sk-otherfile0123456789abcdef\"\n",
1121 )
1122 .expect("write custom");
1123
1124 let config = codewhale_runtime::config::Config::load(Some(custom_path.clone()), None)
1125 .expect("load custom");
1126 let workspace = tempfile::tempdir().expect("workspace");
1127 let registry = codewhale_plugins::PluginRegistry::default();
1128 let plan = DoctorFixPlan {
1129 actions: plan_fixes_for_config(
1130 &config,
1131 workspace.path(),
1132 Some(&custom_path),
1133 &registry,
1134 )
1135 .actions
1136 .into_iter()
1137 .filter(|action| matches!(action, DoctorFixAction::MigrateConfigApiKey { .. }))
1138 .collect(),
1139 };
1140 assert_eq!(plan.len(), 1, "{plan:?}");
1141 let results = apply_fixes(&plan, &config);
1142 assert_eq!(results[0].1, DoctorFixOutcome::Applied, "{results:?}");
1143 assert!(
1144 std::fs::read_to_string(&default_path)
1145 .expect("default")
1146 .contains("sk-defaultfile0123456789abcdef")
1147 );
1148 assert!(
1149 !std::fs::read_to_string(&custom_path)
1150 .expect("custom")
1151 .contains("sk-otherfile0123456789abcdef")
1152 );
1153
1154 let conflict_body = "api_key = \"sk-rootconflict0123456789ab\"\n[providers.deepseek]\napi_key = \"sk-tableconflict0123456789a\"\n";
1155 let (conflict_plan, _, conflict_raw) = adv_plan_and_apply(&home, conflict_body);
1156 assert!(conflict_plan.is_empty(), "{conflict_plan:?}");
1157 assert!(conflict_raw.contains("sk-rootconflict"));
1158 assert!(conflict_raw.contains("sk-tableconflict"));
1159 }
1160
1161 #[test]
1162 fn fix_moves_a_plaintext_provider_key_into_the_secret_store() {
1163 let (home, config) = ScratchHome::new();
1164 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
1165 let config_path = home.path().join("config.toml");
1166 let key = "sk-doctorfixmigration0123456789";
1167 std::fs::write(
1168 &config_path,
1169 format!("[providers.stepfun]\nmodel = \"step-3\"\napi_key = \"{key}\"\n"),
1170 )
1171 .expect("write config");
1172 let workspace = tempfile::tempdir().expect("workspace");
1173 let registry = codewhale_plugins::PluginRegistry::default();
1174 let plan = DoctorFixPlan {
1175 actions: plan_fixes(&config, workspace.path(), &registry)
1176 .actions
1177 .into_iter()
1178 .filter(|action| matches!(action, DoctorFixAction::MigrateConfigApiKey { .. }))
1179 .collect(),
1180 };
1181 assert_eq!(plan.len(), 1, "{plan:?}");
1182 assert!(!plan.describe()[0].contains(key));
1183
1184 let results = apply_fixes(&plan, &config);
1185
1186 assert_eq!(results[0].1, DoctorFixOutcome::Applied, "{results:?}");
1187 let raw = std::fs::read_to_string(&config_path).expect("read config");
1188 assert!(!raw.contains(key), "{raw}");
1189 assert!(raw.contains("step-3"), "{raw}");
1190 assert!(
1191 plan_fixes(&config, workspace.path(), &registry)
1192 .actions
1193 .iter()
1194 .all(|action| !matches!(action, DoctorFixAction::MigrateConfigApiKey { .. }))
1195 );
1196 }
1197
1198 #[test]
1199 fn stale_temp_files_only_names_regular_dot_tmp_files_in_home() {
1200 let (home, config) = ScratchHome::new();
1201 std::fs::write(home.path().join(".tmpAbC123"), b"orphaned").expect("write stale");
1202 std::fs::write(home.path().join(".tmpOther"), b"orphaned 2").expect("write stale 2");
1203 let now = std::time::SystemTime::now();
1204 for name in [".tmpAbC123", ".tmpOther"] {
1205 std::fs::File::options()
1206 .write(true)
1207 .open(home.path().join(name))
1208 .unwrap()
1209 .set_modified(now - std::time::Duration::from_secs(2 * 60 * 60))
1210 .unwrap();
1211 }
1212 for (name, modified) in [
1213 (".tmpLive", now),
1214 (".tmpRecent", now - std::time::Duration::from_secs(30 * 60)),
1215 (".tmpFuture", now + std::time::Duration::from_secs(60 * 60)),
1216 ] {
1217 let file = std::fs::File::create(home.path().join(name)).expect("temp file");
1218 file.set_modified(modified).expect("mtime");
1219 }
1220 std::fs::write(home.path().join("keep.txt"), b"keep").expect("write keep");
1221 std::fs::create_dir_all(home.path().join(".tmpDir")).expect("mkdir .tmpDir");
1222
1223 let workspace = tempfile::tempdir().expect("workspace");
1224 let plan = plan_fixes(
1225 &config,
1226 workspace.path(),
1227 &codewhale_plugins::PluginRegistry::default(),
1228 );
1229 let temp_deletions = plan
1230 .actions
1231 .iter()
1232 .filter(|a| matches!(a, DoctorFixAction::DeleteStaleTempFile { .. }))
1233 .count();
1234 assert_eq!(temp_deletions, 2, "{:?}", plan.actions);
1235
1236 // A stale candidate may become active while waiting for consent.
1237 std::fs::File::options()
1238 .write(true)
1239 .open(home.path().join(".tmpOther"))
1240 .unwrap()
1241 .set_modified(now)
1242 .unwrap();
1243 let results = apply_fixes(
1244 &DoctorFixPlan {
1245 actions: plan
1246 .actions
1247 .iter()
1248 .filter(|a| matches!(a, DoctorFixAction::DeleteStaleTempFile { .. }))
1249 .cloned()
1250 .collect(),
1251 },
1252 &config,
1253 );
1254 assert!(results.iter().all(|(_, o)| *o == DoctorFixOutcome::Applied));
1255 assert!(!home.path().join(".tmpAbC123").exists());
1256 for name in [
1257 ".tmpOther",
1258 ".tmpLive",
1259 ".tmpRecent",
1260 ".tmpFuture",
1261 ".tmpDir",
1262 ] {
1263 assert!(home.path().join(name).exists(), "must preserve {name}");
1264 }
1265 assert!(home.path().join("keep.txt").exists());
1266 }
1267
1268 #[test]
1269 fn missing_user_directories_are_planned_and_scaffolding_is_idempotent() {
1270 let (home, config) = ScratchHome::new();
1271 let workspace = tempfile::tempdir().expect("workspace");
1272 let registry = codewhale_plugins::PluginRegistry::default();
1273 let plan = plan_fixes(&config, workspace.path(), &registry);
1274 assert!(
1275 plan.actions
1276 .iter()
1277 .any(|a| matches!(a, DoctorFixAction::ScaffoldDirectory { .. })),
1278 "scratch home plans scaffolding: {:?}",
1279 plan.actions
1280 );
1281 let results = apply_fixes(&plan, &config);
1282 assert!(
1283 results.iter().all(|(_, o)| *o == DoctorFixOutcome::Applied),
1284 "{results:?}"
1285 );
1286 assert!(home.path().join("skills").exists());
1287 assert!(home.path().join("tools").exists());
1288 assert!(home.path().join("plugins").exists());
1289 let replan = plan_fixes(&config, workspace.path(), &registry);
1290 assert!(
1291 !replan
1292 .actions
1293 .iter()
1294 .any(|a| matches!(a, DoctorFixAction::ScaffoldDirectory { .. })),
1295 "scaffolding converges"
1296 );
1297 }
1298
1299 #[cfg(unix)]
1300 #[test]
1301 fn loose_secret_file_permissions_are_planned_and_tightened() {
1302 use std::os::unix::fs::PermissionsExt;
1303
1304 let (home, config) = ScratchHome::new();
1305 let secrets_dir = home.path().join("secrets");
1306 std::fs::create_dir_all(&secrets_dir).expect("secrets dir");
1307 let secrets_file = secrets_dir.join("secrets.json");
1308 std::fs::write(&secrets_file, b"{}").expect("secrets file");
1309 std::fs::set_permissions(&secrets_file, std::fs::Permissions::from_mode(0o644))
1310 .expect("loosen");
1311
1312 let workspace = tempfile::tempdir().expect("workspace");
1313 let registry = codewhale_plugins::PluginRegistry::default();
1314 let plan = plan_fixes(&config, workspace.path(), &registry);
1315 let tighten = plan
1316 .actions
1317 .iter()
1318 .find(|a| matches!(a, DoctorFixAction::TightenSecretPermissions { .. }))
1319 .expect("loose secret file is planned");
1320 let results = apply_fixes(
1321 &DoctorFixPlan {
1322 actions: vec![tighten.clone()],
1323 },
1324 &config,
1325 );
1326 assert_eq!(results[0].1, DoctorFixOutcome::Applied);
1327 let mode = std::fs::metadata(&secrets_file)
1328 .expect("metadata")
1329 .permissions()
1330 .mode();
1331 assert_eq!(mode & 0o777, 0o600);
1332 }
1333
1334 #[test]
1335 fn fix_flags_parse_and_conflict_with_json_modes() {
1336 use clap::Parser;
1337
1338 let cli = crate::Cli::try_parse_from(["codewhale", "doctor", "--fix", "--yes"])
1339 .expect("--fix --yes parses");
1340 let Some(crate::Commands::Doctor(args)) = cli.command else {
1341 panic!("expected doctor command");
1342 };
1343 assert!(args.fix);
1344 assert!(args.yes);
1345
1346 crate::Cli::try_parse_from(["codewhale", "doctor", "--fix", "--json"])
1347 .expect_err("--fix conflicts with --json");
1348 crate::Cli::try_parse_from(["codewhale", "doctor", "--fix", "--context-json"])
1349 .expect_err("--fix conflicts with --context-json");
1350 crate::Cli::try_parse_from(["codewhale", "doctor", "--yes"])
1351 .expect_err("--yes requires --fix");
1352 }
1353
1354 #[test]
1355 fn broken_mcp_entry_is_disabled_through_the_atomic_save_path() {
1356 let (home, config) = ScratchHome::new();
1357 let workspace = tempfile::tempdir().expect("workspace");
1358 let mcp_path = home.path().join("mcp.json");
1359 std::fs::write(
1360 &mcp_path,
1361 serde_json::json!({
1362 "mcpServers": {
1363 "broken": { "command": "", "args": [] },
1364 "healthy": { "command": "node", "args": ["server.js"] }
1365 }
1366 })
1367 .to_string(),
1368 )
1369 .expect("mcp config");
1370
1371 let mut config = config;
1372 config.mcp_config_path = Some(mcp_path.display().to_string());
1373
1374 let registry = codewhale_plugins::PluginRegistry::default();
1375 let plan = plan_fixes(&config, workspace.path(), &registry);
1376 let disable = plan
1377 .actions
1378 .iter()
1379 .find_map(|a| match a {
1380 DoctorFixAction::DisableMcpServer {
1381 config_path,
1382 server,
1383 } if server == "broken" => Some(config_path.clone()),
1384 _ => None,
1385 })
1386 .expect("broken entry is planned");
1387 assert_eq!(disable, mcp_path);
1388
1389 let results = apply_fixes(
1390 &DoctorFixPlan {
1391 actions: plan
1392 .actions
1393 .iter()
1394 .filter(|a| matches!(a, DoctorFixAction::DisableMcpServer { .. }))
1395 .cloned()
1396 .collect(),
1397 },
1398 &config,
1399 );
1400 assert!(
1401 results.iter().all(|(_, o)| *o == DoctorFixOutcome::Applied),
1402 "{results:?}"
1403 );
1404 let raw: serde_json::Value =
1405 serde_json::from_str(&std::fs::read_to_string(&mcp_path).expect("reread"))
1406 .expect("json");
1407 assert!(
1408 raw.get("servers").is_none(),
1409 "preserve the original mcpServers spelling"
1410 );
1411 assert_eq!(raw["mcpServers"]["broken"]["enabled"], false);
1412 assert_eq!(raw["mcpServers"]["broken"]["disabled"], true);
1413 assert_eq!(
1414 raw["mcpServers"]["healthy"],
1415 serde_json::json!({"command":"node", "args":["server.js"]}),
1416 "healthy entry remains unchanged"
1417 );
1418 assert!(mcp::load_config(&mcp_path).unwrap().servers["healthy"].enabled);
1419 }
1420 }
1421
1421 lines RUST