返回 CodeWhale
git_mention.rs
根目录 / crates / tui / src / tui / git_mention.rs
1 //! `@git` and `@diff` composer mentions (#4067).
2 //!
3 //! The `@` mention system is otherwise path-centric: every token resolves to
4 //! a file or directory. These two tokens resolve to *curated git context*
5 //! instead, so a user can attach "what is going on in this working tree"
6 //! inline rather than making the model spend a round-trip on `git_diff` or a
7 //! shell command that may need approval.
8 //!
9 //! Two deliberate boundaries:
10 //!
11 //! * **Read-only and bounded.** Only `git status` and `git diff` run, always
12 //! with an explicit byte budget and time limit. A repository with a huge
13 //! working-tree diff truncates with a visible marker rather than flooding
14 //! the turn, and a wedged git reports a timeout instead of hanging it.
15 //! * **Honest when unavailable.** No git binary, or a directory that is not a
16 //! repository, produces an explicit `<git-unavailable>` block. A mention
17 //! never silently contributes nothing.
18
19 use std::io;
20 use std::path::Path;
21 use std::time::Duration;
22
23 use codewhale_dependencies::run_bounded_git_with_timeout;
24 use codewhale_dependencies::{ExternalTool, Git};
25
26 const GIT_MENTION_TIMEOUT: Duration = Duration::from_secs(10);
27 const GIT_COMMAND_FAILED: &str = "git command failed";
28 const GIT_COMMAND_TIMED_OUT: &str = "git command timed out";
29 const GIT_COMMAND_NOT_RUN: &str = "git could not run safely";
30
31 /// Byte ceiling for the inlined `@diff` payload. Documented here because the
32 /// context inspector reports the budget alongside actual size.
33 pub const MAX_GIT_DIFF_MENTION_BYTES: usize = 32 * 1024;
34 /// Byte ceiling for the inlined `@git` status summary. Status output is
35 /// bounded in practice, but an unignored `node_modules` can still produce
36 /// tens of thousands of lines.
37 pub const MAX_GIT_STATUS_MENTION_BYTES: usize = 8 * 1024;
38
39 /// Which curated git payload a mention token asks for.
40 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41 pub enum GitMentionKind {
42 /// `@git` — a bounded `git status` summary plus the current branch.
43 Status,
44 /// `@diff` — the working-tree diff, staged and unstaged.
45 Diff,
46 }
47
48 impl GitMentionKind {
49 /// The mention token that selects this payload, without the `@`.
50 #[must_use]
51 pub fn token(self) -> &'static str {
52 match self {
53 Self::Status => "git",
54 Self::Diff => "diff",
55 }
56 }
57
58 /// Byte budget for the inlined payload.
59 #[must_use]
60 pub fn byte_budget(self) -> usize {
61 match self {
62 Self::Status => MAX_GIT_STATUS_MENTION_BYTES,
63 Self::Diff => MAX_GIT_DIFF_MENTION_BYTES,
64 }
65 }
66
67 /// Every git mention kind, in completion-menu order.
68 pub fn iter_all() -> impl Iterator<Item = Self> {
69 GIT_MENTION_KINDS.into_iter()
70 }
71
72 /// Short label for composer previews and the context inspector.
73 #[must_use]
74 pub fn label(self) -> &'static str {
75 match self {
76 Self::Status => "git status",
77 Self::Diff => "working-tree diff",
78 }
79 }
80 }
81
82 /// Every git mention token, in completion-menu order.
83 pub const GIT_MENTION_KINDS: [GitMentionKind; 2] = [GitMentionKind::Status, GitMentionKind::Diff];
84
85 /// Classify a raw mention token. Case-insensitive so `@Git` and `@Diff`
86 /// behave like the lowercase spellings; a path that merely *starts* with
87 /// `git` (`@git/config`, `@diff.txt`) stays a file mention.
88 #[must_use]
89 pub fn git_mention_kind(raw: &str) -> Option<GitMentionKind> {
90 let token = raw.trim();
91 GIT_MENTION_KINDS
92 .into_iter()
93 .find(|kind| token.eq_ignore_ascii_case(kind.token()))
94 }
95
96 /// Outcome of resolving a git mention against a working directory.
97 #[derive(Debug, Clone, PartialEq, Eq)]
98 pub struct GitMentionPayload {
99 /// The model-facing block, already wrapped in its tag.
100 pub block: String,
101 /// Byte size of the payload actually inlined (the tag itself excluded).
102 pub bytes: usize,
103 /// Whether the payload hit its budget and was cut.
104 pub truncated: bool,
105 /// Present when git could not produce the payload at all.
106 pub unavailable_reason: Option<String>,
107 }
108
109 impl GitMentionPayload {
110 fn unavailable(kind: GitMentionKind, reason: &str) -> Self {
111 Self {
112 block: format!(
113 "<git-unavailable mention=\"@{token}\" reason=\"{reason}\" />",
114 token = kind.token(),
115 ),
116 bytes: 0,
117 truncated: false,
118 unavailable_reason: Some(reason.to_string()),
119 }
120 }
121 }
122
123 /// Per-submit memo for resolved git mentions.
124 ///
125 /// One message send resolves mentions twice — once to build the context
126 /// inspector references and once to build the model-facing payload. For
127 /// `@diff` each resolution makes git compute the *entire* working-tree diff
128 /// before the 32 KB budget applies, so a large repository paid for that twice
129 /// to attach it once.
130 ///
131 /// Scoped deliberately: a cache lives for one submit and is then dropped, so a
132 /// second `@diff` in a later message always re-shells out and can never show a
133 /// stale working tree.
134 #[derive(Debug, Default)]
135 pub struct GitMentionCache {
136 resolved: std::collections::HashMap<(GitMentionKind, std::path::PathBuf), GitMentionPayload>,
137 }
138
139 impl GitMentionCache {
140 /// Number of distinct mentions resolved so far this submit. Used by tests
141 /// to prove one submit shells out once per mention.
142 #[cfg(test)]
143 #[must_use]
144 pub fn len(&self) -> usize {
145 self.resolved.len()
146 }
147
148 /// Resolve `kind` against `workspace`, reusing this submit's result.
149 pub fn resolve(&mut self, kind: GitMentionKind, workspace: &Path) -> &GitMentionPayload {
150 self.resolved
151 .entry((kind, workspace.to_path_buf()))
152 .or_insert_with(|| resolve_git_mention(kind, workspace))
153 }
154 }
155
156 /// Run the git commands for `kind` in `cwd` and render the model-facing block.
157 ///
158 /// Never returns an error: an unavailable git, a non-repository directory, or
159 /// a failing command all resolve to an explicit `<git-unavailable>` block so
160 /// the turn records why the mention contributed nothing.
161 #[must_use]
162 pub fn resolve_git_mention(kind: GitMentionKind, cwd: &Path) -> GitMentionPayload {
163 if !Git::available() {
164 return GitMentionPayload::unavailable(kind, "git not found on PATH");
165 }
166 match git_output(&["rev-parse", "--is-inside-work-tree"], cwd) {
167 Ok(out) if out.trim() == "true" => {}
168 Ok(_) | Err(GIT_COMMAND_FAILED) => {
169 return GitMentionPayload::unavailable(kind, "not a git repository");
170 }
171 Err(reason) => return GitMentionPayload::unavailable(kind, reason),
172 }
173
174 let raw = match kind {
175 GitMentionKind::Status => git_status_payload(cwd),
176 GitMentionKind::Diff => git_output(
177 &[&["diff"][..], &Git::REVIEW_DIFF_ARGS[..], &["HEAD"][..]].concat(),
178 cwd,
179 ),
180 };
181 let raw = match raw {
182 Ok(raw) => raw,
183 Err(reason) => return GitMentionPayload::unavailable(kind, reason),
184 };
185
186 if raw.trim().is_empty() {
187 let reason = match kind {
188 GitMentionKind::Status => "working tree clean",
189 GitMentionKind::Diff => "no working-tree changes",
190 };
191 return GitMentionPayload::unavailable(kind, reason);
192 }
193
194 let (body, truncated) = truncate_on_char_boundary(&raw, kind.byte_budget());
195 let tag = match kind {
196 GitMentionKind::Status => "git-status",
197 GitMentionKind::Diff => "git-diff",
198 };
199 let truncated_attr = if truncated {
200 format!(
201 " truncated=\"true\" budget-bytes=\"{}\"",
202 kind.byte_budget()
203 )
204 } else {
205 String::new()
206 };
207 let block = format!(
208 "<{tag} mention=\"@{token}\" bytes=\"{bytes}\"{truncated_attr}>\n{body}\n</{tag}>",
209 token = kind.token(),
210 bytes = body.len(),
211 );
212
213 GitMentionPayload {
214 block,
215 bytes: body.len(),
216 truncated,
217 unavailable_reason: None,
218 }
219 }
220
221 /// `git status` plus the branch line, so the model does not have to infer the
222 /// branch from a porcelain listing.
223 fn git_status_payload(cwd: &Path) -> Result<String, &'static str> {
224 run_git(Git::status_command(cwd), &["--short", "--branch"], "status")
225 }
226
227 /// Run git and return stdout, or the `<git-unavailable>` reason when the
228 /// binary is missing, the command exits non-zero, or it outlives
229 /// `GIT_MENTION_TIMEOUT` and is killed.
230 ///
231 /// Runs under [`Git::review_command`], so repository-configured filters,
232 /// fsmonitor and hooks do not execute while reading the working tree.
233 fn git_output(args: &[&str], cwd: &Path) -> Result<String, &'static str> {
234 run_git(
235 Git::review_command(cwd),
236 args,
237 args.first().copied().unwrap_or("git"),
238 )
239 }
240
241 fn run_git(
242 command: anyhow::Result<std::process::Command>,
243 args: &[&str],
244 subcommand: &str,
245 ) -> Result<String, &'static str> {
246 let mut command = command.map_err(|err| {
247 if err
248 .chain()
249 .filter_map(|cause| cause.downcast_ref::<io::Error>())
250 .any(|cause| cause.kind() == io::ErrorKind::TimedOut)
251 {
252 GIT_COMMAND_TIMED_OUT
253 } else {
254 GIT_COMMAND_NOT_RUN
255 }
256 })?;
257 command.args(args);
258 let output = run_bounded_git_with_timeout(&mut command, subcommand, GIT_MENTION_TIMEOUT)
259 .map_err(|err| match err.kind() {
260 io::ErrorKind::TimedOut => GIT_COMMAND_TIMED_OUT,
261 _ => GIT_COMMAND_NOT_RUN,
262 })?;
263 if !output.status.success() {
264 return Err(GIT_COMMAND_FAILED);
265 }
266 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
267 }
268
269 /// Cut `text` to at most `budget` bytes without splitting a UTF-8 scalar.
270 /// Returns the slice and whether anything was dropped.
271 fn truncate_on_char_boundary(text: &str, budget: usize) -> (&str, bool) {
272 if text.len() <= budget {
273 return (text, false);
274 }
275 let mut end = budget;
276 while end > 0 && !text.is_char_boundary(end) {
277 end -= 1;
278 }
279 (&text[..end], true)
280 }
281
282 #[cfg(test)]
283 mod tests {
284 use super::*;
285 use std::process::Command;
286
287 fn init_repo(dir: &Path) {
288 for args in [
289 vec!["init", "--initial-branch=main"],
290 vec!["config", "user.email", "test@example.com"],
291 vec!["config", "user.name", "Test"],
292 ] {
293 let status = Command::new("git")
294 .args(&args)
295 .current_dir(dir)
296 .output()
297 .expect("git available in tests");
298 assert!(status.status.success(), "git {args:?} failed");
299 }
300 }
301
302 fn commit_all(dir: &Path, message: &str) {
303 Command::new("git")
304 .args(["add", "-A"])
305 .current_dir(dir)
306 .output()
307 .unwrap();
308 Command::new("git")
309 .args(["commit", "-m", message])
310 .current_dir(dir)
311 .output()
312 .unwrap();
313 }
314
315 #[test]
316 fn only_exact_tokens_are_git_mentions() {
317 assert_eq!(git_mention_kind("git"), Some(GitMentionKind::Status));
318 assert_eq!(git_mention_kind("Diff"), Some(GitMentionKind::Diff));
319 // Paths that merely start with the token stay file mentions.
320 assert_eq!(git_mention_kind("git/config"), None);
321 assert_eq!(git_mention_kind("diff.txt"), None);
322 assert_eq!(git_mention_kind("gitignore"), None);
323 }
324
325 #[test]
326 fn non_repository_directory_is_explicitly_unavailable() {
327 let dir = tempfile::tempdir().unwrap();
328 let payload = resolve_git_mention(GitMentionKind::Diff, dir.path());
329 assert_eq!(payload.bytes, 0);
330 assert!(payload.block.contains("git-unavailable"));
331 assert!(
332 payload
333 .unavailable_reason
334 .as_deref()
335 .is_some_and(|r| r.contains("not a git repository")),
336 "unexpected reason: {:?}",
337 payload.unavailable_reason
338 );
339 }
340
341 #[test]
342 fn empty_repository_reports_clean_rather_than_an_empty_block() {
343 let dir = tempfile::tempdir().unwrap();
344 init_repo(dir.path());
345 std::fs::write(dir.path().join("a.txt"), "hello\n").unwrap();
346 commit_all(dir.path(), "initial");
347
348 let payload = resolve_git_mention(GitMentionKind::Diff, dir.path());
349 assert_eq!(payload.bytes, 0);
350 assert!(payload.block.contains("no working-tree changes"));
351 }
352
353 /// `@diff` and `@git` read the working tree without running the
354 /// repository's external diff, textconv or clean filter.
355 #[cfg(unix)]
356 #[test]
357 fn mentions_run_no_repository_configured_commands() {
358 use std::os::unix::fs::PermissionsExt;
359 let dir = tempfile::tempdir().unwrap();
360 let outside = tempfile::tempdir().unwrap();
361 let marker = outside.path().join("marker");
362 let script = outside.path().join("helper.sh");
363 std::fs::write(
364 &script,
365 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
366 )
367 .unwrap();
368 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
369 let script = script.display().to_string();
370 init_repo(dir.path());
371 std::fs::write(
372 dir.path().join(".gitattributes"),
373 "a.txt diff=conv filter=x\n",
374 )
375 .unwrap();
376 std::fs::write(dir.path().join("a.txt"), "hello\n").unwrap();
377 commit_all(dir.path(), "initial");
378 for (key, value) in [
379 ("filter.x.clean", &script),
380 ("diff.conv.textconv", &script),
381 ("diff.external", &script),
382 ] {
383 let status = Command::new("git")
384 .args(["config", key, value])
385 .current_dir(dir.path())
386 .status()
387 .unwrap();
388 assert!(status.success());
389 }
390 std::fs::write(dir.path().join("a.txt"), "changed\n").unwrap();
391
392 let diff = resolve_git_mention(GitMentionKind::Diff, dir.path());
393 let status = resolve_git_mention(GitMentionKind::Status, dir.path());
394 assert!(
395 !marker.exists(),
396 "a mention ran a repository-configured command"
397 );
398 assert!(diff.block.contains("+changed"), "{}", diff.block);
399 assert!(status.block.contains("a.txt"), "{}", status.block);
400 }
401
402 #[cfg(unix)]
403 #[test]
404 fn status_mention_runs_no_nested_repository_filter() {
405 use std::os::unix::fs::PermissionsExt;
406 let dir = tempfile::tempdir().unwrap();
407 let outside = tempfile::tempdir().unwrap();
408 let marker = outside.path().join("marker");
409 let script = outside.path().join("helper.sh");
410 std::fs::write(
411 &script,
412 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
413 )
414 .unwrap();
415 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
416 let sub = dir.path().join("sub");
417 std::fs::create_dir(&sub).unwrap();
418 init_repo(dir.path());
419 init_repo(&sub);
420 std::fs::write(sub.join(".gitattributes"), "* filter=evil\n").unwrap();
421 std::fs::write(sub.join("f.txt"), "a\n").unwrap();
422 commit_all(&sub, "sub");
423 commit_all(dir.path(), "top");
424 for (cwd, key, value) in [
425 (
426 sub.as_path(),
427 "filter.evil.clean",
428 script.display().to_string(),
429 ),
430 (dir.path(), "submodule.sub.ignore", "none".to_string()),
431 ] {
432 let status = Command::new("git")
433 .args(["config", key, &value])
434 .current_dir(cwd)
435 .status()
436 .unwrap();
437 assert!(status.success());
438 }
439 std::fs::File::options()
440 .write(true)
441 .open(sub.join("f.txt"))
442 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
443 .unwrap();
444
445 let control = Command::new("git")
446 .args(["status", "--short"])
447 .current_dir(dir.path())
448 .output()
449 .unwrap();
450 assert!(control.status.success());
451 assert!(marker.exists(), "positive control: nested filter");
452 std::fs::remove_file(&marker).unwrap();
453
454 let payload = resolve_git_mention(GitMentionKind::Status, dir.path());
455 assert!(payload.unavailable_reason.is_none(), "{}", payload.block);
456 assert!(
457 !marker.exists(),
458 "the status mention ran a nested repository filter"
459 );
460 }
461
462 #[cfg(unix)]
463 #[test]
464 fn status_mention_runs_no_nested_repository_filter_despite_gitmodules_ignore_entry() {
465 use std::os::unix::fs::PermissionsExt;
466 let dir = tempfile::tempdir().unwrap();
467 let outside = tempfile::tempdir().unwrap();
468 let marker = outside.path().join("marker");
469 let script = outside.path().join("clean.sh");
470 std::fs::write(
471 &script,
472 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
473 )
474 .unwrap();
475 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
476 let root = dir.path().join("repo");
477 let nested = root.join("nested");
478 std::fs::create_dir_all(&nested).unwrap();
479 init_repo(&root);
480 init_repo(&nested);
481 std::fs::write(nested.join(".gitattributes"), "*.txt filter=fixture\n").unwrap();
482 std::fs::write(nested.join("tracked.txt"), "one\n").unwrap();
483 commit_all(&nested, "nested");
484 let configured = Command::new("git")
485 .args(["config", "filter.fixture.clean"])
486 .arg(&script)
487 .current_dir(&nested)
488 .status()
489 .unwrap();
490 assert!(configured.success());
491 std::fs::write(
492 root.join(".gitmodules"),
493 "[submodule \"nested\"]\n\tpath = nested\n\tignore = none\n",
494 )
495 .unwrap();
496 commit_all(&root, "root");
497 std::fs::write(nested.join("tracked.txt"), "two\n").unwrap();
498 std::fs::File::options()
499 .write(true)
500 .open(nested.join("tracked.txt"))
501 .and_then(|file| file.set_modified(std::time::UNIX_EPOCH))
502 .unwrap();
503
504 let control = Command::new("git")
505 .args(["status", "--porcelain"])
506 .current_dir(&root)
507 .output()
508 .unwrap();
509 assert!(control.status.success());
510 assert!(marker.exists(), "positive control: nested filter");
511 std::fs::remove_file(&marker).unwrap();
512
513 let payload = resolve_git_mention(GitMentionKind::Status, &root);
514 assert!(payload.unavailable_reason.is_none(), "{}", payload.block);
515 assert!(
516 !marker.exists(),
517 "@git ran a nested repository filter: {}",
518 std::fs::read_to_string(&marker).unwrap_or_default()
519 );
520 }
521
522 #[test]
523 fn status_reports_branch_and_dirty_paths() {
524 let dir = tempfile::tempdir().unwrap();
525 init_repo(dir.path());
526 std::fs::write(dir.path().join("a.txt"), "hello\n").unwrap();
527 commit_all(dir.path(), "initial");
528 std::fs::write(dir.path().join("b.txt"), "new\n").unwrap();
529
530 let payload = resolve_git_mention(GitMentionKind::Status, dir.path());
531 assert!(payload.unavailable_reason.is_none());
532 assert!(payload.block.starts_with("<git-status mention=\"@git\""));
533 assert!(payload.block.contains("b.txt"), "{}", payload.block);
534 assert!(!payload.truncated);
535 }
536
537 #[test]
538 fn mentions_name_non_ascii_paths_as_written() {
539 let dir = tempfile::tempdir().unwrap();
540 init_repo(dir.path());
541 Command::new("git")
542 .args(["config", "core.quotePath", "true"])
543 .current_dir(dir.path())
544 .output()
545 .unwrap();
546 std::fs::write(dir.path().join("笔记 📝.md"), "旧\n").unwrap();
547 commit_all(dir.path(), "initial");
548 std::fs::write(dir.path().join("笔记 📝.md"), "新\n").unwrap();
549
550 let status = resolve_git_mention(GitMentionKind::Status, dir.path());
551 let diff = resolve_git_mention(GitMentionKind::Diff, dir.path());
552 assert!(status.block.contains("笔记 📝.md"), "{}", status.block);
553 assert!(diff.block.contains("b/笔记 📝.md"), "{}", diff.block);
554 }
555
556 #[test]
557 fn diff_covers_staged_and_unstaged_changes() {
558 let dir = tempfile::tempdir().unwrap();
559 init_repo(dir.path());
560 std::fs::write(dir.path().join("a.txt"), "one\n").unwrap();
561 std::fs::write(dir.path().join("b.txt"), "one\n").unwrap();
562 commit_all(dir.path(), "initial");
563
564 std::fs::write(dir.path().join("a.txt"), "staged\n").unwrap();
565 Command::new("git")
566 .args(["add", "a.txt"])
567 .current_dir(dir.path())
568 .output()
569 .unwrap();
570 std::fs::write(dir.path().join("b.txt"), "unstaged\n").unwrap();
571
572 let payload = resolve_git_mention(GitMentionKind::Diff, dir.path());
573 assert!(payload.unavailable_reason.is_none());
574 assert!(payload.block.contains("staged"), "{}", payload.block);
575 assert!(payload.block.contains("unstaged"), "{}", payload.block);
576 }
577
578 #[test]
579 fn large_diff_truncates_at_the_documented_budget() {
580 let dir = tempfile::tempdir().unwrap();
581 init_repo(dir.path());
582 std::fs::write(dir.path().join("big.txt"), "seed\n").unwrap();
583 commit_all(dir.path(), "initial");
584
585 let bulk: String = (0..40_000).map(|i| format!("line {i}\n")).collect();
586 std::fs::write(dir.path().join("big.txt"), bulk).unwrap();
587
588 let payload = resolve_git_mention(GitMentionKind::Diff, dir.path());
589 assert!(payload.truncated, "expected truncation");
590 assert!(payload.bytes <= MAX_GIT_DIFF_MENTION_BYTES);
591 assert!(payload.block.contains("truncated=\"true\""));
592 assert!(payload.block.contains("budget-bytes=\"32768\""));
593 }
594
595 #[test]
596 fn truncation_never_splits_a_utf8_scalar() {
597 // Budget lands mid-scalar: "é" is two bytes starting at index 1.
598 let (cut, truncated) = truncate_on_char_boundary("aéb", 2);
599 assert!(truncated);
600 assert_eq!(cut, "a");
601 }
602 }
603
603 lines RUST