| 1 | use super::*; |
| 2 | |
| 3 | #[test] |
| 4 | fn default_probe_request_is_fully_offline() { |
| 5 | let request = DoctorProbeRequest::default(); |
| 6 | assert!(!request.should_check_updates()); |
| 7 | assert!(!request.should_probe_api(false)); |
| 8 | assert!(!request.should_probe_api(true)); |
| 9 | assert!(!request.should_probe_mcp()); |
| 10 | assert!(!request.should_probe_search()); |
| 11 | } |
| 12 | |
| 13 | fn ds4_config() -> codewhale_runtime::config::Config { |
| 14 | let mut providers = codewhale_runtime::config::ProvidersConfig::default(); |
| 15 | providers.custom.insert( |
| 16 | "ds4".to_string(), |
| 17 | codewhale_runtime::config::ProviderConfig { |
| 18 | kind: Some("openai-compatible".to_string()), |
| 19 | base_url: Some("http://127.0.0.1:8000/v1".to_string()), |
| 20 | model: Some("deepseek-v4-flash".to_string()), |
| 21 | auth_mode: Some("none".to_string()), |
| 22 | ..Default::default() |
| 23 | }, |
| 24 | ); |
| 25 | { |
| 26 | let __cw_config_init_0_0 = Some("ds4".to_string()); |
| 27 | let __cw_config_init_0_1 = Some(providers); |
| 28 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = Default::default(); |
| 29 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 30 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 31 | __cw_config_init_0_value |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[test] |
| 36 | fn recognizes_only_the_explicit_keyless_local_ds4_route() { |
| 37 | let ds4 = ds4_config(); |
| 38 | assert!(is_keyless_ds4_route(&ds4)); |
| 39 | |
| 40 | let mut hosted = ds4.clone(); |
| 41 | hosted |
| 42 | .providers |
| 43 | .as_mut() |
| 44 | .and_then(|providers| providers.custom.get_mut("ds4")) |
| 45 | .expect("DS4 config") |
| 46 | .base_url = Some("https://ds4.example/v1".to_string()); |
| 47 | assert!(!is_keyless_ds4_route(&hosted)); |
| 48 | } |
| 49 | |
| 50 | #[test] |
| 51 | fn ds4_probe_error_reports_status_without_response_body() { |
| 52 | let mut config = ds4_config(); |
| 53 | config |
| 54 | .providers |
| 55 | .as_mut() |
| 56 | .and_then(|providers| providers.custom.get_mut("ds4")) |
| 57 | .expect("DS4 config") |
| 58 | .base_url = Some("http://user:secret@127.0.0.1:8000/v1?token=secret".to_string()); |
| 59 | let message = ds4_probe_error( |
| 60 | &config, |
| 61 | "Failed to list models: HTTP 404: secret backend response", |
| 62 | ); |
| 63 | |
| 64 | assert!(message.contains("HTTP 404")); |
| 65 | assert!(!message.contains("secret backend response")); |
| 66 | assert!(!message.contains("secret")); |
| 67 | } |
| 68 | |
| 69 | #[test] |
| 70 | fn update_renderer_omits_untrusted_release_tags_and_errors() { |
| 71 | let release_sentinel = "v9.9.9?token=doctor-update-sentinel"; |
| 72 | let error_sentinel = "https://user:doctor-update-error-sentinel@example.test/path"; |
| 73 | |
| 74 | let metadata = doctor_update_report("0.9.3", Ok::<String, ()>(release_sentinel.to_string())); |
| 75 | let transport = doctor_update_report("0.9.3", Err(error_sentinel.to_string())); |
| 76 | let rendered = [ |
| 77 | doctor_update_report_lines(&metadata, "codewhale update").join("\n"), |
| 78 | doctor_update_report_lines(&transport, "codewhale update").join("\n"), |
| 79 | ] |
| 80 | .join("\n"); |
| 81 | |
| 82 | assert_eq!(metadata, DoctorUpdateReport::ReleaseMetadataInvalid); |
| 83 | assert_eq!(transport, DoctorUpdateReport::ReleaseCheckFailed); |
| 84 | assert!(!rendered.contains(release_sentinel)); |
| 85 | assert!(!rendered.contains(error_sentinel)); |
| 86 | assert!(rendered.contains("details omitted")); |
| 87 | } |
| 88 | |
| 89 | #[test] |
| 90 | fn update_renderer_canonicalizes_safe_release_tags() { |
| 91 | let report = doctor_update_report("0.9.3", Ok::<String, ()>(" v0.9.4 ".to_string())); |
| 92 | assert_eq!( |
| 93 | doctor_update_report_lines(&report, "codewhale update"), |
| 94 | vec![ |
| 95 | "latest: v0.9.4".to_string(), |
| 96 | "Update available. Run `codewhale update` to install.".to_string(), |
| 97 | ] |
| 98 | ); |
| 99 | } |
| 100 | |
| 101 | #[test] |
| 102 | fn update_renderer_names_the_package_manager_for_managed_installs() { |
| 103 | let report = doctor_update_report("0.9.3", Ok::<String, ()>("v0.9.4".to_string())); |
| 104 | let npm = codewhale_release::InstallMethod::Npm.update_command(); |
| 105 | let lines = doctor_update_report_lines(&report, npm); |
| 106 | assert_eq!( |
| 107 | lines[1], |
| 108 | "Update available. Run `npm install -g codewhale@latest` to install." |
| 109 | ); |
| 110 | assert!( |
| 111 | !lines.join("\n").contains("`codewhale update`"), |
| 112 | "an npm-owned binary must not be told to self-update: {lines:?}" |
| 113 | ); |
| 114 | } |
| 115 | |
| 116 | #[test] |
| 117 | fn live_probe_flags_open_only_their_owned_boundary() { |
| 118 | let update = DoctorProbeRequest { |
| 119 | check_updates: true, |
| 120 | ..DoctorProbeRequest::default() |
| 121 | }; |
| 122 | assert!(update.should_check_updates()); |
| 123 | assert!(!update.should_probe_api(false)); |
| 124 | assert!(!update.should_probe_api(true)); |
| 125 | |
| 126 | let hosted = DoctorProbeRequest { |
| 127 | probe_api: true, |
| 128 | ..DoctorProbeRequest::default() |
| 129 | }; |
| 130 | assert!(hosted.should_probe_api(false)); |
| 131 | assert!(!hosted.should_probe_api(true)); |
| 132 | |
| 133 | let local = DoctorProbeRequest { |
| 134 | probe_local: true, |
| 135 | ..DoctorProbeRequest::default() |
| 136 | }; |
| 137 | assert!(!local.should_probe_api(false)); |
| 138 | assert!(local.should_probe_api(true)); |
| 139 | |
| 140 | let search = DoctorProbeRequest { |
| 141 | probe_search: true, |
| 142 | ..DoctorProbeRequest::default() |
| 143 | }; |
| 144 | assert!(search.should_probe_search()); |
| 145 | assert!(!search.should_check_updates()); |
| 146 | assert!(!search.should_probe_api(false)); |
| 147 | assert!(!search.should_probe_mcp()); |
| 148 | } |
| 149 | |
| 150 | #[tokio::test] |
| 151 | async fn search_probe_counts_any_http_response_as_transport_only() { |
| 152 | use wiremock::matchers::{method, path}; |
| 153 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 154 | |
| 155 | let server = MockServer::start().await; |
| 156 | Mock::given(method("HEAD")) |
| 157 | .and(path("/")) |
| 158 | .respond_with(ResponseTemplate::new(401)) |
| 159 | .expect(1) |
| 160 | .mount(&server) |
| 161 | .await; |
| 162 | let config = { |
| 163 | let __cw_config_init_1_0 = Some(codewhale_runtime::config::SearchConfig { |
| 164 | provider: Some(codewhale_runtime::config::SearchProvider::DuckDuckGo), |
| 165 | base_url: Some(server.uri()), |
| 166 | api_key: None, |
| 167 | native: None, |
| 168 | third_party: None, |
| 169 | }); |
| 170 | let mut __cw_config_init_1_value: codewhale_runtime::config::Config = Default::default(); |
| 171 | __cw_config_init_1_value.search = __cw_config_init_1_0; |
| 172 | __cw_config_init_1_value |
| 173 | }; |
| 174 | |
| 175 | let report = doctor_search_probe( |
| 176 | &config, |
| 177 | DoctorProbeRequest { |
| 178 | probe_search: true, |
| 179 | ..DoctorProbeRequest::default() |
| 180 | }, |
| 181 | ) |
| 182 | .await; |
| 183 | let lines = doctor_search_probe_lines(&report).join("\n"); |
| 184 | |
| 185 | assert!(matches!( |
| 186 | report, |
| 187 | DoctorSearchProbeReport::Reachable { status: 401, .. } |
| 188 | )); |
| 189 | assert!(lines.contains("responded (HTTP 401)"), "{lines}"); |
| 190 | assert!(lines.contains("Transport only"), "{lines}"); |
| 191 | assert!(lines.contains("authentication and search results were not tested")); |
| 192 | assert!(!lines.contains("search successful")); |
| 193 | let requests = server.received_requests().await.expect("recorded probe"); |
| 194 | assert_eq!(requests.len(), 1); |
| 195 | assert!(requests[0].url.query().is_none()); |
| 196 | assert!(requests[0].body.is_empty()); |
| 197 | assert!(requests[0].headers.get("authorization").is_none()); |
| 198 | assert!(requests[0].headers.get("x-api-key").is_none()); |
| 199 | assert!(requests[0].headers.get("cookie").is_none()); |
| 200 | } |
| 201 | |
| 202 | #[tokio::test] |
| 203 | async fn search_probe_does_not_follow_redirects() { |
| 204 | use wiremock::matchers::{method, path}; |
| 205 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 206 | |
| 207 | let server = MockServer::start().await; |
| 208 | Mock::given(method("HEAD")) |
| 209 | .and(path("/")) |
| 210 | .respond_with(ResponseTemplate::new(302).insert_header("Location", "/redirected")) |
| 211 | .expect(1) |
| 212 | .mount(&server) |
| 213 | .await; |
| 214 | Mock::given(method("HEAD")) |
| 215 | .and(path("/redirected")) |
| 216 | .respond_with(ResponseTemplate::new(200)) |
| 217 | .expect(0) |
| 218 | .mount(&server) |
| 219 | .await; |
| 220 | let config = { |
| 221 | let __cw_config_init_2_0 = Some(codewhale_runtime::config::SearchConfig { |
| 222 | provider: Some(codewhale_runtime::config::SearchProvider::Searxng), |
| 223 | base_url: Some(server.uri()), |
| 224 | api_key: None, |
| 225 | native: None, |
| 226 | third_party: None, |
| 227 | }); |
| 228 | let mut __cw_config_init_2_value: codewhale_runtime::config::Config = Default::default(); |
| 229 | __cw_config_init_2_value.search = __cw_config_init_2_0; |
| 230 | __cw_config_init_2_value |
| 231 | }; |
| 232 | |
| 233 | let report = doctor_search_probe( |
| 234 | &config, |
| 235 | DoctorProbeRequest { |
| 236 | probe_search: true, |
| 237 | ..DoctorProbeRequest::default() |
| 238 | }, |
| 239 | ) |
| 240 | .await; |
| 241 | |
| 242 | assert!(matches!( |
| 243 | report, |
| 244 | DoctorSearchProbeReport::Reachable { status: 302, .. } |
| 245 | )); |
| 246 | } |
| 247 | |
| 248 | #[tokio::test] |
| 249 | async fn search_probe_respects_network_policy_without_contacting_the_authority() { |
| 250 | let config = { |
| 251 | let __cw_config_init_3_0 = Some(codewhale_runtime::config::SearchConfig { |
| 252 | provider: Some(codewhale_runtime::config::SearchProvider::Searxng), |
| 253 | base_url: Some("https://search.example/private?token=secret".to_string()), |
| 254 | api_key: None, |
| 255 | native: None, |
| 256 | third_party: None, |
| 257 | }); |
| 258 | let __cw_config_init_3_1 = Some(codewhale_config::NetworkPolicyToml { |
| 259 | default: "allow".to_string(), |
| 260 | deny: vec!["search.example".to_string()], |
| 261 | ..Default::default() |
| 262 | }); |
| 263 | let mut __cw_config_init_3_value: codewhale_runtime::config::Config = Default::default(); |
| 264 | __cw_config_init_3_value.search = __cw_config_init_3_0; |
| 265 | __cw_config_init_3_value.network = __cw_config_init_3_1; |
| 266 | __cw_config_init_3_value |
| 267 | }; |
| 268 | |
| 269 | let report = doctor_search_probe( |
| 270 | &config, |
| 271 | DoctorProbeRequest { |
| 272 | probe_search: true, |
| 273 | ..DoctorProbeRequest::default() |
| 274 | }, |
| 275 | ) |
| 276 | .await; |
| 277 | let lines = doctor_search_probe_lines(&report).join("\n"); |
| 278 | |
| 279 | assert_eq!( |
| 280 | report, |
| 281 | DoctorSearchProbeReport::PolicyDenied { |
| 282 | authority: "https://search.example".to_string() |
| 283 | } |
| 284 | ); |
| 285 | assert!(!lines.contains("private")); |
| 286 | assert!(!lines.contains("token")); |
| 287 | assert!(!lines.contains("secret")); |
| 288 | } |
| 289 | |
| 290 | #[tokio::test] |
| 291 | async fn search_probe_skips_the_default_provider_when_web_search_is_disabled() { |
| 292 | let mut config = codewhale_runtime::config::Config::default(); |
| 293 | config |
| 294 | .set_feature("web_search", false) |
| 295 | .expect("known feature"); |
| 296 | |
| 297 | let report = doctor_search_probe( |
| 298 | &config, |
| 299 | DoctorProbeRequest { |
| 300 | probe_search: true, |
| 301 | ..DoctorProbeRequest::default() |
| 302 | }, |
| 303 | ) |
| 304 | .await; |
| 305 | |
| 306 | assert_eq!(report, DoctorSearchProbeReport::FeatureDisabled); |
| 307 | assert!( |
| 308 | doctor_search_probe_lines(&report) |
| 309 | .join("\n") |
| 310 | .contains("web_search feature is disabled") |
| 311 | ); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn explicit_codewhale_home_owns_every_default_user_path() { |
| 316 | let _lock = crate::test_support::lock_test_env(); |
| 317 | let temp = tempfile::tempdir().expect("temp home"); |
| 318 | let home = temp.path().join("isolated-codewhale-home"); |
| 319 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 320 | let _config = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 321 | let _legacy_config = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 322 | let _automations = crate::test_support::EnvVarGuard::remove("CODEWHALE_AUTOMATIONS_DIR"); |
| 323 | let _legacy_automations = crate::test_support::EnvVarGuard::remove("DEEPSEEK_AUTOMATIONS_DIR"); |
| 324 | let _tasks = crate::test_support::EnvVarGuard::remove("CODEWHALE_TASKS_DIR"); |
| 325 | let _legacy_tasks = crate::test_support::EnvVarGuard::remove("DEEPSEEK_TASKS_DIR"); |
| 326 | let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR"); |
| 327 | let _legacy_runtime = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR"); |
| 328 | |
| 329 | let report = DoctorPathReport::resolve(None).expect("resolve doctor paths"); |
| 330 | let task_manager_root = codewhale_engine::task_manager::default_tasks_dir(); |
| 331 | let runtime_config = |
| 332 | codewhale_engine::runtime_threads::manager::RuntimeThreadManagerConfig::from_task_data_dir( |
| 333 | task_manager_root.clone(), |
| 334 | ); |
| 335 | let (secrets, legacy_secrets) = |
| 336 | codewhale_secrets::FileKeyringStore::default_paths_read_only().expect("secret paths"); |
| 337 | |
| 338 | assert_eq!(report.home, home); |
| 339 | assert_eq!(report.config, home.join("config.toml")); |
| 340 | assert_eq!(report.settings, home.join("settings.toml")); |
| 341 | assert_eq!(report.sessions, home.join("sessions")); |
| 342 | assert_eq!(report.logs, home.join("logs")); |
| 343 | assert_eq!(report.automations, home.join("automations")); |
| 344 | assert_eq!(report.task_manager_root, task_manager_root); |
| 345 | assert_eq!(report.task_manager_tasks, task_manager_root.join("tasks")); |
| 346 | assert_eq!( |
| 347 | report.task_manager_artifacts, |
| 348 | task_manager_root.join("artifacts") |
| 349 | ); |
| 350 | assert_eq!(report.runtime_store, runtime_config.data_dir); |
| 351 | assert_eq!( |
| 352 | report.runtime_events, |
| 353 | runtime_config.data_dir.join("events") |
| 354 | ); |
| 355 | assert_eq!( |
| 356 | report.personal_fleet_definitions, |
| 357 | codewhale_engine::fleet::exact::personal_fleet_definitions_dir().expect("personal fleets") |
| 358 | ); |
| 359 | assert_eq!( |
| 360 | report.personal_fleet_agents, |
| 361 | codewhale_engine::fleet::profile::personal_agent_profile_dir().expect("personal agents") |
| 362 | ); |
| 363 | assert_eq!(report.secrets, secrets); |
| 364 | assert_eq!(legacy_secrets, None); |
| 365 | assert_eq!(report.entries().len(), 14); |
| 366 | let json = serde_json::to_value(&report).expect("serialize path snapshot"); |
| 367 | for (label, path) in report.entries() { |
| 368 | assert_eq!( |
| 369 | json[label].as_str(), |
| 370 | Some(path.to_string_lossy().as_ref()), |
| 371 | "human and JSON path snapshots diverged for {label}" |
| 372 | ); |
| 373 | } |
| 374 | assert!( |
| 375 | !home.exists(), |
| 376 | "path reporting must not create the configured home" |
| 377 | ); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn explicit_relative_config_matches_the_canonical_loader_path() { |
| 382 | let relative = Path::new("fixtures/relative-doctor-config.toml"); |
| 383 | let expected = codewhale_config::resolve_config_path(Some(relative.to_path_buf())) |
| 384 | .expect("canonical config path"); |
| 385 | |
| 386 | let report = DoctorPathReport::resolve(Some(relative)).expect("resolve doctor paths"); |
| 387 | |
| 388 | assert_eq!(report.config, expected); |
| 389 | assert!(report.config.is_absolute()); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn path_report_json_contains_no_secret_file_contents() { |
| 394 | let _lock = crate::test_support::lock_test_env(); |
| 395 | let temp = tempfile::tempdir().expect("temp home"); |
| 396 | let home = temp.path().join("isolated-codewhale-home"); |
| 397 | let secret_path = home.join("secrets").join("secrets.json"); |
| 398 | std::fs::create_dir_all(secret_path.parent().unwrap()).expect("secret dir fixture"); |
| 399 | let sentinel = "doctor-path-report-secret-sentinel"; |
| 400 | std::fs::write(&secret_path, sentinel).expect("secret fixture"); |
| 401 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 402 | |
| 403 | let report = DoctorPathReport::resolve(None).expect("resolve doctor paths"); |
| 404 | let json = serde_json::to_string(&report).expect("serialize path report"); |
| 405 | |
| 406 | assert!(!json.contains(sentinel)); |
| 407 | assert_eq!(std::fs::read_to_string(secret_path).unwrap(), sentinel); |
| 408 | } |
| 409 | |
| 410 | #[test] |
| 411 | fn human_and_json_backend_reports_never_include_secret_file_contents() { |
| 412 | let _lock = crate::test_support::lock_test_env(); |
| 413 | let temp = tempfile::tempdir().expect("temp home"); |
| 414 | let home = temp.path().join("isolated-codewhale-home"); |
| 415 | let secret_path = home.join("secrets").join("secrets.json"); |
| 416 | std::fs::create_dir_all(secret_path.parent().unwrap()).expect("secret dir fixture"); |
| 417 | let sentinel = "doctor-render-secret-sentinel"; |
| 418 | std::fs::write(&secret_path, format!("not-json:{sentinel}")).expect("secret fixture"); |
| 419 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 420 | let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 421 | |
| 422 | let diagnostic = codewhale_secrets::diagnose_secret_backend(); |
| 423 | let human = secret_backend_human_lines(&diagnostic).join("\n"); |
| 424 | let json = serde_json::to_string(&diagnostic).expect("serialize backend diagnostic"); |
| 425 | |
| 426 | assert!(!human.contains(sentinel)); |
| 427 | assert!(!json.contains(sentinel)); |
| 428 | assert_eq!( |
| 429 | std::fs::read_to_string(secret_path).unwrap(), |
| 430 | format!("not-json:{sentinel}") |
| 431 | ); |
| 432 | } |
| 433 | |
| 434 | #[test] |
| 435 | fn structural_url_authority_omits_every_secret_capable_component() { |
| 436 | let sentinels = [ |
| 437 | "URL-USER-SENTINEL", |
| 438 | "URL-PASSWORD-SENTINEL", |
| 439 | "URL-PATH-SENTINEL", |
| 440 | "URL-QUERY-KEY-SENTINEL", |
| 441 | "URL-QUERY-VALUE-SENTINEL", |
| 442 | "URL-FRAGMENT-SENTINEL", |
| 443 | ]; |
| 444 | let raw = format!( |
| 445 | "https://{}:{}@example.invalid:8443/{}/child?{}={}#{}", |
| 446 | sentinels[0], sentinels[1], sentinels[2], sentinels[3], sentinels[4], sentinels[5] |
| 447 | ); |
| 448 | |
| 449 | let authority = codewhale_config::structural_url_authority(&raw); |
| 450 | |
| 451 | assert_eq!(authority, "https://example.invalid:8443"); |
| 452 | for sentinel in sentinels { |
| 453 | assert!(!authority.contains(sentinel)); |
| 454 | } |
| 455 | assert_eq!( |
| 456 | codewhale_config::structural_url_authority("http://[::1]:9000/private?token=review-secret"), |
| 457 | "http://[::1]:9000" |
| 458 | ); |
| 459 | } |
| 460 | |
| 461 | #[test] |
| 462 | fn credential_shaped_config_values_are_flagged_by_key_name_only() { |
| 463 | // Fixture tokens stay low-entropy on purpose: realistic random strings |
| 464 | // trip secret scanners (GitGuardian flagged the originals as live credentials). |
| 465 | let raw = r#" |
| 466 | # comment with sk-not-a-real-line |
| 467 | model = "deepseek-v4-flash" |
| 468 | base_url = "https://api.moonshot.ai/kimi-code/v1" |
| 469 | chatgpt_access_token = "eyJ0000000000000000000000000" |
| 470 | moonshot_api_key = "[redacted]" |
| 471 | provider_api_key = "sk-test0000000000000000" |
| 472 | workspace_token_note = "short" |
| 473 | random_id = "0123456789abcdef0123456789abcdef" |
| 474 | "#; |
| 475 | let flagged = super::config_credential_shaped_keys(raw); |
| 476 | assert_eq!(flagged, vec!["chatgpt_access_token", "provider_api_key"]); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn credential_scan_ignores_urls_models_and_redacted_entries() { |
| 481 | let raw = r#" |
| 482 | model = "kimi-k3-instruct-preview-2026" |
| 483 | endpoint = "https://example.com/v1?key=nope" |
| 484 | api_key = "[redacted]" |
| 485 | "#; |
| 486 | assert!(super::config_credential_shaped_keys(raw).is_empty()); |
| 487 | } |
| 488 | |
| 489 | #[test] |
| 490 | fn latest_session_route_ignores_boot_owners_and_oversized_files() { |
| 491 | use codewhale_engine::session_manager::{SessionManager, create_saved_session}; |
| 492 | use codewhale_models::{ContentBlock, Message, Role}; |
| 493 | |
| 494 | let dir = tempfile::tempdir().expect("tempdir"); |
| 495 | let workspace = dir.path().join("ws"); |
| 496 | std::fs::create_dir_all(&workspace).expect("workspace"); |
| 497 | let sessions = dir.path().join("sessions"); |
| 498 | let manager = SessionManager::new(sessions.clone()).expect("session manager"); |
| 499 | let msg = Message { |
| 500 | role: Role::User, |
| 501 | content: vec![ContentBlock::Text { |
| 502 | text: "hi".to_string(), |
| 503 | cache_control: None, |
| 504 | }], |
| 505 | }; |
| 506 | let mut session = create_saved_session(&[msg], "deepseek-flash", &workspace, 0, None); |
| 507 | session.metadata.model_provider_id = Some("google".to_string()); |
| 508 | session.metadata.model = "gemini-4-hydrogen".to_string(); |
| 509 | let saved_id = session.metadata.id.clone(); |
| 510 | manager.save_session(&session).expect("save session"); |
| 511 | |
| 512 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 513 | std::fs::write( |
| 514 | sessions.join("session_boot_owners.json"), |
| 515 | format!("{{\"{saved_id}\": \"owner-1\"}}\n"), |
| 516 | ) |
| 517 | .expect("write boot owners"); |
| 518 | std::fs::write( |
| 519 | sessions.join("corrupt-newest.json"), |
| 520 | "not valid session json", |
| 521 | ) |
| 522 | .expect("write corrupt"); |
| 523 | |
| 524 | let line = super::latest_session_route_line(&sessions, "deepseek", "deepseek-flash") |
| 525 | .expect("latest session route line"); |
| 526 | assert!(line.contains("google / gemini-4-hydrogen"), "{line}"); |
| 527 | assert!( |
| 528 | line.contains("differs from the configured default"), |
| 529 | "{line}" |
| 530 | ); |
| 531 | assert!( |
| 532 | !line.contains("because that session switched with /provider"), |
| 533 | "{line}" |
| 534 | ); |
| 535 | } |
| 536 | |
| 537 | #[test] |
| 538 | fn doctor_detail_is_short_unless_a_flag_needs_the_sections() { |
| 539 | assert_eq!( |
| 540 | DoctorDetail::from_flags(false, false, false), |
| 541 | DoctorDetail::Short |
| 542 | ); |
| 543 | assert_eq!( |
| 544 | DoctorDetail::from_flags(true, false, false), |
| 545 | DoctorDetail::Full |
| 546 | ); |
| 547 | assert_eq!( |
| 548 | DoctorDetail::from_flags(false, false, true), |
| 549 | DoctorDetail::Full |
| 550 | ); |
| 551 | assert_eq!( |
| 552 | DoctorDetail::from_flags(false, true, false), |
| 553 | DoctorDetail::All |
| 554 | ); |
| 555 | assert_eq!( |
| 556 | DoctorDetail::from_flags(true, true, true), |
| 557 | DoctorDetail::All |
| 558 | ); |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn short_report_splits_the_verdict_from_its_next_step() { |
| 563 | let lines = short_report_lines( |
| 564 | "Not ready: the deepseek route has no verified key → save one with /provider in Codewhale.", |
| 565 | &[ |
| 566 | DoctorShortCheck::Works("Codewhale 0.10.5 is installed".to_string()), |
| 567 | DoctorShortCheck::NeedsAttention("Model deepseek / deepseek-v4-flash".to_string()), |
| 568 | DoctorShortCheck::Note("No settings file yet".to_string()), |
| 569 | ], |
| 570 | ); |
| 571 | assert_eq!( |
| 572 | lines, |
| 573 | vec![ |
| 574 | "Not ready: the deepseek route has no verified key.".to_string(), |
| 575 | String::new(), |
| 576 | "Works:".to_string(), |
| 577 | " ✓ Codewhale 0.10.5 is installed".to_string(), |
| 578 | " · No settings file yet".to_string(), |
| 579 | "Needs attention:".to_string(), |
| 580 | " ! Model deepseek / deepseek-v4-flash".to_string(), |
| 581 | "Next step:".to_string(), |
| 582 | " Save one with /provider in Codewhale.".to_string(), |
| 583 | String::new(), |
| 584 | SHORT_REPORT_FOOTER.to_string(), |
| 585 | ] |
| 586 | ); |
| 587 | } |
| 588 | |
| 589 | #[test] |
| 590 | fn short_report_for_a_ready_setup_says_nothing_needs_attention() { |
| 591 | let lines = short_report_lines( |
| 592 | "Ready: setup is complete.", |
| 593 | &[DoctorShortCheck::Works("Model deepseek".to_string())], |
| 594 | ); |
| 595 | assert_eq!(lines[0], "Ready: setup is complete."); |
| 596 | let attention = lines |
| 597 | .iter() |
| 598 | .position(|line| line == "Needs attention:") |
| 599 | .expect("attention heading"); |
| 600 | assert_eq!(lines[attention + 1], " nothing"); |
| 601 | assert_eq!(lines[attention + 3], format!(" {SHORT_REPORT_READY_STEP}")); |
| 602 | assert!( |
| 603 | lines.len() <= 14, |
| 604 | "short report grew to {} lines", |
| 605 | lines.len() |
| 606 | ); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn short_report_does_not_point_at_a_section_it_does_not_print() { |
| 611 | let lines = short_report_lines( |
| 612 | "Not ready: the live deepseek API check failed → see API Connectivity below; `codewhale auth set --provider deepseek` replaces a rejected key.", |
| 613 | &[], |
| 614 | ); |
| 615 | assert!(lines.iter().all(|line| !line.contains("below"))); |
| 616 | assert!(lines.contains( |
| 617 | &" `codewhale auth set --provider deepseek` replaces a rejected key.".to_string() |
| 618 | )); |
| 619 | assert!(lines.contains(&" nothing was confirmed".to_string())); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn active_env_overrides_reports_sorted_names_without_values() { |
| 624 | let secret_sentinel = "doctor-env-override-secret-sentinel"; |
| 625 | let route_sentinel = "doctor-env-route-sentinel"; |
| 626 | let names = active_env_override_names_from([ |
| 627 | ("DEEPSEEK_MODEL", route_sentinel), |
| 628 | ("CODEWHALE_API_KEY", secret_sentinel), |
| 629 | ("CODEWHALE_PROVIDER", "deepseek"), |
| 630 | ("CODEWHALE_BLANK", " "), |
| 631 | ("DEEPSEEK_EMPTY", ""), |
| 632 | ("CODEWHALE_", "ignored"), |
| 633 | ("DEEPSEEK_", "ignored"), |
| 634 | ("OPENAI_API_KEY", secret_sentinel), |
| 635 | ("PATH", "/usr/bin"), |
| 636 | ]); |
| 637 | |
| 638 | assert_eq!( |
| 639 | names, |
| 640 | vec![ |
| 641 | "CODEWHALE_API_KEY".to_string(), |
| 642 | "CODEWHALE_PROVIDER".to_string(), |
| 643 | "DEEPSEEK_MODEL".to_string(), |
| 644 | ] |
| 645 | ); |
| 646 | let human = env_override_human_line(&names).expect("human line"); |
| 647 | let json = serde_json::to_string(&names).expect("serialize env overrides"); |
| 648 | assert!(human.contains("CODEWHALE_API_KEY, CODEWHALE_PROVIDER, DEEPSEEK_MODEL")); |
| 649 | assert!(!human.contains(secret_sentinel)); |
| 650 | assert!(!human.contains(route_sentinel)); |
| 651 | assert!(!json.contains(secret_sentinel)); |
| 652 | assert!(!json.contains(route_sentinel)); |
| 653 | assert_eq!(env_override_human_line(&[]), None); |
| 654 | } |
| 655 | |
| 656 | #[test] |
| 657 | fn active_env_overrides_reads_live_process_env_without_leaking_values() { |
| 658 | let _lock = crate::test_support::lock_test_env(); |
| 659 | let sentinel = "doctor-live-env-secret-sentinel"; |
| 660 | let _cw = crate::test_support::EnvVarGuard::set("CODEWHALE_TEST_DOCTOR_OVERRIDE", sentinel); |
| 661 | let _ds = crate::test_support::EnvVarGuard::set("DEEPSEEK_TEST_DOCTOR_OVERRIDE", sentinel); |
| 662 | let _blank = crate::test_support::EnvVarGuard::set("CODEWHALE_TEST_DOCTOR_BLANK", " "); |
| 663 | |
| 664 | let names = active_env_override_names(); |
| 665 | let human = env_override_human_line(&names).expect("human line"); |
| 666 | |
| 667 | assert!(names.contains(&"CODEWHALE_TEST_DOCTOR_OVERRIDE".to_string())); |
| 668 | assert!(names.contains(&"DEEPSEEK_TEST_DOCTOR_OVERRIDE".to_string())); |
| 669 | assert!(!names.contains(&"CODEWHALE_TEST_DOCTOR_BLANK".to_string())); |
| 670 | assert!(names.windows(2).all(|pair| pair[0] < pair[1])); |
| 671 | assert!(!human.contains(sentinel)); |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn permissions_report_surfaces_unreachable_rule_warnings() { |
| 676 | let dir = tempfile::tempdir().expect("tempdir"); |
| 677 | let config_path = dir.path().join("config.toml"); |
| 678 | let permissions_path = dir.path().join("permissions.toml"); |
| 679 | std::fs::write( |
| 680 | &permissions_path, |
| 681 | r#" |
| 682 | [[rules]] |
| 683 | action = "allow" |
| 684 | tool = "write" |
| 685 | |
| 686 | [[rules]] |
| 687 | action = "allow" |
| 688 | tool = "bash" |
| 689 | path = "src/**" |
| 690 | |
| 691 | [[rules]] |
| 692 | action = "allow" |
| 693 | tool = "read_file" |
| 694 | path = "src/**" |
| 695 | "#, |
| 696 | ) |
| 697 | .expect("write permissions"); |
| 698 | |
| 699 | let report = DoctorPermissionsReport::inspect(&config_path); |
| 700 | |
| 701 | assert_eq!( |
| 702 | report.path.canonicalize().expect("canonical report path"), |
| 703 | permissions_path |
| 704 | .canonicalize() |
| 705 | .expect("canonical permissions path") |
| 706 | ); |
| 707 | assert!(report.present); |
| 708 | assert_eq!(report.rule_count, 3); |
| 709 | assert_eq!(report.error, None); |
| 710 | assert_eq!(report.warnings.len(), 2); |
| 711 | assert_eq!(report.warnings[0].rule_index, 1); |
| 712 | assert_eq!(report.warnings[0].tool, "write"); |
| 713 | assert!( |
| 714 | report.warnings[0].message.contains("write_file"), |
| 715 | "{}", |
| 716 | report.warnings[0].message |
| 717 | ); |
| 718 | assert_eq!(report.warnings[1].rule_index, 2); |
| 719 | assert_eq!(report.warnings[1].tool, "bash"); |
| 720 | assert!( |
| 721 | report.warnings[1].message.contains("bash"), |
| 722 | "{}", |
| 723 | report.warnings[1].message |
| 724 | ); |
| 725 | |
| 726 | let human = permissions_human_lines(&report).join("\n"); |
| 727 | assert!(human.contains("rule #1 (write)"), "{human}"); |
| 728 | assert!(human.contains("rule #2 (bash)"), "{human}"); |
| 729 | let attention = permissions_short_attention(&report).expect("short attention"); |
| 730 | assert!(attention.contains("2 unreachable rule(s)"), "{attention}"); |
| 731 | |
| 732 | let json = serde_json::to_value(&report).expect("serialize permissions report"); |
| 733 | assert_eq!(json["present"], true); |
| 734 | assert_eq!(json["rule_count"], 3); |
| 735 | assert_eq!(json["warnings"].as_array().map(Vec::len), Some(2)); |
| 736 | assert_eq!(json["warnings"][0]["rule_index"], 1); |
| 737 | assert_eq!(json["warnings"][0]["tool"], "write"); |
| 738 | assert_eq!(json["warnings"][1]["rule_index"], 2); |
| 739 | assert_eq!(json["warnings"][1]["tool"], "bash"); |
| 740 | assert!(json.get("error").is_none()); |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn permissions_report_is_read_only_when_file_is_missing() { |
| 745 | let dir = tempfile::tempdir().expect("tempdir"); |
| 746 | let config_path = dir.path().join("nested").join("config.toml"); |
| 747 | |
| 748 | let report = DoctorPermissionsReport::inspect(&config_path); |
| 749 | |
| 750 | assert!(!report.present); |
| 751 | assert_eq!(report.rule_count, 0); |
| 752 | assert!(report.warnings.is_empty()); |
| 753 | assert_eq!(report.error, None); |
| 754 | assert!(permissions_human_lines(&report).is_empty()); |
| 755 | assert_eq!(permissions_short_attention(&report), None); |
| 756 | assert!(!report.path.exists()); |
| 757 | assert!(!dir.path().join("nested").exists()); |
| 758 | } |
| 759 |