use super::*;
use mine::Kind;
pub const SCAN_HELP: &str = "usage: instinct scan [--days N] [--json] [--share]\n\
What did your coding agent get wrong in the last N days (default 30), and what would Instinct have caught?\n\
Reads ~/.claude/projects/*/*.jsonl and ~/.codex/sessions/**/*.jsonl. Read-only: no network, writes nothing,\n\
needs no bank. Prompt and reply text is never printed; commands appear only as redacted 60-character snippets.\n\
1 risky commands shell commands the starter tripwires would have warned about, by title\n\
2 corrections how often you corrected the agent, and how often the next message corrected it again\n\
3 memory files what CLAUDE.md and AGENTS.md cost across the prompts in the window\n\
4 next steps runnable lines\n\
--days N window in days, by file modification time (default 30)\n\
--json the counts and the same snippets as JSON\n\
--share print only a short plain-text summary (at most 280 characters); it is never uploaded";
const REPO: &str = "https://github.com/koscak-labs/instinct";
const SNIPPET: usize = 60;
const EXAMPLES: usize = 3;
const MIN_FOR_RATIO: u32 = 20;
#[derive(Default, Clone)]
pub struct Group {
pub title: String,
pub count: u32,
pub examples: Vec<String>,
}
#[derive(Default, Clone, Copy)]
pub struct Pairs {
pub n: u32,
pub repeated: u32,
}
impl Pairs {
pub fn rate(&self) -> Option<f64> {
(self.n > 0).then(|| self.repeated as f64 / self.n as f64)
}
}
#[derive(Default)]
pub struct Report {
pub days: u64,
pub files: u32,
pub claude_files: u32,
pub codex_files: u32,
pub skipped_old: u32,
pub unreadable: u32,
pub prompts: u32,
pub claude_prompts: u32,
pub codex_prompts: u32,
pub commands: u32,
pub flagged: u32,
pub groups: Vec<Group>,
pub corrections: u32,
pub after_correction: Pairs,
pub after_other: Pairs,
pub memory: Vec<(String, usize)>,
pub memory_tokens_in_window: u64,
pub memory_user_tokens: u64,
pub folders: Vec<(PathBuf, u32, u32)>,
pub projects: Vec<(String, u64, u32)>,
pub projects_with_memory: u32,
pub starter: Option<(usize, usize)>,
}
impl Report {
pub fn ratio(&self) -> Option<f64> {
let (a, b) = (self.after_correction, self.after_other);
if a.n < MIN_FOR_RATIO || b.n < MIN_FOR_RATIO {
return None;
}
let base = b.rate()?;
(base > 0.0).then(|| a.rate().unwrap_or(0.0) / base)
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum Harness {
Claude,
Codex,
}
fn secret_key(name: &str) -> bool {
let n = name.to_lowercase();
["key", "token", "secret", "passw", "pwd", "credential", "auth"].iter().any(|s| n.contains(s))
}
fn token_like(v: &str) -> bool {
let n = v.chars().count();
let digit = v.chars().any(|c| c.is_ascii_digit());
if n >= 16 && digit && v.chars().all(|c| c.is_ascii_hexdigit()) {
return true;
}
n >= 24
&& !v.starts_with(['/', '.', '~'])
&& digit
&& v.chars().any(|c| c.is_ascii_uppercase())
&& v.chars().any(|c| c.is_ascii_lowercase())
&& v.chars().all(|c| c.is_ascii_alphanumeric() || "+/_=-".contains(c))
}
pub fn redact_snippet(cmd: &str) -> String {
let head: String = cmd.chars().take(2000).collect();
let first = mine::redact(&url_userinfo(&head)).0.replace("[REDACTED]", "***");
let mut out = String::with_capacity(first.len());
for tok in first.split_inclusive(char::is_whitespace) {
let word = tok.trim_end();
let ws = &tok[word.len()..];
out.push_str(&redact_word(word));
out.push_str(ws);
}
out
}
fn url_userinfo(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find("://") {
let (head, tail) = rest.split_at(i + 3);
out.push_str(head);
let end = tail.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '"' | '\'' | '`')).unwrap_or(tail.len());
match tail[..end].rfind('@').filter(|at| tail[..*at].contains(':')) {
Some(at) => {
out.push_str("***");
out.push_str(&tail[at..end]);
}
None => out.push_str(&tail[..end]),
}
rest = &tail[end..];
}
out.push_str(rest);
out
}
fn redact_word(word: &str) -> String {
let edge = |c: char| matches!(c, '"' | '\'' | '`' | ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}');
let core = word.trim_matches(edge);
if core.is_empty() || core.contains("***") {
return word.to_string();
}
let at = word.find(core).unwrap_or(0);
if let Some(rest) = core.strip_prefix("-p").filter(|r| !r.is_empty() && !r.starts_with('-')) {
const FLAGS: [&str; 6] = ["edantic", "thread", "ipe", "g", "ackage", "rofile"];
let name = core.trim_start_matches('-');
if !FLAGS.iter().any(|s| name.strip_prefix('p') == Some(*s)) && !rest.contains('=') {
return format!("{}-p***{}", &word[..at], &word[at + core.len()..]);
}
}
let (lead, tail) = (&word[..at], &word[at + core.len()..]);
if let Some((name, value)) = core.split_once('=') {
let named = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
if (named && secret_key(name) && !value.is_empty()) || token_like(value.trim_matches(edge)) {
return format!("{lead}{name}=***{tail}");
}
return word.to_string();
}
if token_like(core) {
return format!("{lead}***{tail}");
}
word.to_string()
}
pub fn snippet(cmd: &str) -> String {
mine::clip(&redact_snippet(cmd), SNIPPET)
}
fn roots() -> Vec<(PathBuf, Harness)> {
outcomes::default_roots()
.into_iter()
.filter_map(|r| match r.file_name().and_then(|n| n.to_str()) {
Some("projects") => Some((r, Harness::Claude)),
Some("sessions") => Some((r, Harness::Codex)),
_ => None,
})
.collect()
}
fn modified_secs(p: &Path) -> Option<u64> {
fs::metadata(p).and_then(|m| m.modified()).ok()?.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs())
}
fn files_in(root: &Path, harness: Harness) -> Vec<PathBuf> {
let mut out = Vec::new();
match harness {
Harness::Claude => {
let Ok(rd) = fs::read_dir(root) else { return out };
for d in rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
if let Ok(files) = fs::read_dir(&d) {
out.extend(files.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "jsonl")));
}
}
}
Harness::Codex => mine::collect(root, &mut out, 1),
}
out.sort();
out
}
struct Matcher {
title: String,
tags: String,
}
fn matchers() -> Vec<Matcher> {
starter::pack_matchers()
.into_iter()
.filter(|(_, tags)| tripwire::has_cmd(tags))
.map(|(title, tags)| Matcher { title, tags })
.collect()
}
fn tripwire_title<'a>(ms: &'a [Matcher], cmd: &str) -> Option<&'a str> {
let w = tripwire::words(cmd);
let mut best: Option<(usize, &str)> = None;
for m in ms {
if let Some(n) = tripwire::best_match(&m.tags, &w) {
if best.is_none_or(|(b, _)| n > b) {
best = Some((n, &m.title));
}
}
}
best.map(|(_, t)| t)
}
fn shell_command(e: &mine::Ev, harness: Harness) -> Option<&str> {
let c = e.cmd.trim();
if c.is_empty() || e.kind != Kind::ToolUse {
return None;
}
(harness == Harness::Codex || e.text == "Bash").then_some(c)
}
pub fn scan(roots: &[(PathBuf, Harness)], days: u64, since: u64) -> Report {
let mut r = Report { days, ..Default::default() };
let ms = matchers();
let mut folders: Vec<(PathBuf, u32, u32)> = Vec::new();
let mut groups: Vec<Group> = Vec::new();
for (root, harness) in roots {
for path in files_in(root, *harness) {
if modified_secs(&path).is_none_or(|m| m < since) {
r.skipped_old += 1;
continue;
}
let Ok(evs) = mine::read_events_with(&path, true) else {
r.unreadable += 1;
continue;
};
r.files += 1;
match harness {
Harness::Claude => r.claude_files += 1,
Harness::Codex => r.codex_files += 1,
}
let mut last: Option<(bool, bool)> = None;
let mut file_prompts = 0u32;
for e in &evs {
match e.kind {
Kind::User => {
let corr = corrections::correction(&e.text);
r.prompts += 1;
file_prompts += 1;
match harness {
Harness::Claude => r.claude_prompts += 1,
Harness::Codex => r.codex_prompts += 1,
}
if corr {
r.corrections += 1;
}
if let Some((prev, true)) = last {
let p = if prev { &mut r.after_correction } else { &mut r.after_other };
p.n += 1;
p.repeated += corr as u32;
}
last = Some((corr, false));
}
Kind::Assistant | Kind::ToolUse => {
if let Some((_, acted)) = last.as_mut() {
*acted = true;
}
if let Some(cmd) = shell_command(e, *harness) {
r.commands += 1;
if let Some(title) = tripwire_title(&ms, cmd) {
r.flagged += 1;
let i = groups.iter().position(|g| g.title == title).unwrap_or_else(|| {
groups.push(Group { title: title.to_string(), ..Default::default() });
groups.len() - 1
});
let g = &mut groups[i];
g.count += 1;
if g.examples.len() < EXAMPLES {
let s = snippet(cmd);
if !g.examples.contains(&s) {
g.examples.push(s);
}
}
}
}
}
Kind::ToolResult => {}
}
}
if let Some(cwd) = file_cwd(&path) {
let i = folders.iter().position(|f| same_dir(&f.0, &cwd)).unwrap_or_else(|| {
folders.push((cwd, 0, 0));
folders.len() - 1
});
match harness {
Harness::Claude => folders[i].1 += file_prompts,
Harness::Codex => folders[i].2 += file_prompts,
}
}
}
}
for (cwd, claude, codex) in &folders {
r.folders.push((cwd.clone(), *claude, *codex));
}
groups.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.title.cmp(&b.title)));
r.groups = groups;
r
}
fn memory_files() -> Vec<(Harness, String, usize)> {
let home = home_dir();
let mut out = Vec::new();
for (root, harness) in roots() {
let (name, dir) = match harness {
Harness::Claude => ("CLAUDE.md", root.parent().map(Path::to_path_buf)),
Harness::Codex => ("AGENTS.md", root.parent().map(Path::to_path_buf)),
};
let mut candidates: Vec<PathBuf> = dir.into_iter().map(|d| d.join(name)).collect();
candidates.extend(home.iter().map(|h| h.join(name)));
candidates.dedup();
for c in candidates {
if let Ok(m) = fs::metadata(&c) {
if m.is_file() {
out.push((harness, name.to_string(), m.len() as usize));
}
}
}
}
out
}
fn file_cwd(path: &Path) -> Option<PathBuf> {
let file = fs::File::open(path).ok()?;
let mut reader = std::io::BufReader::new(file);
let mut buf = Vec::new();
for _ in 0..60 {
buf.clear();
if reader.read_until(b'\n', &mut buf).ok()? == 0 {
break;
}
let line = String::from_utf8_lossy(&buf);
if !line.contains("\"cwd\"") {
continue;
}
let Ok(j) = parse_json(line.trim()) else { continue };
let found = j
.get("cwd")
.or_else(|| j.get("payload").and_then(|p| p.get("cwd")))
.and_then(Json::as_str)
.filter(|c| !c.is_empty());
if let Some(c) = found {
return Some(PathBuf::from(c));
}
}
None
}
fn home_dir() -> Option<PathBuf> {
let (first, second) = if cfg!(windows) { ("USERPROFILE", "HOME") } else { ("HOME", "USERPROFILE") };
std::env::var_os(first)
.filter(|v| !v.is_empty())
.or_else(|| std::env::var_os(second).filter(|v| !v.is_empty()))
.map(PathBuf::from)
}
fn same_dir(a: &Path, b: &Path) -> bool {
if cfg!(windows) {
let n = |p: &Path| p.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase();
n(a) == n(b)
} else {
a == b
}
}
fn tilde(p: &Path, home: Option<&Path>) -> String {
let rest = home.and_then(|h| {
if same_dir(p, h) {
return Some(PathBuf::new());
}
let (mut pc, mut hc) = (p.components(), h.components());
loop {
let Some(a) = hc.next() else { return Some(pc.as_path().to_path_buf()) };
match pc.next() {
Some(b) if same_dir(Path::new(a.as_os_str()), Path::new(b.as_os_str())) => {}
_ => return None,
}
}
});
match rest {
Some(r) if r.as_os_str().is_empty() => "~".to_string(),
Some(r) => {
let parts: Vec<String> = r.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
format!("~/{}", parts.join("/"))
}
None => p.display().to_string(),
}
}
fn add_memory_cost(r: &mut Report) {
for (harness, name, bytes) in memory_files() {
let tokens = audit::tokens_of(bytes);
let prompts = if harness == Harness::Claude { r.claude_prompts } else { r.codex_prompts };
r.memory_tokens_in_window += tokens as u64 * prompts as u64;
r.memory.push((name, tokens));
}
r.memory_user_tokens = r.memory_tokens_in_window;
let home = home_dir();
let mut projects: Vec<(String, u64, u32)> = Vec::new();
for (cwd, claude, codex) in &r.folders {
if !cwd.is_dir() || home.as_ref().is_some_and(|h| same_dir(h, cwd)) {
continue;
}
let size = |name: &str| fs::metadata(cwd.join(name)).ok().filter(|m| m.is_file()).map(|m| audit::tokens_of(m.len() as usize) as u64);
let total = size("CLAUDE.md").unwrap_or(0) * *claude as u64 + size("AGENTS.md").unwrap_or(0) * *codex as u64;
if total > 0 {
projects.push((tilde(cwd, home.as_deref()), total, claude + codex));
}
}
projects.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
r.projects_with_memory = projects.len() as u32;
r.memory_tokens_in_window += projects.iter().map(|p| p.1).sum::<u64>();
projects.truncate(5);
r.projects = projects;
}
fn commas(n: u64) -> String {
let s = n.to_string();
let mut out = String::new();
for (i, c) in s.chars().enumerate() {
if i > 0 && (s.len() - i) % 3 == 0 {
out.push(',');
}
out.push(c);
}
out
}
fn noun(n: u64, one: &str, many: &str) -> String {
format!("{} {}", commas(n), if n == 1 { one } else { many })
}
fn times(n: u32) -> String {
match n {
1 => "once".to_string(),
2 => "twice".to_string(),
n => format!("{} times", commas(n as u64)),
}
}
fn span(days: u64) -> String {
if days == 1 { "day".to_string() } else { format!("{days} days") }
}
fn pct(x: Option<f64>) -> String {
x.map_or("n/a".to_string(), |v| format!("{:.1}%", v * 100.0))
}
pub fn share_text(r: &Report) -> String {
let mut s = if r.commands == 0 {
format!("My coding agent, last {}: I corrected it {}", span(r.days), times(r.corrections))
} else {
format!(
"My coding agent, last {}: {} of {} would have drawn an Instinct tripwire warning; I corrected it {}",
span(r.days), r.flagged, noun(r.commands as u64, "shell command", "shell commands"), times(r.corrections)
)
};
s.push_str(&format!(". `instinct scan` {REPO}"));
if s.chars().count() > 280 {
s = format!("Coding agent, last {}: {}, {}. `instinct scan` {REPO}", span(r.days), noun(r.flagged as u64, "risky command", "risky commands"), noun(r.corrections as u64, "correction", "corrections"));
}
s.chars().take(280).collect()
}
fn next_steps(r: &Report) -> Vec<String> {
let mut v = Vec::new();
match r.starter {
Some((all, have)) if have >= all => v.push(format!(
"Your bank already holds all {all} starter tripwires; `instinct doctor` checks the hooks that deliver them."
)),
Some((all, have)) => v.push(format!(
"Your bank holds {have} of {all} starter tripwires: `instinct starter --apply` adds the rest."
)),
None => v.push("No bank yet: `instinct starter --apply` banks the starter tripwires (run `instinct starter` first to read them).".into()),
}
if r.corrections > 0 {
v.push(format!("`instinct mine --since {}d` turns your corrections into lesson candidates (a dry run).", r.days));
}
if r.memory_tokens_in_window > 0 {
v.push("`instinct audit ~/.claude/CLAUDE.md` grades the memory file and measures the same rules behind Instinct.".into());
}
v.truncate(3);
v
}
pub fn render_text(r: &Report, secs: f64) -> String {
let mut o = String::new();
o.push_str(&format!("instinct scan: the last {} (read-only, nothing leaves this machine)\n", span(r.days)));
if r.files == 0 {
o.push_str(&format!(
"\nNo Claude Code or Codex transcripts changed in the last {} (looked in ~/.claude/projects and ~/.codex/sessions).\n\
Nothing to report. Run it again after a few sessions, or widen the window with --days.\n",
span(r.days)
));
o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
return o;
}
o.push_str(&format!(
"Read {} ({} Claude Code, {} Codex): {}, {}.\n",
noun(r.files as u64, "transcript", "transcripts"),
r.claude_files,
r.codex_files,
noun(r.prompts as u64, "prompt", "prompts"),
noun(r.commands as u64, "shell command", "shell commands")
));
if r.commands == 0 {
o.push_str("\n1. Risky commands: No shell commands in the window.\n");
} else {
o.push_str(&format!("\n1. Risky commands: {} of {} would have drawn a tripwire warning\n", r.flagged, commas(r.commands as u64)));
}
if r.commands > 0 && r.groups.is_empty() {
o.push_str(" None matched the starter tripwires.\n");
}
for g in &r.groups {
o.push_str(&format!(" {:>4} {}\n", g.count, g.title));
for e in &g.examples {
o.push_str(&format!(" {e}\n"));
}
}
o.push_str(&format!(
"\n2. Corrections: {} of {} told the agent it went wrong ({})\n",
r.corrections,
noun(r.prompts as u64, "prompt", "prompts"),
pct(if r.prompts > 0 { Some(r.corrections as f64 / r.prompts as f64) } else { None })
));
let (a, b) = (r.after_correction, r.after_other);
o.push_str(&format!(
" Next message corrected again, after a correction: {}/{} {}\n",
a.repeated, a.n, pct(a.rate())
));
o.push_str(&format!(
" Next message corrected, after any other message: {}/{} {}\n",
b.repeated, b.n, pct(b.rate())
));
match r.ratio() {
Some(x) => o.push_str(&format!(" Ratio: {x:.1}x more likely to be corrected again right after a correction.\n")),
None => o.push_str(&format!(" No ratio yet: it needs at least {MIN_FOR_RATIO} reply pairs in each group.\n")),
}
o.push_str(" Only clear corrections are counted, so these numbers are a floor, not a measurement.\n");
o.push_str("\n3. Memory files\n");
if r.memory.is_empty() && r.projects.is_empty() {
o.push_str(" No CLAUDE.md or AGENTS.md at user level or in the project folders of these sessions.\n");
} else {
for (name, t) in &r.memory {
o.push_str(&format!(" {name} (user level): about {} on every prompt\n", noun(*t as u64, "token", "tokens")));
}
if !r.memory.is_empty() {
o.push_str(&format!(
" User-level files across {} ({} Claude Code, {} Codex): about {}.\n",
noun(r.prompts as u64, "prompt", "prompts"),
commas(r.claude_prompts as u64),
commas(r.codex_prompts as u64),
noun(r.memory_user_tokens, "token", "tokens")
));
}
if !r.projects.is_empty() {
o.push_str(&format!(
" Project files, top {} of {} (tokens x that project's prompts):\n",
r.projects.len(),
noun(r.projects_with_memory as u64, "project", "projects")
));
for (path, tokens, prompts) in &r.projects {
o.push_str(&format!(" {:>10} {path} ({})\n", commas(*tokens), noun(*prompts as u64, "prompt", "prompts")));
}
}
o.push_str(&format!(
" Overall: about {} of memory files sent in the window (an estimate, bytes / 4).\n",
noun(r.memory_tokens_in_window, "token", "tokens")
));
}
o.push_str("\n4. Next steps\n");
for l in next_steps(r) {
o.push_str(&format!(" {l}\n"));
}
if r.skipped_old > 0 || r.unreadable > 0 {
o.push_str(&format!(
"\n({} skipped as older than the window, {} unreadable)\n",
noun(r.skipped_old as u64, "file", "files"),
r.unreadable
));
}
o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
o
}
fn f(x: Option<f64>) -> String {
x.map_or("null".to_string(), |v| format!("{v:.4}"))
}
pub fn render_json(r: &Report, secs: f64) -> String {
let groups: Vec<String> = r
.groups
.iter()
.map(|g| {
let ex: Vec<String> = g.examples.iter().map(|e| format!("\"{}\"", escape_json(e))).collect();
format!("{{\"title\":\"{}\",\"count\":{},\"examples\":[{}]}}", escape_json(&g.title), g.count, ex.join(","))
})
.collect();
let pairs = |p: Pairs| format!("{{\"replies\":{},\"repeated\":{},\"rate\":{}}}", p.n, p.repeated, f(p.rate()));
let mem: Vec<String> =
r.memory.iter().map(|(n, t)| format!("{{\"file\":\"{}\",\"tokens_per_prompt\":{t}}}", escape_json(n))).collect();
let proj: Vec<String> = r
.projects
.iter()
.map(|(p, t, n)| format!("{{\"path\":\"{}\",\"tokens_in_window\":{t},\"prompts\":{n}}}", escape_json(p)))
.collect();
let next: Vec<String> = next_steps(r).iter().map(|l| format!("\"{}\"", escape_json(l))).collect();
format!(
"{{\"days\":{},\"files\":{{\"scanned\":{},\"claude_code\":{},\"codex\":{},\"skipped_old\":{},\"unreadable\":{}}},\
\"prompts\":{},\"commands\":{},\
\"risky\":{{\"flagged\":{},\"groups\":[{}]}},\
\"corrections\":{{\"count\":{},\"after_correction\":{},\"after_other\":{},\"ratio\":{}}},\
\"memory\":{{\"files\":[{}],\"user_tokens_in_window\":{},\"projects_with_memory\":{},\"top_projects\":[{}],\"tokens_in_window\":{}}},\
\"next\":[{}],\"share\":\"{}\",\"elapsed_ms\":{}}}",
r.days,
r.files,
r.claude_files,
r.codex_files,
r.skipped_old,
r.unreadable,
r.prompts,
r.commands,
r.flagged,
groups.join(","),
r.corrections,
pairs(r.after_correction),
pairs(r.after_other),
f(r.ratio()),
mem.join(","),
r.memory_user_tokens,
r.projects_with_memory,
proj.join(","),
r.memory_tokens_in_window,
next.join(","),
escape_json(&share_text(r)),
(secs * 1000.0).round() as u64
)
}
pub fn run(argv: &[String]) -> Result<(), String> {
let (mut days, mut json, mut share) = (30u64, false, false);
let mut it = argv.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--json" => json = true,
"--share" => share = true,
"--days" => {
days = it
.next()
.and_then(|v| v.parse().ok())
.filter(|d| *d > 0)
.ok_or("scan: --days needs a whole number of days, 1 or more")?
}
"--help" | "-h" => {
println!("{SCAN_HELP}");
return Ok(());
}
other => return Err(format!("scan: unknown argument {other}\n\n{SCAN_HELP}")),
}
}
let started = std::time::Instant::now();
let since = now_secs().saturating_sub(days.saturating_mul(86_400));
let mut r = scan(&roots(), days, since);
add_memory_cost(&mut r);
r.starter = starter::banked_in_default();
let secs = started.elapsed().as_secs_f64();
if json {
println!("{}", render_json(&r, secs));
} else if share {
println!("{}", share_text(&r));
} else {
print!("{}", render_text(&r, secs));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redaction_hides_tokens_and_keeps_commands() {
let s = redact_snippet("curl -H 'Authorization: Bearer abcdef0123456789abcdef' https://x.test");
assert!(!s.contains("abcdef0123456789abcdef"), "{s}");
let s = redact_snippet("API_KEY=abc deploy.sh");
assert_eq!(s, "API_KEY=*** deploy.sh");
let s = redact_snippet("export GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789");
assert!(s.contains("GITHUB_TOKEN=***") && !s.contains("ghp_"), "{s}");
let s = redact_snippet("docker login -p sk-abcdefghijklmnopqrstuv");
assert!(!s.contains("sk-abc"), "{s}");
let s = redact_snippet("git checkout 3f2a9c1d4b5e6f708192a3b4c5d6e7f801234567");
assert_eq!(s, "git checkout ***");
let s = redact_snippet("echo QUtJQTEyMzQ1Njc4OTBhYmNkZWZnaGlqa2xt");
assert_eq!(s, "echo ***");
assert_eq!(redact_snippet("rm -rf ./target/debug/build-output"), "rm -rf ./target/debug/build-output");
assert_eq!(redact_snippet("cargo build --release --locked"), "cargo build --release --locked");
}
#[test]
fn url_credentials_become_stars() {
assert_eq!(redact_snippet("git clone https://alice:s3cr3t@github.com/o/r.git"), "git clone https://***@github.com/o/r.git");
assert_eq!(redact_snippet("psql postgres://app:hunter22@db.internal:5432/prod"), "psql postgres://***@db.internal:5432/prod");
assert_eq!(redact_snippet("curl http://a:b@h1/x https://c:d@h2/y"), "curl http://***@h1/x https://***@h2/y");
assert_eq!(redact_snippet("curl 'https://u:p@host.test/a?b=c'"), "curl 'https://***@host.test/a?b=c'");
assert_eq!(redact_snippet("git fetch https://u:p@ss@host.test/r"), "git fetch https://***@host.test/r");
assert_eq!(redact_snippet("git clone ssh://git@github.com/o/r.git"), "git clone ssh://git@github.com/o/r.git");
assert_eq!(redact_snippet("curl https://example.com/a@b:c"), "curl https://example.com/a@b:c");
}
#[test]
fn password_flags_and_variables_become_stars() {
assert_eq!(redact_snippet("mysql -psupersecret -h db"), "mysql -p*** -h db");
assert_eq!(redact_snippet("mysql -u root --password=topsecret1 db"), "mysql -u root --password=*** db");
assert_eq!(redact_snippet("PGPASSWORD=pgsecret1 psql -c 'select 1'"), "PGPASSWORD=*** psql -c 'select 1'");
assert_eq!(redact_snippet("MYSQL_PWD=abcd1234 mysqldump db"), "MYSQL_PWD=*** mysqldump db");
assert_eq!(redact_snippet("gcc -pedantic -pthread -pipe -o a a.c"), "gcc -pedantic -pthread -pipe -o a a.c");
assert_eq!(redact_snippet("cargo test -p instinct-cli"), "cargo test -p instinct-cli");
assert_eq!(redact_snippet("mkdir -p a/b"), "mkdir -p a/b");
}
#[test]
fn snippet_is_at_most_60_chars() {
let s = snippet(&format!("git push --force {}", "origin/very-long-branch-name-".repeat(5)));
assert!(s.chars().count() <= SNIPPET, "{s}");
assert!(s.starts_with("git push --force"));
}
#[test]
fn share_fits_280_even_with_huge_numbers() {
let r = Report {
days: 3650,
commands: u32::MAX,
flagged: u32::MAX,
corrections: u32::MAX,
after_correction: Pairs { n: u32::MAX, repeated: u32::MAX },
after_other: Pairs { n: u32::MAX, repeated: u32::MAX },
..Default::default()
};
let s = share_text(&r);
assert!(s.chars().count() <= 280, "{} {s}", s.chars().count());
assert!(s.contains(REPO));
}
#[test]
fn ratio_needs_twenty_each() {
let mut r = Report {
after_correction: Pairs { n: 19, repeated: 10 },
after_other: Pairs { n: 100, repeated: 10 },
..Default::default()
};
assert!(r.ratio().is_none());
r.after_correction = Pairs { n: 20, repeated: 10 };
assert!((r.ratio().unwrap() - 5.0).abs() < 1e-9);
}
}