1use super::check::{cmd_verdict, pipeline_verdict};
2use super::*;
3use crate::allowlist::Matcher;
4use crate::parse::Token;
5use crate::verdict::{SafetyLevel, Verdict};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Explanation {
14 pub overall: Verdict,
15 pub segments: Vec<SegmentReport>,
16 pub parsed: bool,
18 pub stateful: bool,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SegmentReport {
25 pub text: String,
27 pub verdict: Verdict,
28 pub culprit: Option<String>,
33}
34
35pub fn explain(input: &str) -> Explanation {
37 let _rules = crate::allowlist::suspended();
38 explain_inner(input)
39}
40
41pub fn explain_with_coverage(input: &str, patterns: &Matcher) -> Explanation {
46 let _rules = crate::allowlist::in_force(patterns);
47 explain_inner(input)
48}
49
50fn explain_inner(input: &str) -> Explanation {
51 let Some(_guard) = super::check::ClassifyGuard::enter(input.len()) else {
61 return Explanation {
62 overall: Verdict::Denied,
63 segments: vec![SegmentReport { text: input.trim().to_string(), verdict: Verdict::Denied, culprit: None }],
64 parsed: false,
65 stateful: false,
66 };
67 };
68 let Some(script) = parse(input) else {
69 return Explanation {
70 overall: Verdict::Denied,
71 segments: vec![SegmentReport { text: input.trim().to_string(), verdict: Verdict::Denied, culprit: None }],
72 parsed: false,
73 stateful: false,
74 };
75 };
76
77 let segments: Vec<SegmentReport> = super::check::walk_with_scope(&script, segment_report, worst_segment);
82 if super::scope_budget::walk_untrusted() {
90 return Explanation {
91 overall: Verdict::Denied,
92 segments: vec![SegmentReport { text: input.trim().to_string(), verdict: Verdict::Denied, culprit: None }],
93 parsed: true,
94 stateful: false,
95 };
96 }
97 let overall = segments.iter().map(|s| s.verdict).fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
98 let stateful = segments.len() >= 2 && script.0.iter().any(establishes_shell_state);
99
100 Explanation { overall, segments, parsed: true, stateful }
101}
102
103fn worst_segment(first: SegmentReport, second: SegmentReport) -> SegmentReport {
104 let culprit = if first.verdict.is_allowed() { second.culprit } else { first.culprit };
105 SegmentReport { text: first.text, verdict: first.verdict.combine(second.verdict), culprit }
106}
107
108fn segment_report(stmt: &Stmt) -> SegmentReport {
109 let verdict = pipeline_verdict(&stmt.pipeline);
110 let redundant_with_segment_text = matches!(stmt.pipeline.commands.as_slice(), [Cmd::Simple(_)]);
118 let culprit = if verdict.is_allowed() || redundant_with_segment_text { None } else { first_denied_label(&stmt.pipeline) };
119 SegmentReport { text: stmt.pipeline.to_string(), verdict, culprit }
120}
121
122fn first_denied_label(pipeline: &Pipeline) -> Option<String> {
123 pipeline.commands.iter().find(|c| !cmd_verdict(c).is_allowed()).and_then(command_label)
124}
125
126fn command_label(cmd: &Cmd) -> Option<String> {
143 match cmd {
144 Cmd::Simple(s) => simple_cmd_name(s),
145 Cmd::FunctionDef { .. } => None,
148 Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } => denied_label_in(body),
149 Cmd::For { body, .. } => denied_label_in(body),
150 Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => denied_label_in(cond).or_else(|| denied_label_in(body)),
151 Cmd::If { branches, else_body, .. } => branches
152 .iter()
153 .find_map(|b| denied_label_in(&b.cond).or_else(|| denied_label_in(&b.body)))
154 .or_else(|| else_body.as_ref().and_then(denied_label_in)),
155 Cmd::Case { arms, .. } => arms.iter().find_map(|arm| denied_label_in(&arm.body)),
156 Cmd::DoubleBracket { .. } => None,
158 }
159}
160
161pub(crate) fn denied_inner_words(input: &str) -> Option<Vec<String>> {
171 let _guard = super::check::ClassifyGuard::enter(input.len())?;
172 let script = parse(input)?;
173 let [stmt] = &script.0[..] else { return None };
174 let [cmd] = &stmt.pipeline.commands[..] else { return None };
175 if matches!(cmd, Cmd::Simple(_)) {
178 return None;
179 }
180 first_denied_simple(cmd)
181}
182
183fn first_denied_simple(cmd: &Cmd) -> Option<Vec<String>> {
185 match cmd {
186 Cmd::Simple(s) => Some(s.words.iter().map(Word::eval).collect()),
187 Cmd::FunctionDef { .. } | Cmd::DoubleBracket { .. } => None,
188 Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } | Cmd::For { body, .. } => first_denied_simple_in(body),
189 Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => {
190 first_denied_simple_in(cond).or_else(|| first_denied_simple_in(body))
191 }
192 Cmd::If { branches, else_body, .. } => branches
193 .iter()
194 .find_map(|b| first_denied_simple_in(&b.cond).or_else(|| first_denied_simple_in(&b.body)))
195 .or_else(|| else_body.as_ref().and_then(first_denied_simple_in)),
196 Cmd::Case { arms, .. } => arms.iter().find_map(|arm| first_denied_simple_in(&arm.body)),
197 }
198}
199
200fn first_denied_simple_in(script: &Script) -> Option<Vec<String>> {
201 first_denied_in(script, first_denied_simple)
202}
203
204fn first_denied_in<T>(script: &Script, describe: fn(&Cmd) -> Option<T>) -> Option<T> {
207 super::check::walk_with_scope(
208 script,
209 |stmt| stmt.pipeline.commands.iter().find(|c| !cmd_verdict(c).is_allowed()).and_then(describe),
210 Option::or,
211 )
212 .into_iter()
213 .flatten()
214 .next()
215}
216
217fn denied_label_in(script: &Script) -> Option<String> {
224 first_denied_in(script, command_label)
225}
226
227fn simple_cmd_name(s: &SimpleCmd) -> Option<String> {
228 s.words
229 .first()
230 .map(|w| Token::from_raw(w.eval()).command_name().to_string())
231 .filter(|name| !name.is_empty())
232}
233
234fn establishes_shell_state(stmt: &Stmt) -> bool {
238 stmt.pipeline.commands.iter().any(|cmd| match cmd {
239 Cmd::Simple(s) => {
240 if s.words.is_empty() && !s.env.is_empty() {
241 return true;
242 }
243 matches!(simple_cmd_name(s).as_deref(), Some("cd" | "pushd" | "popd" | "export" | "source" | "." | "set" | "alias" | "umask"))
244 }
245 _ => false,
246 })
247}
248
249impl Explanation {
250 pub fn is_allowed(&self) -> bool {
251 self.overall.is_allowed()
252 }
253
254 fn counts(&self) -> (usize, usize) {
255 let total = self.segments.len();
256 let denied = self.segments.iter().filter(|s| !s.verdict.is_allowed()).count();
257 (total, denied)
258 }
259
260 pub fn should_surface(&self) -> bool {
266 if !self.parsed || self.segments.len() < 2 {
267 return false;
268 }
269 let (total, denied) = self.counts();
270 denied > 0 && denied < total
271 }
272
273 pub fn render(&self) -> String {
276 let mut out = self.render_for_person();
277 if self.parsed
278 && let (total, denied) = self.counts()
279 && let Some(tip) = self.guidance(total, denied)
280 {
281 out.push_str(tip);
282 out.push('\n');
283 }
284 out
285 }
286
287 pub fn render_for_person(&self) -> String {
290 if !self.parsed {
291 return "safe-chains: could not parse this command, so it will not be auto-approved.\n".to_string();
292 }
293 if self.segments.is_empty() {
294 return "safe-chains: no command to check.\n".to_string();
295 }
296
297 let (total, denied) = self.counts();
298 let mut out = String::new();
299 out.push_str(&header(total, denied));
300 for s in &self.segments {
301 out.push_str(&render_line(s));
302 }
303 out
304 }
305
306 pub fn render_context(&self) -> String {
307 if !(self.parsed && self.stateful) {
308 return self.render();
309 }
310 let mut out = String::from("safe-chains did not auto-approve:\n");
311 for s in self.segments.iter().filter(|s| !s.verdict.is_allowed()) {
312 out.push_str(&render_line(s));
313 }
314 out.push_str("The command has likely already run. This is feedback, not a request to re-run it.\n");
315 out
316 }
317
318 fn guidance(&self, total: usize, denied: usize) -> Option<&'static str> {
319 if denied == 0 {
320 return None;
321 }
322 if total == 1 {
327 return None;
328 }
329 if denied == total {
330 return Some("This is not a block. These all need manual approval. None of them auto-approve on their own.");
331 }
332 if self.stateful {
333 return Some(
334 "This is not a block. The command has likely already run, so this is feedback and not a request to re-run it. These segments share shell state, such as a cd, a variable, or a source, so they belong in one call. Bundling them was correct. Nothing to change.",
335 );
336 }
337 Some(
338 "This is not a block. The command has likely already run, so this is feedback and not a request to re-run it. Next time send independent commands as separate tool calls instead of chaining them. The ✓ segments auto-approve on their own, so only a ✗ segment needs approval.",
339 )
340 }
341}
342
343fn header(total: usize, denied: usize) -> String {
344 if denied == 0 {
345 if total == 1 {
346 return "safe-chains: auto-approves.\n".to_string();
347 }
348 return format!("safe-chains: all {total} segments auto-approve.\n");
349 }
350 if total == 1 {
355 return format!("safe-chains: {}\n", crate::refusal::EXPLAIN_SINGLE);
356 }
357 format!("safe-chains: did not auto-approve {denied} of {total} segments. {}\n", crate::refusal::EXPLAIN_MANY)
358}
359
360fn render_line(s: &SegmentReport) -> String {
364 let mark = if s.verdict.is_allowed() { '✓' } else { '✗' };
365 let text = crate::sanitize_display(&s.text);
366 match &s.culprit {
367 Some(culprit) if !s.verdict.is_allowed() => {
368 format!(" {mark} {text} ({})\n", crate::sanitize_display(culprit))
369 }
370 _ => format!(" {mark} {text}\n"),
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 fn marks(input: &str) -> Vec<bool> {
379 explain(input).segments.iter().map(|s| s.verdict.is_allowed()).collect()
380 }
381
382 #[test]
383 fn single_safe_command_one_allowed_segment() {
384 let e = explain("ls -la");
385 assert!(e.is_allowed());
386 assert_eq!(e.segments.len(), 1);
387 assert!(e.segments[0].verdict.is_allowed());
388 assert_eq!(e.segments[0].culprit, None);
389 }
390
391 #[test]
392 fn single_unsafe_command_is_denied_without_redundant_culprit() {
393 let e = explain("rm -rf /");
394 assert!(!e.is_allowed());
395 assert_eq!(e.segments.len(), 1);
396 assert_eq!(e.segments[0].culprit, None);
397 }
398
399 #[test]
400 fn one_torpedo_marks_only_that_segment() {
401 let e = explain("git status && rm -rf / && echo done");
402 assert!(!e.is_allowed());
403 assert_eq!(marks("git status && rm -rf / && echo done"), vec![true, false, true]);
404 assert!(e.segments.iter().all(|s| s.culprit.is_none()));
405 }
406
407 #[test]
408 fn all_safe_chain_is_allowed() {
409 let e = explain("git status && ls && echo hi");
410 assert!(e.is_allowed());
411 assert_eq!(marks("git status && ls && echo hi"), vec![true, true, true]);
412 }
413
414 #[test]
415 fn semicolons_and_or_split_into_segments() {
416 assert_eq!(explain("ls; pwd; whoami").segments.len(), 3);
417 assert_eq!(explain("ls || rm -rf /").segments.len(), 2);
418 }
419
420 #[test]
432 fn a_denied_compound_names_the_command_inside_it() {
433 for src in [
434 "(cat ~/.ssh/id_rsa)", "{ cat ~/.ssh/id_rsa; }", "if true; then cat ~/.ssh/id_rsa; fi",
435 "for f in a b; do cat ~/.ssh/id_rsa; done", "while true; do cat ~/.ssh/id_rsa; done",
436 "case $x in a) cat ~/.ssh/id_rsa ;; esac",
437 ] {
438 let ex = explain(src);
439 assert_eq!(ex.segments.len(), 1, "{src}: one segment");
440 assert!(!ex.is_allowed(), "{src}: denied");
441 assert_eq!(ex.segments[0].culprit.as_deref(), Some("cat"), "{src}: must name the command inside the construct");
442 }
443
444 assert_eq!(denied_inner_words("(cat ~/.ssh/id_rsa)"), Some(vec!["cat".to_string(), "~/.ssh/id_rsa".to_string()]),);
446 assert_eq!(denied_inner_words("cat ~/.ssh/id_rsa"), None);
448 assert_eq!(denied_inner_words("(ls)"), None);
450 }
451
452 #[test]
453 fn culprit_is_first_denied_in_a_pipeline() {
454 let e = explain("grep foo file | rm -rf /");
455 assert!(!e.is_allowed());
456 assert_eq!(e.segments.len(), 1);
457 assert_eq!(e.segments[0].culprit.as_deref(), Some("rm"));
458 }
459
460 #[test]
461 fn segment_text_round_trips() {
462 let e = explain("git status && echo done");
463 assert_eq!(e.segments[0].text, "git status");
464 assert_eq!(e.segments[1].text, "echo done");
465 }
466
467 #[test]
468 fn unparseable_input_is_a_single_unparsed_segment() {
469 let e = explain("echo 'unterminated");
470 assert!(!e.parsed);
471 assert!(!e.is_allowed());
472 }
473
474 #[test]
477 fn cd_chain_is_marked_stateful() {
478 assert!(explain("cd build && rm -rf x").stateful);
479 assert!(explain("export FOO=bar && rm -rf x").stateful);
480 assert!(explain("FOO=bar && rm -rf x").stateful);
481 assert!(explain("source ./env && rm -rf x").stateful);
482 }
483
484 #[test]
485 fn independent_chain_is_not_stateful() {
486 assert!(!explain("git status && rm -rf x && echo done").stateful);
487 assert!(!explain("ls && pwd").stateful);
488 }
489
490 #[test]
491 fn single_segment_is_never_stateful() {
492 assert!(!explain("cd build").stateful);
493 }
494
495 #[test]
498 fn surfaces_only_the_mixed_bundling_case() {
499 assert!(explain("git status && rm -rf / && echo done").should_surface());
500 assert!(!explain("ls && pwd").should_surface(), "all-safe: nothing to teach");
501 assert!(!explain("rm -rf / && rm -rf /etc").should_surface(), "all-denied: no rescue");
502 assert!(!explain("rm -rf /").should_surface(), "single denied: no chaining lesson");
503 assert!(!explain("echo 'unterminated").should_surface(), "unparseable");
504 }
505
506 #[test]
509 fn stateful_chain_context_names_only_the_refused_segments() {
510 assert_eq!(
511 explain("cd build && cargo publish").render_context(),
512 "safe-chains did not auto-approve:\n ✗ cargo publish\nThe command has likely already run. This is feedback, not a request to re-run it.\n"
513 );
514 }
515
516 proptest::proptest! {
517 #[test]
518 fn hook_context_has_one_line_per_listed_segment(
519 cmd in proptest::sample::select(crate::handler_property_tests::FORGERY_PAYLOADS.to_vec()),
520 ) {
521 let e = explain(&format!("cd x && {cmd}"));
522 let context = e.render_context();
523 let short = e.parsed && e.stateful;
524 let expected = if short { e.segments.iter().filter(|s| !s.verdict.is_allowed()).count() } else { e.segments.len() };
525 let lines = context.lines().filter(|l| l.starts_with(" \u{2713} ") || l.starts_with(" \u{2717} ")).count();
526 proptest::prop_assert_eq!(lines, expected, "{}", context);
527 proptest::prop_assert!(!short || !context.contains('\u{2713}'), "{}", context);
528 }
529 }
530
531 #[test]
532 fn stateless_chain_context_keeps_the_full_breakdown() {
533 let e = explain("git status && rm -rf / && echo done");
534 assert_eq!(e.render_context(), e.render());
535 }
536
537 #[test]
540 fn coverage_overlay_flips_a_user_allowed_segment() {
541 let patterns = Matcher::from_allow_patterns(&["rm *"]);
542 let e = explain_with_coverage("git status && rm -rf / && echo done", &patterns);
543 assert!(e.is_allowed(), "user allowlisted rm, so the chain auto-approves");
544 assert!(e.segments.iter().all(|s| s.verdict.is_allowed()));
545 assert!(!e.should_surface());
546 }
547
548 #[test]
549 fn coverage_overlay_leaves_uncovered_segments_denied() {
550 let patterns = Matcher::from_allow_patterns(&["rm *"]);
551 let e = explain_with_coverage("rm -rf / && cargo publish", &patterns);
552 assert!(!e.is_allowed());
553 assert_eq!(marks_cov("rm -rf / && cargo publish", &patterns), vec![true, false]);
554 }
555
556 fn marks_cov(input: &str, patterns: &Matcher) -> Vec<bool> {
557 explain_with_coverage(input, patterns).segments.iter().map(|s| s.verdict.is_allowed()).collect()
558 }
559
560 #[test]
563 fn render_mixed_chain_lists_marks_and_split_tip() {
564 let out = explain("git status && rm -rf / && echo done").render();
565 assert!(out.contains("✓ git status"));
566 assert!(out.contains("✗ rm -rf /"));
567 assert!(out.contains("✓ echo done"));
568 assert!(out.contains("1 of 3 segments"));
569 assert!(out.contains("not a block"), "must clarify it is not a block: {out}");
570 assert!(out.contains("not a request to re-run"), "must not invite a re-run: {out}");
571 assert!(out.contains("separate tool calls"));
572 }
573
574 #[test]
575 fn render_stateful_chain_says_belongs_in_one_call() {
576 let out = explain("cd build && rm -rf / && echo done").render();
577 assert!(out.contains("belong in one call"), "stateful chain must not advise splitting: {out}");
578 assert!(out.contains("not a request to re-run"));
579 assert!(!out.contains("separate tool calls"));
580 }
581
582 #[test]
583 fn render_pipeline_culprit_disambiguates_failing_stage() {
584 let out = explain("grep foo file | rm -rf /").render();
585 assert!(out.contains("(rm)"), "pipeline should name the failing stage: {out}");
586 }
587
588 #[test]
589 fn render_all_safe_has_no_tip() {
590 let out = explain("ls && pwd").render();
591 assert!(out.contains("all 2 segments auto-approve"));
592 assert!(!out.contains('✗'));
593 assert!(!out.contains("approval"));
594 }
595
596 #[test]
597 fn render_single_denied_keeps_it_alone() {
598 let out = explain("cargo publish").render();
599 assert!(out.contains("did not auto-approve"), "says what happened: {out}");
604 assert!(out.contains("has researched"), "says why, without rating the command: {out}");
605 assert!(!out.contains("on its own"), "{out}");
607 }
608
609 #[test]
610 fn render_unparseable_is_explicit() {
611 let out = explain("echo 'unterminated").render();
612 assert!(out.contains("could not parse"));
613 }
614
615 #[test]
616 fn empty_input_renders_no_command() {
617 for input in ["", " "] {
618 let e = explain(input);
619 assert!(e.segments.is_empty(), "{input:?} should have no segments");
620 assert!(e.render().contains("no command to check"));
621 }
622 }
623}