| 1 | fn parse_cli(args: &[&str]) -> Cli { |
| 2 | parse_cli_args(args).expect("CLI args should parse") |
| 3 | } |
| 4 | |
| 5 | #[test] |
| 6 | fn worker_command_policy_prompt_that_looks_like_a_flag_parses() { |
| 7 | use codewhale_config::FleetExecConfig; |
| 8 | use codewhale_engine::fleet::executor::build_worker_exec_command; |
| 9 | use codewhale_protocol::fleet::FleetTaskSpec; |
| 10 | |
| 11 | let task: FleetTaskSpec = serde_json::from_value(serde_json::json!({ |
| 12 | "id": "t1", |
| 13 | "name": "Smoke", |
| 14 | "objective": "prove it runs", |
| 15 | "instructions": "audit", |
| 16 | "worker": { "role": "reviewer", "tool_profile": "read-only" } |
| 17 | })) |
| 18 | .unwrap(); |
| 19 | |
| 20 | // A Markdown bullet list, and a policy that reads exactly like one of |
| 21 | // exec's own flags; the latter makes clap reject a split |
| 22 | // `--append-system-prompt <value>` pair. |
| 23 | for policy in ["- Never push to main\n- Never touch .git/config", "--hooks"] { |
| 24 | let exec = FleetExecConfig { |
| 25 | append_system_prompt: policy.to_string(), |
| 26 | ..FleetExecConfig::default() |
| 27 | }; |
| 28 | let cmd = build_worker_exec_command("codewhale", &task, &exec, None); |
| 29 | let cli = Cli::try_parse_from(std::iter::once("codewhale".to_string()).chain(cmd.args)) |
| 30 | .unwrap_or_else(|e| panic!("{policy:?}: {e}")); |
| 31 | let Some(Commands::Exec(args)) = cli.command else { |
| 32 | panic!("expected exec command"); |
| 33 | }; |
| 34 | assert_eq!(args.append_system_prompt.as_deref(), Some(policy)); |
| 35 | assert!( |
| 36 | args.prompt.last().is_some_and(|p| p.contains("audit")), |
| 37 | "{policy}" |
| 38 | ); |
| 39 | assert!(!args.hooks, "{policy:?} must stay text, not a flag"); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[test] |
| 44 | fn sessions_archive_cli_keeps_legacy_listing_and_export_options() { |
| 45 | let legacy = parse_cli(&["codewhale", "sessions", "--limit", "7", "--search", "work"]); |
| 46 | assert!( |
| 47 | matches!(legacy.command, Some(Commands::Sessions { limit: 7, search: Some(ref s), command: None }) if s == "work") |
| 48 | ); |
| 49 | let list = parse_cli(&["codewhale", "sessions", "list", "--limit", "4"]); |
| 50 | assert!(matches!( |
| 51 | list.command, |
| 52 | Some(Commands::Sessions { |
| 53 | command: Some(SessionsCommand::List { limit: 4, .. }), |
| 54 | .. |
| 55 | }) |
| 56 | )); |
| 57 | let export = parse_cli(&[ |
| 58 | "codewhale", |
| 59 | "sessions", |
| 60 | "export", |
| 61 | "abc123", |
| 62 | "--output", |
| 63 | "session.tar.xz", |
| 64 | "--skip-artifacts", |
| 65 | "--force", |
| 66 | "--compression", |
| 67 | "0", |
| 68 | ]); |
| 69 | assert!( |
| 70 | matches!(export.command, Some(Commands::Sessions { command: Some(SessionsCommand::Export { ref id, output: Some(ref output), skip_artifacts: true, compression: 0, force: true }), .. }) if id == "abc123" && output == Path::new("session.tar.xz")) |
| 71 | ); |
| 72 | let migrate = parse_cli(&[ |
| 73 | "codewhale", |
| 74 | "sessions", |
| 75 | "migrate", |
| 76 | "--old-path", |
| 77 | "/tmp/Project_A", |
| 78 | "--new-path", |
| 79 | "/tmp/Project_B", |
| 80 | "--session", |
| 81 | "abc123", |
| 82 | "--dry-run", |
| 83 | ]); |
| 84 | assert!( |
| 85 | matches!(migrate.command, Some(Commands::Sessions { command: Some(SessionsCommand::Migrate { ref old_path, ref new_path, session: Some(ref session), dry_run: true }), .. }) if old_path == Path::new("/tmp/Project_A") && new_path == Path::new("/tmp/Project_B") && session == "abc123") |
| 86 | ); |
| 87 | let trim = parse_cli(&[ |
| 88 | "codewhale", |
| 89 | "sessions", |
| 90 | "trim", |
| 91 | "abc123", |
| 92 | "--keep-mib", |
| 93 | "6.5", |
| 94 | "--apply", |
| 95 | ]); |
| 96 | assert!( |
| 97 | matches!(trim.command, Some(Commands::Sessions { command: Some(SessionsCommand::Trim { ref id, keep_mib, apply: true }), .. }) if id == "abc123" && (keep_mib - 6.5).abs() < f64::EPSILON) |
| 98 | ); |
| 99 | let archive_default = parse_cli(&["codewhale", "sessions", "archive"]); |
| 100 | assert!(matches!( |
| 101 | archive_default.command, |
| 102 | Some(Commands::Sessions { |
| 103 | command: Some(SessionsCommand::Archive { |
| 104 | command: None, |
| 105 | json: false, |
| 106 | }), |
| 107 | .. |
| 108 | }) |
| 109 | )); |
| 110 | let archive_json = parse_cli(&["codewhale", "sessions", "archive", "list", "--json"]); |
| 111 | assert!(matches!( |
| 112 | archive_json.command, |
| 113 | Some(Commands::Sessions { |
| 114 | command: Some(SessionsCommand::Archive { |
| 115 | command: Some(SessionsArchiveCommand::List { json: true }), |
| 116 | .. |
| 117 | }), |
| 118 | .. |
| 119 | }) |
| 120 | )); |
| 121 | let archive_compact = parse_cli(&[ |
| 122 | "codewhale", |
| 123 | "sessions", |
| 124 | "archive", |
| 125 | "compact", |
| 126 | "abc123", |
| 127 | "--apply", |
| 128 | "--json", |
| 129 | ]); |
| 130 | assert!(matches!( |
| 131 | archive_compact.command, |
| 132 | Some(Commands::Sessions { |
| 133 | command: Some(SessionsCommand::Archive { |
| 134 | command: Some(SessionsArchiveCommand::Compact { |
| 135 | session_id: Some(ref id), |
| 136 | apply: true, |
| 137 | json: true, |
| 138 | }), |
| 139 | .. |
| 140 | }), |
| 141 | .. |
| 142 | }) if id == "abc123" |
| 143 | )); |
| 144 | let archive_prune = parse_cli(&[ |
| 145 | "codewhale", |
| 146 | "sessions", |
| 147 | "archive", |
| 148 | "prune", |
| 149 | "--orphans-only", |
| 150 | "--older-than-days", |
| 151 | "30", |
| 152 | "--apply", |
| 153 | "--json", |
| 154 | ]); |
| 155 | assert!(matches!( |
| 156 | archive_prune.command, |
| 157 | Some(Commands::Sessions { |
| 158 | command: Some(SessionsCommand::Archive { |
| 159 | command: Some(SessionsArchiveCommand::Prune { |
| 160 | orphans_only: true, |
| 161 | session: None, |
| 162 | older_than_days: Some(30), |
| 163 | apply: true, |
| 164 | json: true, |
| 165 | }), |
| 166 | .. |
| 167 | }), |
| 168 | .. |
| 169 | }) |
| 170 | )); |
| 171 | let archive_prune_session = parse_cli(&[ |
| 172 | "codewhale", |
| 173 | "sessions", |
| 174 | "archive", |
| 175 | "prune", |
| 176 | "--session", |
| 177 | "abc123", |
| 178 | ]); |
| 179 | assert!(matches!( |
| 180 | archive_prune_session.command, |
| 181 | Some(Commands::Sessions { |
| 182 | command: Some(SessionsCommand::Archive { |
| 183 | command: Some(SessionsArchiveCommand::Prune { |
| 184 | orphans_only: false, |
| 185 | session: Some(ref id), |
| 186 | older_than_days: None, |
| 187 | apply: false, |
| 188 | json: false, |
| 189 | }), |
| 190 | .. |
| 191 | }), |
| 192 | .. |
| 193 | }) if id == "abc123" |
| 194 | )); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn hidden_remote_control_flag_starts_the_interactive_handoff() { |
| 199 | let cli = parse_cli(&["codewhale-tui", "--remote-control"]); |
| 200 | assert!(cli.remote_control); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn plugin_registry_discovery_is_route_independent_and_read_only() { |
| 205 | let _env_lock = crate::test_support::lock_test_env(); |
| 206 | let temp = tempfile::tempdir().unwrap(); |
| 207 | let workspace = temp.path().join("workspace"); |
| 208 | let codewhale_home = temp.path().join("home"); |
| 209 | std::fs::create_dir_all(&workspace).unwrap(); |
| 210 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 211 | let workspace_arg = workspace.to_string_lossy().into_owned(); |
| 212 | |
| 213 | for route in [ |
| 214 | Vec::<&str>::new(), |
| 215 | vec!["resume", "--last"], |
| 216 | vec!["fork", "--last"], |
| 217 | vec!["exec", "hello"], |
| 218 | vec!["serve", "--mcp"], |
| 219 | ] { |
| 220 | let mut args = vec![ |
| 221 | "codewhale-tui".to_string(), |
| 222 | "--workspace".to_string(), |
| 223 | workspace_arg.clone(), |
| 224 | ]; |
| 225 | args.extend(route.into_iter().map(str::to_string)); |
| 226 | let cli = Cli::try_parse_from(args).expect("route should parse"); |
| 227 | let discovery = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv(); |
| 228 | let registry = discovery |
| 229 | .registry_for_workspace(cli.workspace.as_deref().unwrap_or(workspace.as_path())); |
| 230 | assert_eq!(registry.workspace(), workspace.as_path()); |
| 231 | assert!( |
| 232 | !codewhale_home.join("plugins/state.json").exists(), |
| 233 | "startup discovery must remain read-only" |
| 234 | ); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn doctor_json_surfaces_keep_exact_named_custom_provider() { |
| 240 | let config = custom_exec_config("custom-a"); |
| 241 | let workspace = tempfile::tempdir().expect("doctor workspace"); |
| 242 | |
| 243 | let operate = doctor_operate_fleet_report_json(&config, workspace.path()); |
| 244 | let provider_model = doctor_provider_model_report_json(&config); |
| 245 | let capability = provider_capability_report(&config); |
| 246 | let route = doctor_route_report(&config); |
| 247 | |
| 248 | assert_eq!(operate["provider"]["id"], "custom-a"); |
| 249 | assert_eq!(provider_model["provider"]["id"], "custom-a"); |
| 250 | assert_eq!(capability["resolved_provider"], "custom-a"); |
| 251 | assert_eq!(route["provider"], "custom-a"); |
| 252 | assert_eq!(route["provider_config_table"], "providers.custom-a"); |
| 253 | let serialized = serde_json::to_string(&serde_json::json!({ |
| 254 | "operate": operate, |
| 255 | "provider_model": provider_model, |
| 256 | "capability": capability, |
| 257 | "route": route, |
| 258 | })) |
| 259 | .expect("doctor JSON"); |
| 260 | assert!(!serialized.contains("local-test-key")); |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn doctor_operate_fleet_json_lists_multi_layer_profile_paths() { |
| 265 | // #5098: doctor must name the winning layer and every losing path |
| 266 | // when project and personal both define the same id. |
| 267 | let _env_lock = crate::test_support::lock_test_env(); |
| 268 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 269 | let home = tmp.path().join("home"); |
| 270 | let workspace = tmp.path().join("workspace"); |
| 271 | let personal = home.join("agents"); |
| 272 | let project = workspace.join(".codewhale").join("agents"); |
| 273 | std::fs::create_dir_all(&personal).expect("personal agents"); |
| 274 | std::fs::create_dir_all(&project).expect("project agents"); |
| 275 | std::fs::write( |
| 276 | personal.join("builder.toml"), |
| 277 | "id = \"builder\"\nrole_hint = \"builder\"\nmodel = \"deepseek-v4-flash\"\n", |
| 278 | ) |
| 279 | .expect("personal builder"); |
| 280 | std::fs::write( |
| 281 | project.join("builder.toml"), |
| 282 | "id = \"builder\"\nrole_hint = \"builder\"\nmodel = \"deepseek-v4-pro\"\n", |
| 283 | ) |
| 284 | .expect("project builder"); |
| 285 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 286 | |
| 287 | let operate = doctor_operate_fleet_report_json(&Config::default(), &workspace); |
| 288 | let layers = operate["roster"]["multi_layer"] |
| 289 | .as_array() |
| 290 | .expect("multi_layer array"); |
| 291 | let builder = layers |
| 292 | .iter() |
| 293 | .find(|entry| entry["id"] == "builder") |
| 294 | .expect("builder multi-layer entry"); |
| 295 | assert_eq!(builder["effective"], "project"); |
| 296 | let paths: Vec<&str> = builder["layers"] |
| 297 | .as_array() |
| 298 | .expect("layers") |
| 299 | .iter() |
| 300 | .filter_map(|layer| layer["path"].as_str()) |
| 301 | .collect(); |
| 302 | assert!( |
| 303 | paths.iter().any(|path| path.ends_with("builder.toml")), |
| 304 | "layer paths include the profile files: {builder}" |
| 305 | ); |
| 306 | assert!( |
| 307 | builder["layers"] |
| 308 | .as_array() |
| 309 | .expect("layers") |
| 310 | .iter() |
| 311 | .any(|layer| layer["origin"] == "personal" && layer["wins"] == false), |
| 312 | "personal layer is listed as ignored: {builder}" |
| 313 | ); |
| 314 | assert!( |
| 315 | builder["layers"] |
| 316 | .as_array() |
| 317 | .expect("layers") |
| 318 | .iter() |
| 319 | .any(|layer| layer["origin"] == "project" && layer["wins"] == true), |
| 320 | "project layer wins: {builder}" |
| 321 | ); |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn doctor_fleet_report_flags_pins_absent_from_fresh_live_roster() { |
| 326 | // #6035: a pin that vanished from the provider's current live roster |
| 327 | // is drift the report must name — warning only, never a rewrite. |
| 328 | let _env_lock = crate::test_support::lock_test_env(); |
| 329 | let _live = codewhale_engine::provider_lake::lock_live_snapshot(); |
| 330 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 331 | let home = tmp.path().join("home"); |
| 332 | let workspace = tmp.path().join("workspace"); |
| 333 | std::fs::create_dir_all(&workspace).expect("workspace"); |
| 334 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 335 | let fleets = home.join("fleets"); |
| 336 | std::fs::create_dir_all(&fleets).expect("fleets dir"); |
| 337 | std::fs::write( |
| 338 | fleets.join("default.toml"), |
| 339 | "schema = \"fleet\"\nschema_revision = 2\nname = \"default\"\n\ |
| 340 | [operator]\nprovider = \"deepseek\"\nmodel = \"deepseek-flash\"\n\ |
| 341 | [[members]]\nid = \"builder\"\nprovider = \"deepseek\"\nmodel = \"deepseek-v4-flash\"\n", |
| 342 | ) |
| 343 | .expect("fleet file"); |
| 344 | |
| 345 | let config = { |
| 346 | let __cw_config_init_2_0 = Some("deepseek".to_string()); |
| 347 | // A fresh one-row roster must not replace the normal DeepSeek |
| 348 | // endpoint's process-wide catalog for unrelated route tests. |
| 349 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 350 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 351 | __cw_config_init_2_value |
| 352 | } |
| 353 | .with_legacy_root( |
| 354 | None, |
| 355 | Some("https://api.deepseek.com/v1/doctor-roster-fixture".to_string()), |
| 356 | ); |
| 357 | let base_url = config.base_url_for_route( |
| 358 | &config |
| 359 | .resolve_provider_selection_identity("deepseek") |
| 360 | .unwrap(), |
| 361 | ); |
| 362 | let fetched_at = std::time::SystemTime::now() |
| 363 | .duration_since(std::time::UNIX_EPOCH) |
| 364 | .expect("clock") |
| 365 | .as_secs(); |
| 366 | let fingerprint = codewhale_config::catalog::base_url_fingerprint(&base_url); |
| 367 | assert_eq!( |
| 368 | codewhale_engine::provider_catalog_live::record_success( |
| 369 | codewhale_config::catalog::ProviderCatalogDelta { |
| 370 | provider: "deepseek".to_string(), |
| 371 | base_url_fingerprint: fingerprint.clone(), |
| 372 | fetched_at, |
| 373 | offerings: vec![codewhale_config::catalog::CatalogOffering { |
| 374 | provider: "deepseek".to_string(), |
| 375 | wire_model_id: "deepseek-flash".to_string(), |
| 376 | endpoint_key: "chat".to_string(), |
| 377 | source: codewhale_config::catalog::CatalogSource::Live { |
| 378 | base_url_fingerprint: fingerprint, |
| 379 | fetched_at, |
| 380 | }, |
| 381 | ..Default::default() |
| 382 | }], |
| 383 | } |
| 384 | ), |
| 385 | codewhale_config::catalog::CatalogStatus::Fresh |
| 386 | ); |
| 387 | |
| 388 | let operate = doctor_operate_fleet_report_json(&config, &workspace); |
| 389 | let drift = &operate["model_pin_drift"]; |
| 390 | let drifted = drift["drifted"].as_array().expect("drifted array"); |
| 391 | let row = drifted |
| 392 | .iter() |
| 393 | .find(|row| row["model"] == "deepseek-v4-flash") |
| 394 | .expect("member pin flagged: {drift}"); |
| 395 | assert_eq!(row["provider"], "deepseek"); |
| 396 | assert!( |
| 397 | row["owners"] |
| 398 | .as_array() |
| 399 | .expect("owners") |
| 400 | .iter() |
| 401 | .any(|owner| owner.as_str().is_some_and(|o| o.contains("member:builder"))), |
| 402 | "the fleet member pin is named: {row}" |
| 403 | ); |
| 404 | // The operator pin moved to the listed id — not drift. |
| 405 | assert!( |
| 406 | !drifted.iter().any(|row| row["model"] == "deepseek-flash"), |
| 407 | "listed pin must not be flagged: {drifted:?}" |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | fn saved_exec_session(provider: &str, model: &str) -> session_manager::SavedSession { |
| 412 | let mut saved = session_manager::create_saved_session_with_mode( |
| 413 | &[], |
| 414 | model, |
| 415 | Path::new("/tmp/exec-resume"), |
| 416 | 0, |
| 417 | None, |
| 418 | Some("exec"), |
| 419 | ); |
| 420 | let kind = codewhale_config::ProviderKind::parse(provider) |
| 421 | .unwrap_or(codewhale_config::ProviderKind::Custom) |
| 422 | .as_str(); |
| 423 | let exact_id = (!provider |
| 424 | .eq_ignore_ascii_case(codewhale_config::ProviderKind::Custom.as_str())) |
| 425 | .then_some(provider); |
| 426 | saved.metadata.set_model_provider_route(kind, exact_id); |
| 427 | saved |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn exec_conversation_mode_flag_sets_a_new_session_mode() { |
| 432 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 433 | let cli = parse_cli(&["codewhale", "exec", "--conversation-mode", "creator", "hi"]); |
| 434 | let Some(Commands::Exec(args)) = cli.command else { |
| 435 | panic!("exec command"); |
| 436 | }; |
| 437 | assert_eq!(args.conversation_mode.as_deref(), Some("creator")); |
| 438 | let none = parse_cli(&["codewhale", "exec", "hi"]); |
| 439 | let Some(Commands::Exec(args_none)) = none.command else { |
| 440 | panic!("exec command"); |
| 441 | }; |
| 442 | assert_eq!(args_none.conversation_mode, None); |
| 443 | |
| 444 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 445 | .build() |
| 446 | .unwrap(); |
| 447 | let config = codewhale_runtime::config::Config::default(); |
| 448 | let locale = codewhale_localization::Locale::En; |
| 449 | let resolve = |flag: Option<&str>| { |
| 450 | runtime.block_on(tui::conversation_mode::launch_conversation_mode( |
| 451 | &config, locale, flag, None, |
| 452 | )) |
| 453 | }; |
| 454 | { |
| 455 | let _available = CreatorAvailabilityGuard::set(None); |
| 456 | assert_eq!(resolve(Some("creator")), Ok(Some("creator".to_string()))); |
| 457 | assert_eq!(resolve(Some("standard")), Ok(None)); |
| 458 | assert_eq!(resolve(None), Ok(None)); |
| 459 | let unknown = resolve(Some("minimal")).expect_err("unknown id"); |
| 460 | assert!(unknown.contains("standard, creator"), "{unknown}"); |
| 461 | } |
| 462 | { |
| 463 | let _unavailable = CreatorAvailabilityGuard::set(Some( |
| 464 | codewhale_engine::conversation_modes::CREATOR_KEY_OFF_REASON, |
| 465 | )); |
| 466 | let refused = resolve(Some("creator")).expect_err("unavailable"); |
| 467 | assert!( |
| 468 | refused.contains(codewhale_engine::conversation_modes::CREATOR_KEY_OFF_REASON), |
| 469 | "{refused}" |
| 470 | ); |
| 471 | } |
| 472 | |
| 473 | let mut saved = saved_exec_session("deepseek", "deepseek-v4-pro"); |
| 474 | saved.agent_preset = resolve_stored_for_test(&runtime, &config, "creator"); |
| 475 | let raw = serde_json::to_value(&saved).unwrap(); |
| 476 | assert_eq!(raw["agent_preset"], "creator"); |
| 477 | let standard = saved_exec_session("deepseek", "deepseek-v4-pro"); |
| 478 | assert!(serde_json::to_value(&standard).unwrap().get("agent_preset").is_none()); |
| 479 | } |
| 480 | |
| 481 | fn resolve_stored_for_test( |
| 482 | runtime: &tokio::runtime::Runtime, |
| 483 | config: &codewhale_runtime::config::Config, |
| 484 | flag: &str, |
| 485 | ) -> Option<String> { |
| 486 | let _available = codewhale_engine::conversation_modes::CreatorAvailabilityGuard::set(None); |
| 487 | runtime |
| 488 | .block_on(tui::conversation_mode::launch_conversation_mode( |
| 489 | config, |
| 490 | codewhale_localization::Locale::En, |
| 491 | Some(flag), |
| 492 | None, |
| 493 | )) |
| 494 | .expect("resolves") |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn exec_conversation_mode_flag_that_differs_from_a_resumed_session_is_refused_before_any_model_call() { |
| 499 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 500 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 501 | .build() |
| 502 | .unwrap(); |
| 503 | let config = codewhale_runtime::config::Config::default(); |
| 504 | let locale = codewhale_localization::Locale::En; |
| 505 | let resolve = |flag: &str, saved: &session_manager::SavedSession| { |
| 506 | runtime.block_on(tui::conversation_mode::launch_conversation_mode( |
| 507 | &config, |
| 508 | locale, |
| 509 | Some(flag), |
| 510 | Some(saved), |
| 511 | )) |
| 512 | }; |
| 513 | let _unavailable = CreatorAvailabilityGuard::set(Some( |
| 514 | codewhale_engine::conversation_modes::CREATOR_KEY_OFF_REASON, |
| 515 | )); |
| 516 | let standard = saved_exec_session("deepseek", "deepseek-v4-pro"); |
| 517 | let mut creator = saved_exec_session("deepseek", "deepseek-v4-pro"); |
| 518 | creator.agent_preset = Some("creator".to_string()); |
| 519 | |
| 520 | let refused = resolve("creator", &standard).expect_err("Standard session, creator flag"); |
| 521 | assert!(refused.contains("fixed") && refused.contains("/new creator"), "{refused}"); |
| 522 | let refused = resolve("standard", &creator).expect_err("creator session, standard flag"); |
| 523 | assert!(refused.contains("fixed") && refused.contains("/new"), "{refused}"); |
| 524 | assert!(resolve("minimal", &creator).is_err()); |
| 525 | assert_eq!(resolve("standard", &standard), Ok(None)); |
| 526 | assert_eq!( |
| 527 | resolve("creator", &creator), |
| 528 | Ok(Some("creator".to_string())), |
| 529 | "a matching flag resumes even while the mode is unavailable" |
| 530 | ); |
| 531 | } |
| 532 | |
| 533 | #[test] |
| 534 | fn prompt_flag_accepts_split_prompt_words_for_windows_cmd_shims() { |
| 535 | let cli = parse_cli(&["codewhale", "-p", "hello", "world"]); |
| 536 | |
| 537 | assert_eq!(cli.prompt, vec!["hello", "world"]); |
| 538 | } |
| 539 | |
| 540 | #[test] |
| 541 | fn prompt_flag_starts_interactive_submit_input() { |
| 542 | let cli = parse_cli(&["codewhale", "-p", "read", "the", "project"]); |
| 543 | |
| 544 | assert_eq!( |
| 545 | top_level_prompt_initial_input(&cli.prompt), |
| 546 | Some(tui::InitialInput::Submit("read the project".to_string())) |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | #[test] |
| 551 | fn runtime_decoder_uses_the_canonical_command_name() { |
| 552 | assert_eq!(Cli::command().get_name(), "codewhale"); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn usage_errors_name_the_codewhale_command() { |
| 557 | let error = Cli::try_parse_from(["codewhale-tui", "doctor", "--bogus"]) |
| 558 | .expect_err("an unknown doctor flag must not parse"); |
| 559 | let rendered = error.render().to_string(); |
| 560 | assert!( |
| 561 | rendered.contains("codewhale doctor"), |
| 562 | "usage should name `codewhale doctor`: {rendered}" |
| 563 | ); |
| 564 | assert!( |
| 565 | !rendered.contains("codewhale-tui"), |
| 566 | "usage must not name the retired binary: {rendered}" |
| 567 | ); |
| 568 | } |
| 569 | |
| 570 | #[test] |
| 571 | fn xai_device_auth_subcommand_parses() { |
| 572 | let cli = parse_cli(&["codewhale-tui", "auth", "xai-device"]); |
| 573 | assert!(matches!( |
| 574 | cli.command, |
| 575 | Some(Commands::Auth(TuiAuthArgs { |
| 576 | command: TuiAuthCommand::XaiDevice |
| 577 | })) |
| 578 | )); |
| 579 | } |
| 580 | |
| 581 | #[test] |
| 582 | fn chatgpt_auth_subcommand_parses() { |
| 583 | let cli = parse_cli(&["codewhale-tui", "auth", "chatgpt"]); |
| 584 | assert!(matches!( |
| 585 | cli.command, |
| 586 | Some(Commands::Auth(TuiAuthArgs { |
| 587 | command: TuiAuthCommand::Chatgpt { |
| 588 | reauth: false, |
| 589 | new_account: false, |
| 590 | } |
| 591 | })) |
| 592 | )); |
| 593 | let cli = parse_cli(&["codewhale-tui", "auth", "chatgpt", "--reauth"]); |
| 594 | assert!(matches!( |
| 595 | cli.command, |
| 596 | Some(Commands::Auth(TuiAuthArgs { |
| 597 | command: TuiAuthCommand::Chatgpt { |
| 598 | reauth: true, |
| 599 | new_account: false, |
| 600 | } |
| 601 | })) |
| 602 | )); |
| 603 | let cli = parse_cli(&["codewhale-tui", "auth", "chatgpt", "--new-account"]); |
| 604 | assert!(matches!( |
| 605 | cli.command, |
| 606 | Some(Commands::Auth(TuiAuthArgs { |
| 607 | command: TuiAuthCommand::Chatgpt { |
| 608 | reauth: false, |
| 609 | new_account: true, |
| 610 | } |
| 611 | })) |
| 612 | )); |
| 613 | let cli = parse_cli(&["codewhale-tui", "auth", "chatgpt", "--switch"]); |
| 614 | assert!(matches!( |
| 615 | cli.command, |
| 616 | Some(Commands::Auth(TuiAuthArgs { |
| 617 | command: TuiAuthCommand::Chatgpt { |
| 618 | reauth: false, |
| 619 | new_account: true, |
| 620 | } |
| 621 | })) |
| 622 | )); |
| 623 | let cli = parse_cli(&["codewhale-tui", "auth", "chatgpt-revoke"]); |
| 624 | assert!(matches!( |
| 625 | cli.command, |
| 626 | Some(Commands::Auth(TuiAuthArgs { |
| 627 | command: TuiAuthCommand::ChatgptRevoke |
| 628 | })) |
| 629 | )); |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn workflow_tool_internal_subcommand_parses_exact_json() { |
| 634 | let cli = parse_cli(&[ |
| 635 | "codewhale-tui", |
| 636 | "workflow-tool", |
| 637 | "--approval-source", |
| 638 | "explicit-workflow-command", |
| 639 | "--input-json", |
| 640 | r#"{"action":"run","source_path":"workflows/demo.js"}"#, |
| 641 | ]); |
| 642 | let Some(Commands::WorkflowTool(args)) = cli.command else { |
| 643 | panic!("expected workflow-tool command"); |
| 644 | }; |
| 645 | assert!(args.input_json.contains("\"action\":\"run\"")); |
| 646 | } |
| 647 | |
| 648 | #[tokio::test] |
| 649 | async fn direct_workflow_tool_runs_without_an_operator_model_turn() { |
| 650 | use codewhale_engine::tools::spec::ToolSpec; |
| 651 | |
| 652 | let workspace = tempfile::tempdir().expect("workspace"); |
| 653 | let config = { |
| 654 | let __cw_config_init_3_0 = Some("vllm".to_string()); |
| 655 | let __cw_config_init_3_1 = Some( |
| 656 | workspace |
| 657 | .path() |
| 658 | .join("missing-mcp.json") |
| 659 | .display() |
| 660 | .to_string(), |
| 661 | ); |
| 662 | let __cw_config_init_3_2 = Some(codewhale_runtime::config::ProvidersConfig { |
| 663 | vllm: codewhale_runtime::config::ProviderConfig { |
| 664 | base_url: Some("http://127.0.0.1:9/v1".to_string()), |
| 665 | model: Some("offline-test-model".to_string()), |
| 666 | ..Default::default() |
| 667 | }, |
| 668 | ..Default::default() |
| 669 | }); |
| 670 | let mut __cw_config_init_3_value: Config = Default::default(); |
| 671 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 672 | __cw_config_init_3_value.mcp_config_path = __cw_config_init_3_1; |
| 673 | __cw_config_init_3_value.providers = __cw_config_init_3_2; |
| 674 | __cw_config_init_3_value |
| 675 | }; |
| 676 | let route = CliAutoRoute { |
| 677 | provider: config.test_identity_for_kind(codewhale_config::ProviderKind::Vllm), |
| 678 | model: "offline-test-model".to_string(), |
| 679 | reasoning_effort: None, |
| 680 | auto_controls_reasoning: false, |
| 681 | auto_model: false, |
| 682 | }; |
| 683 | let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64); |
| 684 | let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(workspace.path())); |
| 685 | let manager = Arc::new( |
| 686 | session_manager::SessionManager::new(workspace.path().join("sessions")) |
| 687 | .expect("isolated Workflow session store"), |
| 688 | ); |
| 689 | let (_, source, _lease) = admit_cli_saved_operation( |
| 690 | Some(manager), |
| 691 | uuid::Uuid::new_v4().to_string(), |
| 692 | workspace.path().to_path_buf(), |
| 693 | route.model.clone(), |
| 694 | route.provider.clone(), |
| 695 | "Run a model-free Workflow".to_string(), |
| 696 | ) |
| 697 | .await |
| 698 | .expect("admitted Workflow invocation"); |
| 699 | let origin = source |
| 700 | .usage_origin(codewhale_engine::cost_status::scope_token()) |
| 701 | .expect("captured Workflow usage origin"); |
| 702 | let (tool, context) = build_direct_workflow_tool( |
| 703 | &config, |
| 704 | &route, |
| 705 | workspace.path(), |
| 706 | event_tx, |
| 707 | plugins, |
| 708 | Some(origin), |
| 709 | ) |
| 710 | .await |
| 711 | .expect("build direct workflow runtime"); |
| 712 | |
| 713 | let result = tool |
| 714 | .execute( |
| 715 | serde_json::json!({ |
| 716 | "action": "run", |
| 717 | "script": "phase('offline'); return { ok: true };", |
| 718 | "token_budget": 1_000_000 |
| 719 | }), |
| 720 | &context, |
| 721 | ) |
| 722 | .await |
| 723 | .expect("model-free workflow run"); |
| 724 | let payload: serde_json::Value = serde_json::from_str(&result.content).expect("workflow JSON"); |
| 725 | |
| 726 | assert_eq!(payload["status"], "completed"); |
| 727 | assert_eq!(payload["result"]["ok"], true); |
| 728 | assert_eq!(payload["child_ids"].as_array().map(Vec::len), Some(0)); |
| 729 | assert_eq!( |
| 730 | payload["plan_approval"]["decision"], |
| 731 | "approved_explicit_cli_command" |
| 732 | ); |
| 733 | assert!(!context.auto_approve); |
| 734 | assert!(!context.trust_mode); |
| 735 | assert_eq!( |
| 736 | context.shell_policy, |
| 737 | codewhale_agent_contract::worker_profile::ShellPolicy::None |
| 738 | ); |
| 739 | assert!(matches!( |
| 740 | context.elevated_sandbox_policy, |
| 741 | Some(codewhale_sandbox::SandboxPolicy::WorkspaceWrite { .. }) |
| 742 | )); |
| 743 | let mut event_types = Vec::new(); |
| 744 | while let Ok(event) = event_rx.try_recv() { |
| 745 | if let codewhale_engine::core::events::Event::WorkflowUi { event, .. } = event |
| 746 | && let Some(kind) = event["type"].as_str() |
| 747 | { |
| 748 | event_types.push(kind.to_string()); |
| 749 | } |
| 750 | } |
| 751 | assert!(event_types.iter().any(|kind| kind == "run_started")); |
| 752 | assert!(event_types.iter().any(|kind| kind == "run_completed")); |
| 753 | } |
| 754 | |
| 755 | #[tokio::test] |
| 756 | async fn direct_workflow_mcp_pool_applies_network_policy_before_connect() { |
| 757 | let workspace = tempfile::tempdir().expect("workspace"); |
| 758 | let mcp_path = workspace.path().join("mcp.json"); |
| 759 | std::fs::write( |
| 760 | &mcp_path, |
| 761 | r#"{ |
| 762 | "mcpServers": { |
| 763 | "blocked": { "url": "https://blocked.invalid/mcp" } |
| 764 | } |
| 765 | }"#, |
| 766 | ) |
| 767 | .expect("write MCP config"); |
| 768 | let config = { |
| 769 | let __cw_config_init_4_0 = Some(mcp_path.display().to_string()); |
| 770 | let mut __cw_config_init_4_value: Config = Default::default(); |
| 771 | __cw_config_init_4_value.mcp_config_path = __cw_config_init_4_0; |
| 772 | __cw_config_init_4_value |
| 773 | }; |
| 774 | let policy = codewhale_net::network_policy::NetworkPolicyDecider::new( |
| 775 | codewhale_net::network_policy::NetworkPolicy { |
| 776 | default: codewhale_net::network_policy::DecisionToml::Deny, |
| 777 | allow: Vec::new(), |
| 778 | deny: Vec::new(), |
| 779 | proxy: Vec::new(), |
| 780 | proxy_fake_ip_cidrs: Vec::new(), |
| 781 | audit: false, |
| 782 | }, |
| 783 | None, |
| 784 | ); |
| 785 | |
| 786 | let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(workspace.path())); |
| 787 | let (_pool, failures) = |
| 788 | initialize_direct_workflow_mcp_pool(&config, workspace.path(), Some(policy), plugins) |
| 789 | .await |
| 790 | .expect("MCP feature enabled"); |
| 791 | assert_eq!(failures.len(), 1, "failures={failures:?}"); |
| 792 | assert_eq!(failures[0].0, "blocked"); |
| 793 | assert!(failures[0].1.contains("blocked by network policy")); |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn exec_model_resolution_uses_provider_scoped_default() { |
| 798 | let _env_lock = crate::test_support::lock_test_env(); |
| 799 | let _codewhale_model = crate::test_support::EnvVarGuard::remove("CODEWHALE_MODEL"); |
| 800 | let _deepseek_model = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MODEL"); |
| 801 | let config = { |
| 802 | let __cw_config_init_5_0 = Some("openrouter".to_string()); |
| 803 | let __cw_config_init_5_1 = Some("deepseek/deepseek-v4-pro".to_string()); |
| 804 | let __cw_config_init_5_2 = Some(codewhale_runtime::config::ProvidersConfig { |
| 805 | openrouter: codewhale_runtime::config::ProviderConfig { |
| 806 | model: Some("arcee-ai/trinity-large-thinking".to_string()), |
| 807 | ..Default::default() |
| 808 | }, |
| 809 | ..Default::default() |
| 810 | }); |
| 811 | let mut __cw_config_init_5_value: Config = Default::default(); |
| 812 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 813 | __cw_config_init_5_value.default_text_model = __cw_config_init_5_1; |
| 814 | __cw_config_init_5_value.providers = __cw_config_init_5_2; |
| 815 | __cw_config_init_5_value |
| 816 | }; |
| 817 | |
| 818 | assert_eq!( |
| 819 | resolve_exec_model(&config, None), |
| 820 | "arcee-ai/trinity-large-thinking" |
| 821 | ); |
| 822 | assert_eq!( |
| 823 | resolve_exec_model(&config, Some("arcee-ai/trinity-large-thinking")), |
| 824 | "arcee-ai/trinity-large-thinking" |
| 825 | ); |
| 826 | } |
| 827 | |
| 828 | #[test] |
| 829 | fn exec_model_resolution_prefers_codewhale_model_env_override() { |
| 830 | let _env_lock = crate::test_support::lock_test_env(); |
| 831 | let _codewhale_model = crate::test_support::EnvVarGuard::set("CODEWHALE_MODEL", " auto "); |
| 832 | let _deepseek_model = |
| 833 | crate::test_support::EnvVarGuard::set("DEEPSEEK_MODEL", "stale-deepseek-model"); |
| 834 | let config = { |
| 835 | let __cw_config_init_6_0 = Some("deepseek/deepseek-v4-pro".to_string()); |
| 836 | let mut __cw_config_init_6_value: Config = Default::default(); |
| 837 | __cw_config_init_6_value.default_text_model = __cw_config_init_6_0; |
| 838 | __cw_config_init_6_value |
| 839 | }; |
| 840 | |
| 841 | assert_eq!(resolve_exec_model(&config, None), "auto"); |
| 842 | } |
| 843 | |
| 844 | #[test] |
| 845 | fn exec_model_resolution_uses_legacy_deepseek_model_env_override() { |
| 846 | let _env_lock = crate::test_support::lock_test_env(); |
| 847 | let _codewhale_model = crate::test_support::EnvVarGuard::remove("CODEWHALE_MODEL"); |
| 848 | let _deepseek_model = crate::test_support::EnvVarGuard::set("DEEPSEEK_MODEL", " auto "); |
| 849 | let config = { |
| 850 | let __cw_config_init_7_0 = Some("deepseek/deepseek-v4-pro".to_string()); |
| 851 | let mut __cw_config_init_7_value: Config = Default::default(); |
| 852 | __cw_config_init_7_value.default_text_model = __cw_config_init_7_0; |
| 853 | __cw_config_init_7_value |
| 854 | }; |
| 855 | |
| 856 | assert_eq!(resolve_exec_model(&config, None), "auto"); |
| 857 | } |
| 858 | |
| 859 | #[test] |
| 860 | fn exec_model_resolution_uses_provider_safe_default_for_zai() { |
| 861 | let _env_lock = crate::test_support::lock_test_env(); |
| 862 | let _codewhale_model = crate::test_support::EnvVarGuard::remove("CODEWHALE_MODEL"); |
| 863 | let _deepseek_model = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MODEL"); |
| 864 | let config = { |
| 865 | let __cw_config_init_8_0 = Some("zai".to_string()); |
| 866 | let __cw_config_init_8_1 = |
| 867 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 868 | let mut __cw_config_init_8_value: Config = Default::default(); |
| 869 | __cw_config_init_8_value.provider = __cw_config_init_8_0; |
| 870 | __cw_config_init_8_value.default_text_model = __cw_config_init_8_1; |
| 871 | __cw_config_init_8_value |
| 872 | }; |
| 873 | |
| 874 | assert_eq!( |
| 875 | resolve_exec_model(&config, None), |
| 876 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 877 | ); |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn fresh_launch_uses_selected_fleet_operator_unless_route_is_explicit() { |
| 882 | let workspace = tempfile::tempdir().expect("workspace"); |
| 883 | let fleets = workspace.path().join(".codewhale").join("fleets"); |
| 884 | std::fs::create_dir_all(&fleets).expect("fleet directory"); |
| 885 | std::fs::write(fleets.join("selected"), "Launch\n").expect("selection"); |
| 886 | std::fs::write( |
| 887 | fleets.join("launch.toml"), |
| 888 | r#"schema = "fleet" |
| 889 | schema_revision = 2 |
| 890 | name = "Launch" |
| 891 | |
| 892 | [operator] |
| 893 | provider = "deepseek" |
| 894 | model = "deepseek-v4-flash-vision-exp" |
| 895 | reasoning = "high" |
| 896 | "#, |
| 897 | ) |
| 898 | .expect("fleet file"); |
| 899 | |
| 900 | let base = { |
| 901 | let __cw_config_init_9_0 = Some("openrouter".to_string()); |
| 902 | let __cw_config_init_9_1 = Some("off".to_string()); |
| 903 | let mut __cw_config_init_9_value: Config = Default::default(); |
| 904 | __cw_config_init_9_value.provider = __cw_config_init_9_0; |
| 905 | __cw_config_init_9_value.reasoning_effort = __cw_config_init_9_1; |
| 906 | __cw_config_init_9_value |
| 907 | } |
| 908 | .with_legacy_root(Some("test-key".to_string()), None); |
| 909 | let mut explicit = base.clone(); |
| 910 | assert!( |
| 911 | !apply_selected_fleet_operator_for_launch(&mut explicit, workspace.path(), true, false,) |
| 912 | .expect("explicit route bypasses Fleet operator") |
| 913 | ); |
| 914 | assert_eq!( |
| 915 | explicit.active_provider_identity().unwrap().provider, |
| 916 | codewhale_config::ProviderKind::Openrouter |
| 917 | ); |
| 918 | |
| 919 | let mut selected = base; |
| 920 | assert!( |
| 921 | apply_selected_fleet_operator_for_launch(&mut selected, workspace.path(), false, false,) |
| 922 | .expect("selected operator applies") |
| 923 | ); |
| 924 | assert_eq!( |
| 925 | selected.active_provider_identity().unwrap().provider, |
| 926 | codewhale_config::ProviderKind::Deepseek |
| 927 | ); |
| 928 | assert_eq!(selected.default_model(), "deepseek-v4-flash-vision-exp"); |
| 929 | assert_eq!(selected.reasoning_effort(), Some("high")); |
| 930 | assert!(selected.fleet_operator_route_applied); |
| 931 | assert!(selected.fleet_operator_reasoning_applied); |
| 932 | |
| 933 | let mut reasoning_override = { |
| 934 | let __cw_config_init_10_0 = Some("off".to_string()); |
| 935 | let mut __cw_config_init_10_value: Config = Default::default(); |
| 936 | __cw_config_init_10_value.reasoning_effort = __cw_config_init_10_0; |
| 937 | __cw_config_init_10_value |
| 938 | } |
| 939 | .with_legacy_root(Some("test-key".to_string()), None); |
| 940 | apply_selected_fleet_operator_for_launch( |
| 941 | &mut reasoning_override, |
| 942 | workspace.path(), |
| 943 | false, |
| 944 | true, |
| 945 | ) |
| 946 | .expect("explicit reasoning coexists with Fleet route"); |
| 947 | assert_eq!( |
| 948 | reasoning_override.default_model(), |
| 949 | "deepseek-v4-flash-vision-exp" |
| 950 | ); |
| 951 | assert_eq!(reasoning_override.reasoning_effort(), Some("off")); |
| 952 | assert!(reasoning_override.fleet_operator_route_applied); |
| 953 | assert!(!reasoning_override.fleet_operator_reasoning_applied); |
| 954 | } |
| 955 | |
| 956 | #[test] |
| 957 | fn selected_fleet_operator_load_error_redacts_paths_excerpts_and_opaque_name() { |
| 958 | let workspace = tempfile::tempdir().expect("workspace"); |
| 959 | let fleets = workspace.path().join(".codewhale").join("fleets"); |
| 960 | std::fs::create_dir_all(&fleets).expect("fleet directory"); |
| 961 | let secret_marker = "sk-live-abcdef0123456789abcdef"; |
| 962 | std::fs::write(fleets.join("selected"), format!("{secret_marker}\n")).expect("selection"); |
| 963 | std::fs::write( |
| 964 | fleets.join(format!("{secret_marker}.toml")), |
| 965 | format!("invalid TOML /Users/operator/private {secret_marker}\n"), |
| 966 | ) |
| 967 | .expect("invalid Fleet"); |
| 968 | |
| 969 | let mut config = Config::default(); |
| 970 | let message = |
| 971 | apply_selected_fleet_operator_for_launch(&mut config, workspace.path(), false, false) |
| 972 | .expect_err("invalid selected Fleet must fail") |
| 973 | .to_string(); |
| 974 | |
| 975 | assert!(!message.contains(&workspace.path().display().to_string())); |
| 976 | assert!(!message.contains("/Users/operator")); |
| 977 | assert!(!message.contains(secret_marker)); |
| 978 | assert!(!message.contains("invalid TOML")); |
| 979 | assert!(message.chars().count() <= 700, "{message}"); |
| 980 | } |
| 981 | |
| 982 | #[test] |
| 983 | fn exec_accepts_split_prompt_words_for_windows_cmd_shims() { |
| 984 | let cli = parse_cli(&["codewhale", "exec", "hello", "world"]); |
| 985 | let Some(Commands::Exec(args)) = cli.command else { |
| 986 | panic!("expected exec command"); |
| 987 | }; |
| 988 | |
| 989 | assert_eq!(args.prompt, vec!["hello", "world"]); |
| 990 | } |
| 991 | |
| 992 | #[test] |
| 993 | fn exec_keeps_model_flag_before_split_prompt_words() { |
| 994 | let cli = parse_cli(&["codewhale", "exec", "--model", "auto", "hello", "world"]); |
| 995 | let Some(Commands::Exec(args)) = cli.command else { |
| 996 | panic!("expected exec command"); |
| 997 | }; |
| 998 | |
| 999 | assert_eq!(args.model.as_deref(), Some("auto")); |
| 1000 | assert_eq!(args.prompt, vec!["hello", "world"]); |
| 1001 | } |
| 1002 | |
| 1003 | #[test] |
| 1004 | fn exec_keeps_flags_before_split_prompt_words() { |
| 1005 | let cli = parse_cli(&["codewhale", "exec", "--json", "hello", "--world"]); |
| 1006 | let Some(Commands::Exec(args)) = cli.command else { |
| 1007 | panic!("expected exec command"); |
| 1008 | }; |
| 1009 | |
| 1010 | assert!(args.json); |
| 1011 | assert_eq!(args.prompt, vec!["hello", "--world"]); |
| 1012 | for flag in [ |
| 1013 | "--sandbox", |
| 1014 | "--sandbox=workspace-write", |
| 1015 | "--auto", |
| 1016 | "--help", |
| 1017 | "--enable=web_search", |
| 1018 | "--operation-key=example", |
| 1019 | ] { |
| 1020 | let error = parse_cli_args(&["codewhale", "exec", "--auto", "fix tests", flag]) |
| 1021 | .expect_err("exec flags after the prompt must not silently become text"); |
| 1022 | assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument); |
| 1023 | assert!(error.to_string().contains(flag.split('=').next().unwrap())); |
| 1024 | } |
| 1025 | for prompt in [ |
| 1026 | vec!["--", "--sandbox", "workspace-write"], |
| 1027 | vec!["hello", "--", "--sandbox=workspace-write"], |
| 1028 | ] { |
| 1029 | let argv: Vec<&str> = ["codewhale", "exec", "--auto"] |
| 1030 | .into_iter() |
| 1031 | .chain(prompt) |
| 1032 | .collect(); |
| 1033 | let cli = parse_cli(&argv); |
| 1034 | let Some(Commands::Exec(args)) = cli.command else { |
| 1035 | panic!("expected exec command"); |
| 1036 | }; |
| 1037 | assert!(args.sandbox.is_none()); |
| 1038 | assert!(args.prompt.iter().any(|word| word.starts_with("--sandbox"))); |
| 1039 | } |
| 1040 | let error = Cli::try_parse_from([ |
| 1041 | "codewhale", |
| 1042 | "exec", |
| 1043 | "--auto", |
| 1044 | "--sandox", |
| 1045 | "workspace-write", |
| 1046 | "--max-turns", |
| 1047 | "1", |
| 1048 | "--json", |
| 1049 | "Reply with the single word OK and use no tools.", |
| 1050 | ]) |
| 1051 | .expect_err("unknown flags before the prompt must fail parsing"); |
| 1052 | assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument); |
| 1053 | } |
| 1054 | |
| 1055 | #[test] |
| 1056 | fn exec_prompt_file_carries_prompts_past_the_argv_ceiling() { |
| 1057 | // #6688: argv caps one argument at 128 KiB; the file transport does not. |
| 1058 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1059 | let path = dir.path().join("big-prompt.txt"); |
| 1060 | let body = "стих ".repeat(60_000); |
| 1061 | assert!(body.len() > 512 * 1024); |
| 1062 | std::fs::write(&path, &body).expect("write prompt"); |
| 1063 | let path_arg = path.to_str().expect("utf-8 path"); |
| 1064 | |
| 1065 | let cli = parse_cli(&["codewhale", "exec", "--auto", "--prompt-file", path_arg]); |
| 1066 | let Some(Commands::Exec(args)) = cli.command else { |
| 1067 | panic!("expected exec command"); |
| 1068 | }; |
| 1069 | assert!(args.auto); |
| 1070 | assert!(args.prompt.is_empty()); |
| 1071 | assert_eq!(resolve_exec_prompt(&args).expect("prompt"), body); |
| 1072 | |
| 1073 | let conflict = |
| 1074 | Cli::try_parse_from(["codewhale", "exec", "--prompt-file", path_arg, "also argv"]) |
| 1075 | .expect_err("positional prompt and --prompt-file conflict"); |
| 1076 | assert_eq!(conflict.kind(), clap::error::ErrorKind::ArgumentConflict); |
| 1077 | |
| 1078 | let missing = dir.path().join("missing.txt"); |
| 1079 | let cli = parse_cli(&[ |
| 1080 | "codewhale", |
| 1081 | "exec", |
| 1082 | "--prompt-file", |
| 1083 | missing.to_str().expect("utf-8 path"), |
| 1084 | ]); |
| 1085 | let Some(Commands::Exec(args)) = cli.command else { |
| 1086 | panic!("expected exec command"); |
| 1087 | }; |
| 1088 | let err = resolve_exec_prompt(&args).expect_err("missing file fails"); |
| 1089 | assert!(err.to_string().contains("--prompt-file"), "{err:#}"); |
| 1090 | |
| 1091 | let cli = parse_cli(&[ |
| 1092 | "codewhale", |
| 1093 | "exec", |
| 1094 | "--parent-death-watch", |
| 1095 | "--prompt-file", |
| 1096 | "-", |
| 1097 | ]); |
| 1098 | let Some(Commands::Exec(args)) = cli.command else { |
| 1099 | panic!("expected exec command"); |
| 1100 | }; |
| 1101 | let err = resolve_exec_prompt(&args).expect_err("stdin is owned by the watcher"); |
| 1102 | assert!(err.to_string().contains("--parent-death-watch"), "{err:#}"); |
| 1103 | |
| 1104 | let cli = parse_cli(&["codewhale", "exec", "explain", "this"]); |
| 1105 | let Some(Commands::Exec(args)) = cli.command else { |
| 1106 | panic!("expected exec command"); |
| 1107 | }; |
| 1108 | assert_eq!( |
| 1109 | resolve_exec_prompt(&args).expect("argv prompt"), |
| 1110 | "explain this" |
| 1111 | ); |
| 1112 | |
| 1113 | // A positional `-` is prompt text, never a stdin read: cloud dispatch |
| 1114 | // passes job prompts verbatim as argv. |
| 1115 | let cli = parse_cli(&["codewhale", "exec", "--auto", "-"]); |
| 1116 | let Some(Commands::Exec(args)) = cli.command else { |
| 1117 | panic!("expected exec command"); |
| 1118 | }; |
| 1119 | assert_eq!(resolve_exec_prompt(&args).expect("literal dash"), "-"); |
| 1120 | } |
| 1121 | |
| 1122 | #[test] |
| 1123 | fn read_capped_text_names_the_limit_in_bytes() { |
| 1124 | let err = |
| 1125 | read_capped_text(&b"abcdef"[..], 4, "exec prompt on stdin").expect_err("over the cap"); |
| 1126 | assert_eq!( |
| 1127 | err.to_string(), |
| 1128 | "exec prompt on stdin exceeds the 4-byte limit" |
| 1129 | ); |
| 1130 | assert_eq!( |
| 1131 | read_capped_text(&b"abcd"[..], 4, "x").expect("at the cap"), |
| 1132 | "abcd" |
| 1133 | ); |
| 1134 | } |
| 1135 | |
| 1136 | #[test] |
| 1137 | fn exec_parses_provider_flag_alongside_model() { |
| 1138 | // #4093: Fleet threads `--provider <id>` so a worker launches on its |
| 1139 | // profile-pinned provider even when the parent session is elsewhere. |
| 1140 | let cli = parse_cli(&[ |
| 1141 | "codewhale", |
| 1142 | "exec", |
| 1143 | "--provider", |
| 1144 | "openrouter", |
| 1145 | "--model", |
| 1146 | "glm-5.2", |
| 1147 | "audit", |
| 1148 | ]); |
| 1149 | let Some(Commands::Exec(args)) = cli.command else { |
| 1150 | panic!("expected exec command"); |
| 1151 | }; |
| 1152 | |
| 1153 | assert_eq!(args.provider.as_deref(), Some("openrouter")); |
| 1154 | assert_eq!(args.model.as_deref(), Some("glm-5.2")); |
| 1155 | assert_eq!(args.prompt, vec!["audit"]); |
| 1156 | // The threaded id round-trips through the provider vocabulary the exec |
| 1157 | // handler validates against — never a model-id sniff (EPIC #2608). |
| 1158 | assert_eq!( |
| 1159 | codewhale_config::ProviderKind::parse(args.provider.as_deref().unwrap()), |
| 1160 | Some(codewhale_config::ProviderKind::Openrouter) |
| 1161 | ); |
| 1162 | } |
| 1163 | |
| 1164 | #[test] |
| 1165 | fn exec_provider_override_accepts_configured_custom_provider() { |
| 1166 | let mut custom = std::collections::HashMap::new(); |
| 1167 | custom.insert( |
| 1168 | "lm-studio".to_string(), |
| 1169 | codewhale_runtime::config::ProviderConfig { |
| 1170 | kind: Some("openai-compatible".to_string()), |
| 1171 | base_url: Some("http://127.0.0.1:1234/v1".to_string()), |
| 1172 | model: Some("qwen-2.5-7b".to_string()), |
| 1173 | api_key: Some("lm-studio".to_string()), |
| 1174 | ..Default::default() |
| 1175 | }, |
| 1176 | ); |
| 1177 | let mut config = { |
| 1178 | let __cw_config_init_16_0 = Some("deepseek".to_string()); |
| 1179 | let __cw_config_init_16_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1180 | custom, |
| 1181 | ..Default::default() |
| 1182 | }); |
| 1183 | let mut __cw_config_init_16_value: Config = Default::default(); |
| 1184 | __cw_config_init_16_value.provider = __cw_config_init_16_0; |
| 1185 | __cw_config_init_16_value.providers = __cw_config_init_16_1; |
| 1186 | __cw_config_init_16_value |
| 1187 | }; |
| 1188 | |
| 1189 | apply_exec_provider_override(&mut config, "lm-studio") |
| 1190 | .expect("configured custom provider should be accepted"); |
| 1191 | |
| 1192 | assert_eq!(config.provider.as_deref(), Some("lm-studio")); |
| 1193 | assert_eq!( |
| 1194 | config.active_provider_identity().unwrap().provider, |
| 1195 | codewhale_config::ProviderKind::Custom |
| 1196 | ); |
| 1197 | } |
| 1198 | |
| 1199 | #[test] |
| 1200 | fn exec_provider_override_prefers_exact_case_colliding_custom_key() { |
| 1201 | let mut config = { |
| 1202 | let __cw_config_init_17_0 = Some("deepseek".to_string()); |
| 1203 | let __cw_config_init_17_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1204 | custom: std::collections::HashMap::from([( |
| 1205 | "CUSTOM".to_string(), |
| 1206 | codewhale_runtime::config::ProviderConfig { |
| 1207 | kind: Some("openai-compatible".to_string()), |
| 1208 | base_url: Some("http://127.0.0.1:5678/v1".to_string()), |
| 1209 | model: Some("case-model".to_string()), |
| 1210 | api_key: Some("case-key".to_string()), |
| 1211 | ..Default::default() |
| 1212 | }, |
| 1213 | )]), |
| 1214 | ..Default::default() |
| 1215 | }); |
| 1216 | let mut __cw_config_init_17_value: Config = Default::default(); |
| 1217 | __cw_config_init_17_value.provider = __cw_config_init_17_0; |
| 1218 | __cw_config_init_17_value.providers = __cw_config_init_17_1; |
| 1219 | __cw_config_init_17_value |
| 1220 | }; |
| 1221 | |
| 1222 | apply_exec_provider_override(&mut config, "CUSTOM") |
| 1223 | .expect("exact case-colliding custom provider"); |
| 1224 | assert_eq!(config.provider.as_deref(), Some("CUSTOM")); |
| 1225 | assert_eq!( |
| 1226 | config.active_provider_identity().unwrap().provider, |
| 1227 | codewhale_config::ProviderKind::Custom |
| 1228 | ); |
| 1229 | assert_eq!( |
| 1230 | config.active_provider_identity().unwrap().key.as_str(), |
| 1231 | "CUSTOM" |
| 1232 | ); |
| 1233 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 1234 | &config, |
| 1235 | codewhale_config::ProviderKind::Custom, |
| 1236 | Some("case-model"), |
| 1237 | ) |
| 1238 | .expect("resolve exact case-colliding route") |
| 1239 | .validate() |
| 1240 | .expect("preflight exact case-colliding route"); |
| 1241 | assert_eq!(route.identity.key.as_str(), "CUSTOM"); |
| 1242 | assert_eq!(route.client.base_url(), "http://127.0.0.1:5678/v1"); |
| 1243 | } |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn exec_provider_override_rejects_unknown_provider() { |
| 1247 | let mut config = { |
| 1248 | let __cw_config_init_18_0 = Some("deepseek".to_string()); |
| 1249 | let mut __cw_config_init_18_value: Config = Default::default(); |
| 1250 | __cw_config_init_18_value.provider = __cw_config_init_18_0; |
| 1251 | __cw_config_init_18_value |
| 1252 | }; |
| 1253 | |
| 1254 | let err = apply_exec_provider_override(&mut config, "lm-studio") |
| 1255 | .expect_err("unconfigured custom provider should fail closed"); |
| 1256 | let message = err.to_string(); |
| 1257 | |
| 1258 | assert!(message.contains("Unrecognized --provider")); |
| 1259 | assert!(message.contains("[providers.<name>] custom provider")); |
| 1260 | assert_eq!(config.provider.as_deref(), Some("deepseek")); |
| 1261 | } |
| 1262 | |
| 1263 | #[test] |
| 1264 | fn exec_resume_route_matrix_preserves_or_overrides_exact_provider_deliberately() { |
| 1265 | let saved = saved_exec_session( |
| 1266 | "custom-a", |
| 1267 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 1268 | ); |
| 1269 | |
| 1270 | let mut restored = custom_exec_config("custom-b"); |
| 1271 | let model = resolve_exec_resume_route(&mut restored, &saved, false, None) |
| 1272 | .expect("plain resume restores saved route"); |
| 1273 | assert_eq!(restored.provider.as_deref(), Some("custom-a")); |
| 1274 | assert_eq!( |
| 1275 | model, |
| 1276 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 1277 | ); |
| 1278 | |
| 1279 | let mut explicit_provider = custom_exec_config("custom-a"); |
| 1280 | apply_exec_provider_override(&mut explicit_provider, "custom-b").expect("custom B"); |
| 1281 | let model = resolve_exec_resume_route(&mut explicit_provider, &saved, true, None) |
| 1282 | .expect("explicit provider wins"); |
| 1283 | assert_eq!(explicit_provider.provider.as_deref(), Some("custom-b")); |
| 1284 | assert_eq!(model, "model-b"); |
| 1285 | |
| 1286 | let mut explicit_model = custom_exec_config("custom-b"); |
| 1287 | let model = |
| 1288 | resolve_exec_resume_route(&mut explicit_model, &saved, false, Some("override-model")) |
| 1289 | .expect("explicit model keeps saved provider"); |
| 1290 | assert_eq!(explicit_model.provider.as_deref(), Some("custom-a")); |
| 1291 | assert_eq!(model, "override-model"); |
| 1292 | |
| 1293 | let mut missing = custom_exec_config("custom-b"); |
| 1294 | missing |
| 1295 | .providers |
| 1296 | .as_mut() |
| 1297 | .expect("providers") |
| 1298 | .custom |
| 1299 | .remove("custom-a"); |
| 1300 | let before = missing.provider.clone(); |
| 1301 | let err = resolve_exec_resume_route(&mut missing, &saved, false, None) |
| 1302 | .expect_err("removed saved provider must fail closed"); |
| 1303 | assert!(err.to_string().contains("will not fall back"), "{err}"); |
| 1304 | assert_eq!(missing.provider, before); |
| 1305 | } |
| 1306 | |
| 1307 | #[test] |
| 1308 | fn exec_resume_honours_dispatcher_forwarded_launch_overrides() { |
| 1309 | // `codewhale --provider X --model Y exec --resume ID ...` reaches this |
| 1310 | // binary with X/Y only in CODEWHALE_PROVIDER / CODEWHALE_MODEL; a |
| 1311 | // resume must treat them as explicit instead of restoring the saved |
| 1312 | // route. |
| 1313 | assert_eq!( |
| 1314 | exec_resume_route_overrides(None, None, None, None), |
| 1315 | (false, None) |
| 1316 | ); |
| 1317 | assert_eq!( |
| 1318 | exec_resume_route_overrides(None, None, Some("modelstudio-token-plan"), None), |
| 1319 | (true, None) |
| 1320 | ); |
| 1321 | assert_eq!( |
| 1322 | exec_resume_route_overrides(None, None, None, Some("qwen3.8-flash")), |
| 1323 | (false, Some("qwen3.8-flash".to_string())) |
| 1324 | ); |
| 1325 | assert_eq!( |
| 1326 | exec_resume_route_overrides( |
| 1327 | None, |
| 1328 | None, |
| 1329 | Some("modelstudio-token-plan"), |
| 1330 | Some(" qwen3.8-flash ") |
| 1331 | ), |
| 1332 | (true, Some("qwen3.8-flash".to_string())) |
| 1333 | ); |
| 1334 | // Exec-level flags still win over the forwarded launch env. |
| 1335 | assert_eq!( |
| 1336 | exec_resume_route_overrides( |
| 1337 | Some("deepseek"), |
| 1338 | Some("deepseek-v4-pro"), |
| 1339 | Some("x"), |
| 1340 | Some("y") |
| 1341 | ), |
| 1342 | (true, Some("deepseek-v4-pro".to_string())) |
| 1343 | ); |
| 1344 | // Blank values are not overrides. |
| 1345 | assert_eq!( |
| 1346 | exec_resume_route_overrides(None, None, Some(" "), Some("")), |
| 1347 | (false, None) |
| 1348 | ); |
| 1349 | |
| 1350 | let saved = saved_exec_session( |
| 1351 | "custom-a", |
| 1352 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 1353 | ); |
| 1354 | let mut launch_model_only = custom_exec_config("custom-b"); |
| 1355 | let (explicit_provider, explicit_model) = |
| 1356 | exec_resume_route_overrides(None, None, None, Some("override-model")); |
| 1357 | let model = resolve_exec_resume_route( |
| 1358 | &mut launch_model_only, |
| 1359 | &saved, |
| 1360 | explicit_provider, |
| 1361 | explicit_model.as_deref(), |
| 1362 | ) |
| 1363 | .expect("launch model override keeps saved provider"); |
| 1364 | assert_eq!(launch_model_only.provider.as_deref(), Some("custom-a")); |
| 1365 | assert_eq!(model, "override-model"); |
| 1366 | |
| 1367 | let mut launch_provider = custom_exec_config("custom-b"); |
| 1368 | let (explicit_provider, explicit_model) = |
| 1369 | exec_resume_route_overrides(None, None, Some("custom-b"), None); |
| 1370 | let model = resolve_exec_resume_route( |
| 1371 | &mut launch_provider, |
| 1372 | &saved, |
| 1373 | explicit_provider, |
| 1374 | explicit_model.as_deref(), |
| 1375 | ) |
| 1376 | .expect("launch provider override keeps the launched route"); |
| 1377 | assert_eq!(launch_provider.provider.as_deref(), Some("custom-b")); |
| 1378 | assert_eq!(model, "model-b"); |
| 1379 | } |
| 1380 | |
| 1381 | #[test] |
| 1382 | fn exec_resume_uses_dispatcher_env_route_loaded_by_config() { |
| 1383 | // Exercise the production sequence without starting an Engine turn: |
| 1384 | // `Config::load` applies the dispatcher-forwarded environment, then |
| 1385 | // the resume seam must treat the same launch env as explicit and skip |
| 1386 | // the unavailable persisted route rather than restoring it. |
| 1387 | let _env_lock = crate::test_support::lock_test_env(); |
| 1388 | let _legacy_provider = crate::test_support::EnvVarGuard::remove("DEEPSEEK_PROVIDER"); |
| 1389 | let _legacy_model = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MODEL"); |
| 1390 | let _provider = crate::test_support::EnvVarGuard::set("CODEWHALE_PROVIDER", "launch-route"); |
| 1391 | let _model = crate::test_support::EnvVarGuard::set("CODEWHALE_MODEL", "dispatcher-model"); |
| 1392 | let tmp = tempfile::tempdir().expect("config tempdir"); |
| 1393 | let codewhale_home = tmp.path().join("codewhale-home"); |
| 1394 | std::fs::create_dir_all(&codewhale_home).expect("isolated Codewhale home"); |
| 1395 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 1396 | let config_path = tmp.path().join("config.toml"); |
| 1397 | std::fs::write( |
| 1398 | &config_path, |
| 1399 | r#"provider = "stored-route" |
| 1400 | |
| 1401 | [providers.launch-route] |
| 1402 | kind = "openai-compatible" |
| 1403 | base_url = "https://launch.example.test/v1" |
| 1404 | model = "configured-launch-model" |
| 1405 | api_key = "test-only-key" |
| 1406 | "#, |
| 1407 | ) |
| 1408 | .expect("write config"); |
| 1409 | |
| 1410 | let mut config = codewhale_plugins::providers::load_config(Some(config_path), None) |
| 1411 | .expect("load launch config"); |
| 1412 | assert_eq!(config.provider.as_deref(), Some("launch-route")); |
| 1413 | assert_eq!(config.default_model(), "dispatcher-model"); |
| 1414 | |
| 1415 | // The saved route deliberately has no live config table. This control |
| 1416 | // proves that a non-explicit resume would fail closed instead of |
| 1417 | // silently falling back; the dispatcher overrides must prevent that |
| 1418 | // restore attempt. |
| 1419 | let saved = saved_exec_session("stored-route", "stored-model"); |
| 1420 | let mut restore_attempt = config.clone(); |
| 1421 | let restore_error = resolve_exec_resume_route(&mut restore_attempt, &saved, false, None) |
| 1422 | .expect_err("unavailable saved route must not be restored"); |
| 1423 | assert!( |
| 1424 | restore_error.to_string().contains("stored-route"), |
| 1425 | "{restore_error}" |
| 1426 | ); |
| 1427 | |
| 1428 | let (explicit_provider, explicit_model) = exec_resume_route_overrides( |
| 1429 | None, |
| 1430 | None, |
| 1431 | codewhale_runtime::config::explicit_launch_provider_override().as_deref(), |
| 1432 | codewhale_runtime::config::explicit_launch_model_override().as_deref(), |
| 1433 | ); |
| 1434 | assert!(explicit_provider); |
| 1435 | assert_eq!(explicit_model.as_deref(), Some("dispatcher-model")); |
| 1436 | |
| 1437 | let model = resolve_exec_resume_route( |
| 1438 | &mut config, |
| 1439 | &saved, |
| 1440 | explicit_provider, |
| 1441 | explicit_model.as_deref(), |
| 1442 | ) |
| 1443 | .expect("dispatcher environment must keep the launch route on resume"); |
| 1444 | assert_eq!(config.provider.as_deref(), Some("launch-route")); |
| 1445 | assert_eq!(model, "dispatcher-model"); |
| 1446 | } |
| 1447 | |
| 1448 | #[test] |
| 1449 | fn exec_model_reads_wait_for_foreign_test_env_overrides_to_restore() { |
| 1450 | let (started_tx, started_rx) = std::sync::mpsc::channel(); |
| 1451 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1452 | |
| 1453 | let (reader, expected_after_restore) = { |
| 1454 | let lock = crate::test_support::lock_test_env(); |
| 1455 | let expected_after_restore = exec_model_env_override(); |
| 1456 | let temporary = crate::test_support::EnvVarGuard::set("CODEWHALE_MODEL", "temporary-model"); |
| 1457 | let reader = std::thread::spawn(move || { |
| 1458 | started_tx.send(()).expect("signal model read start"); |
| 1459 | tx.send(exec_model_env_override()) |
| 1460 | .expect("send resolved model override"); |
| 1461 | }); |
| 1462 | |
| 1463 | started_rx |
| 1464 | .recv_timeout(std::time::Duration::from_secs(2)) |
| 1465 | .expect("reader reached model read"); |
| 1466 | assert!( |
| 1467 | rx.recv_timeout(std::time::Duration::from_millis(50)) |
| 1468 | .is_err(), |
| 1469 | "a foreign reader observed another test's temporary model override" |
| 1470 | ); |
| 1471 | drop(temporary); |
| 1472 | drop(lock); |
| 1473 | (reader, expected_after_restore) |
| 1474 | }; |
| 1475 | |
| 1476 | let observed = rx |
| 1477 | .recv_timeout(std::time::Duration::from_secs(2)) |
| 1478 | .expect("reader resumed after model override was restored"); |
| 1479 | reader.join().expect("reader thread"); |
| 1480 | assert_eq!(observed, expected_after_restore); |
| 1481 | } |
| 1482 | |
| 1483 | #[tokio::test] |
| 1484 | async fn no_flag_exec_keeps_configured_named_custom_route_for_matching_builtin_model() { |
| 1485 | let mut config = custom_exec_config("custom-a"); |
| 1486 | config |
| 1487 | .providers |
| 1488 | .as_mut() |
| 1489 | .expect("providers") |
| 1490 | .custom |
| 1491 | .get_mut("custom-a") |
| 1492 | .expect("custom A") |
| 1493 | .model = |
| 1494 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string()); |
| 1495 | let model = resolve_exec_model(&config, None); |
| 1496 | let force = should_force_configured_exec_route(false, None, None); |
| 1497 | |
| 1498 | assert!(force, "configured/default exec route must be authoritative"); |
| 1499 | assert!(!should_force_configured_exec_route( |
| 1500 | false, |
| 1501 | None, |
| 1502 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL) |
| 1503 | )); |
| 1504 | assert!(should_force_configured_exec_route( |
| 1505 | false, |
| 1506 | Some("custom-a"), |
| 1507 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL) |
| 1508 | )); |
| 1509 | assert!(should_force_configured_exec_route( |
| 1510 | true, |
| 1511 | None, |
| 1512 | Some("override-model") |
| 1513 | )); |
| 1514 | |
| 1515 | let route = resolve_cli_exec_route(&config, &model, "audit", force, None) |
| 1516 | .await |
| 1517 | .expect("no-flag configured route"); |
| 1518 | let execution = config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 1519 | assert_eq!( |
| 1520 | route.provider.provider, |
| 1521 | codewhale_config::ProviderKind::Custom |
| 1522 | ); |
| 1523 | assert_eq!( |
| 1524 | route.model, |
| 1525 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 1526 | ); |
| 1527 | assert_eq!(execution.provider.as_deref(), Some("custom-a")); |
| 1528 | } |
| 1529 | |
| 1530 | #[tokio::test] |
| 1531 | async fn configured_review_default_keeps_named_custom_route_and_exact_receipt() { |
| 1532 | let mut config = custom_exec_config("custom-a"); |
| 1533 | config |
| 1534 | .providers |
| 1535 | .as_mut() |
| 1536 | .expect("providers") |
| 1537 | .custom |
| 1538 | .get_mut("custom-a") |
| 1539 | .expect("custom A") |
| 1540 | .model = Some("model-a".to_string()); |
| 1541 | config.default_text_model = Some("stale-root-deepseek-model".to_string()); |
| 1542 | let model = resolve_review_model(&config, None); |
| 1543 | assert_eq!(model, "model-a"); |
| 1544 | assert_eq!( |
| 1545 | resolve_review_model(&config, Some("explicit-review-model")), |
| 1546 | "explicit-review-model" |
| 1547 | ); |
| 1548 | |
| 1549 | let route = resolve_cli_exec_route(&config, &model, "review diff", true, None) |
| 1550 | .await |
| 1551 | .expect("configured review route"); |
| 1552 | let execution = config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 1553 | let identity = execution.active_provider_identity().unwrap(); |
| 1554 | let provider = identity.key.as_str(); |
| 1555 | |
| 1556 | assert_eq!( |
| 1557 | route.provider.provider, |
| 1558 | codewhale_config::ProviderKind::Custom |
| 1559 | ); |
| 1560 | assert_eq!(provider, "custom-a"); |
| 1561 | assert_eq!( |
| 1562 | execution.active_route_base_url(), |
| 1563 | "http://127.0.0.1:18181/v1" |
| 1564 | ); |
| 1565 | let output = codewhale_engine::tools::review::ReviewOutput::parse("{}"); |
| 1566 | let receipt = codewhale_engine::tools::review::build_review_receipt( |
| 1567 | "working tree", |
| 1568 | "diff --git a/a b/a", |
| 1569 | provider, |
| 1570 | &route.model, |
| 1571 | &output, |
| 1572 | "{}", |
| 1573 | Vec::new(), |
| 1574 | ); |
| 1575 | assert_eq!(receipt.provider, "custom-a"); |
| 1576 | let serialized = serde_json::to_string(&receipt).expect("review receipt"); |
| 1577 | assert!(!serialized.contains("127.0.0.1")); |
| 1578 | assert!(!serialized.contains("local-test-key")); |
| 1579 | } |
| 1580 | |
| 1581 | fn review_args(argv: &[&str]) -> ReviewArgs { |
| 1582 | let cli = parse_cli(argv); |
| 1583 | let Some(Commands::Review(args)) = cli.command else { |
| 1584 | panic!("expected review command"); |
| 1585 | }; |
| 1586 | args |
| 1587 | } |
| 1588 | |
| 1589 | #[test] |
| 1590 | fn review_parses_provider_flag_alongside_model() { |
| 1591 | let args = review_args(&[ |
| 1592 | "codewhale", |
| 1593 | "review", |
| 1594 | "--pr", |
| 1595 | "5709", |
| 1596 | "--provider", |
| 1597 | "zai", |
| 1598 | "--model", |
| 1599 | "GLM-5.3", |
| 1600 | ]); |
| 1601 | |
| 1602 | assert_eq!(args.provider.as_deref(), Some("zai")); |
| 1603 | assert_eq!(args.model.as_deref(), Some("GLM-5.3")); |
| 1604 | assert_eq!(args.pr, Some(5709)); |
| 1605 | assert_eq!(args.max_passes, 1); |
| 1606 | // The threaded id round-trips through the provider vocabulary the |
| 1607 | // override validates against — never a model-id sniff. |
| 1608 | assert_eq!( |
| 1609 | codewhale_config::ProviderKind::parse(args.provider.as_deref().unwrap()), |
| 1610 | Some(codewhale_config::ProviderKind::Zai) |
| 1611 | ); |
| 1612 | } |
| 1613 | |
| 1614 | #[test] |
| 1615 | fn review_batch_passes_require_explicit_bounded_opt_in() { |
| 1616 | let args = review_args(&["codewhale", "review", "--pr", "6002", "--max-passes", "31"]); |
| 1617 | assert_eq!(args.max_passes, 31); |
| 1618 | assert!(validate_review_receipt_args(&args).is_ok()); |
| 1619 | let too_many = review_args(&["codewhale", "review", "--pr", "6002", "--max-passes", "65"]); |
| 1620 | assert!(validate_review_receipt_args(&too_many).is_err()); |
| 1621 | let local = review_args(&["codewhale", "review", "--max-passes", "2"]); |
| 1622 | assert!(validate_review_receipt_args(&local).is_err()); |
| 1623 | } |
| 1624 | |
| 1625 | #[test] |
| 1626 | fn review_failure_payload_preserves_usage_without_complete_claim() { |
| 1627 | let usage = codewhale_models::Usage { |
| 1628 | input_tokens: 24, |
| 1629 | output_tokens: 4, |
| 1630 | reasoning_tokens: Some(3), |
| 1631 | ..Default::default() |
| 1632 | }; |
| 1633 | let payload = review_failure_payload( |
| 1634 | "fixture-provider", |
| 1635 | "fixture-model", |
| 1636 | &usage, |
| 1637 | 1, |
| 1638 | 2, |
| 1639 | ReviewPublication::NotAttempted, |
| 1640 | "second pass malformed", |
| 1641 | ); |
| 1642 | assert_eq!(payload["success"], false); |
| 1643 | assert_eq!(payload["complete"], false); |
| 1644 | assert_eq!(payload["completed_review_passes"], 1); |
| 1645 | assert_eq!(payload["planned_review_passes"], 2); |
| 1646 | assert_eq!(payload["publication"], "not_attempted"); |
| 1647 | assert_eq!(payload["usage_scope"], "completed_review_passes"); |
| 1648 | assert_eq!(payload["usage_coverage"], "incomplete"); |
| 1649 | assert_eq!(payload["usage"]["input_tokens"], 24); |
| 1650 | assert_eq!(payload["usage"]["reasoning_tokens"], 3); |
| 1651 | assert!(payload.get("review").is_none()); |
| 1652 | assert!(payload.get("receipt").is_none()); |
| 1653 | } |
| 1654 |