repotoire 0.9.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Hook runtime — invoked by Claude Code via PreToolUse hook.
//!
//! Fail-open philosophy: ANY internal error must result in `ExitCode::SUCCESS` with no stdout.
//! The user must always be able to commit, even if the hook is broken.
//!
//! IMPORTANT: We emit the PreToolUse-specific `hookSpecificOutput` schema (per
//! code.claude.com/docs/en/hooks), NOT the legacy/common form
//! `{decision: "block", reason: "..."}`. Both forms appear in different Claude Code
//! docs (anthropics/claude-code#19115) but only the form below works for PreToolUse deny.
//! Do not "fix" this back to the legacy form.

use std::process::ExitCode;
use std::sync::LazyLock;

use regex::Regex;

/// Matches `git commit` and variants where `commit` is the git subcommand:
///   - `git commit`, `git commit -am 'x'`, `git commit --amend`
///   - `git -c user.email=x commit ...` (config-override flags between git and commit)
///   - `git checkout && git commit` (anywhere in a chained command)
///   - `'git commit'` quoted inside another command (acceptable false-positive)
///
/// Rejects:
///   - `git commit-tree`, `git commit-graph` (sibling subcommands)
///   - `gitlab commit` (different binary)
///   - `git status` (no commit)
///
/// Pattern reasoning: `\bgit\b` ensures `git` is a whole word (rejects `gitlab`).
/// `[^\n]*?` non-greedy match of anything-but-newline allows arbitrary args between
/// `git` and `commit`. `\bcommit` ensures `commit` starts on a word boundary
/// (rejects `recommit`). `(?:\s|$|[^\w-])` requires `commit` to be terminated by
/// whitespace, end-of-string, or a non-word non-hyphen character (rejects
/// `commit-tree`, `commit-graph`; accepts `commit`, `commit'`, `commit;`, etc.).
///
/// Case-sensitive (matches git's own dispatch on Unix).
static GIT_COMMIT_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\bgit\b[^\n]*?\bcommit(?:\s|$|[^\w-])").expect("static regex compiles")
});

/// True if `cmd` issues a `git commit` (with or without arguments, with or without
/// preceding `git -c k=v`-style flags).
pub(super) fn matches_git_commit(cmd: &str) -> bool {
    GIT_COMMIT_RE.is_match(cmd)
}

/// Maximum bytes we'll accept on stdin. Hook payloads are tiny (~1 KiB typical);
/// 1 MiB is a comfortable cap that prevents memory exhaustion on malicious input.
const MAX_STDIN_BYTES: u64 = 1024 * 1024;

/// Hook runtime entry point. ALL internal errors → exit 0 with no stdout.
pub fn run() -> ExitCode {
    match try_run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            tracing::debug!("claude-hook run: {e:#}");
            // Optional: surface to stderr for users debugging the hook themselves.
            // Claude Code does not display stderr to users.
            eprintln!("repotoire claude-hook: {e:#}");
            ExitCode::SUCCESS
        }
    }
}

