返回 CodeWhale
file_mutation.rs
根目录 / crates / tui / src / tui / history / file_mutation.rs
1 //! Structured, success-only File mutation receipts.
2 //!
3 //! Tool execution owns the exact before/after evidence. This module shapes
4 //! that evidence for the calm transcript without depending on whether an
5 //! approval modal happened to run.
6
7 use std::path::{Component, Path};
8
9 use ratatui::style::Style;
10 use ratatui::text::Line;
11 use serde_json::Value;
12
13 use codewhale_engine::tools::spec::ToolResult;
14 use codewhale_localization::{Locale, MessageId, tr};
15 use codewhale_palette as palette;
16 use codewhale_runtime::settings::InlineDiffMode;
17 use codewhale_tui_kit::diff_render;
18
19 use super::details_affordance_line;
20
21 const MAX_INLINE_DIFF_LINES: usize = 14;
22 const MAX_SUMMARY_CHARS: usize = 180;
23
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum FileMutationOutcome {
26 Created,
27 Updated,
28 Deleted,
29 Renamed,
30 }
31
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub struct FileMutationFile {
34 pub path: String,
35 pub previous_path: Option<String>,
36 pub outcome: FileMutationOutcome,
37 }
38
39 #[derive(Debug, Clone, PartialEq, Eq)]
40 pub struct FileMutationReceipt {
41 /// Raw execution-owned evidence exposed only through the explicit detail
42 /// route. It is never painted into the ambient Work/transcript surface.
43 pub exact_diff: String,
44 /// Header-redacted copy safe for inline presentation.
45 pub display_diff: String,
46 pub files: Vec<FileMutationFile>,
47 pub added: usize,
48 pub deleted: usize,
49 }
50
51 impl FileMutationReceipt {
52 /// Build a receipt only from an authoritative successful tool result.
53 /// Failed/cancelled calls never carry a success diff into the transcript.
54 #[must_use]
55 pub fn from_success(workspace: &Path, result: &ToolResult) -> Option<Self> {
56 if !result.success {
57 return None;
58 }
59 let mutation = result.metadata.as_ref()?.get("mutation")?;
60 let raw_diff = mutation.get("diff")?.as_str().unwrap_or("");
61 let exact_diff = raw_diff.to_string();
62 let display_diff = redact_diff_headers(workspace, raw_diff);
63 let mut files = Vec::new();
64
65 if let Some(entries) = mutation.get("files").and_then(Value::as_array) {
66 for entry in entries {
67 let Some(raw_path) = entry.get("path").and_then(Value::as_str) else {
68 continue;
69 };
70 let outcome = match entry.get("outcome").and_then(Value::as_str) {
71 Some("created") => FileMutationOutcome::Created,
72 Some("updated") => FileMutationOutcome::Updated,
73 Some("deleted") => FileMutationOutcome::Deleted,
74 _ => continue,
75 };
76 files.push(FileMutationFile {
77 path: privacy_safe_path(workspace, raw_path),
78 previous_path: None,
79 outcome,
80 });
81 }
82 }
83 if let Some(renames) = mutation.get("renames").and_then(Value::as_array) {
84 for rename in renames {
85 let Some(from) = rename.get("from").and_then(Value::as_str) else {
86 continue;
87 };
88 let Some(to) = rename.get("to").and_then(Value::as_str) else {
89 continue;
90 };
91 files.push(FileMutationFile {
92 path: privacy_safe_path(workspace, to),
93 previous_path: Some(privacy_safe_path(workspace, from)),
94 outcome: FileMutationOutcome::Renamed,
95 });
96 }
97 }
98
99 let totals = diff_render::diff_totals(&display_diff);
100 let added = totals.added;
101 let deleted = totals.deleted;
102 if files.is_empty() && exact_diff.trim().is_empty() {
103 return None;
104 }
105 Some(Self {
106 exact_diff,
107 display_diff,
108 files,
109 added,
110 deleted,
111 })
112 }
113
114 #[must_use]
115 pub fn outcome_label(&self, locale: Locale) -> String {
116 let created = self.count(FileMutationOutcome::Created);
117 let updated = self.count(FileMutationOutcome::Updated);
118 let deleted = self.count(FileMutationOutcome::Deleted);
119 let renamed = self.count(FileMutationOutcome::Renamed);
120 let mut outcome_parts = Vec::new();
121 push_count(
122 &mut outcome_parts,
123 created,
124 locale,
125 MessageId::FileMutationCreatedCount,
126 );
127 push_count(
128 &mut outcome_parts,
129 updated,
130 locale,
131 MessageId::FileMutationUpdatedCount,
132 );
133 push_count(
134 &mut outcome_parts,
135 deleted,
136 locale,
137 MessageId::FileMutationDeletedCount,
138 );
139 push_count(
140 &mut outcome_parts,
141 renamed,
142 locale,
143 MessageId::FileMutationRenamedCount,
144 );
145
146 if self.files.is_empty() {
147 tr(locale, MessageId::FileMutationChangedFiles).into_owned()
148 } else if self.files.len() == 1 {
149 let file = &self.files[0];
150 match file.outcome {
151 FileMutationOutcome::Created => {
152 tr(locale, MessageId::FileMutationCreated).replace("{path}", &file.path)
153 }
154 FileMutationOutcome::Updated => {
155 tr(locale, MessageId::FileMutationUpdated).replace("{path}", &file.path)
156 }
157 FileMutationOutcome::Deleted => {
158 tr(locale, MessageId::FileMutationDeleted).replace("{path}", &file.path)
159 }
160 FileMutationOutcome::Renamed => {
161 let fallback = tr(locale, MessageId::FileMutationMissingFile);
162 let paths = format!(
163 "{} → {}",
164 file.previous_path.as_deref().unwrap_or(fallback.as_ref()),
165 file.path
166 );
167 tr(locale, MessageId::FileMutationRenamed).replace("{path}", &paths)
168 }
169 }
170 } else {
171 let count = super::tool_run::counted(
172 self.files.len(),
173 locale,
174 MessageId::ActivityFileOne,
175 MessageId::ActivityFileMany,
176 );
177 format!("{count} · {}", outcome_parts.join(" · "))
178 }
179 }
180
181 #[must_use]
182 pub fn semantic_summary(&self, locale: Locale) -> String {
183 let stats = format!("+{} -{}", self.added, self.deleted);
184 let separator_chars = " · ".chars().count();
185 let outcome_budget = MAX_SUMMARY_CHARS
186 .saturating_sub(stats.chars().count())
187 .saturating_sub(separator_chars);
188 format!(
189 "{} · {stats}",
190 bounded_text(&self.outcome_label(locale), outcome_budget)
191 )
192 }
193
194 #[must_use]
195 pub fn inspect_text(&self, locale: Locale) -> String {
196 let summary = self.semantic_summary(locale);
197 if self.exact_diff.trim().is_empty() {
198 format!("{summary}\n\n{}", tr(locale, MessageId::FileMutationNoText))
199 } else {
200 format!("{summary}\n\n{}", self.exact_diff)
201 }
202 }
203
204 pub fn render_inline(
205 &self,
206 width: u16,
207 mode: InlineDiffMode,
208 locale: Locale,
209 ) -> Vec<Line<'static>> {
210 match mode {
211 InlineDiffMode::Off | InlineDiffMode::Summary => vec![exact_evidence_hint(locale)],
212 InlineDiffMode::Full => {
213 let mut lines = Vec::new();
214 if !self.display_diff.trim().is_empty() {
215 let rendered = diff_render::render_diff_body_bounded(
216 &self.display_diff,
217 width,
218 MAX_INLINE_DIFF_LINES,
219 );
220 lines.extend(rendered.lines);
221 if rendered.omitted_rows > 0 {
222 let detail_hint =
223 crate::tui::key_shortcuts::tool_details_shortcut_action_hint(
224 tr(locale, MessageId::FileMutationChange).as_ref(),
225 );
226 lines.push(details_affordance_line(
227 &tr(locale, MessageId::FileMutationMoreDiff)
228 .replace("{count}", &rendered.omitted_rows.to_string())
229 .replace("{hint}", &detail_hint),
230 Style::default().fg(palette::TEXT_MUTED).italic(),
231 ));
232 } else {
233 lines.push(exact_evidence_hint(locale));
234 }
235 } else {
236 lines.push(exact_evidence_hint(locale));
237 }
238 lines
239 }
240 }
241 }
242
243 fn count(&self, outcome: FileMutationOutcome) -> usize {
244 self.files
245 .iter()
246 .filter(|file| file.outcome == outcome)
247 .count()
248 }
249 }
250
251 fn exact_evidence_hint(locale: Locale) -> Line<'static> {
252 details_affordance_line(
253 &crate::tui::key_shortcuts::tool_details_shortcut_action_hint(
254 tr(locale, MessageId::FileMutationChange).as_ref(),
255 ),
256 Style::default().fg(palette::TEXT_MUTED).italic(),
257 )
258 }
259
260 fn push_count(parts: &mut Vec<String>, count: usize, locale: Locale, label: MessageId) {
261 if count > 0 {
262 parts.push(tr(locale, label).replace("{count}", &count.to_string()));
263 }
264 }
265
266 fn bounded_text(value: &str, max_chars: usize) -> String {
267 if value.chars().count() <= max_chars {
268 return value.to_string();
269 }
270 if max_chars == 0 {
271 return String::new();
272 }
273 let mut bounded = value
274 .chars()
275 .take(max_chars.saturating_sub(1))
276 .collect::<String>();
277 bounded.push('…');
278 bounded
279 }
280
281 fn privacy_safe_path(workspace: &Path, raw: &str) -> String {
282 let normalized = raw.replace('\\', "/");
283 let workspace = workspace.to_string_lossy().replace('\\', "/");
284 let relative = if Path::new(raw).is_absolute() || normalized.starts_with('/') {
285 let prefix = workspace.trim_end_matches('/');
286 if normalized == prefix {
287 ""
288 } else if let Some(relative) = normalized.strip_prefix(&format!("{prefix}/")) {
289 relative
290 } else {
291 return "<external file>".to_string();
292 }
293 } else {
294 normalized.as_str()
295 };
296 let path = Path::new(relative);
297 if path.components().any(|component| {
298 matches!(
299 component,
300 Component::ParentDir | Component::RootDir | Component::Prefix(_)
301 )
302 }) {
303 return "<external file>".to_string();
304 }
305 let display = path.to_string_lossy().replace('\\', "/");
306 if display.is_empty() {
307 "<workspace>".to_string()
308 } else {
309 display
310 }
311 }
312
313 fn redact_diff_headers(workspace: &Path, diff: &str) -> String {
314 let mut redacted = diff
315 .lines()
316 .map(|line| {
317 for prefix in ["--- ", "+++ ", "rename from ", "rename to "] {
318 if let Some(raw) = line.strip_prefix(prefix) {
319 if raw == "/dev/null" {
320 return line.to_string();
321 }
322 let side = if raw.starts_with("a/") {
323 "a/"
324 } else if raw.starts_with("b/") {
325 "b/"
326 } else {
327 ""
328 };
329 let path = raw.strip_prefix(side).unwrap_or(raw);
330 return format!("{prefix}{side}{}", privacy_safe_path(workspace, path));
331 }
332 }
333 if let Some(rest) = line.strip_prefix("diff --git ") {
334 let mut paths = rest.split_whitespace();
335 if let (Some(old), Some(new)) = (paths.next(), paths.next()) {
336 let old = old.strip_prefix("a/").unwrap_or(old);
337 let new = new.strip_prefix("b/").unwrap_or(new);
338 return format!(
339 "diff --git a/{} b/{}",
340 privacy_safe_path(workspace, old),
341 privacy_safe_path(workspace, new)
342 );
343 }
344 }
345 line.to_string()
346 })
347 .collect::<Vec<_>>()
348 .join("\n");
349 if diff.ends_with('\n') {
350 redacted.push('\n');
351 }
352 redacted
353 }
354
355 #[cfg(test)]
356 mod tests {
357 use super::*;
358 use serde_json::json;
359
360 fn plain(lines: &[Line<'_>]) -> String {
361 lines
362 .iter()
363 .map(|line| {
364 line.spans
365 .iter()
366 .map(|span| span.content.as_ref())
367 .collect::<String>()
368 })
369 .collect::<Vec<_>>()
370 .join("\n")
371 }
372
373 fn result(mutation: Value) -> ToolResult {
374 ToolResult::success("ok").with_metadata(json!({ "mutation": mutation }))
375 }
376
377 #[test]
378 fn creates_bounded_semantic_summary_and_redacts_external_headers() {
379 let result = result(json!({
380 "diff": "--- /Users/alice/private.rs\n+++ /Users/alice/private.rs\n@@ -0,0 +1 @@\n+secret\n",
381 "files": [{ "path": "/Users/alice/private.rs", "outcome": "created" }],
382 "renames": []
383 }));
384 let receipt =
385 FileMutationReceipt::from_success(Path::new("/workspace"), &result).expect("receipt");
386 assert_eq!(receipt.files[0].path, "<external file>");
387 assert!(receipt.exact_diff.contains("alice"));
388 assert!(!receipt.display_diff.contains("alice"));
389 assert!(
390 receipt
391 .semantic_summary(Locale::En)
392 .contains("Created <external file>")
393 );
394 }
395
396 #[test]
397 fn rename_and_multifile_outcomes_stay_semantic() {
398 let result = result(json!({
399 "diff": "diff --git a/old.rs b/new.rs\nrename from old.rs\nrename to new.rs\n--- a/lib.rs\n+++ b/lib.rs\n@@ -1 +1 @@\n-old\n+new\n",
400 "files": [{ "path": "lib.rs", "outcome": "updated" }],
401 "renames": [{ "from": "old.rs", "to": "new.rs" }]
402 }));
403 let receipt =
404 FileMutationReceipt::from_success(Path::new("/workspace"), &result).expect("receipt");
405 assert_eq!(receipt.files.len(), 2);
406 assert_eq!(receipt.added, 1);
407 assert_eq!(receipt.deleted, 1);
408 assert_eq!(
409 receipt.semantic_summary(Locale::En),
410 "2 files · 1 updated · 1 renamed · +1 -1"
411 );
412 let renamed = FileMutationReceipt {
413 exact_diff: String::new(),
414 display_diff: String::new(),
415 files: vec![FileMutationFile {
416 path: "new{path}.rs".into(),
417 previous_path: Some("old{path}.rs".into()),
418 outcome: FileMutationOutcome::Renamed,
419 }],
420 added: 0,
421 deleted: 0,
422 };
423 assert_eq!(
424 renamed.outcome_label(Locale::En),
425 "Renamed old{path}.rs → new{path}.rs"
426 );
427 for (locale, verb) in [
428 (Locale::ZhHans, "已重命名"),
429 (Locale::ZhHant, "已重新命名"),
430 (Locale::Ja, "名前変更"),
431 ] {
432 let text = renamed.semantic_summary(locale);
433 assert!(text.starts_with(verb), "{text}");
434 assert!(text.contains("old{path}.rs → new{path}.rs"), "{text}");
435 assert!(text.ends_with("+0 -0"), "{text}");
436 }
437 }
438
439 #[test]
440 fn failed_results_never_become_success_receipts() {
441 let failed = ToolResult::error("cancelled").with_metadata(json!({
442 "mutation": {
443 "diff": "--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n",
444 "files": [{ "path": "a", "outcome": "updated" }],
445 "renames": []
446 }
447 }));
448 assert!(FileMutationReceipt::from_success(Path::new("/workspace"), &failed).is_none());
449 }
450
451 #[test]
452 fn inline_diff_modes_are_bounded_and_keep_the_exact_detail_route() {
453 let additions = (0..30)
454 .map(|index| format!("+line {index}"))
455 .collect::<Vec<_>>()
456 .join("\n");
457 let result = result(json!({
458 "diff": format!("--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -0,0 +1,30 @@\n{additions}\n"),
459 "files": [{ "path": "src/lib.rs", "outcome": "created" }],
460 "renames": []
461 }));
462 let receipt =
463 FileMutationReceipt::from_success(Path::new("/workspace"), &result).expect("receipt");
464
465 let full = receipt.render_inline(80, InlineDiffMode::Full, Locale::En);
466 let full_text = plain(&full);
467 assert!(full.len() <= MAX_INLINE_DIFF_LINES + 2, "{full_text}");
468 assert!(full_text.contains("line 0"), "{full_text}");
469 assert!(full_text.contains("diff lines"), "{full_text}");
470 assert!(full_text.contains(" change"), "{full_text}");
471 assert!(!full_text.contains("summary:"), "{full_text}");
472
473 let summary = plain(&receipt.render_inline(80, InlineDiffMode::Summary, Locale::En));
474 assert!(!summary.contains("Created src/lib.rs"), "{summary}");
475 assert!(!summary.contains("+30 -0"), "{summary}");
476 assert!(!summary.contains("line 0"), "{summary}");
477 assert!(summary.contains(" change"), "{summary}");
478
479 let off = plain(&receipt.render_inline(80, InlineDiffMode::Off, Locale::En));
480 assert!(!off.contains("line 0"), "{off}");
481 assert!(!off.contains("+30 -0"), "{off}");
482 assert!(off.contains(" change"), "{off}");
483 }
484
485 #[test]
486 fn full_mode_spends_its_bound_on_red_green_evidence() {
487 let result = result(json!({
488 "diff": "diff --git a/old.rs b/new.rs\nsimilarity index 100%\nrename from old.rs\nrename to new.rs\ndiff --git a/lib.rs b/lib.rs\n--- a/lib.rs\n+++ b/lib.rs\n@@ -1 +1 @@\n-old\n+new\n",
489 "files": [{ "path": "lib.rs", "outcome": "updated" }],
490 "renames": [{ "from": "old.rs", "to": "new.rs" }]
491 }));
492 let receipt =
493 FileMutationReceipt::from_success(Path::new("/workspace"), &result).expect("receipt");
494 let full_text = plain(&receipt.render_inline(80, InlineDiffMode::Full, Locale::En));
495
496 assert!(full_text.contains("- old"), "{full_text}");
497 assert!(full_text.contains("+ new"), "{full_text}");
498 assert!(!full_text.contains("summary:"), "{full_text}");
499 }
500
501 #[test]
502 fn bounded_summary_never_truncates_semantic_stats() {
503 let long_path = format!("src/{}.rs", "whale".repeat(80));
504 let result = result(json!({
505 "diff": format!("--- a/{long_path}\n+++ b/{long_path}\n@@ -1 +1 @@\n-old\n+new\n"),
506 "files": [{ "path": long_path, "outcome": "updated" }],
507 "renames": []
508 }));
509 let receipt =
510 FileMutationReceipt::from_success(Path::new("/workspace"), &result).expect("receipt");
511 let summary = receipt.semantic_summary(Locale::En);
512 assert!(summary.ends_with(" · +1 -1"), "{summary}");
513 assert!(summary.chars().count() <= MAX_SUMMARY_CHARS);
514 }
515
516 #[test]
517 fn failed_file_cell_never_paints_a_forged_success_receipt() {
518 let receipt = FileMutationReceipt::from_success(
519 Path::new("/workspace"),
520 &result(json!({
521 "diff": "--- a/a.rs\n+++ b/a.rs\n@@ -1 +1 @@\n-old\n+FORGED-SUCCESS\n",
522 "files": [{ "path": "a.rs", "outcome": "updated" }],
523 "renames": []
524 })),
525 )
526 .expect("receipt");
527 let cell = super::super::PatchSummaryCell {
528 path: "a.rs".to_string(),
529 summary: "editing".to_string(),
530 status: super::super::ToolStatus::Failed,
531 error: Some("cancelled".to_string()),
532 receipt: Some(receipt),
533 };
534
535 let text = plain(&cell.render(
536 80,
537 true,
538 super::super::RenderMode::Live,
539 InlineDiffMode::Full,
540 codewhale_localization::Locale::En,
541 ));
542 assert!(text.contains("cancelled"), "{text}");
543 assert!(!text.contains("FORGED-SUCCESS"), "{text}");
544 }
545 }
546
546 lines RUST