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, worst_segment);
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 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    // A culprit is suppressed when it would only repeat the segment's own name: for a lone SIMPLE
111    // command the segment text already IS `cat ~/.ssh/id_rsa`, so labelling it `cat` says nothing.
112    //
113    // That used to be spelled `commands.len() <= 1`, which caught compounds as well — and there the
114    // label is the only actionable information there is. The segment text of a denied `for` loop is
115    // the whole loop; what the caller has to change is the command inside it, and suppressing that
116    // is how a third of the author's decision-log denials came to read "no reason recorded".
117    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
126/// The name to report as the culprit for a denied command.
127///
128/// A compound is not itself a command anyone can act on: the thing the caller has to change lives
129/// INSIDE it. So this descends into the body and names the first inner command that is denied on
130/// its own — `(cat ~/.ssh/id_rsa)` reports `cat`, not nothing.
131///
132/// It used to return `None` for everything but `Simple`, which is why a denied `for`/`while`/`case`
133/// left `culprit: null` and `facets: null` in the decision log — roughly a third of the denials in
134/// the author's own log read "no reason recorded". `--explain` had the same hole, and it is the
135/// worse place for it: the hook renders that text back to the agent, so a refusal with no reason is
136/// one the agent cannot act on except by guessing.
137///
138/// Every body is descended, not just the one that will run. Which `if` branch or `case` arm
139/// executes is a runtime value, so the classifier already treats such a command as only as safe as
140/// its worst body; reporting has to look in the same places or it would name nothing for exactly
141/// the constructs that were denied because of what is buried in them.
142fn command_label(cmd: &Cmd) -> Option<String> {
143    match cmd {
144        Cmd::Simple(s) => simple_cmd_name(s),
145        // A function DEFINITION is inert — its body only matters when called, and naming the body's
146        // commands here would report a culprit for a command that did nothing.
147        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        // `[[ … ]]` is a test expression, not a command that could be the culprit.
157        Cmd::DoubleBracket { .. } => None,
158    }
159}
160
161/// The WORDS of the first denied command inside a compound, for the facet breakdown.
162///
163/// `--explain`'s profile section tokenises the raw string flatly, which cannot see into a compound:
164/// `(cat ~/.ssh/id_rsa)` splits to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises `(cat`, and
165/// the refusal renders with no reason at all. Roughly a third of the denials in the author's
166/// decision log read "no reason recorded" for this shape.
167///
168/// Returns `None` for a plain simple command, so the caller keeps its existing path and this is
169/// only consulted where that path has nothing to say.
170pub(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    // A simple command is already handled by the flat path, and going through the CST for it would
176    // change what that path reports on inputs it handles correctly today.
177    if matches!(cmd, Cmd::Simple(_)) {
178        return None;
179    }
180    first_denied_simple(cmd)
181}
182
183/// The first simple command at or below `cmd` that is denied on its own.
184fn 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
204/// `describe` applied to the first command in `script` denied in the scope the statements before
205/// it leave, so a call to a function defined earlier in the body is judged as the function.
206fn 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
217/// The first command inside `script` that is denied on its own, by name.
218///
219/// Recurses through `command_label`, so a culprit nested several constructs deep is still found.
220/// Termination rests on the CST being finite and acyclic — a body is always a strictly smaller
221/// subtree than the command containing it — which is the same property the classifier's own walk
222/// relies on.
223fn 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
234/// Whether a segment establishes shell state that later segments would rely on:
235/// a directory change, an environment change, or a sourced script. Splitting
236/// such a chain into separate calls would silently lose that state.
237fn 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    /// Whether this explanation is worth injecting into an agent's context
261    /// automatically. The teachable case is a *mix*: an otherwise-auto-approving
262    /// chain dragged into a manual prompt by one un-allowlisted segment. A single
263    /// denied command, or an all-denied chain, carries no chaining lesson — so we
264    /// stay quiet and let the normal approval flow handle it.
265    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    /// The breakdown an agent reads after the hook let a chain through: which segments
274    /// auto-approve, which don't, and the chaining lesson for next time.
275    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    /// The same breakdown for a person who ran `--explain`, without the lesson addressed to an
288    /// agent whose command has already run.
289    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        // The auto-injected case is always the mixed chain (see should_surface).
323        // By the time an agent reads this, the command has gone through the
324        // normal approval flow and most likely already run — so the guidance is
325        // feedback for next time, never an instruction to re-run.
326        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    // The THIRD producer of refusal copy, and the one that kept "not on the allowlist" alive after
351    // it was removed from the others. It routes through the same builder now, with
352    // `Outcome::Unknown`: `--explain` is run against no harness, so what follows is not ours to
353    // claim. See docs/design/refusal-copy.md.
354    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
360/// One `✓`/`✗` line. The echoed text is command-derived, so it is neutralized first: a raw newline
361/// in it let a command forge an entire extra line carrying our own `✓` marker (see
362/// [`crate::sanitize_display`]).
363fn 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    /// A denied COMPOUND names the command inside it, rather than nothing.
421    ///
422    /// `command_label` returned `None` for every non-simple command, so a denied `for`/`while`/
423    /// `case`/subshell left `culprit: null` in the decision log and no reason in `--explain`.
424    /// Roughly a third of the denials in the author's own log read "no reason recorded".
425    ///
426    /// The construct itself is never the actionable answer — the caller cannot change "a subshell",
427    /// only the command in it — so every body is descended, including the branches and arms that
428    /// may not run. The classifier already treats such a command as only as safe as its worst body;
429    /// reporting looks in the same places, or it names nothing for precisely the constructs whose
430    /// denial came from something buried in them.
431    #[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        // And the words reach the facet breakdown, which is what puts a REASON on the refusal.
445        assert_eq!(denied_inner_words("(cat ~/.ssh/id_rsa)"), Some(vec!["cat".to_string(), "~/.ssh/id_rsa".to_string()]),);
446        // A plain simple command keeps the existing path — this is only for what it cannot see.
447        assert_eq!(denied_inner_words("cat ~/.ssh/id_rsa"), None);
448        // A construct whose body is fine has no culprit to name.
449        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    // ---- stateful detection ----
475
476    #[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    // ---- should_surface (auto-injection gate) ----
496
497    #[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    // ---- render_context (what the hook injects) ----
507
508    #[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    // ---- coverage overlay ----
538
539    #[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    // ---- rendering ----
561
562    #[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        // The header moved to the shared builder (`refusal::EXPLAIN_SINGLE`), so this asserts the
600        // FACTS it has to carry rather than the exact sentence — the spec's own note that target
601        // tests pinning literal copy "keep passing while the real copy changes, which is worse than
602        // no test". Wording is the copy guards' job (`refusal::tests`).
603        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        // No advice to send it "on its own": it already was. `--explain` ends with the fix instead.
606        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}