返回 CodeWhale
git.rs
根目录 / crates / engine / src / tools / git.rs
1 //! Git power tools: `git_status`, `git_diff`, and the propose-only
2 //! `git_commit_plan`.
3 //!
4 //! These tools are read-only wrappers around common git inspection commands,
5 //! scoped to the workspace and optionally to a sub-path within it. The commit
6 //! planner (#3999) is read-only too: it proposes an ordered atomic split and
7 //! leaves staging and committing to the ordinary shell write path.
8
9 use std::collections::{BTreeMap, BTreeSet, HashSet};
10 use std::fs;
11 use std::path::{Path, PathBuf};
12
13 use async_trait::async_trait;
14 use serde_json::{Value, json};
15
16 use codewhale_dependencies::ExternalTool;
17
18 use crate::git_status::{ChangeCounts, parse_porcelain_v1};
19
20 use super::spec::{
21 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
22 optional_bool, optional_str, optional_u64,
23 };
24
25 const DEFAULT_UNIFIED: u64 = 3;
26 const MAX_UNIFIED: u64 = 50;
27 const MAX_GIT_DIFF_REV_LEN: usize = 1024;
28
29 /// Resolve untrusted revision text before using it as an argument to another
30 /// Git command. Only a verified commit ID crosses that option boundary.
31 pub(super) async fn resolve_commit_ref(workspace: &Path, base: &str) -> Result<String, ToolError> {
32 resolve_commit_ref_named(workspace, "base", base).await
33 }
34
35 async fn resolve_commit_ref_named(
36 workspace: &Path,
37 label: &str,
38 rev: &str,
39 ) -> Result<String, ToolError> {
40 let revision = format!("{rev}^{{commit}}");
41 let output = run_git_command_async(
42 workspace.to_path_buf(),
43 vec![
44 "rev-parse".to_string(),
45 "--verify".to_string(),
46 "--end-of-options".to_string(),
47 revision,
48 ],
49 )
50 .await?;
51 if !output.status.success() {
52 return Err(ToolError::invalid_input(format!(
53 "Invalid git {label} ref '{rev}': {}",
54 String::from_utf8_lossy(&output.stderr).trim()
55 )));
56 }
57 let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
58 if !matches!(commit.len(), 40 | 64) || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) {
59 return Err(ToolError::execution_failed(format!(
60 "git resolved {label} to an invalid commit id"
61 )));
62 }
63 Ok(commit)
64 }
65
66 enum GitDiffRev<'a> {
67 Single(&'a str),
68 TwoDot(&'a str, &'a str),
69 ThreeDot(&'a str, &'a str),
70 }
71
72 fn validate_git_diff_single_rev(label: &str, value: &str) -> Result<(), ToolError> {
73 if value.is_empty() {
74 return Err(ToolError::invalid_input(format!(
75 "git diff {label} must not be empty"
76 )));
77 }
78 if value.len() > MAX_GIT_DIFF_REV_LEN {
79 return Err(ToolError::invalid_input(format!(
80 "git diff {label} exceeds {MAX_GIT_DIFF_REV_LEN} bytes"
81 )));
82 }
83 if value.starts_with('-') || value.starts_with('^') || value.starts_with(':') {
84 return Err(ToolError::invalid_input(format!(
85 "git diff {label} must not start with '-', '^', or ':'"
86 )));
87 }
88 if value.chars().any(char::is_whitespace) {
89 return Err(ToolError::invalid_input(format!(
90 "git diff {label} must not contain whitespace"
91 )));
92 }
93 if value.chars().any(|ch| ch == '\0' || ch.is_control()) {
94 return Err(ToolError::invalid_input(format!(
95 "git diff {label} must not contain control characters"
96 )));
97 }
98 if value.contains("..") {
99 return Err(ToolError::invalid_input(format!(
100 "git diff {label} must be a single revision, not a range"
101 )));
102 }
103 Ok(())
104 }
105
106 fn parse_git_diff_rev(rev: &str) -> Result<GitDiffRev<'_>, ToolError> {
107 if rev.is_empty() {
108 return Err(ToolError::invalid_input("git diff rev must not be empty"));
109 }
110 if rev.len() > MAX_GIT_DIFF_REV_LEN {
111 return Err(ToolError::invalid_input(format!(
112 "git diff rev exceeds {MAX_GIT_DIFF_REV_LEN} bytes"
113 )));
114 }
115 if rev.starts_with('-') || rev.starts_with('^') || rev.starts_with(':') {
116 return Err(ToolError::invalid_input(
117 "git diff rev must not start with '-', '^', or ':'",
118 ));
119 }
120 if rev.chars().any(char::is_whitespace) {
121 return Err(ToolError::invalid_input(
122 "git diff rev must not contain whitespace",
123 ));
124 }
125 if rev.chars().any(|ch| ch == '\0' || ch.is_control()) {
126 return Err(ToolError::invalid_input(
127 "git diff rev must not contain control characters",
128 ));
129 }
130 if let Some((left, right)) = rev.split_once("...") {
131 if left.is_empty() && right.is_empty() {
132 return Err(ToolError::invalid_input(
133 "git diff rev range must specify at least one revision",
134 ));
135 }
136 if left.contains("..")
137 || right.contains("..")
138 || right.starts_with('.')
139 || left.ends_with('.')
140 {
141 return Err(ToolError::invalid_input(
142 "git diff rev contains an invalid range operator",
143 ));
144 }
145 let left = if left.is_empty() { "HEAD" } else { left };
146 let right = if right.is_empty() { "HEAD" } else { right };
147 validate_git_diff_single_rev("rev", left)?;
148 validate_git_diff_single_rev("rev", right)?;
149 return Ok(GitDiffRev::ThreeDot(left, right));
150 }
151 if let Some((left, right)) = rev.split_once("..") {
152 if left.is_empty() && right.is_empty() {
153 return Err(ToolError::invalid_input(
154 "git diff rev range must specify at least one revision",
155 ));
156 }
157 if left.contains("..")
158 || right.contains("..")
159 || right.starts_with('.')
160 || left.ends_with('.')
161 {
162 return Err(ToolError::invalid_input(
163 "git diff rev contains an invalid range operator",
164 ));
165 }
166 let left = if left.is_empty() { "HEAD" } else { left };
167 let right = if right.is_empty() { "HEAD" } else { right };
168 validate_git_diff_single_rev("rev", left)?;
169 validate_git_diff_single_rev("rev", right)?;
170 return Ok(GitDiffRev::TwoDot(left, right));
171 }
172 validate_git_diff_single_rev("rev", rev)?;
173 Ok(GitDiffRev::Single(rev))
174 }
175
176 // === GitStatusTool ===
177
178 /// Tool for reading the concise git status of the workspace.
179 pub struct GitStatusTool;
180
181 #[async_trait]
182 impl ToolSpec for GitStatusTool {
183 fn name(&self) -> &'static str {
184 "git_status"
185 }
186
187 fn model_visible(&self) -> bool {
188 false
189 }
190
191 fn description(&self) -> &'static str {
192 "Run `git status --porcelain=v1 -b` in the workspace (optionally scoped to a path), with the HEAD commit and counts of staged, modified, untracked and conflicted paths. Submodule contents are not checked."
193 }
194
195 fn input_schema(&self) -> Value {
196 json!({
197 "type": "object",
198 "properties": {
199 "path": {
200 "type": "string",
201 "description": "Optional subdirectory or file to scope the status to (must be within the workspace)."
202 }
203 },
204 "additionalProperties": false
205 })
206 }
207
208 fn capabilities(&self) -> Vec<ToolCapability> {
209 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
210 }
211
212 fn approval_requirement(&self) -> ApprovalRequirement {
213 ApprovalRequirement::Auto
214 }
215
216 fn supports_parallel(&self) -> bool {
217 true
218 }
219
220 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
221 git_status(input, context.clone()).await
222 }
223 }
224
225 async fn git_status(input: Value, context: ToolContext) -> Result<ToolResult, ToolError> {
226 let path = optional_str(&input, "path")?.map(str::to_string);
227 let requested = path.clone();
228 let git_ctx =
229 on_blocking_pool(move || resolve_git_context(&context, requested.as_deref())).await?;
230
231 let mut args = ["--porcelain=v1", "-b", "--untracked-files=normal"]
232 .map(String::from)
233 .to_vec();
234 if let Some(pathspec) = &git_ctx.pathspec {
235 args.push("--".to_string());
236 args.push(pathspec.display().to_string());
237 }
238
239 let mut shown = ["status", "--ignore-submodules=dirty"]
240 .map(String::from)
241 .to_vec();
242 shown.extend(args.iter().cloned());
243 let command_str = format_command(&git_ctx.working_dir, &shown);
244 let output = run_git_status_async(git_ctx.working_dir.clone(), args).await?;
245
246 if !output.status.success() {
247 let stderr = String::from_utf8_lossy(&output.stderr);
248 let message = format!("git status failed: {}", stderr.trim());
249 return Ok(ToolResult::error(message).with_metadata(json!({
250 "command": command_str,
251 "exit_code": output.status.code(),
252 "stderr": stderr.trim(),
253 })));
254 }
255
256 let stdout = String::from_utf8_lossy(&output.stdout);
257 let (branch, entries) = match stdout
258 .strip_prefix("## ")
259 .and_then(|rest| rest.split_once('\n'))
260 {
261 Some((branch, entries)) => (Some(branch), entries),
262 None => (None, &*stdout),
263 };
264 let unborn = branch.is_some_and(|branch| branch.starts_with("No commits yet on "));
265 let head_sha = if unborn {
266 None
267 } else {
268 resolve_commit_ref_named(&git_ctx.working_dir, "head", "HEAD")
269 .await
270 .ok()
271 };
272 let head = match (&head_sha, unborn) {
273 (Some(sha), _) => sha.as_str(),
274 (None, true) => "unborn",
275 (None, false) => "unknown",
276 };
277 let (changes, _, entry_count) = parse_porcelain_v1(entries);
278 let ChangeCounts {
279 staged,
280 modified,
281 untracked,
282 conflicts,
283 } = changes;
284 let clean = entry_count == 0;
285 let state = if clean { "clean" } else { "dirty" };
286 let scope = path
287 .as_deref()
288 .map(|path| format!(" within {path}"))
289 .unwrap_or_default();
290 let submodules = if clean {
291 "; submodule contents not checked"
292 } else {
293 ""
294 };
295 let header = branch
296 .map(|branch| format!("## {branch}\n"))
297 .unwrap_or_default();
298 let content = format!(
299 "{header}head: {head}\nstatus: {state}{scope} ({staged} staged, {modified} modified, {untracked} untracked, {conflicts} conflicted{submodules})\n{entries}"
300 );
301
302 Ok(ToolResult::success(content).with_metadata(json!({
303 "command": command_str,
304 "working_dir": git_ctx.working_dir,
305 "pathspec": git_ctx.pathspec,
306 "scoped": git_ctx.pathspec.is_some(),
307 "branch": branch,
308 "head_sha": head_sha,
309 "unborn": unborn,
310 "clean": clean,
311 "staged": staged,
312 "modified": modified,
313 "untracked": untracked,
314 "conflicted": conflicts,
315 "entries": entry_count,
316 })))
317 }
318
319 // === GitDiffTool ===
320
321 /// Tool for reading git diffs in the workspace.
322 pub struct GitDiffTool;
323
324 #[async_trait]
325 impl ToolSpec for GitDiffTool {
326 fn name(&self) -> &'static str {
327 "git_diff"
328 }
329
330 fn model_visible(&self) -> bool {
331 false
332 }
333
334 fn description(&self) -> &'static str {
335 "Run `git diff` in the workspace with sensible defaults and safe truncation."
336 }
337
338 fn input_schema(&self) -> Value {
339 json!({
340 "type": "object",
341 "properties": {
342 "path": {
343 "type": "string",
344 "description": "Optional subdirectory or file to scope the diff to (must be within the workspace)."
345 },
346 "cached": {
347 "type": "boolean",
348 "description": "When true, diff staged changes (`--cached`)."
349 },
350 "unified": {
351 "type": "integer",
352 "minimum": 0,
353 "maximum": MAX_UNIFIED,
354 "default": DEFAULT_UNIFIED,
355 "description": "Number of context lines to include around changes."
356 },
357 "rev": {
358 "type": "string",
359 "description": "Optional revision or range to diff (e.g. HEAD~3, main..HEAD, main...HEAD). Cannot be combined with base or target."
360 },
361 "base": {
362 "type": "string",
363 "description": "Optional base revision to diff from (diffs against working tree/index, or to target when target is set)."
364 },
365 "target": {
366 "type": "string",
367 "description": "Optional target revision to diff to (requires base)."
368 }
369 },
370 "additionalProperties": false
371 })
372 }
373
374 fn capabilities(&self) -> Vec<ToolCapability> {
375 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
376 }
377
378 fn approval_requirement(&self) -> ApprovalRequirement {
379 ApprovalRequirement::Auto
380 }
381
382 fn supports_parallel(&self) -> bool {
383 true
384 }
385
386 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
387 git_diff(input, context.clone()).await
388 }
389 }
390
391 async fn git_diff(input: Value, context: ToolContext) -> Result<ToolResult, ToolError> {
392 let path = optional_str(&input, "path")?.map(str::to_string);
393 let cached = optional_bool(&input, "cached", false)?;
394 let unified = optional_u64(&input, "unified", DEFAULT_UNIFIED)?.min(MAX_UNIFIED);
395 let rev = optional_str(&input, "rev")?.map(str::to_string);
396 let base = optional_str(&input, "base")?.map(str::to_string);
397 let target = optional_str(&input, "target")?.map(str::to_string);
398
399 if rev.is_some() && (base.is_some() || target.is_some()) {
400 return Err(ToolError::invalid_input(
401 "cannot combine rev with base or target; use either rev or base/target",
402 ));
403 }
404 if target.is_some() && base.is_none() {
405 return Err(ToolError::invalid_input(
406 "target requires base when diffing revisions",
407 ));
408 }
409 if cached && base.is_some() && target.is_some() {
410 return Err(ToolError::invalid_input(
411 "cannot combine cached=true with both base and target",
412 ));
413 }
414
415 let parsed_rev = match rev.as_deref() {
416 Some(value) => {
417 let parsed = parse_git_diff_rev(value)?;
418 if cached && !matches!(parsed, GitDiffRev::Single(_)) {
419 return Err(ToolError::invalid_input(
420 "cannot combine cached=true with a revision range in rev",
421 ));
422 }
423 Some(parsed)
424 }
425 None => None,
426 };
427 if let Some(base_ref) = base.as_deref() {
428 validate_git_diff_single_rev("base", base_ref)?;
429 }
430 if let Some(target_ref) = target.as_deref() {
431 validate_git_diff_single_rev("target", target_ref)?;
432 }
433
434 let git_ctx = on_blocking_pool(move || resolve_git_context(&context, path.as_deref())).await?;
435
436 let mut rev_args: Vec<String> = Vec::new();
437 match parsed_rev {
438 Some(GitDiffRev::Single(single)) => {
439 rev_args.push(resolve_commit_ref_named(&git_ctx.working_dir, "rev", single).await?);
440 }
441 Some(GitDiffRev::TwoDot(left, right)) => {
442 let left_sha = resolve_commit_ref_named(&git_ctx.working_dir, "rev", left).await?;
443 let right_sha = resolve_commit_ref_named(&git_ctx.working_dir, "rev", right).await?;
444 rev_args.push(format!("{left_sha}..{right_sha}"));
445 }
446 Some(GitDiffRev::ThreeDot(left, right)) => {
447 let left_sha = resolve_commit_ref_named(&git_ctx.working_dir, "rev", left).await?;
448 let right_sha = resolve_commit_ref_named(&git_ctx.working_dir, "rev", right).await?;
449 rev_args.push(format!("{left_sha}...{right_sha}"));
450 }
451 None => {
452 if let Some(base_ref) = base.as_deref() {
453 let base_sha =
454 resolve_commit_ref_named(&git_ctx.working_dir, "base", base_ref).await?;
455 rev_args.push(base_sha);
456 if let Some(target_ref) = target.as_deref() {
457 let target_sha =
458 resolve_commit_ref_named(&git_ctx.working_dir, "target", target_ref)
459 .await?;
460 rev_args.push(target_sha);
461 }
462 }
463 }
464 }
465
466 let mut args = vec![
467 "-c".to_string(),
468 "core.quotepath=false".to_string(),
469 "diff".to_string(),
470 "--no-color".to_string(),
471 ];
472 args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from));
473 args.push(format!("--unified={unified}"));
474 if cached {
475 args.push("--cached".to_string());
476 }
477 if !rev_args.is_empty() {
478 args.push("--end-of-options".to_string());
479 args.extend(rev_args);
480 }
481 if let Some(pathspec) = &git_ctx.pathspec {
482 args.push("--".to_string());
483 args.push(pathspec.display().to_string());
484 }
485
486 let command_str = format_command(&git_ctx.working_dir, &args);
487 let output = run_git_command_async(git_ctx.working_dir.clone(), args).await?;
488
489 if !output.status.success() {
490 let stderr = String::from_utf8_lossy(&output.stderr);
491 let message = format!("git diff failed: {}", stderr.trim());
492 return Ok(ToolResult::error(message).with_metadata(json!({
493 "command": command_str,
494 "exit_code": output.status.code(),
495 "stderr": stderr.trim(),
496 })));
497 }
498
499 let stdout = String::from_utf8_lossy(&output.stdout);
500 let content = stdout.into_owned();
501
502 Ok(ToolResult::success(content).with_metadata(json!({
503 "command": command_str,
504 "working_dir": git_ctx.working_dir,
505 "pathspec": git_ctx.pathspec,
506 "cached": cached,
507 "unified": unified,
508 "rev": rev,
509 "base": base,
510 "target": target,
511 })))
512 }
513
514 // === GitCommitPlanTool ===
515
516 /// Propose-only planner that splits the working tree into ordered atomic
517 /// commits (#3999).
518 ///
519 /// The planner reads `git diff HEAD` plus the untracked-file list, groups
520 /// whole files into logical commits, orders the groups so a commit that
521 /// defines a symbol lands before the commit that uses it, and refuses the
522 /// whole plan when that dependency graph has a cycle. It never touches the
523 /// index or the object store — no `git add -N`, no `git apply --cached`, no
524 /// `git commit`. The model lands each proposed commit through the ordinary
525 /// `git add` / `git commit` shell path, which is where the approval gate
526 /// already lives: one commit authority, not two.
527 pub struct GitCommitPlanTool;
528
529 #[async_trait]
530 impl ToolSpec for GitCommitPlanTool {
531 fn name(&self) -> &'static str {
532 "git_commit_plan"
533 }
534
535 fn model_visible(&self) -> bool {
536 false
537 }
538
539 fn description(&self) -> &'static str {
540 "Propose how to split the working tree into ordered atomic commits. Read-only: returns the plan and writes nothing."
541 }
542
543 fn input_schema(&self) -> Value {
544 json!({
545 "type": "object",
546 "properties": {
547 "path": {
548 "type": "string",
549 "description": "Optional subdirectory or file to scope the plan to (must be within the workspace)."
550 }
551 },
552 "additionalProperties": false
553 })
554 }
555
556 fn capabilities(&self) -> Vec<ToolCapability> {
557 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
558 }
559
560 fn approval_requirement(&self) -> ApprovalRequirement {
561 ApprovalRequirement::Auto
562 }
563
564 fn supports_parallel(&self) -> bool {
565 true
566 }
567
568 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
569 git_commit_plan(input, context.clone()).await
570 }
571 }
572
573 async fn git_commit_plan(input: Value, context: ToolContext) -> Result<ToolResult, ToolError> {
574 let path = optional_str(&input, "path")?.map(str::to_string);
575 let git_ctx = on_blocking_pool(move || resolve_git_context(&context, path.as_deref())).await?;
576 let working_dir = &git_ctx.working_dir;
577
578 let root_args = vec!["rev-parse".to_string(), "--show-toplevel".to_string()];
579 let repo_root = match git_stdout(working_dir, &root_args).await? {
580 Ok(stdout) => PathBuf::from(String::from_utf8_lossy(&stdout).trim_end()),
581 Err(failure) => return Ok(failure),
582 };
583
584 let mut diff_args = vec![
585 "-c".to_string(),
586 "core.quotepath=false".to_string(),
587 "diff".to_string(),
588 "HEAD".to_string(),
589 "--no-color".to_string(),
590 "-U3".to_string(),
591 ];
592 diff_args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from));
593 if let Some(pathspec) = &git_ctx.pathspec {
594 diff_args.push("--".to_string());
595 diff_args.push(pathspec.display().to_string());
596 }
597 let command = format_command(working_dir, &diff_args);
598 let diff_output = run_git_command_async(working_dir.clone(), diff_args.clone()).await?;
599 let mut files = match stdout_or_failure(working_dir, &diff_args, diff_output) {
600 Ok(stdout) => parse_diff(&String::from_utf8_lossy(&stdout)),
601 Err(failure) => return Ok(failure),
602 };
603
604 // Untracked files are listed by path and read for symbol analysis.
605 // Never `git add -N` them: intent-to-add mutates the index, and a
606 // planner that mutates the index is not propose-only.
607 let mut untracked_args = vec![
608 "-c".to_string(),
609 "core.quotepath=false".to_string(),
610 "ls-files".to_string(),
611 "--others".to_string(),
612 "--exclude-standard".to_string(),
613 "--full-name".to_string(),
614 "-z".to_string(),
615 ];
616 if let Some(pathspec) = &git_ctx.pathspec {
617 untracked_args.push("--".to_string());
618 untracked_args.push(pathspec.display().to_string());
619 }
620 let untracked_paths: Vec<String> = match git_stdout(working_dir, &untracked_args).await? {
621 Ok(stdout) => String::from_utf8_lossy(&stdout)
622 .split('\0')
623 .filter(|path| !path.is_empty())
624 .map(str::to_string)
625 .collect(),
626 Err(failure) => return Ok(failure),
627 };
628
629 if files.is_empty() && untracked_paths.is_empty() {
630 return Ok(
631 ToolResult::success("No changes to plan: the working tree matches HEAD.")
632 .with_metadata(json!({
633 "command": command,
634 "propose_only": true,
635 "commits": [],
636 })),
637 );
638 }
639
640 let mut staged_args = vec![
641 "diff".to_string(),
642 "--cached".to_string(),
643 "--quiet".to_string(),
644 ];
645 staged_args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from));
646 let index_has_staged_changes = run_git_command_async(working_dir.clone(), staged_args)
647 .await?
648 .status
649 .code()
650 == Some(1);
651
652 let root = repo_root.clone();
653 let planned = on_blocking_pool(move || {
654 files.extend(untracked_paths.into_iter().map(|path| ChangedFile {
655 hunks: untracked_hunk(&root, &path).into_iter().collect(),
656 path,
657 untracked: true,
658 }));
659 Ok(plan_commits(files))
660 })
661 .await?;
662
663 let commits = match planned {
664 Ok(commits) => commits,
665 Err(cycle) => {
666 let message = format!(
667 "Dependency cycle detected among changes in: {}. Atomic commit split rejected; nothing was written.\nCycle edges:\n{}",
668 cycle.files.join(", "),
669 cycle
670 .edges
671 .iter()
672 .map(|edge| format!(" {edge}"))
673 .collect::<Vec<_>>()
674 .join("\n")
675 );
676 return Ok(ToolResult::error(message).with_metadata(json!({
677 "command": command,
678 "propose_only": true,
679 "cycle_detected": true,
680 "cyclic_files": cycle.files,
681 "cycle_edges": cycle.edges,
682 })));
683 }
684 };
685
686 let content = render_commit_plan(&repo_root, index_has_staged_changes, &commits);
687 let metadata_commits: Vec<Value> = commits
688 .iter()
689 .enumerate()
690 .map(|(idx, commit)| {
691 json!({
692 "order": idx + 1,
693 "message": commit.message,
694 "files": commit.files.iter().filter(|f| !f.untracked).map(|f| &f.path).collect::<Vec<_>>(),
695 "untracked": commit.files.iter().filter(|f| f.untracked).map(|f| &f.path).collect::<Vec<_>>(),
696 "hunks": commit.files.iter().flat_map(|f| f.hunks.iter().map(|h| json!({"file": h.file_path, "header": h.header}))).collect::<Vec<_>>(),
697 "defines": commit.defines,
698 "depends_on": commit.depends_on.iter().map(|(order, reason)| json!({"order": order, "reason": reason})).collect::<Vec<_>>(),
699 })
700 })
701 .collect();
702
703 Ok(ToolResult::success(content).with_metadata(json!({
704 "command": command,
705 "repo_root": repo_root.display().to_string(),
706 "propose_only": true,
707 "cycle_detected": false,
708 "index_has_staged_changes": index_has_staged_changes,
709 "commits": metadata_commits,
710 })))
711 }
712
713 // === Helpers ===
714
715 struct GitContext {
716 working_dir: PathBuf,
717 pathspec: Option<PathBuf>,
718 }
719
720 fn resolve_git_context(context: &ToolContext, path: Option<&str>) -> Result<GitContext, ToolError> {
721 let workspace = canonical_or_workspace(&context.workspace);
722 let mut working_dir = workspace.clone();
723 let mut pathspec = None;
724
725 if let Some(raw) = path {
726 let resolved = context.resolve_path(raw)?;
727 let metadata = fs::metadata(&resolved).map_err(|e| {
728 ToolError::invalid_input(format!(
729 "Path does not exist or is not accessible: {raw} ({e})"
730 ))
731 })?;
732
733 if metadata.is_dir() {
734 working_dir = resolved;
735 pathspec = Some(PathBuf::from("."));
736 } else {
737 // For file paths, run from the parent and scope to the file name.
738 let parent = resolved.parent().ok_or_else(|| {
739 ToolError::invalid_input(format!("Path has no parent directory: {raw}"))
740 })?;
741 working_dir = parent.to_path_buf();
742 pathspec = Some(pathspec_from(&working_dir, &resolved));
743 }
744 }
745
746 if !working_dir.exists() {
747 return Err(ToolError::invalid_input(format!(
748 "Working directory does not exist: {}",
749 working_dir.display()
750 )));
751 }
752
753 Ok(GitContext {
754 working_dir,
755 pathspec,
756 })
757 }
758
759 fn canonical_or_workspace(workspace: &Path) -> PathBuf {
760 workspace
761 .canonicalize()
762 .unwrap_or_else(|_| workspace.to_path_buf())
763 }
764
765 fn pathspec_from(working_dir: &Path, resolved: &Path) -> PathBuf {
766 match resolved.strip_prefix(working_dir) {
767 Ok(rel) if rel.as_os_str().is_empty() => PathBuf::from("."),
768 Ok(rel) => rel.to_path_buf(),
769 Err(_) => PathBuf::from("."),
770 }
771 }
772
773 /// Build the git command for the read-only workspace tools (`git_diff`,
774 /// `git_log`, `git_show`, `git_blame`, `verify`; `git_status` goes through
775 /// [`codewhale_dependencies::Git::status_command`]). It goes through
776 /// [`codewhale_dependencies::Git::review_command`], so fsmonitor, hooks and
777 /// clean/process filters from the workspace's own config do not run.
778 pub(super) fn read_only_git_command(
779 working_dir: &Path,
780 ) -> Result<std::process::Command, ToolError> {
781 if !codewhale_dependencies::Git::available() {
782 return Err(ToolError::not_available(
783 "git is not installed or not in PATH",
784 ));
785 }
786 codewhale_dependencies::Git::review_command(working_dir)
787 .map_err(|e| ToolError::execution_failed(format!("Failed to prepare git: {e:#}")))
788 }
789
790 /// Run a git tool's synchronous preparation (path resolution, untracked-file
791 /// reads, planning) on the blocking pool rather than an async worker
792 /// (#6561 D03-m1).
793 async fn on_blocking_pool<T: Send + 'static>(
794 work: impl FnOnce() -> Result<T, ToolError> + Send + 'static,
795 ) -> Result<T, ToolError> {
796 tokio::task::spawn_blocking(work)
797 .await
798 .map_err(|error| ToolError::execution_failed(format!("git task panicked: {error}")))?
799 }
800
801 /// Run a read-only git command for the workspace tools. The command is
802 /// prepared on the blocking pool, because filter discovery reads repository
803 /// config through git, then runs contained
804 /// ([`codewhale_runtime::process_tree::contained_output`]): dropping the
805 /// future — a cancelled or timed-out tool call — kills git and everything it
806 /// started (D03-m3).
807 ///
808 /// Known limitation: the short config probe inside
809 /// [`codewhale_dependencies::Git::review_command`] is not contained; a call
810 /// dropped during preparation lets that probe finish on the blocking pool.
811 pub(super) async fn run_git_command_async(
812 working_dir: PathBuf,
813 args: Vec<String>,
814 ) -> Result<std::process::Output, ToolError> {
815 run_prepared_git_async(working_dir, args, read_only_git_command).await
816 }
817
818 pub(super) async fn run_git_status_async(
819 working_dir: PathBuf,
820 args: Vec<String>,
821 ) -> Result<std::process::Output, ToolError> {
822 run_prepared_git_async(working_dir, args, |dir| {
823 if !codewhale_dependencies::Git::available() {
824 return Err(ToolError::not_available(
825 "git is not installed or not in PATH",
826 ));
827 }
828 codewhale_dependencies::Git::status_command(dir)
829 .map_err(|e| ToolError::execution_failed(format!("Failed to prepare git: {e:#}")))
830 })
831 .await
832 }
833
834 async fn run_prepared_git_async(
835 working_dir: PathBuf,
836 args: Vec<String>,
837 prepare: fn(&Path) -> Result<std::process::Command, ToolError>,
838 ) -> Result<std::process::Output, ToolError> {
839 let prepare_dir = working_dir.clone();
840 let command = on_blocking_pool(move || prepare(&prepare_dir)).await?;
841 let mut command = tokio::process::Command::from(command);
842 command.args(&args).current_dir(&working_dir);
843 codewhale_runtime::process_tree::contained_output(&mut command)
844 .await
845 .map_err(|e| {
846 if e.kind() == std::io::ErrorKind::NotFound {
847 ToolError::not_available("git is not installed or not in PATH")
848 } else {
849 ToolError::execution_failed(format!("Failed to run git: {e}"))
850 }
851 })
852 }
853
854 fn format_command(working_dir: &Path, args: &[String]) -> String {
855 // `[String]::join` produces the same string as collecting `&str` first, so
856 // join the slice directly and skip the intermediate `Vec<&str>` allocation.
857 format!("git -C {} {}", working_dir.display(), args.join(" "))
858 }
859
860 // === Commit Split Specific Types & Helpers ===
861
862 // === Commit plan: types, parsing, grouping, ordering ===
863
864 /// Largest untracked file the planner reads for symbol analysis. Bigger or
865 /// binary files are still listed by path; they just carry no hunks.
866 const MAX_UNTRACKED_BYTES: u64 = 1 << 20;
867
868 /// One hunk of a unified diff, kept for symbol analysis and for the plan's
869 /// per-file hunk listing. The `@@` ranges stay in `header`: nothing rebuilds
870 /// a patch from them anymore, so parsed copies would be dead weight.
871 #[derive(Debug, Clone)]
872 pub struct Hunk {
873 pub file_path: String,
874 pub header: String,
875 pub lines: Vec<String>,
876 }
877
878 /// One file the working tree changed relative to HEAD. Tracked binary and
879 /// mode-only changes carry no hunks; untracked files carry a synthesized
880 /// all-additions hunk when they are readable text.
881 #[derive(Debug, Clone)]
882 pub struct ChangedFile {
883 pub path: String,
884 pub hunks: Vec<Hunk>,
885 pub untracked: bool,
886 }
887
888 /// One proposed commit in dependency order.
889 #[derive(Debug, Clone)]
890 pub struct PlannedCommit {
891 pub message: String,
892 /// Sorted by path; every hunk of a file stays in the same commit.
893 pub files: Vec<ChangedFile>,
894 pub defines: Vec<String>,
895 /// `(order, reason)` pairs naming the earlier commits this one builds on.
896 pub depends_on: Vec<(usize, String)>,
897 }
898
899 /// Why a plan was refused: the files on the cycle and the edges that close it.
900 #[derive(Debug, Clone)]
901 pub struct CycleDiagnostic {
902 pub files: Vec<String>,
903 pub edges: Vec<String>,
904 }
905
906 struct CommitGroup {
907 files: BTreeMap<String, ChangedFile>,
908 defined_symbols: BTreeSet<String>,
909 referenced_symbols: BTreeSet<String>,
910 }
911
912 impl CommitGroup {
913 fn from_file(file: ChangedFile) -> Self {
914 let mut defined_symbols = BTreeSet::new();
915 let mut referenced_symbols = BTreeSet::new();
916 for hunk in &file.hunks {
917 defined_symbols.extend(extract_defined_symbols(hunk));
918 referenced_symbols.extend(extract_referenced_symbols(hunk));
919 }
920 let mut group = Self {
921 files: BTreeMap::from([(file.path.clone(), file)]),
922 defined_symbols,
923 referenced_symbols,
924 };
925 group.drop_self_references();
926 group
927 }
928
929 fn absorb(&mut self, other: CommitGroup) {
930 self.files.extend(other.files);
931 self.defined_symbols.extend(other.defined_symbols);
932 self.referenced_symbols.extend(other.referenced_symbols);
933 self.drop_self_references();
934 }
935
936 fn drop_self_references(&mut self) {
937 for symbol in &self.defined_symbols {
938 self.referenced_symbols.remove(symbol);
939 }
940 }
941
942 fn has_source_file(&self) -> bool {
943 self.files.keys().any(|path| is_source_file(path))
944 }
945
946 fn first_path(&self) -> &str {
947 self.files.keys().next().map_or("", String::as_str)
948 }
949 }
950
951 /// Run git and hand back stdout, or the operator-facing failure result.
952 async fn git_stdout(
953 working_dir: &Path,
954 args: &[String],
955 ) -> Result<Result<Vec<u8>, ToolResult>, ToolError> {
956 let output = run_git_command_async(working_dir.to_path_buf(), args.to_vec()).await?;
957 Ok(stdout_or_failure(working_dir, args, output))
958 }
959
960 fn stdout_or_failure(
961 working_dir: &Path,
962 args: &[String],
963 output: std::process::Output,
964 ) -> Result<Vec<u8>, ToolResult> {
965 if output.status.success() {
966 return Ok(output.stdout);
967 }
968 let stderr = String::from_utf8_lossy(&output.stderr);
969 Err(ToolResult::error(format!(
970 "{} failed: {}",
971 format_command(working_dir, args),
972 stderr.trim()
973 )))
974 }
975
976 /// Parse `git diff` output into per-file hunks. Every `diff --git` section
977 /// yields a file even when it has no hunks (binary or mode-only change), so
978 /// no changed file can silently drop out of the plan.
979 fn parse_diff(diff_output: &str) -> Vec<ChangedFile> {
980 let mut files: Vec<ChangedFile> = Vec::new();
981 let mut current_hunk: Option<Hunk> = None;
982
983 let flush = |files: &mut Vec<ChangedFile>, hunk: Option<Hunk>| {
984 if let (Some(hunk), Some(file)) = (hunk, files.last_mut()) {
985 file.hunks.push(hunk);
986 }
987 };
988
989 for line in diff_output.lines() {
990 if let Some(rest) = line.strip_prefix("diff --git ") {
991 flush(&mut files, current_hunk.take());
992 let path = rest
993 .rfind(" b/")
994 .map(|pos| &rest[pos + 3..])
995 .unwrap_or(rest)
996 .trim_matches('"')
997 .to_string();
998 files.push(ChangedFile {
999 path,
1000 hunks: Vec::new(),
1001 untracked: false,
1002 });
1003 } else if line.starts_with("@@ ") {
1004 flush(&mut files, current_hunk.take());
1005 let Some(file) = files.last() else { continue };
1006 current_hunk = Some(Hunk {
1007 file_path: file.path.clone(),
1008 header: line.to_string(),
1009 lines: Vec::new(),
1010 });
1011 } else if let Some(hunk) = current_hunk.as_mut() {
1012 hunk.lines.push(line.to_string());
1013 }
1014 }
1015 flush(&mut files, current_hunk.take());
1016 files
1017 }
1018
1019 /// Synthesize an all-additions hunk for an untracked text file so its
1020 /// symbols take part in grouping. Binary, oversized, or unreadable files
1021 /// yield `None` and are listed by path only. So does a path that is a link
1022 /// or sits under one: an untracked link must not make this read-only tool
1023 /// return text from outside the repository.
1024 fn untracked_hunk(repo_root: &Path, path: &str) -> Option<Hunk> {
1025 use std::io::Read as _;
1026 let full = repo_root.join(path);
1027 let file = codewhale_util::fs_confined::open_read(repo_root, &full).ok()?;
1028 if file.metadata().ok()?.len() > MAX_UNTRACKED_BYTES {
1029 return None;
1030 }
1031 let mut bytes = Vec::new();
1032 file.take(MAX_UNTRACKED_BYTES + 1)
1033 .read_to_end(&mut bytes)
1034 .ok()?;
1035 if bytes.len() as u64 > MAX_UNTRACKED_BYTES {
1036 return None;
1037 }
1038 if bytes.iter().take(8000).any(|byte| *byte == 0) {
1039 return None;
1040 }
1041 let text = String::from_utf8(bytes).ok()?;
1042 let lines: Vec<String> = text.lines().map(|line| format!("+{line}")).collect();
1043 Some(Hunk {
1044 file_path: path.to_string(),
1045 header: format!("@@ -0,0 +1,{} @@", lines.len()),
1046 lines,
1047 })
1048 }
1049
1050 /// Group changed files into commits and order them by dependency.
1051 ///
1052 /// Pure: reads nothing from git and writes nothing anywhere. Returns the
1053 /// cycle diagnostic instead of a plan when the dependency graph is not a DAG.
1054 fn plan_commits(files: Vec<ChangedFile>) -> Result<Vec<PlannedCommit>, CycleDiagnostic> {
1055 let (lock_files, files): (Vec<ChangedFile>, Vec<ChangedFile>) =
1056 files.into_iter().partition(|file| is_lock_file(&file.path));
1057
1058 let mut groups: Vec<CommitGroup> = files.into_iter().map(CommitGroup::from_file).collect();
1059
1060 // Lock files are excluded from symbol analysis and ride with the manifest
1061 // change that moved them; a lock file with no manifest change stands alone.
1062 for lock in lock_files {
1063 let lock_path = lock.path.clone();
1064 let mut group = CommitGroup::from_file(lock);
1065 group.defined_symbols.clear();
1066 group.referenced_symbols.clear();
1067 match groups.iter_mut().find(|existing| {
1068 existing
1069 .files
1070 .keys()
1071 .any(|manifest| matches_lock_file(manifest, &lock_path))
1072 }) {
1073 Some(manifest_group) => manifest_group.files.extend(group.files),
1074 None => groups.push(group),
1075 }
1076 }
1077
1078 // Merge files with closely related names (source with its test/spec).
1079 let mut merged: Vec<CommitGroup> = Vec::new();
1080 for group in groups {
1081 let related = merged.iter_mut().find(|existing| {
1082 group
1083 .files
1084 .keys()
1085 .any(|a| existing.files.keys().any(|b| are_files_related(a, b)))
1086 });
1087 match related {
1088 Some(existing) => existing.absorb(group),
1089 None => merged.push(group),
1090 }
1091 }
1092 let groups = merged;
1093
1094 // Dependency graph: `edges[j]` lists the groups that must land after j.
1095 let n = groups.len();
1096 let mut edges: Vec<Vec<(usize, String)>> = vec![Vec::new(); n];
1097 let mut in_degree = vec![0usize; n];
1098 for i in 0..n {
1099 for j in 0..n {
1100 if i == j {
1101 continue;
1102 }
1103 let reason = groups[i]
1104 .referenced_symbols
1105 .iter()
1106 .find(|symbol| groups[j].defined_symbols.contains(*symbol))
1107 .map(|symbol| format!("uses `{symbol}`"))
1108 .or_else(|| {
1109 // Tests, docs, and configs follow the source change that
1110 // lives beside them.
1111 (!groups[i].has_source_file() && groups[j].has_source_file())
1112 .then(|| {
1113 groups[i]
1114 .files
1115 .keys()
1116 .any(|a| groups[j].files.keys().any(|b| share_context(a, b)))
1117 })
1118 .filter(|shares| *shares)
1119 .map(|_| "follows the source change in the same directory".to_string())
1120 });
1121 if let Some(reason) = reason {
1122 edges[j].push((i, reason));
1123 in_degree[i] += 1;
1124 }
1125 }
1126 }
1127
1128 // Kahn's algorithm; among ready groups, source changes land first, then
1129 // path order, so the plan is deterministic.
1130 let mut ready: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
1131 let mut order: Vec<usize> = Vec::with_capacity(n);
1132 while !ready.is_empty() {
1133 ready.sort_by(|&a, &b| {
1134 groups[b]
1135 .has_source_file()
1136 .cmp(&groups[a].has_source_file())
1137 .then_with(|| groups[a].first_path().cmp(groups[b].first_path()))
1138 });
1139 let current = ready.remove(0);
1140 order.push(current);
1141 for (next, _) in &edges[current] {
1142 in_degree[*next] -= 1;
1143 if in_degree[*next] == 0 {
1144 ready.push(*next);
1145 }
1146 }
1147 }
1148
1149 if order.len() < n {
1150 let cyclic: Vec<usize> = (0..n).filter(|&i| in_degree[i] > 0).collect();
1151 let files = cyclic
1152 .iter()
1153 .flat_map(|&i| groups[i].files.keys().cloned())
1154 .collect();
1155 let mut cycle_edges = Vec::new();
1156 for &j in &cyclic {
1157 for (i, reason) in &edges[j] {
1158 if cyclic.contains(i) {
1159 cycle_edges.push(format!(
1160 "{} -> {} ({reason})",
1161 groups[*i].first_path(),
1162 groups[j].first_path()
1163 ));
1164 }
1165 }
1166 }
1167 return Err(CycleDiagnostic {
1168 files,
1169 edges: cycle_edges,
1170 });
1171 }
1172
1173 let mut position = vec![0usize; n];
1174 for (idx, &group) in order.iter().enumerate() {
1175 position[group] = idx + 1;
1176 }
1177 let mut depends_on: Vec<Vec<(usize, String)>> = vec![Vec::new(); n];
1178 for (j, outgoing) in edges.iter().enumerate() {
1179 for (i, reason) in outgoing {
1180 depends_on[*i].push((position[j], reason.clone()));
1181 }
1182 }
1183
1184 Ok(order
1185 .into_iter()
1186 .map(|idx| {
1187 let mut deps = std::mem::take(&mut depends_on[idx]);
1188 deps.sort();
1189 let group = &groups[idx];
1190 PlannedCommit {
1191 message: generate_commit_message(group),
1192 files: group.files.values().cloned().collect(),
1193 defines: group.defined_symbols.iter().cloned().collect(),
1194 depends_on: deps,
1195 }
1196 })
1197 .collect())
1198 }
1199
1200 fn render_commit_plan(
1201 repo_root: &Path,
1202 index_has_staged_changes: bool,
1203 commits: &[PlannedCommit],
1204 ) -> String {
1205 let mut out = format!(
1206 "Commit plan for {}: {} commit{} (propose-only; nothing was staged or committed).\n\
1207 Groups are whole files. Land each in order from the repo root with \
1208 `git add -- <files>` then `git commit -m '<message>'`; those commands go \
1209 through the normal shell approval gate.\n",
1210 repo_root.display(),
1211 commits.len(),
1212 if commits.len() == 1 { "" } else { "s" }
1213 );
1214 if index_has_staged_changes {
1215 out.push_str(
1216 "WARNING: the index already holds staged changes. Run `git reset` before \
1217 staging commit 1, or those hunks will ride into it.\n",
1218 );
1219 }
1220 for (idx, commit) in commits.iter().enumerate() {
1221 out.push_str(&format!("\n{}. {}\n", idx + 1, commit.message));
1222 for file in &commit.files {
1223 let hunks = match file.hunks.len() {
1224 0 if file.untracked => "untracked; listed by path".to_string(),
1225 0 => "no text hunks (binary or mode change)".to_string(),
1226 1 => format!("1 hunk: {}", file.hunks[0].header),
1227 count => format!(
1228 "{count} hunks: {}",
1229 file.hunks
1230 .iter()
1231 .map(|hunk| hunk.header.as_str())
1232 .collect::<Vec<_>>()
1233 .join(" ")
1234 ),
1235 };
1236 let flag = if file.untracked { " (untracked)" } else { "" };
1237 out.push_str(&format!(" {}{flag} — {hunks}\n", file.path));
1238 }
1239 if !commit.defines.is_empty() {
1240 out.push_str(&format!(" defines: {}\n", commit.defines.join(", ")));
1241 }
1242 if commit.depends_on.is_empty() {
1243 out.push_str(" depends on: none\n");
1244 } else {
1245 let deps: Vec<String> = commit
1246 .depends_on
1247 .iter()
1248 .map(|(order, reason)| format!("{order} ({reason})"))
1249 .collect();
1250 out.push_str(&format!(" depends on: {}\n", deps.join(", ")));
1251 }
1252 }
1253 out
1254 }
1255
1256 fn is_lock_file(path: &str) -> bool {
1257 let name = file_name(path);
1258 name.ends_with(".lock")
1259 || matches!(
1260 name,
1261 "go.sum" | "package-lock.json" | "pnpm-lock.yaml" | "yarn.lock"
1262 )
1263 }
1264
1265 fn is_manifest_file(path: &str) -> bool {
1266 matches!(file_name(path), "Cargo.toml" | "package.json" | "go.mod")
1267 }
1268
1269 fn file_name(path: &str) -> &str {
1270 Path::new(path)
1271 .file_name()
1272 .and_then(|n| n.to_str())
1273 .unwrap_or(path)
1274 }
1275
1276 fn file_stem(path: &str) -> &str {
1277 Path::new(path)
1278 .file_stem()
1279 .and_then(|s| s.to_str())
1280 .unwrap_or(path)
1281 }
1282
1283 fn matches_lock_file(manifest: &str, lock: &str) -> bool {
1284 let m_path = Path::new(manifest);
1285 let l_path = Path::new(lock);
1286 if m_path.parent() != l_path.parent() {
1287 return false;
1288 }
1289 match (file_name(manifest), file_name(lock)) {
1290 ("Cargo.toml", "Cargo.lock") | ("go.mod", "go.sum") => true,
1291 ("package.json", "package-lock.json" | "yarn.lock" | "pnpm-lock.yaml") => true,
1292 (m_name, l_name) => {
1293 file_stem(manifest) == file_stem(lock)
1294 || (m_name.ends_with(".json") && l_name.ends_with(".json"))
1295 }
1296 }
1297 }
1298
1299 /// Lowercased file stem with test/spec markers removed — the name two
1300 /// related files share (`math.rs` and `math_test.rs` both reduce to `math`).
1301 fn related_stem(path: &str) -> String {
1302 file_stem(path)
1303 .to_lowercase()
1304 .replace("_test", "")
1305 .replace("test_", "")
1306 .replace("_spec", "")
1307 .replace("spec_", "")
1308 .replace("test", "")
1309 }
1310
1311 fn are_files_related(f1: &str, f2: &str) -> bool {
1312 let stem1 = file_stem(f1).to_lowercase();
1313 let stem2 = file_stem(f2).to_lowercase();
1314 if stem1 == stem2 {
1315 return true;
1316 }
1317 let clean1 = related_stem(f1);
1318 !clean1.is_empty() && clean1 == related_stem(f2)
1319 }
1320
1321 fn is_source_file(path: &str) -> bool {
1322 let p = Path::new(path);
1323 let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
1324 let name = file_name(path).to_lowercase();
1325 if name.contains("test") || name.contains("spec") || name.contains("mock") {
1326 return false;
1327 }
1328 matches!(
1329 ext,
1330 "rs" | "py" | "go" | "js" | "ts" | "cpp" | "h" | "c" | "java" | "cs" | "rb" | "php"
1331 )
1332 }
1333
1334 fn is_doc_file(path: &str) -> bool {
1335 matches!(
1336 Path::new(path).extension().and_then(|e| e.to_str()),
1337 Some("md" | "rst" | "txt" | "adoc")
1338 )
1339 }
1340
1341 fn share_context(f1: &str, f2: &str) -> bool {
1342 Path::new(f1).parent() == Path::new(f2).parent()
1343 }
1344
1345 const DEFINING_KEYWORDS: &[&str] = &[
1346 "fn",
1347 "func",
1348 "def",
1349 "function",
1350 "struct",
1351 "enum",
1352 "trait",
1353 "class",
1354 "interface",
1355 "type",
1356 "const",
1357 "let",
1358 "mod",
1359 ];
1360
1361 fn extract_defined_symbols(hunk: &Hunk) -> HashSet<String> {
1362 let mut symbols = HashSet::new();
1363 for content in added_lines(hunk) {
1364 let tokens = tokenize(content);
1365 for pair in tokens.windows(2) {
1366 if DEFINING_KEYWORDS.contains(&pair[0].as_str()) && is_valid_identifier(&pair[1]) {
1367 symbols.insert(pair[1].clone());
1368 }
1369 }
1370 }
1371 symbols
1372 }
1373
1374 fn extract_referenced_symbols(hunk: &Hunk) -> HashSet<String> {
1375 let mut symbols = HashSet::new();
1376 for content in added_lines(hunk) {
1377 for token in tokenize(content) {
1378 if is_valid_identifier(&token) && !is_keyword(&token) {
1379 symbols.insert(token);
1380 }
1381 }
1382 }
1383 symbols
1384 }
1385
1386 fn added_lines(hunk: &Hunk) -> impl Iterator<Item = &str> {
1387 hunk.lines
1388 .iter()
1389 .filter(|line| line.starts_with('+') && !line.starts_with("+++"))
1390 .map(|line| &line[1..])
1391 }
1392
1393 fn tokenize(s: &str) -> Vec<String> {
1394 s.split(|c: char| !(c.is_alphanumeric() || c == '_'))
1395 .filter(|token| !token.is_empty())
1396 .map(str::to_string)
1397 .collect()
1398 }
1399
1400 fn is_valid_identifier(s: &str) -> bool {
1401 let mut chars = s.chars();
1402 chars
1403 .next()
1404 .is_some_and(|first| first.is_alphabetic() || first == '_')
1405 && chars.all(|c| c.is_alphanumeric() || c == '_')
1406 }
1407
1408 fn is_keyword(s: &str) -> bool {
1409 matches!(
1410 s,
1411 "if" | "else"
1412 | "while"
1413 | "for"
1414 | "return"
1415 | "import"
1416 | "use"
1417 | "pub"
1418 | "impl"
1419 | "crate"
1420 | "self"
1421 | "true"
1422 | "false"
1423 | "let"
1424 | "mut"
1425 | "match"
1426 | "var"
1427 | "void"
1428 | "int"
1429 | "string"
1430 | "bool"
1431 | "float"
1432 | "double"
1433 | "public"
1434 | "private"
1435 | "protected"
1436 | "static"
1437 | "final"
1438 | "class"
1439 | "fn"
1440 | "struct"
1441 | "enum"
1442 | "trait"
1443 | "interface"
1444 | "type"
1445 | "const"
1446 | "mod"
1447 | "def"
1448 | "func"
1449 | "function"
1450 | "and"
1451 | "or"
1452 | "not"
1453 | "in"
1454 | "as"
1455 | "break"
1456 | "continue"
1457 | "new"
1458 | "this"
1459 | "super"
1460 )
1461 }
1462
1463 /// A conventional-commit proposal for one group. The model is expected to
1464 /// refine it; the point is that it names the group's single concern rather
1465 /// than "wip".
1466 fn generate_commit_message(group: &CommitGroup) -> String {
1467 let paths: Vec<&str> = group.files.keys().map(String::as_str).collect();
1468 let scope = match paths.as_slice() {
1469 [single] => file_stem(single).to_string(),
1470 _ => {
1471 // A test or spec rides with the source it names; when every file
1472 // in the group shares that stem, the stem is the subject. An
1473 // unrelated group falls back to its directory name.
1474 let shared = related_stem(paths[0]);
1475 if !shared.is_empty() && paths.iter().all(|path| related_stem(path) == shared) {
1476 shared
1477 } else {
1478 paths
1479 .iter()
1480 .map(|path| Path::new(path).parent())
1481 .reduce(|a, b| if a == b { a } else { None })
1482 .flatten()
1483 .and_then(|dir| dir.file_name().and_then(|n| n.to_str()))
1484 .map_or_else(|| "repo".to_string(), str::to_string)
1485 }
1486 }
1487 };
1488 if !group.defined_symbols.is_empty() {
1489 let shown: Vec<&str> = group
1490 .defined_symbols
1491 .iter()
1492 .take(3)
1493 .map(String::as_str)
1494 .collect();
1495 let more = group.defined_symbols.len().saturating_sub(shown.len());
1496 let suffix = if more > 0 {
1497 format!(" (+{more} more)")
1498 } else {
1499 String::new()
1500 };
1501 return format!("feat({scope}): add {}{suffix}", shown.join(", "));
1502 }
1503 let names: Vec<&str> = paths.iter().map(|path| file_name(path)).collect();
1504 let kind = if paths
1505 .iter()
1506 .all(|path| is_lock_file(path) || is_manifest_file(path))
1507 {
1508 return format!("chore(deps): update {}", names.join(", "));
1509 } else if paths.iter().all(|path| is_doc_file(path)) {
1510 "docs"
1511 } else if paths
1512 .iter()
1513 .all(|path| !is_source_file(path) && file_name(path).to_lowercase().contains("test"))
1514 {
1515 "test"
1516 } else {
1517 "chore"
1518 };
1519 format!("{kind}({scope}): update {}", names.join(", "))
1520 }
1521
1522 #[cfg(test)]
1523 mod tests {
1524 use super::*;
1525 use std::fs;
1526 use tempfile::tempdir;
1527
1528 fn git_available() -> bool {
1529 codewhale_dependencies::Git::available()
1530 }
1531
1532 fn init_git_repo(root: &Path) {
1533 let run = |args: &[&str]| {
1534 let status = codewhale_dependencies::Git::status(args, root).expect("git should spawn");
1535 assert!(status.success(), "git {args:?} failed");
1536 };
1537
1538 run(&["init", "-q"]);
1539 run(&["config", "core.autocrlf", "false"]);
1540 run(&["config", "user.email", "test@example.com"]);
1541 run(&["config", "user.name", "Test User"]);
1542 }
1543
1544 fn commit_all(root: &Path, message: &str) {
1545 let run = |args: &[&str]| {
1546 let status = codewhale_dependencies::Git::status(args, root).expect("git should spawn");
1547 assert!(status.success(), "git {args:?} failed");
1548 };
1549 run(&["add", "."]);
1550 run(&["commit", "-q", "-m", message]);
1551 }
1552
1553 #[cfg(unix)]
1554 #[tokio::test]
1555 async fn git_status_runs_no_nested_repository_filter_despite_gitmodules_ignore_entry() {
1556 use std::os::unix::fs::PermissionsExt;
1557 if !git_available() {
1558 return;
1559 }
1560 let tmp = tempdir().expect("tempdir");
1561 let helpers = tempdir().expect("helpers");
1562 let marker = helpers.path().join("ran");
1563 let script = helpers.path().join("clean.sh");
1564 fs::write(
1565 &script,
1566 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
1567 )
1568 .expect("write script");
1569 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).expect("chmod");
1570 let run = |dir: &Path, args: &[&str]| {
1571 let status = codewhale_dependencies::Git::status(args, dir).expect("git should spawn");
1572 assert!(status.success(), "git {args:?} failed");
1573 };
1574 let repo = tmp.path().join("repo");
1575 let nested = repo.join("nested");
1576 fs::create_dir_all(&nested).expect("mkdir");
1577 init_git_repo(&repo);
1578 init_git_repo(&nested);
1579 fs::write(nested.join(".gitattributes"), "*.txt filter=fixture\n").expect("attrs");
1580 fs::write(nested.join("tracked.txt"), "one\n").expect("write");
1581 commit_all(&nested, "nested");
1582 run(
1583 &nested,
1584 &["config", "filter.fixture.clean", &script.to_string_lossy()],
1585 );
1586 fs::write(
1587 repo.join(".gitmodules"),
1588 "[submodule \"nested\"]\n\tpath = nested\n\tignore = none\n",
1589 )
1590 .expect("gitmodules");
1591 commit_all(&repo, "root");
1592 fs::write(nested.join("tracked.txt"), "two\n").expect("modify");
1593 fs::File::options()
1594 .write(true)
1595 .open(nested.join("tracked.txt"))
1596 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
1597 .expect("age the file so git re-reads it");
1598
1599 let control = codewhale_dependencies::Git::output(&["status", "--porcelain"], &repo)
1600 .expect("control status");
1601 assert!(control.status.success());
1602 assert!(marker.exists(), "positive control: nested filter");
1603 fs::remove_file(&marker).expect("reset");
1604
1605 let status = GitStatusTool
1606 .execute(json!({}), &ToolContext::new(&repo))
1607 .await
1608 .expect("git_status");
1609 assert!(status.success, "{}", status.content);
1610 assert!(
1611 !marker.exists(),
1612 "git_status ran a nested repository filter: {}",
1613 fs::read_to_string(&marker).unwrap_or_default()
1614 );
1615 }
1616
1617 /// The read-only git tools must not run programs named by the
1618 /// workspace's own config: `core.fsmonitor` would otherwise execute on
1619 /// every `git_status`.
1620 #[cfg(unix)]
1621 #[tokio::test]
1622 async fn read_only_git_tools_do_not_run_workspace_fsmonitor() {
1623 use std::os::unix::fs::PermissionsExt;
1624 if !git_available() {
1625 return;
1626 }
1627 let tmp = tempdir().expect("tempdir");
1628 init_git_repo(tmp.path());
1629 fs::write(tmp.path().join("file.txt"), "hello\n").expect("write");
1630 commit_all(tmp.path(), "init");
1631 fs::write(tmp.path().join("file.txt"), "hello\nworld\n").expect("modify");
1632
1633 let hooks = tempdir().expect("hooks");
1634 let marker = hooks.path().join("ran");
1635 let hook = hooks.path().join("fsmonitor.sh");
1636 fs::write(
1637 &hook,
1638 format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()),
1639 )
1640 .expect("write hook");
1641 fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).expect("chmod");
1642 let status = codewhale_dependencies::Git::status(
1643 &["config", "core.fsmonitor", &hook.to_string_lossy()],
1644 tmp.path(),
1645 )
1646 .expect("git config");
1647 assert!(status.success());
1648
1649 let ctx = ToolContext::new(tmp.path());
1650 let status = GitStatusTool
1651 .execute(json!({}), &ctx)
1652 .await
1653 .expect("status");
1654 assert!(status.success, "{}", status.content);
1655 assert!(status.content.contains("file.txt"), "{}", status.content);
1656 let diff = GitDiffTool.execute(json!({}), &ctx).await.expect("diff");
1657 assert!(diff.success, "{}", diff.content);
1658 assert!(diff.content.contains("+world"), "{}", diff.content);
1659 assert!(!marker.exists(), "workspace fsmonitor hook ran");
1660 }
1661
1662 #[tokio::test]
1663 async fn git_status_reports_branch_and_changes() {
1664 if !git_available() {
1665 return;
1666 }
1667 let tmp = tempdir().expect("tempdir");
1668 init_git_repo(tmp.path());
1669
1670 let file = tmp.path().join("file.txt");
1671 fs::write(&file, "hello\n").expect("write");
1672 commit_all(tmp.path(), "init");
1673
1674 fs::write(&file, "hello\nworld\n").expect("modify");
1675
1676 let ctx = ToolContext::new(tmp.path());
1677 let tool = GitStatusTool;
1678 let result = tool.execute(json!({}), &ctx).await.expect("execute");
1679 assert!(result.success);
1680 assert!(result.content.contains("##"));
1681 assert!(result.content.contains("head: "));
1682 assert!(
1683 result
1684 .content
1685 .contains("status: dirty (0 staged, 1 modified, 0 untracked, 0 conflicted)"),
1686 "{}",
1687 result.content
1688 );
1689 assert!(result.content.contains("file.txt"));
1690 let meta = result.metadata.as_ref().expect("status metadata");
1691 assert_eq!(meta["clean"], false);
1692 assert_eq!(meta["staged"], 0);
1693 assert_eq!(meta["modified"], 1);
1694 assert_eq!(meta["untracked"], 0);
1695 assert_eq!(meta["unborn"], false);
1696 assert!(meta["head_sha"].as_str().is_some_and(|sha| !sha.is_empty()));
1697 }
1698
1699 #[tokio::test]
1700 async fn git_status_reports_explicit_clean_and_unborn_state() {
1701 if !git_available() {
1702 return;
1703 }
1704 let tmp = tempdir().expect("tempdir");
1705 init_git_repo(tmp.path());
1706
1707 let ctx = ToolContext::new(tmp.path());
1708 let tool = GitStatusTool;
1709 let unborn = tool.execute(json!({}), &ctx).await.expect("unborn status");
1710 assert!(unborn.success);
1711 assert!(
1712 unborn.content.contains("head: unborn"),
1713 "{}",
1714 unborn.content
1715 );
1716 assert!(
1717 unborn
1718 .content
1719 .contains("status: clean (0 staged, 0 modified, 0 untracked, 0 conflicted;"),
1720 "{}",
1721 unborn.content
1722 );
1723 let unborn_meta = unborn.metadata.as_ref().expect("unborn metadata");
1724 assert_eq!(unborn_meta["clean"], true);
1725 assert_eq!(unborn_meta["unborn"], true);
1726 assert!(unborn_meta["head_sha"].is_null());
1727
1728 fs::write(tmp.path().join("file.txt"), "hello\n").expect("write");
1729 commit_all(tmp.path(), "init");
1730
1731 let clean = tool.execute(json!({}), &ctx).await.expect("clean status");
1732 assert!(clean.success);
1733 assert!(clean.content.contains("head: "), "{}", clean.content);
1734 assert!(!clean.content.contains("head: unborn"), "{}", clean.content);
1735 assert!(
1736 clean
1737 .content
1738 .contains("status: clean (0 staged, 0 modified, 0 untracked, 0 conflicted;"),
1739 "{}",
1740 clean.content
1741 );
1742 let clean_meta = clean.metadata.as_ref().expect("clean metadata");
1743 assert_eq!(clean_meta["clean"], true);
1744 assert_eq!(clean_meta["unborn"], false);
1745 assert!(
1746 clean_meta["head_sha"]
1747 .as_str()
1748 .is_some_and(|sha| !sha.is_empty())
1749 );
1750 }
1751
1752 #[tokio::test]
1753 async fn git_status_never_calls_unchecked_paths_clean_and_counts_conflicts() {
1754 if !git_available() {
1755 return;
1756 }
1757 let tmp = tempdir().expect("tempdir");
1758 let run = |args: &[&str]| {
1759 codewhale_dependencies::Git::status(args, tmp.path()).expect("git should spawn")
1760 };
1761 init_git_repo(tmp.path());
1762 let file = tmp.path().join("file.txt");
1763 fs::create_dir(tmp.path().join("docs")).expect("mkdir");
1764 fs::write(tmp.path().join("docs/a.md"), "a\n").expect("write");
1765 fs::write(&file, "base\n").expect("write");
1766 commit_all(tmp.path(), "base");
1767 assert!(run(&["config", "status.showUntrackedFiles", "no"]).success());
1768
1769 fs::write(tmp.path().join("new.txt"), "new\n").expect("write");
1770 let ctx = ToolContext::new(tmp.path());
1771 let hidden = GitStatusTool
1772 .execute(json!({}), &ctx)
1773 .await
1774 .expect("status");
1775 assert!(hidden.content.contains("?? new.txt"), "{}", hidden.content);
1776 assert_eq!(hidden.metadata.as_ref().expect("metadata")["clean"], false);
1777
1778 let scoped = GitStatusTool
1779 .execute(json!({"path": "docs"}), &ctx)
1780 .await
1781 .expect("scoped status");
1782 assert!(
1783 scoped.content.contains("status: clean within docs ("),
1784 "{}",
1785 scoped.content
1786 );
1787 assert_eq!(scoped.metadata.as_ref().expect("metadata")["scoped"], true);
1788
1789 fs::remove_file(tmp.path().join("new.txt")).expect("remove");
1790 assert!(run(&["checkout", "-q", "-b", "other"]).success());
1791 fs::write(&file, "other\n").expect("write");
1792 commit_all(tmp.path(), "other");
1793 assert!(run(&["checkout", "-q", "-b", "mine", "HEAD~1"]).success());
1794 fs::write(&file, "mine\n").expect("write");
1795 commit_all(tmp.path(), "mine");
1796 assert!(!run(&["merge", "-q", "other"]).success());
1797 let conflict = GitStatusTool
1798 .execute(json!({}), &ctx)
1799 .await
1800 .expect("conflict status");
1801 assert!(
1802 conflict
1803 .content
1804 .contains("status: dirty (0 staged, 0 modified, 0 untracked, 1 conflicted)"),
1805 "{}",
1806 conflict.content
1807 );
1808 }
1809
1810 #[tokio::test]
1811 async fn git_status_reports_unquoted_unicode_paths() {
1812 if !git_available() {
1813 return;
1814 }
1815
1816 let tmp = tempdir().expect("tempdir");
1817 init_git_repo(tmp.path());
1818
1819 let file = tmp.path().join("中文-данные.txt");
1820 fs::write(&file, "hello\n").expect("write");
1821 commit_all(tmp.path(), "init");
1822
1823 fs::write(&file, "hello\nworld\n").expect("modify");
1824
1825 let ctx = ToolContext::new(tmp.path());
1826 let tool = GitStatusTool;
1827 let result = tool.execute(json!({}), &ctx).await.expect("execute");
1828 assert!(result.success);
1829 assert!(
1830 result
1831 .metadata
1832 .as_ref()
1833 .and_then(|m| m.get("command"))
1834 .and_then(Value::as_str)
1835 .is_some_and(|command| command.contains("status --ignore-submodules=dirty"))
1836 );
1837 assert!(result.content.contains("中文-данные.txt"));
1838 assert!(!result.content.contains("\\344"));
1839 assert!(!result.content.contains("\\320"));
1840 }
1841
1842 #[tokio::test]
1843 async fn git_diff_supports_cached_and_path_scoping() {
1844 if !git_available() {
1845 return;
1846 }
1847 let tmp = tempdir().expect("tempdir");
1848 init_git_repo(tmp.path());
1849
1850 let subdir = tmp.path().join("src");
1851 fs::create_dir_all(&subdir).expect("mkdir");
1852 let file = subdir.join("lib.rs");
1853 fs::write(&file, "pub fn one() -> i32 { 1 }\n").expect("write");
1854 commit_all(tmp.path(), "init");
1855
1856 fs::write(&file, "pub fn one() -> i32 { 2 }\n").expect("modify");
1857
1858 let ctx = ToolContext::new(tmp.path());
1859 let tool = GitDiffTool;
1860
1861 let uncached = tool
1862 .execute(json!({ "path": "src" }), &ctx)
1863 .await
1864 .expect("diff");
1865 assert!(uncached.success);
1866 assert!(uncached.content.contains("diff --git"));
1867 assert!(uncached.content.contains("lib.rs"));
1868
1869 let _ = codewhale_dependencies::Git::status(&["add", "src/lib.rs"], tmp.path())
1870 .expect("git add");
1871
1872 let cached = tool
1873 .execute(json!({ "path": "src", "cached": true }), &ctx)
1874 .await
1875 .expect("diff cached");
1876 assert!(cached.success);
1877 assert!(cached.content.contains("diff --git"));
1878 assert!(
1879 cached
1880 .metadata
1881 .as_ref()
1882 .and_then(|m| m.get("cached"))
1883 .and_then(Value::as_bool)
1884 .unwrap_or(false)
1885 );
1886 }
1887
1888 #[tokio::test]
1889 async fn git_diff_reports_unquoted_unicode_paths() {
1890 if !git_available() {
1891 return;
1892 }
1893
1894 let tmp = tempdir().expect("tempdir");
1895 init_git_repo(tmp.path());
1896
1897 let unicode_name = "\u{4e2d}\u{6587}-\u{0434}\u{0430}\u{043d}\u{043d}\u{044b}\u{0435}.txt";
1898 let file = tmp.path().join(unicode_name);
1899 fs::write(&file, "hello\n").expect("write");
1900 commit_all(tmp.path(), "init");
1901
1902 fs::write(&file, "hello\nworld\n").expect("modify");
1903
1904 let ctx = ToolContext::new(tmp.path());
1905 let tool = GitDiffTool;
1906 let result = tool.execute(json!({}), &ctx).await.expect("execute");
1907
1908 assert!(result.success);
1909 assert!(
1910 result
1911 .metadata
1912 .as_ref()
1913 .and_then(|m| m.get("command"))
1914 .and_then(Value::as_str)
1915 .is_some_and(|command| command.contains("-c core.quotepath=false"))
1916 );
1917 assert!(result.content.contains(unicode_name));
1918 assert!(!result.content.contains("\\344"));
1919 assert!(!result.content.contains("\\320"));
1920 }
1921
1922 #[test]
1923 fn format_command_joins_args_without_intermediate_vec() {
1924 let args = vec![
1925 "-c".to_string(),
1926 "core.quotepath=false".to_string(),
1927 "status".to_string(),
1928 "--porcelain=v1".to_string(),
1929 "-b".to_string(),
1930 ];
1931 let rendered = format_command(Path::new("/tmp/repo"), &args);
1932 assert_eq!(
1933 rendered,
1934 "git -C /tmp/repo -c core.quotepath=false status --porcelain=v1 -b"
1935 );
1936
1937 assert_eq!(
1938 format_command(Path::new("/tmp/repo"), &[]),
1939 "git -C /tmp/repo "
1940 );
1941 }
1942
1943 #[tokio::test]
1944 async fn git_diff_returns_a_large_diff_whole_with_its_last_file() {
1945 // #6508: git_diff used to keep the first 40,000 characters, so a big
1946 // diff silently lost its last files. Size is now the engine's one
1947 // recoverable budget, not a per-tool cut.
1948 if !git_available() {
1949 return;
1950 }
1951 let tmp = tempdir().expect("tempdir");
1952 init_git_repo(tmp.path());
1953 for name in ["a_first.txt", "z_last.txt"] {
1954 fs::write(tmp.path().join(name), "base\n").expect("write");
1955 }
1956 commit_all(tmp.path(), "init");
1957 fs::write(tmp.path().join("a_first.txt"), "big line\n".repeat(6_000)).expect("write");
1958 fs::write(tmp.path().join("z_last.txt"), "LAST FILE CHANGE\n").expect("write");
1959
1960 let result = GitDiffTool
1961 .execute(json!({}), &ToolContext::new(tmp.path()))
1962 .await
1963 .expect("diff");
1964 assert!(result.success);
1965 assert!(result.content.chars().count() > 40_000);
1966 assert!(result.content.contains("+LAST FILE CHANGE"));
1967 assert!(!result.content.contains("output truncated"));
1968 }
1969
1970 // === Commit plan (#3999) ===
1971
1972 #[test]
1973 fn test_parse_diff() {
1974 let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
1975 index e69de29..4b2a8d3 100644
1976 --- a/src/lib.rs
1977 +++ b/src/lib.rs
1978 @@ -1,3 +1,4 @@
1979 line1
1980 -line2
1981 +line2 modified
1982 line3
1983 +line4 added
1984 diff --git a/image.png b/image.png
1985 index 1111111..2222222 100644
1986 Binary files a/image.png and b/image.png differ
1987 "#;
1988 let files = parse_diff(diff);
1989 assert_eq!(files.len(), 2);
1990 let hunks = &files[0].hunks;
1991 assert_eq!(hunks.len(), 1);
1992 assert_eq!(hunks[0].file_path, "src/lib.rs");
1993 assert_eq!(hunks[0].header, "@@ -1,3 +1,4 @@");
1994 assert_eq!(hunks[0].lines.len(), 5);
1995 // A binary change has no hunks but must not vanish from the plan.
1996 assert_eq!(files[1].path, "image.png");
1997 assert!(files[1].hunks.is_empty());
1998 }
1999
2000 #[test]
2001 fn test_dependency_extraction() {
2002 let hunk = Hunk {
2003 file_path: "src/lib.rs".to_string(),
2004 header: "@@ -1 +1,2 @@".to_string(),
2005 lines: vec![
2006 " pub fn add(a: i32, b: i32) -> i32 {".to_string(),
2007 "+ let sum = a + b;".to_string(),
2008 "+ struct Answer;".to_string(),
2009 " sum".to_string(),
2010 ],
2011 };
2012 let defined = extract_defined_symbols(&hunk);
2013 let referenced = extract_referenced_symbols(&hunk);
2014
2015 assert!(defined.contains("Answer"));
2016 assert!(defined.contains("sum"));
2017 assert!(referenced.contains("sum"));
2018 assert!(referenced.contains("Answer"));
2019 }
2020
2021 fn text_file(path: &str, added: &[&str]) -> ChangedFile {
2022 ChangedFile {
2023 path: path.to_string(),
2024 hunks: vec![Hunk {
2025 file_path: path.to_string(),
2026 header: format!("@@ -1 +1,{} @@", added.len()),
2027 lines: added.iter().map(|line| format!("+{line}")).collect(),
2028 }],
2029 untracked: false,
2030 }
2031 }
2032
2033 fn paths(commit: &PlannedCommit) -> Vec<&str> {
2034 commit.files.iter().map(|f| f.path.as_str()).collect()
2035 }
2036
2037 #[test]
2038 fn plan_orders_definition_before_use_and_tests_after_source() {
2039 let commits = plan_commits(vec![
2040 text_file("src/main.rs", &["fn main() { let y = math::sub(3, 4); }"]),
2041 text_file(
2042 "src/math.rs",
2043 &["pub fn sub(a: i32, b: i32) -> i32 { a - b }"],
2044 ),
2045 text_file("src/math_test.rs", &["#[test] fn sub_works() {}"]),
2046 text_file("docs/notes.md", &["Some notes"]),
2047 ])
2048 .expect("acyclic");
2049
2050 assert_eq!(commits.len(), 3, "{commits:#?}");
2051 // The test rides with the source file it names.
2052 assert_eq!(paths(&commits[0]), vec!["src/math.rs", "src/math_test.rs"]);
2053 assert!(commits[0].depends_on.is_empty());
2054 assert_eq!(paths(&commits[1]), vec!["src/main.rs"]);
2055 assert_eq!(commits[1].depends_on, vec![(1, "uses `sub`".to_string())]);
2056 assert_eq!(paths(&commits[2]), vec!["docs/notes.md"]);
2057 assert!(
2058 commits[0].message.starts_with("feat(math): add sub"),
2059 "{}",
2060 commits[0].message
2061 );
2062 assert_eq!(commits[2].message, "docs(notes): update notes.md");
2063 }
2064
2065 #[test]
2066 fn plan_rejects_cycles_with_a_diagnostic() {
2067 let cycle = plan_commits(vec![
2068 text_file("a.rs", &["pub fn func_a2() { b::func_b2(); }"]),
2069 text_file("b.rs", &["pub fn func_b2() { a::func_a2(); }"]),
2070 ])
2071 .expect_err("cycle");
2072 assert_eq!(cycle.files, vec!["a.rs", "b.rs"]);
2073 assert!(
2074 cycle
2075 .edges
2076 .iter()
2077 .any(|edge| edge.contains("uses `func_b2`")),
2078 "{:?}",
2079 cycle.edges
2080 );
2081 }
2082
2083 #[test]
2084 fn lock_file_rides_with_its_manifest_and_stays_out_of_analysis() {
2085 let mut lock = text_file("Cargo.lock", &["name = \"serde\"", "fn sub() {}"]);
2086 lock.hunks[0].file_path = "Cargo.lock".to_string();
2087 let commits = plan_commits(vec![
2088 text_file("Cargo.toml", &["serde = \"1\""]),
2089 lock,
2090 text_file("src/math.rs", &["pub fn sub() {}"]),
2091 ])
2092 .expect("acyclic");
2093 assert_eq!(commits.len(), 2, "{commits:#?}");
2094 let deps = commits
2095 .iter()
2096 .find(|c| paths(c).contains(&"Cargo.lock"))
2097 .expect("lock group");
2098 assert_eq!(paths(deps), vec!["Cargo.lock", "Cargo.toml"]);
2099 assert_eq!(deps.message, "chore(deps): update Cargo.lock, Cargo.toml");
2100 // The lock file's tokens never create a dependency edge.
2101 assert!(
2102 commits.iter().all(|c| c.depends_on.is_empty()),
2103 "{commits:#?}"
2104 );
2105 }
2106
2107 #[cfg(unix)]
2108 #[tokio::test]
2109 async fn cancelled_read_only_git_run_kills_only_its_own_tree() {
2110 if !git_available() {
2111 return;
2112 }
2113 let tmp = tempdir().expect("tempdir");
2114 init_git_repo(tmp.path());
2115 let mut bystander = std::process::Command::new("sleep")
2116 .arg("300")
2117 .spawn()
2118 .expect("spawn bystander");
2119 let pid_file = tmp.path().join("hang.pid");
2120 let args = vec![
2121 "-c".to_string(),
2122 "alias.hang=!sleep 300 & echo $! > hang.pid; wait".to_string(),
2123 "hang".to_string(),
2124 ];
2125 let run = run_git_command_async(tmp.path().to_path_buf(), args);
2126 let grandchild =
2127 codewhale_runtime::process_tree::drop_once_pid_written(run, &pid_file).await;
2128 let grandchild_exited = codewhale_runtime::process_tree::wait_for_pid_exit(
2129 grandchild,
2130 std::time::Duration::from_secs(5),
2131 );
2132 let bystander_alive = bystander.try_wait().expect("poll bystander").is_none();
2133 let _ = bystander.kill();
2134 let _ = bystander.wait();
2135 assert!(
2136 grandchild_exited,
2137 "a process git started outlived the cancelled call"
2138 );
2139 assert!(
2140 bystander_alive,
2141 "cancelling git signalled an unrelated process"
2142 );
2143 }
2144
2145 fn git_out(root: &Path, args: &[&str]) -> String {
2146 let output = codewhale_dependencies::Git::output(args, root).expect("git");
2147 assert!(output.status.success(), "git {args:?} failed");
2148 String::from_utf8_lossy(&output.stdout).to_string()
2149 }
2150
2151 #[tokio::test]
2152 async fn commit_plan_proposes_without_touching_the_index() {
2153 if !git_available() {
2154 return;
2155 }
2156 let tmp = tempdir().expect("tempdir");
2157 init_git_repo(tmp.path());
2158
2159 let math_file = tmp.path().join("math.rs");
2160 let main_file = tmp.path().join("main.rs");
2161 fs::write(&math_file, "pub fn add(a: i32, b: i32) -> i32 { a + b }\n").expect("write");
2162 fs::write(&main_file, "fn main() { let x = math::add(1, 2); }\n").expect("write");
2163 commit_all(tmp.path(), "init");
2164
2165 fs::write(
2166 &math_file,
2167 "pub fn add(a: i32, b: i32) -> i32 { a + b }\npub fn sub(a: i32, b: i32) -> i32 { a - b }\n",
2168 )
2169 .expect("modify");
2170 fs::write(
2171 &main_file,
2172 "fn main() { let x = math::add(1, 2); let y = math::sub(3, 4); }\n",
2173 )
2174 .expect("modify");
2175 fs::write(tmp.path().join("NOTES.md"), "untracked notes\n").expect("write");
2176
2177 let ctx = ToolContext::new(tmp.path());
2178 let result = GitCommitPlanTool
2179 .execute(json!({}), &ctx)
2180 .await
2181 .expect("execute");
2182 assert!(result.success, "{}", result.content);
2183 assert!(
2184 result.content.contains("propose-only"),
2185 "{}",
2186 result.content
2187 );
2188 let metadata = result.metadata.expect("metadata");
2189 let commits = metadata["commits"].as_array().expect("commits");
2190 assert_eq!(commits.len(), 3, "{}", result.content);
2191 assert_eq!(commits[0]["files"], json!(["math.rs"]));
2192 assert_eq!(commits[1]["files"], json!(["main.rs"]));
2193 assert_eq!(commits[1]["depends_on"][0]["order"], json!(1));
2194 assert_eq!(commits[2]["untracked"], json!(["NOTES.md"]));
2195 assert_eq!(metadata["index_has_staged_changes"], json!(false));
2196
2197 // Nothing was staged, intent-added, or committed.
2198 assert_eq!(
2199 git_out(tmp.path(), &["diff", "--cached", "--name-only"]),
2200 ""
2201 );
2202 assert_eq!(
2203 git_out(tmp.path(), &["rev-list", "--count", "HEAD"]).trim(),
2204 "1"
2205 );
2206 assert_eq!(
2207 git_out(tmp.path(), &["ls-files", "--others", "--exclude-standard"]).trim(),
2208 "NOTES.md"
2209 );
2210
2211 // The plan lands through the ordinary write path, in order.
2212 for commit in commits {
2213 let mut add = vec!["add", "--"];
2214 let files: Vec<String> = commit["files"]
2215 .as_array()
2216 .unwrap()
2217 .iter()
2218 .chain(commit["untracked"].as_array().unwrap())
2219 .map(|f| f.as_str().unwrap().to_string())
2220 .collect();
2221 add.extend(files.iter().map(String::as_str));
2222 git_out(tmp.path(), &add);
2223 git_out(
2224 tmp.path(),
2225 &["commit", "-q", "-m", commit["message"].as_str().unwrap()],
2226 );
2227 }
2228 assert_eq!(
2229 git_out(tmp.path(), &["rev-list", "--count", "HEAD"]).trim(),
2230 "4"
2231 );
2232 assert_eq!(git_out(tmp.path(), &["status", "--porcelain"]), "");
2233 }
2234
2235 #[tokio::test]
2236 async fn commit_plan_rejects_cycles_and_writes_nothing() {
2237 if !git_available() {
2238 return;
2239 }
2240 let tmp = tempdir().expect("tempdir");
2241 init_git_repo(tmp.path());
2242
2243 let a_file = tmp.path().join("a.rs");
2244 let b_file = tmp.path().join("b.rs");
2245 fs::write(&a_file, "pub fn func_a() {}\n").expect("write a");
2246 fs::write(&b_file, "pub fn func_b() {}\n").expect("write b");
2247 commit_all(tmp.path(), "init");
2248
2249 fs::write(
2250 &a_file,
2251 "pub fn func_a() {}\npub fn func_a2() { b::func_b2(); }\n",
2252 )
2253 .expect("modify a");
2254 fs::write(
2255 &b_file,
2256 "pub fn func_b() {}\npub fn func_b2() { a::func_a2(); }\n",
2257 )
2258 .expect("modify b");
2259
2260 let ctx = ToolContext::new(tmp.path());
2261 let result = GitCommitPlanTool
2262 .execute(json!({}), &ctx)
2263 .await
2264 .expect("execute");
2265 assert!(!result.success);
2266 assert!(
2267 result.content.contains("Dependency cycle detected"),
2268 "{}",
2269 result.content
2270 );
2271 assert!(
2272 result.content.contains("nothing was written"),
2273 "{}",
2274 result.content
2275 );
2276 assert_eq!(result.metadata.unwrap()["cycle_detected"], json!(true));
2277 assert_eq!(
2278 git_out(tmp.path(), &["diff", "--cached", "--name-only"]),
2279 ""
2280 );
2281 assert_eq!(
2282 git_out(tmp.path(), &["rev-list", "--count", "HEAD"]).trim(),
2283 "1"
2284 );
2285 }
2286
2287 #[tokio::test]
2288 async fn commit_plan_warns_when_the_index_already_holds_changes() {
2289 if !git_available() {
2290 return;
2291 }
2292 let tmp = tempdir().expect("tempdir");
2293 init_git_repo(tmp.path());
2294 let file = tmp.path().join("a.rs");
2295 fs::write(&file, "pub fn a() {}\n").expect("write");
2296 commit_all(tmp.path(), "init");
2297 fs::write(&file, "pub fn a() {}\npub fn a2() {}\n").expect("modify");
2298 git_out(tmp.path(), &["add", "a.rs"]);
2299
2300 let ctx = ToolContext::new(tmp.path());
2301 let result = GitCommitPlanTool
2302 .execute(json!({}), &ctx)
2303 .await
2304 .expect("execute");
2305 assert!(result.success, "{}", result.content);
2306 assert!(
2307 result
2308 .content
2309 .contains("WARNING: the index already holds staged changes")
2310 );
2311 assert_eq!(
2312 result.metadata.unwrap()["index_has_staged_changes"],
2313 json!(true)
2314 );
2315 // Still staged exactly as the user left it.
2316 assert_eq!(
2317 git_out(tmp.path(), &["diff", "--cached", "--name-only"]).trim(),
2318 "a.rs"
2319 );
2320 }
2321
2322 #[tokio::test]
2323 async fn commit_plan_reports_a_clean_tree() {
2324 if !git_available() {
2325 return;
2326 }
2327 let tmp = tempdir().expect("tempdir");
2328 init_git_repo(tmp.path());
2329 fs::write(tmp.path().join("a.rs"), "pub fn a() {}\n").expect("write");
2330 commit_all(tmp.path(), "init");
2331
2332 let ctx = ToolContext::new(tmp.path());
2333 let result = GitCommitPlanTool
2334 .execute(json!({}), &ctx)
2335 .await
2336 .expect("execute");
2337 assert!(result.success);
2338 assert!(
2339 result.content.contains("No changes to plan"),
2340 "{}",
2341 result.content
2342 );
2343 }
2344
2345 /// Diff and show reads must not run commands a repository configures:
2346 /// a superproject textconv driver, or — through a child git spawned in a
2347 /// submodule for its dirty check or `diff.submodule=diff` — a submodule's
2348 /// clean filter or external diff driver.
2349 #[cfg(unix)]
2350 #[tokio::test]
2351 async fn diff_and_show_reads_run_no_repository_configured_commands() {
2352 use std::os::unix::fs::PermissionsExt;
2353 if !git_available() {
2354 return;
2355 }
2356 let tmp = tempdir().expect("tempdir");
2357 let marker = tmp.path().join("marker");
2358 let script = |name: &str, body: &str| {
2359 let path = tmp.path().join(name);
2360 fs::write(
2361 &path,
2362 format!("#!/bin/sh\necho {name} >> '{}'\n{body}", marker.display()),
2363 )
2364 .expect("write script");
2365 fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod");
2366 path.display().to_string()
2367 };
2368 let clean = script("clean.sh", "cat\n");
2369 let external = script("external.sh", "");
2370 let textconv = script("textconv.sh", "cat \"$1\"\n");
2371 let git = |dir: &Path, args: &[&str]| {
2372 let status = codewhale_dependencies::Git::status(args, dir).expect("git should spawn");
2373 assert!(status.success(), "git {args:?} failed");
2374 };
2375 let identity = ["-c", "user.email=test@example.com", "-c", "user.name=Test"];
2376
2377 let upstream = tmp.path().join("upstream");
2378 fs::create_dir_all(&upstream).expect("mkdir upstream");
2379 init_git_repo(&upstream);
2380 fs::write(upstream.join("f.txt"), "a\n").expect("write");
2381 commit_all(&upstream, "init");
2382
2383 let repo = tmp.path().join("repo");
2384 fs::create_dir_all(&repo).expect("mkdir repo");
2385 init_git_repo(&repo);
2386 fs::write(
2387 repo.join(".gitattributes"),
2388 "a.md diff=conv\nc.txt filter=x\n",
2389 )
2390 .expect("attrs");
2391 fs::write(repo.join("a.md"), "one\n").expect("write");
2392 fs::write(repo.join("c.txt"), "c1\n").expect("write");
2393 let upstream_arg = upstream.display().to_string();
2394 git(
2395 &repo,
2396 &[
2397 "-c",
2398 "protocol.file.allow=always",
2399 "submodule",
2400 "add",
2401 "-q",
2402 &upstream_arg,
2403 "sub",
2404 ],
2405 );
2406 commit_all(&repo, "init");
2407
2408 let sub = repo.join("sub");
2409 fs::write(sub.join(".gitattributes"), "* filter=evil\n").expect("sub attrs");
2410 git(&sub, &[&identity[..], &["add", "."]].concat());
2411 git(
2412 &sub,
2413 &[&identity[..], &["commit", "-q", "-m", "attrs"]].concat(),
2414 );
2415 git(&sub, &["config", "filter.evil.clean", &clean]);
2416 git(&sub, &["config", "diff.external", &external]);
2417 let edited = sub.join("f.txt");
2418 fs::write(&edited, "c\n").expect("same-size edit");
2419 fs::File::options()
2420 .write(true)
2421 .open(&edited)
2422 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
2423 .expect("age the edit so git re-reads it");
2424 git(&repo, &["config", "diff.submodule", "diff"]);
2425 git(&repo, &["config", "submodule.sub.ignore", "none"]);
2426 git(&repo, &["config", "diff.conv.textconv", &textconv]);
2427 fs::write(repo.join("a.md"), "two\n").expect("modify");
2428
2429 let no_marker = |step: &str| {
2430 assert!(
2431 !marker.exists(),
2432 "{step} ran a repository-configured command: {}",
2433 fs::read_to_string(&marker).unwrap_or_default()
2434 );
2435 };
2436 let ctx = ToolContext::new(&repo);
2437 let diff = GitDiffTool
2438 .execute(json!({}), &ctx)
2439 .await
2440 .expect("git_diff");
2441 no_marker("git_diff");
2442 assert!(diff.success, "{}", diff.content);
2443 assert!(
2444 diff.content.contains("Subproject commit"),
2445 "{}",
2446 diff.content
2447 );
2448 assert!(diff.content.contains("+two"), "{}", diff.content);
2449
2450 git(&repo, &["add", "sub"]);
2451 git(
2452 &repo,
2453 &[&identity[..], &["commit", "-q", "-m", "bump", "--", "sub"]].concat(),
2454 );
2455 let show = super::super::git_history::GitShowTool
2456 .execute(json!({"rev": "HEAD"}), &ctx)
2457 .await
2458 .expect("git_show");
2459 no_marker("git_show");
2460 assert!(show.success, "{}", show.content);
2461 assert!(
2462 show.content.contains("Subproject commit"),
2463 "{}",
2464 show.content
2465 );
2466
2467 // Working-tree reads also run the superproject's clean filter, which
2468 // no diff flag disables; blame applies textconv unless told not to.
2469 git(&repo, &["config", "filter.x.clean", &clean]);
2470 fs::write(repo.join("c.txt"), "c2\n").expect("modify");
2471 let diff = GitDiffTool
2472 .execute(json!({}), &ctx)
2473 .await
2474 .expect("git_diff");
2475 no_marker("git_diff with a clean filter");
2476 assert!(diff.content.contains("+c2"), "{}", diff.content);
2477 let plan = GitCommitPlanTool
2478 .execute(json!({}), &ctx)
2479 .await
2480 .expect("git_commit_plan");
2481 no_marker("git_commit_plan");
2482 assert!(plan.success, "{}", plan.content);
2483 let blame = super::super::git_history::GitBlameTool
2484 .execute(json!({"path": "a.md"}), &ctx)
2485 .await
2486 .expect("git_blame");
2487 no_marker("git_blame");
2488 assert!(blame.success, "{}", blame.content);
2489 }
2490
2491 #[cfg(unix)]
2492 #[tokio::test]
2493 async fn git_status_runs_no_nested_repository_filter() {
2494 use std::os::unix::fs::PermissionsExt;
2495 if !git_available() {
2496 return;
2497 }
2498 let tmp = tempdir().expect("tempdir");
2499 let marker = tmp.path().join("marker");
2500 let clean = tmp.path().join("clean.sh");
2501 fs::write(
2502 &clean,
2503 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
2504 )
2505 .expect("write script");
2506 fs::set_permissions(&clean, fs::Permissions::from_mode(0o755)).expect("chmod");
2507 let git = |dir: &Path, args: &[&str]| {
2508 let status = codewhale_dependencies::Git::status(args, dir).expect("git should spawn");
2509 assert!(status.success(), "git {args:?} failed");
2510 };
2511
2512 let repo = tmp.path().join("repo");
2513 let sub = repo.join("sub");
2514 for dir in [&repo, &sub] {
2515 fs::create_dir_all(dir).expect("mkdir");
2516 init_git_repo(dir);
2517 }
2518 fs::write(sub.join(".gitattributes"), "* filter=evil\n").expect("attrs");
2519 fs::write(sub.join("f.txt"), "a\n").expect("write");
2520 commit_all(&sub, "sub");
2521 commit_all(&repo, "top");
2522 git(
2523 &sub,
2524 &["config", "filter.evil.clean", &clean.display().to_string()],
2525 );
2526 git(&repo, &["config", "submodule.sub.ignore", "none"]);
2527 fs::File::options()
2528 .write(true)
2529 .open(sub.join("f.txt"))
2530 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
2531 .expect("age the file so git re-reads it");
2532
2533 let control =
2534 codewhale_dependencies::Git::output(&["status", "--porcelain"], &repo).expect("status");
2535 assert!(control.status.success());
2536 assert!(marker.exists(), "positive control: nested filter");
2537 fs::remove_file(&marker).expect("reset");
2538
2539 let status = GitStatusTool
2540 .execute(json!({}), &ToolContext::new(&repo))
2541 .await
2542 .expect("git_status");
2543 assert!(status.success, "{}", status.content);
2544 assert!(
2545 !marker.exists(),
2546 "git_status ran a nested repository filter: {}",
2547 fs::read_to_string(&marker).unwrap_or_default()
2548 );
2549 }
2550
2551 #[cfg(unix)]
2552 #[test]
2553 fn untracked_links_are_listed_by_path_and_never_read() {
2554 let outside = tempdir().expect("outside");
2555 let secret = outside.path().join("secret.txt");
2556 fs::write(&secret, "fn outside_marker() {}\n").expect("write");
2557 let repo = tempdir().expect("repo");
2558 fs::write(repo.path().join("plain.rs"), "fn inside() {}\n").expect("write");
2559 std::os::unix::fs::symlink(&secret, repo.path().join("link.rs")).expect("link");
2560 std::os::unix::fs::symlink(outside.path(), repo.path().join("dir")).expect("link");
2561
2562 assert!(untracked_hunk(repo.path(), "plain.rs").is_some());
2563 assert!(untracked_hunk(repo.path(), "link.rs").is_none());
2564 assert!(untracked_hunk(repo.path(), "dir/secret.txt").is_none());
2565 }
2566 }
2567
2567 lines RUST