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);
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 segment_report(stmt: &Stmt) -> SegmentReport {
104 let verdict = pipeline_verdict(&stmt.pipeline);
105 let redundant_with_segment_text = matches!(stmt.pipeline.commands.as_slice(), [Cmd::Simple(_)]);
113 let culprit = if verdict.is_allowed() || redundant_with_segment_text { None } else { first_denied_label(&stmt.pipeline) };
114 SegmentReport { text: stmt.pipeline.to_string(), verdict, culprit }
115}
116
117fn first_denied_label(pipeline: &Pipeline) -> Option<String> {
118 pipeline.commands.iter().find(|c| !cmd_verdict(c).is_allowed()).and_then(command_label)
119}
120
121fn command_label(cmd: &Cmd) -> Option<String> {
138 match cmd {
139 Cmd::Simple(s) => simple_cmd_name(s),
140 Cmd::FunctionDef { .. } => None,
143 Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } => denied_label_in(body),
144 Cmd::For { body, .. } => denied_label_in(body),
145 Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => denied_label_in(cond).or_else(|| denied_label_in(body)),
146 Cmd::If { branches, else_body, .. } => branches
147 .iter()
148 .find_map(|b| denied_label_in(&b.cond).or_else(|| denied_label_in(&b.body)))
149 .or_else(|| else_body.as_ref().and_then(denied_label_in)),
150 Cmd::Case { arms, .. } => arms.iter().find_map(|arm| denied_label_in(&arm.body)),
151 Cmd::DoubleBracket { .. } => None,
153 }
154}
155
156pub(crate) fn denied_inner_words(input: &str) -> Option<Vec<String>> {
166 let _guard = super::check::ClassifyGuard::enter(input.len())?;
167 let script = parse(input)?;
168 let [stmt] = &script.0[..] else { return None };
169 let [cmd] = &stmt.pipeline.commands[..] else { return None };
170 if matches!(cmd, Cmd::Simple(_)) {
173 return None;
174 }
175 first_denied_simple(cmd)
176}
177
178fn first_denied_simple(cmd: &Cmd) -> Option<Vec<String>> {
180 match cmd {
181 Cmd::Simple(s) => Some(s.words.iter().map(Word::eval).collect()),
182 Cmd::FunctionDef { .. } | Cmd::DoubleBracket { .. } => None,
183 Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } | Cmd::For { body, .. } => first_denied_simple_in(body),
184 Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => {
185 first_denied_simple_in(cond).or_else(|| first_denied_simple_in(body))
186 }
187 Cmd::If { branches, else_body, .. } => branches
188 .iter()
189 .find_map(|b| first_denied_simple_in(&b.cond).or_else(|| first_denied_simple_in(&b.body)))
190 .or_else(|| else_body.as_ref().and_then(first_denied_simple_in)),
191 Cmd::Case { arms, .. } => arms.iter().find_map(|arm| first_denied_simple_in(&arm.body)),
192 }
193}
194
195fn first_denied_simple_in(script: &Script) -> Option<Vec<String>> {
196 first_denied_in(script, first_denied_simple)
197}
198
199fn first_denied_in<T>(script: &Script, describe: fn(&Cmd) -> Option<T>) -> Option<T> {
202 super::check::walk_with_scope(script, |stmt| stmt.pipeline.commands.iter().find(|c| !cmd_verdict(c).is_allowed()).and_then(describe))
203 .into_iter()
204 .flatten()
205 .next()
206}
207
208fn denied_label_in(script: &Script) -> Option<String> {
215 first_denied_in(script, command_label)
216}
217
218fn simple_cmd_name(s: &SimpleCmd) -> Option<String> {
219 s.words
220 .first()
221 .map(|w| Token::from_raw(w.eval()).command_name().to_string())
222 .filter(|name| !name.is_empty())
223}
224
225fn establishes_shell_state(stmt: &Stmt) -> bool {
229 stmt.pipeline.commands.iter().any(|cmd| match cmd {
230 Cmd::Simple(s) => {
231 if s.words.is_empty() && !s.env.is_empty() {
232 return true;
233 }
234 matches!(simple_cmd_name(s).as_deref(), Some("cd" | "pushd" | "popd" | "export" | "source" | "." | "set" | "alias" | "umask"))
235 }
236 _ => false,
237 })
238}
239
240impl Explanation {
241 pub fn is_allowed(&self) -> bool {
242 self.overall.is_allowed()
243 }
244
245 fn counts(&self) -> (usize, usize) {
246 let total = self.segments.len();
247 let denied = self.segments.iter().filter(|s| !s.verdict.is_allowed()).count();
248 (total, denied)
249 }
250
251 pub fn should_surface(&self) -> bool {
257 if !self.parsed || self.segments.len() < 2 {
258 return false;
259 }
260 let (total, denied) = self.counts();
261 denied > 0 && denied < total
262 }
263
264 pub fn render(&self) -> String {
267 let mut out = self.render_for_person();
268 if self.parsed
269 && let (total, denied) = self.counts()
270 && let Some(tip) = self.guidance(total, denied)
271 {
272 out.push_str(tip);
273 out.push('\n');
274 }
275 out
276 }
277
278 pub fn render_for_person(&self) -> String {
281 if !self.parsed {
282 return "safe-chains: could not parse this command, so it will not be auto-approved.\n".to_string();
283 }
284 if self.segments.is_empty() {
285 return "safe-chains: no command to check.\n".to_string();
286 }
287
288 let (total, denied) = self.counts();
289 let mut out = String::new();
290 out.push_str(&header(total, denied));
291 for s in &self.segments {
292 out.push_str(&render_line(s));
293 }
294 out
295 }
296
297 pub fn render_context(&self) -> String {
298 if !(self.parsed && self.stateful) {
299 return self.render();
300 }
301 let mut out = String::from("safe-chains did not auto-approve:\n");
302 for s in self.segments.iter().filter(|s| !s.verdict.is_allowed()) {
303 out.push_str(&render_line(s));
304 }
305 out.push_str("The command has likely already run. This is feedback, not a request to re-run it.\n");
306 out
307 }
308
309 fn guidance(&self, total: usize, denied: usize) -> Option<&'static str> {
310 if denied == 0 {
311 return None;
312 }
313 if total == 1 {
318 return None;
319 }
320 if denied == total {
321 return Some("This is not a block. These all need manual approval. None of them auto-approve on their own.");
322 }
323 if self.stateful {
324 return Some(
325 "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.",
326 );
327 }
328 Some(
329 "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.",
330 )
331 }
332}
333
334fn header(total: usize, denied: usize) -> String {
335 if denied == 0 {
336 if total == 1 {
337 return "safe-chains: auto-approves.\n".to_string();
338 }
339 return format!("safe-chains: all {total} segments auto-approve.\n");
340 }
341 if total == 1 {
346 return format!("safe-chains: {}\n", crate::refusal::EXPLAIN_SINGLE);
347 }
348 format!("safe-chains: did not auto-approve {denied} of {total} segments. {}\n", crate::refusal::EXPLAIN_MANY)
349}
350
351fn render_line(s: &SegmentReport) -> String {
355 let mark = if s.verdict.is_allowed() { '✓' } else { '✗' };
356 let text = crate::sanitize_display(&s.text);
357 match &s.culprit {
358 Some(culprit) if !s.verdict.is_allowed() => {
359 format!(" {mark} {text} ({})\n", crate::sanitize_display(culprit))
360 }
361 _ => format!(" {mark} {text}\n"),
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 fn marks(input: &str) -> Vec<bool> {
370 explain(input).segments.iter().map(|s| s.verdict.is_allowed()).collect()
371 }
372
373 #[test]
374 fn single_safe_command_one_allowed_segment() {
375 let e = explain("ls -la");
376 assert!(e.is_allowed());
377 assert_eq!(e.segments.len(), 1);
378 assert!(e.segments[0].verdict.is_allowed());
379 assert_eq!(e.segments[0].culprit, None);
380 }
381
382 #[test]
383 fn single_unsafe_command_is_denied_without_redundant_culprit() {
384 let e = explain("rm -rf /");
385 assert!(!e.is_allowed());
386 assert_eq!(e.segments.len(), 1);
387 assert_eq!(e.segments[0].culprit, None);
388 }
389
390 #[test]
391 fn one_torpedo_marks_only_that_segment() {
392 let e = explain("git status && rm -rf / && echo done");
393 assert!(!e.is_allowed());
394 assert_eq!(marks("git status && rm -rf / && echo done"), vec![true, false, true]);
395 assert!(e.segments.iter().all(|s| s.culprit.is_none()));
396 }
397
398 #[test]
399 fn all_safe_chain_is_allowed() {
400 let e = explain("git status && ls && echo hi");
401 assert!(e.is_allowed());
402 assert_eq!(marks("git status && ls && echo hi"), vec![true, true, true]);
403 }
404
405 #[test]
406 fn semicolons_and_or_split_into_segments() {
407 assert_eq!(explain("ls; pwd; whoami").segments.len(), 3);
408 assert_eq!(explain("ls || rm -rf /").segments.len(), 2);
409 }
410
411 #[test]
423 fn a_denied_compound_names_the_command_inside_it() {
424 for src in [
425 "(cat ~/.ssh/id_rsa)", "{ cat ~/.ssh/id_rsa; }", "if true; then cat ~/.ssh/id_rsa; fi",
426 "for f in a b; do cat ~/.ssh/id_rsa; done", "while true; do cat ~/.ssh/id_rsa; done",
427 "case $x in a) cat ~/.ssh/id_rsa ;; esac",
428 ] {
429 let ex = explain(src);
430 assert_eq!(ex.segments.len(), 1, "{src}: one segment");
431 assert!(!ex.is_allowed(), "{src}: denied");
432 assert_eq!(ex.segments[0].culprit.as_deref(), Some("cat"), "{src}: must name the command inside the construct");
433 }
434
435 assert_eq!(denied_inner_words("(cat ~/.ssh/id_rsa)"), Some(vec!["cat".to_string(), "~/.ssh/id_rsa".to_string()]),);
437 assert_eq!(denied_inner_words("cat ~/.ssh/id_rsa"), None);
439 assert_eq!(denied_inner_words("(ls)"), None);
441 }
442
443 #[test]
444 fn culprit_is_first_denied_in_a_pipeline() {
445 let e = explain("grep foo file | rm -rf /");
446 assert!(!e.is_allowed());
447 assert_eq!(e.segments.len(), 1);
448 assert_eq!(e.segments[0].culprit.as_deref(), Some("rm"));
449 }
450
451 #[test]
452 fn segment_text_round_trips() {
453 let e = explain("git status && echo done");
454 assert_eq!(e.segments[0].text, "git status");
455 assert_eq!(e.segments[1].text, "echo done");
456 }
457
458 #[test]
459 fn unparseable_input_is_a_single_unparsed_segment() {
460 let e = explain("echo 'unterminated");
461 assert!(!e.parsed);
462 assert!(!e.is_allowed());
463 }
464
465 #[test]
468 fn cd_chain_is_marked_stateful() {
469 assert!(explain("cd build && rm -rf x").stateful);
470 assert!(explain("export FOO=bar && rm -rf x").stateful);
471 assert!(explain("FOO=bar && rm -rf x").stateful);
472 assert!(explain("source ./env && rm -rf x").stateful);
473 }
474
475 #[test]
476 fn independent_chain_is_not_stateful() {
477 assert!(!explain("git status && rm -rf x && echo done").stateful);
478 assert!(!explain("ls && pwd").stateful);
479 }
480
481 #[test]
482 fn single_segment_is_never_stateful() {
483 assert!(!explain("cd build").stateful);
484 }
485
486 #[test]
489 fn surfaces_only_the_mixed_bundling_case() {
490 assert!(explain("git status && rm -rf / && echo done").should_surface());
491 assert!(!explain("ls && pwd").should_surface(), "all-safe: nothing to teach");
492 assert!(!explain("rm -rf / && rm -rf /etc").should_surface(), "all-denied: no rescue");
493 assert!(!explain("rm -rf /").should_surface(), "single denied: no chaining lesson");
494 assert!(!explain("echo 'unterminated").should_surface(), "unparseable");
495 }
496
497 #[test]
500 fn stateful_chain_context_names_only_the_refused_segments() {
501 assert_eq!(
502 explain("cd build && cargo publish").render_context(),
503 "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"
504 );
505 }
506
507 proptest::proptest! {
508 #[test]
509 fn hook_context_has_one_line_per_listed_segment(
510 cmd in proptest::sample::select(crate::handler_property_tests::FORGERY_PAYLOADS.to_vec()),
511 ) {
512 let e = explain(&format!("cd x && {cmd}"));
513 let context = e.render_context();
514 let short = e.parsed && e.stateful;
515 let expected = if short { e.segments.iter().filter(|s| !s.verdict.is_allowed()).count() } else { e.segments.len() };
516 let lines = context.lines().filter(|l| l.starts_with(" \u{2713} ") || l.starts_with(" \u{2717} ")).count();
517 proptest::prop_assert_eq!(lines, expected, "{}", context);
518 proptest::prop_assert!(!short || !context.contains('\u{2713}'), "{}", context);
519 }
520 }
521
522 #[test]
523 fn stateless_chain_context_keeps_the_full_breakdown() {
524 let e = explain("git status && rm -rf / && echo done");
525 assert_eq!(e.render_context(), e.render());
526 }
527
528 #[test]
531 fn coverage_overlay_flips_a_user_allowed_segment() {
532 let patterns = Matcher::from_allow_patterns(&["rm *"]);
533 let e = explain_with_coverage("git status && rm -rf / && echo done", &patterns);
534 assert!(e.is_allowed(), "user allowlisted rm, so the chain auto-approves");
535 assert!(e.segments.iter().all(|s| s.verdict.is_allowed()));
536 assert!(!e.should_surface());
537 }
538
539 #[test]
540 fn coverage_overlay_leaves_uncovered_segments_denied() {
541 let patterns = Matcher::from_allow_patterns(&["rm *"]);
542 let e = explain_with_coverage("rm -rf / && cargo publish", &patterns);
543 assert!(!e.is_allowed());
544 assert_eq!(marks_cov("rm -rf / && cargo publish", &patterns), vec![true, false]);
545 }
546
547 fn marks_cov(input: &str, patterns: &Matcher) -> Vec<bool> {
548 explain_with_coverage(input, patterns).segments.iter().map(|s| s.verdict.is_allowed()).collect()
549 }
550
551 #[test]
554 fn render_mixed_chain_lists_marks_and_split_tip() {
555 let out = explain("git status && rm -rf / && echo done").render();
556 assert!(out.contains("✓ git status"));
557 assert!(out.contains("✗ rm -rf /"));
558 assert!(out.contains("✓ echo done"));
559 assert!(out.contains("1 of 3 segments"));
560 assert!(out.contains("not a block"), "must clarify it is not a block: {out}");
561 assert!(out.contains("not a request to re-run"), "must not invite a re-run: {out}");
562 assert!(out.contains("separate tool calls"));
563 }
564
565 #[test]
566 fn render_stateful_chain_says_belongs_in_one_call() {
567 let out = explain("cd build && rm -rf / && echo done").render();
568 assert!(out.contains("belong in one call"), "stateful chain must not advise splitting: {out}");
569 assert!(out.contains("not a request to re-run"));
570 assert!(!out.contains("separate tool calls"));
571 }
572
573 #[test]
574 fn render_pipeline_culprit_disambiguates_failing_stage() {
575 let out = explain("grep foo file | rm -rf /").render();
576 assert!(out.contains("(rm)"), "pipeline should name the failing stage: {out}");
577 }
578
579 #[test]
580 fn render_all_safe_has_no_tip() {
581 let out = explain("ls && pwd").render();
582 assert!(out.contains("all 2 segments auto-approve"));
583 assert!(!out.contains('✗'));
584 assert!(!out.contains("approval"));
585 }
586
587 #[test]
588 fn render_single_denied_keeps_it_alone() {
589 let out = explain("cargo publish").render();
590 assert!(out.contains("did not auto-approve"), "says what happened: {out}");
595 assert!(out.contains("has researched"), "says why, without rating the command: {out}");
596 assert!(!out.contains("on its own"), "{out}");
598 }
599
600 #[test]
601 fn render_unparseable_is_explicit() {
602 let out = explain("echo 'unterminated").render();
603 assert!(out.contains("could not parse"));
604 }
605
606 #[test]
607 fn empty_input_renders_no_command() {
608 for input in ["", " "] {
609 let e = explain(input);
610 assert!(e.segments.is_empty(), "{input:?} should have no segments");
611 assert!(e.render().contains("no command to check"));
612 }
613 }
614}