/// Internal flow. Returning Err means "fail-open silently" — the wrapper turns it into ExitCode::SUCCESS.
fn try_run() -> anyhow::Result<()> {
    use std::io::Read;

    // 1. Read stdin (capped).
    let mut buf = String::new();
    std::io::stdin()
        .lock()
        .take(MAX_STDIN_BYTES)
        .read_to_string(&mut buf)
        .map_err(|e| anyhow::anyhow!("read stdin: {e}"))?;
    let payload: serde_json::Value =
        serde_json::from_str(&buf).map_err(|e| anyhow::anyhow!("parse stdin JSON: {e}"))?;

    // 2. Cheap pre-filter: tool_name must be "Bash".
    let tool_name = payload
        .get("tool_name")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    if tool_name != "Bash" {
        return Ok(());
    }

    // 3. Extract and match the command.
    let command = payload
        .get("tool_input")
        .and_then(|v| v.get("command"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    if !matches_git_commit(command) {
        return Ok(());
    }

    // 4. Read cwd from the payload (NOT the inherited subprocess cwd).
    let cwd_str = payload
        .get("cwd")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("payload.cwd missing"))?;
    let cwd = std::path::Path::new(cwd_str);
    if !cwd.is_dir() {
        return Ok(());
    }

    // 5. Locate repo root via `git rev-parse --show-toplevel`.
    let toplevel = std::process::Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| anyhow::anyhow!("spawn git rev-parse: {e}"))?;
    if !toplevel.status.success() {
        return Ok(());
    }
    let repo_root = String::from_utf8_lossy(&toplevel.stdout).trim().to_string();
    if repo_root.is_empty() {
        return Ok(());
    }
    let repo_root = std::path::PathBuf::from(repo_root);

    // 6. Skip if no commits yet.
    let head_check = std::process::Command::new("git")
        .arg("-C")
        .arg(&repo_root)
        .args(["rev-parse", "--verify", "HEAD"])
        .output()
        .map_err(|e| anyhow::anyhow!("spawn git rev-parse HEAD: {e}"))?;
    if !head_check.status.success() {
        return Ok(());
    }

    // 7. Skip if no baseline cached.
    //    Known race: `repotoire analyze` writes baseline_findings.json from a detached
    //    cache_results thread; a hook that fires immediately after analyze (before the
    //    write completes) may see a partially-written file and parse-fail in step 8.
    //    Fail-open is the intended outcome — the user's commit goes through and the
    //    hook fires correctly on the next attempt.
    let baseline = crate::cache::paths::cache_dir(&repo_root).join("baseline_findings.json");
    if !baseline.exists() {
        return Ok(());
    }

    // 8. Compute diff with NO inline analysis and NO telemetry.
    //    Pass `all=true` so we get every new finding vs baseline regardless of
    //    hunk attribution. The hook fires before the commit, so `git diff HEAD..HEAD`
    //    (the attribution source for `all=false`) is empty by definition.
    let opts = crate::cli::diff::SmartDiffOptions {
        allow_inline_analysis: false,
        emit_telemetry: false,
    };
    let telemetry = crate::telemetry::Telemetry::Disabled;
    let result = crate::cli::diff::compute_smart_diff(
        &repo_root,
        Some("HEAD"),
        true,  // all
        false, // changed
        false, // working_tree: all=true here, so the attribution source is moot. (A future
        // rewrite of this hook to `diff HEAD --working-tree --changed` could drop all=true.)
        opts,
        &telemetry,
    )?;
    let result = match result {
        Some(r) => r,
        None => return Ok(()),
    };

    // 9. Decide. The gate keys off `tier`, not `severity`: it blocks `git commit` when this
    //    branch introduced at least one finding at the effective block tier or higher (default
    //    `Tier::Blocking`). `REPOTOIRE_GATE_TIER=off` disables the gate entirely.
    let block_tier = match resolved_block_tier() {
        Some(t) => t,
        None => return Ok(()), // gate disabled (REPOTOIRE_GATE_TIER=off)
    };
    if !gate_tripped(&result, block_tier) {
        return Ok(());
    }

    // 10. Emit deny response on stdout.
    let reason = format_deny_reason(&result, block_tier);
    let response = build_deny_response(&reason);
    println!("{}", serde_json::to_string(&response)?);
    Ok(())
}

use crate::cli::diff::SmartDiffResult;
use crate::models::{Evidence, Severity, SourceSpan, Tier};

/// Maximum bullet lines we put in the deny reason (sorted by tier desc, then severity desc,
/// then file).
const MAX_BULLETS: usize = 5;

