| 1 | use super::*; |
| 2 | use serde_json::json; |
| 3 | use tempfile::tempdir; |
| 4 | |
| 5 | #[tokio::test] |
| 6 | async fn lowercase_read_returns_a_typed_image_block() { |
| 7 | let tmp = tempdir().expect("tempdir"); |
| 8 | let path = tmp.path().join("shot.png"); |
| 9 | std::fs::write(&path, crate::image_attach::test_support::PNG_1X1).expect("write png"); |
| 10 | let context = ToolContext::new(tmp.path().to_path_buf()); |
| 11 | |
| 12 | let rich = ReadTool |
| 13 | .execute_rich(json!({ "path": "shot.png" }), &context) |
| 14 | .await |
| 15 | .expect("read image"); |
| 16 | |
| 17 | assert!(rich.result.success); |
| 18 | assert_eq!(rich.content_blocks.len(), 1); |
| 19 | assert!(matches!( |
| 20 | &rich.content_blocks[0], |
| 21 | codewhale_tools::ToolResultContentBlock::Image { mime_type, data } |
| 22 | if mime_type == "image/png" && !data.is_empty() |
| 23 | )); |
| 24 | } |
| 25 | |
| 26 | /// `fuzz` belongs to `apply_patch` alone; `edit_file` must not advertise a |
| 27 | /// parameter it does not implement. |
| 28 | #[test] |
| 29 | fn fuzz_is_advertised_only_for_patch() { |
| 30 | assert_eq!( |
| 31 | crate::tools::apply_patch::ApplyPatchTool.input_schema()["properties"]["fuzz"]["type"], |
| 32 | "integer" |
| 33 | ); |
| 34 | assert!( |
| 35 | EditFileTool.input_schema()["properties"] |
| 36 | .get("fuzz") |
| 37 | .is_none(), |
| 38 | "edit must not advertise a parameter it does not implement" |
| 39 | ); |
| 40 | } |
| 41 | |
| 42 | // === Per-tool parameter validation === |
| 43 | // |
| 44 | // #5209 taught `edit` to refuse a parameter it does not implement. Only |
| 45 | // `edit` learned it, so every other file tool still dropped unknown keys and |
| 46 | // answered anyway: a misspelled `start_line` on `read_file` returned the head |
| 47 | // of the file with nothing in the response admitting the requested window |
| 48 | // was never honored. These cover the refusal on every file tool, and — the |
| 49 | // half that keeps a refusal honest — that each still accepts its full |
| 50 | // legitimate parameter set, optional names and aliases included. |
| 51 | |
| 52 | fn file_tool(action: &str) -> Box<dyn ToolSpec> { |
| 53 | match action { |
| 54 | "read" => Box::new(ReadFileTool), |
| 55 | "list" => Box::new(crate::tools::file::ListDirTool), |
| 56 | "search_name" => Box::new(crate::tools::file_search::FileSearchTool), |
| 57 | "search_content" => Box::new(crate::tools::search::GrepFilesTool), |
| 58 | "write" => Box::new(WriteFileTool), |
| 59 | "edit" => Box::new(EditFileTool), |
| 60 | "patch" => Box::new(crate::tools::apply_patch::ApplyPatchTool), |
| 61 | other => panic!("no file tool for {other}"), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn refusal_name(action: &str) -> &'static str { |
| 66 | match action { |
| 67 | "read" => "read", |
| 68 | "list" => "list_dir", |
| 69 | "search_name" => "file_search", |
| 70 | "search_content" => "grep_files", |
| 71 | "write" => "write", |
| 72 | "edit" => "edit", |
| 73 | "patch" => "apply_patch", |
| 74 | other => panic!("no file tool for {other}"), |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | async fn dispatch( |
| 79 | action: &str, |
| 80 | mut input: Value, |
| 81 | ctx: &ToolContext, |
| 82 | ) -> Result<ToolResult, ToolError> { |
| 83 | input.as_object_mut().expect("object").remove("action"); |
| 84 | file_tool(action).execute(input, ctx).await |
| 85 | } |
| 86 | |
| 87 | /// A workspace with one file, already read, so `edit` and `patch` are |
| 88 | /// past their freshness precondition and reach parameter validation. |
| 89 | async fn workspace() -> (tempfile::TempDir, ToolContext) { |
| 90 | let tmp = tempdir().expect("tempdir"); |
| 91 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 92 | std::fs::write(tmp.path().join("doc.txt"), "alpha\nbeta\ngamma\n").expect("write"); |
| 93 | dispatch("read", json!({"path": "doc.txt"}), &ctx) |
| 94 | .await |
| 95 | .expect("seed read"); |
| 96 | (tmp, ctx) |
| 97 | } |
| 98 | |
| 99 | /// The minimal call that dispatches for each action, in schema order. |
| 100 | fn minimal_calls() -> Vec<(&'static str, Value)> { |
| 101 | vec![ |
| 102 | ("read", json!({"action": "read", "path": "doc.txt"})), |
| 103 | ("list", json!({"action": "list"})), |
| 104 | ( |
| 105 | "search_name", |
| 106 | json!({"action": "search_name", "query": "doc"}), |
| 107 | ), |
| 108 | ( |
| 109 | "search_content", |
| 110 | json!({"action": "search_content", "pattern": "alpha"}), |
| 111 | ), |
| 112 | ( |
| 113 | "write", |
| 114 | json!({"action": "write", "path": "new.txt", "content": "x\n"}), |
| 115 | ), |
| 116 | ( |
| 117 | "edit", |
| 118 | json!({"action": "edit", "path": "doc.txt", "search": "alpha", "replace": "delta"}), |
| 119 | ), |
| 120 | ( |
| 121 | "patch", |
| 122 | json!({"action": "patch", "path": "doc.txt", "patch": "@@ -1,1 +1,1 @@\n-alpha\n+delta\n"}), |
| 123 | ), |
| 124 | ] |
| 125 | } |
| 126 | |
| 127 | fn with_key(mut input: Value, key: &str, value: Value) -> Value { |
| 128 | input |
| 129 | .as_object_mut() |
| 130 | .expect("object") |
| 131 | .insert(key.to_string(), value); |
| 132 | input |
| 133 | } |
| 134 | |
| 135 | /// The gap this closes. A parameter with no known meaning is refused by |
| 136 | /// every file tool, not just `edit`, and the refusal carries the same four |
| 137 | /// facts everywhere: what was wrong, what is allowed, what is required, |
| 138 | /// and that nothing was done. |
| 139 | #[tokio::test] |
| 140 | async fn every_action_refuses_an_unknown_parameter() { |
| 141 | for (action, call) in minimal_calls() { |
| 142 | let (_tmp, ctx) = workspace().await; |
| 143 | let tool = refusal_name(action); |
| 144 | let message = dispatch(action, with_key(call, "bogus_param", json!(true)), &ctx) |
| 145 | .await |
| 146 | .expect_err("an unknown parameter must be refused") |
| 147 | .to_string(); |
| 148 | assert!( |
| 149 | message.contains("bogus_param"), |
| 150 | "{action} must name the offending parameter: {message}" |
| 151 | ); |
| 152 | assert!( |
| 153 | message.contains(&format!("unexpected {tool} parameter")), |
| 154 | "{action} must name the tool that refused: {message}" |
| 155 | ); |
| 156 | assert!( |
| 157 | message.contains("Allowed parameters are"), |
| 158 | "{action} must name the allowed set: {message}" |
| 159 | ); |
| 160 | assert!( |
| 161 | message.contains("Required:"), |
| 162 | "{action} must name the required set: {message}" |
| 163 | ); |
| 164 | assert!( |
| 165 | message.contains("The call was not performed"), |
| 166 | "{action} must deny having done the work: {message}" |
| 167 | ); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// The specific silent wrong answer that motivated this: a misspelled |
| 172 | /// read window used to be dropped, and the head of the file came back |
| 173 | /// under a success receipt as if it were the requested range. |
| 174 | #[tokio::test] |
| 175 | async fn a_misspelled_read_window_is_refused_rather_than_answered_with_the_head() { |
| 176 | let (_tmp, ctx) = workspace().await; |
| 177 | let message = dispatch("read", json!({"path": "doc.txt", "start_lien": 2}), &ctx) |
| 178 | .await |
| 179 | .expect_err("a misspelled window must not silently return the head") |
| 180 | .to_string(); |
| 181 | assert!(message.contains("start_lien"), "{message}"); |
| 182 | assert!(message.contains("`start_line`"), "{message}"); |
| 183 | } |
| 184 | |
| 185 | /// A refusal is only worth having if the legitimate call still lands. |
| 186 | /// Every tool's full parameter set — every optional name included — must |
| 187 | /// survive validation. |
| 188 | #[tokio::test] |
| 189 | async fn every_action_accepts_its_full_legitimate_parameter_set() { |
| 190 | let full: Vec<(&str, Value)> = vec![ |
| 191 | ( |
| 192 | "read", |
| 193 | json!({"action": "read", "path": "doc.txt", "start_line": 1, "max_lines": 2, "pages": "1"}), |
| 194 | ), |
| 195 | ("list", json!({"action": "list", "path": "."})), |
| 196 | ( |
| 197 | "search_name", |
| 198 | json!({"action": "search_name", "query": "doc", "path": ".", "limit": 5, |
| 199 | "extensions": ["txt"], "exclude": ["target/**"]}), |
| 200 | ), |
| 201 | ( |
| 202 | "search_content", |
| 203 | json!({"action": "search_content", "pattern": "alpha", "path": ".", |
| 204 | "include": ["*.txt"], "exclude": ["target/**"], |
| 205 | "replace_default_excludes": false, "mode": "matches", |
| 206 | "context_lines": 1, "case_insensitive": true, "max_results": 5}), |
| 207 | ), |
| 208 | ( |
| 209 | "write", |
| 210 | json!({"action": "write", "path": "new.txt", "content": "x\n"}), |
| 211 | ), |
| 212 | ( |
| 213 | "edit", |
| 214 | json!({"action": "edit", "path": "doc.txt", "search": "alpha", "replace": "delta"}), |
| 215 | ), |
| 216 | ( |
| 217 | "patch", |
| 218 | json!({"action": "patch", "path": "doc.txt", |
| 219 | "patch": "@@ -1,1 +1,1 @@\n-alpha\n+delta\n", |
| 220 | "fuzz": 3, "create_if_missing": false}), |
| 221 | ), |
| 222 | ]; |
| 223 | |
| 224 | for (action, call) in full { |
| 225 | let (_tmp, ctx) = workspace().await; |
| 226 | let result = dispatch(action, call, &ctx) |
| 227 | .await |
| 228 | .unwrap_or_else(|error| panic!("{action} must accept its own parameters: {error}")); |
| 229 | assert!(result.success, "{action}: {}", result.content); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /// Validation runs *after* alias translation, so every cross-harness |
| 234 | /// spelling the alias lane folds must still reach the action it names. |
| 235 | /// A refusal that fired first would undo #5209's fix. |
| 236 | #[tokio::test] |
| 237 | async fn every_alias_survives_validation() { |
| 238 | let aliased: Vec<(&str, Value)> = vec![ |
| 239 | // Path spellings, on every action that takes a path. |
| 240 | ("read", json!({"action": "read", "file_path": "doc.txt"})), |
| 241 | ("read", json!({"action": "read", "filePath": "doc.txt"})), |
| 242 | ("list", json!({"action": "list", "file_path": "."})), |
| 243 | ( |
| 244 | "search_name", |
| 245 | json!({"action": "search_name", "query": "doc", "file_path": "."}), |
| 246 | ), |
| 247 | ( |
| 248 | "search_content", |
| 249 | json!({"action": "search_content", "pattern": "alpha", "file_path": "."}), |
| 250 | ), |
| 251 | ( |
| 252 | "write", |
| 253 | json!({"action": "write", "file_path": "new.txt", "content": "x\n"}), |
| 254 | ), |
| 255 | // Read-window spellings. |
| 256 | ( |
| 257 | "read", |
| 258 | json!({"action": "read", "path": "doc.txt", "offset": 2, "limit": 1}), |
| 259 | ), |
| 260 | ( |
| 261 | "read", |
| 262 | json!({"action": "read", "path": "doc.txt", "line_offset": 2, "n_lines": 1}), |
| 263 | ), |
| 264 | ( |
| 265 | "read", |
| 266 | json!({"action": "read", "path": "doc.txt", "num_lines": 1}), |
| 267 | ), |
| 268 | // Search spellings folded across both search tools. |
| 269 | ( |
| 270 | "search_name", |
| 271 | json!({"action": "search_name", "query": "doc", "max_results": 5}), |
| 272 | ), |
| 273 | ( |
| 274 | "search_content", |
| 275 | json!({"action": "search_content", "query": "alpha", "limit": 5}), |
| 276 | ), |
| 277 | ]; |
| 278 | |
| 279 | for (action, call) in aliased { |
| 280 | let (_tmp, ctx) = workspace().await; |
| 281 | let result = dispatch(action, call.clone(), &ctx) |
| 282 | .await |
| 283 | .unwrap_or_else(|error| panic!("{action} must accept {call}: {error}")); |
| 284 | assert!(result.success, "{action} / {call}: {}", result.content); |
| 285 | } |
| 286 | |
| 287 | // Edit spellings need their own loop: each one mutates the file. |
| 288 | for (search, replace) in [ |
| 289 | ("old_string", "new_string"), |
| 290 | ("old_str", "new_str"), |
| 291 | ("oldText", "newText"), |
| 292 | ("old_text", "new_text"), |
| 293 | ] { |
| 294 | let (_tmp, ctx) = workspace().await; |
| 295 | let result = dispatch( |
| 296 | "edit", |
| 297 | json!({"path": "doc.txt", search: "alpha", replace: "delta"}), |
| 298 | &ctx, |
| 299 | ) |
| 300 | .await |
| 301 | .unwrap_or_else(|error| panic!("edit must accept {search}/{replace}: {error}")); |
| 302 | assert!(result.success, "{search}/{replace}: {}", result.content); |
| 303 | } |
| 304 | let (_tmp, ctx) = workspace().await; |
| 305 | let result = dispatch( |
| 306 | "edit", |
| 307 | json!({"path": "doc.txt", "search": "alpha", "replacement": "delta"}), |
| 308 | &ctx, |
| 309 | ) |
| 310 | .await |
| 311 | .expect("edit must accept `replacement`"); |
| 312 | assert!(result.success, "{}", result.content); |
| 313 | } |
| 314 | |
| 315 | /// A parameter that belongs to a *different* tool is still unknown to this |
| 316 | /// one. Silently dropping it is how a model learns a call worked |
| 317 | /// when the argument it cared about was discarded. |
| 318 | #[tokio::test] |
| 319 | async fn parameters_do_not_leak_between_actions() { |
| 320 | for (action, call) in [ |
| 321 | ( |
| 322 | "read", |
| 323 | json!({"action": "read", "path": "doc.txt", "case_insensitive": true}), |
| 324 | ), |
| 325 | ( |
| 326 | "write", |
| 327 | json!({"action": "write", "path": "new.txt", "content": "x\n", "start_line": 2}), |
| 328 | ), |
| 329 | ( |
| 330 | "list", |
| 331 | json!({"action": "list", "path": ".", "context_lines": 3}), |
| 332 | ), |
| 333 | ( |
| 334 | "search_name", |
| 335 | json!({"action": "search_name", "query": "doc", "context_lines": 3}), |
| 336 | ), |
| 337 | ( |
| 338 | "search_content", |
| 339 | json!({"action": "search_content", "pattern": "alpha", "extensions": ["txt"]}), |
| 340 | ), |
| 341 | ] { |
| 342 | let (_tmp, ctx) = workspace().await; |
| 343 | let message = dispatch(action, call, &ctx) |
| 344 | .await |
| 345 | .expect_err("another tool's parameter must be refused") |
| 346 | .to_string(); |
| 347 | assert!( |
| 348 | message.contains("The call was not performed"), |
| 349 | "{action}: {message}" |
| 350 | ); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | /// Every action's required names must be names it also allows, or a |
| 355 | /// refusal would tell the model to pass something the action rejects. |
| 356 | #[test] |
| 357 | fn every_required_parameter_is_also_an_allowed_one() { |
| 358 | use crate::tools::file::{ |
| 359 | EDIT_PARAMS, LIST_PARAMS, PATCH_PARAMS, READ_PARAMS, SEARCH_CONTENT_PARAMS, |
| 360 | SEARCH_NAME_PARAMS, WRITE_PARAMS, |
| 361 | }; |
| 362 | |
| 363 | for params in [ |
| 364 | READ_PARAMS, |
| 365 | WRITE_PARAMS, |
| 366 | EDIT_PARAMS, |
| 367 | LIST_PARAMS, |
| 368 | SEARCH_NAME_PARAMS, |
| 369 | SEARCH_CONTENT_PARAMS, |
| 370 | PATCH_PARAMS, |
| 371 | ] { |
| 372 | params.assert_required_is_allowed(); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn primitive_schemas_are_separate_and_small_contract_shaped() { |
| 378 | assert_eq!(ReadTool.name(), "read"); |
| 379 | assert_eq!(WriteTool.name(), "write"); |
| 380 | assert_eq!(EditTool.name(), "edit"); |
| 381 | assert_eq!( |
| 382 | ReadTool.input_schema()["properties"] |
| 383 | .as_object() |
| 384 | .expect("read properties") |
| 385 | .keys() |
| 386 | .cloned() |
| 387 | .collect::<std::collections::BTreeSet<_>>(), |
| 388 | ["limit", "offset", "pages", "path"] |
| 389 | .into_iter() |
| 390 | .map(str::to_string) |
| 391 | .collect() |
| 392 | ); |
| 393 | assert_eq!( |
| 394 | WriteTool.input_schema()["properties"] |
| 395 | .as_object() |
| 396 | .expect("write properties") |
| 397 | .keys() |
| 398 | .cloned() |
| 399 | .collect::<std::collections::BTreeSet<_>>(), |
| 400 | ["content", "line_ending", "path"] |
| 401 | .into_iter() |
| 402 | .map(str::to_string) |
| 403 | .collect() |
| 404 | ); |
| 405 | assert_eq!( |
| 406 | EditTool.input_schema()["required"], |
| 407 | json!(["path", "edits"]) |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | #[tokio::test] |
| 412 | async fn primitive_edit_applies_disjoint_matches_against_original() { |
| 413 | let (tmp, ctx) = workspace().await; |
| 414 | let result = EditTool |
| 415 | .execute( |
| 416 | json!({ |
| 417 | "path": "doc.txt", |
| 418 | "edits": [ |
| 419 | {"oldText": "alpha", "newText": "ALPHA-LONG"}, |
| 420 | {"oldText": "gamma", "newText": "g"} |
| 421 | ] |
| 422 | }), |
| 423 | &ctx, |
| 424 | ) |
| 425 | .await |
| 426 | .expect("multi-edit"); |
| 427 | |
| 428 | assert!(result.success, "{}", result.content); |
| 429 | assert_eq!( |
| 430 | std::fs::read_to_string(tmp.path().join("doc.txt")).expect("read"), |
| 431 | "ALPHA-LONG\nbeta\ng\n" |
| 432 | ); |
| 433 | assert_eq!( |
| 434 | result.content.lines().next(), |
| 435 | Some("Successfully replaced 2 block(s) in doc.txt.") |
| 436 | ); |
| 437 | assert!(result.content.contains("-alpha"), "{}", result.content); |
| 438 | assert!(result.content.contains("+ALPHA-LONG"), "{}", result.content); |
| 439 | assert!(result.content.contains("-gamma"), "{}", result.content); |
| 440 | assert!(result.content.contains("+g"), "{}", result.content); |
| 441 | } |
| 442 | |
| 443 | #[tokio::test] |
| 444 | async fn primitive_edit_rejects_overlap_without_writing() { |
| 445 | let (tmp, ctx) = workspace().await; |
| 446 | let before = std::fs::read_to_string(tmp.path().join("doc.txt")).expect("before"); |
| 447 | let error = EditTool |
| 448 | .execute( |
| 449 | json!({ |
| 450 | "path": "doc.txt", |
| 451 | "edits": [ |
| 452 | {"oldText": "alpha\nbeta", "newText": "one"}, |
| 453 | {"oldText": "beta\ngamma", "newText": "two"} |
| 454 | ] |
| 455 | }), |
| 456 | &ctx, |
| 457 | ) |
| 458 | .await |
| 459 | .expect_err("overlap must fail"); |
| 460 | |
| 461 | assert!(error.to_string().contains("overlap")); |
| 462 | assert_eq!( |
| 463 | std::fs::read_to_string(tmp.path().join("doc.txt")).expect("after"), |
| 464 | before |
| 465 | ); |
| 466 | } |
| 467 | |
| 468 | #[tokio::test] |
| 469 | async fn primitive_edit_does_not_require_a_prior_read() { |
| 470 | let tmp = tempdir().expect("tempdir"); |
| 471 | std::fs::write(tmp.path().join("doc.txt"), "alpha\n").expect("write"); |
| 472 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 473 | let result = EditTool |
| 474 | .execute( |
| 475 | json!({ |
| 476 | "path": "doc.txt", |
| 477 | "edits": [{"oldText": "alpha", "newText": "beta"}] |
| 478 | }), |
| 479 | &ctx, |
| 480 | ) |
| 481 | .await |
| 482 | .expect("lowercase edit must be Pi-simple"); |
| 483 | assert!(result.success, "{}", result.content); |
| 484 | assert_eq!( |
| 485 | std::fs::read_to_string(tmp.path().join("doc.txt")).expect("updated"), |
| 486 | "beta\n" |
| 487 | ); |
| 488 | } |
| 489 |