use super::*;
use mine::Kind;
pub const SCAN_HELP: &str = "usage: instinct scan [--days N] [--json | --format 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, and what `instinct fix` would have rewritten, by rule\n\
2 corrections how often you corrected the agent, how often the next message corrected it again, failing commands retried the same way 3+ times, and done-claims with nothing run since the last change\n\
3 memory files what CLAUDE.md and AGENTS.md cost across the prompts in the window\n\
4 waiting wait loops that match themselves, guess a PID or have no deadline, and the wall time\n\
they took where the transcript lets it be measured (shown when there are any)\n\
5 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 (also --format 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)]
pub struct Replay {
pub unique: u32,
pub rewritten_unique: u32,
pub rewritten_runs: u32,
pub rules: Vec<(String, u32)>,
pub warned_unique: u32,
pub warned_runs: u32,
pub titles: Vec<(String, u32)>,
pub samples: Vec<(String, String, 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)>,
pub retried: u32,
pub claimed_done: u32,
pub waits: [WaitClass; 3],
pub wait_all: WaitClass,
pub replay: Replay,
pub claude_commands: u32,
pub codex_commands: u32,
}
const WAIT_IDS: [&str; 3] = ["wait-pgrep-self-match", "wait-pid-from-pgrep", "wait-no-deadline"];
const WAIT_NAMES: [&str; 3] = [
"pgrep -f loop that matches its own shell",
"tail --pid or wait on a PID guessed with pgrep",
"poll loop with no deadline and no counter",
];
#[derive(Default, Clone)]
pub struct WaitClass {
pub count: u32,
pub measured: u32,
pub measured_background: u32,
pub secs: u64,
pub longest: u64,
pub examples: Vec<String>,
}
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)
}
pub(crate) 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()
}
pub(crate) 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())
}
pub(crate) 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,
wait: Option<usize>,
}
fn all_matchers() -> Vec<Matcher> {
starter::pack_matchers()
.into_iter()
.filter(|(_, _, tags)| tripwire::has_cmd(tags))
.map(|(id, title, tags)| Matcher { title, tags, wait: WAIT_IDS.iter().position(|w| *w == id.as_str()) })
.collect()
}
fn wait_matchers() -> Vec<String> {
let all = starter::pack_matchers();
WAIT_IDS.iter().map(|id| all.iter().find(|(i, _, _)| i == id).map(|(_, _, t)| t.clone()).unwrap_or_default()).collect()
}
fn wait_classes(ws: &[String], cmd: &str) -> u8 {
let w = tripwire::command_words(cmd);
ws.iter().enumerate().filter(|(_, tags)| tripwire::best_match(tags, &w).is_some()).fold(0, |m, (i, _)| m | 1 << i)
}
struct Pending {
classes: u8,
start: u64,
background: bool,
done: bool,
}
fn tripwire_titles<'a>(all: &'a [Matcher], cmd: &str) -> (Option<&'a str>, Option<&'a str>, u8) {
let w = tripwire::command_words(cmd);
let (mut guard, mut risky): (Option<(usize, &str)>, Option<(usize, &str)>) = (None, None);
let mut waits = 0u8;
for m in all {
if let Some(n) = tripwire::best_match(&m.tags, &w) {
if guard.is_none_or(|(b, _)| n > b) {
guard = Some((n, &m.title));
}
match m.wait {
Some(i) => waits |= 1 << i,
None => {
if risky.is_none_or(|(b, _)| n > b) {
risky = Some((n, &m.title));
}
}
}
}
}
(risky.map(|(_, t)| t), guard.map(|(_, t)| t), waits)
}
const REPLAY_MAX_LEN: usize = 4000;
const REPLAY_SAMPLES: usize = 8;
fn changed_window(old: &str, new: &str) -> (String, String) {
let (a, b): (Vec<char>, Vec<char>) = (old.chars().collect(), new.chars().collect());
let mut s = 0;
while s < a.len() && s < b.len() && a[s] == b[s] {
s += 1;
}
let mut e = 0;
while e < a.len() - s && e < b.len() - s && a[a.len() - 1 - e] == b[b.len() - 1 - e] {
e += 1;
}
let cut = |x: &[char], end: usize| -> String {
let from = s.saturating_sub(30);
let to = (end + 20).min(x.len());
x[from.min(to)..to].iter().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")
};
(cut(&a, a.len() - e), cut(&b, b.len() - e))
}
struct Row {
risky: Option<String>,
guard: Option<String>,
rewrite: Option<(String, Vec<&'static str>)>,
}
fn replay(seen: &std::collections::BTreeMap<String, (u32, usize)>, all: &[Matcher]) -> (Replay, Vec<Group>, u32) {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut cmds: Vec<(&str, u32, usize)> = seen.iter().map(|(c, (n, i))| (c.as_str(), *n, *i)).collect();
cmds.sort_by_key(|c| c.2);
let next = AtomicUsize::new(0);
let rows: Vec<std::sync::Mutex<Option<Row>>> = cmds.iter().map(|_| std::sync::Mutex::new(None)).collect();
let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 16);
std::thread::scope(|s| {
for _ in 0..threads {
s.spawn(|| loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some((cmd, _, _)) = cmds.get(i) else { break };
let (risky_title, guard_title, waits) = tripwire_titles(all, cmd);
let risky = if waits == 0 { risky_title.map(str::to_string) } else { None };
let short = cmd.encode_utf16().count() <= REPLAY_MAX_LEN;
let guard = if short { guard_title.map(str::to_string) } else { None };
let rewrite = if short {
fix::rewrite(cmd, &|_| true).filter(|(new, _)| new != cmd).map(|(new, fired)| (new, fired.iter().map(|a| a.rule).collect()))
} else {
None
};
*rows[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(Row { risky, guard, rewrite });
});
}
});
let mut rp = Replay { unique: seen.len() as u32, ..Default::default() };
let mut groups: Vec<Group> = Vec::new();
let mut flagged = 0u32;
let mut rules: std::collections::BTreeMap<String, u32> = Default::default();
let mut titles: std::collections::BTreeMap<String, u32> = Default::default();
let mut rewrites: Vec<(u32, &str, String, String)> = Vec::new();
for ((cmd, n, _), row) in cmds.iter().zip(rows) {
let Some(row) = row.into_inner().unwrap_or_else(|e| e.into_inner()) else { continue };
if let Some(t) = &row.risky {
flagged += n;
let i = groups.iter().position(|g| &g.title == t).unwrap_or_else(|| {
groups.push(Group { title: t.clone(), ..Default::default() });
groups.len() - 1
});
let g = &mut groups[i];
g.count += n;
if g.examples.len() < EXAMPLES {
let s = snippet(cmd);
if !g.examples.contains(&s) {
g.examples.push(s);
}
}
}
if let Some(t) = &row.guard {
rp.warned_unique += 1;
rp.warned_runs += n;
*titles.entry(t.chars().take(70).collect()).or_default() += n;
}
if let Some((new, names)) = row.rewrite {
rp.rewritten_unique += 1;
rp.rewritten_runs += n;
for r in &names {
*rules.entry((*r).to_string()).or_default() += n;
}
rewrites.push((*n, cmd, new, names.join(",")));
}
}
let by_runs = |m: std::collections::BTreeMap<String, u32>| {
let mut v: Vec<(String, u32)> = m.into_iter().collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
v
};
rp.rules = by_runs(rules);
rp.titles = by_runs(titles);
rewrites.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
for (_, old, new, names) in rewrites.into_iter().filter(|r| r.1.chars().count() <= 2000 && r.2.chars().count() <= 2000).take(REPLAY_SAMPLES) {
let (a, b) = changed_window(&redact_snippet(old), &redact_snippet(&new));
rp.samples.push((names, a, b));
}
groups.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.title.cmp(&b.title)));
(rp, groups, flagged)
}
fn nested_claude_files(root: &Path) -> Vec<PathBuf> {
fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
let Ok(rd) = fs::read_dir(dir) else { return };
for p in rd.flatten().map(|e| e.path()) {
if p.is_dir() {
walk(&p, depth + 1, out);
} else if depth >= 2 && p.extension().is_some_and(|e| e == "jsonl") {
out.push(p);
}
}
}
let mut out = Vec::new();
walk(root, 0, &mut out);
out.sort();
out
}
fn codex_command(e: &mine::Ev) -> Option<&str> {
let c = e.cmd.trim();
(!c.is_empty() && e.kind == Kind::ToolUse).then_some(c)
}
fn raw_commands_in(text: &str) -> Vec<String> {
let mut out = Vec::new();
for line in text.lines() {
if !line.contains("\"command\"") {
continue;
}
let Ok(j) = parse_json(line) else { continue };
let content = j.get("message").and_then(|m| m.get("content")).or_else(|| j.get("payload").and_then(|p| p.get("content")));
if let Some(Json::Arr(items)) = content {
for b in items {
let is_bash = b.get("type").and_then(Json::as_str) == Some("tool_use") && b.get("name").and_then(Json::as_str) == Some("Bash");
if let (true, Some(c)) = (is_bash, b.get("input").and_then(|i| i.get("command")).and_then(Json::as_str)) {
out.push(c.to_string());
}
}
}
}
out
}
fn add_wait(dst: &mut WaitClass, src: &WaitClass) {
dst.count += src.count;
dst.measured += src.measured;
dst.measured_background += src.measured_background;
dst.secs += src.secs;
dst.longest = dst.longest.max(src.longest);
if dst.examples.is_empty() {
dst.examples.extend(src.examples.iter().take(1).cloned());
}
}
#[derive(Default)]
struct FileStats {
read: bool,
prompts: u32,
corrections: u32,
after_correction: Pairs,
after_other: Pairs,
cmds: Vec<String>,
waits: [WaitClass; 3],
wait_all: WaitClass,
retried: u32,
claimed_done: u32,
cwd: Option<PathBuf>,
}
fn count_wait(f: &mut FileStats, c: u8, cmd: &str) {
if c == 0 {
return;
}
f.wait_all.count += 1;
for i in (0..3).filter(|i| c >> i & 1 == 1) {
let w = &mut f.waits[i];
w.count += 1;
if w.examples.is_empty() {
w.examples.push(snippet(cmd));
}
}
}
fn analyze(path: &Path, harness: Harness, commands_only: bool, ws: &[String]) -> FileStats {
let mut f = FileStats::default();
let evs = if commands_only {
None
} else {
match mine::read_events_timed(path) {
Ok(evs) => Some(evs),
Err(_) => return f,
}
};
f.read = true;
if harness == Harness::Claude {
let Ok(bytes) = fs::read(path) else { return f };
let text = String::from_utf8_lossy(&bytes);
f.cmds = raw_commands_in(&text);
for c in &f.cmds.clone() {
count_wait(&mut f, wait_classes(ws, c), c);
}
if evs.is_some() {
let g = mine::gate_events(&text);
f.retried = gates::retried_forms(&g);
f.claimed_done = gates::run_gate(&g, None).len() as u32;
}
}
let Some(evs) = evs else { return f };
let mut last: Option<(bool, bool)> = None;
let mut pending: HashMap<String, Pending> = HashMap::new();
for e in &evs {
match e.kind {
Kind::User => {
let corr = corrections::correction(&e.text);
f.prompts += 1;
if corr {
f.corrections += 1;
}
if let Some((prev, true)) = last {
let p = if prev { &mut f.after_correction } else { &mut f.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;
}
let cmd = match harness {
Harness::Claude => (e.kind == Kind::ToolUse && e.text == "Bash").then_some(e.cmd.trim()).filter(|c| !c.is_empty()),
Harness::Codex => codex_command(e),
};
if let Some(cmd) = cmd {
let c = wait_classes(ws, cmd);
if harness == Harness::Codex {
f.cmds.push(cmd.to_string());
count_wait(&mut f, c, cmd);
}
if c != 0 && !e.id.is_empty() && e.ts > 0 {
pending.insert(e.id.clone(), Pending { classes: c, start: e.ts, background: e.bg == 1, done: false });
}
}
}
Kind::ToolResult => {
let Some(p) = pending.get_mut(&e.id) else { continue };
if p.done {
continue;
}
let end = |p: &mut Pending, f: &mut FileStats, background: bool| {
p.done = true;
if e.ts >= p.start {
let d = e.ts - p.start;
let (a, b) = (&mut f.wait_all, &mut f.waits);
for w in std::iter::once(a).chain(b.iter_mut().enumerate().filter(|(i, _)| p.classes >> i & 1 == 1).map(|(_, w)| w)) {
w.measured += 1;
w.measured_background += background as u32;
w.secs += d;
w.longest = w.longest.max(d);
}
}
};
match e.bg {
1 => p.background = true,
2 if p.background => end(p, &mut f, true),
0 if !p.background => end(p, &mut f, false),
_ => {}
}
}
}
}
f.cwd = file_cwd(path);
f
}
fn analyze_all(jobs: &[(PathBuf, Harness, bool)], ws: &[String]) -> Vec<FileStats> {
use std::sync::{atomic::AtomicUsize, Mutex};
let next = AtomicUsize::new(0);
let slots: Vec<Mutex<Option<FileStats>>> = jobs.iter().map(|_| Mutex::new(None)).collect();
let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 16);
std::thread::scope(|s| {
for _ in 0..threads {
s.spawn(|| loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let Some((path, harness, only)) = jobs.get(i) else { break };
*slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(analyze(path, *harness, *only, ws));
});
}
});
slots.into_iter().map(|m| m.into_inner().unwrap_or_else(|e| e.into_inner()).unwrap_or_default()).collect()
}
pub fn scan(roots: &[(PathBuf, Harness)], days: u64, since: u64) -> Report {
let mut r = Report { days, ..Default::default() };
let all = all_matchers();
let ws = wait_matchers();
let mut seen: std::collections::BTreeMap<String, (u32, usize)> = Default::default();
let mut folders: Vec<(PathBuf, u32, u32)> = Vec::new();
let mut jobs: Vec<(PathBuf, Harness, bool)> = 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;
} else {
jobs.push((path, *harness, false));
}
}
}
let top = jobs.len();
for (root, harness) in roots {
if *harness == Harness::Claude {
jobs.extend(nested_claude_files(root).into_iter().filter(|p| modified_secs(p).is_some_and(|m| m >= since)).map(|p| (p, Harness::Claude, true)));
}
}
let stats = analyze_all(&jobs, &ws);
for (i, (f, (_, harness, _))) in stats.into_iter().zip(&jobs).enumerate() {
if i < top {
if !f.read {
r.unreadable += 1;
continue;
}
r.files += 1;
match harness {
Harness::Claude => {
r.claude_files += 1;
r.claude_prompts += f.prompts;
}
Harness::Codex => {
r.codex_files += 1;
r.codex_prompts += f.prompts;
}
}
r.prompts += f.prompts;
r.corrections += f.corrections;
r.after_correction.n += f.after_correction.n;
r.after_correction.repeated += f.after_correction.repeated;
r.after_other.n += f.after_other.n;
r.after_other.repeated += f.after_other.repeated;
r.retried += f.retried;
r.claimed_done += f.claimed_done;
if let Some(cwd) = &f.cwd {
let k = folders.iter().position(|x| same_dir(&x.0, cwd)).unwrap_or_else(|| {
folders.push((cwd.clone(), 0, 0));
folders.len() - 1
});
match harness {
Harness::Claude => folders[k].1 += f.prompts,
Harness::Codex => folders[k].2 += f.prompts,
}
}
}
for cmd in &f.cmds {
r.commands += 1;
match harness {
Harness::Claude => r.claude_commands += 1,
Harness::Codex => r.codex_commands += 1,
}
let next = seen.len();
seen.entry(cmd.clone()).or_insert((0, next)).0 += 1;
}
for k in 0..3 {
add_wait(&mut r.waits[k], &f.waits[k]);
}
add_wait(&mut r.wait_all, &f.wait_all);
}
for (cwd, claude, codex) in &folders {
r.folders.push((cwd.clone(), *claude, *codex));
}
(r.replay, r.groups, r.flagged) = replay(&seen, &all);
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
}
fn duration(secs: u64) -> String {
match secs {
0..=59 => format!("{secs} s"),
60..=3599 => format!("{} min", secs / 60),
_ => format!("{} h {:02} min", secs / 3600, secs % 3600 / 60),
}
}
fn render_waiting(r: &Report) -> String {
let total = r.wait_all.count;
if total == 0 {
return String::new();
}
let (measured, secs) = (r.wait_all.measured, r.wait_all.secs);
let mut o = format!(
"\n4. Waiting: {} that wait badly (a tripwire would have warned before each; one that fits two classes is listed under both)\n",
noun(total as u64, "shell command", "shell commands")
);
for (i, w) in r.waits.iter().enumerate() {
if w.count == 0 {
continue;
}
o.push_str(&format!(" {:>4} {}\n", w.count, WAIT_NAMES[i]));
for e in &w.examples {
o.push_str(&format!(" {e}\n"));
}
}
if measured == 0 {
o.push_str(" Time: none of these had both a start and an end in the transcripts, so no time is reported.\n");
} else {
o.push_str(&format!(
" Time: at least {} of wall time across {} of the {} (longest {}).\n",
duration(secs),
measured,
total,
duration(r.wait_all.longest)
));
}
for l in [
"How: a foreground command is timed from its tool call to its result; a background command from its",
"launch to the completion notice in the transcript. Commands with no end on record add nothing, so",
"this is a floor. It is how long the command ran, not how much of that was avoidable.",
] {
o.push_str(&format!(" {l}\n"));
}
o
}
fn render_replay(r: &Report) -> String {
let p = &r.replay;
let mut o = String::new();
if r.commands == 0 {
return o;
}
let share = 100.0 * p.rewritten_runs as f64 / r.commands as f64;
o.push_str(&format!(
" Safe rewrites: instinct fix would have changed {} of {} distinct commands ({}, {share:.2}% of all runs)\n",
commas(p.rewritten_unique as u64),
commas(p.unique as u64),
noun(p.rewritten_runs as u64, "run", "runs")
));
for (rule, n) in &p.rules {
o.push_str(&format!(" {n:>4} rule {rule}\n"));
}
for (rules, a, b) in &p.samples {
o.push_str(&format!(" [{rules}] - {a}\n {} + {b}\n", " ".repeat(rules.len())));
}
o
}
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(&format!("Shell commands by harness: {} Claude Code, {} Codex.\n", commas(r.claude_commands as u64), commas(r.codex_commands as u64)));
}
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(&render_replay(r));
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(&format!(" Retried a failing command the same way 3+ times: {}\n", r.retried));
o.push_str(&format!(
" Claimed done with nothing run since the last change, right after a correction: {}\n",
r.claimed_done
));
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")
));
}
let waiting = render_waiting(r);
o.push_str(&waiting);
o.push_str(&format!("\n{}. Next steps\n", if waiting.is_empty() { 4 } else { 5 }));
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 wait_all = format!(
"{{\"count\":{},\"measured\":{},\"measured_background\":{},\"seconds\":{},\"longest_seconds\":{}}}",
r.wait_all.count, r.wait_all.measured, r.wait_all.measured_background, r.wait_all.secs, r.wait_all.longest
);
let waits: Vec<String> = r
.waits
.iter()
.enumerate()
.map(|(i, w)| {
let ex: Vec<String> = w.examples.iter().map(|e| format!("\"{}\"", escape_json(e))).collect();
format!(
"{{\"id\":\"{}\",\"count\":{},\"measured\":{},\"measured_background\":{},\"seconds\":{},\"longest_seconds\":{},\"examples\":[{}]}}",
WAIT_IDS[i], w.count, w.measured, w.measured_background, w.secs, w.longest, ex.join(",")
)
})
.collect();
let named = |v: &[(String, u32)], key: &str| -> String {
v.iter().map(|(n, c)| format!("{{\"{key}\":\"{}\",\"runs\":{c}}}", escape_json(n))).collect::<Vec<_>>().join(",")
};
let samples: Vec<String> = r
.replay
.samples
.iter()
.map(|(rules, a, b)| format!("{{\"rules\":\"{}\",\"before\":\"{}\",\"after\":\"{}\"}}", escape_json(rules), escape_json(a), escape_json(b)))
.collect();
let replay = format!(
"{{\"unique\":{},\"rewritten\":{{\"unique\":{},\"runs\":{},\"by_rule\":[{}]}},\"warned\":{{\"unique\":{},\"runs\":{},\"by_title\":[{}]}},\"samples\":[{}]}}",
r.replay.unique,
r.replay.rewritten_unique,
r.replay.rewritten_runs,
named(&r.replay.rules, "rule"),
r.replay.warned_unique,
r.replay.warned_runs,
named(&r.replay.titles, "title"),
samples.join(",")
);
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\":{},\"commands_by_harness\":{{\"claude_code\":{},\"codex\":{}}},\
\"risky\":{{\"flagged\":{},\"groups\":[{}]}},\"replay\":{},\
\"corrections\":{{\"count\":{},\"after_correction\":{},\"after_other\":{},\"ratio\":{},\"retried_same_command_3plus\":{},\"claimed_done_unverified\":{}}},\
\"waiting\":{{\"measured_as\":\"floor: foreground call to result, background launch to completion notice\",\"total\":{},\"classes\":[{}]}},\
\"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.claude_commands,
r.codex_commands,
r.flagged,
groups.join(","),
replay,
r.corrections,
pairs(r.after_correction),
pairs(r.after_other),
f(r.ratio()),
r.retried,
r.claimed_done,
wait_all,
waits.join(","),
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,
"--format" => match it.next().map(String::as_str) {
Some("json") => json = true,
Some("text") => json = false,
_ => return Err("scan: --format needs json or text".into()),
},
"--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);
}
}