Skip to main content

safe_chains/cst/
explain.rs

1use super::check::{cmd_verdict, pipeline_verdict};
2use super::*;
3use crate::allowlist::Matcher;
4use crate::parse::Token;
5use crate::verdict::{SafetyLevel, Verdict};
6
7/// A per-segment breakdown of why a command would or would not auto-approve.
8///
9/// "Segment" means a top-level list element — the pieces a user separates with
10/// `&&`, `||`, `;`, or `&`. This is the granularity that matters for the common
11/// failure mode: one un-allowlisted command torpedoing an otherwise-safe chain.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Explanation {
14    pub overall: Verdict,
15    pub segments: Vec<SegmentReport>,
16    /// False when the input could not be parsed at all.
17    pub parsed: bool,
18    /// True when segments share shell state (a `cd`, `export`, assignment, or
19    /// `source`) so that splitting them into separate calls would break them.
20    pub stateful: bool,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SegmentReport {
25    /// The segment rendered back to source (whitespace/operators normalized).
26    pub text: String,
27    pub verdict: Verdict,
28    /// For a denied *pipeline* segment (`a | b | c`), the name of the first
29    /// stage that is not auto-approved — disambiguating which stage to drop.
30    /// `None` for a single-command segment (its text already names it) or when
31    /// the culprit isn't a plain command (e.g. a subshell or redirect target).
32    pub culprit: Option<String>,
33}
34
35/// Explain against the built-in classification only.
36pub fn explain(input: &str) -> Explanation {
37    let _rules = crate::allowlist::suspended();
38    explain_inner(input)
39}
40
41/// Explain with the user's allowlist patterns overlaid, so a command the user
42/// has allowed isn't reported as not-auto-approved. This mirrors the hook's own
43/// coverage check (`main.rs`): each simple command the shell runs, at any depth, counts as allowed
44/// when it is built-in safe *or* a user rule covers it (`allowlist::with_rules`).
45pub 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    // ONE work budget for the whole explanation, taken the same way `command_verdict` takes it.
52    //
53    // Without this, explaining had no budget of its own: brace-expansion fan-out charged the shared
54    // counter while the per-segment classifications inside reset it whenever one bottomed out at
55    // depth 0. The result depended on how much the CALLER had already spent and on where the resets
56    // fell, so `explain` was neither order-independent (it disagreed with the verdict enforced just
57    // before it) nor deterministic (two consecutive calls on one dense input rendered different
58    // answers). Entering here resets once, at the top, and keeps every nested classification at
59    // depth >= 1, which is what makes explaining and enforcing spend from the same pool.
60    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    // Walk with the SAME accumulated scope as `script_verdict` (cwd + `VAR=` bindings + function
78    // definitions), so each segment is judged in the context of the ones before it. Without this the
79    // per-segment view — and the hook's coverage fallback built on it — would re-allow a call whose
80    // definition shadows a builtin (`ls(){ rm; }; ls`) that the whole-command verdict denies.
81    let segments: Vec<SegmentReport> = super::check::walk_with_scope(&script, segment_report);
82    // The scope walk exceeded its uncertain-binding budget (too much shell state to track), or a
83    // name it read as a number took something else later in the line, so the command is refused —
84    // the same fail-closed call `command_verdict` makes, so the explanation can never describe a
85    // more permissive verdict than the one enforced (the `explain_render` target's first property). One denied segment for the whole input, as for an unparseable one:
86    // per-segment marks would claim a granularity the walk no longer earned. NOT liftable by the
87    // coverage overlay above — a user rule cannot cover a refusal that exists because what the
88    // command does to later segments cannot be bounded.
89    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    // A culprit is suppressed when it would only repeat the segment's own name: for a lone SIMPLE
106    // command the segment text already IS `cat ~/.ssh/id_rsa`, so labelling it `cat` says nothing.
107    //
108    // That used to be spelled `commands.len() <= 1`, which caught compounds as well — and there the
109    // label is the only actionable information there is. The segment text of a denied `for` loop is
110    // the whole loop; what the caller has to change is the command inside it, and suppressing that
111    // is how a third of the author's decision-log denials came to read "no reason recorded".
112    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
121/// The name to report as the culprit for a denied command.
122///
123/// A compound is not itself a command anyone can act on: the thing the caller has to change lives
124/// INSIDE it. So this descends into the body and names the first inner command that is denied on
125/// its own — `(cat ~/.ssh/id_rsa)` reports `cat`, not nothing.
126///
127/// It used to return `None` for everything but `Simple`, which is why a denied `for`/`while`/`case`
128/// left `culprit: null` and `facets: null` in the decision log — roughly a third of the denials in
129/// the author's own log read "no reason recorded". `--explain` had the same hole, and it is the
130/// worse place for it: the hook renders that text back to the agent, so a refusal with no reason is
131/// one the agent cannot act on except by guessing.
132///
133/// Every body is descended, not just the one that will run. Which `if` branch or `case` arm
134/// executes is a runtime value, so the classifier already treats such a command as only as safe as
135/// its worst body; reporting has to look in the same places or it would name nothing for exactly
136/// the constructs that were denied because of what is buried in them.
137fn command_label(cmd: &Cmd) -> Option<String> {
138    match cmd {
139        Cmd::Simple(s) => simple_cmd_name(s),
140        // A function DEFINITION is inert — its body only matters when called, and naming the body's
141        // commands here would report a culprit for a command that did nothing.
142        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        // `[[ … ]]` is a test expression, not a command that could be the culprit.
152        Cmd::DoubleBracket { .. } => None,
153    }
154}
155
156/// The WORDS of the first denied command inside a compound, for the facet breakdown.
157///
158/// `--explain`'s profile section tokenises the raw string flatly, which cannot see into a compound:
159/// `(cat ~/.ssh/id_rsa)` splits to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises `(cat`, and
160/// the refusal renders with no reason at all. Roughly a third of the denials in the author's
161/// decision log read "no reason recorded" for this shape.
162///
163/// Returns `None` for a plain simple command, so the caller keeps its existing path and this is
164/// only consulted where that path has nothing to say.
165pub(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    // A simple command is already handled by the flat path, and going through the CST for it would
171    // change what that path reports on inputs it handles correctly today.
172    if matches!(cmd, Cmd::Simple(_)) {
173        return None;
174    }
175    first_denied_simple(cmd)
176}
177
178/// The first simple command at or below `cmd` that is denied on its own.
179fn 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
199/// `describe` applied to the first command in `script` denied in the scope the statements before
200/// it leave, so a call to a function defined earlier in the body is judged as the function.
201fn 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
208/// The first command inside `script` that is denied on its own, by name.
209///
210/// Recurses through `command_label`, so a culprit nested several constructs deep is still found.
211/// Termination rests on the CST being finite and acyclic — a body is always a strictly smaller
212/// subtree than the command containing it — which is the same property the classifier's own walk
213/// relies on.
214fn 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
225/// Whether a segment establishes shell state that later segments would rely on:
226/// a directory change, an environment change, or a sourced script. Splitting
227/// such a chain into separate calls would silently lose that state.
228fn 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    /// Whether this explanation is worth injecting into an agent's context
252    /// automatically. The teachable case is a *mix*: an otherwise-auto-approving
253    /// chain dragged into a manual prompt by one un-allowlisted segment. A single
254    /// denied command, or an all-denied chain, carries no chaining lesson — so we
255    /// stay quiet and let the normal approval flow handle it.
256    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    /// The breakdown an agent reads after the hook let a chain through: which segments
265    /// auto-approve, which don't, and the chaining lesson for next time.
266    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    /// The same breakdown for a person who ran `--explain`, without the lesson addressed to an
279    /// agent whose command has already run.
280    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        // The auto-injected case is always the mixed chain (see should_surface).
314        // By the time an agent reads this, the command has gone through the
315        // normal approval flow and most likely already run — so the guidance is
316        // feedback for next time, never an instruction to re-run.
317        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    // The THIRD producer of refusal copy, and the one that kept "not on the allowlist" alive after
342    // it was removed from the others. It routes through the same builder now, with
343    // `Outcome::Unknown`: `--explain` is run against no harness, so what follows is not ours to
344    // claim. See docs/design/refusal-copy.md.
345    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
351/// One `✓`/`✗` line. The echoed text is command-derived, so it is neutralized first: a raw newline
352/// in it let a command forge an entire extra line carrying our own `✓` marker (see
353/// [`crate::sanitize_display`]).
354fn 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    /// A denied COMPOUND names the command inside it, rather than nothing.
412    ///
413    /// `command_label` returned `None` for every non-simple command, so a denied `for`/`while`/
414    /// `case`/subshell left `culprit: null` in the decision log and no reason in `--explain`.
415    /// Roughly a third of the denials in the author's own log read "no reason recorded".
416    ///
417    /// The construct itself is never the actionable answer — the caller cannot change "a subshell",
418    /// only the command in it — so every body is descended, including the branches and arms that
419    /// may not run. The classifier already treats such a command as only as safe as its worst body;
420    /// reporting looks in the same places, or it names nothing for precisely the constructs whose
421    /// denial came from something buried in them.
422    #[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        // And the words reach the facet breakdown, which is what puts a REASON on the refusal.
436        assert_eq!(denied_inner_words("(cat ~/.ssh/id_rsa)"), Some(vec!["cat".to_string(), "~/.ssh/id_rsa".to_string()]),);
437        // A plain simple command keeps the existing path — this is only for what it cannot see.
438        assert_eq!(denied_inner_words("cat ~/.ssh/id_rsa"), None);
439        // A construct whose body is fine has no culprit to name.
440        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    // ---- stateful detection ----
466
467    #[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    // ---- should_surface (auto-injection gate) ----
487
488    #[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    // ---- render_context (what the hook injects) ----
498
499    #[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    // ---- coverage overlay ----
529
530    #[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    // ---- rendering ----
552
553    #[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        // The header moved to the shared builder (`refusal::EXPLAIN_SINGLE`), so this asserts the
591        // FACTS it has to carry rather than the exact sentence — the spec's own note that target
592        // tests pinning literal copy "keep passing while the real copy changes, which is worse than
593        // no test". Wording is the copy guards' job (`refusal::tests`).
594        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        // No advice to send it "on its own": it already was. `--explain` ends with the fix instead.
597        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}