termaxa 0.19.6

A cooperative gate for the shell commands AI coding agents run — command previews, automatic backups, allow/ask/deny policy, and audit logging.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
use crate::policy::{Action, Decision, DecisionSource};
use std::process::Command;

/// A signal the context engine noticed about the environment or the command.
#[derive(Debug, Clone)]
pub struct Signal {
    pub label: String,
    pub escalate: bool,
}

/// Gather cheap, local context signals. Never fails; absence of signal is fine.
///
/// The signals are read off the command the policy judged - unnamed
/// wrappers and harness scaffolding left out - not off the raw line. Claude
/// Code's preamble says `unset -f` on every Bash tool call; read raw, that
/// was a destructive flag escalating every allowed command to an ask
/// (Sep 10, 2026, under `wrap`). A flag on the agent's own command is still
/// found: it is inside the part that is kept.
/// `gather_with` reading nothing: every substitution is a signal. The
/// production paths pass the policy's `allows_explicitly`; the tests here
/// use this form where readability is not what they test.
#[cfg_attr(not(test), allow(dead_code))]
pub fn gather(command: &str) -> Vec<Signal> {
    gather_with(command, &|_| false)
}

/// `gather`, with the caller saying which substitutions it can read.
/// A `$(…)` whose inner command the policy would explicitly allow (`git
/// branch --show-current`, `cat <<'EOF' … EOF`) is not "contents not
/// analyzable": the gate just analyzed it. The signal stays for any
/// substitution that is not readable, and for an unbalanced one.
pub fn gather_with(command: &str, readable: &dyn Fn(&str) -> bool) -> Vec<Signal> {
    let mut signals = Vec::new();
    let command = crate::shell::context_text(command);
    let command = command.as_str();
    let cmd_lc = command.to_lowercase();

    // Git branch awareness: pushing/committing while on a protected branch.
    if cmd_lc.starts_with("git push") || cmd_lc.starts_with("git commit") {
        if let Some(branch) = current_git_branch() {
            let protected = matches!(
                branch.as_str(),
                "main" | "master" | "production" | "release"
            );
            signals.push(Signal {
                label: format!("current branch: {}", branch),
                escalate: protected && cmd_lc.starts_with("git push"),
            });
        }
    }

    // Force / destructive flags.
    for flag in ["--force", "-f ", "--hard", "--no-verify", "-rf"] {
        if cmd_lc.contains(flag) {
            signals.push(Signal {
                label: format!("destructive flag detected: {}", flag.trim()),
                escalate: true,
            });
        }
    }

    // Production markers in the command itself (connection strings, env names).
    for marker in ["prod", "production"] {
        if cmd_lc.contains(marker) && !cmd_lc.starts_with("git") {
            signals.push(Signal {
                label: format!("possible production target: contains `{}`", marker),
                escalate: true,
            });
            break;
        }
    }

    // SQL red flags.
    for stmt in ["drop table", "drop database", "truncate ", "delete from"] {
        if cmd_lc.contains(stmt) {
            signals.push(Signal {
                label: format!("destructive SQL: `{}`", stmt.trim()),
                escalate: true,
            });
        }
    }

    // Options that turn a reading command into a writing or running one.
    // The starter allows `sed -n *`, `find *`, `git diff*`, `git log*`,
    // `git show*` and `git branch*` for the reading forms; the option beside
    // them writes a file, overwrites a branch or runs a command (reported by
    // Tim Schipper, Sep 27, 2026, and extended the same day). Read off each
    // segment's own words, through wrappers, `-c` strings and git's global
    // options, so the allow the rule gives the reading form is not the
    // allow the writing form gets.
    for label in option_effects(command) {
        signals.push(Signal {
            label,
            escalate: true,
        });
    }

    // Command substitution: contents the gate cannot read are a reason to
    // put a human in the loop. Contents it can read and would allow are
    // not; a quoted heredoc is data and needs no reading at all.
    if crate::shell::has_substitution(command) {
        let unreadable = crate::shell::substitutions(command)
            .into_iter()
            .any(|inner| !(crate::shell::is_literal_heredoc(&inner) || readable(&inner)));
        if unreadable {
            signals.push(Signal {
                label: "command substitution ($(...) or ``) — contents not analyzable".into(),
                escalate: true,
            });
        }
    }

    signals
}