/// The structured `:ignore` instruction shown in the deny message (spec §3). A *bare*
/// `// repotoire:ignore` hides a finding from the human report but does NOT clear the gate;
/// only an accounted reason from the taxonomy does.
const IGNORE_INSTRUCTION: &str = "Genuine false positive: add `// repotoire:ignore[<detector>] \u{2014} <reason>` where <reason> is one of framework-pattern | test-fixture | protocol-required | redaction-list | vendored | generated | accepted-risk, and tell me you did it. A bare `// repotoire:ignore` will hide it from the report but will NOT clear this gate.";

/// Resolve the effective block tier for the `git commit` gate from the environment.
///
/// `REPOTOIRE_GATE_TIER=off` (case-insensitive) is the process-wide kill switch — it disables
/// the gate (`None`) unconditionally, exactly like the `Stop` hook's top-of-file short-circuit,
/// even if `REPOTOIRE_HOOK_BLOCK_TIER` is also set. Otherwise the precedence (matching the `Stop`
/// hook) is `REPOTOIRE_HOOK_BLOCK_TIER` > `REPOTOIRE_GATE_TIER` > default `Tier::Blocking`; a
/// value of `off` on `REPOTOIRE_HOOK_BLOCK_TIER` also disables. A set-but-empty or unparseable
/// value is ignored (treated as unset) — fail-open.
fn resolved_block_tier() -> Option<Tier> {
    // Process-wide kill switch — wins over everything, like the Stop hook.
    if std::env::var("REPOTOIRE_GATE_TIER").is_ok_and(|v| v.trim().eq_ignore_ascii_case("off")) {
        return None;
    }
    for key in ["REPOTOIRE_HOOK_BLOCK_TIER", "REPOTOIRE_GATE_TIER"] {
        let raw = match std::env::var(key) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let raw = raw.trim();
        if raw.is_empty() {
            continue;
        }
        if raw.eq_ignore_ascii_case("off") {
            return None;
        }
        match raw.parse::<Tier>() {
            Ok(t) => return Some(t),
            Err(e) => {
                tracing::debug!("claude-hook: ignoring {key}={raw:?}: {e:#}");
                continue;
            }
        }
    }
    Some(Tier::Blocking)
}

/// True when this branch introduced something the gate must block on: at least one new finding
/// at `block_tier` or higher, or a `Blocking` finding suppressed by a *bare* `// repotoire:ignore`
/// (no accounted reason — see `SmartDiffResult::suppressed_unaccounted_blocking_count`).
fn gate_tripped(result: &SmartDiffResult, block_tier: Tier) -> bool {
    result
        .new_findings
        .iter()
        .any(|af| af.finding.tier >= block_tier)
        || result.suppressed_unaccounted_blocking_count > 0
}

fn severity_rank(sev: Severity) -> u8 {
    match sev {
        Severity::Critical => 0,
        Severity::High => 1,
        Severity::Medium => 2,
        Severity::Low => 3,
        Severity::Info => 4,
    }
}

fn first_file(finding: &crate::models::Finding) -> String {
    finding
        .affected_files
        .first()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "<unknown>".into())
}

/// `path:line` for a [`SourceSpan`].
fn span_loc(span: &SourceSpan) -> String {
    format!("{}:{}", span.file.display(), span.line_start)
}

/// One-line evidence summary for a bullet — leads with the proof a `Blocking` finding carries.
/// Falls back to `path:line` for findings without `evidence` (e.g. an Advisory finding that
/// trips a widened gate).
fn evidence_summary(finding: &crate::models::Finding) -> String {
    match &finding.evidence {
        Some(Evidence::TaintPath {
            source,
            sink,
            sink_kind,
            ..
        }) => format!(
            "source {} \u{2192} {sink_kind} sink {}",
            span_loc(source),
            span_loc(sink)
        ),
        Some(Evidence::Secret { span, format, .. }) => {
            format!("{format} at {}", span_loc(span))
        }
        Some(Evidence::ConfigFact { span, rule }) => format!("{rule} at {}", span_loc(span)),
        None => {
            let line = finding
                .line_start
                .map(|l| format!(":{l}"))
                .unwrap_or_default();
            format!("{}{line}", first_file(finding))
        }
    }
}

