| 1 | //! Structural, offline-by-default diagnostics shared by doctor renderers. |
| 2 | |
| 3 | use std::ffi::OsStr; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use anyhow::{Context, Result}; |
| 8 | use codewhale_release::InstallMethod; |
| 9 | use serde::Serialize; |
| 10 | |
| 11 | /// Canonical user-scoped paths reported by both human and JSON doctor output. |
| 12 | /// |
| 13 | /// Resolution is read-only: this type does not construct managers, create |
| 14 | /// directories, or trigger legacy migration. |
| 15 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 16 | pub(crate) struct DoctorPathReport { |
| 17 | pub(crate) home: PathBuf, |
| 18 | pub(crate) config: PathBuf, |
| 19 | pub(crate) settings: PathBuf, |
| 20 | pub(crate) sessions: PathBuf, |
| 21 | pub(crate) logs: PathBuf, |
| 22 | pub(crate) automations: PathBuf, |
| 23 | pub(crate) task_manager_root: PathBuf, |
| 24 | pub(crate) task_manager_tasks: PathBuf, |
| 25 | pub(crate) task_manager_artifacts: PathBuf, |
| 26 | pub(crate) runtime_store: PathBuf, |
| 27 | pub(crate) runtime_events: PathBuf, |
| 28 | pub(crate) personal_fleet_definitions: PathBuf, |
| 29 | pub(crate) personal_fleet_agents: PathBuf, |
| 30 | pub(crate) secrets: PathBuf, |
| 31 | } |
| 32 | |
| 33 | impl DoctorPathReport { |
| 34 | pub(crate) fn resolve(config_override: Option<&Path>) -> Result<Self> { |
| 35 | let home = codewhale_paths::codewhale_home() |
| 36 | .map_err(anyhow::Error::new)? |
| 37 | .context("could not resolve the canonical Codewhale state root")?; |
| 38 | let config = match config_override { |
| 39 | Some(path) => codewhale_config::resolve_config_path(Some(path.to_path_buf())) |
| 40 | .context("could not normalize the explicit config path")?, |
| 41 | None => codewhale_config::resolve_config_path(None) |
| 42 | .unwrap_or_else(|_| home.join(codewhale_config::CONFIG_FILE_NAME)), |
| 43 | }; |
| 44 | let settings = codewhale_runtime::settings::Settings::path() |
| 45 | .context("could not resolve the canonical settings path")?; |
| 46 | let sessions = codewhale_config::resolve_state_dir("sessions") |
| 47 | .context("could not resolve the sessions path")?; |
| 48 | let logs = codewhale_runtime::runtime_log::log_directory() |
| 49 | .context("could not resolve the runtime log directory")?; |
| 50 | let automations = codewhale_engine::automation_manager::default_automations_dir(); |
| 51 | let task_manager_root = codewhale_engine::task_manager::default_tasks_dir(); |
| 52 | let task_manager_tasks = task_manager_root.join("tasks"); |
| 53 | let task_manager_artifacts = task_manager_root.join("artifacts"); |
| 54 | let runtime_config = |
| 55 | codewhale_engine::runtime_threads::manager::RuntimeThreadManagerConfig::from_task_data_dir( |
| 56 | task_manager_root.clone(), |
| 57 | ); |
| 58 | let runtime_store = runtime_config.data_dir; |
| 59 | let runtime_events = runtime_store.join("events"); |
| 60 | let personal_fleet_definitions = |
| 61 | codewhale_engine::fleet::exact::personal_fleet_definitions_dir() |
| 62 | .context("could not resolve the personal Fleet definitions directory")?; |
| 63 | let personal_fleet_agents = codewhale_engine::fleet::profile::personal_agent_profile_dir() |
| 64 | .context("could not resolve the personal Fleet agent directory")?; |
| 65 | let (secrets, _) = codewhale_secrets::FileKeyringStore::default_paths_read_only() |
| 66 | .context("could not resolve the file secret backend path")?; |
| 67 | Ok(Self { |
| 68 | home, |
| 69 | config, |
| 70 | settings, |
| 71 | sessions, |
| 72 | logs, |
| 73 | automations, |
| 74 | task_manager_root, |
| 75 | task_manager_tasks, |
| 76 | task_manager_artifacts, |
| 77 | runtime_store, |
| 78 | runtime_events, |
| 79 | personal_fleet_definitions, |
| 80 | personal_fleet_agents, |
| 81 | secrets, |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | pub(crate) fn entries(&self) -> [(&'static str, &Path); 14] { |
| 86 | [ |
| 87 | ("home", self.home.as_path()), |
| 88 | ("config", self.config.as_path()), |
| 89 | ("settings", self.settings.as_path()), |
| 90 | ("sessions", self.sessions.as_path()), |
| 91 | ("logs", self.logs.as_path()), |
| 92 | ("automations", self.automations.as_path()), |
| 93 | ("task_manager_root", self.task_manager_root.as_path()), |
| 94 | ("task_manager_tasks", self.task_manager_tasks.as_path()), |
| 95 | ( |
| 96 | "task_manager_artifacts", |
| 97 | self.task_manager_artifacts.as_path(), |
| 98 | ), |
| 99 | ("runtime_store", self.runtime_store.as_path()), |
| 100 | ("runtime_events", self.runtime_events.as_path()), |
| 101 | ( |
| 102 | "personal_fleet_definitions", |
| 103 | self.personal_fleet_definitions.as_path(), |
| 104 | ), |
| 105 | ( |
| 106 | "personal_fleet_agents", |
| 107 | self.personal_fleet_agents.as_path(), |
| 108 | ), |
| 109 | ("secrets", self.secrets.as_path()), |
| 110 | ] |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 115 | pub(crate) struct SessionStoreCounts { |
| 116 | pub(crate) saved: usize, |
| 117 | pub(crate) checkpoints: usize, |
| 118 | } |
| 119 | |
| 120 | pub(crate) fn latest_session_route_line( |
| 121 | sessions: &Path, |
| 122 | configured_provider: &str, |
| 123 | configured_model: &str, |
| 124 | ) -> Option<String> { |
| 125 | let mut candidates: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(sessions) |
| 126 | .ok()? |
| 127 | .flatten() |
| 128 | .filter(|entry| { |
| 129 | let path = entry.path(); |
| 130 | path.extension().is_some_and(|ext| ext == "json") |
| 131 | && path |
| 132 | .file_stem() |
| 133 | .and_then(|stem| stem.to_str()) |
| 134 | .is_some_and(|stem| { |
| 135 | stem != "session_boot_owners" |
| 136 | && codewhale_runtime::artifacts::is_valid_session_id(stem) |
| 137 | }) |
| 138 | && entry.file_type().is_ok_and(|kind| kind.is_file()) |
| 139 | }) |
| 140 | .filter_map(|entry| Some((entry.metadata().ok()?.modified().ok()?, entry.path()))) |
| 141 | .collect(); |
| 142 | candidates.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1))); |
| 143 | |
| 144 | let metadata = candidates |
| 145 | .into_iter() |
| 146 | .take(32) |
| 147 | .filter_map(|(_, path)| { |
| 148 | codewhale_engine::session_manager::SessionManager::load_session_metadata(&path).ok() |
| 149 | }) |
| 150 | .filter(|meta| { |
| 151 | let provider = meta |
| 152 | .model_provider_id |
| 153 | .as_deref() |
| 154 | .unwrap_or(meta.model_provider.as_str()); |
| 155 | !provider.trim().is_empty() && !meta.model.trim().is_empty() |
| 156 | }) |
| 157 | .max_by_key(|meta| meta.updated_at)?; |
| 158 | |
| 159 | let clean = |value: &str| -> String { value.chars().filter(|ch| !ch.is_control()).collect() }; |
| 160 | let provider = clean( |
| 161 | metadata |
| 162 | .model_provider_id |
| 163 | .as_deref() |
| 164 | .unwrap_or(metadata.model_provider.as_str()), |
| 165 | ); |
| 166 | let model = clean(&metadata.model); |
| 167 | let short_id: String = clean(&metadata.id).chars().take(8).collect(); |
| 168 | let relation = if provider == configured_provider |
| 169 | && model.trim_start_matches("models/") == configured_model.trim_start_matches("models/") |
| 170 | { |
| 171 | "same as the configured default" |
| 172 | } else { |
| 173 | "differs from the configured default; each session keeps the route it ran with, and /provider or /model without saving as default changes only that session" |
| 174 | }; |
| 175 | Some(format!( |
| 176 | "most recent saved session route: {provider} / {model} (session {short_id}, updated {}; {relation})", |
| 177 | metadata.updated_at.format("%Y-%m-%d %H:%M UTC"), |
| 178 | )) |
| 179 | } |
| 180 | |
| 181 | pub(crate) fn session_store_counts(sessions: &Path) -> Result<Option<SessionStoreCounts>, String> { |
| 182 | let Some(manager) = |
| 183 | codewhale_engine::session_manager::SessionManager::open_read_only(sessions.to_path_buf()) |
| 184 | .map_err(|error| error.to_string())? |
| 185 | else { |
| 186 | return Ok(None); |
| 187 | }; |
| 188 | Ok(Some(SessionStoreCounts { |
| 189 | saved: manager |
| 190 | .saved_session_count() |
| 191 | .map_err(|error| error.to_string())?, |
| 192 | checkpoints: manager |
| 193 | .list_checkpoints() |
| 194 | .map_err(|error| error.to_string())? |
| 195 | .len(), |
| 196 | })) |
| 197 | } |
| 198 | |
| 199 | /// Render structural secret-backend facts for the human doctor report. |
| 200 | /// |
| 201 | /// The input type cannot carry secret values, keeping this renderer safe by |
| 202 | /// construction. |
| 203 | pub(crate) fn secret_backend_human_lines( |
| 204 | diagnostic: &codewhale_secrets::SecretBackendDiagnostic, |
| 205 | ) -> Vec<String> { |
| 206 | use codewhale_secrets::{ |
| 207 | SecretBackendDiagnosticKind, SecretBackendInspection, SecretBackendPresence, |
| 208 | }; |
| 209 | |
| 210 | let presence = |value| match value { |
| 211 | SecretBackendPresence::Present => "present", |
| 212 | SecretBackendPresence::Absent => "absent", |
| 213 | SecretBackendPresence::Unknown => "unknown", |
| 214 | }; |
| 215 | let inspection = match diagnostic.inspection { |
| 216 | SecretBackendInspection::MetadataOnly => "metadata_only", |
| 217 | SecretBackendInspection::NotProbed => "not_probed", |
| 218 | }; |
| 219 | let mut lines = match diagnostic.backend { |
| 220 | SecretBackendDiagnosticKind::File => vec![ |
| 221 | "backend: file".to_string(), |
| 222 | format!("presence: {} ({inspection})", presence(diagnostic.presence)), |
| 223 | ], |
| 224 | SecretBackendDiagnosticKind::System => vec![ |
| 225 | "backend: system".to_string(), |
| 226 | "status: unknown (not_probed)".to_string(), |
| 227 | ], |
| 228 | SecretBackendDiagnosticKind::Unknown => vec![ |
| 229 | "backend: unknown".to_string(), |
| 230 | "status: unknown (not_probed; unsupported configuration)".to_string(), |
| 231 | ], |
| 232 | }; |
| 233 | if let Some(path) = diagnostic.path.as_deref() { |
| 234 | lines.push(format!("path: {}", path.display())); |
| 235 | } |
| 236 | if let Some(path) = diagnostic.legacy_path.as_deref() { |
| 237 | lines.push(format!( |
| 238 | "legacy_path: {} ({}, {inspection})", |
| 239 | path.display(), |
| 240 | presence(diagnostic.legacy_presence) |
| 241 | )); |
| 242 | } |
| 243 | lines.push("No credential-store values were read or printed by this check.".to_string()); |
| 244 | lines |
| 245 | } |
| 246 | |
| 247 | /// Report key names — never values — for config entries whose value is |
| 248 | /// shaped like a bearer credential. `config.toml` is plain text, not a |
| 249 | /// secret store; doctor warns so tokens migrate to the secret backend |
| 250 | /// (morning-report issue: a plaintext OAuth token sat beside a `[redacted]` |
| 251 | /// sibling entry). |
| 252 | pub(crate) fn config_credential_shaped_keys(raw: &str) -> Vec<String> { |
| 253 | fn strong_shape(value: &str) -> bool { |
| 254 | const PREFIXES: [&str; 9] = [ |
| 255 | "sk-", |
| 256 | "sk_", |
| 257 | "xai-", |
| 258 | "ghp_", |
| 259 | "gho_", |
| 260 | "github_pat_", |
| 261 | "xoxb-", |
| 262 | "xoxp-", |
| 263 | "eyJ", |
| 264 | ]; |
| 265 | value.len() >= 20 && PREFIXES.iter().any(|prefix| value.starts_with(prefix)) |
| 266 | } |
| 267 | fn suspect_key(key: &str) -> bool { |
| 268 | if key == "oauth_credential_generation" { |
| 269 | return false; |
| 270 | } |
| 271 | let key = key.to_ascii_lowercase(); |
| 272 | [ |
| 273 | "token", |
| 274 | "secret", |
| 275 | "password", |
| 276 | "credential", |
| 277 | "api_key", |
| 278 | "apikey", |
| 279 | "access_key", |
| 280 | ] |
| 281 | .iter() |
| 282 | .any(|needle| key.contains(needle)) |
| 283 | } |
| 284 | fn random_shape(value: &str) -> bool { |
| 285 | value.len() >= 24 |
| 286 | && value |
| 287 | .chars() |
| 288 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')) |
| 289 | && value.chars().any(|ch| ch.is_ascii_digit()) |
| 290 | && value.chars().any(|ch| ch.is_ascii_alphabetic()) |
| 291 | } |
| 292 | |
| 293 | let mut flagged: Vec<String> = Vec::new(); |
| 294 | for line in raw.lines() { |
| 295 | let line = line.trim(); |
| 296 | if line.starts_with('#') { |
| 297 | continue; |
| 298 | } |
| 299 | let Some((key, value)) = line.split_once('=') else { |
| 300 | continue; |
| 301 | }; |
| 302 | let key = key.trim().trim_matches('"'); |
| 303 | let value = value.trim(); |
| 304 | let Some(value) = value |
| 305 | .strip_prefix('"') |
| 306 | .and_then(|value| value.strip_suffix('"')) |
| 307 | else { |
| 308 | continue; |
| 309 | }; |
| 310 | if value.is_empty() || value.eq_ignore_ascii_case("[redacted]") { |
| 311 | continue; |
| 312 | } |
| 313 | if (strong_shape(value) || (suspect_key(key) && random_shape(value))) |
| 314 | && !flagged.iter().any(|existing| existing == key) |
| 315 | { |
| 316 | flagged.push(key.to_string()); |
| 317 | } |
| 318 | } |
| 319 | flagged |
| 320 | } |
| 321 | |
| 322 | pub(crate) fn active_env_override_names() -> Vec<String> { |
| 323 | active_env_override_names_from(std::env::vars_os()) |
| 324 | } |
| 325 | |
| 326 | pub(crate) fn active_env_override_names_from<I, K, V>(vars: I) -> Vec<String> |
| 327 | where |
| 328 | I: IntoIterator<Item = (K, V)>, |
| 329 | K: AsRef<OsStr>, |
| 330 | V: AsRef<OsStr>, |
| 331 | { |
| 332 | let mut names: Vec<String> = vars |
| 333 | .into_iter() |
| 334 | .filter_map(|(key, value)| { |
| 335 | let key = key.as_ref().to_str()?; |
| 336 | let matches_prefix = (key.starts_with("CODEWHALE_") && key.len() > "CODEWHALE_".len()) |
| 337 | || (key.starts_with("DEEPSEEK_") && key.len() > "DEEPSEEK_".len()); |
| 338 | if !matches_prefix { |
| 339 | return None; |
| 340 | } |
| 341 | let value = value.as_ref(); |
| 342 | let non_blank = value |
| 343 | .to_str() |
| 344 | .map_or(!value.is_empty(), |raw| !raw.trim().is_empty()); |
| 345 | non_blank.then(|| key.to_string()) |
| 346 | }) |
| 347 | .collect(); |
| 348 | names.sort(); |
| 349 | names.dedup(); |
| 350 | names |
| 351 | } |
| 352 | |
| 353 | pub(crate) fn env_override_human_line(names: &[String]) -> Option<String> { |
| 354 | (!names.is_empty()).then(|| format!("active env overrides (names only): {}", names.join(", "))) |
| 355 | } |
| 356 | |
| 357 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 358 | pub(crate) struct DoctorPermissionWarning { |
| 359 | pub(crate) rule_index: usize, |
| 360 | pub(crate) tool: String, |
| 361 | pub(crate) message: String, |
| 362 | } |
| 363 | |
| 364 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 365 | pub(crate) struct DoctorPermissionsReport { |
| 366 | pub(crate) path: PathBuf, |
| 367 | pub(crate) present: bool, |
| 368 | pub(crate) rule_count: usize, |
| 369 | pub(crate) warnings: Vec<DoctorPermissionWarning>, |
| 370 | #[serde(skip_serializing_if = "Option::is_none")] |
| 371 | pub(crate) error: Option<String>, |
| 372 | } |
| 373 | |
| 374 | impl DoctorPermissionsReport { |
| 375 | pub(crate) fn inspect(config_path: &Path) -> Self { |
| 376 | match codewhale_config::load_permissions_snapshot(Some(config_path.to_path_buf())) { |
| 377 | Ok(snapshot) => Self { |
| 378 | path: snapshot.path().to_path_buf(), |
| 379 | present: snapshot.file_exists(), |
| 380 | rule_count: snapshot.rules().len(), |
| 381 | warnings: snapshot |
| 382 | .warnings() |
| 383 | .iter() |
| 384 | .map(|warning| DoctorPermissionWarning { |
| 385 | rule_index: warning.rule_index + 1, |
| 386 | tool: warning.tool.clone(), |
| 387 | message: warning.message.clone(), |
| 388 | }) |
| 389 | .collect(), |
| 390 | error: None, |
| 391 | }, |
| 392 | Err(error) => { |
| 393 | let path = codewhale_config::permissions_path_for_config_path(config_path); |
| 394 | let present = path.exists(); |
| 395 | Self { |
| 396 | path, |
| 397 | present, |
| 398 | rule_count: 0, |
| 399 | warnings: Vec::new(), |
| 400 | error: Some(format!("{error:#}")), |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | pub(crate) fn permissions_human_lines(report: &DoctorPermissionsReport) -> Vec<String> { |
| 408 | if let Some(error) = &report.error { |
| 409 | return vec![format!("permissions.toml could not be read: {error}")]; |
| 410 | } |
| 411 | report |
| 412 | .warnings |
| 413 | .iter() |
| 414 | .map(|warning| { |
| 415 | format!( |
| 416 | "permissions.toml rule #{} ({}): {}", |
| 417 | warning.rule_index, warning.tool, warning.message |
| 418 | ) |
| 419 | }) |
| 420 | .collect() |
| 421 | } |
| 422 | |
| 423 | pub(crate) fn permissions_short_attention(report: &DoctorPermissionsReport) -> Option<String> { |
| 424 | if let Some(error) = &report.error { |
| 425 | return Some(format!("permissions.toml could not be read: {error}")); |
| 426 | } |
| 427 | (!report.warnings.is_empty()).then(|| { |
| 428 | format!( |
| 429 | "permissions.toml has {} unreachable rule(s): `codewhale doctor --full` or `/permissions` shows them", |
| 430 | report.warnings.len() |
| 431 | ) |
| 432 | }) |
| 433 | } |
| 434 | |
| 435 | /// Explicit live operations requested for one doctor invocation. |
| 436 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 437 | pub(crate) struct DoctorProbeRequest { |
| 438 | pub(crate) check_updates: bool, |
| 439 | pub(crate) probe_api: bool, |
| 440 | pub(crate) probe_local: bool, |
| 441 | pub(crate) probe_mcp: bool, |
| 442 | pub(crate) probe_search: bool, |
| 443 | } |
| 444 | |
| 445 | impl DoctorProbeRequest { |
| 446 | /// Whether a release service may be contacted. |
| 447 | pub(crate) fn should_check_updates(self) -> bool { |
| 448 | self.check_updates |
| 449 | } |
| 450 | |
| 451 | /// Whether the configured provider endpoint may be contacted. |
| 452 | /// |
| 453 | /// Hosted and local endpoints have separate opt-ins because a local probe |
| 454 | /// can wake a desktop-managed daemon. |
| 455 | pub(crate) fn should_probe_api(self, endpoint_is_local: bool) -> bool { |
| 456 | if endpoint_is_local { |
| 457 | self.probe_local |
| 458 | } else { |
| 459 | self.probe_api |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | /// Whether configured MCP processes may be started and contacted. |
| 464 | pub(crate) fn should_probe_mcp(self) -> bool { |
| 465 | self.probe_mcp |
| 466 | } |
| 467 | |
| 468 | /// Whether the selected web-search provider authority may be contacted. |
| 469 | pub(crate) fn should_probe_search(self) -> bool { |
| 470 | self.probe_search |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | const SEARCH_PROBE_TIMEOUT: Duration = Duration::from_secs(5); |
| 475 | |
| 476 | /// Bounded, credential-free reachability result for the configured search |
| 477 | /// provider. This intentionally cannot represent a successful search or valid |
| 478 | /// authentication: a HEAD response proves transport reachability only. |
| 479 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 480 | pub(crate) enum DoctorSearchProbeReport { |
| 481 | NotChecked, |
| 482 | FeatureDisabled, |
| 483 | ConfigurationError(codewhale_engine::tools::web_search::SearchProbeTargetError), |
| 484 | PolicyDenied { |
| 485 | authority: String, |
| 486 | }, |
| 487 | PolicyApprovalRequired { |
| 488 | authority: String, |
| 489 | }, |
| 490 | Reachable { |
| 491 | authority: String, |
| 492 | status: u16, |
| 493 | }, |
| 494 | Unreachable { |
| 495 | authority: String, |
| 496 | failure: DoctorSearchProbeFailure, |
| 497 | }, |
| 498 | } |
| 499 | |
| 500 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 501 | pub(crate) enum DoctorSearchProbeFailure { |
| 502 | Timeout, |
| 503 | Connection, |
| 504 | Request, |
| 505 | } |
| 506 | |
| 507 | /// Probe the selected search provider without reading credentials, issuing a |
| 508 | /// query, following redirects, or writing a network-policy audit receipt. |
| 509 | pub(crate) async fn doctor_search_probe( |
| 510 | config: &codewhale_runtime::config::Config, |
| 511 | probes: DoctorProbeRequest, |
| 512 | ) -> DoctorSearchProbeReport { |
| 513 | use codewhale_net::network_policy::{Decision, NetworkPolicyDecider}; |
| 514 | |
| 515 | if !probes.should_probe_search() { |
| 516 | return DoctorSearchProbeReport::NotChecked; |
| 517 | } |
| 518 | if !config |
| 519 | .features() |
| 520 | .enabled(codewhale_runtime::features::Feature::WebSearch) |
| 521 | { |
| 522 | return DoctorSearchProbeReport::FeatureDisabled; |
| 523 | } |
| 524 | |
| 525 | let provider = config.search_provider(); |
| 526 | let base_url = config |
| 527 | .search |
| 528 | .as_ref() |
| 529 | .and_then(|search| search.base_url.as_deref()); |
| 530 | let target = match codewhale_engine::tools::web_search::search_probe_target(provider, base_url) |
| 531 | { |
| 532 | Ok(target) => target, |
| 533 | Err(error) => return DoctorSearchProbeReport::ConfigurationError(error), |
| 534 | }; |
| 535 | let authority = codewhale_config::structural_url_authority(target.url.as_str()); |
| 536 | |
| 537 | if let Some(policy) = config.network.clone().map(|network| { |
| 538 | // Doctor is a read-only diagnostic. Evaluate the same typed policy as |
| 539 | // web_search, but do not attach the runtime audit writer. |
| 540 | NetworkPolicyDecider::new( |
| 541 | codewhale_net::network_policy::NetworkPolicy::from(network), |
| 542 | None, |
| 543 | ) |
| 544 | }) { |
| 545 | match policy.evaluate(&target.host, "web_search") { |
| 546 | Decision::Allow => {} |
| 547 | Decision::Deny => return DoctorSearchProbeReport::PolicyDenied { authority }, |
| 548 | Decision::Prompt => { |
| 549 | return DoctorSearchProbeReport::PolicyApprovalRequired { authority }; |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | let client = match codewhale_release::tls::reqwest_client_builder() |
| 555 | .redirect(reqwest::redirect::Policy::none()) |
| 556 | .connect_timeout(SEARCH_PROBE_TIMEOUT) |
| 557 | .timeout(SEARCH_PROBE_TIMEOUT) |
| 558 | .user_agent(concat!("codewhale-doctor/", env!("CARGO_PKG_VERSION"))) |
| 559 | .build() |
| 560 | { |
| 561 | Ok(client) => client, |
| 562 | Err(_) => { |
| 563 | return DoctorSearchProbeReport::Unreachable { |
| 564 | authority, |
| 565 | failure: DoctorSearchProbeFailure::Request, |
| 566 | }; |
| 567 | } |
| 568 | }; |
| 569 | |
| 570 | match client.head(target.url).send().await { |
| 571 | Ok(response) => DoctorSearchProbeReport::Reachable { |
| 572 | authority, |
| 573 | status: response.status().as_u16(), |
| 574 | }, |
| 575 | Err(error) => { |
| 576 | let failure = if error.is_timeout() { |
| 577 | DoctorSearchProbeFailure::Timeout |
| 578 | } else if error.is_connect() { |
| 579 | DoctorSearchProbeFailure::Connection |
| 580 | } else { |
| 581 | DoctorSearchProbeFailure::Request |
| 582 | }; |
| 583 | DoctorSearchProbeReport::Unreachable { authority, failure } |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | /// Plain, bounded doctor copy for a search reachability result. |
| 589 | pub(crate) fn doctor_search_probe_lines(report: &DoctorSearchProbeReport) -> Vec<String> { |
| 590 | use codewhale_engine::tools::web_search::SearchProbeTargetError; |
| 591 | |
| 592 | match report { |
| 593 | DoctorSearchProbeReport::NotChecked => vec![ |
| 594 | "· not checked (offline default)".to_string(), |
| 595 | "Run `codewhale doctor --probe-search` to test the selected provider authority." |
| 596 | .to_string(), |
| 597 | ], |
| 598 | DoctorSearchProbeReport::FeatureDisabled => vec![ |
| 599 | "· not checked because the web_search feature is disabled".to_string(), |
| 600 | "Enable web_search before probing its provider.".to_string(), |
| 601 | ], |
| 602 | DoctorSearchProbeReport::ConfigurationError(error) => { |
| 603 | let detail = match error { |
| 604 | SearchProbeTargetError::Missing => { |
| 605 | "SearXNG requires an explicit [search] base_url" |
| 606 | } |
| 607 | SearchProbeTargetError::Unsupported => { |
| 608 | "[search] base_url is supported only for DuckDuckGo-compatible or SearXNG providers" |
| 609 | } |
| 610 | SearchProbeTargetError::Invalid => { |
| 611 | "the configured [search] base_url is not a valid HTTP(S) authority" |
| 612 | } |
| 613 | }; |
| 614 | vec![format!("! not probed: {detail}")] |
| 615 | } |
| 616 | DoctorSearchProbeReport::PolicyDenied { authority } => vec![ |
| 617 | format!("! {authority} blocked by configured network policy"), |
| 618 | "The same policy blocks web_search; update /network only if this authority should be allowed." |
| 619 | .to_string(), |
| 620 | ], |
| 621 | DoctorSearchProbeReport::PolicyApprovalRequired { authority } => vec![ |
| 622 | format!("! {authority} requires network approval"), |
| 623 | "Allow the authority with /network, then rerun this probe.".to_string(), |
| 624 | ], |
| 625 | DoctorSearchProbeReport::Reachable { authority, status } => vec![ |
| 626 | format!("✓ {authority} responded (HTTP {status})"), |
| 627 | "Transport only; authentication and search results were not tested.".to_string(), |
| 628 | ], |
| 629 | DoctorSearchProbeReport::Unreachable { authority, failure } => { |
| 630 | let detail = match failure { |
| 631 | DoctorSearchProbeFailure::Timeout => "timed out", |
| 632 | DoctorSearchProbeFailure::Connection => "connection, DNS, or TLS setup failed", |
| 633 | DoctorSearchProbeFailure::Request => "request failed", |
| 634 | }; |
| 635 | vec![ |
| 636 | format!("✗ {authority} {detail}"), |
| 637 | "No search API key or query was sent; provider error details were omitted." |
| 638 | .to_string(), |
| 639 | ] |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 645 | enum DoctorUpdateReport { |
| 646 | NotChecked, |
| 647 | UpdateAvailable { latest: String }, |
| 648 | UpToDate { latest: String }, |
| 649 | CurrentNewer { latest: String }, |
| 650 | ReleaseMetadataInvalid, |
| 651 | ReleaseCheckFailed, |
| 652 | } |
| 653 | |
| 654 | fn doctor_update_report<E>( |
| 655 | current_version: &str, |
| 656 | latest_result: Result<String, E>, |
| 657 | ) -> DoctorUpdateReport { |
| 658 | let Ok(raw_latest) = latest_result else { |
| 659 | return DoctorUpdateReport::ReleaseCheckFailed; |
| 660 | }; |
| 661 | let Some(latest) = doctor_safe_release_tag(&raw_latest) else { |
| 662 | return DoctorUpdateReport::ReleaseMetadataInvalid; |
| 663 | }; |
| 664 | match codewhale_release::compare_release_versions(current_version, &latest) { |
| 665 | Ok(std::cmp::Ordering::Less) => DoctorUpdateReport::UpdateAvailable { latest }, |
| 666 | Ok(std::cmp::Ordering::Equal) => DoctorUpdateReport::UpToDate { latest }, |
| 667 | Ok(std::cmp::Ordering::Greater) => DoctorUpdateReport::CurrentNewer { latest }, |
| 668 | Err(_) => DoctorUpdateReport::ReleaseMetadataInvalid, |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | /// Canonicalize a release tag before any doctor renderer sees it. A release |
| 673 | /// server response is untrusted input: it may not become an error echo or a |
| 674 | /// terminal control sequence merely because the user opted into an update |
| 675 | /// check. |
| 676 | fn doctor_safe_release_tag(raw: &str) -> Option<String> { |
| 677 | let version = raw.trim().strip_prefix('v').unwrap_or(raw.trim()); |
| 678 | semver::Version::parse(version) |
| 679 | .ok() |
| 680 | .map(|version| format!("v{version}")) |
| 681 | } |
| 682 | |
| 683 | /// `update_command` is the install-method-aware upgrade command |
| 684 | /// ([`codewhale_release::InstallMethod::update_command`]): an npm, Homebrew, |
| 685 | /// cargo or Omarchy install must be upgraded by its package manager, never by |
| 686 | /// `codewhale update`, which refuses to replace a managed binary. |
| 687 | fn doctor_update_report_lines(report: &DoctorUpdateReport, update_command: &str) -> Vec<String> { |
| 688 | match report { |
| 689 | DoctorUpdateReport::NotChecked => vec![ |
| 690 | "latest: unknown (not checked; offline default)".to_string(), |
| 691 | "Run `codewhale doctor --check-updates` to opt in.".to_string(), |
| 692 | ], |
| 693 | DoctorUpdateReport::UpdateAvailable { latest } => vec![ |
| 694 | format!("latest: {latest}"), |
| 695 | format!("Update available. Run `{update_command}` to install."), |
| 696 | ], |
| 697 | DoctorUpdateReport::UpToDate { latest } => { |
| 698 | vec![ |
| 699 | format!("latest: {latest}"), |
| 700 | "Already up to date.".to_string(), |
| 701 | ] |
| 702 | } |
| 703 | DoctorUpdateReport::CurrentNewer { latest } => vec![ |
| 704 | format!("latest: {latest}"), |
| 705 | "Current build is newer than the latest published release.".to_string(), |
| 706 | ], |
| 707 | DoctorUpdateReport::ReleaseMetadataInvalid => vec![ |
| 708 | "latest: unknown (release metadata invalid; details omitted)".to_string(), |
| 709 | "Run `codewhale update --check` to retry.".to_string(), |
| 710 | ], |
| 711 | DoctorUpdateReport::ReleaseCheckFailed => vec![ |
| 712 | "latest: unknown (release check failed; details omitted)".to_string(), |
| 713 | "Run `codewhale update --check` to retry.".to_string(), |
| 714 | ], |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | /// Print the update portion of the human doctor report. |
| 719 | /// |
| 720 | /// The release service is contacted only when `--check-updates` populated the |
| 721 | /// explicit request bit. The default branch returns before constructing an |
| 722 | /// HTTP request. Failure details are deliberately typed and generic because |
| 723 | /// transport errors and release metadata are untrusted strings. |
| 724 | pub(crate) async fn print_update_report( |
| 725 | probes: DoctorProbeRequest, |
| 726 | update: &codewhale_runtime::config::UpdateConfig, |
| 727 | ) { |
| 728 | let current_version = env!("CARGO_PKG_VERSION"); |
| 729 | println!(" · current: v{current_version}"); |
| 730 | for line in update_mode_lines(update) { |
| 731 | println!(" · {line}"); |
| 732 | } |
| 733 | let cached = (!probes.should_check_updates()) |
| 734 | .then(codewhale_config::codewhale_home) |
| 735 | .and_then(Result::ok) |
| 736 | .and_then(|home| { |
| 737 | codewhale_release::UpdateCheckCache::load(&codewhale_release::check::cache_path_in( |
| 738 | &home, |
| 739 | )) |
| 740 | }) |
| 741 | .and_then(|entry| entry.latest_tag); |
| 742 | let report = if probes.should_check_updates() { |
| 743 | doctor_update_report( |
| 744 | current_version, |
| 745 | codewhale_release::latest_release_tag_async(codewhale_release::ReleaseChannel::Stable) |
| 746 | .await, |
| 747 | ) |
| 748 | } else if let Some(tag) = cached.as_deref() { |
| 749 | doctor_update_report(current_version, Ok::<_, ()>(tag.to_string())) |
| 750 | } else { |
| 751 | DoctorUpdateReport::NotChecked |
| 752 | }; |
| 753 | let update_command = std::env::current_exe().map_or_else( |
| 754 | |_| "codewhale update".to_string(), |
| 755 | |exe| { |
| 756 | codewhale_release::installs::manager_update_command(InstallMethod::detect(&exe), &exe) |
| 757 | }, |
| 758 | ); |
| 759 | for (index, line) in doctor_update_report_lines(&report, &update_command) |
| 760 | .into_iter() |
| 761 | .enumerate() |
| 762 | { |
| 763 | let indent = if index == 0 { " ·" } else { " " }; |
| 764 | println!("{indent} {line}"); |
| 765 | } |
| 766 | if cached.is_some() { |
| 767 | println!( |
| 768 | " (latest is from the last automatic check; `codewhale doctor --check-updates` asks again)" |
| 769 | ); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | pub(crate) fn is_keyless_ds4_route(config: &codewhale_runtime::config::Config) -> bool { |
| 774 | config |
| 775 | .provider |
| 776 | .as_deref() |
| 777 | .is_some_and(|provider| provider.eq_ignore_ascii_case("ds4")) |
| 778 | && codewhale_runtime::config::base_url_uses_local_host(&config.active_route_base_url()) |
| 779 | && codewhale_config::auth_mode_disables_api_key( |
| 780 | config |
| 781 | .active_provider_identity() |
| 782 | .ok() |
| 783 | .and_then(|identity| config.auth_mode_for_provider(&identity)) |
| 784 | .as_deref(), |
| 785 | ) |
| 786 | } |
| 787 | |
| 788 | /// Probe DS4 through its cheap `/v1/models` contract instead of waking the |
| 789 | /// model for a completion. The selected model must be advertised. |
| 790 | pub(crate) async fn probe_ds4_models( |
| 791 | config: &codewhale_runtime::config::Config, |
| 792 | ) -> anyhow::Result<()> { |
| 793 | use codewhale_engine::client::CodewhaleClient; |
| 794 | use codewhale_engine::core::model_client::ModelClient; |
| 795 | |
| 796 | let endpoint = |
| 797 | codewhale_sanitize::sanitize::redact_url_for_display(&config.active_route_base_url()); |
| 798 | let client = CodewhaleClient::new(config)?; |
| 799 | let configured_alias = client.model().to_string(); |
| 800 | let models = match tokio::time::timeout( |
| 801 | std::time::Duration::from_secs(15), |
| 802 | client.list_models(), |
| 803 | ) |
| 804 | .await |
| 805 | { |
| 806 | Ok(Ok(models)) => models, |
| 807 | Ok(Err(error)) => anyhow::bail!(ds4_probe_error(config, &error.to_string())), |
| 808 | Err(_) => anyhow::bail!("DS4 /v1/models timed out after 15 seconds at {}", endpoint), |
| 809 | }; |
| 810 | if !models |
| 811 | .iter() |
| 812 | .any(|available| available.id == configured_alias) |
| 813 | { |
| 814 | let advertised = models |
| 815 | .iter() |
| 816 | .take(8) |
| 817 | .map(|available| available.id.as_str()) |
| 818 | .collect::<Vec<_>>() |
| 819 | .join(", "); |
| 820 | anyhow::bail!( |
| 821 | "DS4 /v1/models at {} did not list configured alias '{configured_alias}' (advertised: {})", |
| 822 | endpoint, |
| 823 | if advertised.is_empty() { |
| 824 | "none" |
| 825 | } else { |
| 826 | advertised.as_str() |
| 827 | } |
| 828 | ); |
| 829 | } |
| 830 | Ok(()) |
| 831 | } |
| 832 | |
| 833 | fn ds4_probe_error(config: &codewhale_runtime::config::Config, error: &str) -> String { |
| 834 | let endpoint = |
| 835 | codewhale_sanitize::sanitize::redact_url_for_display(&config.active_route_base_url()); |
| 836 | let status = error |
| 837 | .split_whitespace() |
| 838 | .collect::<Vec<_>>() |
| 839 | .windows(2) |
| 840 | .find_map(|pair| { |
| 841 | (pair[0].eq_ignore_ascii_case("HTTP") |
| 842 | && pair[1].trim_matches(|ch: char| !ch.is_ascii_digit()).len() == 3) |
| 843 | .then(|| { |
| 844 | pair[1] |
| 845 | .trim_matches(|ch: char| !ch.is_ascii_digit()) |
| 846 | .to_string() |
| 847 | }) |
| 848 | }); |
| 849 | match status { |
| 850 | Some(status) => format!("DS4 /v1/models returned HTTP {status} at {}", endpoint), |
| 851 | None => format!( |
| 852 | "DS4 /v1/models could not be reached at {} (is ds4-server running?)", |
| 853 | endpoint |
| 854 | ), |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 859 | pub(crate) enum DoctorDetail { |
| 860 | Short, |
| 861 | Full, |
| 862 | All, |
| 863 | } |
| 864 | |
| 865 | impl DoctorDetail { |
| 866 | pub(crate) fn from_flags(full: bool, all: bool, needs_sections: bool) -> Self { |
| 867 | if all { |
| 868 | Self::All |
| 869 | } else if full || needs_sections { |
| 870 | Self::Full |
| 871 | } else { |
| 872 | Self::Short |
| 873 | } |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 878 | pub(crate) enum DoctorShortCheck { |
| 879 | Works(String), |
| 880 | Note(String), |
| 881 | NeedsAttention(String), |
| 882 | } |
| 883 | |
| 884 | const SHORT_REPORT_READY_STEP: &str = "Run `codewhale` in the folder you want to work in."; |
| 885 | const SHORT_REPORT_DETAIL_STEP: &str = "Run `codewhale doctor --full` to see every check."; |
| 886 | pub(crate) const SHORT_REPORT_FOOTER: &str = "`codewhale doctor --full` prints every check."; |
| 887 | |
| 888 | pub(crate) fn short_report_lines(verdict: &str, checks: &[DoctorShortCheck]) -> Vec<String> { |
| 889 | let (head, step) = match verdict.split_once(" → ") { |
| 890 | Some((head, step)) => (head.trim(), Some(step.trim())), |
| 891 | None => (verdict.trim(), None), |
| 892 | }; |
| 893 | let mut lines = vec![if head.ends_with(['.', '!', '?']) { |
| 894 | head.to_string() |
| 895 | } else { |
| 896 | format!("{head}.") |
| 897 | }]; |
| 898 | lines.push(String::new()); |
| 899 | lines.push("Works:".to_string()); |
| 900 | let before = lines.len(); |
| 901 | for check in checks { |
| 902 | match check { |
| 903 | DoctorShortCheck::Works(text) => lines.push(format!(" ✓ {text}")), |
| 904 | DoctorShortCheck::Note(text) => lines.push(format!(" · {text}")), |
| 905 | DoctorShortCheck::NeedsAttention(_) => {} |
| 906 | } |
| 907 | } |
| 908 | if lines.len() == before { |
| 909 | lines.push(" nothing was confirmed".to_string()); |
| 910 | } |
| 911 | lines.push("Needs attention:".to_string()); |
| 912 | let before = lines.len(); |
| 913 | for check in checks { |
| 914 | if let DoctorShortCheck::NeedsAttention(text) = check { |
| 915 | lines.push(format!(" ! {text}")); |
| 916 | } |
| 917 | } |
| 918 | if lines.len() == before { |
| 919 | lines.push(" nothing".to_string()); |
| 920 | } |
| 921 | lines.push("Next step:".to_string()); |
| 922 | let step = match step { |
| 923 | Some(step) => { |
| 924 | let step = step |
| 925 | .replace("see API Connectivity below; ", "") |
| 926 | .replace("; see API Connectivity below", ""); |
| 927 | let mut chars = step.chars(); |
| 928 | match chars.next() { |
| 929 | Some(first) => first.to_uppercase().chain(chars).collect(), |
| 930 | None => SHORT_REPORT_DETAIL_STEP.to_string(), |
| 931 | } |
| 932 | } |
| 933 | None if head.starts_with("Ready") => SHORT_REPORT_READY_STEP.to_string(), |
| 934 | None => SHORT_REPORT_DETAIL_STEP.to_string(), |
| 935 | }; |
| 936 | lines.push(format!(" {step}")); |
| 937 | lines.push(String::new()); |
| 938 | lines.push(SHORT_REPORT_FOOTER.to_string()); |
| 939 | lines |
| 940 | } |
| 941 | |
| 942 | #[cfg(test)] |
| 943 | #[path = "doctor/tests.rs"] |
| 944 | mod tests; |
| 945 | |
| 946 | pub(crate) fn update_mode_lines(update: &codewhale_runtime::config::UpdateConfig) -> Vec<String> { |
| 947 | use codewhale_release::autoupdate; |
| 948 | let exe = std::env::current_exe().unwrap_or_default(); |
| 949 | let method = InstallMethod::detect(&exe); |
| 950 | let resolved = autoupdate::resolve_mode(update.mode.as_deref(), update.check_for_updates); |
| 951 | let mut lines = vec![codewhale_release::installs::update_answer(method, &exe)]; |
| 952 | if method.supports_self_update() { |
| 953 | lines.push(format!("automatic updates: {}", resolved.describe())); |
| 954 | } |
| 955 | if let Ok(home) = codewhale_config::codewhale_home() { |
| 956 | if let Some(staged) = autoupdate::load_staged(&home) { |
| 957 | lines.push(format!( |
| 958 | "staged: v{} ({}){}", |
| 959 | staged.version, |
| 960 | if staged.signed { |
| 961 | "signed; applies at next start" |
| 962 | } else { |
| 963 | "checksum verified; waits for your OK" |
| 964 | }, |
| 965 | if staged.declined { |
| 966 | "; you declined it, run `codewhale update` to install" |
| 967 | } else { |
| 968 | "" |
| 969 | } |
| 970 | )); |
| 971 | } |
| 972 | if let Some(previous) = autoupdate::load_previous(&home) { |
| 973 | lines.push( |
| 974 | match autoupdate::rollback_blocker(&previous.version, env!("CARGO_PKG_VERSION")) { |
| 975 | None => format!( |
| 976 | "rollback: v{} is kept (`codewhale update --rollback`)", |
| 977 | previous.version |
| 978 | ), |
| 979 | Some(blocker) => { |
| 980 | format!("rollback: v{} is kept, but {blocker}", previous.version) |
| 981 | } |
| 982 | }, |
| 983 | ); |
| 984 | } |
| 985 | let state = autoupdate::load_state(&home); |
| 986 | if let Some(skip) = state.skip_version { |
| 987 | lines.push(format!( |
| 988 | "skipped: v{skip} was rolled back and is not reinstalled automatically" |
| 989 | )); |
| 990 | } |
| 991 | if let Some(reason) = state.last_failure { |
| 992 | lines.push(format!( |
| 993 | "last automatic update failed: {reason}. Run `codewhale update` to retry and see the full error." |
| 994 | )); |
| 995 | } |
| 996 | } |
| 997 | lines |
| 998 | } |
| 999 | |
| 1000 | pub(crate) fn installation_lines(brief: bool) -> Vec<String> { |
| 1001 | let mut lines = install_summary_lines(brief); |
| 1002 | lines.extend(recovery_lines()); |
| 1003 | lines |
| 1004 | } |
| 1005 | |
| 1006 | pub(crate) fn install_summary_lines(brief: bool) -> Vec<String> { |
| 1007 | let running = std::env::current_exe().ok(); |
| 1008 | let inventory = codewhale_release::installs::inventory(running.as_deref()); |
| 1009 | inventory.summary_lines(brief, env!("CARGO_PKG_VERSION")) |
| 1010 | } |
| 1011 | |
| 1012 | pub(crate) fn recovery_lines() -> Vec<String> { |
| 1013 | let mut lines = Vec::new(); |
| 1014 | if let Ok(home) = codewhale_config::codewhale_home() { |
| 1015 | let now = codewhale_release::check::now_unix(); |
| 1016 | for folder in codewhale_release::installs::recovery_folders(&home) { |
| 1017 | if folder.records.is_empty() { |
| 1018 | continue; |
| 1019 | } |
| 1020 | lines.push(format!( |
| 1021 | "Recovery {}: {} item(s), {}, deleted in {} day(s). Undo: codewhale doctor --restore {}", |
| 1022 | folder.stamp, |
| 1023 | folder.records.len(), |
| 1024 | codewhale_release::installs::human_bytes(folder.bytes()), |
| 1025 | folder.expires_in_days(now).unwrap_or(0), |
| 1026 | folder.stamp |
| 1027 | )); |
| 1028 | } |
| 1029 | } |
| 1030 | lines |
| 1031 | } |
| 1032 | |
| 1033 | /// `update` is set for the installers' brief report, so their closing lines |
| 1034 | /// come from the installed binary's own update state rather than a guess. |
| 1035 | pub(crate) fn run_installs_report( |
| 1036 | json: bool, |
| 1037 | brief: bool, |
| 1038 | update: Option<&codewhale_runtime::config::UpdateConfig>, |
| 1039 | ) -> Result<()> { |
| 1040 | if !json { |
| 1041 | for line in installation_lines(brief) { |
| 1042 | println!("{line}"); |
| 1043 | } |
| 1044 | // The installers already print the update command with its full path. |
| 1045 | if let Some(update) = update { |
| 1046 | for line in update_mode_lines(update).into_iter().skip(1) { |
| 1047 | println!("{line}"); |
| 1048 | } |
| 1049 | println!("Change it with: codewhale config set update.mode auto|notify|off"); |
| 1050 | } |
| 1051 | return Ok(()); |
| 1052 | } |
| 1053 | let running = std::env::current_exe().ok(); |
| 1054 | let inventory = codewhale_release::installs::inventory(running.as_deref()); |
| 1055 | let rows: Vec<_> = inventory |
| 1056 | .entries |
| 1057 | .iter() |
| 1058 | .map(|entry| { |
| 1059 | serde_json::json!({ |
| 1060 | "path": entry.path, |
| 1061 | "class": entry.class.label(), |
| 1062 | "reason": match &entry.class { |
| 1063 | codewhale_release::installs::InstallClass::NotOurs(reason) => Some(*reason), |
| 1064 | _ => None, |
| 1065 | }, |
| 1066 | "owner": match &entry.class { |
| 1067 | codewhale_release::installs::InstallClass::PackageManaged(method) => Some(method.label()), |
| 1068 | _ => None, |
| 1069 | }, |
| 1070 | "owner_command": entry.owner_command(), |
| 1071 | "is_dir": entry.is_dir, |
| 1072 | "bytes": entry.bytes, |
| 1073 | "active": entry.active, |
| 1074 | "running": Some(entry.path.as_path()) == running.as_deref(), |
| 1075 | "same_as_running": entry.same_as_running, |
| 1076 | }) |
| 1077 | }) |
| 1078 | .collect(); |
| 1079 | let recovery: Vec<_> = codewhale_config::codewhale_home() |
| 1080 | .map(|home| codewhale_release::installs::recovery_folders(&home)) |
| 1081 | .unwrap_or_default() |
| 1082 | .into_iter() |
| 1083 | .map(|folder| { |
| 1084 | serde_json::json!({ |
| 1085 | "stamp": folder.stamp, |
| 1086 | "path": folder.dir, |
| 1087 | "items": folder.records.len(), |
| 1088 | "bytes": folder.bytes(), |
| 1089 | "expires_in_days": folder.expires_in_days(codewhale_release::check::now_unix()), |
| 1090 | }) |
| 1091 | }) |
| 1092 | .collect(); |
| 1093 | println!( |
| 1094 | "{}", |
| 1095 | serde_json::to_string_pretty(&serde_json::json!({ |
| 1096 | "version": env!("CARGO_PKG_VERSION"), |
| 1097 | "installations": rows, |
| 1098 | "leftover_bytes": inventory.leftover_bytes(), |
| 1099 | "summary": inventory.summary_lines(brief, env!("CARGO_PKG_VERSION")), |
| 1100 | "recovery": recovery, |
| 1101 | }))? |
| 1102 | ); |
| 1103 | Ok(()) |
| 1104 | } |
| 1105 | |
| 1106 | pub(crate) fn run_restore(stamp: &str) -> Result<()> { |
| 1107 | let home = codewhale_config::codewhale_home()?; |
| 1108 | let stamp = (stamp != "latest").then_some(stamp); |
| 1109 | let (stamp, report) = codewhale_release::installs::restore(&home, stamp)?; |
| 1110 | for path in &report.restored { |
| 1111 | println!("Restored {}", path.display()); |
| 1112 | } |
| 1113 | for (path, reason) in &report.skipped { |
| 1114 | println!("Kept in recovery: {} ({reason})", path.display()); |
| 1115 | } |
| 1116 | if let Some(displaced) = &report.displaced { |
| 1117 | println!( |
| 1118 | "The files that were in those places are kept in recovery {displaced}. Undo: codewhale doctor --restore {displaced}" |
| 1119 | ); |
| 1120 | } |
| 1121 | println!( |
| 1122 | "Restored {} of {} item(s) from recovery {stamp}.", |
| 1123 | report.restored.len(), |
| 1124 | report.restored.len() + report.skipped.len() |
| 1125 | ); |
| 1126 | if !report.skipped.is_empty() { |
| 1127 | anyhow::bail!("some items could not be restored; they stay in the recovery folder"); |
| 1128 | } |
| 1129 | Ok(()) |
| 1130 | } |
| 1131 |