use super::*;
use std::path::Path;
pub const MINE_HELP: &str = "usage: instinct mine [PATHS...] [--since 7d] [--project P] [--limit 10] [--min-confidence 0.6] [--apply] [--json]\n\
Mines lessons from sessions you already had. No model, nothing leaves the machine.\n\
Mining finds candidates; you decide what to bank.\n\
PATHS are transcript files or folders (*.jsonl). With none, reads ~/.claude/projects/*/*.jsonl and\n\
~/.codex/sessions/**/*.jsonl.\n\
correction window the user rejects or corrects the agent (\"no, don't ...\", \"that's wrong\", \"actually ...\")\n\
and a later step succeeds: a test or build passes, or the user confirms.\n\
recovery window a tool call fails, then a changed call of the same command succeeds.\n\
Each candidate: when = the user's words, found = what failed, how = what worked, evidence = file, turn and\n\
line, tags include mined. Keys, tokens, passwords and env dumps are redacted or skipped.\n\
--since 7d only files modified in the last N m/h/d/w\n\
--project P only paths containing P; --apply also scopes the lessons to project P\n\
--limit N show and bank at most N candidates, highest confidence first (default 10);\n\
the rest are counted, not shown\n\
--min-confidence drop candidates below this score (default 0.6; 0 shows all)\n\
--apply bank the shown candidates into the default bank (or --store PATH) as source: mined;\n\
the default is a dry run\n\
--store PATH bank file to dedupe against and write to (default: INSTINCT_STORE or the usual bank)\n\
--json print the candidates and counts as JSON\n\
Windows that touch credentials or access (authorized_keys, ~/.ssh, .netrc, .env files, sshpass, passwd,\n\
keychains, gpg or age keys, sudoers, chmod 777) are never mined; they are counted as skipped.\n\
Candidates already in the bank, or repeated in this run, are not added again.";
struct Opts {
paths: Vec<String>,
since: Option<u64>,
project: String,
min_conf: f64,
limit: usize,
store: Option<String>,
apply: bool,
json: bool,
help: bool,
}
fn parse_limit(v: &str) -> Result<usize, String> {
v.parse().ok().filter(|n: &usize| *n >= 1).ok_or_else(|| "--limit needs a number of 1 or more".to_string())
}
fn parse_since(v: &str) -> Result<u64, String> {
let (n, unit) = v.split_at(v.len().saturating_sub(1));
let n: u64 = n
.parse()
.map_err(|_| format!("--since {v}: use a number and m, h, d or w (7d)"))?;
let mult = match unit {
"m" => 60,
"h" => 3600,
"d" => 86_400,
"w" => 604_800,
_ => return Err(format!("--since {v}: use a number and m, h, d or w (7d)")),
};
Ok(n * mult)
}
fn opts(argv: &[String]) -> Result<Opts, String> {
let mut o = Opts {
paths: Vec::new(),
since: None,
project: String::new(),
min_conf: 0.6,
limit: 10,
store: None,
apply: false,
json: false,
help: false,
};
let mut i = 0;
while i < argv.len() {
let a = argv[i].as_str();
let mut value = |name: &str| -> Result<String, String> {
if let Some(v) = a.strip_prefix(&format!("{name}=")) {
return Ok(v.to_string());
}
i += 1;
argv.get(i).cloned().ok_or(format!("{name} needs a value"))
};
match a {
"--apply" => o.apply = true,
"--json" => o.json = true,
"--help" | "-h" => o.help = true,
"--since" => o.since = Some(parse_since(&value("--since")?)?),
"--project" => o.project = value("--project")?,
"--limit" => o.limit = parse_limit(&value("--limit")?)?,
"--store" => o.store = Some(value("--store")?),
_ if a.starts_with("--limit=") => o.limit = parse_limit(&value("--limit")?)?,
_ if a.starts_with("--store=") => o.store = Some(value("--store")?),
"--min-confidence" => {
o.min_conf = value("--min-confidence")?
.parse()
.map_err(|_| "--min-confidence needs a number from 0 to 1".to_string())?
}
_ if a.starts_with("--since=") => o.since = Some(parse_since(&value("--since")?)?),
_ if a.starts_with("--project=") => o.project = value("--project")?,
_ if a.starts_with("--min-confidence=") => {
o.min_conf = value("--min-confidence")?
.parse()
.map_err(|_| "--min-confidence needs a number from 0 to 1".to_string())?
}
_ if a.starts_with("--") => return Err(format!("unknown option {a}")),
_ => o.paths.push(a.to_string()),
}
i += 1;
}
Ok(o)
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Kind {
User,
Assistant,
ToolUse,
ToolResult,
}
#[derive(Clone)]
pub(crate) struct Ev {
pub(crate) kind: Kind,
pub(crate) text: String,
pub(crate) cmd: String,
pub(crate) err: bool,
pub(crate) id: String,
pub(crate) line: usize,
pub(crate) ts: u64,
pub(crate) bg: u8,
}
pub(crate) fn possible_user_line(line: &str) -> bool {
line.contains("\"user\"") && !line.contains("\"tool_result\"")
}
pub(crate) fn gate_events(text: &str) -> Vec<Ev> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
if line.len() < 20 {
continue;
}
let Ok(top) = parse_json(line.trim()) else { continue };
let results = top.get("type").and_then(Json::as_str) == Some("user")
&& matches!(top.get("message").and_then(|m| m.get("content")),
Some(Json::Arr(bs)) if bs.iter().any(|b| b.get("type").and_then(Json::as_str) == Some("tool_result")));
claude_events(&top, i + 1, &mut out, !results, false);
}
out
}
#[cfg(test)]
pub(crate) fn test_ev(kind: Kind, text: &str, cmd: &str) -> Ev {
Ev { text: text.into(), cmd: cmd.into(), ..ev(kind, 0) }
}
fn ev(kind: Kind, line: usize) -> Ev {
Ev {
kind,
text: String::new(),
cmd: String::new(),
err: false,
id: String::new(),
line,
ts: 0,
bg: 0,
}
}
fn content_text(v: &Json) -> String {
match v {
Json::Str(s) => s.clone(),
Json::Arr(items) => items
.iter()
.filter_map(|b| b.get("text").and_then(Json::as_str))
.collect::<Vec<_>>()
.join("\n"),
_ => String::new(),
}
}
fn human_text(t: &str) -> bool {
let s = t.trim_start();
!s.is_empty()
&& !s.starts_with('<')
&& !s.starts_with('[')
&& !s.starts_with("Caveat:")
&& !s.starts_with("# AGENTS.md")
&& !s.contains("API Error")
}
const HARNESS_BLOCKS: [&str; 14] = [
"system-reminder", "task-notification", "cross-session-message", "local-command-stdout", "local-command-stderr",
"local-command-caveat", "command-name", "command-message", "command-args", "pasted_content",
"user-prompt-submit-hook", "environment_context", "user_instructions", "turn_aborted",
];
pub(crate) fn strip_blocks(t: &str) -> String {
let mut s = t.to_string();
for tag in HARNESS_BLOCKS {
let open = format!("<{tag}");
let close = format!("</{tag}>");
let mut from = 0;
while let Some(i) = s[from..].find(&open).map(|i| i + from) {
let after = s[i + open.len()..].chars().next();
if !matches!(after, Some('>') | Some('/') | Some(' ') | Some('\n') | Some('\t')) {
from = i + open.len();
continue;
}
let end = s[i..].find(&close).map_or(s.len(), |c| i + c + close.len());
s.replace_range(i..end, " ");
from = i;
}
}
s
}
fn user_text(t: &str, typed: bool) -> Option<String> {
if typed {
let s = strip_blocks(t);
human_text(&s).then_some(s)
} else {
human_text(t).then(|| t.to_string())
}
}
pub(crate) fn is_typed_user_record(top: &Json) -> bool {
let claude = top.get("type").and_then(Json::as_str) == Some("user");
let codex = top.get("type").and_then(Json::as_str) == Some("response_item")
&& top.get("payload").and_then(|p| p.get("role")).and_then(Json::as_str) == Some("user");
if !claude && !codex { return false; }
let mut events = Vec::new();
if claude { claude_events(top, 0, &mut events, true, false); }
else { codex_events(top, 0, &mut events, true); }
events.iter().any(|e| e.kind == Kind::User)
}
fn claude_events(top: &Json, line: usize, out: &mut Vec<Ev>, typed: bool, timed: bool) {
if matches!(top.get("isSidechain"), Some(Json::Bool(true)))
|| matches!(top.get("isMeta"), Some(Json::Bool(true)))
{
return;
}
let echo = typed && top.get("type").and_then(Json::as_str) == Some("user") && top.get("toolUseResult").is_some();
if typed
&& top.get("type").and_then(Json::as_str) == Some("user")
&& ((echo && !timed)
|| matches!(top.get("isCompactSummary"), Some(Json::Bool(true)))
|| matches!(top.get("isVisibleInTranscriptOnly"), Some(Json::Bool(true))))
{
return;
}
let (Some(t), Some(msg)) = (top.get("type").and_then(Json::as_str), top.get("message")) else {
return;
};
let Some(content) = msg.get("content") else {
return;
};
match (t, content) {
("user", Json::Str(s)) if !echo => {
if let Some(text) = user_text(s, typed) {
out.push(Ev { text, ..ev(Kind::User, line) });
}
}
("user" | "assistant", Json::Arr(blocks)) => {
for b in blocks {
match b.get("type").and_then(Json::as_str) {
Some("text") if t == "user" && echo => {}
Some("text") if t == "user" => {
let s = b.get("text").and_then(Json::as_str).unwrap_or("");
if let Some(text) = user_text(s, typed) {
out.push(Ev { text, ..ev(Kind::User, line) });
}
}
Some("text") => {
let s = b.get("text").and_then(Json::as_str).unwrap_or("");
if !s.trim().is_empty() {
out.push(Ev { text: s.to_string(), ..ev(Kind::Assistant, line) });
}
}
Some("tool_use") => {
let name = b.get("name").and_then(Json::as_str).unwrap_or("");
let input = b.get("input");
let get = |k: &str| {
input
.and_then(|i| i.get(k))
.and_then(Json::as_str)
.unwrap_or("")
.to_string()
};
let cmd = if name == "Bash" {
get("command")
} else {
let target = [get("file_path"), get("pattern"), get("path"), get("url")]
.into_iter()
.find(|s| !s.is_empty())
.unwrap_or_default();
format!("{name} {target}").trim().to_string()
};
out.push(Ev {
text: name.to_string(),
cmd,
id: b.get("id").and_then(Json::as_str).unwrap_or("").into(),
bg: matches!(input.and_then(|i| i.get("run_in_background")), Some(Json::Bool(true))) as u8,
..ev(Kind::ToolUse, line)
});
}
Some("tool_result") => out.push(Ev {
text: b.get("content").map(content_text).unwrap_or_default(),
err: matches!(b.get("is_error"), Some(Json::Bool(true))),
id: b.get("tool_use_id").and_then(Json::as_str).unwrap_or("").into(),
..ev(Kind::ToolResult, line)
}),
_ => {}
}
}
}
_ => {}
}
}
fn codex_events(top: &Json, line: usize, out: &mut Vec<Ev>, typed: bool) {
if top.get("type").and_then(Json::as_str) != Some("response_item") {
return;
}
let Some(p) = top.get("payload") else {
return;
};
match p.get("type").and_then(Json::as_str) {
Some("message") => {
let role = p.get("role").and_then(Json::as_str).unwrap_or("");
let text = p.get("content").map(content_text).unwrap_or_default();
match role {
"user" => {
if let Some(text) = user_text(&text, typed) {
out.push(Ev { text, ..ev(Kind::User, line) });
}
}
"assistant" if !text.trim().is_empty() => {
out.push(Ev { text, ..ev(Kind::Assistant, line) })
}
_ => {}
}
}
Some("function_call") => {
let args = p
.get("arguments")
.and_then(Json::as_str)
.and_then(|a| parse_json(a).ok());
let cmd = match args.as_ref().and_then(|a| a.get("command").or(a.get("cmd"))) {
Some(Json::Str(s)) => s.clone(),
Some(Json::Arr(parts)) => parts
.iter()
.rev()
.find_map(|x| x.as_str().map(String::from))
.unwrap_or_default(),
_ => String::new(),
};
out.push(Ev {
text: p.get("name").and_then(Json::as_str).unwrap_or("").into(),
cmd,
id: p.get("call_id").and_then(Json::as_str).unwrap_or("").into(),
..ev(Kind::ToolUse, line)
});
}
Some("custom_tool_call") if p.get("name").and_then(Json::as_str) == Some("exec") => {
let input = p.get("input").and_then(Json::as_str).unwrap_or("");
for call in codex_cell::exec_calls(input) {
out.push(Ev {
text: "exec_command".into(),
cmd: call.cmd,
id: p.get("call_id").and_then(Json::as_str).unwrap_or("").into(),
..ev(Kind::ToolUse, line)
});
}
}
Some("function_call_output") => {
let raw = p.get("output").and_then(Json::as_str).unwrap_or("");
let (text, code) = match parse_json(raw) {
Ok(j) if j.get("metadata").is_some() => (
j.get("output").and_then(Json::as_str).unwrap_or("").to_string(),
j.get("metadata")
.and_then(|m| m.get("exit_code"))
.and_then(Json::as_f64),
),
_ => {
let code = raw
.lines()
.find_map(|l| l.to_lowercase().strip_prefix("exit code:").map(str::to_owned))
.and_then(|n| n.trim().parse::<f64>().ok());
(raw.to_string(), code)
}
};
out.push(Ev {
text,
err: code.is_some_and(|c| c != 0.0),
id: p.get("call_id").and_then(Json::as_str).unwrap_or("").into(),
..ev(Kind::ToolResult, line)
});
}
_ => {}
}
}
fn read_events(path: &Path) -> Result<Vec<Ev>, String> {
read_events_with(path, false)
}
pub(crate) fn read_events_with(path: &Path, lite: bool) -> Result<Vec<Ev>, String> {
read_events_inner(path, lite, false)
}
pub(crate) fn iso_secs(s: &str) -> Option<u64> {
let b = s.as_bytes();
let num = |a: usize, n: usize| -> Option<i64> {
let t = s.get(a..a + n)?;
t.bytes().all(|c| c.is_ascii_digit()).then(|| t.parse().ok()).flatten()
};
if b.len() < 19 || b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b' ') || b[13] != b':' || b[16] != b':' {
return None;
}
let (y, m, d) = (num(0, 4)?, num(5, 2)?, num(8, 2)?);
let (hh, mm, ss) = (num(11, 2)?, num(14, 2)?, num(17, 2)?);
if !(1..=12).contains(&m) || !(1..=31).contains(&d) || hh > 23 || mm > 59 || ss > 60 {
return None;
}
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
let mut t = days * 86_400 + hh * 3600 + mm * 60 + ss;
if let Some(off) = s.get(19..).and_then(|r| r.trim_start_matches(|c: char| c == '.' || c.is_ascii_digit()).get(..6)) {
let sign = match off.as_bytes()[0] {
b'+' => 1,
b'-' => -1,
_ => 0,
};
if sign != 0 && off.as_bytes()[3] == b':' {
if let (Ok(oh), Ok(om)) = (off[1..3].parse::<i64>(), off[4..6].parse::<i64>()) {
t -= sign * (oh * 3600 + om * 60);
}
}
}
u64::try_from(t).ok()
}
fn between<'a>(s: &'a str, tag: &str) -> Option<&'a str> {
let open = format!("<{tag}>");
let a = s.find(&open)? + open.len();
let z = s[a..].find(&format!("</{tag}>"))? + a;
Some(s[a..z].trim())
}
pub(crate) fn read_events_timed(path: &Path) -> Result<Vec<Ev>, String> {
read_events_inner(path, true, true)
}
fn read_events_inner(path: &Path, lite: bool, timed: bool) -> Result<Vec<Ev>, String> {
let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut reader = std::io::BufReader::new(file);
let mut out = Vec::new();
let mut buf = Vec::new();
let mut n = 0;
let mut codex: Option<bool> = None;
loop {
buf.clear();
if reader.read_until(b'\n', &mut buf).map_err(|e| e.to_string())? == 0 {
break;
}
n += 1;
let line = String::from_utf8_lossy(&buf);
let Ok(top) = parse_json(line.trim()) else {
continue;
};
if codex.is_none() && top.get("payload").is_some() {
codex = Some(true);
}
let from = out.len();
if timed && top.get("type").and_then(Json::as_str) == Some("queue-operation") && top.get("operation").and_then(Json::as_str) == Some("enqueue") {
if let Some(c) = top.get("content").and_then(Json::as_str).filter(|c| c.contains("<task-notification>")) {
if let Some(id) = between(c, "tool-use-id").filter(|i| !i.is_empty()) {
out.push(Ev { id: id.into(), text: between(c, "status").unwrap_or("").into(), bg: 2, ..ev(Kind::ToolResult, n) });
}
}
}
if codex == Some(true) {
codex_events(&top, n, &mut out, lite);
} else {
claude_events(&top, n, &mut out, lite, timed);
}
if timed {
let ts = top.get("timestamp").and_then(Json::as_str).and_then(iso_secs).unwrap_or(0);
for e in &mut out[from..] {
e.ts = ts;
}
}
if lite {
let mut keep = from;
for i in from..out.len() {
if out[i].kind == Kind::ToolResult && !(timed && !out[i].id.is_empty()) {
continue;
}
if out[i].kind == Kind::ToolResult && out[i].bg == 0 {
out[i].bg = out[i].text.starts_with("Command running in background") as u8;
out[i].text.clear();
}
if out[i].kind == Kind::Assistant {
out[i].text.clear();
}
out.swap(keep, i);
keep += 1;
}
out.truncate(keep);
continue;
}
for e in &mut out[from..] {
e.text = redact(&e.text.chars().take(6000).collect::<String>()).0;
e.cmd = redact(&e.cmd).0;
}
}
Ok(out)
}
const SECRET_NAMES: [&str; 9] = [
"key", "token", "secret", "passw", "pwd", "credential", "auth", "bearer", "passphrase",
];
const SECRET_PREFIXES: [&str; 17] = [
"sk-", "sk_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "xoxb-", "xoxa-", "xoxp-",
"xoxs-", "glpat-", "npm_", "hf_", "AIza", "pypi-",
];
fn edge(c: char) -> bool {
matches!(c, '"' | '\'' | ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '`')
}
fn looks_secret(core: &str) -> bool {
let n = core.chars().count();
if n >= 16 && SECRET_PREFIXES.iter().any(|p| core.starts_with(p)) {
return true;
}
if n == 20 && (core.starts_with("AKIA") || core.starts_with("ASIA"))
&& core.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
{
return true;
}
if core.starts_with("eyJ") && core.matches('.').count() == 2 && n >= 24 {
return true;
}
if n >= 32
&& !core.starts_with(['/', '.', '~'])
&& core.chars().all(|c| c.is_ascii_alphanumeric() || "+/_=-".contains(c))
&& core.chars().any(|c| c.is_ascii_digit())
&& core.chars().any(|c| c.is_ascii_alphabetic())
{
let hex = core.chars().all(|c| c.is_ascii_hexdigit());
return !(hex && n == 40) && (hex || (core.chars().any(|c| c.is_ascii_uppercase()) && core.chars().any(|c| c.is_ascii_lowercase())));
}
false
}
fn secret_name(name: &str) -> bool {
let n = name.trim_matches(|c: char| edge(c)).to_lowercase();
!n.is_empty() && SECRET_NAMES.iter().any(|s| n.contains(s))
}
fn redact_token(tok: &str, prev: &[String], count: &mut usize) -> String {
if tok.contains("[REDACTED]") {
return tok.to_string();
}
let lead = tok.len() - tok.trim_start_matches(edge).len();
let core = tok.trim_matches(edge);
let tail = &tok[lead + core.len()..];
let head = &tok[..lead];
let mut mark = |s: &str| {
*count += 1;
format!("{head}{s}{tail}")
};
if let Some(scheme) = core.find("://") {
let rest = &core[scheme + 3..];
if let Some(at) = rest.find('@') {
let creds = &rest[..at];
if let Some(colon) = creds.find(':') {
if !creds.contains('/') && colon + 1 < creds.len() {
let keep = &core[..scheme + 3 + colon + 1];
return mark(&format!("{keep}[REDACTED]{}", &rest[at..]));
}
}
}
}
let split = core
.find('=')
.map(|i| (i, 1))
.or_else(|| core.find("\":").map(|i| (i + 1, 1)))
.or_else(|| core.find(':').filter(|&i| !core[i..].starts_with("://")).map(|i| (i, 1)));
if let Some((i, w)) = split {
let (name, value) = (&core[..i], core[i + w..].trim_matches(edge));
if secret_name(name) && value.chars().count() >= 4 && value != "[REDACTED]" {
return mark(&format!("{}[REDACTED]", &core[..i + w]));
}
if looks_secret(value) {
return mark(&format!("{}[REDACTED]", &core[..i + w]));
}
}
let p1 = prev.last().map(String::as_str).unwrap_or("");
let p2 = prev.iter().rev().nth(1).map(String::as_str).unwrap_or("");
if matches!(core.to_lowercase().as_str(), "bearer" | "basic") {
return tok.to_string();
}
let after_label = matches!(p1, "bearer" | "basic" | "authorization:" | "token")
|| (p1 == "-p" && p2 == "sshpass")
|| (p1.starts_with("--") && secret_name(p1));
if (after_label && core.chars().count() >= 6) || looks_secret(core) {
return mark("[REDACTED]");
}
tok.to_string()
}
pub(crate) fn redact(s: &str) -> (String, usize) {
let mut count = 0;
let mut text = s.to_string();
while let Some(a) = text.find("-----BEGIN ") {
if !text[a..].contains("PRIVATE KEY-----") {
break;
}
let end = text[a..]
.find("-----END ")
.and_then(|e| text[a + e + 9..].find("-----").map(|x| a + e + 9 + x + 5))
.unwrap_or(text.len());
text.replace_range(a..end, "[REDACTED]");
count += 1;
}
let mut out = String::with_capacity(text.len());
let mut prev: Vec<String> = Vec::new();
let mut tok = String::new();
let flush = |tok: &mut String, prev: &mut Vec<String>, out: &mut String, count: &mut usize| {
if !tok.is_empty() {
out.push_str(&redact_token(tok, prev, count));
prev.push(tok.to_lowercase());
if prev.len() > 3 {
prev.remove(0);
}
tok.clear();
}
};
for c in text.chars() {
if c.is_whitespace() {
flush(&mut tok, &mut prev, &mut out, &mut count);
out.push(c);
} else {
tok.push(c);
}
}
flush(&mut tok, &mut prev, &mut out, &mut count);
(out, count)
}
fn env_dump(s: &str) -> bool {
s.lines()
.filter(|l| {
let name = l.split('=').next().unwrap_or("");
l.contains('=')
&& name.len() >= 3
&& name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
&& name.starts_with(|c: char| c.is_ascii_uppercase())
})
.count()
>= 4
}
pub(crate) fn clip(s: &str, n: usize) -> String {
let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= n {
flat
} else {
format!("{}...", flat.chars().take(n.saturating_sub(3)).collect::<String>().trim_end())
}
}
fn word_set(s: &str) -> HashSet<String> {
s.to_lowercase()
.split(|c: char| !c.is_alphanumeric() && !"-_/.".contains(c))
.filter(|w| w.len() >= 3)
.map(String::from)
.collect()
}
fn head_word(cmd: &str) -> String {
cmd.lines()
.map(str::trim)
.find(|l| !l.is_empty() && !l.starts_with('#'))
.unwrap_or("")
.split_whitespace()
.skip_while(|w| {
["sudo", "timeout", "env", "nohup", "setsid", "cd", "time"].contains(w)
|| w.contains('=')
|| w.chars().all(|c| c.is_ascii_digit())
})
.next()
.unwrap_or("")
.rsplit('/')
.next()
.unwrap_or("")
.to_string()
}
fn first_error_line(text: &str) -> String {
let lines = || text.lines().map(str::trim).filter(|l| !l.is_empty());
let l = lines()
.find(|l| l.to_lowercase().contains("error"))
.or_else(|| lines().next())
.unwrap_or("");
clip(l, 200)
}
const VERIFIERS: [&str; 24] = [
"cargo test", "cargo build", "cargo check", "cargo clippy", "pytest", "npm test", "npm run build",
"npm run test", "pnpm test", "yarn test", "go test", "go build", "make test", "make check", "make",
"tsc", "ruff", "eslint", "mvn test", "gradle test", "dotnet test", "bun test", "rspec", "run_tests",
];
fn is_verifier(cmd: &str) -> bool {
let c = cmd.to_lowercase();
VERIFIERS.iter().any(|v| c.contains(v))
}
fn passed(text: &str) -> bool {
let t = text.to_lowercase().replace("0 failed", "").replace("0 errors", "");
let bad = ["failed", "error:", "error[", "panicked", "traceback", "fail:"];
if bad.iter().any(|b| t.contains(b)) {
return false;
}
let good = ["test result: ok", "passed", "finished", "success", "no issues", "exit code: 0", "all tests"];
t.trim().is_empty() || good.iter().any(|g| t.contains(g)) || text.to_lowercase().contains("0 failed")
}
#[derive(Clone)]
struct Lesson {
kind: &'static str,
title: String,
when: String,
found: String,
how: String,
evidence: String,
tags: String,
confidence: f64,
file: String,
line: usize,
redactions: usize,
}
#[derive(Default)]
struct Skips {
no_success: usize,
probe: usize,
transient: usize,
env_dump: usize,
rejected: usize,
script: usize,
credentials: usize,
low_confidence: usize,
}
const CORRECTION_STARTS: [&str; 22] = [
"no,", "no.", "no!", "no -", "no ", "nope", "wrong", "that's wrong", "thats wrong", "that is wrong",
"that's not", "thats not", "that is not", "actually", "don't", "dont", "do not", "stop", "not what",
"never ", "why did you", "undo",
];
const NOT_CORRECTIONS: [&str; 6] = ["no problem", "no worries", "no idea", "no rush", "no hurry", "no thanks"];
const CONFIRMS: [&str; 16] = [
"thanks", "thank you", "perfect", "great", "good", "works", "nice", "exactly", "correct", "lgtm",
"awesome", "cool", "yes", "yep", "that works", "looks good",
];
fn is_correction(text: &str, prev_assistant: &str) -> bool {
let low = text.trim().to_lowercase();
let words = low.split_whitespace().count();
if words < 3 || text.chars().count() > 500 {
return false;
}
if NOT_CORRECTIONS.iter().any(|n| low.starts_with(n)) {
return false;
}
if low.starts_with("no") && words < 8 && prev_assistant.trim_end().ends_with('?') {
return false;
}
CORRECTION_STARTS.iter().any(|m| low.starts_with(m)) || low.contains("not what i ") || low.contains("that's wrong")
}
fn is_confirm(text: &str) -> bool {
let low = text.trim().to_lowercase();
low.split_whitespace().count() <= 8 && CONFIRMS.iter().any(|c| low.starts_with(c) || low.contains(&format!(" {c}")))
}
fn transient(text: &str) -> bool {
let t = text.to_lowercase();
["timed out", "timeout", "connection refused", "connection reset", "rate limit", "429", "503", "temporarily", "try again", "network is unreachable", "could not resolve"]
.iter()
.any(|m| t.contains(m))
}
pub(crate) fn touches_credentials(s: &str) -> bool {
let t = s.to_lowercase();
const MARKERS: [&str; 18] = [
"authorized_keys", ".ssh/", ".ssh ", "~/.ssh", ".netrc", "sshpass", "passwd", "keychain", ".gnupg",
"gpg ", "gpg2 ", "age-keygen", "id_rsa", "id_ed25519", "sudoers", "chmod 777", "chmod -r 777", "ssh-keygen",
];
if MARKERS.iter().any(|m| t.contains(m)) || t.ends_with(".ssh") || t.ends_with("gpg") {
return true;
}
let mut from = 0;
while let Some(i) = t[from..].find(".env") {
let at = from + i;
let before_ok = at == 0 || t[..at].ends_with(|c: char| c.is_whitespace() || "/'\"=:~".contains(c));
let after = &t[at + 4..];
let after_ok = after.is_empty() || after.starts_with(|c: char| c.is_whitespace() || "'\"./;|&)".contains(c));
if before_ok && after_ok {
return true;
}
from = at + 4;
}
false
}
fn user_rejected(text: &str) -> bool {
let t = text.to_lowercase();
t.contains("hook error") || t.contains("doesn't want to proceed") || t.contains("was rejected") || t.contains("interrupted by user") || t.contains("request interrupted")
}
const PROBES: [&str; 12] = ["grep", "rg", "egrep", "fgrep", "diff", "test", "[", "cmp", "pgrep", "which", "command", "type"];
fn turn_of(evs: &[Ev], i: usize) -> usize {
evs[..=i].iter().filter(|e| e.kind == Kind::User).count()
}
fn last_user_before(evs: &[Ev], i: usize) -> Option<&Ev> {
evs[..i].iter().rev().find(|e| e.kind == Kind::User)
}
fn find_result<'a>(evs: &'a [Ev], from: usize, id: &str) -> Option<(usize, &'a Ev)> {
evs.iter().enumerate().skip(from).find(|(_, e)| e.kind == Kind::ToolResult && e.id == id)
}
fn finish(l: Lesson, file: &str, line: usize, turn: usize, skips: &mut Skips, min: f64) -> Option<Lesson> {
let raw = format!("{}\n{}\n{}\n{}", l.when, l.found, l.how, l.title);
if env_dump(&raw) {
skips.env_dump += 1;
return None;
}
let (mut red, mut n) = (Vec::new(), 0);
for field in [&l.title, &l.when, &l.found, &l.how] {
let (r, c) = redact(field);
red.push(r);
n += c;
}
let n = n + red.iter().map(|r| r.matches("[REDACTED]").count()).sum::<usize>();
let mut it = red.into_iter();
let out = Lesson {
title: it.next()?,
when: it.next()?,
found: it.next()?,
how: it.next()?,
evidence: format!("mined from {file} turn {turn} (line {line})"),
file: file.to_string(),
line,
redactions: n,
..l
};
if out.confidence < min {
skips.low_confidence += 1;
return None;
}
Some(out)
}
fn mine_events(evs: &[Ev], file: &str, min: f64, skips: &mut Skips) -> Vec<Lesson> {
let mut out = Vec::new();
let by_id: HashMap<&str, usize> = evs
.iter()
.enumerate()
.filter(|(_, e)| e.kind == Kind::ToolUse)
.map(|(i, e)| (e.id.as_str(), i))
.collect();
for (i, r) in evs.iter().enumerate() {
if r.kind != Kind::ToolResult || !r.err {
continue;
}
let Some(&ui) = by_id.get(r.id.as_str()) else { continue };
let fail = &evs[ui];
if fail.cmd.is_empty() || fail.text == "Edit" || fail.text == "Write" {
continue;
}
if touches_credentials(&fail.cmd) {
skips.credentials += 1;
continue;
}
let one_line = fail.cmd.trim();
if one_line.contains('\n') || one_line.contains("<<") || one_line.chars().count() > 240 {
skips.script += 1;
continue;
}
let head = head_word(&fail.cmd);
if PROBES.contains(&head.as_str()) {
skips.probe += 1;
continue;
}
if user_rejected(&r.text) {
skips.rejected += 1;
continue;
}
if transient(&r.text) {
skips.transient += 1;
continue;
}
let fw = word_set(&fail.cmd);
let norm = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
for j in i + 1..(i + 13).min(evs.len()) {
let fix = &evs[j];
if fix.kind == Kind::User {
break;
}
if fix.kind != Kind::ToolUse
|| fix.cmd.is_empty()
|| head_word(&fix.cmd) != head
|| norm(&fix.cmd) == norm(&fail.cmd)
{
continue;
}
if touches_credentials(&fix.cmd) {
skips.credentials += 1;
break;
}
let xw = word_set(&fix.cmd);
if (fw.intersection(&xw).count() as f64) / (fw.len().max(1) as f64) < 0.3 {
continue;
}
let Some((_, res)) = find_result(evs, j + 1, &fix.id) else { continue };
if res.err {
continue;
}
let added: Vec<_> = { let mut v: Vec<_> = xw.difference(&fw).cloned().collect(); v.sort(); v };
let removed: Vec<_> = { let mut v: Vec<_> = fw.difference(&xw).cloned().collect(); v.sort(); v };
let mut conf: f64 = 0.3;
if r.text.trim().len() >= 20 {
conf += 0.15;
}
if added.len() + removed.len() <= 3 {
conf += 0.15;
}
if is_verifier(&fix.cmd) && passed(&res.text) {
conf += 0.1;
}
let goal = last_user_before(evs, ui);
if goal.is_some() {
conf += 0.1;
}
let when = goal.map(|g| clip(&g.text, 200)).unwrap_or_else(|| format!("Running `{}`", clip(&fail.cmd, 120)));
let change = match (added.is_empty(), removed.is_empty()) {
(false, false) => format!(" Added {}, dropped {}.", added.join(" "), removed.join(" ")),
(false, true) => format!(" Added {}.", added.join(" ")),
(true, false) => format!(" Dropped {}.", removed.join(" ")),
_ => String::new(),
};
let l = Lesson {
kind: "recovery",
title: format!("Recovery: {} failed, a changed call worked", head),
when,
found: format!("`{}` failed: {}", clip(&fail.cmd, 200), first_error_line(&r.text)),
how: format!("`{}` succeeded instead.{change}", clip(&fix.cmd, 240)),
evidence: String::new(),
tags: format!("mined,recovery,{head}"),
confidence: conf.min(0.9),
file: String::new(),
line: 0,
redactions: 0,
};
if env_dump(&r.text) || env_dump(&fail.cmd) {
skips.env_dump += 1;
break;
}
if let Some(l) = finish(l, file, fail.line, turn_of(evs, ui), skips, min) {
out.push(l);
}
break;
}
}
for (i, c) in evs.iter().enumerate() {
if c.kind != Kind::User {
continue;
}
let prev_text = evs[..i].iter().rev().find(|e| e.kind == Kind::Assistant).map(|e| e.text.as_str()).unwrap_or("");
if !is_correction(&c.text, prev_text) {
continue;
}
let Some(action) = evs[..i].iter().rev().find(|e| matches!(e.kind, Kind::ToolUse | Kind::Assistant)) else {
continue;
};
let mut end = evs.len().min(i + 61);
for k in i + 1..end {
if evs[k].kind == Kind::User && is_correction(&evs[k].text, "") {
end = k;
break;
}
}
let after = &evs[i + 1..end];
if touches_credentials(&action.cmd) || after.iter().any(|e| e.kind == Kind::ToolUse && touches_credentials(&e.cmd)) {
skips.credentials += 1;
continue;
}
let test = after.iter().find_map(|e| {
if e.kind != Kind::ToolResult || e.err {
return None;
}
let &ui = by_id.get(e.id.as_str())?;
(ui > i && is_verifier(&evs[ui].cmd) && passed(&e.text)).then(|| evs[ui].cmd.clone())
});
let confirm = after.iter().find(|e| e.kind == Kind::User).is_some_and(|e| is_confirm(&e.text));
if test.is_none() && !confirm {
skips.no_success += 1;
continue;
}
let mut conf: f64 = 0.45;
if test.is_some() {
conf += 0.25;
}
if confirm {
conf += 0.15;
}
let words = c.text.split_whitespace().count();
if words >= 6 {
conf += 0.1;
} else if words < 4 {
conf -= 0.15;
}
let agent_after = after.iter().find(|e| e.kind == Kind::Assistant).map(|e| clip(&e.text, 240)).unwrap_or_default();
let proof = match (&test, confirm) {
(Some(t), true) => format!("`{}` then passed and the user confirmed", clip(t, 120)),
(Some(t), false) => format!("`{}` then passed", clip(t, 120)),
_ => "the user then confirmed".to_string(),
};
let how = if agent_after.is_empty() { proof } else { format!("{agent_after} ({proof})") };
let acted = if action.kind == Kind::ToolUse { format!("ran `{}`", clip(&action.cmd, 160)) } else { format!("said \"{}\"", clip(&action.text, 160)) };
let head: String = clip(&c.text, 70);
let l = Lesson {
kind: "correction",
title: format!("Correction: {head}"),
when: last_user_before(evs, i).map(|g| clip(&g.text, 200)).unwrap_or_else(|| clip(&c.text, 200)),
found: format!("The agent {acted}. The user rejected it: \"{}\"", clip(&c.text, 240)),
how,
evidence: String::new(),
tags: "mined,correction".into(),
confidence: conf.clamp(0.0, 0.95),
file: String::new(),
line: 0,
redactions: 0,
};
if let Some(l) = finish(l, file, c.line, turn_of(evs, i), skips, min) {
out.push(l);
}
}
out
}
pub(crate) fn collect(path: &Path, out: &mut Vec<PathBuf>, depth: usize) {
if path.is_file() {
if path.extension().is_some_and(|e| e == "jsonl") || depth == 0 {
out.push(path.to_path_buf());
}
return;
}
let Ok(rd) = fs::read_dir(path) else { return };
let mut entries: Vec<_> = rd.filter_map(Result::ok).map(|e| e.path()).collect();
entries.sort();
for p in entries {
if p.is_dir() {
if depth < 8 {
collect(&p, out, depth + 1);
}
} else if p.extension().is_some_and(|e| e == "jsonl") {
out.push(p);
}
}
}
pub(crate) fn default_files() -> Vec<PathBuf> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let mut out = Vec::new();
if let Ok(rd) = fs::read_dir(home.join(".claude/projects")) {
let mut dirs: Vec<_> = rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();
dirs.sort();
for d in dirs {
if let Ok(files) = fs::read_dir(&d) {
let mut fs_: Vec<_> = files.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "jsonl")).collect();
fs_.sort();
out.extend(fs_);
}
}
}
collect(&home.join(".codex/sessions"), &mut out, 1);
out
}
pub(crate) fn recent(p: &Path, since: u64) -> bool {
let m = fs::metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok());
m.is_some_and(|m| m.as_secs() + since >= now_secs())
}
fn similar(a: &HashSet<String>, b: &HashSet<String>) -> bool {
let inter = a.intersection(b).count() as f64;
let union = a.union(b).count() as f64;
union > 0.0 && inter / union >= 0.8
}
fn lesson_in(l: &Lesson, project: &str) -> BankIn {
BankIn {
title: l.title.clone(),
when: l.when.clone(),
found: l.found.clone(),
how: l.how.clone(),
evidence: l.evidence.clone(),
reconsider: String::new(),
tags: l.tags.clone(),
project: project.to_string(),
persona: String::new(),
applicability_harness: String::new(),
applicability_version: String::new(),
applicability_machine: None,
}
}
pub fn run(argv: &[String]) -> Result<(), String> {
let o = opts(argv)?;
if o.help {
println!("{MINE_HELP}");
return Ok(());
}
let store = match &o.store {
Some(p) => Some(PathBuf::from(p)),
None => default_store().ok(),
};
if o.apply {
match &store {
Some(p) if o.store.is_none() && std::env::var_os("INSTINCT_STORE").is_none_or(|v| v.is_empty()) => ensure_default_dir(p)?,
Some(_) => {}
None => return Err("no home directory found: --apply needs a bank; set INSTINCT_STORE".into()),
}
}
let mut files = Vec::new();
if o.paths.is_empty() {
files = default_files();
} else {
for p in &o.paths {
let path = PathBuf::from(p);
if !path.exists() {
return Err(format!("{p}: no such file or folder"));
}
collect(&path, &mut files, 0);
}
}
let proj = o.project.to_lowercase();
files.retain(|f| (proj.is_empty() || f.to_string_lossy().to_lowercase().contains(&proj)) && o.since.is_none_or(|s| recent(f, s)));
let mut existing_ids: HashSet<String> = HashSet::new();
let (mut bank_text, mut run_text): (Vec<HashSet<String>>, Vec<HashSet<String>>) = (Vec::new(), Vec::new());
if let Some(p) = store.as_ref().filter(|p| p.is_file()) {
for d in load(p)? {
bank_text.push(word_set(&format!("{} {}", d.when, d.found)));
existing_ids.insert(d.id);
}
}
let mut skips = Skips::default();
let mut new: Vec<(String, Lesson, bool)> = Vec::new(); let (mut dup_bank, mut dup_run, mut scanned, mut unreadable) = (0, 0, 0, 0);
let mut run_ids: HashSet<String> = HashSet::new();
let scope = eligibility::Scope { project: o.project.clone(), ..Default::default() };
for f in &files {
let evs = match read_events(f) {
Ok(e) => e,
Err(_) => {
unreadable += 1;
continue;
}
};
scanned += 1;
let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
for l in mine_events(&evs, &name, o.min_conf, &mut skips) {
let d = bank_discovery(lesson_in(&l, &o.project), &scope)?;
let text = word_set(&format!("{} {}", l.when, l.found));
if existing_ids.contains(&d.id) || bank_text.iter().any(|t| similar(t, &text)) {
dup_bank += 1;
continue;
}
if !run_ids.insert(d.id.clone()) || run_text.iter().any(|t| similar(t, &text)) {
dup_run += 1;
continue;
}
run_text.push(text);
new.push((d.id, l, false));
}
}
new.sort_by(|a, b| b.1.confidence.partial_cmp(&a.1.confidence).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
let cut = new.len().saturating_sub(o.limit);
new.truncate(o.limit);
let mut banked = 0;
if o.apply {
let path = store.as_ref().expect("apply has a store");
for (_, l, _) in &new {
let msg = op_bank_as(path, lesson_in(l, &o.project), "mined")?;
if msg.starts_with("banked") {
banked += 1;
}
}
}
let redactions: usize = new.iter().map(|(_, l, _)| l.redactions).sum();
if o.json {
let list: Vec<String> = new
.iter()
.map(|(id, l, _)| {
format!(
"{{\"id\":\"{id}\",\"kind\":\"{}\",\"confidence\":{:.2},\"source\":\"{}:{}\",\"title\":\"{}\",\"when\":\"{}\",\"found\":\"{}\",\"how\":\"{}\",\"evidence\":\"{}\",\"tags\":\"{}\"}}",
l.kind, l.confidence, escape_json(&l.file), l.line, escape_json(&l.title), escape_json(&l.when),
escape_json(&l.found), escape_json(&l.how), escape_json(&l.evidence), escape_json(&l.tags)
)
})
.collect();
println!(
"{{\"mode\":\"{}\",\"transcripts\":{scanned},\"unreadable\":{unreadable},\"candidates\":{},\"cut_by_limit\":{cut},\"already_banked\":{dup_bank},\"repeated_in_run\":{dup_run},\"banked\":{banked},\"redactions\":{redactions},\"skipped\":{{\"no_success\":{},\"probe\":{},\"transient\":{},\"env_dump\":{},\"rejected\":{},\"script\":{},\"credentials\":{},\"low_confidence\":{}}},\"lessons\":[{}]}}",
if o.apply { "apply" } else { "dry-run" },
new.len(), skips.no_success, skips.probe, skips.transient, skips.env_dump, skips.rejected, skips.script, skips.credentials, skips.low_confidence,
list.join(",")
);
return Ok(());
}
println!(
"{scanned} transcript(s) scanned{}",
if o.apply { "" } else { " (dry run, add --apply to bank)" }
);
for (id, l, _) in &new {
println!(" {id} conf {:.2} {:<10} {}:{}", l.confidence, l.kind, l.file, l.line);
println!(" title: {}", l.title);
println!(" when: {}", l.when);
println!(" found: {}", l.found);
println!(" how: {}", l.how);
println!(" evidence: {}", l.evidence);
}
println!(
"{} {} new, {dup_bank} already banked, {dup_run} repeated in this run; redacted {redactions} secret(s)",
if o.apply { "banked:" } else { "would bank:" },
if o.apply { banked } else { new.len() },
);
if cut > 0 {
println!("{cut} more candidate(s) found and cut by --limit {} (raise it to see them)", o.limit);
}
println!(
"skipped: {} correction(s) with no success, {} probe, {} transient, {} user-rejected, {} env dump, {} one-off script, {} credentials, {} below confidence {}",
skips.no_success, skips.probe, skips.transient, skips.rejected, skips.env_dump, skips.script, skips.credentials, skips.low_confidence, o.min_conf
);
Ok(())
}