1use agent_client_protocol::schema::v1::{
4 SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdateFields, ToolKind,
5};
6use mj_core::acp::RuntimeEvent;
7pub use mj_core::transcript::*;
8use serde::Deserialize;
9use serde_json::Value;
10use tree_sitter::{Node, Parser};
11const TOOL_SUMMARY_SOURCE_BYTES: usize = 64 * 1024;
12const TOOL_SUMMARY_MAX_NESTING: usize = 16;
13pub const TOOL_SUMMARY_VERSION: u8 = 6;
15
16pub fn compact_tool_call_for_retention(body: &mut TranscriptBody) -> bool {
27 let TranscriptBody::Tool {
28 call,
29 terminal_outputs,
30 terminal_refs,
31 ..
32 } = body
33 else {
34 return false;
35 };
36 let Some(object) = call.as_object_mut() else {
37 return false;
38 };
39 let mut changed = !terminal_outputs.is_empty() || !terminal_refs.is_empty();
40 terminal_outputs.clear();
41 terminal_refs.clear();
42 for field in ["rawInput", "rawOutput", "_meta"] {
43 changed |= object.remove(field).is_some();
44 }
45 let Some(content) = object
46 .get_mut("content")
47 .and_then(|value| value.as_array_mut())
48 else {
49 return changed;
50 };
51 let before = content.len();
52 content.retain(|item| item.get("type").and_then(|kind| kind.as_str()) == Some("diff"));
57 changed |= content.len() != before;
58 for item in content.iter_mut() {
59 changed |= drop_diff_body(item);
60 }
61 changed
62}
63
64fn drop_diff_body(item: &mut serde_json::Value) -> bool {
65 use agent_client_protocol::schema::v1::ToolCallContent;
66
67 let mut content = match serde_json::from_value::<ToolCallContent>(item.clone()) {
71 Ok(content) => content,
72 Err(error) => {
74 tracing::warn!(%error, "skipping unreadable tool content during retention");
75 return false;
76 }
77 };
78 let ToolCallContent::Diff(diff) = &mut content else {
79 return false;
80 };
81 if !mj_core::diff::drop_patch_text(diff) {
82 return false;
83 }
84 match serde_json::to_value(&content) {
85 Ok(value) => {
86 *item = value;
87 true
88 }
89 Err(error) => {
90 tracing::warn!(%error, "could not rewrite a diff during retention");
91 false
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
97enum ToolSummarySource {
98 Shell(String),
99 Argv {
100 executable: String,
101 arguments: Vec<String>,
102 },
103}
104
105pub fn tool_call_update_changes_presentation(
107 call: &ToolCall,
108 fields: &ToolCallUpdateFields,
109) -> bool {
110 fields
111 .title
112 .as_ref()
113 .is_some_and(|title| title != &call.title)
114 || fields.kind.is_some_and(|kind| kind != call.kind)
115 || fields
116 .raw_input
117 .as_ref()
118 .is_some_and(|input| Some(input) != call.raw_input.as_ref())
119 || (call.kind == ToolKind::Execute
120 && fields
121 .raw_output
122 .as_ref()
123 .is_some_and(|output| Some(output) != call.raw_output.as_ref())
124 && command_source(call.raw_input.as_ref()).is_none())
125}
126
127pub fn tool_call_presentation(call: &ToolCall) -> ToolCallPresentation {
129 let kind = call.kind;
130 if kind == ToolKind::Execute {
131 if let Some(source) = command_source(call.raw_input.as_ref()) {
132 return presentation_from_source(
133 source,
134 ToolSummarySourceKind::RawInput,
135 kind,
136 &call.title,
137 );
138 }
139 if let Some(source) = command_source(call.raw_output.as_ref()) {
140 return presentation_from_source(
141 source,
142 ToolSummarySourceKind::RawOutput,
143 kind,
144 &call.title,
145 );
146 }
147 }
148 presentation_from_title(&call.title, kind)
149}
150
151pub fn materialized_tool_call_presentation(
155 stored: Option<&ToolCallPresentation>,
156 call: &ToolCall,
157) -> ToolCallPresentation {
158 stored
159 .filter(|presentation| presentation.summary_version >= TOOL_SUMMARY_VERSION)
160 .cloned()
161 .unwrap_or_else(|| tool_call_presentation(call))
162}
163
164pub fn update_tool_call_presentation(
168 previous: Option<&ToolCallPresentation>,
169 title: &str,
170 kind: Option<ToolKind>,
171 raw_input: Option<&Value>,
172 raw_output: Option<&Value>,
173) -> ToolCallPresentation {
174 let next_kind = kind.unwrap_or_else(|| {
175 previous
176 .map(|presentation| presentation.tool_kind)
177 .unwrap_or_default()
178 });
179
180 if next_kind == ToolKind::Execute {
181 if let Some(source) = raw_input.and_then(|value| command_source(Some(value))) {
182 return presentation_from_source(
183 source,
184 ToolSummarySourceKind::RawInput,
185 next_kind,
186 title,
187 );
188 }
189 if let Some(source) = raw_output.and_then(|value| command_source(Some(value)))
190 && (raw_input.is_some()
191 || !previous.is_some_and(|previous| {
192 previous.source_kind == ToolSummarySourceKind::RawInput
193 }))
194 {
195 return presentation_from_source(
196 source,
197 ToolSummarySourceKind::RawOutput,
198 next_kind,
199 title,
200 );
201 }
202 if let Some(previous) = previous
203 && previous.tool_kind == ToolKind::Execute
204 && ((raw_input.is_none() && previous.source_kind == ToolSummarySourceKind::RawInput)
205 || (raw_input.is_none()
206 && raw_output.is_none()
207 && previous.source_kind == ToolSummarySourceKind::RawOutput))
208 {
209 return ToolCallPresentation {
210 tool_kind: next_kind,
211 ..previous.clone()
212 };
213 }
214 }
215
216 presentation_from_title(title, next_kind)
217}
218
219fn command_source(raw: Option<&Value>) -> Option<ToolSummarySource> {
220 let command = raw?.get("command")?;
221 match command {
222 Value::String(command) if !command.trim().is_empty() => {
223 Some(ToolSummarySource::Shell(command.clone()))
224 }
225 Value::Array(argv) => {
226 let argv = argv.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
227 let first = argv.first()?.trim();
228 if first.is_empty() {
229 return None;
230 }
231 if is_shell_interpreter(first)
232 && let Some(script) = shell_script_argument(&argv[1..])
233 {
234 return Some(ToolSummarySource::Shell(script.to_owned()));
235 }
236 Some(ToolSummarySource::Argv {
237 executable: first.to_owned(),
238 arguments: argv[1..]
239 .iter()
240 .map(|argument| (*argument).to_owned())
241 .collect(),
242 })
243 }
244 _ => None,
245 }
246}
247
248fn is_shell_interpreter(value: &str) -> bool {
249 let executable = value.rsplit('/').next().unwrap_or(value);
250 matches!(executable, "sh" | "bash" | "dash" | "zsh")
251}
252
253fn shell_script_argument<'a>(arguments: &'a [&'a str]) -> Option<&'a str> {
254 let mut index = 0;
255 while index < arguments.len() {
256 let argument = arguments[index];
257 if argument == "--" {
258 return None;
259 }
260 if argument == "-c" || argument == "--command" {
261 return arguments.get(index + 1).copied();
262 }
263 if argument.starts_with('-') && !argument.starts_with("--") && argument[1..].contains('c') {
264 return arguments.get(index + 1).copied();
265 }
266 index += 1;
267 }
268 None
269}
270
271fn presentation_from_source(
272 source: ToolSummarySource,
273 source_kind: ToolSummarySourceKind,
274 tool_kind: ToolKind,
275 title: &str,
276) -> ToolCallPresentation {
277 let (source, summary) = match source {
278 ToolSummarySource::Shell(source) => {
279 let bounded = bound_summary_source(&source);
280 let summary = summarize_shell(&bounded, 0)
281 .or_else(|| first_meaningful_token(title))
282 .unwrap_or_else(|| "tool".to_owned());
283 (bounded, summary)
284 }
285 ToolSummarySource::Argv {
286 executable,
287 arguments,
288 } => {
289 let source = std::iter::once(executable.as_str())
290 .chain(arguments.iter().map(String::as_str))
291 .collect::<Vec<_>>()
292 .join(" ");
293 let bounded = bound_summary_source(&source);
294 let summary = summarize_invocation(&executable, &arguments)
295 .or_else(|| first_meaningful_token(title))
296 .unwrap_or_else(|| "tool".to_owned());
297 (bounded, summary)
298 }
299 };
300 ToolCallPresentation {
301 summary,
302 source,
303 source_kind,
304 tool_kind,
305 summary_version: TOOL_SUMMARY_VERSION,
306 }
307}
308
309fn presentation_from_title(title: &str, tool_kind: ToolKind) -> ToolCallPresentation {
310 let source = title_source(title);
311 let bounded = bound_summary_source(&source);
312 let summary = if tool_kind == ToolKind::Execute {
313 summarize_shell(&bounded, 0)
314 .or_else(|| first_meaningful_token(&bounded))
315 .unwrap_or_else(|| "tool".to_owned())
316 } else if bounded.trim_end().ends_with('?') {
317 bounded.trim().to_owned()
320 } else {
321 first_meaningful_token(&bounded).unwrap_or_else(|| "tool".to_owned())
322 };
323 ToolCallPresentation {
324 summary,
325 source: bounded,
326 source_kind: ToolSummarySourceKind::Title,
327 tool_kind,
328 summary_version: TOOL_SUMMARY_VERSION,
329 }
330}
331
332fn title_source(title: &str) -> String {
333 let title = title.trim();
334 let title = title
335 .strip_prefix("Running:")
336 .or_else(|| title.strip_prefix("Starting background:"))
337 .map(str::trim)
338 .unwrap_or(title);
339 if let Some(inner) = title
340 .strip_prefix("Execute `")
341 .and_then(|value| value.strip_suffix('`'))
342 {
343 return inner.to_owned();
344 }
345 title.to_owned()
346}
347
348fn first_meaningful_token(value: &str) -> Option<String> {
349 let token = value
350 .split_whitespace()
351 .next()?
352 .trim_matches(|character: char| {
353 !character.is_alphanumeric() && character != '/' && character != '.' && character != '_'
354 });
355 if token.is_empty() {
356 None
357 } else {
358 Some(token.trim_matches(['\'', '"', '`']).to_owned())
359 }
360}
361
362fn bound_summary_source(source: &str) -> String {
363 if source.len() <= TOOL_SUMMARY_SOURCE_BYTES {
364 return source.to_owned();
365 }
366 let mut end = TOOL_SUMMARY_SOURCE_BYTES;
367 while !source.is_char_boundary(end) {
368 end -= 1;
369 }
370 source[..end].to_owned()
371}
372
373fn summarize_shell(source: &str, nesting: usize) -> Option<String> {
374 if nesting >= TOOL_SUMMARY_MAX_NESTING {
377 return Some("…".to_owned());
378 }
379 let mut parser = Parser::new();
380 parser
381 .set_language(&tree_sitter_bash::LANGUAGE.into())
382 .ok()?;
383 let tree = parser.parse(source, None)?;
384 let root = tree.root_node();
385 if root.has_error() {
386 return None;
387 }
388
389 let mut commands = Vec::new();
390 let mut operators = Vec::new();
391 let mut subshells = Vec::new();
392 if !collect_shell_tokens(
393 root,
394 source,
395 nesting,
396 &mut commands,
397 &mut operators,
398 &mut subshells,
399 ) {
400 return None;
401 }
402 if commands.is_empty() {
403 return None;
404 }
405 commands.sort_by_key(|command| command.start);
406 operators.sort_by_key(|operator| operator.start);
407 subshells.sort_by_key(|subshell| subshell.start);
408
409 let mut tokens = Vec::new();
410 for (index, command) in commands.iter().enumerate() {
411 if index > 0 {
412 let previous = &commands[index - 1];
413 let separator = shell_separator_between(previous, command, &operators);
414 tokens.push(ShellToken {
415 start: separator.start,
416 text: separator.kind,
417 order: 1,
418 });
419 }
420 tokens.push(ShellToken {
421 start: command.start,
422 text: command.summary.clone(),
423 order: 2,
424 });
425 }
426
427 for subshell in subshells {
431 if !commands
432 .iter()
433 .any(|command| command.start >= subshell.start && command.end <= subshell.end)
434 {
435 continue;
436 }
437 let close = subshell.end.saturating_sub(1);
438 tokens.push(ShellToken {
439 start: subshell.start,
440 text: "(".to_owned(),
441 order: 0,
442 });
443 tokens.push(ShellToken {
444 start: close,
445 text: ")".to_owned(),
446 order: 3,
447 });
448 }
449
450 tokens.sort_by_key(|token| (token.start, token.order));
451 Some(join_shell_tokens(
452 tokens.into_iter().map(|token| token.text).collect(),
453 ))
454}
455
456#[derive(Debug, Clone)]
457struct ShellCommandToken {
458 start: usize,
459 end: usize,
460 summary: String,
461}
462
463#[derive(Debug, Clone)]
464struct ShellOperatorToken {
465 start: usize,
466 kind: String,
467}
468
469#[derive(Debug, Clone)]
470struct ShellSubshell {
471 start: usize,
472 end: usize,
473}
474
475#[derive(Debug, Clone)]
476struct ShellToken {
477 start: usize,
478 text: String,
479 order: u8,
480}
481
482fn collect_shell_tokens(
483 node: Node<'_>,
484 source: &str,
485 nesting: usize,
486 commands: &mut Vec<ShellCommandToken>,
487 operators: &mut Vec<ShellOperatorToken>,
488 subshells: &mut Vec<ShellSubshell>,
489) -> bool {
490 let kind = node.kind();
491 if matches!(kind, "command_substitution" | "process_substitution") {
492 return true;
493 }
494 if kind == "command" {
495 if let Some(summary) = summarize_command_node(node, source, nesting) {
496 commands.push(ShellCommandToken {
497 start: node.start_byte(),
498 end: node.end_byte(),
499 summary,
500 });
501 return true;
502 }
503 return false;
504 }
505 if is_shell_operator(node) {
506 operators.push(ShellOperatorToken {
507 start: node.start_byte(),
508 kind: kind.to_owned(),
509 });
510 return true;
511 }
512
513 if kind == "subshell" {
514 subshells.push(ShellSubshell {
515 start: node.start_byte(),
516 end: node.end_byte(),
517 });
518 }
519
520 let mut cursor = node.walk();
521 node.children(&mut cursor)
522 .all(|child| collect_shell_tokens(child, source, nesting, commands, operators, subshells))
523}
524
525fn shell_separator_between(
526 previous: &ShellCommandToken,
527 next: &ShellCommandToken,
528 operators: &[ShellOperatorToken],
529) -> ShellOperatorToken {
530 let mut candidates = operators
531 .iter()
532 .filter(|operator| operator.start >= previous.end && operator.start < next.start);
533 let structural = candidates.clone().find(|operator| operator.kind != ";");
534 if let Some(operator) = structural {
535 return operator.clone();
536 }
537 if let Some(operator) = candidates.find(|operator| operator.kind == ";") {
538 return operator.clone();
539 }
540 ShellOperatorToken {
541 start: previous.end,
542 kind: ";".to_owned(),
543 }
544}
545
546#[derive(Debug, Clone)]
550struct InvocationArgument {
551 value: String,
552 literal: bool,
553}
554
555fn summarize_command_node(node: Node<'_>, source: &str, nesting: usize) -> Option<String> {
556 let name = node.child_by_field_name("name")?;
557 let executable = shell_command_name(name, source)?;
558 let mut cursor = node.walk();
559 let arguments = node
560 .children_by_field_name("argument", &mut cursor)
561 .map(|argument| match shell_argument_value(argument, source) {
562 Some(value) => InvocationArgument {
563 value,
564 literal: true,
565 },
566 None => InvocationArgument {
567 value: strip_matching_quotes(source[argument.byte_range()].trim()).to_owned(),
568 literal: false,
569 },
570 })
571 .collect::<Vec<_>>();
572 summarize_invocation_with_literals(&executable, &arguments, nesting)
573}
574
575fn shell_command_name(node: Node<'_>, source: &str) -> Option<String> {
576 if contains_dynamic_shell_node(node) {
577 return None;
578 }
579 normalize_command_name(&source[node.byte_range()])
580}
581
582fn shell_argument_value(node: Node<'_>, source: &str) -> Option<String> {
583 if contains_dynamic_shell_node(node) {
584 return None;
585 }
586 let text = source[node.byte_range()].trim();
587 if text.is_empty() {
588 return None;
589 }
590 Some(strip_matching_quotes(text).to_owned())
591}
592
593fn contains_dynamic_shell_node(node: Node<'_>) -> bool {
594 if matches!(
595 node.kind(),
596 "expansion"
597 | "simple_expansion"
598 | "command_substitution"
599 | "process_substitution"
600 | "arithmetic_expansion"
601 ) {
602 return true;
603 }
604 let mut cursor = node.walk();
605 node.children(&mut cursor).any(contains_dynamic_shell_node)
606}
607
608fn summarize_invocation(executable: &str, arguments: &[String]) -> Option<String> {
609 summarize_invocation_with_literals(
610 executable,
611 &arguments
612 .iter()
613 .map(|value| InvocationArgument {
614 value: strip_matching_quotes(value).to_owned(),
615 literal: true,
616 })
617 .collect::<Vec<_>>(),
618 0,
619 )
620}
621
622fn summarize_invocation_with_literals(
623 executable: &str,
624 arguments: &[InvocationArgument],
625 nesting: usize,
626) -> Option<String> {
627 let mut executable = normalize_command_name(executable)?;
628 let mut arguments = arguments;
629 let mut words = Vec::new();
630 'invocations: loop {
633 let basename = executable
634 .rsplit(['/', '\\'])
635 .next()
636 .unwrap_or(&executable)
637 .to_owned();
638 if is_shell_interpreter(&basename) {
639 words.push(summarize_shell_invocation(&basename, arguments, nesting));
640 break;
641 }
642 words.push(executable);
643 if !is_summary_executable(&basename) {
644 break;
645 }
646 let mut index = 0;
647
648 if matches!(basename.as_str(), "cargo" | "mbx")
649 && arguments.first().is_some_and(|argument| {
650 argument.literal && argument.value.starts_with('+') && argument.value.len() > 1
651 })
652 {
653 index += 1;
654 }
655
656 let mut first_verb = loop {
657 let Some(argument) = arguments.get(index) else {
658 break 'invocations;
659 };
660 if !argument.literal {
661 break 'invocations;
662 }
663 if argument.value == "--" || argument.value.starts_with('-') {
664 if let Some(consumed) = known_leading_option_arguments(&basename, arguments, index)
665 {
666 index += consumed;
667 continue;
668 }
669 break 'invocations;
670 }
671 break argument.value.as_str();
672 };
673
674 if basename == "ssh" {
675 words.push(first_verb.to_owned());
676 index += 1;
677 while let Some(argument) = arguments.get(index) {
680 if !argument.literal || !argument.value.starts_with('-') {
681 break;
682 }
683 let Some(consumed) = known_leading_option_arguments("ssh", arguments, index) else {
684 break 'invocations;
685 };
686 index += consumed;
687 if argument.value == "--" {
688 break;
689 }
690 }
691 let script = arguments[index..]
692 .iter()
693 .map(|argument| argument.value.as_str())
694 .collect::<Vec<_>>()
695 .join(" ");
696 if !script.is_empty()
697 && let Some(inner) = summarize_shell(&script, nesting + 1)
698 {
699 words.push(inner);
700 }
701 break;
702 }
703
704 if basename == "timeout" {
705 let duration = first_verb
706 .strip_suffix(['s', 'm', 'h', 'd'])
707 .unwrap_or(first_verb);
708 if duration.parse::<f64>().is_ok() {
709 index += 1;
710 let Some(argument) = arguments.get(index).filter(|argument| argument.literal)
711 else {
712 break;
713 };
714 first_verb = &argument.value;
715 }
716 }
717
718 if matches!(basename.as_str(), "nice" | "timeout") {
719 let Some(inner) = normalize_command_name(first_verb) else {
720 break;
721 };
722 executable = inner;
723 arguments = &arguments[index + 1..];
724 continue;
725 }
726 words.push(first_verb.to_owned());
727
728 if allows_second_verb(&basename, first_verb)
729 && let Some(argument) = arguments.get(index + 1)
730 && argument.literal
731 && !argument.value.starts_with('-')
732 && argument.value != "--"
733 {
734 if basename == "uv" && first_verb == "run" {
736 let name = argument.value.rsplit('/').next().unwrap_or(&argument.value);
737 let Some(inner) = normalize_command_name(name) else {
738 break;
739 };
740 executable = inner;
741 arguments = &arguments[index + 2..];
742 continue;
743 }
744 words.push(argument.value.clone());
745 }
746 break;
747 }
748 Some(words.join(" "))
749}
750
751fn summarize_shell_invocation(
756 shell: &str,
757 arguments: &[InvocationArgument],
758 nesting: usize,
759) -> String {
760 let values = arguments
761 .iter()
762 .map(|argument| argument.value.as_str())
763 .collect::<Vec<_>>();
764 let Some(script) = shell_script_argument(&values) else {
765 return shell.to_owned();
766 };
767 match summarize_shell(script, nesting + 1) {
768 Some(inner) => format!("{shell} -c {inner}"),
769 None => format!("{shell} -c"),
770 }
771}
772
773fn is_summary_executable(basename: &str) -> bool {
774 matches!(
775 basename,
776 "git"
777 | "gh"
778 | "cargo"
779 | "rustup"
780 | "npm"
781 | "pnpm"
782 | "yarn"
783 | "bun"
784 | "uv"
785 | "pip"
786 | "pip3"
787 | "docker"
788 | "podman"
789 | "nice"
790 | "timeout"
791 | "ssh"
792 | "mbx"
793 | "mj"
794 | "tmux"
795 )
796}
797
798fn allows_second_verb(basename: &str, first_verb: &str) -> bool {
799 match basename {
800 "git" => matches!(
803 first_verb,
804 "bisect"
805 | "bundle"
806 | "hook"
807 | "lfs"
808 | "maintenance"
809 | "notes"
810 | "remote"
811 | "sparse-checkout"
812 | "stash"
813 | "submodule"
814 | "worktree"
815 ),
816 "gh" => matches!(
817 first_verb,
818 "alias"
819 | "auth"
820 | "cache"
821 | "codespace"
822 | "config"
823 | "extension"
824 | "gist"
825 | "gpg-key"
826 | "issue"
827 | "label"
828 | "org"
829 | "pr"
830 | "project"
831 | "release"
832 | "repo"
833 | "ruleset"
834 | "run"
835 | "search"
836 | "secret"
837 | "ssh-key"
838 | "variable"
839 | "workflow"
840 ),
841 "docker" => matches!(
842 first_verb,
843 "buildx"
844 | "compose"
845 | "config"
846 | "context"
847 | "container"
848 | "image"
849 | "manifest"
850 | "network"
851 | "node"
852 | "plugin"
853 | "secret"
854 | "service"
855 | "stack"
856 | "swarm"
857 | "system"
858 | "trust"
859 | "volume"
860 ),
861 "podman" => matches!(
862 first_verb,
863 "artifact"
864 | "container"
865 | "farm"
866 | "generate"
867 | "image"
868 | "machine"
869 | "manifest"
870 | "network"
871 | "play"
872 | "pod"
873 | "secret"
874 | "system"
875 | "volume"
876 ),
877 "uv" => matches!(first_verb, "cache" | "pip" | "python" | "run" | "tool"),
878 "npm" => matches!(first_verb, "run" | "run-script"),
879 "pnpm" | "yarn" | "bun" => first_verb == "run",
880 "mbx" => matches!(first_verb, "cache" | "explain" | "settings"),
881 "mj" => matches!(
882 first_verb,
883 "daemon" | "import" | "recover" | "review" | "setup" | "workspaces"
884 ),
885 "rustup" => matches!(
886 first_verb,
887 "component" | "override" | "target" | "toolchain"
888 ),
889 _ => false,
890 }
891}
892
893fn known_leading_option_arguments(
894 basename: &str,
895 arguments: &[InvocationArgument],
896 index: usize,
897) -> Option<usize> {
898 let option = arguments.get(index)?.value.as_str();
899 if option == "--" {
900 if matches!(basename, "nice" | "timeout" | "ssh") {
901 return Some(1);
902 }
903 return None;
904 }
905 if basename == "ssh" {
906 let flags = option.strip_prefix('-')?;
909 for (offset, flag) in flags.char_indices() {
910 if "BbcDEeFIiJLlmOoPpQRSWw".contains(flag) {
911 return if offset + flag.len_utf8() < flags.len() {
912 Some(1)
913 } else {
914 arguments
915 .get(index + 1)
916 .filter(|argument| argument.literal)
917 .map(|_| 2)
918 };
919 }
920 if !"46AaCfGgKkMNnqsTtVvXxYy".contains(flag) {
921 return None;
922 }
923 }
924 return (!flags.is_empty()).then_some(1);
925 }
926 let (option_name, attached_value) = option
927 .split_once('=')
928 .map_or((option, false), |(name, _)| (name, true));
929 if basename == "nice"
930 && option.starts_with('-')
931 && option.len() > 1
932 && option[1..].parse::<i32>().is_ok()
933 {
934 return Some(1);
935 }
936 if basename == "nice"
937 && option
938 .strip_prefix("-n")
939 .is_some_and(|value| !value.is_empty() && value.parse::<i32>().is_ok())
940 {
941 return Some(1);
942 }
943 let attached_short_value = match basename {
944 "git" => option.starts_with("-C") || option.starts_with("-c"),
945 "gh" => option.starts_with("-R"),
946 "docker" | "podman" => option.starts_with("-H"),
947 "mj" => option.starts_with("-i"),
948 "timeout" => option.starts_with("-s") || option.starts_with("-k"),
949 "tmux" => ["-L", "-S", "-f", "-c", "-T"]
950 .iter()
951 .any(|prefix| option.starts_with(prefix)),
952 _ => false,
953 } && option.len() > 2;
954 let takes_value = match basename {
955 "git" => matches!(
956 option_name,
957 "-C" | "-c"
958 | "--config-env"
959 | "--exec-path"
960 | "--git-dir"
961 | "--namespace"
962 | "--super-prefix"
963 | "--work-tree"
964 ),
965 "gh" => matches!(
966 option_name,
967 "-R" | "--hostname" | "--repo" | "--jq" | "--template"
968 ),
969 "cargo" => matches!(
970 option_name,
971 "--manifest-path" | "--target-dir" | "--config" | "--color"
972 ),
973 "npm" | "pnpm" | "yarn" | "bun" => {
974 matches!(
975 option_name,
976 "--cwd" | "--dir" | "--prefix" | "--registry" | "--userconfig"
977 )
978 }
979 "uv" => matches!(option_name, "--directory" | "--project" | "--python"),
980 "rustup" => matches!(option_name, "--toolchain"),
981 "mj" => matches!(option_name, "-i" | "--instance" | "--workspace"),
982 "tmux" => matches!(option_name, "-L" | "-S" | "-f" | "-c" | "-T"),
983 "nice" => {
984 matches!(option_name, "-n" | "--adjustment")
985 }
986 "timeout" => matches!(option_name, "-s" | "--signal" | "-k" | "--kill-after"),
987 "docker" | "podman" => matches!(
988 option_name,
989 "-H" | "--config" | "--connection" | "--context" | "--host" | "--log-level"
990 ),
991 _ => false,
992 };
993 if attached_short_value {
994 return Some(1);
995 }
996 if attached_value {
997 return takes_value.then_some(1);
998 }
999 if takes_value {
1000 return arguments
1001 .get(index + 1)
1002 .filter(|argument| argument.literal)
1003 .map(|_| 2);
1004 }
1005 let known_flag = match basename {
1006 "git" => matches!(
1007 option_name,
1008 "-p" | "--paginate"
1009 | "-P"
1010 | "--no-pager"
1011 | "--bare"
1012 | "--literal-pathspecs"
1013 | "--glob-pathspecs"
1014 | "--noglob-pathspecs"
1015 | "--icase-pathspecs"
1016 | "--no-optional-locks"
1017 | "--no-advice"
1018 ),
1019 "gh" => false,
1020 "cargo" => matches!(
1021 option_name,
1022 "-q" | "--quiet" | "-v" | "--verbose" | "--locked" | "--offline" | "--frozen"
1023 ),
1024 "npm" | "pnpm" | "yarn" | "bun" => {
1025 matches!(option_name, "-g" | "--global" | "--silent")
1026 }
1027 "uv" => matches!(
1028 option_name,
1029 "-q" | "--quiet" | "-v" | "--verbose" | "--offline"
1030 ),
1031 "rustup" => matches!(option_name, "-q" | "--quiet" | "-v" | "--verbose"),
1032 "docker" | "podman" => matches!(option_name, "-D" | "--debug" | "--tls"),
1033 "tmux" => matches!(
1034 option_name,
1035 "-2" | "-C" | "-CC" | "-D" | "-l" | "-N" | "-u" | "-v"
1036 ),
1037 "nice" => false,
1038 "timeout" => matches!(
1039 option_name,
1040 "-f" | "--foreground" | "-p" | "--preserve-status" | "-v" | "--verbose"
1041 ),
1042 _ => false,
1043 };
1044 known_flag.then_some(1)
1045}
1046
1047fn strip_matching_quotes(value: &str) -> &str {
1048 value
1049 .strip_prefix('"')
1050 .and_then(|value| value.strip_suffix('"'))
1051 .or_else(|| {
1052 value
1053 .strip_prefix('\'')
1054 .and_then(|value| value.strip_suffix('\''))
1055 })
1056 .unwrap_or(value)
1057}
1058
1059fn is_shell_operator(node: Node<'_>) -> bool {
1060 match node.kind() {
1061 ";" => true,
1062 "&&" | "||" => node.parent().is_some_and(|parent| parent.kind() == "list"),
1063 "|" | "|&" => node
1064 .parent()
1065 .is_some_and(|parent| parent.kind() == "pipeline"),
1066 "&" => node.parent().is_none_or(|parent| {
1067 !matches!(
1068 parent.kind(),
1069 "binary_expression" | "unary_expression" | "postfix_expression"
1070 )
1071 }),
1072 _ => false,
1073 }
1074}
1075
1076fn normalize_command_name(text: &str) -> Option<String> {
1077 let text = text.trim();
1078 if text.contains('$') || text.contains('`') {
1079 return None;
1080 }
1081 let text = text
1082 .strip_prefix('"')
1083 .and_then(|value| value.strip_suffix('"'))
1084 .or_else(|| {
1085 text.strip_prefix('\'')
1086 .and_then(|value| value.strip_suffix('\''))
1087 })
1088 .unwrap_or(text);
1089 (!text.is_empty()).then(|| text.to_owned())
1090}
1091
1092fn join_shell_tokens(tokens: Vec<String>) -> String {
1093 let mut output = String::new();
1094 for token in tokens {
1095 match token.as_str() {
1096 "(" => {
1097 if !output.is_empty() && !output.ends_with(' ') {
1098 output.push(' ');
1099 }
1100 output.push('(');
1101 }
1102 ")" => {
1103 output = output.trim_end().to_owned();
1104 output.push(')');
1105 }
1106 _ => {
1107 if !output.is_empty() && !output.ends_with(' ') && !output.ends_with('(') {
1108 output.push(' ');
1109 }
1110 output.push_str(&token);
1111 }
1112 }
1113 }
1114 output
1115}
1116
1117pub fn tool_input_text(input: &Value) -> String {
1120 fn value_text(value: &Value) -> String {
1121 match value {
1122 Value::String(text) => text.clone(),
1123 _ => serde_json::to_string_pretty(value)
1124 .expect("tool arguments are serializable JSON values"),
1125 }
1126 }
1127
1128 let text = match input {
1129 Value::Object(fields) if !fields.is_empty() => fields
1130 .iter()
1131 .map(|(name, value)| format!("{name}:\n{}", value_text(value)))
1132 .collect::<Vec<_>>()
1133 .join("\n\n"),
1134 _ => value_text(input),
1135 };
1136 sanitize_terminal_text(&text)
1137}
1138
1139pub fn tool_content_details(
1140 content: &[ToolCallContent],
1141 terminal_outputs: &[TerminalOutputRecord],
1142 raw_output: Option<&serde_json::Value>,
1143) -> Vec<String> {
1144 let mut details = Vec::new();
1145 let mut referenced: Vec<&str> = Vec::new();
1146 for item in content {
1147 let detail = match item {
1148 ToolCallContent::Content(content) => content_block_text(&content.content),
1149 ToolCallContent::Diff(_) => None,
1150 ToolCallContent::Terminal(terminal) => {
1154 let terminal_id = terminal.terminal_id.0.as_ref();
1155 referenced.push(terminal_id);
1156 Some(
1157 terminal_outputs
1158 .iter()
1159 .find(|record| record.terminal_id.as_str() == terminal_id)
1160 .map(terminal_output_detail)
1161 .or_else(|| raw_output.and_then(raw_output_terminal_detail))
1162 .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
1163 )
1164 }
1165 _ => None,
1166 };
1167 if let Some(detail) = detail {
1168 details.push(sanitize_terminal_text(&detail));
1169 }
1170 }
1171 for record in terminal_outputs {
1175 if referenced.contains(&record.terminal_id.as_str()) {
1176 continue;
1177 }
1178 let output = sanitize_terminal_text(&record.output);
1179 if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1180 details.push(terminal_exit_summary(record));
1184 } else {
1185 details.push(sanitize_terminal_text(&terminal_output_detail(record)));
1186 }
1187 }
1188 details
1189}
1190
1191fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1196 let output = raw_output.get("formatted_output")?.as_str()?;
1197 let Some(exit_code) = raw_output
1198 .get("exit_code")
1199 .and_then(serde_json::Value::as_i64)
1200 else {
1201 return Some(output.to_owned());
1202 };
1203 let summary = format!("exited {exit_code}");
1204 if output.is_empty() {
1205 return Some(summary);
1206 }
1207 Some(format!("{output}\n{summary}"))
1208}
1209
1210pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1212 let summary = terminal_exit_summary(record);
1213 if record.output.is_empty() {
1214 return summary;
1215 }
1216 format!("{}\n{summary}", record.output)
1217}
1218
1219fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1221 let mut summary = match (record.exit_code, &record.signal) {
1222 (_, Some(signal)) => format!("killed by {signal}"),
1223 (Some(code), None) => format!("exited {code}"),
1224 (None, None) => "released before exit".to_owned(),
1225 };
1226 if record.truncated {
1227 summary.push_str(" · output truncated");
1228 }
1229 summary
1230}
1231
1232pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1233 content
1234 .iter()
1235 .filter_map(|item| match item {
1236 ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1237 _ => None,
1238 })
1239 .collect()
1240}
1241
1242pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1243 locations
1244 .iter()
1245 .map(|location| match location.line {
1246 Some(line) => format!("{}:{line}", location.path.display()),
1247 None => location.path.display().to_string(),
1248 })
1249 .collect()
1250}
1251
1252pub(crate) fn push_streamed_entry(
1256 entries: &mut Vec<ChatEntry>,
1257 seq: u64,
1258 recorded_at_ms: Option<i64>,
1259 role: ChatRole,
1260 message_id: Option<String>,
1261 text: &str,
1262) {
1263 let text = sanitize_terminal_text(text);
1264 if let Some(last) = entries.last_mut()
1265 && last.role == role
1266 && (role == ChatRole::Thought || last.message_id == message_id)
1267 {
1268 last.touch(seq);
1269 if role == ChatRole::Thought
1270 && last.message_id != message_id
1271 && !last.text.is_empty()
1272 && !text.is_empty()
1273 {
1274 while last.text.ends_with('\n') {
1275 last.text.pop();
1276 }
1277 last.text.push('\n');
1278 last.text.push_str(text.trim_start_matches('\n'));
1279 } else {
1280 last.text.push_str(&text);
1281 }
1282 return;
1283 }
1284 let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1285 entry.message_id = message_id;
1286 entries.push(entry);
1287}
1288
1289pub fn apply_session_update_to_entries(
1293 entries: &mut Vec<ChatEntry>,
1294 seq: u64,
1295 recorded_at_ms: Option<i64>,
1296 update: SessionUpdate,
1297) -> Option<SessionUpdate> {
1298 match update {
1299 SessionUpdate::AgentMessageChunk(chunk) => {
1300 let message_id = chunk.message_id.map(|id| id.to_string());
1301 if let Some(text) = content_block_text(&chunk.content) {
1302 push_streamed_entry(
1303 entries,
1304 seq,
1305 recorded_at_ms,
1306 ChatRole::Agent,
1307 message_id,
1308 &text,
1309 );
1310 }
1311 }
1312 SessionUpdate::AgentThoughtChunk(chunk) => {
1313 let message_id = chunk.message_id.map(|id| id.to_string());
1314 if let Some(text) = content_block_text(&chunk.content) {
1315 push_streamed_entry(
1316 entries,
1317 seq,
1318 recorded_at_ms,
1319 ChatRole::Thought,
1320 message_id,
1321 &text,
1322 );
1323 }
1324 }
1325 SessionUpdate::UserMessageChunk(_) => {}
1328 SessionUpdate::ToolCall(call) => {
1329 let presentation = tool_call_presentation(&call);
1330 let mut entry = ChatEntry::tool(
1331 seq,
1332 call.title,
1333 Some(call.tool_call_id.to_string()),
1334 tool_status(&call.status),
1335 )
1336 .with_recorded_at(recorded_at_ms);
1337 mark_tool_end(&mut entry, recorded_at_ms);
1338 entry.tool_summary = Some(presentation.summary.clone());
1339 entry.tool_presentation = Some(presentation);
1340 entry.tool_input = call.raw_input;
1341 entry.tool_content = tool_content_details(&call.content, &[], call.raw_output.as_ref());
1342 entry.tool_diffstats = tool_diff_paths(&call.content);
1343 entry.tool_locations = tool_location_details(&call.locations);
1344 entries.push(entry);
1345 }
1346 SessionUpdate::ToolCallUpdate(update) => {
1347 let tool_call_id = update.tool_call_id.to_string();
1348 let entry = entries.iter_mut().rev().find(|entry| {
1349 entry.role == ChatRole::Tool
1350 && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1351 })?;
1352 entry.touch(seq);
1353 let kind = update.fields.kind;
1354 let raw_input = update.fields.raw_input.clone();
1355 let raw_output = update.fields.raw_output.clone();
1356 if let Some(input) = &raw_input {
1357 entry.tool_input = Some(input.clone());
1358 }
1359 if let Some(title) = update.fields.title {
1360 entry.text = sanitize_terminal_text(&title);
1361 }
1362 if let Some(status) = update.fields.status {
1363 entry.tool_status = Some(tool_status(&status));
1364 mark_tool_end(entry, recorded_at_ms);
1365 }
1366 if let Some(content) = update.fields.content {
1367 entry.tool_content =
1368 tool_content_details(&content, &[], update.fields.raw_output.as_ref());
1369 entry.tool_diffstats = tool_diff_paths(&content);
1370 }
1371 if let Some(locations) = update.fields.locations {
1372 entry.tool_locations = tool_location_details(&locations);
1373 }
1374 let presentation = update_tool_call_presentation(
1375 entry.tool_presentation.as_ref(),
1376 &entry.text,
1377 kind,
1378 raw_input.as_ref(),
1379 raw_output.as_ref(),
1380 );
1381 entry.tool_summary = Some(presentation.summary.clone());
1382 entry.tool_presentation = Some(presentation);
1383 }
1384 SessionUpdate::Plan(plan) => {
1385 let lines = plan
1386 .entries
1387 .into_iter()
1388 .map(|entry| PlanLine {
1389 text: sanitize_terminal_text(&entry.content),
1390 status: plan_status(&entry.status),
1391 })
1392 .collect();
1393 let latest_user_seq = entries
1394 .iter()
1395 .rev()
1396 .find(|entry| entry.role == ChatRole::User)
1397 .map_or(0, |entry| entry.seq);
1398 if let Some(entry) = entries
1399 .iter_mut()
1400 .rev()
1401 .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1402 {
1403 entry.touch(seq);
1404 entry.plan = lines;
1405 } else {
1406 entries.push(ChatEntry::plan(seq, lines));
1407 }
1408 }
1409 other => return Some(other),
1410 }
1411 None
1412}
1413
1414fn mark_tool_end(entry: &mut ChatEntry, recorded_at_ms: Option<i64>) {
1416 entry.tool_ended_at_ms = match entry.tool_status {
1417 Some(ToolStatus::Completed | ToolStatus::Failed) => recorded_at_ms,
1418 _ => None,
1419 };
1420}
1421
1422pub fn apply_runtime_event_to_entries(
1426 entries: &mut Vec<ChatEntry>,
1427 seq: u64,
1428 recorded_at_ms: Option<i64>,
1429 runtime: RuntimeEvent,
1430) -> Option<RuntimeEvent> {
1431 match runtime {
1432 RuntimeEvent::SessionUpdate { update } => {
1433 let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1434 Ok(parsed) => parsed,
1435 Err(error) => {
1436 tracing::debug!(%error, "ignoring invalid ACP session update");
1437 return None;
1438 }
1439 };
1440 apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1441 .map(|_| RuntimeEvent::SessionUpdate { update })
1442 }
1443 RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1444 entries.push(ChatEntry::plain(
1445 seq,
1446 ChatRole::System,
1447 format!("warning: {message}"),
1448 ));
1449 None
1450 }
1451 RuntimeEvent::ConfigApplied { key, value, .. } => {
1452 entries.push(ChatEntry::plain(
1453 seq,
1454 ChatRole::System,
1455 format!("{key} set to {value}"),
1456 ));
1457 None
1458 }
1459 RuntimeEvent::SessionStarted { resumed: false, .. } => {
1460 entries.push(ChatEntry::plain(
1461 seq,
1462 ChatRole::System,
1463 "harness session started",
1464 ));
1465 None
1466 }
1467 RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1468 RuntimeEvent::ElicitationResolved {
1469 reply: Some(reply), ..
1470 } => {
1471 let mut entry =
1472 ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1473 entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1474 entries.push(entry);
1475 None
1476 }
1477 other => Some(other),
1478 }
1479}
1480
1481pub fn transcript_item_text(item: &TranscriptItem) -> String {
1487 match &item.body {
1488 TranscriptBody::User { content } => materialized_content_text(content),
1489 TranscriptBody::Message { event } => format!(
1490 "{}\n\n{}",
1491 event.message_label(),
1492 mj_core::transcript::sanitize_terminal_text(
1493 event.message_text().expect("message entry metadata")
1494 )
1495 ),
1496 TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1497 materialized_chunks_text(chunks)
1498 }
1499 TranscriptBody::Tool {
1500 call,
1501 terminal_outputs,
1502 presentation,
1503 ..
1504 } => {
1505 let Ok(call) = ToolCall::deserialize(call) else {
1506 return "[invalid tool call]".to_owned();
1507 };
1508 let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1509 .summary
1510 .clone();
1511 if text.trim().is_empty() {
1512 text = call.title.clone();
1513 }
1514 for record in terminal_outputs {
1515 text.push('\n');
1516 text.push_str(&terminal_output_detail(record));
1517 }
1518 sanitize_terminal_text(&text)
1519 }
1520 TranscriptBody::TerminalOutput { record } => {
1521 sanitize_terminal_text(&terminal_output_detail(record))
1522 }
1523 TranscriptBody::Plan { plan } => {
1524 let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1525 return String::new();
1526 };
1527 plan.entries
1528 .iter()
1529 .map(|entry| {
1530 let status = match plan_status(&entry.status) {
1531 PlanStatus::Pending => "pending",
1532 PlanStatus::Running => "running",
1533 PlanStatus::Completed => "completed",
1534 };
1535 format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1536 })
1537 .collect::<Vec<_>>()
1538 .join("\n")
1539 }
1540 TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1541 TranscriptBody::System { text } => text.clone(),
1542 }
1543}
1544
1545pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1546 content
1547 .iter()
1548 .filter_map(|item| match item {
1549 ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1550 _ => None,
1551 })
1552 .collect()
1553}
1554
1555pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1556 let TranscriptBody::Tool { call, .. } = &item.body else {
1557 return None;
1558 };
1559 let call = match ToolCall::deserialize(call) {
1560 Ok(call) => call,
1561 Err(error) => {
1562 tracing::warn!(
1563 stable_id = %item.stable_id,
1564 %error,
1565 "could not decode a stored tool call while reading diff summary"
1566 );
1567 return None;
1568 }
1569 };
1570 if !matches!(
1571 tool_status(&call.status),
1572 ToolStatus::Completed | ToolStatus::Failed
1573 ) {
1574 return None;
1575 }
1576 let diffstats = compute_tool_diffstats(&call.content);
1577 (!diffstats.is_empty()).then_some(diffstats)
1578}
1579
1580fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1581 let patch = mj_core::diff::patch_of(diff);
1585 format!(
1586 "{} +{} −{}",
1587 diff.path.display(),
1588 patch.insertions,
1589 patch.deletions
1590 )
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595 use super::*;
1596 use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus, ToolCallUpdate};
1597 use serde_json::json;
1598
1599 #[test]
1600 fn a_live_tool_call_records_when_it_started_and_ended() {
1601 let mut entries = Vec::new();
1602 let call = ToolCall::new("tool-1", "cargo test").status(ToolCallStatus::InProgress);
1603 apply_session_update_to_entries(
1604 &mut entries,
1605 1,
1606 Some(1_000),
1607 SessionUpdate::ToolCall(call),
1608 );
1609 assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1610 assert_eq!(entries[0].tool_ended_at_ms, None);
1611
1612 let finish = SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1613 "tool-1",
1614 ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
1615 ));
1616 apply_session_update_to_entries(&mut entries, 2, Some(91_000), finish);
1617 assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1618 assert_eq!(entries[0].tool_ended_at_ms, Some(91_000));
1619 }
1620
1621 #[test]
1625 fn a_question_tool_is_summarized_by_its_whole_question() {
1626 let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1627 .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1628 assert_eq!(
1629 tool_call_presentation(&call).summary,
1630 "Which file name should I use for the new file?"
1631 );
1632 let read = ToolCall::new("read", "Read src/lib.rs");
1633 assert_eq!(tool_call_presentation(&read).summary, "Read");
1634 let stale = ToolCallPresentation {
1635 summary: "Which".into(),
1636 source: call.title.clone(),
1637 source_kind: ToolSummarySourceKind::Title,
1638 tool_kind: ToolKind::Other,
1639 summary_version: 1,
1640 };
1641 assert_eq!(
1642 materialized_tool_call_presentation(Some(&stale), &call).summary,
1643 "Which file name should I use for the new file?",
1644 "stored rows written by the old rules are repaired"
1645 );
1646 }
1647
1648 fn execute_summary(command: serde_json::Value) -> String {
1649 let call = ToolCall::new("argv", "Bash")
1650 .kind(ToolKind::Execute)
1651 .raw_input(command);
1652 tool_call_presentation(&call).summary
1653 }
1654
1655 #[test]
1656 fn unknown_leading_options_make_verb_position_ambiguous() {
1657 assert_eq!(
1658 execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1659 "git"
1660 );
1661 assert_eq!(
1662 execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1663 "cargo"
1664 );
1665 }
1666
1667 #[test]
1668 fn git_commands_with_nested_subcommands_show_both_verbs() {
1669 let cases = [
1670 ("git worktree add ../x mj/session", "git worktree add"),
1671 ("git -C repo worktree list", "git worktree list"),
1672 ("git stash push -u -m tag", "git stash push"),
1673 ("git stash", "git stash"),
1674 ("git remote -v", "git remote"),
1675 ("git bisect good abc123", "git bisect good"),
1676 ("git stash -- src", "git stash"),
1677 ("git log origin/master", "git log"),
1678 ("git config user.name", "git config"),
1679 ];
1680 for (command, summary) in cases {
1681 assert_eq!(
1682 execute_summary(json!({"command": command})),
1683 summary,
1684 "{command}"
1685 );
1686 }
1687 }
1688
1689 #[test]
1690 fn project_tools_and_script_runners_show_their_subcommands() {
1691 let cases = [
1692 ("mbx nextest run -p brokk-mj-tui", "mbx nextest"),
1693 ("mbx +1.91 build bifrost", "mbx build"),
1694 ("mbx cache stats --json", "mbx cache stats"),
1695 ("mj daemon restart", "mj daemon restart"),
1696 (
1697 "mj -i test --workspace hel daemon status",
1698 "mj daemon status",
1699 ),
1700 ("mj transcript abc123", "mj transcript"),
1701 ("tmux -L mjv-e send-keys -t 0 q", "tmux send-keys"),
1702 ("tmux -Lmjv capture-pane -p", "tmux capture-pane"),
1703 ("tmux -S /tmp/sock -2 new-session -d", "tmux new-session"),
1704 ("uv run pytest -q", "uv run pytest"),
1705 ("uv run ./scripts/check.py", "uv run check.py"),
1706 ("uv run --with x pytest", "uv run"),
1707 ("npm run build", "npm run build"),
1708 ("npm run-script test:e2e", "npm run-script test:e2e"),
1709 ("pnpm run lint", "pnpm run lint"),
1710 ("npm test", "npm test"),
1711 ];
1712 for (command, summary) in cases {
1713 assert_eq!(
1714 execute_summary(json!({"command": command})),
1715 summary,
1716 "{command}"
1717 );
1718 }
1719 }
1720
1721 #[test]
1722 fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1723 let cases = [
1724 ("bash -c 'python x.py'", "bash -c python"),
1725 ("/bin/bash -c \"python x.py\"", "bash -c python"),
1726 (
1727 "/usr/bin/zsh -lc 'git status && cargo test'",
1728 "zsh -c git status && cargo test",
1729 ),
1730 ("bash -c \"cd $dir && make\"", "bash -c cd && make"),
1731 ("bash -c \"$script\"", "bash -c"),
1732 ("/bin/bash script.sh", "bash"),
1733 (
1734 "bash -c 'bash -c \"uv run pytest\"'",
1735 "bash -c bash -c uv run pytest",
1736 ),
1737 ];
1738 for (command, summary) in cases {
1739 assert_eq!(
1740 execute_summary(json!({"command": command})),
1741 summary,
1742 "{command}"
1743 );
1744 }
1745 assert_eq!(
1747 execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1748 "python"
1749 );
1750 assert_eq!(
1751 execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1752 "zsh"
1753 );
1754 }
1755
1756 #[test]
1757 fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1758 let quoted = ToolCall::new("quoted", "Bash")
1759 .kind(ToolKind::Execute)
1760 .raw_input(json!({"command": "git \"status\""}));
1761 assert_eq!(tool_call_presentation("ed).summary, "git status");
1762
1763 let dynamic = ToolCall::new("dynamic", "Bash")
1764 .kind(ToolKind::Execute)
1765 .raw_input(json!({"command": "git \"$verb\""}));
1766 assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1767
1768 let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1769 .kind(ToolKind::Execute)
1770 .raw_input(json!({"command": "$command status"}));
1771 assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
1772 }
1773
1774 #[test]
1775 fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
1776 let call = ToolCall::new("call", "Bash")
1777 .kind(ToolKind::Execute)
1778 .raw_input(json!({
1779 "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
1780 }));
1781 assert_eq!(tool_call_presentation(&call).summary, "env");
1782
1783 let subshell = ToolCall::new("subshell", "Bash")
1784 .kind(ToolKind::Execute)
1785 .raw_input(json!({
1786 "command": "(cd dir && python x.py) | cat"
1787 }));
1788 assert_eq!(
1789 tool_call_presentation(&subshell).summary,
1790 "(cd && python) | cat"
1791 );
1792 }
1793
1794 #[test]
1795 fn shell_summary_keeps_list_pipeline_and_background_operators() {
1796 let simple = ToolCall::new("call-1", "Bash")
1797 .kind(ToolKind::Execute)
1798 .raw_input(json!({
1799 "command": "cd dir && python x.py | cat | wc ; print ok"
1800 }));
1801 let presentation = tool_call_presentation(&simple);
1802 assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
1803 assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
1804
1805 let call = ToolCall::new("operators", "Bash")
1806 .kind(ToolKind::Execute)
1807 .raw_input(json!({
1808 "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
1809 }));
1810
1811 assert_eq!(
1812 tool_call_presentation(&call).summary,
1813 "printf |& sed || echo & wait ; cat"
1814 );
1815 }
1816
1817 #[test]
1818 fn shell_summary_removes_structural_loop_and_group_separators() {
1819 let call = ToolCall::new("compound", "Bash")
1820 .kind(ToolKind::Execute)
1821 .raw_input(json!({
1822 "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
1823 }));
1824
1825 assert_eq!(
1826 tool_call_presentation(&call).summary,
1827 "rm ; mkdir ; nice python3"
1828 );
1829
1830 let conditional = ToolCall::new("conditional", "Bash")
1831 .kind(ToolKind::Execute)
1832 .raw_input(json!({
1833 "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
1834 }));
1835 assert_eq!(
1836 tool_call_presentation(&conditional).summary,
1837 "test ; rm ; mkdir ; echo"
1838 );
1839
1840 let case_statement = ToolCall::new("case", "Bash")
1841 .kind(ToolKind::Execute)
1842 .raw_input(json!({
1843 "command": "echo start; case x in a|b) echo branch;; esac; echo done"
1844 }));
1845 assert_eq!(
1846 tool_call_presentation(&case_statement).summary,
1847 "echo ; echo ; echo"
1848 );
1849 }
1850
1851 #[test]
1852 fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
1853 let call = ToolCall::new("live-loop-shape", "Bash")
1854 .kind(ToolKind::Execute)
1855 .raw_input(json!({
1856 "command": "cd /tmp && for spec in a b; do set -- $spec; rm \"$spec\"; mkdir -p \"$spec\"; nice -n 10 ./bin/bifrost \"$spec\"; echo \"$spec\"; done; python3 script.py"
1857 }));
1858
1859 assert_eq!(
1860 tool_call_presentation(&call).summary,
1861 "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
1862 );
1863 }
1864
1865 #[test]
1866 fn shell_summary_inserts_a_separator_after_a_heredoc() {
1867 let call = ToolCall::new("heredoc", "Bash")
1868 .kind(ToolKind::Execute)
1869 .raw_input(json!({
1870 "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
1871 }));
1872
1873 assert_eq!(
1874 tool_call_presentation(&call).summary,
1875 "python3 ; grep | head"
1876 );
1877 }
1878
1879 #[test]
1880 fn materialized_summary_from_an_older_parser_is_repaired() {
1881 let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
1882 let call = ToolCall::new("heredoc", "Bash")
1883 .kind(ToolKind::Execute)
1884 .raw_input(json!({ "command": source }));
1885 let stale = ToolCallPresentation {
1886 summary: "python3 grep | head".into(),
1887 source: source.into(),
1888 source_kind: ToolSummarySourceKind::RawInput,
1889 tool_kind: ToolKind::Execute,
1890 summary_version: 0,
1891 };
1892
1893 let repaired = materialized_tool_call_presentation(Some(&stale), &call);
1894 assert_eq!(repaired.summary, "python3 ; grep | head");
1895 assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
1896
1897 let mut current = repaired;
1898 current.summary = "stored current summary".into();
1899 assert_eq!(
1900 materialized_tool_call_presentation(Some(¤t), &call).summary,
1901 "stored current summary"
1902 );
1903 }
1904
1905 #[test]
1906 fn execute_summary_bounds_the_retained_source_before_parsing() {
1907 let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
1908 let call = ToolCall::new("bounded", "Bash")
1909 .kind(ToolKind::Execute)
1910 .raw_input(json!({ "command": command }));
1911
1912 let presentation = tool_call_presentation(&call);
1913 assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
1914 assert_eq!(presentation.summary, "echo");
1915 }
1916
1917 #[test]
1918 fn title_wrappers_and_malformed_shell_fall_back_safely() {
1919 let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
1920 assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
1921
1922 let malformed = ToolCall::new("bad", "Bash")
1923 .kind(ToolKind::Execute)
1924 .raw_input(json!({"command": "cd && ("}));
1925 assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
1926 }
1927
1928 #[test]
1929 fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
1930 let initial = ToolCall::new("call", "Bash")
1931 .kind(ToolKind::Execute)
1932 .raw_input(json!({"command": "python script.py"}));
1933 let previous = tool_call_presentation(&initial);
1934 let empty_input = json!({"command": null});
1935 let updated = update_tool_call_presentation(
1936 Some(&previous),
1937 "Running: ls -la",
1938 None,
1939 Some(&empty_input),
1940 None,
1941 );
1942 assert_eq!(updated.summary, "ls");
1943 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1944
1945 let output = json!({"command": "cat result.txt"});
1946 let updated = update_tool_call_presentation(
1947 Some(&previous),
1948 "Running: ls -la",
1949 None,
1950 Some(&empty_input),
1951 Some(&output),
1952 );
1953 assert_eq!(updated.summary, "cat");
1954 assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
1955
1956 let output_initial = ToolCall::new("output", "Bash")
1957 .kind(ToolKind::Execute)
1958 .raw_output(json!({"command": "python result.py"}));
1959 let output_previous = tool_call_presentation(&output_initial);
1960 let empty_output = json!({"command": null});
1961 let updated = update_tool_call_presentation(
1962 Some(&output_previous),
1963 "Running: ls -la",
1964 None,
1965 None,
1966 Some(&empty_output),
1967 );
1968 assert_eq!(updated.summary, "ls");
1969 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1970 }
1971
1972 fn rendered_tool_row(call: &ToolCall) -> String {
1973 let presentation = tool_call_presentation(call);
1974 let item = TranscriptItem {
1975 stable_id: "tool:golden".into(),
1976 position: 1,
1977 latest_content_event_ordinal: None,
1978 created_at_ms: 1,
1979 last_changed_at_ms: 1,
1980 body: TranscriptBody::Tool {
1981 call: serde_json::to_value(call).expect("serialize tool call"),
1982 terminal_outputs: Vec::new(),
1983 terminal_refs: Vec::new(),
1984 presentation: Some(Box::new(presentation)),
1985 },
1986 };
1987 transcript_item_text(&item)
1988 }
1989
1990 fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
1991 use std::fmt::Write as _;
1992 if !output.is_empty() {
1993 output.push('\n');
1994 }
1995 writeln!(output, "=== {label} (transcript row) ===").unwrap();
1996 output.push_str(&rendered_tool_row(call));
1997 output.push('\n');
1998 }
1999
2000 #[test]
2001 fn golden_transcript_tool_row_summary() {
2002 use std::fmt::Write as _;
2003
2004 let mut output = String::new();
2005 let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
2006 writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
2007 writeln!(output, "{}", format_diffstat(&diff)).unwrap();
2008
2009 let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
2010 let record = TerminalOutputRecord {
2011 terminal_id: "term-1".into(),
2012 output: text.into(),
2013 truncated,
2014 exit_code,
2015 signal: signal.map(str::to_owned),
2016 };
2017 let item = TranscriptItem {
2018 stable_id: "terminal:golden".into(),
2019 position: 1,
2020 latest_content_event_ordinal: None,
2021 created_at_ms: 1,
2022 last_changed_at_ms: 1,
2023 body: TranscriptBody::TerminalOutput { record },
2024 };
2025 transcript_item_text(&item)
2026 };
2027 for (label, row) in [
2028 ("successful terminal", terminal(Some(0), None, false, "out")),
2029 ("truncated terminal", terminal(Some(1), None, true, "out")),
2030 (
2031 "signal termination",
2032 terminal(None, Some("SIGKILL"), false, "out"),
2033 ),
2034 ("released terminal", terminal(None, None, false, "out")),
2035 (
2036 "silent signal termination",
2037 terminal(None, Some("SIGTERM"), false, ""),
2038 ),
2039 ] {
2040 writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
2041 }
2042
2043 append_tool_row(
2044 &mut output,
2045 "shell command",
2046 &ToolCall::new("shell", "Terminal")
2047 .kind(ToolKind::Execute)
2048 .raw_input(json!({
2049 "command": ["bash", "-lc", "cd dir && python x.py | cat"]
2050 })),
2051 );
2052 append_tool_row(
2053 &mut output,
2054 "ordinary argv command",
2055 &ToolCall::new("argv", "Execute")
2056 .kind(ToolKind::Execute)
2057 .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
2058 );
2059
2060 let update_call = ToolCall::new("shell", "Bash")
2061 .kind(ToolKind::Execute)
2062 .raw_input(json!({"command": "cargo test"}));
2063 let original = tool_call_presentation(&update_call);
2064 let mut output_update = ToolCallUpdateFields::default();
2065 output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
2066 writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
2067 writeln!(
2068 output,
2069 "presentation changed: {}",
2070 tool_call_update_changes_presentation(&update_call, &output_update)
2071 )
2072 .unwrap();
2073 writeln!(output, "{}", original.summary).unwrap();
2074 let mut status_update = ToolCallUpdateFields::default();
2075 status_update.status = Some(ToolCallStatus::Completed);
2076 writeln!(
2077 output,
2078 "status-only update changes presentation: {}",
2079 tool_call_update_changes_presentation(&update_call, &status_update)
2080 )
2081 .unwrap();
2082 let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
2083 writeln!(
2084 output,
2085 "output-only call changes presentation: {}",
2086 tool_call_update_changes_presentation(&output_call, &output_update)
2087 )
2088 .unwrap();
2089 let changed_input = json!({"command": "cargo check"});
2090 let mut input_update = ToolCallUpdateFields::default();
2091 input_update.raw_input = Some(changed_input.clone());
2092 writeln!(
2093 output,
2094 "changed command presentation: {}",
2095 tool_call_update_changes_presentation(&update_call, &input_update)
2096 )
2097 .unwrap();
2098 writeln!(
2099 output,
2100 "updated row: {}",
2101 update_tool_call_presentation(
2102 Some(&original),
2103 "Bash",
2104 Some(ToolKind::Execute),
2105 Some(&changed_input),
2106 None,
2107 )
2108 .summary
2109 )
2110 .unwrap();
2111
2112 for (label, command) in [
2113 (
2114 "git registered verb",
2115 json!({"command": ["git", "--no-pager", "status", "--short"]}),
2116 ),
2117 (
2118 "cargo registered verb",
2119 json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
2120 ),
2121 (
2122 "gh registered namespace",
2123 json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
2124 ),
2125 (
2126 "docker registered namespace",
2127 json!({"command": ["docker", "--context", "work", "compose", "up"]}),
2128 ),
2129 (
2130 "podman registered namespace",
2131 json!({"command": ["podman", "machine", "list"]}),
2132 ),
2133 (
2134 "uv registered namespace",
2135 json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
2136 ),
2137 (
2138 "rustup registered namespace",
2139 json!({"command": ["rustup", "toolchain", "list"]}),
2140 ),
2141 (
2142 "npm registered namespace",
2143 json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
2144 ),
2145 ] {
2146 append_tool_row(
2147 &mut output,
2148 label,
2149 &ToolCall::new("argv", "Bash")
2150 .kind(ToolKind::Execute)
2151 .raw_input(command),
2152 );
2153 }
2154
2155 let shell = ToolCall::new("string", "Bash")
2156 .kind(ToolKind::Execute)
2157 .raw_input(json!({"command": "git --no-pager status --short"}));
2158 let argv = ToolCall::new("argv", "Bash")
2159 .kind(ToolKind::Execute)
2160 .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
2161 writeln!(
2162 output,
2163 "\n=== shell and argv invocation depth (transcript rows) ==="
2164 )
2165 .unwrap();
2166 writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
2167 writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
2168
2169 for (label, command) in [
2170 ("sudo wrapper", "sudo -n git status"),
2171 ("env wrapper", "env FOO=bar git status"),
2172 ("command wrapper", "command git status"),
2173 ] {
2174 append_tool_row(
2175 &mut output,
2176 label,
2177 &ToolCall::new("wrapper", "Bash")
2178 .kind(ToolKind::Execute)
2179 .raw_input(json!({"command": command})),
2180 );
2181 }
2182
2183 for (label, command) in [
2184 (
2185 "unlisted build tool",
2186 json!({"command": ["mytool", "build", "src"]}),
2187 ),
2188 (
2189 "unlisted script",
2190 json!({"command": ["mytool", "./script.sh"]}),
2191 ),
2192 ("python script", json!({"command": ["python", "script.py"]})),
2193 (
2194 "gh API namespace",
2195 json!({"command": ["gh", "api", "graphql"]}),
2196 ),
2197 (
2198 "docker run namespace",
2199 json!({"command": ["docker", "run", "ubuntu"]}),
2200 ),
2201 (
2202 "registered future git verb",
2203 json!({"command": ["git", "future-verb"]}),
2204 ),
2205 (
2206 "absolute git with attached directory",
2207 json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
2208 ),
2209 (
2210 "git short global option",
2211 json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
2212 ),
2213 (
2214 "gh attached repository option",
2215 json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
2216 ),
2217 (
2218 "cargo color option",
2219 json!({"command": ["cargo", "--color=always", "test"]}),
2220 ),
2221 (
2222 "cargo config option",
2223 json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
2224 ),
2225 ] {
2226 append_tool_row(
2227 &mut output,
2228 label,
2229 &ToolCall::new("argv", "Bash")
2230 .kind(ToolKind::Execute)
2231 .raw_input(command),
2232 );
2233 }
2234
2235 for command in [
2236 vec!["nice", "-n", "10", "python3", "script.py"],
2237 vec!["nice", "--adjustment", "10", "python3", "script.py"],
2238 vec!["nice", "--adjustment=10", "python3", "script.py"],
2239 vec!["nice", "-10", "python3", "script.py"],
2240 vec!["nice", "-n10", "python3", "script.py"],
2241 vec!["nice", "--", "python3", "script.py"],
2242 ] {
2243 append_tool_row(
2244 &mut output,
2245 "nice command options",
2246 &ToolCall::new("nice", "Bash")
2247 .kind(ToolKind::Execute)
2248 .raw_input(json!({"command": command})),
2249 );
2250 }
2251 append_tool_row(
2252 &mut output,
2253 "nice shell command",
2254 &ToolCall::new("nice-shell", "Bash")
2255 .kind(ToolKind::Execute)
2256 .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
2257 );
2258 for (label, command) in [
2259 ("timeout shell command", json!("timeout git status")),
2260 (
2261 "timeout argv command",
2262 json!(["timeout", "30s", "git", "-C", "repo", "worktree", "list"]),
2263 ),
2264 (
2265 "timeout command options",
2266 json!([
2267 "timeout",
2268 "--foreground",
2269 "--preserve-status",
2270 "--verbose",
2271 "--signal",
2272 "TERM",
2273 "--kill-after=5s",
2274 "1.5m",
2275 "git",
2276 "status"
2277 ]),
2278 ),
2279 (
2280 "timeout attached short options",
2281 json!("timeout -sTERM -k5s -- 30 git status"),
2282 ),
2283 (
2284 "nested command wrappers",
2285 json!("nice -n 10 timeout 5m nice -- cargo +nightly test -q"),
2286 ),
2287 (
2288 "recursive script runner",
2289 json!("uv run /usr/bin/timeout 5m git status"),
2290 ),
2291 (
2292 "wrapped shell command",
2293 json!("timeout 1h /bin/bash -lc 'git status && cargo test'"),
2294 ),
2295 (
2296 "timeout in a pipeline",
2297 json!("timeout 10 git status | cat && timeout 2m gh pr list"),
2298 ),
2299 (
2300 "timeout unknown option",
2301 json!("nice timeout --mystery 10 git status"),
2302 ),
2303 (
2304 "timeout dynamic duration",
2305 json!("timeout \"$duration\" git status"),
2306 ),
2307 (
2308 "timeout dynamic command",
2309 json!("timeout 30 \"$command\" status"),
2310 ),
2311 ("wrapped dynamic verb", json!("timeout 30 git \"$verb\"")),
2312 ("timeout without command", json!(["timeout", "30"])),
2313 (
2314 "script name is not an invocation",
2315 json!("timeout 30 npm run git status"),
2316 ),
2317 (
2318 "ordinary command arguments are not invocations",
2319 json!("timeout 30 python git status"),
2320 ),
2321 (
2322 "ssh remote command",
2323 json!("ssh builder git status --short"),
2324 ),
2325 (
2326 "ssh remote argv",
2327 json!(["ssh", "builder", "git", "-C", "repo", "worktree", "list"]),
2328 ),
2329 (
2330 "ssh quoted remote script",
2331 json!("ssh builder 'cd repo && git status | cat'"),
2332 ),
2333 (
2334 "ssh quoted remote argv script",
2335 json!(["ssh", "builder", "git status && cargo test -q"]),
2336 ),
2337 (
2338 "ssh connection options",
2339 json!(
2340 "/usr/bin/ssh -vvT -p 2222 -o BatchMode=yes -i /keys/build builder git status"
2341 ),
2342 ),
2343 (
2344 "ssh attached options after destination",
2345 json!("ssh builder -Tp2222 -oBatchMode=yes -- uv run pytest -q"),
2346 ),
2347 (
2348 "ssh wrapped remote shell",
2349 json!("timeout 30 ssh -- builder 'bash -lc \"git status && cargo test\"'"),
2350 ),
2351 ("ssh without remote command", json!("ssh builder")),
2352 ("ssh dynamic destination", json!("ssh \"$host\" git status")),
2353 (
2354 "ssh dynamic remote script",
2355 json!("ssh builder \"cd $dir && git status\""),
2356 ),
2357 (
2358 "ssh dynamic remote command",
2359 json!("ssh builder \"$script\""),
2360 ),
2361 (
2362 "ssh unknown connection option",
2363 json!("ssh --mystery value builder git status"),
2364 ),
2365 (
2366 "ssh unknown option after destination",
2367 json!("ssh builder --mystery value git status"),
2368 ),
2369 ("ssh without destination", json!(["ssh", "-p", "2222"])),
2370 (
2371 "ssh nesting budget",
2372 json!(format!("{}git status", "ssh builder ".repeat(2_000))),
2373 ),
2374 ] {
2375 append_tool_row(
2376 &mut output,
2377 label,
2378 &ToolCall::new("recursive", "Bash")
2379 .kind(ToolKind::Execute)
2380 .raw_input(json!({"command": command})),
2381 );
2382 }
2383 for (label, command, summary, summary_version) in [
2384 (
2385 "cached wrapper summary",
2386 "nice -n 10 timeout 30 git status",
2387 "nice timeout",
2388 4,
2389 ),
2390 ("cached ssh summary", "ssh builder 'git status'", "ssh", 5),
2391 ] {
2392 let cached = ToolCall::new("cached-wrapper", "Bash")
2393 .kind(ToolKind::Execute)
2394 .raw_input(json!({"command": command}));
2395 let item = TranscriptItem {
2396 stable_id: "tool:cached-wrapper".into(),
2397 position: 1,
2398 latest_content_event_ordinal: None,
2399 created_at_ms: 1,
2400 last_changed_at_ms: 1,
2401 body: TranscriptBody::Tool {
2402 call: serde_json::to_value(&cached).expect("serialize tool call"),
2403 terminal_outputs: Vec::new(),
2404 terminal_refs: Vec::new(),
2405 presentation: Some(Box::new(ToolCallPresentation {
2406 summary: summary.into(),
2407 summary_version,
2408 ..tool_call_presentation(&cached)
2409 })),
2410 },
2411 };
2412 writeln!(
2413 output,
2414 "\n=== {label} (transcript row) ===\n{}",
2415 transcript_item_text(&item)
2416 )
2417 .unwrap();
2418 }
2419 append_tool_row(
2420 &mut output,
2421 "non-execute tool title",
2422 &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
2423 );
2424
2425 mj_core::golden::assert_golden(
2426 env!("CARGO_MANIFEST_DIR"),
2427 "transcript-tool-row-summary",
2428 &output,
2429 );
2430 }
2431}