| 1 | //! Canonical action-based wrapper for git inspection tools. |
| 2 | //! |
| 3 | //! The model sees one tool: `Git` with an `action` parameter |
| 4 | //! (status | diff | log | show | blame | commit_plan | fetch | merge_tree). |
| 5 | //! The per-action legacy execution aliases were removed in v0.9.3. |
| 6 | //! `commit_plan` (#3999) is the propose-only atomic-commit planner: it returns |
| 7 | //! a split plan and writes nothing. `fetch` is the family's one ref-mutating, |
| 8 | //! network-reaching action — the bounded verify-mode surface (#6298) — so the |
| 9 | //! family is read-only end to end *except* fetch; `merge_tree` is a pure read. |
| 10 | |
| 11 | use async_trait::async_trait; |
| 12 | use serde_json::{Value, json}; |
| 13 | |
| 14 | use super::git::{GitCommitPlanTool, GitDiffTool, GitStatusTool}; |
| 15 | use super::git_history::{GitBlameTool, GitFetchTool, GitLogTool, GitMergeTreeTool, GitShowTool}; |
| 16 | use super::spec::{ |
| 17 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 18 | }; |
| 19 | use codewhale_tools::required_action; |
| 20 | |
| 21 | pub struct GitTool { |
| 22 | name: &'static str, |
| 23 | } |
| 24 | |
| 25 | impl GitTool { |
| 26 | pub const fn new(name: &'static str) -> Self { |
| 27 | Self { name } |
| 28 | } |
| 29 | |
| 30 | const ACTIONS: &'static [&'static str] = &[ |
| 31 | "status", |
| 32 | "diff", |
| 33 | "log", |
| 34 | "show", |
| 35 | "blame", |
| 36 | "commit_plan", |
| 37 | "fetch", |
| 38 | "merge_tree", |
| 39 | "review_scope", |
| 40 | ]; |
| 41 | |
| 42 | fn required_action(&self, input: &Value) -> Result<String, ToolError> { |
| 43 | required_action(input, self.name, Self::ACTIONS) |
| 44 | } |
| 45 | |
| 46 | fn allowed_params(action: &str) -> Option<&'static [&'static str]> { |
| 47 | match action { |
| 48 | "status" | "commit_plan" => Some(&["path"]), |
| 49 | "diff" => Some(&["path", "cached", "unified", "rev", "base", "target"]), |
| 50 | "log" => Some(&["path", "max_count", "author", "since", "until"]), |
| 51 | "show" => Some(&["rev", "path", "patch", "stat", "unified"]), |
| 52 | "blame" => Some(&["path", "rev", "start_line", "max_lines", "porcelain"]), |
| 53 | "fetch" => Some(&["remote", "refspecs", "path"]), |
| 54 | "merge_tree" => Some(&["ours", "theirs", "base", "path"]), |
| 55 | "review_scope" => Some(&["query", "rev", "ours", "theirs"]), |
| 56 | _ => None, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | fn strip_action(&self, input: Value) -> Result<Value, ToolError> { |
| 61 | let mut input = input; |
| 62 | if let Some(obj) = input.as_object_mut() { |
| 63 | obj.remove("action"); |
| 64 | Ok(input) |
| 65 | } else { |
| 66 | Err(ToolError::invalid_input( |
| 67 | "Git tool input must be a JSON object, e.g. {\"action\": \"status\"}", |
| 68 | )) |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[async_trait] |
| 74 | impl ToolSpec for GitTool { |
| 75 | fn name(&self) -> &'static str { |
| 76 | self.name |
| 77 | } |
| 78 | |
| 79 | fn model_visible(&self) -> bool { |
| 80 | self.name == "Git" |
| 81 | } |
| 82 | |
| 83 | fn description(&self) -> &'static str { |
| 84 | "Inspect repository state and history with status, diff, log, show, blame, merge_tree, or review_scope; commit_plan proposes an ordered atomic-commit split of the working tree; fetch updates remote-tracking refs from a configured remote. Only fetch touches the network or mutates refs; every other action is read-only and parallel-safe." |
| 85 | } |
| 86 | |
| 87 | fn input_schema(&self) -> Value { |
| 88 | json!({ |
| 89 | "type": "object", |
| 90 | "properties": { |
| 91 | "action": { |
| 92 | "type": "string", |
| 93 | "enum": ["status", "diff", "log", "show", "blame", "commit_plan", "fetch", "merge_tree", "review_scope"], |
| 94 | "description": "Action to perform. commit_plan returns a proposed split of the working tree into dependency-ordered commits (rejecting cycles) and writes nothing; land each group with git add/commit. merge_tree computes a merge result without touching the working tree." |
| 95 | }, |
| 96 | "path": { |
| 97 | "type": "string", |
| 98 | "description": "Optional subdirectory or file path to scope the git command" |
| 99 | }, |
| 100 | "query": { |
| 101 | "type": "string", |
| 102 | "enum": ["branches", "commits", "root", "resolve", "ahead_behind", "merge_base"], |
| 103 | "description": "Bounded metadata query for choosing a review scope in the current workspace (action=review_scope). resolve uses rev; ahead_behind and merge_base require full commit IDs in ours and theirs." |
| 104 | }, |
| 105 | "cached": { |
| 106 | "type": "boolean", |
| 107 | "description": "When true, diff staged changes (action=diff)" |
| 108 | }, |
| 109 | "unified": { |
| 110 | "type": "integer", |
| 111 | "description": "Number of context lines for diff or show output" |
| 112 | }, |
| 113 | "max_count": { |
| 114 | "type": "integer", |
| 115 | "description": "Maximum commits to return (action=log)" |
| 116 | }, |
| 117 | "author": { |
| 118 | "type": "string", |
| 119 | "description": "Author filter (action=log)" |
| 120 | }, |
| 121 | "since": { |
| 122 | "type": "string", |
| 123 | "description": "Lower date bound (action=log)" |
| 124 | }, |
| 125 | "until": { |
| 126 | "type": "string", |
| 127 | "description": "Upper date bound (action=log)" |
| 128 | }, |
| 129 | "rev": { |
| 130 | "type": "string", |
| 131 | "description": "Revision or range to diff (action=diff, e.g. main..HEAD or HEAD~3), show (action=show), blame against (action=blame), or resolve (action=review_scope)" |
| 132 | }, |
| 133 | "patch": { |
| 134 | "type": "boolean", |
| 135 | "description": "Include patch hunks (action=show)" |
| 136 | }, |
| 137 | "stat": { |
| 138 | "type": "boolean", |
| 139 | "description": "Include stat summary (action=show)" |
| 140 | }, |
| 141 | "start_line": { |
| 142 | "type": "integer", |
| 143 | "description": "First line to include (action=blame)" |
| 144 | }, |
| 145 | "max_lines": { |
| 146 | "type": "integer", |
| 147 | "description": "Maximum lines to include (action=blame)" |
| 148 | }, |
| 149 | "porcelain": { |
| 150 | "type": "boolean", |
| 151 | "description": "Emit line-porcelain output (action=blame)" |
| 152 | }, |
| 153 | "remote": { |
| 154 | "type": "string", |
| 155 | "description": "Configured remote name to fetch from, default origin (action=fetch). Never a URL." |
| 156 | }, |
| 157 | "refspecs": { |
| 158 | "type": "array", |
| 159 | "items": { "type": "string" }, |
| 160 | "description": "Optional refspecs to fetch, e.g. pull/123/head (action=fetch); a `src:dst` destination must be under refs/remotes/. Empty fetches the remote's defaults." |
| 161 | }, |
| 162 | "ours": { |
| 163 | "type": "string", |
| 164 | "description": "First revision (action=merge_tree)" |
| 165 | }, |
| 166 | "theirs": { |
| 167 | "type": "string", |
| 168 | "description": "Second revision (action=merge_tree)" |
| 169 | }, |
| 170 | "base": { |
| 171 | "type": "string", |
| 172 | "description": "Base revision to diff from (action=diff), or optional merge base (--merge-base, action=merge_tree)" |
| 173 | }, |
| 174 | "target": { |
| 175 | "type": "string", |
| 176 | "description": "Target revision to diff to; requires base (action=diff)" |
| 177 | } |
| 178 | }, |
| 179 | "required": ["action"] |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 184 | vec![ |
| 185 | ToolCapability::Network, |
| 186 | ToolCapability::Sandboxable, |
| 187 | ToolCapability::RequiresApproval, |
| 188 | ToolCapability::StartsWorkspaceProgram, |
| 189 | ] |
| 190 | } |
| 191 | |
| 192 | fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement { |
| 193 | // `fetch` is the family's one network-reaching, ref-mutating action; |
| 194 | // it holds the same bar as the other code/process-executing tools. |
| 195 | if input.get("action").and_then(Value::as_str) == Some("fetch") { |
| 196 | ApprovalRequirement::Required |
| 197 | } else { |
| 198 | ApprovalRequirement::Auto |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | fn is_read_only_for(&self, input: &Value) -> bool { |
| 203 | // Only `fetch` mutates (remote-tracking refs). A missing action |
| 204 | // resolves to the `status` policy default, which is read-only. |
| 205 | input |
| 206 | .get("action") |
| 207 | .and_then(Value::as_str) |
| 208 | .is_none_or(|action| action != "fetch") |
| 209 | } |
| 210 | |
| 211 | fn supports_parallel_for(&self, input: &Value) -> bool { |
| 212 | // Concurrent fetches contend on ref locks; inspection stays parallel. |
| 213 | input.get("action").and_then(Value::as_str) != Some("fetch") |
| 214 | } |
| 215 | |
| 216 | fn starts_detached_for(&self, _input: &Value) -> bool { |
| 217 | false |
| 218 | } |
| 219 | |
| 220 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 221 | let action = self.required_action(&input)?; |
| 222 | let input = self.strip_action(input)?; |
| 223 | let unknown_action = |action: &str| { |
| 224 | ToolError::invalid_input(format!( |
| 225 | "Unknown Git action \"{action}\"; nothing was run. Pass one of: {}.", |
| 226 | Self::ACTIONS.join(", ") |
| 227 | )) |
| 228 | }; |
| 229 | let allowed = Self::allowed_params(&action).ok_or_else(|| unknown_action(&action))?; |
| 230 | validate_action_params(&action, &input, allowed)?; |
| 231 | |
| 232 | match action.as_str() { |
| 233 | "status" => GitStatusTool.execute(input, context).await, |
| 234 | "diff" => GitDiffTool.execute(input, context).await, |
| 235 | "log" => GitLogTool.execute(input, context).await, |
| 236 | "show" => GitShowTool.execute(input, context).await, |
| 237 | "blame" => GitBlameTool.execute(input, context).await, |
| 238 | "commit_plan" => GitCommitPlanTool.execute(input, context).await, |
| 239 | "fetch" => GitFetchTool.execute(input, context).await, |
| 240 | "merge_tree" => GitMergeTreeTool.execute(input, context).await, |
| 241 | "review_scope" => review_scope(input, context).await, |
| 242 | other => Err(unknown_action(other)), |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn validate_action_params(action: &str, input: &Value, allowed: &[&str]) -> Result<(), ToolError> { |
| 248 | let Some(object) = input.as_object() else { |
| 249 | return Err(ToolError::invalid_input( |
| 250 | "Git tool input must be a JSON object, e.g. {\"action\": \"status\"}", |
| 251 | )); |
| 252 | }; |
| 253 | let mut unexpected: Vec<&str> = object |
| 254 | .keys() |
| 255 | .map(String::as_str) |
| 256 | .filter(|key| !allowed.contains(key)) |
| 257 | .collect(); |
| 258 | if unexpected.is_empty() { |
| 259 | return Ok(()); |
| 260 | } |
| 261 | unexpected.sort_unstable(); |
| 262 | Err(ToolError::invalid_input(format!( |
| 263 | "Unexpected parameter(s) for Git action=\"{action}\": {}. Allowed parameters for \"{action}\": {}.", |
| 264 | unexpected.join(", "), |
| 265 | allowed.join(", ") |
| 266 | ))) |
| 267 | } |
| 268 | |
| 269 | fn apply_review_git_options(command: &mut std::process::Command, args: Vec<String>) { |
| 270 | command |
| 271 | .args(["--no-optional-locks", "--no-pager"]) |
| 272 | .args(args) |
| 273 | .env("GIT_TERMINAL_PROMPT", "0") |
| 274 | .env("GIT_OPTIONAL_LOCKS", "0") |
| 275 | .env("GIT_NO_LAZY_FETCH", "1"); |
| 276 | } |
| 277 | |
| 278 | async fn review_scope(input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 279 | let query = input |
| 280 | .get("query") |
| 281 | .and_then(Value::as_str) |
| 282 | .ok_or_else(|| ToolError::invalid_input("review_scope requires a metadata query"))?; |
| 283 | let field = |name: &str| -> Result<String, ToolError> { |
| 284 | let value = input |
| 285 | .get(name) |
| 286 | .and_then(Value::as_str) |
| 287 | .ok_or_else(|| ToolError::invalid_input(format!("review_scope requires {name}")))?; |
| 288 | if value.is_empty() |
| 289 | || value.len() > 1024 |
| 290 | || value.starts_with('-') |
| 291 | || value.chars().any(char::is_whitespace) |
| 292 | || value.chars().any(char::is_control) |
| 293 | { |
| 294 | return Err(ToolError::invalid_input("Invalid Git review reference")); |
| 295 | } |
| 296 | Ok(value.to_string()) |
| 297 | }; |
| 298 | let commit = |name: &str| -> Result<String, ToolError> { |
| 299 | let value = field(name)?; |
| 300 | if !matches!(value.len(), 40 | 64) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) { |
| 301 | return Err(ToolError::invalid_input( |
| 302 | "Git review comparisons require full commit IDs", |
| 303 | )); |
| 304 | } |
| 305 | Ok(value) |
| 306 | }; |
| 307 | let (allowed, args): (&[&str], Vec<String>) = match query { |
| 308 | "branches" => ( |
| 309 | &["query"], |
| 310 | vec![ |
| 311 | "for-each-ref".into(), |
| 312 | "--count=4097".into(), |
| 313 | "--format=%(refname:short)".into(), |
| 314 | "refs/heads".into(), |
| 315 | ], |
| 316 | ), |
| 317 | "commits" => ( |
| 318 | &["query"], |
| 319 | vec![ |
| 320 | "log".into(), |
| 321 | "--no-show-signature".into(), |
| 322 | "--max-count=100".into(), |
| 323 | "--format=%H%x09%s".into(), |
| 324 | ], |
| 325 | ), |
| 326 | "root" => ( |
| 327 | &["query"], |
| 328 | vec!["rev-parse".into(), "--show-toplevel".into()], |
| 329 | ), |
| 330 | "resolve" => ( |
| 331 | &["query", "rev"], |
| 332 | vec![ |
| 333 | "rev-parse".into(), |
| 334 | "--verify".into(), |
| 335 | "--end-of-options".into(), |
| 336 | format!("{}^{{commit}}", field("rev")?), |
| 337 | ], |
| 338 | ), |
| 339 | "ahead_behind" => ( |
| 340 | &["query", "ours", "theirs"], |
| 341 | vec![ |
| 342 | "rev-list".into(), |
| 343 | "--left-right".into(), |
| 344 | "--count".into(), |
| 345 | format!("{}...{}", commit("ours")?, commit("theirs")?), |
| 346 | ], |
| 347 | ), |
| 348 | "merge_base" => ( |
| 349 | &["query", "ours", "theirs"], |
| 350 | vec!["merge-base".into(), commit("ours")?, commit("theirs")?], |
| 351 | ), |
| 352 | _ => { |
| 353 | return Err(ToolError::invalid_input( |
| 354 | "Unsupported Git review metadata query", |
| 355 | )); |
| 356 | } |
| 357 | }; |
| 358 | if input |
| 359 | .as_object() |
| 360 | .is_none_or(|object| object.keys().any(|key| !allowed.contains(&key.as_str()))) |
| 361 | { |
| 362 | return Err(ToolError::invalid_input( |
| 363 | "Unsupported Git review metadata field", |
| 364 | )); |
| 365 | } |
| 366 | let workspace = context.workspace.clone(); |
| 367 | let mut command = |
| 368 | tokio::task::spawn_blocking(move || super::git::read_only_git_command(&workspace)) |
| 369 | .await |
| 370 | .map_err(|error| { |
| 371 | ToolError::execution_failed(format!("Git preparation failed: {error}")) |
| 372 | })??; |
| 373 | apply_review_git_options(&mut command, args); |
| 374 | let mut command = tokio::process::Command::from(command); |
| 375 | let cancel = context.cancel_token.clone().unwrap_or_default(); |
| 376 | let stop = async { |
| 377 | tokio::select! { |
| 378 | () = cancel.cancelled() => {}, |
| 379 | () = tokio::time::sleep(std::time::Duration::from_secs(10)) => {}, |
| 380 | } |
| 381 | }; |
| 382 | let run = codewhale_runtime::process_tree::contained_output_with_input_bounded( |
| 383 | &mut command, |
| 384 | Vec::new(), |
| 385 | 1024 * 1024, |
| 386 | 64 * 1024, |
| 387 | stop, |
| 388 | ) |
| 389 | .await |
| 390 | .map_err(|error| ToolError::execution_failed(format!("Git review metadata failed: {error}")))?; |
| 391 | if run.stopped { |
| 392 | return Err(ToolError::execution_failed( |
| 393 | "Git review metadata was cancelled or exceeded its deadline", |
| 394 | )); |
| 395 | } |
| 396 | let stdout = String::from_utf8_lossy(&run.output.stdout); |
| 397 | if query == "branches" && stdout.lines().count() > 4096 { |
| 398 | return Err(ToolError::execution_failed( |
| 399 | "Git review branch list exceeds 4096 entries", |
| 400 | )); |
| 401 | } |
| 402 | Ok(ToolResult::success( |
| 403 | json!({ |
| 404 | "stdout": stdout, |
| 405 | "stderr": String::from_utf8_lossy(&run.output.stderr), |
| 406 | "exit_code": run.output.status.code(), |
| 407 | }) |
| 408 | .to_string(), |
| 409 | )) |
| 410 | } |
| 411 | |
| 412 | #[cfg(test)] |
| 413 | mod tests { |
| 414 | use super::*; |
| 415 | use serde_json::json; |
| 416 | use tempfile::tempdir; |
| 417 | |
| 418 | async fn err(input: Value) -> String { |
| 419 | let tmp = tempdir().expect("tempdir"); |
| 420 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 421 | GitTool::new("Git") |
| 422 | .execute(input, &ctx) |
| 423 | .await |
| 424 | .expect_err("call must be refused") |
| 425 | .to_string() |
| 426 | } |
| 427 | |
| 428 | #[test] |
| 429 | fn review_git_options_use_env_not_a_flag_old_git_rejects() { |
| 430 | let mut command = std::process::Command::new("git"); |
| 431 | apply_review_git_options(&mut command, vec!["rev-parse".into(), "HEAD".into()]); |
| 432 | let args: Vec<_> = command |
| 433 | .get_args() |
| 434 | .map(|a| a.to_string_lossy().into_owned()) |
| 435 | .collect(); |
| 436 | assert_eq!( |
| 437 | args, |
| 438 | ["--no-optional-locks", "--no-pager", "rev-parse", "HEAD"] |
| 439 | ); |
| 440 | assert!(!args.iter().any(|a| a == "--no-lazy-fetch")); |
| 441 | let lazy = command |
| 442 | .get_envs() |
| 443 | .find(|(key, _)| *key == "GIT_NO_LAZY_FETCH") |
| 444 | .and_then(|(_, value)| value); |
| 445 | assert_eq!(lazy, Some(std::ffi::OsStr::new("1"))); |
| 446 | } |
| 447 | |
| 448 | #[tokio::test] |
| 449 | async fn review_scope_resolve_runs_against_system_git() { |
| 450 | if !<codewhale_dependencies::Git as codewhale_dependencies::ExternalTool>::available() { |
| 451 | return; |
| 452 | } |
| 453 | let tmp = tempdir().expect("tempdir"); |
| 454 | let run = |args: &[&str]| { |
| 455 | let out = std::process::Command::new("git") |
| 456 | .args(args) |
| 457 | .current_dir(tmp.path()) |
| 458 | .output() |
| 459 | .expect("git runs"); |
| 460 | assert!( |
| 461 | out.status.success(), |
| 462 | "{args:?}: {}", |
| 463 | String::from_utf8_lossy(&out.stderr) |
| 464 | ); |
| 465 | }; |
| 466 | run(&["init", "-q"]); |
| 467 | run(&[ |
| 468 | "-c", |
| 469 | "user.name=t", |
| 470 | "-c", |
| 471 | "user.email=t@example.com", |
| 472 | "commit", |
| 473 | "-q", |
| 474 | "--allow-empty", |
| 475 | "-m", |
| 476 | "init", |
| 477 | ]); |
| 478 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 479 | let result = GitTool::new("Git") |
| 480 | .execute( |
| 481 | json!({"action": "review_scope", "query": "resolve", "rev": "HEAD"}), |
| 482 | &ctx, |
| 483 | ) |
| 484 | .await |
| 485 | .expect("review_scope runs"); |
| 486 | let body: Value = serde_json::from_str(&result.content).expect("json"); |
| 487 | assert_eq!(body["exit_code"], 0, "{body}"); |
| 488 | assert_eq!( |
| 489 | body["stdout"].as_str().map(|s| s.trim().len()), |
| 490 | Some(40), |
| 491 | "{body}" |
| 492 | ); |
| 493 | } |
| 494 | |
| 495 | #[tokio::test] |
| 496 | async fn missing_action_is_refused_with_the_valid_values() { |
| 497 | let message = err(json!({"path": "src"})).await; |
| 498 | assert!(message.contains("requires an `action`"), "{message}"); |
| 499 | assert!(message.contains("nothing was run"), "{message}"); |
| 500 | assert!(message.contains("blame"), "{message}"); |
| 501 | } |
| 502 | |
| 503 | #[tokio::test] |
| 504 | async fn unknown_action_names_the_actions_that_dispatch() { |
| 505 | let message = err(json!({"action": "commit"})).await; |
| 506 | assert!(message.contains("commit"), "{message}"); |
| 507 | assert!( |
| 508 | message.contains("status, diff, log, show, blame, commit_plan, fetch, merge_tree"), |
| 509 | "{message}" |
| 510 | ); |
| 511 | } |
| 512 | |
| 513 | /// `commit_plan` proposes and never writes, so the envelope must class it |
| 514 | /// with the other read-only Git actions rather than as a mutation (#3999). |
| 515 | #[test] |
| 516 | fn commit_plan_is_bounded_read_only_for_the_envelope() { |
| 517 | use crate::tools::execution_envelope::{CallClass, classify_call}; |
| 518 | let tool = GitTool::new("Git"); |
| 519 | let input = json!({"action": "commit_plan"}); |
| 520 | assert!(tool.is_read_only_for(&input)); |
| 521 | assert_eq!(classify_call("Git", &input, &tool), CallClass::Bounded); |
| 522 | } |
| 523 | |
| 524 | /// `fetch` is the family's one ref-mutating action: held approval, not |
| 525 | /// read-only, not parallel-safe, and classed as bounded fetch — shell |
| 526 | /// plus network, never workspace write (#6298). `merge_tree` is a pure |
| 527 | /// read and stays with the inspection actions. |
| 528 | #[test] |
| 529 | fn fetch_and_merge_tree_classification() { |
| 530 | use crate::tools::execution_envelope::{CallClass, classify_call}; |
| 531 | let tool = GitTool::new("Git"); |
| 532 | |
| 533 | let fetch = json!({"action": "fetch", "remote": "origin"}); |
| 534 | assert!(!tool.is_read_only_for(&fetch)); |
| 535 | assert_eq!( |
| 536 | tool.approval_requirement_for(&fetch), |
| 537 | ApprovalRequirement::Required |
| 538 | ); |
| 539 | assert!(!tool.supports_parallel_for(&fetch)); |
| 540 | assert_eq!(classify_call("Git", &fetch, &tool), CallClass::BoundedFetch); |
| 541 | |
| 542 | let merge_tree = json!({"action": "merge_tree", "ours": "main", "theirs": "side"}); |
| 543 | assert!(tool.is_read_only_for(&merge_tree)); |
| 544 | assert_eq!( |
| 545 | tool.approval_requirement_for(&merge_tree), |
| 546 | ApprovalRequirement::Auto |
| 547 | ); |
| 548 | assert!(tool.supports_parallel_for(&merge_tree)); |
| 549 | assert_eq!(classify_call("Git", &merge_tree, &tool), CallClass::Bounded); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn advertised_actions_match_the_actions_that_dispatch() { |
| 554 | let schema = GitTool::new("Git").input_schema(); |
| 555 | let advertised: Vec<&str> = schema["properties"]["action"]["enum"] |
| 556 | .as_array() |
| 557 | .expect("action enum") |
| 558 | .iter() |
| 559 | .map(|value| value.as_str().expect("string")) |
| 560 | .collect(); |
| 561 | assert_eq!(advertised, GitTool::ACTIONS); |
| 562 | } |
| 563 | |
| 564 | #[test] |
| 565 | fn capabilities_reflect_fetch_while_keeping_inspection_actions_read_only() { |
| 566 | let tool = GitTool::new("Git"); |
| 567 | let caps = tool.capabilities(); |
| 568 | assert!(!caps.contains(&ToolCapability::ReadOnly), "{caps:?}"); |
| 569 | assert!(!tool.is_read_only()); |
| 570 | assert!(caps.contains(&ToolCapability::Network), "{caps:?}"); |
| 571 | assert!(caps.contains(&ToolCapability::Sandboxable), "{caps:?}"); |
| 572 | |
| 573 | for action in [ |
| 574 | "status", |
| 575 | "diff", |
| 576 | "log", |
| 577 | "show", |
| 578 | "blame", |
| 579 | "commit_plan", |
| 580 | "merge_tree", |
| 581 | "review_scope", |
| 582 | ] { |
| 583 | assert!( |
| 584 | tool.is_read_only_for(&json!({"action": action})), |
| 585 | "{action} must stay read-only" |
| 586 | ); |
| 587 | } |
| 588 | assert!(!tool.is_read_only_for(&json!({"action": "fetch"}))); |
| 589 | } |
| 590 | |
| 591 | #[tokio::test] |
| 592 | async fn diff_supports_rev_base_target_and_rejects_flag_injection() { |
| 593 | if !<codewhale_dependencies::Git as codewhale_dependencies::ExternalTool>::available() { |
| 594 | return; |
| 595 | } |
| 596 | let tmp = tempdir().expect("tempdir"); |
| 597 | let run = |args: &[&str]| { |
| 598 | let out = std::process::Command::new("git") |
| 599 | .args(args) |
| 600 | .current_dir(tmp.path()) |
| 601 | .output() |
| 602 | .expect("git runs"); |
| 603 | assert!( |
| 604 | out.status.success(), |
| 605 | "{args:?}: {}", |
| 606 | String::from_utf8_lossy(&out.stderr) |
| 607 | ); |
| 608 | }; |
| 609 | run(&["init", "-q"]); |
| 610 | run(&["config", "user.name", "t"]); |
| 611 | run(&["config", "user.email", "t@example.com"]); |
| 612 | |
| 613 | std::fs::write(tmp.path().join("a.txt"), "one\n").expect("write a"); |
| 614 | std::fs::write(tmp.path().join("b.txt"), "b1\n").expect("write b"); |
| 615 | run(&["add", "."]); |
| 616 | run(&["commit", "-q", "-m", "c1"]); |
| 617 | |
| 618 | std::fs::write(tmp.path().join("a.txt"), "two\n").expect("write a"); |
| 619 | run(&["add", "."]); |
| 620 | run(&["commit", "-q", "-m", "c2"]); |
| 621 | |
| 622 | std::fs::write(tmp.path().join("a.txt"), "three\n").expect("write a"); |
| 623 | std::fs::write(tmp.path().join("b.txt"), "b2\n").expect("write b"); |
| 624 | run(&["add", "."]); |
| 625 | run(&["commit", "-q", "-m", "c3"]); |
| 626 | |
| 627 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 628 | let tool = GitTool::new("Git"); |
| 629 | |
| 630 | let rev_diff = tool |
| 631 | .execute(json!({"action": "diff", "rev": "HEAD~1..HEAD"}), &ctx) |
| 632 | .await |
| 633 | .expect("rev range diff"); |
| 634 | assert!(rev_diff.success, "{}", rev_diff.content); |
| 635 | assert!(rev_diff.content.contains("-two"), "{}", rev_diff.content); |
| 636 | assert!(rev_diff.content.contains("+three"), "{}", rev_diff.content); |
| 637 | assert!(rev_diff.content.contains("+b2"), "{}", rev_diff.content); |
| 638 | |
| 639 | let base_target = tool |
| 640 | .execute( |
| 641 | json!({ |
| 642 | "action": "diff", |
| 643 | "base": "HEAD~2", |
| 644 | "target": "HEAD~1", |
| 645 | "path": "a.txt" |
| 646 | }), |
| 647 | &ctx, |
| 648 | ) |
| 649 | .await |
| 650 | .expect("base..target diff"); |
| 651 | assert!(base_target.success, "{}", base_target.content); |
| 652 | assert!( |
| 653 | base_target.content.contains("-one"), |
| 654 | "{}", |
| 655 | base_target.content |
| 656 | ); |
| 657 | assert!( |
| 658 | base_target.content.contains("+two"), |
| 659 | "{}", |
| 660 | base_target.content |
| 661 | ); |
| 662 | assert!( |
| 663 | !base_target.content.contains("b.txt"), |
| 664 | "{}", |
| 665 | base_target.content |
| 666 | ); |
| 667 | |
| 668 | let three_dot = tool |
| 669 | .execute(json!({"action": "diff", "rev": "HEAD~1...HEAD"}), &ctx) |
| 670 | .await |
| 671 | .expect("three-dot diff"); |
| 672 | assert!(three_dot.success, "{}", three_dot.content); |
| 673 | assert!( |
| 674 | three_dot.content.contains("+three"), |
| 675 | "{}", |
| 676 | three_dot.content |
| 677 | ); |
| 678 | |
| 679 | let pwn_path = tmp.path().join("should_not_exist"); |
| 680 | let pwn_flag = format!("--output={}", pwn_path.display()); |
| 681 | for bad in [ |
| 682 | json!({"action": "diff", "rev": pwn_flag}), |
| 683 | json!({"action": "diff", "rev": format!(" --output={}", pwn_path.display())}), |
| 684 | json!({"action": "diff", "rev": format!("HEAD~1..--output={}", pwn_path.display())}), |
| 685 | json!({"action": "diff", "rev": "HEAD\0--ext-diff"}), |
| 686 | json!({"action": "diff", "base": "--ext-diff"}), |
| 687 | json!({"action": "diff", "base": "HEAD~1", "target": "--output=/tmp/pwn"}), |
| 688 | json!({"action": "diff", "base": "/etc/passwd", "target": "/etc/hosts"}), |
| 689 | json!({"action": "diff", "target": "HEAD"}), |
| 690 | json!({"action": "diff", "rev": "HEAD~1..HEAD", "base": "HEAD~1"}), |
| 691 | json!({"action": "diff", "rev": "HEAD~1..HEAD", "cached": true}), |
| 692 | json!({"action": "diff", "base": "HEAD~1", "target": "HEAD", "cached": true}), |
| 693 | ] { |
| 694 | let error = tool |
| 695 | .execute(bad.clone(), &ctx) |
| 696 | .await |
| 697 | .expect_err(&format!("must reject {bad}")); |
| 698 | assert!( |
| 699 | matches!(error, ToolError::InvalidInput { .. }), |
| 700 | "expected invalid_input for {bad}, got {error:?}" |
| 701 | ); |
| 702 | } |
| 703 | assert!(!pwn_path.exists()); |
| 704 | } |
| 705 | |
| 706 | #[tokio::test] |
| 707 | async fn per_action_parameter_validation_rejects_cross_action_keys() { |
| 708 | let schema = GitTool::new("Git").input_schema(); |
| 709 | let props = schema["properties"] |
| 710 | .as_object() |
| 711 | .expect("Git schema properties"); |
| 712 | for action in GitTool::ACTIONS { |
| 713 | let allowed = GitTool::allowed_params(action) |
| 714 | .unwrap_or_else(|| panic!("missing allowed_params for {action}")); |
| 715 | for key in allowed { |
| 716 | assert!( |
| 717 | props.contains_key(*key), |
| 718 | "allowed param {key} for {action} missing from schema" |
| 719 | ); |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | let status_err = err(json!({"action": "status", "rev": "HEAD"})).await; |
| 724 | assert!(status_err.contains("rev"), "{status_err}"); |
| 725 | assert!(status_err.contains("Allowed parameters"), "{status_err}"); |
| 726 | assert!(status_err.contains("path"), "{status_err}"); |
| 727 | |
| 728 | let diff_err = err(json!({"action": "diff", "ours": "main", "theirs": "HEAD"})).await; |
| 729 | assert!(diff_err.contains("ours, theirs"), "{diff_err}"); |
| 730 | assert!(diff_err.contains("rev, base, target"), "{diff_err}"); |
| 731 | |
| 732 | let log_err = err(json!({"action": "log", "cached": true})).await; |
| 733 | assert!(log_err.contains("cached"), "{log_err}"); |
| 734 | assert!(log_err.contains("max_count"), "{log_err}"); |
| 735 | } |
| 736 | } |
| 737 |