/// Build the human-readable reason string Claude Code shows in the deny dialog.
///
/// `block_tier` is the effective gate tier (from [`resolved_block_tier`]); findings at that tier
/// or higher are the blockers. Each bullet leads with the evidence, then comes the structured
/// `:ignore` instruction (spec §3).
pub(super) fn format_deny_reason(result: &SmartDiffResult, block_tier: Tier) -> String {
    let mut out = String::new();

    let mut blockers: Vec<&crate::cli::diff::AttributedFinding> = result
        .new_findings
        .iter()
        .filter(|af| af.finding.tier >= block_tier)
        .collect();

    let tier_word = if block_tier == Tier::Blocking {
        "blocking".to_string()
    } else {
        format!("{block_tier}+")
    };
    out.push_str(&format!(
        "Repotoire: {} new {tier_word} finding(s) on this branch:\n",
        blockers.len()
    ));

    if let (Some(before), Some(after)) = (result.score_before, result.score_after) {
        let delta = after - before;
        out.push_str(&format!(
            "Score: {before:.1} \u{2192} {after:.1} (\u{0394} {delta:+.1})\n"
        ));
    }
    if result.suppressed_unaccounted_blocking_count > 0 {
        out.push_str(&format!(
            "{} blocking finding(s) suppressed without an accounted reason \u{2014} still blocking.\n",
            result.suppressed_unaccounted_blocking_count
        ));
    }
    out.push('\n');

    blockers.sort_by(|a, b| {
        // Highest tier first, then highest severity, then file path.
        b.finding
            .tier
            .cmp(&a.finding.tier)
            .then_with(|| severity_rank(a.finding.severity).cmp(&severity_rank(b.finding.severity)))
            .then_with(|| first_file(&a.finding).cmp(&first_file(&b.finding)))
    });

    for af in blockers.iter().take(MAX_BULLETS) {
        out.push_str(&format!(
            "- [{}] {} \u{2014} {}\n",
            af.finding.detector,
            af.finding.title,
            evidence_summary(&af.finding),
        ));
    }
    if blockers.len() > MAX_BULLETS {
        out.push_str(&format!("- ...and {} more\n", blockers.len() - MAX_BULLETS));
    }

    out.push('\n');
    out.push_str(IGNORE_INSTRUCTION);
    out.push_str("\n\nFix these before committing.\n");
    out
}