/// What a command does through its options besides reading: the labels of
/// every write or run found, one per kind, in a stable order.
pub fn option_effects(command: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for seg in crate::shell::split_segments_deep(command) {
        let raw = crate::pg::shell_tokens(seg.command());
        let toks = crate::delete::without_any_wrappers(&raw).unwrap_or(raw);
        let Some(first) = toks.first() else {
            continue;
        };
        match crate::delete::command_head(first).as_str() {
            "sed" | "gsed" => {
                let inv = crate::sed::parse_args(&toks[1..]);
                if inv.in_place {
                    out.push("sed edits its input files in place: -i".into());
                }
                // `--sandbox` makes sed itself refuse `w`, `e` and `r`.
                if !inv.sandbox {
                    if inv.script_file {
                        out.push("sed runs a script file the gate does not read: -f".into());
                    }
                    for script in &inv.scripts {
                        let fx = crate::sed::effects(script);
                        for w in &fx.writes {
                            out.push(format!("sed writes a file: {w}"));
                        }
                        if fx.executes {
                            out.push("sed runs a shell command: e".into());
                        }
                        if fx.not_understood {
                            out.push("sed script not understood".into());
                        }
                    }
                }
            }
            // Inline code is typed on the command line and read by no one:
            // the dev loop's `node *` allows a file the project runs, not a
            // program the agent writes into `-e`.
            "node" | "nodejs" => {
                let inline = toks[1..].iter().any(|t| {
                    matches!(t.as_str(), "-e" | "-p" | "--eval" | "--print")
                        || t.starts_with("--eval=")
                        || t.starts_with("--print=")
                        || (t.len() > 2
                            && t.starts_with('-')
                            && !t.starts_with("--")
                            && t[1..].chars().all(|c| c == 'e' || c == 'p'))
                });
                if inline {
                    out.push("node runs inline code the gate does not read: -e/-p".into());
                }
            }
            "find" | "gfind" => {
                for t in &toks[1..] {
                    if matches!(t.as_str(), "-fprint" | "-fprint0" | "-fprintf" | "-fls") {
                        out.push(format!("find writes a file: {t}"));
                    }
                }
            }
            "git" => {
                let g = crate::delete::git_without_global_options(&toks)
                    .unwrap_or_else(|| toks.clone());
                let sub = g.get(1).map(String::as_str).unwrap_or("");
                let args = if g.len() > 2 { &g[2..] } else { &[][..] };
                let long_output = args.iter().any(|a| {
                    a == "--output"
                        || a.starts_with("--output=")
                        || a == "--output-directory"
                        || a.starts_with("--output-directory=")
                });
                let short_output = matches!(sub, "format-patch" | "archive")
                    && args
                        .iter()
                        .any(|a| a.starts_with("-o") && !a.starts_with("--"));
                if long_output || short_output {
                    out.push(format!("git {sub} writes a file: --output"));
                }
                // `-M`/`-C` rename or copy over an existing branch; `-f`
                // resets one. The long `--force` is already a flag signal.
                if sub == "branch"
                    && args.iter().any(|a| {
                        a.starts_with('-')
                            && !a.starts_with("--")
                            && a[1..].chars().any(|c| matches!(c, 'M' | 'C' | 'f'))
                    })
                {
                    out.push("git branch overwrites an existing branch: -M/-C/-f".into());
                }
            }
            _ => {}
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Escalation ladder: allow -> ask. `ask` and `deny` are never escalated further
/// (a human is already in the loop, or it's already blocked), and context never
/// downgrades a decision.
/// Uninsurability AMPLIFIES an existing concern; it never creates one.
///
/// Roadmap 2.5. The preview has known since v0.13 whether a command destroys
/// something the backup engine cannot copy aside first, and nothing could act
/// on it - the strongest unused signal in the product.
///
/// The rule is `uninsurable + Ask -> Deny`, NOT `uninsurable -> Deny`, and the
/// difference is the whole design. Measured on a realistic tree before writing
/// this: `rm -rf node_modules` (9,330 files) exceeds the 5,000-file copy
/// budget and reads as uninsurable. It is also the most routine destructive
/// command in JavaScript work, and it destroys nothing that `npm install`
/// cannot rebuild. A gate that denies it out of the box gets uninstalled, and
/// the user who uninstalls it loses protection against the commands that
/// actually matter (#48).
///
/// So uninsurability is a risk AMPLIFIER, not a risk signal. Something else -
/// a policy rule, a context signal, the default - has to have already said
/// "this is worth stopping for". Then uninsurability decides whether asking is
/// safe, because an ask a human approves on a command with no net is a
/// decision made without the fact that matters most.
///
/// This also means no regenerable-directory heuristic is needed. The existing
/// signals establish concern; `rm -rf ~/Documents` is already Ask because it
/// resolves to a user profile, and becomes Deny here. `rm -rf node_modules`
/// has no other concern and keeps whatever verdict it had.
pub fn apply_insurance(decision: Decision, uninsurable: bool) -> (Decision, bool) {
    // The amplifier may STRENGTHEN an existing safety concern; it does not
    // create one from an otherwise-unmatched command.
    //
    // `DecisionSource::Default` is the absence of an opinion, not a weak
    // opinion, and the two are semantically different rather than different
    // strengths of the same thing. Without this clause, a `default: ask`
    // policy - which the starter policy is - turned every unmatched
    // uninsurable command into a deny, including `rm -r node_modules`. That
    // is `uninsurable -> deny` under another name, and it is the posture this
    // design exists to avoid (#48).
    let concerned = decision.source != DecisionSource::Default;
    if uninsurable && concerned && decision.action == Action::Ask {
        return (
            Decision {
                action: Action::Deny,
                source: decision.source,
                matched_rule: decision.matched_rule,
                reason: format!(
                    "{} — and nothing can be recovered afterwards, so this is \
                     refused rather than asked",
                    decision.reason
                ),
            },
            true,
        );
    }
    (decision, false)
}

pub fn apply(decision: Decision, signals: &[Signal]) -> (Decision, bool) {
    let should_escalate = signals.iter().any(|s| s.escalate);
    if should_escalate && decision.action == Action::Allow {
        let labels: Vec<&str> = signals
            .iter()
            .filter(|s| s.escalate)
            .map(|s| s.label.as_str())
            .collect();
        return (
            Decision {
                action: Action::Ask,
                // A context signal CHOSE this ask; it is not the absence of
                // an opinion. That distinction is what lets the insurance
                // amplifier fire here but not on an unmatched command.
                source: DecisionSource::Context,
                matched_rule: decision.matched_rule,
                reason: format!(
                    "{} — escalated to ask by context: {}",
                    decision.reason,
                    labels.join("; ")
                ),
            },
            true,
        );
    }
    (decision, false)
}

fn current_git_branch() -> Option<String> {
    let out = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if branch.is_empty() {
        None
    } else {
        Some(branch)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dec(action: Action, source: DecisionSource) -> Decision {
        Decision {
            action,
            source,
            matched_rule: None,
            reason: "because".into(),
        }
    }

    /// Claude Code's preamble carries `unset -f`; read raw it was a
    /// destructive flag on every command the agent ran, and every allow
    /// became an ask (Sep 10, 2026). The signals come off the command the
    /// policy judged: no flag for `ls`, and the agent's own `-rf` is still
    /// found inside the eval.
    /// Tim Schipper's report (Sep 27, 2026), reproduced on 0.19.5 and
    /// extended the same day: each of these was allowed by a starter rule
    /// written for the reading form of the command. Now the option that
    /// writes or runs is a signal, the allow becomes an ask, and the reason
    /// names the option. The reading forms beside them still pass.
    #[test]
    fn an_option_that_writes_or_runs_turns_a_reading_allow_into_an_ask() {
        let policy = crate::policy::Policy::builtin().expect("the starter parses");
        let ctx = crate::resolve::EvalContext::at(std::path::Path::new("."));
        let verdict = |c: &str| {
            let d = policy.evaluate_command(c, &ctx);
            let signals = gather_with(c, &|_| false);
            apply(d, &signals).0.action
        };
        for (c, label) in [
            ("git branch -M old existing", "git branch overwrites"),
            ("git branch -C old existing", "git branch overwrites"),
            (
                "find . -type f -fprint /tmp/important.txt",
                "find writes a file: -fprint",
            ),
            (
                "find . -type f -fprintf /tmp/important.txt \"%p\\n\"",
                "find writes a file: -fprintf",
            ),
            ("find . -fls /tmp/important.txt", "find writes a file: -fls"),
            (
                "git diff --output=/tmp/important.txt",
                "git diff writes a file",
            ),
            (
                "git log --output=/tmp/important.txt",
                "git log writes a file",
            ),
            (
                "git show --output=/tmp/important.txt HEAD",
                "git show writes a file",
            ),
            (
                "git -C . diff --output=/tmp/important.txt",
                "git diff writes a file",
            ),
            (
                "sed -n -i 's/foo/bar/' /tmp/important.txt",
                "sed edits its input files in place",
            ),
            (
                "sed -n 'w /tmp/important.txt' README.md",
                "sed writes a file: /tmp/important.txt",
            ),
            (
                "sed -n 's/x/y/w /tmp/important.txt' README.md",
                "sed writes a file: /tmp/important.txt",
            ),
            (
                "sed -n '1e touch /tmp/pwned' README.md",
                "sed runs a shell command",
            ),
            (
                "sh -c \"sed -n '1e touch /tmp/pwned' README.md\"",
                "sed runs a shell command",
            ),
            (
                "env LC_ALL=C sed -n '1e touch /tmp/pwned' README.md",
                "sed runs a shell command",
            ),
        ] {
            assert_eq!(verdict(c), Action::Ask, "{c}");
            let effects = option_effects(c);
            assert!(
                effects.iter().any(|e| e.starts_with(label)),
                "{c}: {effects:?}"
            );
        }
        for c in [
            "sed -n '1,5p' README.md",
            "sed -n '/error/p' app.log",
            "sed -n 's/foo/bar/gp' README.md",
            "find . -name '*.rs' -print",
            "git diff --stat",
            "git log --oneline -5",
            "git branch -a",
            "git branch --show-current",
        ] {
            assert!(option_effects(c).is_empty(), "{c}: {:?}", option_effects(c));
            assert_eq!(verdict(c), Action::Allow, "{c}");
        }
        // Inline node code asks: it is typed on the command line and read by
        // no one. A file the project runs stays in the dev loop, as the
        // starter's dev-loop test holds.
        for c in [
            "node -e 'require(\"fs\").writeFileSync(\"/tmp/important.txt\", \"x\")'",
            "node -e \"require('fs').rmSync('/tmp/important.txt')\"",
            "node -p 'process.exit()'",
            "node --input-type=module -e 'x'",
            "node --eval 'x'",
        ] {
            assert_eq!(verdict(c), Action::Ask, "{c}");
        }
        for c in ["node scripts/check.js", "node --version", "node --test"] {
            assert_eq!(verdict(c), Action::Allow, "{c}");
        }
    }

    #[test]
    fn a_harness_preamble_is_not_a_destructive_flag_on_the_agents_command() {
        let form = |cmd: &str| {
            format!(
                r#"bash -c -l "shopt -u extglob 2>/dev/null || true && {{ \\builtin unalias -- 'unsetenv'; \\builtin unset -f -- 'unsetenv'; }} >/dev/null 2>&1 || true && eval '{cmd}' < /dev/null && pwd -P >| /tmp/claude-c32c-cwd""#
            )
        };
        let quiet = gather(&form("ls -la /home/dev/proj/"));
        assert!(
            quiet
                .iter()
                .all(|s| !s.label.starts_with("destructive flag")),
            "{quiet:?}"
        );
        let loud = gather(&form("rm -rf ./scratch"));
        assert!(
            loud.iter()
                .any(|s| s.label == "destructive flag detected: -rf" && s.escalate),
            "{loud:?}"
        );
        // A plain command reads as it always did.
        let plain = gather("git push --force origin main");
        assert!(
            plain.iter().any(|s| s.label.contains("--force")),
            "{plain:?}"
        );
    }

    /// THE PRECEDENCE, pinned in every direction so it cannot be misread.
    ///
    /// The amplifier may STRENGTHEN an existing safety concern; it does not
    /// create one from an otherwise-unmatched command.
    ///
    /// Measured before this was written: `rm -rf node_modules` (9,330 files)
    /// exceeds the 5,000-file copy budget and reads as uninsurable. It is
    /// also routine, and destroys nothing `npm install` cannot rebuild. The
    /// first draft fired on any Ask, which under a `default: ask` policy
    /// denied it - `uninsurable -> deny` under another name (#48).
    #[test]
    fn uninsurability_strengthens_a_concern_and_never_invents_one() {
        // 1. Unmatched + default Ask + uninsurable -> Ask.
        //    `rm -r node_modules`. The default is the ABSENCE of an opinion,
        //    not a weak one, and nothing has said this is worth stopping for.
        let (d, esc) = apply_insurance(dec(Action::Ask, DecisionSource::Default), true);
        assert_eq!(
            d.action,
            Action::Ask,
            "an unmatched command is not a concern"
        );
        assert!(!esc);

        // 2. Explicit Ask + uninsurable -> Deny. A rule chose to stop here;
        //    uninsurability says asking is not safe, because a human
        //    approving a command with no net decides without the fact that
        //    matters most.
        let (d, esc) = apply_insurance(dec(Action::Ask, DecisionSource::ExplicitRule), true);
        assert_eq!(d.action, Action::Deny);
        assert!(esc, "the escalation must be reported, not silent");
        assert!(
            d.reason.contains("nothing can be recovered"),
            "{}",
            d.reason
        );

        // 3. Context-escalated Ask + uninsurable -> Deny. `rm -rf ~/Documents`
        //    is Ask because it resolves to a user profile - a signal, not a
        //    shrug.
        let (d, esc) = apply_insurance(dec(Action::Ask, DecisionSource::Context), true);
        assert_eq!(d.action, Action::Deny);
        assert!(esc);

        // 4. Explicit Allow + uninsurable -> Allow. The escape hatch holds:
        //    an operator who wrote the rule outranks the amplifier.
        for src in [DecisionSource::ExplicitRule, DecisionSource::Context] {
            let (d, esc) = apply_insurance(dec(Action::Allow, src), true);
            assert_eq!(d.action, Action::Allow, "an explicit allow is unchanged");
            assert!(!esc);
        }

        // 5. Existing Deny + uninsurable -> Deny, and NOT re-escalated: a
        //    second amplification would double the reason and claim a change
        //    that did not happen.
        let base = dec(Action::Deny, DecisionSource::ExplicitRule);
        let (d, esc) = apply_insurance(base.clone(), true);
        assert_eq!(d.action, Action::Deny);
        assert!(!esc);
        assert_eq!(d.reason, base.reason, "an existing deny is left alone");

        // CONTROL LEG: with insurance available, nothing moves at all - so a
        // failure above is about the amplifier, not about the plumbing.
        for src in [
            DecisionSource::Default,
            DecisionSource::ExplicitRule,
            DecisionSource::Context,
        ] {
            for act in [Action::Allow, Action::Ask, Action::Deny] {
                let (d, esc) = apply_insurance(dec(act, src), false);
                assert_eq!(d.action, act, "insured commands are untouched");
                assert!(!esc);
            }
        }
    }

    use crate::testutil::TestEnv;
    use std::path::{Path, PathBuf};

    fn git(dir: &Path, args: &[&str]) {
        let out = Command::new("git")
            .current_dir(dir)
            .args(args)
            .output()
            .expect("git must be available: branch awareness is what is under test");
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// A repo with one commit, sitting on `branch`, with the process moved
    /// into it — `current_git_branch` reads the cwd, so the branch has to be
    /// real rather than mocked.
    fn repo_on_branch(env: &mut TestEnv, branch: &str) -> PathBuf {
        let dir = env.root().join("repo");
        std::fs::create_dir_all(&dir).expect("repo dir must be creatable");
        git(&dir, &["init", "-q"]);
        git(
            &dir,
            &[
                "-c",
                "user.email=tests@termaxa.invalid",
                "-c",
                "user.name=termaxa tests",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "--allow-empty",
                "-q",
                "-m",
                "root",
            ],
        );
        git(&dir, &["checkout", "-q", "-B", branch]);
        env.chdir(&dir);
        dir
    }

    fn branch_signal(signals: &[Signal]) -> Signal {
        signals
            .iter()
            .find(|s| s.label.starts_with("current branch:"))
            .cloned()
            .expect("a git command in a repo should report the branch it is on")
    }

    #[test]
    fn committing_reports_the_branch_without_escalating() {
        let mut env = TestEnv::new("ctx-commit");
        repo_on_branch(&mut env, "main");

        let signal = branch_signal(&gather("git commit -m wip"));
        assert_eq!(signal.label, "current branch: main");
        // Being on main is worth showing; a commit is local and reversible,
        // so it is not worth stopping for.
        assert!(!signal.escalate, "a commit on main must not escalate");
    }

    #[test]
    fn pushing_to_a_protected_branch_escalates() {
        let mut env = TestEnv::new("ctx-push-main");
        repo_on_branch(&mut env, "main");

        let signal = branch_signal(&gather("git push origin main"));
        assert_eq!(signal.label, "current branch: main");
        assert!(
            signal.escalate,
            "a push to main is the case this exists for"
        );
    }

    #[test]
    fn pushing_from_a_feature_branch_does_not_escalate() {
        let mut env = TestEnv::new("ctx-push-feature");
        repo_on_branch(&mut env, "feature/widgets");

        let signal = branch_signal(&gather("git push origin feature/widgets"));
        assert_eq!(signal.label, "current branch: feature/widgets");
        assert!(
            !signal.escalate,
            "only the protected branches make a push notable"
        );
    }

    #[test]
    fn a_production_marker_is_flagged_on_a_non_git_command() {
        let signals = gather("psql -h prod-db.internal -c 'select 1'");
        let prod = signals
            .iter()
            .find(|s| s.label.contains("possible production target"))
            .expect("`prod` in a connection string is the whole point of this check");
        assert!(prod.escalate);
    }

    #[test]
    fn git_commands_are_exempt_from_the_production_marker() {
        // Branch and remote names carry `production` constantly; flagging
        // every one of them would train the human to click through.
        let signals = gather("git push origin production");
        assert!(
            !signals
                .iter()
                .any(|s| s.label.contains("possible production target")),
            "a git ref named production is not a production target"
        );
    }

    #[test]
    fn an_ordinary_command_produces_no_signals_at_all() {
        assert!(
            gather("ls -la").is_empty(),
            "a listing is not worth a signal"
        );
    }

    #[test]
    fn destructive_sql_and_flags_are_flagged() {
        let signals = gather("psql -c \"TRUNCATE users\"");
        assert!(signals
            .iter()
            .any(|s| s.label.contains("destructive SQL") && s.escalate));

        let signals = gather("rm -rf build");
        assert!(signals
            .iter()
            .any(|s| s.label.contains("destructive flag") && s.escalate));
    }

    #[test]
    fn command_substitution_is_flagged_because_it_cannot_be_read() {
        let signals = gather("echo $(cat /etc/passwd)");
        assert!(signals
            .iter()
            .any(|s| s.label.contains("command substitution") && s.escalate));
    }

    fn decision(action: Action) -> Decision {
        Decision {
            action,
            source: DecisionSource::ExplicitRule,
            matched_rule: Some("rule".into()),
            reason: "base".into(),
        }
    }

    fn escalating() -> Vec<Signal> {
        vec![Signal {
            label: "destructive flag detected: --force".into(),
            escalate: true,
        }]
    }

    #[test]
    fn context_escalates_allow_to_ask_and_says_why() {
        let (out, escalated) = apply(decision(Action::Allow), &escalating());
        assert_eq!(out.action, Action::Ask);
        assert!(escalated);
        assert!(
            out.reason.contains("base") && out.reason.contains("--force"),
            "the reason must keep the rule's own words and add the signal: {}",
            out.reason
        );
        assert_eq!(
            out.matched_rule,
            Some("rule".into()),
            "escalation does not change which rule matched"
        );
    }

    #[test]
    fn context_never_downgrades_a_decision() {
        // A deny that a signal could soften would be a gate with a bypass.
        let (out, escalated) = apply(decision(Action::Deny), &escalating());
        assert_eq!(out.action, Action::Deny);
        assert!(!escalated);

        let (out, escalated) = apply(decision(Action::Ask), &escalating());
        assert_eq!(out.action, Action::Ask);
        assert!(!escalated);
    }

    #[test]
    fn a_non_escalating_signal_leaves_allow_alone() {
        let noted = vec![Signal {
            label: "current branch: main".into(),
            escalate: false,
        }];
        let (out, escalated) = apply(decision(Action::Allow), &noted);
        assert_eq!(out.action, Action::Allow);
        assert!(!escalated);
        assert_eq!(out.reason, "base", "an untouched decision keeps its reason");
    }
}