返回 CodeWhale
receipts.rs
1 //! Shared pure receipt rendering, moved from `crate::receipts`.
2 //! All data classification/redaction and I/O remain in the authoritative builder.
3
4 use codewhale_command_contract::facets::debug_receipts::*;
5
6 pub fn bounded(text: &str, max: usize) -> String {
7 if text.chars().count() <= max {
8 return text.to_string();
9 }
10 let mut out: String = text.chars().take(max.saturating_sub(1)).collect();
11 out.push('…');
12 out
13 }
14
15 /// One line of totals, verbs first: `Changed 4 files · ran 7 commands · 2
16 /// approved by you · 9 ran without asking under Full Access · 1 denied by
17 /// you`.
18 #[must_use]
19 pub fn totals_line(receipt: &Receipt) -> String {
20 let totals = &receipt.totals;
21 let mut parts: Vec<String> = Vec::new();
22 if totals.files_changed > 0 {
23 let mut part = format!("changed {}", plural(totals.files_changed, "file", "files"));
24 if totals.line_counts_complete {
25 part.push_str(&format!(
26 " (+{} −{})",
27 totals.lines_added, totals.lines_removed
28 ));
29 }
30 if totals.files_changed_outside_file_tools > 0 {
31 part.push_str(&format!(
32 ", {} outside file tools",
33 totals.files_changed_outside_file_tools
34 ));
35 }
36 parts.push(part);
37 }
38 if totals.commands > 0 {
39 let mut part = format!("ran {}", plural(totals.commands, "command", "commands"));
40 if totals.commands_failed > 0 {
41 part.push_str(&format!(" ({} failed)", totals.commands_failed));
42 }
43 parts.push(part);
44 }
45 if totals.code_runs > 0 {
46 parts.push(format!(
47 "ran code {}",
48 plural(totals.code_runs, "time", "times")
49 ));
50 }
51 if totals.network > 0 {
52 parts.push(format!(
53 "made {}",
54 plural(totals.network, "web request", "web requests")
55 ));
56 }
57 if totals.mcp_calls > 0 {
58 parts.push(format!(
59 "made {}",
60 plural(totals.mcp_calls, "MCP call", "MCP calls")
61 ));
62 }
63 if totals.plugin_changes > 0 {
64 parts.push(format!(
65 "changed {}",
66 plural(totals.plugin_changes, "plugin", "plugins")
67 ));
68 }
69 if totals.subagents > 0 {
70 parts.push(format!(
71 "started {}",
72 plural(totals.subagents, "agent", "agents")
73 ));
74 }
75 let approvals = &totals.approvals;
76 let by_decider = |verb: &str, by: &DeciderCounts| -> Vec<String> {
77 [
78 (by.you, "by you"),
79 (by.session_rule, "by session rule"),
80 (by.posture, "by posture"),
81 (by.not_recorded, "(decider not recorded)"),
82 ]
83 .into_iter()
84 .filter(|(count, _)| *count > 0)
85 .map(|(count, who)| format!("{count} {verb} {who}"))
86 .collect()
87 };
88 parts.extend(by_decider("approved", &approvals.approved_by));
89 if totals.ran_without_asking > 0 {
90 let mut part = format!("{} ran without asking", totals.ran_without_asking);
91 if !receipt.postures.is_empty() {
92 part.push_str(&format!(" under {}", receipt.postures.join(" and ")));
93 }
94 parts.push(part);
95 }
96 parts.extend(by_decider("denied", &approvals.denied_by));
97 if approvals.timed_out > 0 {
98 parts.push(format!("{} timed out", approvals.timed_out));
99 }
100 if approvals.not_answered > 0 {
101 parts.push(format!("{} not answered", approvals.not_answered));
102 }
103 if approvals.pending > 0 {
104 parts.push(format!("{} waiting", approvals.pending));
105 }
106 if totals.blocked > 0 {
107 parts.push(format!("{} blocked before running", totals.blocked));
108 }
109 let failures_beyond_commands = totals.failures.saturating_sub(totals.commands_failed);
110 if failures_beyond_commands > 0 {
111 parts.push(plural(
112 failures_beyond_commands,
113 "other failure",
114 "other failures",
115 ));
116 }
117 if parts.is_empty() {
118 return if totals.other_tool_calls > 0 {
119 format!(
120 "Only read or looked things up ({}).",
121 plural(totals.other_tool_calls, "call", "calls")
122 )
123 } else {
124 "No actions recorded.".to_string()
125 };
126 }
127 let mut line = parts.join(" · ");
128 if let Some(first) = line.get(0..1) {
129 line = first.to_uppercase() + &line[1..];
130 }
131 line
132 }
133
134 pub fn plural(count: usize, one: &str, many: &str) -> String {
135 if count == 1 {
136 format!("1 {one}")
137 } else {
138 format!("{count} {many}")
139 }
140 }
141
142 fn decider_label(decider: ApprovalDecider) -> &'static str {
143 match decider {
144 ApprovalDecider::User => "you",
145 ApprovalDecider::SessionRule => "session rule",
146 ApprovalDecider::Posture => "posture",
147 ApprovalDecider::Host => "Codewhale",
148 }
149 }
150
151 fn approval_phrase(fact: &ApprovalFact) -> String {
152 let by = fact
153 .decided_by
154 .map(|by| format!(" by {}", decider_label(by)))
155 .unwrap_or_default();
156 match fact.decision {
157 ApprovalDecisionLabel::Approved => format!("approved{by}"),
158 ApprovalDecisionLabel::ApprovedWithPolicy => format!("approved{by} with a wider sandbox"),
159 ApprovalDecisionLabel::Denied => format!("denied{by}"),
160 ApprovalDecisionLabel::TimedOut => "approval timed out".to_string(),
161 ApprovalDecisionLabel::Cancelled => "turn stopped while waiting".to_string(),
162 ApprovalDecisionLabel::Unavailable => "nobody could be asked".to_string(),
163 ApprovalDecisionLabel::Pending => "waiting for approval".to_string(),
164 }
165 }
166
167 fn counts(added: Option<u64>, removed: Option<u64>) -> String {
168 match (added, removed) {
169 (Some(added), Some(removed)) => format!(" (+{added} −{removed})"),
170 _ => String::new(),
171 }
172 }
173
174 fn file_phrase(file: &FileTouch) -> String {
175 let verb = match file.change {
176 FileChangeKind::Edited => "edited",
177 FileChangeKind::Created => "created",
178 FileChangeKind::Deleted => "deleted",
179 FileChangeKind::Written => "wrote",
180 };
181 let counts = if file.change == FileChangeKind::Deleted {
182 String::new()
183 } else {
184 counts(file.lines_added, file.lines_removed)
185 };
186 format!("{verb} {}{counts}", code_span(&file.path))
187 }
188
189 /// `text` on one line with nothing a terminal acts on: control characters
190 /// (newline, carriage return, escape), Unicode line separators, and bidi
191 /// overrides show as `\u{…}`-style escapes. Paths, commands, and error text
192 /// come from the workspace and from tools, so a file a command named
193 /// `x\n- Ran …` cannot forge a receipt line, and one holding `ESC ]` cannot
194 /// drive the terminal that prints the receipt.
195 fn one_line(text: &str) -> String {
196 let mut out = String::with_capacity(text.len());
197 for ch in text.chars() {
198 let hidden = ch.is_control()
199 || matches!(
200 ch,
201 '\u{2028}'
202 | '\u{2029}'
203 | '\u{200e}'
204 | '\u{200f}'
205 | '\u{202a}'..='\u{202e}'
206 | '\u{2066}'..='\u{2069}'
207 );
208 if hidden {
209 out.extend(ch.escape_default());
210 } else {
211 out.push(ch);
212 }
213 }
214 out
215 }
216
217 /// Inline code that survives backticks in the text: the fence is one
218 /// backtick longer than the longest run inside it.
219 pub fn code_span(text: &str) -> String {
220 let longest = text.split(|ch| ch != '`').map(str::len).max().unwrap_or(0);
221 let fence = "`".repeat(longest + 1);
222 let pad = if text.starts_with('`') || text.ends_with('`') {
223 " "
224 } else {
225 ""
226 };
227 format!("{fence}{pad}{text}{pad}{fence}")
228 }
229
230 /// What the action did (or would have done), past tense and verb first.
231 /// Every phrase starts with one of [`PHRASE_VERBS`], so a call that did not
232 /// run can say so in the same words.
233 fn action_phrase(action: &ReceiptAction) -> String {
234 match &action.what {
235 ActionKind::FileChange { files } => match files.as_slice() {
236 [file] => file_phrase(file),
237 files if action.status == ActionStatus::Ok => format!(
238 "changed {} files: {}",
239 files.len(),
240 files.iter().map(file_phrase).collect::<Vec<_>>().join(", ")
241 ),
242 files => format!(
243 "changed {} files: {}",
244 files.len(),
245 files
246 .iter()
247 .map(|file| code_span(&file.path))
248 .collect::<Vec<_>>()
249 .join(", ")
250 ),
251 },
252 ActionKind::WorkspaceChange { files, truncated } => {
253 let mut text = format!(
254 "changed outside file tools (a command or another process): {}",
255 files.iter().map(file_phrase).collect::<Vec<_>>().join(", ")
256 );
257 if *truncated {
258 text.push_str(", and more");
259 }
260 text
261 }
262 ActionKind::Command {
263 command,
264 cwd,
265 exit_code,
266 } => {
267 let mut text = format!("ran {}", code_span(command));
268 if let Some(cwd) = cwd {
269 text.push_str(&format!(" in {cwd}"));
270 }
271 if let Some(code) = exit_code {
272 text.push_str(&format!(" — exit {code}"));
273 }
274 text
275 }
276 ActionKind::Code { exit_code, nested } => {
277 let mut text = format!("ran code ({})", action.tool);
278 if let Some(code) = exit_code {
279 text.push_str(&format!(" — exit {code}"));
280 }
281 if !nested.is_empty() {
282 let calls = nested
283 .iter()
284 .map(|call| format!("{}{}", call.tool, if call.ok { "" } else { " ✗" }))
285 .collect::<Vec<_>>()
286 .join(", ");
287 text.push_str(&format!(" — called {calls}"));
288 }
289 text
290 }
291 ActionKind::Network {
292 action: kind,
293 host,
294 query,
295 } => match (kind.as_str(), host, query) {
296 ("search", _, Some(query)) => format!("searched the web for “{query}”"),
297 ("search", _, None) => "searched the web".to_string(),
298 ("fetch", Some(host), _) => format!("fetched {host}"),
299 ("git_fetch", Some(remote), _) => format!("fetched git remote {remote}"),
300 (other, Some(host), _) => format!("called {host}: {}", other.replace('_', " ")),
301 (other, None, _) => format!("made a web request ({other})"),
302 },
303 ActionKind::Mcp { server, .. } => {
304 let tool = server
305 .as_deref()
306 .and_then(|server| {
307 action
308 .tool
309 .strip_prefix("mcp_")
310 .and_then(|rest| rest.strip_prefix(server))
311 .map(|rest| rest.trim_start_matches('_'))
312 })
313 .filter(|tool| !tool.is_empty());
314 match (server, tool) {
315 (Some(server), Some(tool)) => format!("called {server} · {tool}"),
316 _ => format!("called {}", action.tool),
317 }
318 }
319 ActionKind::PluginChange {
320 method,
321 plugin,
322 hash,
323 approver,
324 services,
325 } => {
326 let target = if plugin == "not recorded" {
327 "not recorded".to_string()
328 } else {
329 code_span(plugin)
330 };
331 let mut text = format!("changed plugin {target} ({method}) — {approver}");
332 if let Some(hash) = hash.as_deref() {
333 text.push_str(&format!(" · hash {}", code_span(hash)));
334 }
335 if !services.is_empty() {
336 text.push_str(&format!(" · services: {}", services.join(", ")));
337 }
338 text
339 }
340 ActionKind::Subagent {
341 name,
342 agent_id,
343 outcome,
344 } => {
345 let who = name
346 .as_deref()
347 .or(agent_id.as_deref())
348 .unwrap_or("an agent");
349 match outcome {
350 Some(outcome) => format!("started agent {who} — {outcome}"),
351 None => format!("started agent {who}"),
352 }
353 }
354 ActionKind::Approval => format!("asked to use {}", action.tool),
355 ActionKind::Tool => format!("called {}", action.tool),
356 ActionKind::TurnFailed => "turn failed".to_string(),
357 }
358 }
359
360 /// The past-tense verbs [`action_phrase`] starts with, and their base form.
361 const PHRASE_VERBS: [(&str, &str); 11] = [
362 ("ran ", "run "),
363 ("edited ", "edit "),
364 ("created ", "create "),
365 ("deleted ", "delete "),
366 ("wrote ", "write "),
367 ("changed ", "change "),
368 ("searched ", "search "),
369 ("fetched ", "fetch "),
370 ("called ", "call "),
371 ("started ", "start "),
372 ("made ", "make "),
373 ];
374
375 /// `ran `x`` becomes `did not run `x`` (lead `did not`) or `tried to run
376 /// `x`` (lead `tried to`).
377 fn with_base_verb(lead: &str, phrase: &str) -> String {
378 PHRASE_VERBS
379 .iter()
380 .find_map(|(past, base)| {
381 phrase
382 .strip_prefix(past)
383 .map(|rest| format!("{lead} {base}{rest}"))
384 })
385 .unwrap_or_else(|| format!("{lead} run: {phrase}"))
386 }
387
388 fn duration_label(ms: u64) -> String {
389 if ms < 1_000 {
390 format!("{ms}ms")
391 } else if ms < 60_000 {
392 format!("{:.1}s", ms as f64 / 1_000.0)
393 } else {
394 format!("{}m{:02}s", ms / 60_000, (ms % 60_000) / 1_000)
395 }
396 }
397
398 /// One line per action. Plain text that also reads as Markdown; whatever
399 /// the record holds cannot break it onto a second line (`one_line`).
400 #[must_use]
401 pub fn action_line(action: &ReceiptAction) -> String {
402 let mut line = action_phrase(action);
403 match action.status {
404 // An approval line already reads as a request, not a run.
405 ActionStatus::NotRun if action.what == ActionKind::Approval => {}
406 ActionStatus::NotRun => line = with_base_verb("did not", &line),
407 ActionStatus::Blocked => {
408 line = with_base_verb("did not", &line);
409 line.push_str(" — blocked");
410 if let Some(error) = &action.error {
411 line.push_str(&format!(": {error}"));
412 }
413 }
414 ActionStatus::Failed => {
415 line.push_str(" — failed");
416 if let Some(error) = &action.error {
417 line.push_str(&format!(": {error}"));
418 }
419 }
420 ActionStatus::Interrupted => line.push_str(" — interrupted"),
421 ActionStatus::Running if action.what != ActionKind::Approval => {
422 line.push_str(" — still running")
423 }
424 ActionStatus::Unknown => {
425 line = with_base_verb("tried to", &line);
426 match &action.error {
427 Some(error) => line.push_str(&format!(" — error, no exit code: {error}")),
428 None => line.push_str(" — no result recorded"),
429 }
430 }
431 _ => {}
432 }
433 if let Some(ms) = action.duration_ms
434 && !matches!(action.status, ActionStatus::NotRun | ActionStatus::Blocked)
435 {
436 line.push_str(&format!(" · {}", duration_label(ms)));
437 }
438 if let Some(fact) = &action.approval {
439 line.push_str(&format!(" · {}", approval_phrase(fact)));
440 }
441 one_line(&line)
442 }
443
444 fn tokens_line(tokens: &ReceiptTokens) -> String {
445 let mut line = match (tokens.input, tokens.output) {
446 (Some(input), Some(output)) => {
447 format!("Tokens: {input} in · {output} out · {} total", tokens.total)
448 }
449 _ => format!("Tokens: {} total", tokens.total),
450 };
451 if let Some(calls) = tokens.calls {
452 line.push_str(&format!(
453 " · {}",
454 plural(calls, "provider call", "provider calls")
455 ));
456 }
457 let detail: Vec<String> = [
458 ("cache read", tokens.cache_read),
459 ("cache write", tokens.cache_write),
460 ("reasoning", tokens.reasoning),
461 ]
462 .into_iter()
463 .filter_map(|(label, value)| value.map(|value| format!("{value} {label}")))
464 .collect();
465 if !detail.is_empty() {
466 line.push_str(&format!(" ({})", detail.join(", ")));
467 }
468 line
469 }
470
471 fn usage_block(usage: &ReceiptUsage) -> String {
472 let mut out = String::new();
473 if let Some(tokens) = &usage.tokens {
474 out.push_str(&one_line(&tokens_line(tokens)));
475 out.push('\n');
476 }
477 if let Some(cost) = &usage.cost {
478 out.push_str("Cost, as /cost reports it:\n");
479 for line in cost
480 .report
481 .lines()
482 .map(str::trim)
483 .filter(|line| !line.is_empty())
484 {
485 out.push_str(&format!(" {}\n", one_line(line)));
486 }
487 }
488 out
489 }
490
491 /// The readable receipt: header, totals, one line per action, then what the
492 /// record does not hold. Valid Markdown and plain enough for a terminal.
493 #[must_use]
494 pub fn render_markdown(receipt: &Receipt) -> String {
495 let source = &receipt.source;
496 let noun = match source.kind {
497 SourceKind::Session => "session",
498 SourceKind::Thread => "thread",
499 };
500 let mut out = String::new();
501 let title = source
502 .title
503 .as_deref()
504 .map(|title| bounded(title.trim(), 80))
505 .filter(|title| !title.is_empty());
506 match title {
507 Some(title) => out.push_str(&format!("# Receipt: {}\n\n", one_line(&title))),
508 None => out.push_str(&format!("# Receipt: {noun} {}\n\n", one_line(&source.id))),
509 }
510 let mut facts = vec![format!("{noun} {}", source.id)];
511 if let Some(turn) = &receipt.turn {
512 facts.push(format!("turn {turn} only"));
513 }
514 if let Some(workspace) = &source.workspace {
515 facts.push(workspace.clone());
516 }
517 if let Some(model) = &source.model {
518 facts.push(model.clone());
519 }
520 if !receipt.postures.is_empty() {
521 facts.push(receipt.postures.join(", "));
522 }
523 if let (Some(start), Some(end)) = (source.started_at, source.updated_at) {
524 facts.push(format!(
525 "{} → {}",
526 start.format("%Y-%m-%d %H:%M UTC"),
527 end.format("%Y-%m-%d %H:%M UTC")
528 ));
529 }
530 out.push_str(&one_line(&facts.join(" · ")));
531 out.push_str("\n\n");
532 out.push_str(&one_line(&totals_line(receipt)));
533 out.push_str("\n\n");
534 if let Some(usage) = &receipt.usage {
535 out.push_str(&usage_block(usage));
536 out.push('\n');
537 }
538 let width = receipt.actions.len().to_string().len();
539 for action in &receipt.actions {
540 out.push_str(&format!(
541 "{:>width$}. {}\n",
542 action.seq,
543 action_line(action),
544 width = width
545 ));
546 }
547 if receipt.omitted_actions > 0 {
548 out.push_str(&format!(
549 "\n{} more actions are counted above but not listed.\n",
550 receipt.omitted_actions
551 ));
552 }
553 if !receipt.not_recorded.is_empty() {
554 out.push_str("\nNot recorded:\n");
555 for note in &receipt.not_recorded {
556 out.push_str(&format!("- {}\n", one_line(note)));
557 }
558 }
559 out
560 }
561
562 #[must_use]
563 pub fn render_json(receipt: &Receipt) -> String {
564 serde_json::to_string_pretty(receipt).unwrap_or_else(|_| "{}".to_string())
565 }
566
567 /// [`render_json`] inside a fenced code block, for a surface that renders
568 /// Markdown (the terminal's note cell): the fence keeps `$`, `*`, and `_` in
569 /// commands from being read as math or emphasis, and it is longer than any
570 /// backtick run a command holds, so the JSON copies out whole.
571 #[must_use]
572 pub fn render_json_block(receipt: &Receipt) -> String {
573 let json = render_json(receipt);
574 let longest = json.split(|ch| ch != '`').map(str::len).max().unwrap_or(0);
575 let fence = "`".repeat(longest.max(2) + 1);
576 format!("{fence}json\n{json}\n{fence}")
577 }
578
578 lines RUST