| 1 | #[test] |
| 2 | fn default_active_contract_keeps_discovery_and_core_tools_eager() { |
| 3 | const EXPECTED_NATIVE: [&str; 12] = [ |
| 4 | "read", |
| 5 | "write", |
| 6 | "edit", |
| 7 | "list_dir", |
| 8 | "file_search", |
| 9 | "grep_files", |
| 10 | "bash", |
| 11 | "agent", |
| 12 | "todo_write", |
| 13 | "create_goal", |
| 14 | "present", |
| 15 | "load_skill", |
| 16 | ]; |
| 17 | assert_eq!( |
| 18 | default_active_native_tool_names(), |
| 19 | EXPECTED_NATIVE.as_slice() |
| 20 | ); |
| 21 | |
| 22 | let always_load = HashSet::new(); |
| 23 | let mut catalog = build_model_tool_catalog( |
| 24 | EXPECTED_NATIVE.into_iter().map(api_tool).collect(), |
| 25 | Vec::new(), |
| 26 | AppMode::Agent, |
| 27 | &always_load, |
| 28 | ); |
| 29 | ensure_advanced_tooling( |
| 30 | &mut catalog, |
| 31 | AppMode::Agent, |
| 32 | &always_load, |
| 33 | crate::core::engine::tool_catalog::ToolMode::Direct, |
| 34 | ); |
| 35 | let active = initial_active_tools(&catalog); |
| 36 | let expected = EXPECTED_NATIVE |
| 37 | .into_iter() |
| 38 | .chain([TOOL_SEARCH_NAME]) |
| 39 | .map(str::to_string) |
| 40 | .collect::<HashSet<_>>(); |
| 41 | |
| 42 | assert_eq!(active, expected); |
| 43 | assert_eq!( |
| 44 | catalog |
| 45 | .iter() |
| 46 | .find(|tool| tool.name == TOOL_SEARCH_NAME) |
| 47 | .and_then(|tool| tool.defer_loading), |
| 48 | Some(false) |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | #[test] |
| 53 | fn non_yolo_mode_retains_default_defer_policy() { |
| 54 | let always_load = HashSet::new(); |
| 55 | for core in [ |
| 56 | "read", |
| 57 | "write", |
| 58 | "edit", |
| 59 | "bash", |
| 60 | "agent", |
| 61 | "todo_write", |
| 62 | "load_skill", |
| 63 | ] { |
| 64 | assert!(!should_default_defer_tool(core, &always_load)); |
| 65 | } |
| 66 | for searchable in [ |
| 67 | "Bash", |
| 68 | "File", |
| 69 | "Git", |
| 70 | "Run", |
| 71 | "remember", |
| 72 | REQUEST_USER_INPUT_NAME, |
| 73 | "read_file", |
| 74 | "edit_file", |
| 75 | "apply_patch", |
| 76 | "git_status", |
| 77 | "git_blame", |
| 78 | "run_tests", |
| 79 | "web_search", |
| 80 | ] { |
| 81 | assert!(should_default_defer_tool(searchable, &always_load)); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | #[test] |
| 86 | fn default_defer_lookup_matches_linear_scan_over_active_native_tools() { |
| 87 | // Parity guard for #4152: `should_default_defer_tool` now consults an O(1) |
| 88 | // side set built from DEFAULT_ACTIVE_NATIVE_TOOLS instead of a linear |
| 89 | // `.iter().any(...)` scan. Assert the set returns the SAME hit/miss as an |
| 90 | // explicit linear scan over the ordered array — every array member is a hit |
| 91 | // (not deferred); names outside the array miss (deferred by default). |
| 92 | let always_load = HashSet::new(); |
| 93 | let active = default_active_native_tool_names(); |
| 94 | |
| 95 | for name in active { |
| 96 | // Reference linear scan == what the converted lookup must agree with. |
| 97 | let linear_hit = active.iter().any(|core| core == name); |
| 98 | assert!(linear_hit, "reference scan should find array member {name}"); |
| 99 | assert!( |
| 100 | !should_default_defer_tool(name, &always_load), |
| 101 | "array member {name} must stay active (not deferred)" |
| 102 | ); |
| 103 | } |
| 104 | |
| 105 | for name in [ |
| 106 | "git_blame", |
| 107 | "task_shell_start", |
| 108 | REQUEST_USER_INPUT_NAME, |
| 109 | "definitely_not_a_tool", |
| 110 | ] { |
| 111 | let linear_hit = active.contains(&name); |
| 112 | assert!(!linear_hit, "non-member {name} should be absent from array"); |
| 113 | assert!( |
| 114 | should_default_defer_tool(name, &always_load), |
| 115 | "non-member {name} must default to deferred" |
| 116 | ); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn model_tool_catalog_applies_native_and_mcp_deferral() { |
| 122 | let always_load = HashSet::new(); |
| 123 | let catalog = build_model_tool_catalog( |
| 124 | vec![ |
| 125 | api_tool("read"), |
| 126 | api_tool("write"), |
| 127 | api_tool("edit"), |
| 128 | api_tool("bash"), |
| 129 | api_tool("agent"), |
| 130 | api_tool("Git"), |
| 131 | api_tool("Run"), |
| 132 | api_tool("remember"), |
| 133 | api_tool("tui_help"), |
| 134 | ], |
| 135 | vec![api_tool("list_mcp_resources"), api_tool("mcp_server_write")], |
| 136 | AppMode::Agent, |
| 137 | &always_load, |
| 138 | ); |
| 139 | |
| 140 | let defer_loading = |name: &str| { |
| 141 | catalog |
| 142 | .iter() |
| 143 | .find(|tool| tool.name == name) |
| 144 | .and_then(|tool| tool.defer_loading) |
| 145 | }; |
| 146 | |
| 147 | for core in ["read", "write", "edit", "bash", "agent"] { |
| 148 | assert_eq!(defer_loading(core), Some(false)); |
| 149 | } |
| 150 | assert_eq!(defer_loading("Git"), Some(true)); |
| 151 | assert_eq!(defer_loading("Run"), Some(true)); |
| 152 | assert_eq!(defer_loading("remember"), Some(true)); |
| 153 | assert_eq!(defer_loading("tui_help"), Some(true)); |
| 154 | assert_eq!(defer_loading("list_mcp_resources"), Some(true)); |
| 155 | assert_eq!(defer_loading("mcp_server_write"), Some(true)); |
| 156 | } |
| 157 | |
| 158 | #[test] |
| 159 | fn registry_sync_results_are_bounded_like_every_other_tool() { |
| 160 | // The full-catalog bypass is gone: an oversized registry payload flows |
| 161 | // through the same route budget as any other tool result. |
| 162 | let budget = crate::route_budget::route_inline_char_budget_for_route( |
| 163 | ProviderKind::Deepseek, |
| 164 | "small-context-model", |
| 165 | None, |
| 166 | ); |
| 167 | let raw = format!( |
| 168 | "{{\"instruction\":\"compare all\",\"servers\":[{{\"name\":\"{}\"}}]}}", |
| 169 | "a".repeat(budget + 1_000), |
| 170 | ); |
| 171 | let output = ToolResult::success(raw.clone()); |
| 172 | |
| 173 | let context = compact_tool_result_for_route( |
| 174 | ProviderKind::Deepseek, |
| 175 | "small-context-model", |
| 176 | None, |
| 177 | "registry_sync", |
| 178 | &output, |
| 179 | ); |
| 180 | |
| 181 | assert_ne!(context, raw); |
| 182 | assert!(context.chars().count() <= budget); |
| 183 | assert!(context.contains(codewhale_tools::names::SPILLOVER_RECOVERY_HINT)); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn capability_compact_surface_defers_nonessential_core_tools() { |
| 188 | let always_load = HashSet::new(); |
| 189 | let catalog = build_model_tool_catalog_with_surface( |
| 190 | vec![ |
| 191 | api_tool("read"), |
| 192 | api_tool("write"), |
| 193 | api_tool("edit"), |
| 194 | api_tool("bash"), |
| 195 | api_tool("agent"), |
| 196 | api_tool("Git"), |
| 197 | api_tool("Run"), |
| 198 | api_tool("update_plan"), |
| 199 | api_tool("Web"), |
| 200 | ], |
| 201 | vec![api_tool("list_mcp_resources"), api_tool("mcp_server_write")], |
| 202 | AppMode::Agent, |
| 203 | &always_load, |
| 204 | crate::model_profile::ToolSurfaceBudget::Compact, |
| 205 | ); |
| 206 | |
| 207 | let defer_loading = |name: &str| { |
| 208 | catalog |
| 209 | .iter() |
| 210 | .find(|tool| tool.name == name) |
| 211 | .and_then(|tool| tool.defer_loading) |
| 212 | }; |
| 213 | |
| 214 | for core in ["read", "write", "edit", "bash", "agent"] { |
| 215 | assert_eq!(defer_loading(core), Some(false)); |
| 216 | } |
| 217 | assert_eq!(defer_loading("Git"), Some(true)); |
| 218 | assert_eq!(defer_loading("update_plan"), Some(true)); |
| 219 | assert_eq!(defer_loading("list_mcp_resources"), Some(true)); |
| 220 | assert_eq!(defer_loading("Run"), Some(true)); |
| 221 | assert_eq!(defer_loading("Web"), Some(true)); |
| 222 | assert_eq!(defer_loading("mcp_server_write"), Some(true)); |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn capability_full_surface_preserves_small_default_head() { |
| 227 | let always_load = HashSet::new(); |
| 228 | let catalog = build_model_tool_catalog_with_surface( |
| 229 | vec![ |
| 230 | api_tool("read"), |
| 231 | api_tool("write"), |
| 232 | api_tool("edit"), |
| 233 | api_tool("bash"), |
| 234 | api_tool("agent"), |
| 235 | api_tool("Run"), |
| 236 | ], |
| 237 | Vec::new(), |
| 238 | AppMode::Agent, |
| 239 | &always_load, |
| 240 | crate::model_profile::ToolSurfaceBudget::Full, |
| 241 | ); |
| 242 | |
| 243 | for name in ["read", "write", "edit", "bash", "agent"] { |
| 244 | assert_eq!( |
| 245 | catalog |
| 246 | .iter() |
| 247 | .find(|tool| tool.name == name) |
| 248 | .and_then(|tool| tool.defer_loading), |
| 249 | Some(false), |
| 250 | "{name} should stay eager on full tool surfaces" |
| 251 | ); |
| 252 | } |
| 253 | assert_eq!( |
| 254 | catalog |
| 255 | .iter() |
| 256 | .find(|tool| tool.name == "Run") |
| 257 | .and_then(|tool| tool.defer_loading), |
| 258 | Some(true) |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn plugin_or_benchmark_tools_remain_searchable_not_eager() { |
| 264 | let always_load = HashSet::new(); |
| 265 | let mut catalog = build_model_tool_catalog( |
| 266 | vec![api_tool("KB_search"), api_tool("read")], |
| 267 | Vec::new(), |
| 268 | AppMode::Agent, |
| 269 | &always_load, |
| 270 | ); |
| 271 | |
| 272 | ensure_advanced_tooling( |
| 273 | &mut catalog, |
| 274 | AppMode::Agent, |
| 275 | &always_load, |
| 276 | crate::core::engine::tool_catalog::ToolMode::Direct, |
| 277 | ); |
| 278 | |
| 279 | let active = initial_active_tools(&catalog); |
| 280 | assert!(!active.contains("KB_search")); |
| 281 | assert!(active.contains("read")); |
| 282 | assert_eq!( |
| 283 | catalog |
| 284 | .iter() |
| 285 | .find(|tool| tool.name == "KB_search") |
| 286 | .and_then(|tool| tool.defer_loading), |
| 287 | Some(true) |
| 288 | ); |
| 289 | } |
| 290 | |
| 291 | #[tokio::test] |
| 292 | async fn registry_discovery_and_start_handlers_exist_in_agent_and_plan_modes() { |
| 293 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 294 | engine.ensure_mcp_pool().await.expect("initialize MCP pool"); |
| 295 | |
| 296 | for mode in [AppMode::Agent, AppMode::Plan] { |
| 297 | let registry = engine |
| 298 | .build_turn_tool_registry_builder(mode, engine.config.todos.clone()) |
| 299 | .build(engine.build_tool_context(mode, false)); |
| 300 | assert!(registry.contains("registry_sync"), "missing in {mode:?}"); |
| 301 | assert!(registry.contains("read_media"), "missing in {mode:?}"); |
| 302 | let media_tools = registry |
| 303 | .to_api_tools_with_cache(true) |
| 304 | .into_iter() |
| 305 | .filter(|tool| tool.name == "read_media") |
| 306 | .collect::<Vec<_>>(); |
| 307 | assert_eq!( |
| 308 | media_tools.len(), |
| 309 | 1, |
| 310 | "read_media must be registered exactly once in {mode:?}" |
| 311 | ); |
| 312 | assert_eq!( |
| 313 | media_tools[0].defer_loading, |
| 314 | Some(true), |
| 315 | "read_media must remain default-off/deferred in {mode:?}" |
| 316 | ); |
| 317 | assert!( |
| 318 | registry.contains("start_registry_mcp_server"), |
| 319 | "missing in {mode:?}" |
| 320 | ); |
| 321 | assert!(!registry.contains("registry_install_run_info")); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn catalog_consistency_self_check_flags_registered_core_tool_missing_from_catalog() { |
| 327 | let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 328 | let registry = engine |
| 329 | .build_turn_tool_registry_builder(AppMode::Agent, engine.config.todos.clone()) |
| 330 | .build(engine.build_tool_context(AppMode::Agent, false)); |
| 331 | let always_load = HashSet::new(); |
| 332 | let mut catalog = build_model_tool_catalog( |
| 333 | registry.to_api_tools_with_cache(true), |
| 334 | vec![], |
| 335 | AppMode::Agent, |
| 336 | &always_load, |
| 337 | ); |
| 338 | catalog.retain(|tool| tool.name != "read"); |
| 339 | |
| 340 | let issues = tool_catalog_consistency_issues(&catalog, ®istry); |
| 341 | assert!( |
| 342 | issues |
| 343 | .iter() |
| 344 | .any(|issue| issue.contains("registered core tool 'read'")), |
| 345 | "missing registered read should be reported: {issues:?}" |
| 346 | ); |
| 347 | } |
| 348 | |
| 349 | fn assert_exec_shell_is_not_discoverable(match_kind: &str) { |
| 350 | let catalog = vec![api_tool("read_file")]; |
| 351 | let mut active = initial_active_tools(&catalog); |
| 352 | |
| 353 | let result = execute_tool_search( |
| 354 | TOOL_SEARCH_NAME, |
| 355 | &json!({ "query": "exec_shell", "match": match_kind }), |
| 356 | &catalog, |
| 357 | &mut active, |
| 358 | ) |
| 359 | .expect("tool search succeeds"); |
| 360 | |
| 361 | assert!(!active.contains("exec_shell")); |
| 362 | let metadata = result.metadata.as_ref().expect("search metadata"); |
| 363 | let references = metadata["tool_references"] |
| 364 | .as_array() |
| 365 | .expect("tool references are an array"); |
| 366 | assert!( |
| 367 | references |
| 368 | .iter() |
| 369 | .all(|reference| reference.as_str() != Some("exec_shell")), |
| 370 | "legacy shell alias must not surface via {match_kind}: {references:?}" |
| 371 | ); |
| 372 | let unavailable = metadata["unavailable_tool_references"] |
| 373 | .as_array() |
| 374 | .expect("unavailable references are an array"); |
| 375 | assert!( |
| 376 | unavailable |
| 377 | .iter() |
| 378 | .all(|reference| reference["tool_name"].as_str() != Some("exec_shell")), |
| 379 | "legacy shell alias must not surface as an unavailable fallback via {match_kind}: {unavailable:?}" |
| 380 | ); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn regex_tool_search_does_not_discover_hidden_exec_shell_alias() { |
| 385 | assert_exec_shell_is_not_discoverable("regex"); |
| 386 | } |
| 387 | |
| 388 | #[test] |
| 389 | fn bm25_tool_search_does_not_discover_hidden_exec_shell_alias() { |
| 390 | assert_exec_shell_is_not_discoverable("bm25"); |
| 391 | } |
| 392 | |
| 393 | #[test] |
| 394 | fn tools_always_scenario() { |
| 395 | // Scenario consolidation of: tools_always_load_overrides_mcp_deferral, tools_always_load_overrides_default_native_deferral |
| 396 | // from tools_always_load_overrides_mcp_deferral |
| 397 | { |
| 398 | let always_load = HashSet::from(["mcp_server_write".to_string()]); |
| 399 | let catalog = build_model_tool_catalog( |
| 400 | vec![api_tool("read_file")], |
| 401 | vec![api_tool("mcp_server_write")], |
| 402 | AppMode::Agent, |
| 403 | &always_load, |
| 404 | ); |
| 405 | let mcp = catalog |
| 406 | .iter() |
| 407 | .find(|tool| tool.name == "mcp_server_write") |
| 408 | .expect("mcp tool"); |
| 409 | assert_eq!(mcp.defer_loading, Some(false)); |
| 410 | } |
| 411 | // from tools_always_load_overrides_default_native_deferral |
| 412 | { |
| 413 | let always_load = HashSet::from(["git_blame".to_string()]); |
| 414 | assert!(!should_default_defer_tool("git_blame", &always_load)); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | fn tool_catalog_surface_metrics(catalog: &[Tool]) -> serde_json::Value { |
| 419 | let serialized = serde_json::to_vec(catalog).expect("serialize canonical tool catalog"); |
| 420 | let mut tool_names = catalog |
| 421 | .iter() |
| 422 | .map(|tool| tool.name.clone()) |
| 423 | .collect::<Vec<_>>(); |
| 424 | tool_names.sort(); |
| 425 | let identity_sha256 = codewhale_runtime::hashing::sha256_hex(tool_names.join("\0").as_bytes()); |
| 426 | serde_json::json!({ |
| 427 | "tools": catalog.len(), |
| 428 | "bytes": serialized.len(), |
| 429 | "tokens_est": serialized.len().div_ceil(4), |
| 430 | "tool_names": tool_names, |
| 431 | "identity_sha256": identity_sha256, |
| 432 | }) |
| 433 | } |
| 434 | |
| 435 | async fn measure_production_mode_tool_catalogs() -> serde_json::Value { |
| 436 | let _env_lock = lock_test_env(); |
| 437 | let tmp = tempdir().expect("tempdir"); |
| 438 | let home = tmp.path().join("home"); |
| 439 | fs::create_dir_all(&home).expect("create isolated home"); |
| 440 | let _home = EnvVarGuard::set("HOME", &home); |
| 441 | let _userprofile = EnvVarGuard::set("USERPROFILE", &home); |
| 442 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 443 | // Interpreter-backed advanced tools are intentionally excluded from this |
| 444 | // cross-platform built-in profile. Pin host capabilities because Windows |
| 445 | // system-directory lookup can find interpreters outside PATH. Keep the |
| 446 | // nonexistent PATH root for the canonical shell spelling below. |
| 447 | let _host_tools = codewhale_dependencies::pin_recorded_host_tools(Vec::new()); |
| 448 | let _path = EnvVarGuard::set("PATH", tmp.path().join("no-host-interpreters")); |
| 449 | // Shell syntax is part of the tool schema. A bare name plus the empty |
| 450 | // PATH resolves to the same `bash` spelling on Unix and Windows without |
| 451 | // executing or requiring that interpreter. Do not inherit the host shell. |
| 452 | let _shell = EnvVarGuard::set("SHELL", "bash"); |
| 453 | // Keep the explicit OCR-unavailable environment for framework probes that |
| 454 | // ignore PATH; the host capability pin above also excludes local OCR from |
| 455 | // this profile. |
| 456 | let _ocr = EnvVarGuard::set("CODEWHALE_LOCAL_OCR_UNAVAILABLE", "1"); |
| 457 | |
| 458 | let api_config = { |
| 459 | let __cw_config_init_0_0 = Some(DEFAULT_TEXT_MODEL.to_string()); |
| 460 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 461 | __cw_config_init_0_value.default_text_model = __cw_config_init_0_0; |
| 462 | __cw_config_init_0_value |
| 463 | } |
| 464 | .with_legacy_root(Some("local-runtime-contract-fixture".to_string()), None); |
| 465 | let mut mode_metrics = serde_json::Map::new(); |
| 466 | for (mode_name, mode) in [ |
| 467 | ("plan", AppMode::Plan), |
| 468 | ("act", AppMode::Agent), |
| 469 | ("operate", AppMode::Agent), |
| 470 | ] { |
| 471 | let workspace = tmp.path().join(mode_name); |
| 472 | fs::create_dir_all(&workspace).expect("create isolated mode workspace"); |
| 473 | let engine_config = EngineConfig { |
| 474 | workspace, |
| 475 | allow_shell: true, |
| 476 | ..EngineConfig::default() |
| 477 | }; |
| 478 | let (mut engine, _handle) = Engine::new(engine_config, &api_config); |
| 479 | // MCP catalogs depend on configured external servers. This receipt owns |
| 480 | // the canonical provider-free built-in profile and exercises the same |
| 481 | // production builder/planner with MCP explicitly disabled. |
| 482 | engine.config.features.disable(Feature::Mcp); |
| 483 | let route = TurnRouteContext { |
| 484 | provider: ProviderKind::Deepseek, |
| 485 | model: DEFAULT_TEXT_MODEL.to_string(), |
| 486 | capabilities: codewhale_config::route::RouteCapabilities::default(), |
| 487 | limits: None, |
| 488 | client: engine.codewhale_client.clone(), |
| 489 | api_config: Box::new(api_config.clone()), |
| 490 | locale_tag: engine.config.locale_tag.clone(), |
| 491 | role_models: engine.subagent_role_models(), |
| 492 | auto_model: false, |
| 493 | reasoning_effort: None, |
| 494 | reasoning_effort_auto: false, |
| 495 | }; |
| 496 | let policy = crate::core::authority::TurnAuthority::from_effective_fields( |
| 497 | mode, |
| 498 | true, |
| 499 | false, |
| 500 | false, |
| 501 | ApprovalMode::Suggest, |
| 502 | ); |
| 503 | let build = engine |
| 504 | .build_turn_tool_registry_and_catalog( |
| 505 | &policy, |
| 506 | &[], |
| 507 | None, |
| 508 | SubAgentWiring::Inert, |
| 509 | McpAccess::PassiveSnapshot, |
| 510 | &[], |
| 511 | route, |
| 512 | "", |
| 513 | ) |
| 514 | .await; |
| 515 | let active = build.surface.active.clone().unwrap_or_default(); |
| 516 | mode_metrics.insert( |
| 517 | mode_name.to_string(), |
| 518 | serde_json::json!({ |
| 519 | "full": tool_catalog_surface_metrics(&super::tool_catalog::mode_visible_catalog( |
| 520 | &build.surface.catalog, |
| 521 | mode, |
| 522 | )), |
| 523 | "active": tool_catalog_surface_metrics(&active), |
| 524 | }), |
| 525 | ); |
| 526 | } |
| 527 | |
| 528 | serde_json::json!({ |
| 529 | "surface_profile": "production-default-builtins-no-mcp-no-host-interpreters-bash-v2", |
| 530 | "execution_shell": codewhale_sandbox::shell_dispatcher::global_dispatcher().kind().binary(), |
| 531 | "modes": mode_metrics, |
| 532 | }) |
| 533 | } |
| 534 | |
| 535 | fn metric_tool_names<'a>( |
| 536 | payload: &'a serde_json::Value, |
| 537 | mode: &str, |
| 538 | surface: &str, |
| 539 | ) -> HashSet<&'a str> { |
| 540 | payload["modes"][mode][surface]["tool_names"] |
| 541 | .as_array() |
| 542 | .expect("tool names array") |
| 543 | .iter() |
| 544 | .map(|name| name.as_str().expect("tool name string")) |
| 545 | .collect() |
| 546 | } |
| 547 | |
| 548 | #[tokio::test] |
| 549 | #[allow(clippy::await_holding_lock)] |
| 550 | async fn runtime_contract_tool_metric_uses_canonical_mode_surfaces() { |
| 551 | let payload = measure_production_mode_tool_catalogs().await; |
| 552 | let expected_active = HashSet::from([ |
| 553 | "agent", |
| 554 | "create_goal", |
| 555 | "edit", |
| 556 | "file_search", |
| 557 | "grep_files", |
| 558 | "list_dir", |
| 559 | "read", |
| 560 | "todo_write", |
| 561 | "write", |
| 562 | "load_skill", |
| 563 | "present", |
| 564 | ]); |
| 565 | |
| 566 | for mode in ["plan", "act", "operate"] { |
| 567 | let full = metric_tool_names(&payload, mode, "full"); |
| 568 | for required in [ |
| 569 | "read", |
| 570 | "write", |
| 571 | "edit", |
| 572 | "agent", |
| 573 | "workflow", |
| 574 | "create_goal", |
| 575 | "get_goal", |
| 576 | "update_goal", |
| 577 | ] { |
| 578 | assert!(full.contains(required), "{mode} must include {required}"); |
| 579 | } |
| 580 | for hidden in ["File", "Bash", "read_file", "write_file", "edit_file"] { |
| 581 | assert!(!full.contains(hidden), "{mode} must hide {hidden}"); |
| 582 | } |
| 583 | // #6562: `[features] code_mode` defaults on, so Plan, Act, and Operate |
| 584 | // promote `execute_tools` into the request head in place of `tool_search`. |
| 585 | assert!( |
| 586 | full.contains("execute_tools"), |
| 587 | "{mode} must include execute_tools" |
| 588 | ); |
| 589 | assert!( |
| 590 | !full.contains("tool_search"), |
| 591 | "{mode} offers tool_search only without execute_tools" |
| 592 | ); |
| 593 | let mut expected_mode_active = expected_active.clone(); |
| 594 | expected_mode_active.insert("execute_tools"); |
| 595 | if mode != "plan" { |
| 596 | expected_mode_active.insert("bash"); |
| 597 | } |
| 598 | assert_eq!( |
| 599 | metric_tool_names(&payload, mode, "active"), |
| 600 | expected_mode_active, |
| 601 | "{mode} must expose the expected request head" |
| 602 | ); |
| 603 | } |
| 604 | |
| 605 | let plan = metric_tool_names(&payload, "plan", "full"); |
| 606 | for forbidden in ["bash", "Run", "fim_edit", "verify"] { |
| 607 | assert!(!plan.contains(forbidden), "Plan must exclude {forbidden}"); |
| 608 | } |
| 609 | |
| 610 | for mode in ["act", "operate"] { |
| 611 | let full = metric_tool_names(&payload, mode, "full"); |
| 612 | for required in ["bash", "Run"] { |
| 613 | assert!(full.contains(required), "{mode} must include {required}"); |
| 614 | } |
| 615 | assert!(!full.contains("verify"), "{mode} must exclude verify"); |
| 616 | assert!( |
| 617 | !full.contains("fim_edit"), |
| 618 | "{mode} must exclude FIM on its unsupported route" |
| 619 | ); |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | #[tokio::test] |
| 624 | #[ignore = "one-shot tool-catalog metric"] |
| 625 | #[allow(clippy::await_holding_lock)] |
| 626 | #[allow(clippy::print_stdout)] |
| 627 | async fn print_mode_tool_catalog_metrics() { |
| 628 | let metrics = measure_production_mode_tool_catalogs().await; |
| 629 | assert_eq!( |
| 630 | metrics["execution_shell"], "bash", |
| 631 | "run this exact metric in a fresh process so its shell fixture owns dispatcher initialization" |
| 632 | ); |
| 633 | println!("TOOL_CATALOG_METRICS {metrics}"); |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn runtime_contract_tool_metric_is_independent_of_inherited_shell() { |
| 638 | let metric = "core::engine::tests::print_mode_tool_catalog_metrics"; |
| 639 | let samples: Vec<serde_json::Value> = ["/bin/zsh", "pwsh"] |
| 640 | .into_iter() |
| 641 | .map(|shell| { |
| 642 | let output = std::process::Command::new(std::env::current_exe().expect("test binary")) |
| 643 | .args([ |
| 644 | metric, |
| 645 | "--exact", |
| 646 | "--ignored", |
| 647 | "--nocapture", |
| 648 | "--test-threads=1", |
| 649 | ]) |
| 650 | .env("SHELL", shell) |
| 651 | .output() |
| 652 | .expect("run exact metric in a fresh process"); |
| 653 | assert!( |
| 654 | output.status.success(), |
| 655 | "metric failed: {}{}", |
| 656 | String::from_utf8_lossy(&output.stdout), |
| 657 | String::from_utf8_lossy(&output.stderr) |
| 658 | ); |
| 659 | String::from_utf8(output.stdout) |
| 660 | .expect("metric UTF-8") |
| 661 | .lines() |
| 662 | .find_map(|line| { |
| 663 | line.split_once("TOOL_CATALOG_METRICS ") |
| 664 | .map(|(_, payload)| serde_json::from_str(payload).expect("metric JSON")) |
| 665 | }) |
| 666 | .expect("metric marker") |
| 667 | }) |
| 668 | .collect(); |
| 669 | assert_eq!(samples[0], samples[1], "host shell changed the fixture"); |
| 670 | assert_eq!(samples[0]["execution_shell"], "bash"); |
| 671 | } |
| 672 | |
| 673 | #[test] |
| 674 | #[ignore = "one-shot metric for scripts/measure-runtime-contract.py"] |
| 675 | #[allow(clippy::print_stdout)] |
| 676 | fn print_mode_runtime_contract_metrics() { |
| 677 | let _env_lock = lock_test_env(); |
| 678 | let tmp = tempdir().expect("tempdir"); |
| 679 | let workspace = tmp.path().join("workspace"); |
| 680 | let home = tmp.path().join("home"); |
| 681 | fs::create_dir_all(&workspace).expect("create isolated workspace"); |
| 682 | fs::create_dir_all(&home).expect("create isolated home"); |
| 683 | let _home = EnvVarGuard::set("HOME", &home); |
| 684 | let _userprofile = EnvVarGuard::set("USERPROFILE", &home); |
| 685 | let codewhale_home = home.join(".codewhale"); |
| 686 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 687 | // Pin host facts independently of platform-specific shell detection and |
| 688 | // process-wide dispatcher initialization in other tests. |
| 689 | let _environment = crate::prompts::pin_recorded_environment("linux", "/bin/bash"); |
| 690 | let _shell = EnvVarGuard::set("SHELL", "/bin/bash"); |
| 691 | let mut mode_metrics = serde_json::Map::new(); |
| 692 | for (mode_name, mode) in [ |
| 693 | ("plan", AppMode::Plan), |
| 694 | ("act", AppMode::Agent), |
| 695 | ("operate", AppMode::Agent), |
| 696 | ] { |
| 697 | let prompt = system_prompt_for_mode_with_context_skills_and_session( |
| 698 | &workspace, |
| 699 | None, |
| 700 | None, |
| 701 | None, |
| 702 | PromptSessionContext { |
| 703 | mode, |
| 704 | ..PromptSessionContext::default() |
| 705 | }, |
| 706 | ); |
| 707 | let prompt_bytes = system_prompt_flat_text(&prompt).len(); |
| 708 | let prompt_blocks = match &prompt { |
| 709 | codewhale_models::SystemPrompt::Blocks(blocks) => blocks.len(), |
| 710 | _ => 1, |
| 711 | }; |
| 712 | mode_metrics.insert( |
| 713 | mode_name.to_string(), |
| 714 | serde_json::json!({ |
| 715 | "system_prompt_bytes": prompt_bytes, |
| 716 | "system_prompt_tokens_est": prompt_bytes.div_ceil(4), |
| 717 | "system_prompt_blocks": prompt_blocks, |
| 718 | "mode_instructions_bytes": 0, |
| 719 | "mode_instructions_tokens_est": 0, |
| 720 | }), |
| 721 | ); |
| 722 | } |
| 723 | |
| 724 | println!( |
| 725 | "RUNTIME_CONTRACT_METRICS {}", |
| 726 | serde_json::json!({ |
| 727 | "modes": mode_metrics, |
| 728 | }) |
| 729 | ); |
| 730 | } |
| 731 | |
| 732 | fn representative_prompt( |
| 733 | workspace: &Path, |
| 734 | skills_dir: &Path, |
| 735 | instructions: Option<&[InstructionSource]>, |
| 736 | user_memory_block: Option<&str>, |
| 737 | goal_objective: Option<&str>, |
| 738 | ) -> codewhale_models::SystemPrompt { |
| 739 | system_prompt_for_mode_with_context_skills_and_session( |
| 740 | workspace, |
| 741 | None, |
| 742 | Some(skills_dir), |
| 743 | instructions, |
| 744 | PromptSessionContext { |
| 745 | user_memory_block, |
| 746 | goal_objective, |
| 747 | skills_config: std::sync::Arc::new(codewhale_runtime::config::SkillsConfig { |
| 748 | scan_codewhale_only: Some(true), |
| 749 | ..Default::default() |
| 750 | }), |
| 751 | mode: AppMode::Agent, |
| 752 | ..PromptSessionContext::default() |
| 753 | }, |
| 754 | ) |
| 755 | } |
| 756 | |
| 757 | fn prompt_block_count(prompt: &codewhale_models::SystemPrompt) -> usize { |
| 758 | match prompt { |
| 759 | codewhale_models::SystemPrompt::Blocks(blocks) => blocks.len(), |
| 760 | codewhale_models::SystemPrompt::Text(_) => 1, |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | #[derive(Debug)] |
| 765 | struct RepresentativePromptStage { |
| 766 | name: &'static str, |
| 767 | flat: String, |
| 768 | normalized: String, |
| 769 | } |
| 770 | |
| 771 | fn normalize_representative_prompt(text: &str, workspace: &Path, home: &Path) -> String { |
| 772 | let mut replacements = Vec::new(); |
| 773 | for (path, replacement) in [(workspace, "<WORKSPACE>"), (home, "<HOME>")] { |
| 774 | replacements.push((path.to_path_buf(), replacement)); |
| 775 | if let Ok(canonical) = path.canonicalize() { |
| 776 | replacements.push((canonical, replacement)); |
| 777 | } |
| 778 | } |
| 779 | replacements.sort_by(|(left, _), (right, _)| { |
| 780 | right |
| 781 | .to_string_lossy() |
| 782 | .len() |
| 783 | .cmp(&left.to_string_lossy().len()) |
| 784 | .then_with(|| left.cmp(right)) |
| 785 | }); |
| 786 | replacements.dedup_by(|(left, _), (right, _)| left == right); |
| 787 | |
| 788 | let normalized = |
| 789 | replacements |
| 790 | .into_iter() |
| 791 | .fold(text.to_string(), |normalized, (path, replacement)| { |
| 792 | normalized.replace(path.to_string_lossy().as_ref(), replacement) |
| 793 | }); |
| 794 | // Platform remains an actionable host fact in the stable environment |
| 795 | // block. Pin it so this fixture measures prompt structure across hosts. |
| 796 | normalized.replace("- platform: linux", "- platform: <PLATFORM>") |
| 797 | } |
| 798 | |
| 799 | fn representative_stage( |
| 800 | name: &'static str, |
| 801 | prompt: codewhale_models::SystemPrompt, |
| 802 | workspace: &Path, |
| 803 | home: &Path, |
| 804 | ) -> RepresentativePromptStage { |
| 805 | let flat = system_prompt_flat_text(&prompt); |
| 806 | let normalized = normalize_representative_prompt(&flat, workspace, home); |
| 807 | RepresentativePromptStage { |
| 808 | name, |
| 809 | flat, |
| 810 | normalized, |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | fn measure_representative_runtime_context() |
| 815 | -> (serde_json::Value, Vec<RepresentativePromptStage>, String) { |
| 816 | let _env_lock = lock_test_env(); |
| 817 | let tmp = tempdir().expect("tempdir"); |
| 818 | let workspace = tmp.path().join("workspace"); |
| 819 | let home = tmp.path().join("home"); |
| 820 | let skills_dir = workspace.join(".codewhale").join("skills"); |
| 821 | fs::create_dir_all(&workspace).expect("create isolated workspace"); |
| 822 | fs::create_dir_all(&home).expect("create isolated home"); |
| 823 | |
| 824 | let _home = EnvVarGuard::set("HOME", &home); |
| 825 | let _userprofile = EnvVarGuard::set("USERPROFILE", &home); |
| 826 | let codewhale_home = home.join(".codewhale"); |
| 827 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 828 | // Pin host facts independently of platform-specific shell detection and |
| 829 | // process-wide dispatcher initialization in other tests. |
| 830 | let _environment = crate::prompts::pin_recorded_environment("linux", "/bin/bash"); |
| 831 | let _shell = EnvVarGuard::set("SHELL", "/bin/bash"); |
| 832 | // The fixture measures a trusted repository: project skills load only in |
| 833 | // a trusted workspace, and the skill stage exists to measure one. |
| 834 | crate::test_support::trust_workspace(&workspace); |
| 835 | |
| 836 | let mut stages = vec![representative_stage( |
| 837 | "base", |
| 838 | representative_prompt(&workspace, &skills_dir, None, None, None), |
| 839 | &workspace, |
| 840 | &home, |
| 841 | )]; |
| 842 | |
| 843 | fs::write( |
| 844 | workspace.join("AGENTS.md"), |
| 845 | REPRESENTATIVE_PROJECT_AUTHORITY_BODY, |
| 846 | ) |
| 847 | .expect("write representative project authority"); |
| 848 | stages.push(representative_stage( |
| 849 | "project", |
| 850 | representative_prompt(&workspace, &skills_dir, None, None, None), |
| 851 | &workspace, |
| 852 | &home, |
| 853 | )); |
| 854 | |
| 855 | let instructions = [InstructionSource::Inline { |
| 856 | name: "embedded:representative-v1".to_string(), |
| 857 | content: REPRESENTATIVE_INLINE_INSTRUCTIONS.to_string(), |
| 858 | }]; |
| 859 | stages.push(representative_stage( |
| 860 | "instructions", |
| 861 | representative_prompt(&workspace, &skills_dir, Some(&instructions), None, None), |
| 862 | &workspace, |
| 863 | &home, |
| 864 | )); |
| 865 | |
| 866 | let skill_dir = skills_dir.join("representative-skill"); |
| 867 | fs::create_dir_all(&skill_dir).expect("create representative skill directory"); |
| 868 | fs::write( |
| 869 | skill_dir.join("SKILL.md"), |
| 870 | format!( |
| 871 | "---\nname: representative-skill\ndescription: {REPRESENTATIVE_SKILL_DESCRIPTION}\n---\nExercise the deterministic runtime-contract fixture.\n" |
| 872 | ), |
| 873 | ) |
| 874 | .expect("write representative skill"); |
| 875 | stages.push(representative_stage( |
| 876 | "skill", |
| 877 | representative_prompt(&workspace, &skills_dir, Some(&instructions), None, None), |
| 878 | &workspace, |
| 879 | &home, |
| 880 | )); |
| 881 | |
| 882 | let memory_block = format!("## Memory\n\n- {REPRESENTATIVE_MEMORY_CHECKPOINT}"); |
| 883 | stages.push(representative_stage( |
| 884 | "memory", |
| 885 | representative_prompt( |
| 886 | &workspace, |
| 887 | &skills_dir, |
| 888 | Some(&instructions), |
| 889 | Some(&memory_block), |
| 890 | None, |
| 891 | ), |
| 892 | &workspace, |
| 893 | &home, |
| 894 | )); |
| 895 | stages.push(representative_stage( |
| 896 | "goal", |
| 897 | representative_prompt( |
| 898 | &workspace, |
| 899 | &skills_dir, |
| 900 | Some(&instructions), |
| 901 | Some(&memory_block), |
| 902 | Some(REPRESENTATIVE_GOAL_OBJECTIVE), |
| 903 | ), |
| 904 | &workspace, |
| 905 | &home, |
| 906 | )); |
| 907 | |
| 908 | fs::write( |
| 909 | workspace.join(crate::prompts::HANDOFF_RELATIVE_PATH), |
| 910 | format!("# Representative Relay\n\n{REPRESENTATIVE_HANDOFF_RELAY}\n"), |
| 911 | ) |
| 912 | .expect("write representative handoff"); |
| 913 | let final_prompt = representative_prompt( |
| 914 | &workspace, |
| 915 | &skills_dir, |
| 916 | Some(&instructions), |
| 917 | Some(&memory_block), |
| 918 | Some(REPRESENTATIVE_GOAL_OBJECTIVE), |
| 919 | ); |
| 920 | let final_blocks = prompt_block_count(&final_prompt); |
| 921 | stages.push(representative_stage( |
| 922 | "handoff", |
| 923 | final_prompt, |
| 924 | &workspace, |
| 925 | &home, |
| 926 | )); |
| 927 | let repeated_flat = system_prompt_flat_text(&representative_prompt( |
| 928 | &workspace, |
| 929 | &skills_dir, |
| 930 | Some(&instructions), |
| 931 | Some(&memory_block), |
| 932 | Some(REPRESENTATIVE_GOAL_OBJECTIVE), |
| 933 | )); |
| 934 | |
| 935 | let mut stage_metrics = serde_json::Map::new(); |
| 936 | for (index, stage) in stages.iter().enumerate() { |
| 937 | let mut metrics = serde_json::json!({ |
| 938 | // Keep byte ceilings host-independent just like the structural |
| 939 | // identity: temporary workspace/home paths vary across runners. |
| 940 | "bytes": stage.normalized.len(), |
| 941 | "identity_sha256": codewhale_runtime::hashing::sha256_hex(stage.normalized.as_bytes()), |
| 942 | }); |
| 943 | if let Some(previous) = index.checked_sub(1).and_then(|i| stages.get(i)) { |
| 944 | metrics["delta_bytes"] = serde_json::json!( |
| 945 | stage |
| 946 | .normalized |
| 947 | .len() |
| 948 | .checked_sub(previous.normalized.len()) |
| 949 | .unwrap_or_else(|| panic!( |
| 950 | "representative {} stage unexpectedly shrank prompt", |
| 951 | stage.name |
| 952 | )) |
| 953 | ); |
| 954 | } |
| 955 | stage_metrics.insert(stage.name.to_string(), metrics); |
| 956 | } |
| 957 | let final_stage = stages.last().expect("handoff stage"); |
| 958 | let payload = serde_json::json!({ |
| 959 | "fixture_id": REPRESENTATIVE_FIXTURE_ID, |
| 960 | "stages": stage_metrics, |
| 961 | "total_bytes": final_stage.normalized.len(), |
| 962 | "total_tokens_est": final_stage.normalized.len().div_ceil(4), |
| 963 | "system_prompt_blocks": final_blocks, |
| 964 | "prompts_byte_identical": final_stage.flat == repeated_flat, |
| 965 | }); |
| 966 | |
| 967 | (payload, stages, repeated_flat) |
| 968 | } |
| 969 | |
| 970 | #[test] |
| 971 | fn representative_runtime_context_fixture_is_stable_and_contains_expected_markers() { |
| 972 | let (payload, stages, repeated_prompt) = measure_representative_runtime_context(); |
| 973 | let (second_payload, second_stages, _) = measure_representative_runtime_context(); |
| 974 | let final_stage = stages.last().expect("handoff stage"); |
| 975 | assert_eq!(payload["fixture_id"], REPRESENTATIVE_FIXTURE_ID); |
| 976 | assert_eq!(final_stage.flat, repeated_prompt); |
| 977 | assert_eq!(payload["prompts_byte_identical"], true); |
| 978 | for (first, second) in stages.iter().zip(&second_stages) { |
| 979 | assert_eq!(first.name, second.name); |
| 980 | assert_eq!(first.normalized, second.normalized); |
| 981 | assert_eq!( |
| 982 | payload["stages"][first.name]["identity_sha256"], |
| 983 | second_payload["stages"][second.name]["identity_sha256"], |
| 984 | "representative {} digest must be stable across temp roots", |
| 985 | first.name |
| 986 | ); |
| 987 | } |
| 988 | for pair in stages.windows(2) { |
| 989 | let [previous, current] = pair else { |
| 990 | unreachable!("stage windows always contain two entries") |
| 991 | }; |
| 992 | assert_eq!( |
| 993 | payload["stages"][current.name]["delta_bytes"], |
| 994 | current.normalized.len() - previous.normalized.len(), |
| 995 | "representative {} delta must be computed from its adjacent stages", |
| 996 | current.name |
| 997 | ); |
| 998 | } |
| 999 | let markers = [ |
| 1000 | REPRESENTATIVE_PROJECT_AUTHORITY, |
| 1001 | REPRESENTATIVE_INLINE_INSTRUCTIONS, |
| 1002 | REPRESENTATIVE_SKILL_DESCRIPTION, |
| 1003 | REPRESENTATIVE_MEMORY_CHECKPOINT, |
| 1004 | REPRESENTATIVE_GOAL_OBJECTIVE, |
| 1005 | REPRESENTATIVE_HANDOFF_RELAY, |
| 1006 | ]; |
| 1007 | for (stage_index, stage) in stages.iter().enumerate() { |
| 1008 | for (marker_index, marker) in markers.iter().enumerate() { |
| 1009 | let expected = usize::from(marker_index > 2 && marker_index < stage_index); |
| 1010 | assert_eq!( |
| 1011 | stage.flat.matches(marker).count(), |
| 1012 | expected, |
| 1013 | "representative {} stage has the wrong count for {marker}", |
| 1014 | stage.name |
| 1015 | ); |
| 1016 | } |
| 1017 | } |
| 1018 | let fixture_sources = [ |
| 1019 | REPRESENTATIVE_PROJECT_AUTHORITY, |
| 1020 | REPRESENTATIVE_INLINE_INSTRUCTIONS, |
| 1021 | REPRESENTATIVE_SKILL_DESCRIPTION, |
| 1022 | REPRESENTATIVE_MEMORY_CHECKPOINT, |
| 1023 | REPRESENTATIVE_GOAL_OBJECTIVE, |
| 1024 | REPRESENTATIVE_HANDOFF_RELAY, |
| 1025 | ] |
| 1026 | .join("\n") |
| 1027 | .to_ascii_lowercase(); |
| 1028 | for secret_shape in ["sk-", "api_key=", "password=", "bearer "] { |
| 1029 | assert!( |
| 1030 | !fixture_sources.contains(secret_shape), |
| 1031 | "representative fixture must not contain secret-shaped values" |
| 1032 | ); |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | #[test] |
| 1037 | #[ignore = "one-shot metric for scripts/measure-runtime-contract.py"] |
| 1038 | #[allow(clippy::print_stdout)] |
| 1039 | fn print_representative_runtime_context_metrics() { |
| 1040 | let (payload, _, _) = measure_representative_runtime_context(); |
| 1041 | println!("REPRESENTATIVE_CONTEXT_METRICS {payload}"); |
| 1042 | } |
| 1043 | |
| 1044 | fn measure_unchanged_prompt_skill_discovery() -> ( |
| 1045 | codewhale_skills::SkillDiscoveryMetrics, |
| 1046 | codewhale_skills::SkillDiscoveryMetrics, |
| 1047 | bool, |
| 1048 | ) { |
| 1049 | let _env_lock = lock_test_env(); |
| 1050 | let tmp = tempdir().expect("tempdir"); |
| 1051 | let workspace = tmp.path().join("workspace"); |
| 1052 | let home = tmp.path().join("home"); |
| 1053 | let skills_dir = workspace.join(".codewhale").join("skills"); |
| 1054 | let skill = skills_dir.join("receipt-demo"); |
| 1055 | fs::create_dir_all(&skill).expect("create skill directory"); |
| 1056 | fs::create_dir_all(&home).expect("create isolated home"); |
| 1057 | fs::write( |
| 1058 | skill.join("SKILL.md"), |
| 1059 | "---\nname: receipt-demo\ndescription: Hermetic measurement skill\n---\nMeasure discovery.\n", |
| 1060 | ) |
| 1061 | .expect("write skill"); |
| 1062 | |
| 1063 | let _home = EnvVarGuard::set("HOME", &home); |
| 1064 | let _userprofile = EnvVarGuard::set("USERPROFILE", &home); |
| 1065 | let codewhale_home = home.join(".codewhale"); |
| 1066 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 1067 | crate::test_support::trust_workspace(&workspace); |
| 1068 | |
| 1069 | codewhale_skills::clear_skill_discovery_cache(); |
| 1070 | codewhale_skills::reset_discovery_metrics(); |
| 1071 | let start = codewhale_skills::discovery_metrics_snapshot(); |
| 1072 | let first_prompt = system_prompt_for_mode_with_context_skills_and_session( |
| 1073 | &workspace, |
| 1074 | None, |
| 1075 | Some(&skills_dir), |
| 1076 | None, |
| 1077 | PromptSessionContext::default(), |
| 1078 | ); |
| 1079 | let after_first = codewhale_skills::discovery_metrics_snapshot(); |
| 1080 | let second_prompt = system_prompt_for_mode_with_context_skills_and_session( |
| 1081 | &workspace, |
| 1082 | None, |
| 1083 | Some(&skills_dir), |
| 1084 | None, |
| 1085 | PromptSessionContext::default(), |
| 1086 | ); |
| 1087 | let after_second = codewhale_skills::discovery_metrics_snapshot(); |
| 1088 | |
| 1089 | let first = after_first.delta_since(start); |
| 1090 | let second = after_second.delta_since(after_first); |
| 1091 | let first_flat = system_prompt_flat_text(&first_prompt); |
| 1092 | let second_flat = system_prompt_flat_text(&second_prompt); |
| 1093 | (first, second, first_flat == second_flat) |
| 1094 | } |
| 1095 | |
| 1096 | #[test] |
| 1097 | fn unchanged_prompt_skill_discovery_baseline_caches_the_second_turn() { |
| 1098 | let (first, second, prompts_byte_identical) = measure_unchanged_prompt_skill_discovery(); |
| 1099 | assert_eq!(first, codewhale_skills::SkillDiscoveryMetrics::default()); |
| 1100 | assert_eq!(second, codewhale_skills::SkillDiscoveryMetrics::default()); |
| 1101 | assert!(prompts_byte_identical); |
| 1102 | } |
| 1103 | |
| 1104 | fn skill_discovery_metric_payload( |
| 1105 | first: codewhale_skills::SkillDiscoveryMetrics, |
| 1106 | second: codewhale_skills::SkillDiscoveryMetrics, |
| 1107 | prompts_byte_identical: bool, |
| 1108 | ) -> serde_json::Value { |
| 1109 | serde_json::json!({ |
| 1110 | "first_delta": { |
| 1111 | "root_discovery_calls": first.root_discovery_calls, |
| 1112 | "directories_visited": first.directories_visited, |
| 1113 | "skill_md_read_attempts": first.skill_md_read_attempts, |
| 1114 | }, |
| 1115 | "second_delta": { |
| 1116 | "root_discovery_calls": second.root_discovery_calls, |
| 1117 | "directories_visited": second.directories_visited, |
| 1118 | "skill_md_read_attempts": second.skill_md_read_attempts, |
| 1119 | }, |
| 1120 | "prompts_byte_identical": prompts_byte_identical, |
| 1121 | }) |
| 1122 | } |
| 1123 | |
| 1124 | #[test] |
| 1125 | fn skill_discovery_metric_payload_accepts_cached_second_turn() { |
| 1126 | let first = codewhale_skills::SkillDiscoveryMetrics { |
| 1127 | root_discovery_calls: 1, |
| 1128 | directories_visited: 1, |
| 1129 | skill_md_read_attempts: 1, |
| 1130 | }; |
| 1131 | let payload = skill_discovery_metric_payload( |
| 1132 | first, |
| 1133 | codewhale_skills::SkillDiscoveryMetrics::default(), |
| 1134 | true, |
| 1135 | ); |
| 1136 | assert_eq!(payload["first_delta"]["root_discovery_calls"], 1); |
| 1137 | assert_eq!(payload["second_delta"]["root_discovery_calls"], 0); |
| 1138 | assert_eq!(payload["second_delta"]["directories_visited"], 0); |
| 1139 | assert_eq!(payload["second_delta"]["skill_md_read_attempts"], 0); |
| 1140 | } |
| 1141 | |
| 1142 | #[test] |
| 1143 | #[ignore = "one-shot metric for scripts/measure-runtime-contract.py"] |
| 1144 | #[allow(clippy::print_stdout)] |
| 1145 | fn print_skill_discovery_turn_metrics() { |
| 1146 | let (first, second, prompts_byte_identical) = measure_unchanged_prompt_skill_discovery(); |
| 1147 | |
| 1148 | println!( |
| 1149 | "SKILL_DISCOVERY_METRICS {}", |
| 1150 | skill_discovery_metric_payload(first, second, prompts_byte_identical) |
| 1151 | ); |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn deferred_first_use_executes_well_formed_calls_and_hydrates_malformed_ones() { |
| 1156 | let mut apply_patch = api_tool("apply_patch"); |
| 1157 | apply_patch.defer_loading = Some(true); |
| 1158 | apply_patch.input_schema = json!({ |
| 1159 | "type": "object", |
| 1160 | "properties": { |
| 1161 | "patch": { "type": "string" } |
| 1162 | }, |
| 1163 | "required": ["patch"] |
| 1164 | }); |
| 1165 | |
| 1166 | let catalog = vec![apply_patch]; |
| 1167 | let active_at_batch_start = HashSet::new(); |
| 1168 | let mut hydrated_this_batch = HashSet::new(); |
| 1169 | // A call already shaped like the unseen schema must not lose its turn. |
| 1170 | assert!( |
| 1171 | maybe_hydrate_requested_deferred_tool( |
| 1172 | "apply_patch", |
| 1173 | &json!({"patch": "*** Begin Patch\n*** End Patch"}), |
| 1174 | &catalog, |
| 1175 | &active_at_batch_start, |
| 1176 | &mut hydrated_this_batch, |
| 1177 | ) |
| 1178 | .is_none(), |
| 1179 | "a well-formed first call executes" |
| 1180 | ); |
| 1181 | assert!( |
| 1182 | hydrated_this_batch.contains("apply_patch"), |
| 1183 | "the executed tool still activates for later requests" |
| 1184 | ); |
| 1185 | |
| 1186 | for malformed in [ |
| 1187 | json!({}), |
| 1188 | json!({"diff": "*** Begin Patch\n*** End Patch"}), |
| 1189 | json!({"patch": "x", "path": "src/lib.rs"}), |
| 1190 | json!("*** Begin Patch"), |
| 1191 | ] { |
| 1192 | let mut hydrated = HashSet::new(); |
| 1193 | let result = maybe_hydrate_requested_deferred_tool( |
| 1194 | "apply_patch", |
| 1195 | &malformed, |
| 1196 | &catalog, |
| 1197 | &active_at_batch_start, |
| 1198 | &mut hydrated, |
| 1199 | ) |
| 1200 | .unwrap_or_else(|| panic!("{malformed} must return the schema instead of executing")); |
| 1201 | assert!(hydrated.contains("apply_patch")); |
| 1202 | assert!(!result.success); |
| 1203 | assert!(result.content.contains("Tool `apply_patch` was deferred")); |
| 1204 | assert!(result.content.contains("patch: string")); |
| 1205 | assert!(result.content.contains("The tool was not executed")); |
| 1206 | let metadata = result.metadata.expect("metadata"); |
| 1207 | assert_eq!(metadata["event"], "tool.schema_hydrated"); |
| 1208 | assert_eq!(metadata["executed"], false); |
| 1209 | assert_eq!(metadata["retry_required"], true); |
| 1210 | } |
| 1211 | |
| 1212 | let mut active_next_batch = active_at_batch_start.clone(); |
| 1213 | active_next_batch.extend(hydrated_this_batch); |
| 1214 | let mut hydrated_next_batch = HashSet::new(); |
| 1215 | assert!( |
| 1216 | maybe_hydrate_requested_deferred_tool( |
| 1217 | "apply_patch", |
| 1218 | &json!({}), |
| 1219 | &catalog, |
| 1220 | &active_next_batch, |
| 1221 | &mut hydrated_next_batch, |
| 1222 | ) |
| 1223 | .is_none(), |
| 1224 | "tools hydrated in a previous batch execute normally, even malformed" |
| 1225 | ); |
| 1226 | } |
| 1227 | |
| 1228 | /// E3: the first call to a deferred tool hydrates its schema and tells the |
| 1229 | /// model to retry. That hint is model-facing; it reaches the model in the |
| 1230 | /// tool result and must not surface as a user status line. |
| 1231 | #[tokio::test] |
| 1232 | #[allow(clippy::await_holding_lock)] |
| 1233 | async fn deferred_tool_first_use_does_not_emit_a_retry_status() { |
| 1234 | use wiremock::matchers::{body_string_contains, method, path}; |
| 1235 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 1236 | |
| 1237 | let _lock = lock_test_env(); |
| 1238 | let workspace = tempdir().expect("tempdir"); |
| 1239 | let server = MockServer::start().await; |
| 1240 | let tool_call_sse = concat!( |
| 1241 | "data: {\"id\":\"chatcmpl-e3\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[", |
| 1242 | "{\"index\":0,\"id\":\"call_e3_map\",\"type\":\"function\",\"function\":{\"name\":\"tui_help\",", |
| 1243 | // Malformed on purpose: a well-formed first call now executes, and |
| 1244 | // this test covers the schema hint returned for a malformed one. |
| 1245 | "\"arguments\":\"{\\\"not_a_tui_help_field\\\":true}\"}}", |
| 1246 | "]},\"finish_reason\":null}]}\n\n", |
| 1247 | "data: {\"id\":\"chatcmpl-e3\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 1248 | "\"finish_reason\":\"tool_calls\"}]}\n\n", |
| 1249 | "data: [DONE]\n\n", |
| 1250 | ); |
| 1251 | let done_sse = concat!( |
| 1252 | "data: {\"id\":\"chatcmpl-e3-done\",\"choices\":[{\"index\":0,", |
| 1253 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 1254 | "data: {\"id\":\"chatcmpl-e3-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 1255 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 1256 | "data: [DONE]\n\n", |
| 1257 | ); |
| 1258 | Mock::given(method("POST")) |
| 1259 | .and(path("/v1/chat/completions")) |
| 1260 | .and(body_string_contains("call_e3_map")) |
| 1261 | .respond_with( |
| 1262 | ResponseTemplate::new(200) |
| 1263 | .insert_header("content-type", "text/event-stream") |
| 1264 | .set_body_string(done_sse), |
| 1265 | ) |
| 1266 | .with_priority(1) |
| 1267 | .mount(&server) |
| 1268 | .await; |
| 1269 | Mock::given(method("POST")) |
| 1270 | .and(path("/v1/chat/completions")) |
| 1271 | .respond_with( |
| 1272 | ResponseTemplate::new(200) |
| 1273 | .insert_header("content-type", "text/event-stream") |
| 1274 | .set_body_string(tool_call_sse), |
| 1275 | ) |
| 1276 | .expect(1) |
| 1277 | .with_priority(2) |
| 1278 | .mount(&server) |
| 1279 | .await; |
| 1280 | |
| 1281 | let api_config = |
| 1282 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 1283 | let (engine, handle) = Engine::new( |
| 1284 | EngineConfig { |
| 1285 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 1286 | workspace: workspace.path().to_path_buf(), |
| 1287 | snapshots_enabled: false, |
| 1288 | subagents_enabled: false, |
| 1289 | terminal_chrome_enabled: false, |
| 1290 | ..EngineConfig::default() |
| 1291 | }, |
| 1292 | &api_config, |
| 1293 | ); |
| 1294 | let run_task = tokio::spawn(engine.run()); |
| 1295 | handle |
| 1296 | .send(Op::SendMessage(TurnSpec { |
| 1297 | profile_constitution: None, |
| 1298 | max_output_tokens: None, |
| 1299 | content: "Map this project".to_string(), |
| 1300 | images: Vec::new(), |
| 1301 | mode: AppMode::Agent, |
| 1302 | route: resolved_route_for_test( |
| 1303 | &api_config, |
| 1304 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 1305 | ), |
| 1306 | compaction: Box::new(CompactionConfig::default()), |
| 1307 | initial_routed_usage: Box::default(), |
| 1308 | goal_objective: None, |
| 1309 | goal_token_budget: None, |
| 1310 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1311 | reasoning_effort: None, |
| 1312 | reasoning_effort_auto: false, |
| 1313 | auto_model: false, |
| 1314 | allow_shell: true, |
| 1315 | trust_mode: false, |
| 1316 | auto_approve: false, |
| 1317 | approval_mode: ApprovalMode::Suggest, |
| 1318 | translation_enabled: false, |
| 1319 | allowed_tools: None, |
| 1320 | dynamic_tools: Vec::new(), |
| 1321 | hook_executor: None, |
| 1322 | verbosity: None, |
| 1323 | provenance: UserInputProvenance::ExternalUser, |
| 1324 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1325 | submission_id: None, |
| 1326 | })) |
| 1327 | .await |
| 1328 | .expect("send model turn"); |
| 1329 | |
| 1330 | let mut hydration_result = None; |
| 1331 | let mut statuses = Vec::new(); |
| 1332 | let mut rx = handle.rx_event.write().await; |
| 1333 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 1334 | .await |
| 1335 | .expect("timed out waiting for turn event") |
| 1336 | { |
| 1337 | match event { |
| 1338 | Event::Status { message, .. } => statuses.push(message), |
| 1339 | Event::ToolCallComplete { name, result, .. } if name == "tui_help" => { |
| 1340 | hydration_result = Some(result); |
| 1341 | } |
| 1342 | Event::TurnComplete { .. } => break, |
| 1343 | _ => {} |
| 1344 | } |
| 1345 | } |
| 1346 | drop(rx); |
| 1347 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1348 | run_task.await.expect("engine task"); |
| 1349 | |
| 1350 | let hydration = hydration_result |
| 1351 | .expect("the deferred call completes") |
| 1352 | .expect("hydration result"); |
| 1353 | assert!( |
| 1354 | hydration.content.contains("was deferred"), |
| 1355 | "the model still gets the retry hint: {}", |
| 1356 | hydration.content |
| 1357 | ); |
| 1358 | assert!( |
| 1359 | statuses |
| 1360 | .iter() |
| 1361 | .all(|status| !status.contains("Loaded deferred tool")), |
| 1362 | "{statuses:?}" |
| 1363 | ); |
| 1364 | } |
| 1365 | |
| 1366 | #[test] |
| 1367 | fn model_tool_catalog_defers_non_core_native_tools_in_act_mode() { |
| 1368 | let always_load = HashSet::new(); |
| 1369 | let catalog = build_model_tool_catalog( |
| 1370 | vec![api_tool("read"), api_tool("tui_help")], |
| 1371 | vec![api_tool("mcp_server_write")], |
| 1372 | AppMode::Agent, |
| 1373 | &always_load, |
| 1374 | ); |
| 1375 | |
| 1376 | let defer_loading = |name: &str| { |
| 1377 | catalog |
| 1378 | .iter() |
| 1379 | .find(|tool| tool.name == name) |
| 1380 | .and_then(|tool| tool.defer_loading) |
| 1381 | }; |
| 1382 | |
| 1383 | assert_eq!(defer_loading("read"), Some(false)); |
| 1384 | assert_eq!(defer_loading("tui_help"), Some(true)); |
| 1385 | assert_eq!(defer_loading("mcp_server_write"), Some(true)); |
| 1386 | } |
| 1387 | |
| 1388 | #[test] |
| 1389 | fn request_user_input_stays_deferred_but_can_be_dynamically_activated() { |
| 1390 | let always_load = HashSet::new(); |
| 1391 | let catalog = build_model_tool_catalog( |
| 1392 | vec![api_tool("read_file"), api_tool(REQUEST_USER_INPUT_NAME)], |
| 1393 | Vec::new(), |
| 1394 | AppMode::Agent, |
| 1395 | &always_load, |
| 1396 | ); |
| 1397 | |
| 1398 | assert_eq!( |
| 1399 | catalog |
| 1400 | .iter() |
| 1401 | .find(|tool| tool.name == REQUEST_USER_INPUT_NAME) |
| 1402 | .and_then(|tool| tool.defer_loading), |
| 1403 | Some(true) |
| 1404 | ); |
| 1405 | |
| 1406 | let mut active = initial_active_tools(&catalog); |
| 1407 | assert!(!active.contains(REQUEST_USER_INPUT_NAME)); |
| 1408 | active.insert(REQUEST_USER_INPUT_NAME.to_string()); |
| 1409 | |
| 1410 | let active_tools = active_tools_for_step(&catalog, &active); |
| 1411 | assert!( |
| 1412 | active_tools |
| 1413 | .iter() |
| 1414 | .any(|tool| tool.name == REQUEST_USER_INPUT_NAME), |
| 1415 | "dynamic active tools should expose the question modal without making it eager by default" |
| 1416 | ); |
| 1417 | } |
| 1418 | |
| 1419 | #[test] |
| 1420 | fn question_tool_survives_the_tool_surface_in_every_posture() { |
| 1421 | // Questions are separate from approval posture: the surface takes no |
| 1422 | // posture input, so Auto-Review offers `request_user_input` exactly like |
| 1423 | // Suggest, Never and Full Access. Only an explicit deny (headless exec's |
| 1424 | // default) withholds it. |
| 1425 | let surface = policy_for_catalog( |
| 1426 | vec![api_tool("read_file"), api_tool(REQUEST_USER_INPUT_NAME)], |
| 1427 | None, |
| 1428 | None, |
| 1429 | ); |
| 1430 | assert!( |
| 1431 | surface |
| 1432 | .catalog |
| 1433 | .iter() |
| 1434 | .any(|tool| tool.name == REQUEST_USER_INPUT_NAME) |
| 1435 | ); |
| 1436 | |
| 1437 | // Headless exec's default deny list; `exec_agent` tests pin that |
| 1438 | // `exec_disallowed_tools(None)` produces it. |
| 1439 | let headless = policy_for_catalog( |
| 1440 | vec![api_tool("read_file"), api_tool(REQUEST_USER_INPUT_NAME)], |
| 1441 | None, |
| 1442 | Some(vec![REQUEST_USER_INPUT_NAME.to_string()]), |
| 1443 | ); |
| 1444 | assert!( |
| 1445 | !headless |
| 1446 | .catalog |
| 1447 | .iter() |
| 1448 | .any(|tool| tool.name == REQUEST_USER_INPUT_NAME) |
| 1449 | ); |
| 1450 | assert!(headless.catalog.iter().any(|tool| tool.name == "read_file")); |
| 1451 | } |
| 1452 | |
| 1453 | #[test] |
| 1454 | fn model_tool_catalog_sorts_each_partition_for_prefix_cache_stability() { |
| 1455 | // Regression for #263: deterministic byte order of the tools array is a |
| 1456 | // hard requirement for DeepSeek's KV prefix cache. Built-ins stay as a |
| 1457 | // contiguous prefix; MCP tools follow. Within each partition: alphabetical. |
| 1458 | let always_load = HashSet::new(); |
| 1459 | let catalog = build_model_tool_catalog( |
| 1460 | vec![ |
| 1461 | api_tool("read_file"), |
| 1462 | api_tool("apply_patch"), |
| 1463 | api_tool("exec_shell"), |
| 1464 | ], |
| 1465 | vec![api_tool("mcp_zoo_b"), api_tool("mcp_aardvark_a")], |
| 1466 | AppMode::Agent, |
| 1467 | &always_load, |
| 1468 | ); |
| 1469 | |
| 1470 | let names: Vec<&str> = catalog.iter().map(|t| t.name.as_str()).collect(); |
| 1471 | assert_eq!( |
| 1472 | names, |
| 1473 | vec![ |
| 1474 | "apply_patch", |
| 1475 | "exec_shell", |
| 1476 | "read_file", |
| 1477 | "mcp_aardvark_a", |
| 1478 | "mcp_zoo_b", |
| 1479 | ], |
| 1480 | "built-ins must be alphabetical and contiguous; MCP tools follow, alphabetical", |
| 1481 | ); |
| 1482 | } |
| 1483 | |
| 1484 | #[test] |
| 1485 | fn active_tool_list_pushes_deferred_activations_to_the_tail() { |
| 1486 | // Regression for #263: when ToolSearch activates a deferred tool mid- |
| 1487 | // session, it must NOT be inserted at its catalog index — that would |
| 1488 | // shift every later tool's byte offset and bust the cached prefix. |
| 1489 | // Deferred-but-now-active tools belong at the tail. |
| 1490 | let mut a = api_tool("a_load_now"); |
| 1491 | a.defer_loading = Some(false); |
| 1492 | let mut search = api_tool("search_via_toolsearch"); |
| 1493 | search.defer_loading = Some(true); |
| 1494 | let mut b = api_tool("b_load_now"); |
| 1495 | b.defer_loading = Some(false); |
| 1496 | |
| 1497 | let catalog = vec![a, search, b]; |
| 1498 | let active: HashSet<String> = ["a_load_now", "search_via_toolsearch", "b_load_now"] |
| 1499 | .into_iter() |
| 1500 | .map(String::from) |
| 1501 | .collect(); |
| 1502 | |
| 1503 | let listed = active_tools_for_step(&catalog, &active); |
| 1504 | let names: Vec<&str> = listed.iter().map(|t| t.name.as_str()).collect(); |
| 1505 | assert_eq!( |
| 1506 | names, |
| 1507 | vec!["a_load_now", "b_load_now", "search_via_toolsearch"], |
| 1508 | "deferred-but-active tools must come after always-loaded tools", |
| 1509 | ); |
| 1510 | } |
| 1511 | |
| 1512 | #[test] |
| 1513 | fn legacy_rlm_actions_are_not_advertised_to_new_model_turns() { |
| 1514 | let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 1515 | let registry = engine |
| 1516 | .build_turn_tool_registry_builder(AppMode::Agent, engine.config.todos.clone()) |
| 1517 | .build(engine.build_tool_context(AppMode::Agent, false)); |
| 1518 | let always_load = HashSet::new(); |
| 1519 | let catalog = build_model_tool_catalog( |
| 1520 | registry.to_api_tools_with_cache(true), |
| 1521 | vec![], |
| 1522 | AppMode::Agent, |
| 1523 | &always_load, |
| 1524 | ); |
| 1525 | let canonical = catalog |
| 1526 | .iter() |
| 1527 | .find(|tool| tool.name == "rlm") |
| 1528 | .expect("canonical rlm tool must be in the model catalog"); |
| 1529 | assert_eq!(canonical.defer_loading, Some(true)); |
| 1530 | for legacy_name in [ |
| 1531 | "rlm_session_objects", |
| 1532 | "rlm_open", |
| 1533 | "rlm_eval", |
| 1534 | "rlm_configure", |
| 1535 | "rlm_close", |
| 1536 | ] { |
| 1537 | assert!( |
| 1538 | !catalog.iter().any(|tool| tool.name == legacy_name), |
| 1539 | "{legacy_name} must remain outside the new-turn model catalog" |
| 1540 | ); |
| 1541 | } |
| 1542 | } |
| 1543 |