/// Build the JSON response Claude Code expects on stdout.
pub(super) fn build_deny_response(reason: &str) -> serde_json::Value {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": reason,
        }
    })
}

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

    #[test]
    fn matches_basic_git_commit() {
        assert!(matches_git_commit("git commit"));
    }

    #[test]
    fn matches_git_commit_with_short_flags() {
        assert!(matches_git_commit("git commit -am 'fix bug'"));
    }

    #[test]
    fn matches_git_commit_with_amend() {
        assert!(matches_git_commit("git commit --amend"));
    }

    #[test]
    fn matches_git_commit_with_config_override() {
        assert!(matches_git_commit(
            "git -c user.email=x@y.z commit -am 'fix'"
        ));
    }

    #[test]
    fn matches_git_commit_with_extra_whitespace() {
        assert!(matches_git_commit("\t  git    commit\n"));
    }

    #[test]
    fn rejects_git_commit_tree() {
        assert!(!matches_git_commit("git commit-tree foo"));
    }

    #[test]
    fn rejects_git_commit_graph() {
        assert!(!matches_git_commit("git commit-graph write"));
    }

    #[test]
    fn rejects_gitlab_commit() {
        assert!(!matches_git_commit("gitlab commit something"));
    }

    #[test]
    fn rejects_git_status() {
        assert!(!matches_git_commit("git status"));
    }

    #[test]
    fn rejects_empty_string() {
        assert!(!matches_git_commit(""));
    }

    #[test]
    fn rejects_bare_git() {
        assert!(!matches_git_commit("git"));
    }

    #[test]
    fn matches_chained_git_commit() {
        // Acceptable false-positive per spec: command-substitution chained with `git commit`.
        assert!(matches_git_commit("git checkout main && git commit"));
    }

    #[test]
    fn matches_quoted_git_commit_in_echo() {
        // Acceptable false-positive per spec.
        assert!(matches_git_commit("echo 'git commit'"));
    }

    use crate::cli::diff::AttributedFinding;
    use crate::cli::diff_hunks::Attribution;
    use crate::models::Finding;
    use std::path::PathBuf;
    use std::sync::Mutex;

    /// Serializes the tests that mutate the process-global gate env vars
    /// (`REPOTOIRE_GATE_TIER` / `REPOTOIRE_HOOK_BLOCK_TIER`), which `cargo test` would
    /// otherwise run in parallel.
    static GATE_ENV_LOCK: Mutex<()> = Mutex::new(());

    /// Run `f` with the two gate env vars set to the given values, restoring the prior state
    /// (and dropping the lock) afterwards.
    fn with_gate_env<R>(
        hook_block_tier: Option<&str>,
        gate_tier: Option<&str>,
        f: impl FnOnce() -> R,
    ) -> R {
        let _guard = GATE_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let keys = ["REPOTOIRE_HOOK_BLOCK_TIER", "REPOTOIRE_GATE_TIER"];
        let prev: Vec<Option<String>> = keys.iter().map(|k| std::env::var(k).ok()).collect();
        for (k, v) in keys.iter().zip([hook_block_tier, gate_tier]) {
            match v {
                Some(v) => std::env::set_var(k, v),
                None => std::env::remove_var(k),
            }
        }
        let out = f();
        for (k, v) in keys.iter().zip(prev) {
            match v {
                Some(v) => std::env::set_var(k, v),
                None => std::env::remove_var(k),
            }
        }
        out
    }

    fn span(file: &str, line: u32) -> SourceSpan {
        SourceSpan {
            file: PathBuf::from(file),
            line_start: line,
            line_end: line,
            snippet: None,
        }
    }

    fn fake_finding(
        detector: &str,
        title: &str,
        file: &str,
        line: u32,
        tier: Tier,
        evidence: Option<Evidence>,
    ) -> AttributedFinding {
        AttributedFinding {
            finding: Finding {
                detector: detector.into(),
                title: title.into(),
                severity: Severity::High,
                affected_files: vec![PathBuf::from(file)],
                line_start: Some(line),
                tier,
                evidence,
                ..Default::default()
            },
            attribution: Attribution::InChangedHunk,
        }
    }

    fn taint_finding(detector: &str, file: &str, line: u32) -> AttributedFinding {
        fake_finding(
            detector,
            "tainted input reaches a dangerous sink",
            file,
            line,
            Tier::Blocking,
            Some(Evidence::TaintPath {
                source: span(file, line),
                sink: span(file, line + 5),
                sink_kind: "exec".into(),
                flow: Vec::new(),
                sanitizers_seen: Vec::new(),
            }),
        )
    }

    fn advisory_finding(detector: &str, file: &str, line: u32) -> AttributedFinding {
        fake_finding(detector, "magic number", file, line, Tier::Advisory, None)
    }

    fn fake_result(
        findings: Vec<AttributedFinding>,
        before: Option<f64>,
        after: Option<f64>,
    ) -> SmartDiffResult {
        let n = findings.len();
        SmartDiffResult {
            base_ref: "cached".into(),
            head_ref: "HEAD".into(),
            files_changed: 1,
            new_findings: findings,
            all_new_count: n,
            fixed_findings: vec![],
            score_before: before,
            score_after: after,
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        }
    }

    // ── gate decision (`gate_tripped`) ──

    #[test]
    fn gate_blocks_on_new_blocking_finding() {
        let r = fake_result(
            vec![taint_finding("command-injection", "a.js", 3)],
            None,
            None,
        );
        assert!(gate_tripped(&r, Tier::Blocking));
    }

    #[test]
    fn gate_allows_when_only_advisory_or_deep() {
        let mut r = fake_result(
            vec![advisory_finding("magic-numbers", "a.js", 7)],
            None,
            None,
        );
        assert!(!gate_tripped(&r, Tier::Blocking));
        r.new_findings[0].finding.tier = Tier::Deep;
        assert!(!gate_tripped(&r, Tier::Blocking));
    }

    #[test]
    fn gate_blocks_advisory_when_widened() {
        let r = fake_result(
            vec![advisory_finding("magic-numbers", "a.js", 7)],
            None,
            None,
        );
        assert!(!gate_tripped(&r, Tier::Blocking));
        assert!(gate_tripped(&r, Tier::Advisory));
    }

    #[test]
    fn gate_blocks_on_unaccounted_suppressed_blocking() {
        let mut r = fake_result(vec![], None, None);
        r.suppressed_unaccounted_blocking_count = 1;
        assert!(gate_tripped(&r, Tier::Blocking));
    }

    // ── env-knob resolution (`resolved_block_tier`) ──

    #[test]
    fn block_tier_defaults_to_blocking() {
        with_gate_env(None, None, || {
            assert_eq!(resolved_block_tier(), Some(Tier::Blocking));
        });
    }

    #[test]
    fn hook_block_tier_advisory_widens() {
        with_gate_env(Some("advisory"), None, || {
            assert_eq!(resolved_block_tier(), Some(Tier::Advisory));
        });
    }

    #[test]
    fn gate_tier_advisory_widens() {
        with_gate_env(None, Some("advisory"), || {
            assert_eq!(resolved_block_tier(), Some(Tier::Advisory));
        });
    }

    #[test]
    fn hook_block_tier_wins_over_gate_tier() {
        with_gate_env(Some("blocking"), Some("advisory"), || {
            assert_eq!(resolved_block_tier(), Some(Tier::Blocking));
        });
    }

    #[test]
    fn gate_tier_off_disables_the_gate() {
        with_gate_env(None, Some("off"), || {
            assert_eq!(resolved_block_tier(), None);
        });
        with_gate_env(None, Some("OFF"), || {
            assert_eq!(resolved_block_tier(), None);
        });
        // The process-wide kill switch wins even when a hook-specific tier is set —
        // matching the Stop hook's top-of-file `REPOTOIRE_GATE_TIER=off` short-circuit.
        with_gate_env(Some("blocking"), Some("off"), || {
            assert_eq!(resolved_block_tier(), None);
        });
    }

    #[test]
    fn empty_or_garbage_env_is_ignored() {
        with_gate_env(Some("   "), Some("not-a-tier"), || {
            assert_eq!(resolved_block_tier(), Some(Tier::Blocking));
        });
    }

    // ── deny message (`format_deny_reason`) ──

    #[test]
    fn deny_reason_leads_with_taint_evidence_and_ignore_instruction() {
        let r = fake_result(
            vec![taint_finding("command-injection", "src/a.js", 12)],
            None,
            None,
        );
        let s = format_deny_reason(&r, Tier::Blocking);
        assert!(s.contains("1 new blocking finding(s)"), "header: {s}");
        assert!(s.contains("[command-injection]"), "detector in bullet: {s}");
        assert!(
            s.contains("source src/a.js:12 \u{2192} exec sink src/a.js:17"),
            "evidence summary: {s}"
        );
        assert!(
            s.contains("repotoire:ignore[<detector>]") && s.contains("accepted-risk"),
            "structured :ignore instruction: {s}"
        );
        assert!(
            s.contains("A bare `// repotoire:ignore`"),
            "bare-ignore caveat: {s}"
        );
    }

    #[test]
    fn deny_reason_summarizes_secret_and_config_fact_evidence() {
        let secret = fake_finding(
            "secrets",
            "AWS access key id committed",
            "config.py",
            4,
            Tier::Blocking,
            Some(Evidence::Secret {
                span: span("config.py", 4),
                format: "aws_access_key_id".into(),
                entropy_bits: 132.0,
                checksum_valid: None,
            }),
        );
        let cfg = fake_finding(
            "insecure-tls",
            "TLS verification disabled",
            "client.js",
            9,
            Tier::Blocking,
            Some(Evidence::ConfigFact {
                span: span("client.js", 9),
                rule: "tls_verify_disabled".into(),
            }),
        );
        let s = format_deny_reason(&fake_result(vec![secret, cfg], None, None), Tier::Blocking);
        assert!(
            s.contains("aws_access_key_id at config.py:4"),
            "secret: {s}"
        );
        assert!(
            s.contains("tls_verify_disabled at client.js:9"),
            "config fact: {s}"
        );
    }

    #[test]
    fn deny_reason_truncates_to_top_5() {
        let findings: Vec<_> = (0..50)
            .map(|i| taint_finding("command-injection", "a.js", i + 1))
            .collect();
        let r = fake_result(findings, Some(95.0), Some(90.0));
        let s = format_deny_reason(&r, Tier::Blocking);
        let bullet_count = s.matches("- [command-injection]").count();
        assert_eq!(bullet_count, 5, "should be exactly 5 bullets, got: {s}");
        assert!(
            s.contains("...and 45 more"),
            "should mention truncated count: {s}"
        );
    }

    #[test]
    fn deny_reason_includes_score_line_when_both_set() {
        let r = fake_result(
            vec![taint_finding("command-injection", "a.js", 1)],
            Some(95.0),
            Some(90.0),
        );
        let s = format_deny_reason(&r, Tier::Blocking);
        assert!(s.contains("Score: 95.0"), "missing score line: {s}");
        assert!(s.contains("90.0"), "missing after-score: {s}");
        assert!(s.contains("-5.0"), "missing delta: {s}");
    }

    #[test]
    fn deny_reason_omits_score_line_when_either_missing() {
        let r = fake_result(
            vec![taint_finding("command-injection", "a.js", 1)],
            None,
            Some(90.0),
        );
        let s = format_deny_reason(&r, Tier::Blocking);
        assert!(!s.contains("Score:"), "should omit score line: {s}");
    }

    #[test]
    fn deny_reason_mentions_unaccounted_suppressions() {
        let mut r = fake_result(
            vec![taint_finding("command-injection", "a.js", 1)],
            None,
            None,
        );
        r.suppressed_unaccounted_blocking_count = 2;
        let s = format_deny_reason(&r, Tier::Blocking);
        assert!(
            s.contains("2 blocking finding(s) suppressed without an accounted reason"),
            "unaccounted note: {s}"
        );
    }

    #[test]
    fn deny_reason_sorts_blocking_before_advisory_when_widened() {
        let r = fake_result(
            vec![
                advisory_finding("magic-numbers", "a.js", 10),
                taint_finding("command-injection", "a.js", 20),
            ],
            None,
            None,
        );
        let s = format_deny_reason(&r, Tier::Advisory);
        let block_pos = s
            .find("command-injection")
            .expect("blocking bullet present");
        let adv_pos = s.find("magic-numbers").expect("advisory bullet present");
        assert!(
            block_pos < adv_pos,
            "Blocking should sort before Advisory: {s}"
        );
    }

    #[test]
    fn deny_response_has_correct_schema() {
        let v = build_deny_response("hello");
        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse");
        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
        assert_eq!(v["hookSpecificOutput"]["permissionDecisionReason"], "hello");
    }
}