feat(cli): bulk triage, and stop truncating locations twice

Status changes take selectors — --rule, --harness, --under <path>,
--fingerprint — with --dry-run, alongside bare ids. A first sweep of a real
machine reports over a thousand findings, most of them the same few test
fixtures repeated through vendored dependencies, and dismissing those one id
at a time is data entry rather than triage: a tool that demands it gets
abandoned instead of tuned. --fingerprint is the useful one for a genuine
leak, since one rotation resolves every copy of the secret at once.

Also fixes the location column, which was shortened twice. short_path keeps
the tail of a path, then the table clipped the right-hand end, so the row
lost both the filename and the line number — the two things that identify a
finding. Column widths are now derived from the same constants as the
constraints, and format::location budgets for the line-number suffix before
shortening the path around it.

Verified by driving the TUI through a pty and reconstructing the frame.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAqHWfdMAsYu1o36tgeima
This commit is contained in:
2026-09-02 15:23:58 +03:00
co-authored by Claude Opus 5
parent 510f856174
commit eff78fcddf
4 changed files with 286 additions and 60 deletions
+80 -4
View File
@@ -140,13 +140,30 @@ pub fn short_path(path: &std::path::Path, home: &std::path::Path, width: usize)
format!("…{keep}")
}
/// A finding's location — path and line — rendered to fit exactly `width`
/// characters.
///
/// The line number is budgeted for first and the path shortened around it.
/// Truncating the path to the full width and then appending `:1712` pushes the
/// row over the column, and the terminal takes the line number off the end —
/// leaving a location that names a file but not a place in it.
#[must_use]
pub fn location(finding: &Finding, home: &std::path::Path, width: usize) -> String {
let suffix = finding.line.map_or_else(String::new, |l| format!(":{l}"));
let path = short_path(
finding.origin.path(),
home,
width.saturating_sub(suffix.chars().count()).max(8),
);
format!("{path}{suffix}")
}
/// One finding as a table row.
#[must_use]
pub fn row(finding: &Finding, home: &std::path::Path, style: &Style, width: usize) -> String {
let location = short_path(finding.origin.path(), home, width);
let line = finding.line.map_or_else(String::new, |l| format!(":{l}"));
let where_ = location(finding, home, width);
format!(
"{:>5} {:<8} {:<9} {:<9} {:<26} {location}{line}",
"{:>5} {:<8} {:<9} {:<9} {:<26} {where_}",
finding.id.0,
when(finding.last_seen),
style.severity(finding.severity),
@@ -194,10 +211,39 @@ pub fn json(finding: &Finding) -> serde_json::Value {
#[cfg(test)]
mod tests {
use std::path::Path;
use std::path::{Path, PathBuf};
use nanny_entities::{FindingId, Fingerprint, Harness, Origin, RuleId};
use time::OffsetDateTime;
use super::*;
fn finding_at(path: &str, line: Option<u32>) -> Finding {
Finding {
id: FindingId(1),
fingerprint: Fingerprint::from_stored("abcdef0123456789".into()),
rule: RuleId::new("anthropic-api-key"),
label: "Anthropic API key".into(),
severity: Severity::Critical,
confidence: nanny_entities::Confidence::Certain,
harness: Harness::WorkingTree,
origin: Origin::File {
path: PathBuf::from(path),
},
detail: None,
line,
byte_offset: Some(0),
preview: nanny_entities::Preview::from_safe("…••••[49]…"),
matched_len: 49,
first_seen: OffsetDateTime::now_utc(),
last_seen: OffsetDateTime::now_utc(),
occurrences: 1,
status: Status::Open,
note: None,
status_changed_at: None,
}
}
#[test]
fn paths_are_shortened_from_the_left_keeping_the_filename() {
let home = Path::new("/home/tester");
@@ -228,6 +274,36 @@ mod tests {
);
}
#[test]
fn a_location_fits_its_column_and_keeps_the_line_number() {
let home = Path::new("/home/tester");
let finding = finding_at(
"/home/tester/git/zeroclaw/crates/zeroclaw-runtime/src/skills/creator.rs",
Some(1712),
);
let rendered = location(&finding, home, 40);
assert!(
rendered.chars().count() <= 40,
"overflows the column: {rendered:?}"
);
assert!(
rendered.ends_with(":1712"),
"lost the line number: {rendered:?}"
);
assert!(
rendered.contains("creator.rs"),
"lost the filename: {rendered:?}"
);
}
#[test]
fn a_location_without_a_line_number_uses_the_whole_column() {
let home = Path::new("/home/tester");
let finding = finding_at("/home/tester/.local/share/opencode/opencode.db", None);
let rendered = location(&finding, home, 40);
assert_eq!(rendered, "~/.local/share/opencode/opencode.db");
}
#[test]
fn plain_style_emits_no_escape_codes() {
let style = Style::plain();
+155 -44
View File
@@ -41,6 +41,56 @@ struct Args {
command: Option<Command>,
}
/// Which findings a status change applies to.
///
/// Ids alone would make the tool unusable at the scale it actually reports: a
/// first sweep of a real machine produced over a thousand findings, most of
/// them the same handful of test fixtures repeated across vendored
/// dependencies. Dismissing those one id at a time is not triage, it is data
/// entry, and a tool that demands it gets abandoned rather than tuned.
#[derive(Debug, clap::Args)]
struct Triage {
/// Finding ids. Repeatable.
ids: Vec<i64>,
/// Every finding from this rule.
#[arg(long)]
rule: Option<String>,
/// Every finding from this harness.
#[arg(long)]
harness: Option<String>,
/// Every finding under this path prefix — the usual way to dismiss a
/// third-party checkout whose test fixtures are not your credentials.
#[arg(long, value_name = "PATH")]
under: Option<PathBuf>,
/// Every copy of the same secret, selected by the fingerprint of a finding
/// you have already looked at.
#[arg(long)]
fingerprint: Option<String>,
/// Note recorded against every finding changed.
#[arg(long)]
note: Option<String>,
/// Show what would change, without changing it.
#[arg(long)]
dry_run: bool,
}
impl Triage {
/// Whether any selector was given at all.
fn is_empty(&self) -> bool {
self.ids.is_empty()
&& self.rule.is_none()
&& self.harness.is_none()
&& self.under.is_none()
&& self.fingerprint.is_none()
}
}
#[derive(Debug, Subcommand)]
enum Command {
/// Scan now and report what is found.
@@ -79,29 +129,17 @@ enum Command {
/// Show one finding in full, including how to rotate it.
Show { id: i64 },
/// Mark a finding as seen and triaged. The credential is still live.
Ack {
id: i64,
#[arg(long)]
note: Option<String>,
},
/// Mark findings as seen and triaged. The credentials are still live.
Ack(Triage),
/// Mark a finding's credential as revoked or replaced.
Rotated {
id: i64,
#[arg(long)]
note: Option<String>,
},
/// Mark findings' credentials as revoked or replaced.
Rotated(Triage),
/// Mark a finding as not a secret.
Ignore {
id: i64,
#[arg(long)]
note: Option<String>,
},
/// Mark findings as not secrets.
Ignore(Triage),
/// Reopen a finding.
Reopen { id: i64 },
/// Reopen findings.
Reopen(Triage),
/// List the active detection rules.
Rules {
@@ -153,16 +191,10 @@ async fn main() -> Result<()> {
.await?;
}
Some(Command::Show { id }) => show(&runtime, FindingId(id), &style).await?,
Some(Command::Ack { id, note }) => {
mark(&runtime, FindingId(id), Status::Acknowledged, note).await?;
}
Some(Command::Rotated { id, note }) => {
mark(&runtime, FindingId(id), Status::Rotated, note).await?;
}
Some(Command::Ignore { id, note }) => {
mark(&runtime, FindingId(id), Status::Ignored, note).await?;
}
Some(Command::Reopen { id }) => mark(&runtime, FindingId(id), Status::Open, None).await?,
Some(Command::Ack(t)) => triage(&runtime, &t, Status::Acknowledged, &style).await?,
Some(Command::Rotated(t)) => triage(&runtime, &t, Status::Rotated, &style).await?,
Some(Command::Ignore(t)) => triage(&runtime, &t, Status::Ignored, &style).await?,
Some(Command::Reopen(t)) => triage(&runtime, &t, Status::Open, &style).await?,
Some(Command::Rules { json }) => rules(&runtime, json, &style),
Some(Command::Doctor) => doctor(&runtime, &style).await?,
}
@@ -226,7 +258,7 @@ async fn scan(runtime: &Runtime, full: bool, json: bool, style: &Style) -> Resul
);
} else {
println!("{}", format::header(style));
let width = terminal_width().saturating_sub(58).max(20);
let width = path_column_width();
for finding in &new {
println!("{}", format::row(finding, &runtime.home, style, width));
}
@@ -348,7 +380,7 @@ async fn findings(
}
println!("{}", format::header(style));
let width = terminal_width().saturating_sub(58).max(20);
let width = path_column_width();
for finding in &found {
println!("{}", format::row(finding, &runtime.home, style, width));
}
@@ -432,18 +464,90 @@ async fn show(runtime: &Runtime, id: FindingId, style: &Style) -> Result<()> {
Ok(())
}
async fn mark(
runtime: &Runtime,
id: FindingId,
status: Status,
note: Option<String>,
) -> Result<()> {
runtime
.store
.set_status(&StatusChange { id, status, note })
.await
.with_context(|| format!("cannot update finding {id}"))?;
println!("finding {id} marked {status}");
/// Apply a status change to everything the selectors match.
async fn triage(runtime: &Runtime, selector: &Triage, status: Status, style: &Style) -> Result<()> {
anyhow::ensure!(
!selector.is_empty(),
"give at least one id, or a --rule / --harness / --under / --fingerprint selector"
);
let mut targets: Vec<FindingId> = selector.ids.iter().copied().map(FindingId).collect();
// Any selector beyond bare ids means querying. Statuses are left open so a
// selector can also be used to reopen something already resolved.
if selector.rule.is_some()
|| selector.harness.is_some()
|| selector.under.is_some()
|| selector.fingerprint.is_some()
{
let mut query = Query {
rule: selector.rule.clone(),
..Query::default()
};
if let Some(h) = &selector.harness {
query.harness = Some(h.parse::<Harness>().context("unknown harness")?);
}
let under = selector
.under
.as_ref()
.map(|p| nanny_core::config::expand_tilde(p, &runtime.home));
for finding in runtime.store.list(&query).await? {
if let Some(prefix) = &under
&& !finding.origin.path().starts_with(prefix)
{
continue;
}
if let Some(fingerprint) = &selector.fingerprint
&& finding.fingerprint.as_str() != fingerprint
{
continue;
}
if finding.status == status {
continue;
}
targets.push(finding.id);
}
}
targets.sort_unstable();
targets.dedup();
if targets.is_empty() {
println!("{}", style.dim("nothing matched"));
return Ok(());
}
if selector.dry_run {
println!("{}", format::header(style));
let width = path_column_width();
for id in &targets {
if let Some(finding) = runtime.store.get(*id).await? {
println!("{}", format::row(&finding, &runtime.home, style, width));
}
}
println!();
println!(
"{}",
style.bold(&format!("would mark {} finding(s) {status}", targets.len()))
);
return Ok(());
}
for id in &targets {
runtime
.store
.set_status(&StatusChange {
id: *id,
status,
note: selector.note.clone(),
})
.await
.with_context(|| format!("cannot update finding {id}"))?;
}
println!("marked {} finding(s) {status}", targets.len());
Ok(())
}
@@ -579,3 +683,10 @@ fn terminal_width() -> usize {
.and_then(|c| c.parse().ok())
.unwrap_or(120)
}
/// Width left for the path column in [`format::row`], which spends 62
/// characters on the fixed columns and the spaces between them. Shortening a
/// path to more than this makes the terminal wrap the row instead.
fn path_column_width() -> usize {
terminal_width().saturating_sub(62).max(16)
}
+29 -12
View File
@@ -54,6 +54,21 @@ impl Filter {
}
}
// Table geometry. The truncation width handed to `format::short_path` has to
// agree with these or the path is shortened twice, from both ends.
const WHEN_W: u16 = 9;
const SEVERITY_W: u16 = 9;
const HARNESS_W: u16 = 9;
const WHAT_W: u16 = 26;
const STATUS_W: u16 = 13;
const FIXED_COLUMNS: usize = (WHEN_W + SEVERITY_W + HARNESS_W + WHAT_W + STATUS_W) as usize;
/// One space between each of the six columns.
const COLUMN_GAPS: usize = 5;
/// Left and right border of the surrounding block.
const BORDERS: usize = 2;
/// Two columns for the `highlight_symbol` prefix.
const HIGHLIGHT: usize = 2;
/// Screen state.
struct App {
findings: Vec<Finding>,
@@ -299,22 +314,24 @@ fn draw_table(frame: &mut ratatui::Frame<'_>, area: Rect, app: &mut App) {
return;
}
let path_width = usize::from(area.width).saturating_sub(58).max(20);
// Must match the constraints below exactly. Shortening to a width wider
// than the column means ratatui clips the right-hand end afterwards — and
// since `short_path` keeps the tail, that loses the filename, which is the
// part that identifies the finding.
let path_width = usize::from(area.width)
.saturating_sub(BORDERS + COLUMN_GAPS + HIGHLIGHT + FIXED_COLUMNS)
.max(16);
let rows: Vec<Row<'_>> = app
.findings
.iter()
.map(|f| {
let line = f.line.map_or_else(String::new, |l| format!(":{l}"));
Row::new(vec![
Cell::from(format::when(f.last_seen)),
Cell::from(f.severity.to_string())
.style(Style::default().fg(severity_colour(f.severity))),
Cell::from(f.harness.slug().to_owned()),
Cell::from(f.label.clone()),
Cell::from(format!(
"{}{line}",
format::short_path(f.origin.path(), &app.home, path_width)
)),
Cell::from(format::location(f, &app.home, path_width)),
Cell::from(f.status.to_string())
.style(Style::default().fg(status_colour(f.status))),
])
@@ -324,12 +341,12 @@ fn draw_table(frame: &mut ratatui::Frame<'_>, area: Rect, app: &mut App) {
let table = Table::new(
rows,
[
Constraint::Length(9),
Constraint::Length(9),
Constraint::Length(9),
Constraint::Length(26),
Constraint::Min(20),
Constraint::Length(13),
Constraint::Length(WHEN_W),
Constraint::Length(SEVERITY_W),
Constraint::Length(HARNESS_W),
Constraint::Length(WHAT_W),
Constraint::Min(16),
Constraint::Length(STATUS_W),
],
)
.header(
+22
View File
@@ -83,6 +83,28 @@ nanny rules # the active ruleset
nanny doctor # is nanny itself configured safely
```
`ack`, `rotated`, `ignore` and `reopen` take ids or a selector — `--rule`,
`--harness`, `--under <path>`, `--fingerprint` — with `--dry-run` to see what
would change first. That matters more than it sounds: a first sweep of a real
machine reports over a thousand findings, most of them the same few test
fixtures repeated through vendored dependencies, and dismissing those one id at
a time is data entry rather than triage.
```sh
nanny ignore --under ~/git/some-upstream-checkout --note "not my credentials"
nanny rotated --fingerprint c7c0c9894025e096 # every copy of one secret, at once
```
### Tuning the noise
`~/git` is watched by default because a spilled value there is a spill whether
or not it was ever committed. On a machine with third-party checkouts it is also
where most of the false positives are: someone else's test keys, committed on
purpose. Build output, vendored dependencies, tool caches and minified assets
are excluded already; beyond that, `exclude` in the config takes globs, and
`nanny ignore --under` handles a checkout you would rather keep but not hear
about.
The triage screen is the default because the usual question is "do I have to
rotate something right now", and that is a list to walk rather than a query to
compose: