//! `instinct learn [PATHS...] [--days 30] [--project P] [--limit 10] [--apply] [--json] [--store PATH]`.
//!
//! Closes the loop after `instinct scan`: it reads the transcripts you already have (Claude Code and Codex), finds shell
//! commands that failed and were retried in a corrected form, and commands the user corrected right after, and proposes
//! a `cmd:` tripwire for each pattern seen at least twice. When the corrected form is a token-level edit of the failed one
//! (a flag added, dropped or swapped, a subcommand swapped) the proposal also carries the fix.
//!
//! Only flags and subcommand words ever reach a proposal. Paths, patterns, values and every other argument stay out, so a
//! proposal cannot carry a secret and shows no transcript text. Evidence is counts and dates (file modification dates).
//!
//! Replay scoring: each proposal is run over the commands that worked the first time in that same history. A proposal
//! that would fire on more than 1% of them is dropped (and the proposals together may not exceed 1%), and the report says
//! how many of the original failures each tripwire would have caught. Reads only; `--apply` banks the proposals as
//! candidate lessons, the same way `instinct mine --apply` does.
//! Sibling access goes through `super::` because the playground compiles main.rs as a submodule.
use super::mine::{self, Ev, Kind};
use super::*;
pub const LEARN_HELP: &str = "usage: instinct learn [PATHS...] [--days 30] [--project P] [--limit 10] [--apply] [--json] [--store PATH]\n\
Learns tripwires and fixes from your own transcripts. No model, nothing leaves the machine.\n\
PATHS are transcript files or folders (*.jsonl). With none, reads ~/.claude/projects/*/*.jsonl and ~/.codex/sessions/**/*.jsonl.\n\
retry pattern a shell command failed, then a changed form of the same command worked: the same edit seen\n\
at least twice becomes a cmd: tripwire, plus a fix when the change is a flag or subcommand edit\n\
correction pattern a command followed by you correcting the agent, seen at least twice\n\
Only flags and subcommand words are used; paths, values and other arguments never appear. Each proposal is replayed over\n\
your commands that worked the first time: one that would fire on more than 1% of them is dropped.\n\
--days N only transcripts modified in the last N days (default 30)\n\
--project P only paths containing P; --apply also scopes the lessons to project P\n\
--limit N show and bank at most N proposals, most repeated first (default 10)\n\
--apply bank the proposals as candidate lessons (default: dry run)\n\
--store PATH bank file to write to (default: INSTINCT_STORE or the usual bank)\n\
--json print the counts and proposals as JSON";
const MIN_SEEN: usize = 2;
/// Replay limit: at most 1 in 100 of the commands that worked first time may match.
const FALSE_ALARM_PCT: usize = 1;
// ---------------------------------------------------------------- tokens
fn is_flag(t: &str) -> bool {
let body = t.trim_start_matches('-');
let dashes = t.len() - body.len();
(1..=2).contains(&dashes)
&& t.len() <= 24
&& body.starts_with(|c: char| c.is_ascii_alphabetic())
&& body.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
/// A subcommand word right after the command: `ci`, `add`, `push`. Never later in the line, where it is an argument.
fn is_sub(t: &str, idx: usize) -> bool {
idx == 1 && t.len() <= 16 && t.starts_with(|c: char| c.is_ascii_lowercase()) && t.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// Tools whose first word is a subcommand. For any other command that word is an argument (`grep foo`, `cd src`) and
/// never generalises.
const SUB_TOOLS: [&str; 33] = [
"git", "npm", "pnpm", "yarn", "bun", "deno", "cargo", "rustup", "docker", "podman", "kubectl", "helm", "terraform", "pip", "pip3", "uv", "poetry", "conda", "go", "gh", "brew", "apt",
"apt-get", "dnf", "systemctl", "gcloud", "aws", "az", "nvm", "make", "mvn", "gradle", "dotnet",
];
fn general(head: &str, t: &str, idx: usize) -> bool {
is_flag(t) || (is_sub(t, idx) && SUB_TOOLS.contains(&head))
}
fn is_head(t: &str) -> bool {
!t.is_empty() && t.len() <= 24 && t.starts_with(|c: char| c.is_ascii_alphabetic()) && t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
}
/// The command split into pipeline segments at unquoted `; | & ` and newlines, each as words (quotes removed). A leading
/// `VAR=value` or `sudo` is dropped so the first word is the command.
fn segments(cmd: &str) -> Vec<Vec<String>> {
let mut raws: Vec<String> = Vec::new();
let mut cur = String::new();
let mut quote = None::<char>;
let mut prev_escape = false;
for c in cmd.chars() {
if let Some(q) = quote {
cur.push(c);
if c == q && !(q == '"' && prev_escape) {
quote = None;
}
} else if matches!(c, '"' | '\'') {
quote = Some(c);
cur.push(c);
} else if matches!(c, ';' | '|' | '&' | '\n') {
raws.push(std::mem::take(&mut cur));
} else {
cur.push(c);
}
prev_escape = c == '\\' && !prev_escape;
}
raws.push(cur);
raws.iter()
.map(|r| {
let mut w = tripwire::words(r);
while w.first().is_some_and(|t| t == "sudo" || (t.contains('=') && !t.starts_with('-'))) {
w.remove(0);
}
w
})
.filter(|w| !w.is_empty())
.collect()
}
// ---------------------------------------------------------------- one edit
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Shape {
Add,
Drop,
Swap,
}
#[derive(Clone, Debug)]
struct Proposal {
/// The `cmd:` matcher text (after `cmd:`).
spec: String,
shape: Option<Shape>,
/// Plain words for the fix: `add -A`, `drop --force`, `ci instead of i`.
fix: String,
head: String,
/// The generalised tokens, for the title.
from: Vec<String>,
to: Vec<String>,
}
/// The single token-level edit between a failed segment and the corrected one, when it generalises.
fn edit(f: &[String], c: &[String]) -> Result<Proposal, &'static str> {
if f.len() < 2 && c.len() < 2 {
return Err("no_arguments");
}
let head = f.first().ok_or("no_arguments")?;
if head != c.first().ok_or("no_arguments")? || !is_head(head) {
return Err("head_changed");
}
let mut p = 1;
while p < f.len() && p < c.len() && f[p] == c[p] {
p += 1;
}
let mut s = 0;
while p + s < f.len() && p + s < c.len() && f[f.len() - 1 - s] == c[c.len() - 1 - s] {
s += 1;
}
let x = &f[p..f.len() - s];
let y = &c[p..c.len() - s];
if x.len() + y.len() == 0 {
return Err("same_words");
}
if x.len() > 2 || y.len() > 2 {
return Err("bigger_than_two_words");
}
if x.iter().enumerate().any(|(i, t)| !general(head, t, p + i)) || y.iter().enumerate().any(|(i, t)| !general(head, t, p + i)) {
return Err("argument_changed");
}
let (spec, shape, fix) = if x.is_empty() {
// A flag was added: the tripwire fires on the command that has its neighbour flag but not the new one.
if y.iter().any(|t| !is_flag(t)) {
return Err("argument_changed");
}
let anchor = f
.get(p)
.filter(|t| is_flag(t))
.or_else(|| p.checked_sub(1).filter(|&i| i >= 1).and_then(|i| f.get(i)).filter(|t| is_flag(t)))
.ok_or("no_flag_to_anchor_on")?;
let negs: Vec<String> = y.iter().map(|t| format!("!{t}")).collect();
(format!("{head} {anchor} {}", negs.join(" ")), Shape::Add, format!("add {}", y.join(" ")))
} else if y.is_empty() {
if x.iter().any(|t| !is_flag(t)) {
return Err("argument_changed");
}
(format!("{head} {}", x.join(" ")), Shape::Drop, format!("drop {}", x.join(" ")))
} else {
(format!("{head} {}", x.join(" ")), Shape::Swap, format!("{} instead of {}", y.join(" "), x.join(" ")))
};
Ok(Proposal { spec, shape: Some(shape), fix, head: head.clone(), from: x.to_vec(), to: y.to_vec() })
}
/// The edit between two whole commands: the same number of segments, exactly one of them different.
/// Err carries the reason it is not a token-level edit, for the aggregate breakdown.
fn pair(failed: &str, fixed: &str) -> Result<Proposal, &'static str> {
let (a, b) = (segments(failed), segments(fixed));
if a.len() != b.len() {
return Err("different_number_of_pipeline_steps");
}
let diff: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect();
match diff.as_slice() {
[i] => edit(&a[*i], &b[*i]),
[] => Err("same_words"),
_ => Err("several_steps_changed"),
}
}
// ---------------------------------------------------------------- reading history
struct Shell {
cmd: String,
ok: bool,
}
/// What one transcript contributes.
#[derive(Default)]
struct Session {
date: String,
/// (failed command, corrected command) pairs: the retry succeeded.
retries: Vec<(String, String)>,
/// Commands that worked the first time (not a corrected retry).
first_ok: Vec<String>,
/// First-try failures.
failed: usize,
/// Command signature (head + subcommand) each time the user corrected the agent right after it.
corrected: Vec<String>,
shell_total: usize,
}
fn ymd(secs: u64) -> String {
let z = (secs / 86_400) as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}")
}
fn signature(cmd: &str) -> Option<String> {
let seg = segments(cmd).into_iter().last()?;
let head = seg.first().filter(|h| is_head(h))?;
let sub = seg.get(1).filter(|t| general(head, t, 1))?;
Some(format!("{head} {sub}"))
}
/// A retry is the same command again, changed: same first word and most of the words shared. A different command that
/// happens to follow a failure is not a retry.
fn same_intent(failed: &str, fixed: &str) -> bool {
let (a, b) = (tripwire::words(failed), tripwire::words(fixed));
if a.first().is_none() || a.first() != b.first() {
return false;
}
let (sa, sb): (HashSet<&String>, HashSet<&String>) = (a.iter().collect(), b.iter().collect());
let shared = sa.intersection(&sb).count();
// At least half of each command's words are in the other.
shared * 2 >= sa.len() && shared * 2 >= sb.len()
}
fn read_session(path: &Path, codex: bool) -> Option<Session> {
let evs: Vec<Ev> = mine::read_events_with(path, false).ok()?;
let mtime = fs::metadata(path).and_then(|m| m.modified()).ok()?.duration_since(UNIX_EPOCH).ok()?.as_secs();
let mut s = Session { date: ymd(mtime), ..Session::default() };
let results: HashMap<&str, bool> = evs.iter().filter(|e| e.kind == Kind::ToolResult).map(|e| (e.id.as_str(), !e.err)).collect();
let result_of = |id: &str| results.get(id).copied();
// The shell commands of this session, in order, with whether each worked.
let mut shells: Vec<(usize, Shell)> = Vec::new();
for (i, e) in evs.iter().enumerate() {
if e.kind != Kind::ToolUse || e.cmd.trim().is_empty() || !(codex || e.text == "Bash") {
continue;
}
if mine::touches_credentials(&e.cmd) {
continue;
}
let Some(ok) = result_of(&e.id) else { continue };
shells.push((i, Shell { cmd: e.cmd.trim().to_string(), ok }));
}
s.shell_total = shells.len();
let user_between = |a: usize, b: usize| evs[a..b].iter().any(|e| e.kind == Kind::User);
let mut retried = vec![false; shells.len()];
for (n, (i, f)) in shells.iter().enumerate() {
if f.ok {
continue;
}
s.failed += 1;
// Within the next few commands of the same turn, the first changed form that worked is the retry.
for (m, (j, c)) in shells.iter().enumerate().skip(n + 1).take(5) {
if user_between(*i, *j) {
break;
}
if c.ok && !retried[m] && c.cmd != f.cmd && same_intent(&f.cmd, &c.cmd) {
retried[m] = true;
s.retries.push((f.cmd.clone(), c.cmd.clone()));
break;
}
}
}
for (n, (_, c)) in shells.iter().enumerate() {
if c.ok && !retried[n] {
s.first_ok.push(c.cmd.clone());
}
}
// A command followed, before the next shell command, by the user correcting the agent.
let mut pending: Option<(Option<String>, String)> = None;
for e in &evs {
match e.kind {
Kind::ToolUse if (codex || e.text == "Bash") && !e.cmd.trim().is_empty() && !mine::touches_credentials(&e.cmd) => pending = Some((signature(&e.cmd), e.cmd.trim().to_string())),
Kind::User => {
if let Some((sig, cmd)) = pending.take() {
if corrections::correction(&e.text) {
// Not a clean success either: the user had to correct what followed it.
if let Some(at) = s.first_ok.iter().position(|c| *c == cmd) {
s.first_ok.remove(at);
}
s.corrected.extend(sig);
}
}
}
_ => {}
}
}
Some(s)
}
// ---------------------------------------------------------------- the report
struct Found {
p: Proposal,
kind: &'static str,
seen: usize,
sessions: usize,
first: String,
last: String,
/// Replay over the commands that worked first time: how many it would have fired on.
false_alarms: usize,
/// Replay over the original failures: how many it fires on, of how many.
caught: usize,
of: usize,
}
struct Opts {
paths: Vec<String>,
days: u64,
project: String,
limit: usize,
apply: bool,
json: bool,
store: Option<String>,
help: bool,
}
fn opts(argv: &[String]) -> Result<Opts, String> {
let mut o = Opts { paths: Vec::new(), days: 30, project: String::new(), limit: 10, apply: false, json: false, store: None, 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,
"--days" => o.days = value("--days")?.parse().ok().filter(|n: &u64| *n >= 1).ok_or("--days needs a number of 1 or more")?,
"--limit" => o.limit = value("--limit")?.parse().ok().filter(|n: &usize| *n >= 1).ok_or("--limit needs a number of 1 or more")?,
"--project" => o.project = value("--project")?,
"--store" => o.store = Some(value("--store")?),
_ if a.starts_with("--days=") => o.days = value("--days")?.parse().ok().filter(|n: &u64| *n >= 1).ok_or("--days needs a number of 1 or more")?,
_ if a.starts_with("--limit=") => o.limit = value("--limit")?.parse().ok().filter(|n: &usize| *n >= 1).ok_or("--limit needs a number of 1 or more")?,
_ if a.starts_with("--project=") => o.project = value("--project")?,
_ if a.starts_with("--store=") => o.store = Some(value("--store")?),
_ if a.starts_with('-') => return Err(format!("unknown option {a}\n{LEARN_HELP}")),
_ => o.paths.push(a.to_string()),
}
i += 1;
}
Ok(o)
}
fn commas(n: usize) -> 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 matches_spec(spec: &str, cmd: &str) -> bool {
tripwire::best_match(&format!("cmd:{spec}"), &tripwire::command_words(cmd)).is_some()
}
fn title_of(p: &Proposal) -> String {
match p.shape {
Some(Shape::Add) => format!("`{}`: add {}", p.head, p.to.join(" ")),
Some(Shape::Drop) => format!("`{}`: drop {}", p.head, p.from.join(" ")),
Some(Shape::Swap) => format!("`{}`: {} instead of {}", p.head, p.to.join(" "), p.from.join(" ")),
None => format!("`{}` was corrected afterwards", p.spec),
}
}
fn lesson(f: &Found, project: &str) -> BankIn {
let span = if f.first == f.last { f.first.clone() } else { format!("{} to {}", f.first, f.last) };
let (when, found, how) = match f.p.shape {
Some(_) => (
format!("Running `{}` in this form", f.p.spec.replace(" !", " without ")),
format!("This form failed and a changed form worked on the retry, {} times in {} sessions ({span}).", f.seen, f.sessions),
format!("Fix: {}. Check the corrected form before running it.", f.p.fix),
),
None => (
format!("Running `{}`", f.p.spec),
format!("You corrected the agent right after this command {} times in {} sessions ({span}).", f.seen, f.sessions),
"Re-read your last instruction before running it and check it still holds.".to_string(),
),
};
let fix_tag = f.p.shape.as_ref().map(|_| format!(";fix:{}", f.p.fix)).unwrap_or_default();
BankIn {
title: title_of(&f.p),
when,
found,
how,
evidence: format!("learned from {} sessions, {span}; replay: {} of {} failures caught, {} false alarms", f.sessions, f.caught, f.of, f.false_alarms),
reconsider: String::new(),
tags: format!("tool_bash;learned;cmd:{}{}", f.p.spec, fix_tag),
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!("{LEARN_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<PathBuf> = Vec::new();
if o.paths.is_empty() {
files = mine::default_files();
} else {
for p in &o.paths {
mine::collect(Path::new(p), &mut files, 0);
}
}
let window = o.days.saturating_mul(86_400);
files.retain(|p| (o.paths.is_empty() && mine::recent(p, window) || !o.paths.is_empty()) && (o.project.is_empty() || p.to_string_lossy().contains(&o.project)));
let mut sessions: Vec<Session> = Vec::new();
let mut unreadable = 0usize;
for f in &files {
let codex = f.to_string_lossy().contains("/.codex/") || f.to_string_lossy().contains("\\.codex\\");
match read_session(f, codex) {
Some(s) => sessions.push(s),
None => unreadable += 1,
}
}
let shell_total: usize = sessions.iter().map(|s| s.shell_total).sum();
let failed: usize = sessions.iter().map(|s| s.failed).sum();
let retried: usize = sessions.iter().map(|s| s.retries.len()).sum();
// Group the edits and the corrections by the tripwire they would make.
let mut groups: Vec<(Proposal, &'static str, Vec<usize>, Vec<String>)> = Vec::new();
let mut edits = 0usize;
// Why a retry was not a flag or subcommand edit, counted: it explains an empty result.
let mut not_edits: Vec<(&'static str, usize)> = Vec::new();
for (si, s) in sessions.iter().enumerate() {
for (f, c) in &s.retries {
match pair(f, c) {
Ok(p) => {
edits += 1;
match groups.iter_mut().find(|g| g.0.spec == p.spec && g.0.fix == p.fix) {
Some(g) => {
g.2.push(si);
g.3.push(f.clone());
}
None => groups.push((p, "retry", vec![si], vec![f.clone()])),
}
}
Err(why) => match not_edits.iter_mut().find(|(w, _)| *w == why) {
Some((_, n)) => *n += 1,
None => not_edits.push((why, 1)),
},
}
}
}
not_edits.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (si, s) in sessions.iter().enumerate() {
for sig in &s.corrected {
if groups.iter().any(|g| g.1 == "retry" && g.0.spec == *sig) {
// Already covered by a retry pattern on the same command: count it there.
continue;
}
match groups.iter_mut().find(|g| g.1 == "correction" && g.0.spec == *sig) {
Some(g) => g.2.push(si),
None => groups.push((
Proposal { spec: sig.clone(), shape: None, fix: String::new(), head: sig.split(' ').next().unwrap_or("").into(), from: Vec::new(), to: Vec::new() },
"correction",
vec![si],
Vec::new(),
)),
}
}
}
let too_few = groups.iter().filter(|g| g.2.len() < MIN_SEEN).count();
groups.retain(|g| g.2.len() >= MIN_SEEN);
// Replay: the commands that worked the first time, and the first failures.
let ok_cmds: Vec<&String> = sessions.iter().flat_map(|s| s.first_ok.iter()).collect();
let fail_cmds: Vec<&String> = sessions.iter().flat_map(|s| s.retries.iter().map(|(f, _)| f)).collect();
let total_ok = ok_cmds.len();
let mut found: Vec<Found> = Vec::new();
let mut dropped_noisy = 0usize;
let mut scored: Vec<(Found, Vec<usize>)> = Vec::new();
for (p, kind, seen_in, _) in groups {
let hits: Vec<usize> = ok_cmds.iter().enumerate().filter(|(_, c)| matches_spec(&p.spec, c)).map(|(i, _)| i).collect();
if hits.len() * 100 > total_ok * FALSE_ALARM_PCT {
dropped_noisy += 1;
continue;
}
let mut uniq = seen_in.clone();
uniq.sort_unstable();
uniq.dedup();
let dates: Vec<&String> = uniq.iter().map(|&i| &sessions[i].date).collect();
let caught = fail_cmds.iter().filter(|c| matches_spec(&p.spec, c)).count();
scored.push((
Found {
p,
kind,
seen: seen_in.len(),
sessions: uniq.len(),
first: dates.iter().min().map(|d| (*d).clone()).unwrap_or_default(),
last: dates.iter().max().map(|d| (*d).clone()).unwrap_or_default(),
false_alarms: hits.len(),
caught,
of: fail_cmds.len(),
},
hits,
));
}
// Together they may not exceed the limit either: fewest false alarms first, then most repeated.
scored.sort_by(|a, b| a.0.false_alarms.cmp(&b.0.false_alarms).then(b.0.seen.cmp(&a.0.seen)).then(a.0.p.spec.cmp(&b.0.p.spec)));
let mut union = vec![false; total_ok];
let mut union_n = 0usize;
for (f, hits) in scored {
let new = hits.iter().filter(|&&i| !union[i]).count();
if (union_n + new) * 100 > total_ok * FALSE_ALARM_PCT {
dropped_noisy += 1;
continue;
}
for i in hits {
union[i] = true;
}
union_n += new;
found.push(f);
}
found.sort_by(|a, b| b.seen.cmp(&a.seen).then(a.p.spec.cmp(&b.p.spec)));
let cut = found.len().saturating_sub(o.limit);
found.truncate(o.limit);
let with_fix = found.iter().filter(|f| f.p.shape.is_some()).count();
let caught_total: usize = found.iter().map(|f| f.caught).sum();
let mut banked = 0usize;
let mut already = 0usize;
if o.apply {
let path = store.as_ref().expect("apply has a store");
for f in &found {
let msg = op_bank_as(path, lesson(f, &o.project), "mined")?;
if msg.starts_with("banked") {
banked += 1;
} else {
already += 1;
}
}
}
let rate = if total_ok == 0 { 0.0 } else { union_n as f64 * 100.0 / total_ok as f64 };
if o.json {
let list: Vec<String> = found
.iter()
.map(|f| {
format!(
"{{\"kind\":\"{}\",\"title\":\"{}\",\"tripwire\":\"cmd:{}\",\"fix\":{},\"seen\":{},\"sessions\":{},\"first\":\"{}\",\"last\":\"{}\",\"replay\":{{\"false_alarms\":{},\"of_first_try_successes\":{},\"failures_caught\":{},\"of_failures\":{}}}}}",
f.kind,
escape_json(&title_of(&f.p)),
escape_json(&f.p.spec),
if f.p.shape.is_some() { format!("\"{}\"", escape_json(&f.p.fix)) } else { "null".into() },
f.seen,
f.sessions,
f.first,
f.last,
f.false_alarms,
total_ok,
f.caught,
f.of
)
})
.collect();
println!(
"{{\"mode\":\"{}\",\"transcripts\":{},\"unreadable\":{unreadable},\"shell_commands\":{shell_total},\"failed\":{failed},\"retried_in_corrected_form\":{retried},\"token_level_edits\":{edits},\"not_token_edits\":{{{}}},\"proposals\":{},\"with_fix\":{with_fix},\"cut_by_limit\":{cut},\"too_few_uses\":{too_few},\"dropped_for_false_alarms\":{dropped_noisy},\"banked\":{banked},\"already_banked\":{already},\"replay\":{{\"first_try_successes\":{total_ok},\"false_alarms\":{union_n},\"false_alarm_pct\":{rate:.2},\"limit_pct\":{FALSE_ALARM_PCT},\"failures_caught\":{caught_total}}},\"lessons\":[{}]}}",
if o.apply { "apply" } else { "dry-run" },
sessions.len(),
not_edits.iter().map(|(w, n)| format!("\"{w}\":{n}")).collect::<Vec<_>>().join(","),
found.len(),
list.join(",")
);
return Ok(());
}
let mut out = String::new();
out.push_str(&format!("instinct learn ({}: nothing leaves this machine)\n\n", if o.apply { "writes the bank" } else { "read-only" }));
out.push_str(&format!(
"read {} transcripts from the last {} days: {} shell commands, {} failed first, {} retried in a changed form, {} of those a flag or subcommand edit\n",
commas(sessions.len()),
o.days,
commas(shell_total),
commas(failed),
commas(retried),
commas(edits)
));
if !not_edits.is_empty() {
out.push_str(&format!(
"not edits {}\n",
not_edits.iter().map(|(w, n)| format!("{n} {}", w.replace('_', " "))).collect::<Vec<_>>().join(", ")
));
}
out.push_str(&format!(
"found {} tripwires ({} with a fix); {} seen fewer than {MIN_SEEN} times, {} dropped for false alarms, {} past --limit\n",
found.len(),
with_fix,
too_few,
dropped_noisy,
cut
));
out.push_str(&format!(
"replay on your {} commands that worked first time they would fire {} times ({:.2}%, limit {FALSE_ALARM_PCT}%); they catch {} of the {} first failures\n",
commas(total_ok),
union_n,
rate,
caught_total,
commas(fail_cmds.len())
));
for (n, f) in found.iter().enumerate() {
out.push_str(&format!("\n{}. {}\n", n + 1, title_of(&f.p)));
out.push_str(&format!(" tripwire cmd:{}\n", f.p.spec));
if f.p.shape.is_some() {
out.push_str(&format!(" fix {}\n", f.p.fix));
}
let span = if f.first == f.last { f.first.clone() } else { format!("{} to {}", f.first, f.last) };
out.push_str(&format!(
" evidence {} {} in {} sessions, {span}; replay: {} false alarms, {} of {} failures caught\n",
f.seen,
if f.kind == "retry" { "retries" } else { "corrections" },
f.sessions,
f.false_alarms,
f.caught,
f.of
));
}
if found.is_empty() {
out.push_str("\nnothing repeated often enough yet: a pattern needs at least 2 uses and under 1% false alarms\n");
} else if o.apply {
out.push_str(&format!("\nbanked: {banked} as candidate lessons ({already} already in the bank). Candidates are held back until a lookup matches closely or you give feedback.\n"));
} else {
out.push_str(&format!("\nwould bank: {} as candidate lessons (dry run, add --apply to bank)\n", found.len()));
}
print!("{out}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn w(s: &str) -> Vec<String> {
segments(s).into_iter().next().unwrap()
}
#[test]
fn an_added_flag_becomes_a_negated_matcher_with_its_neighbour_as_anchor() {
let p = pair("pgrep -f myservice", "pgrep -A -f myservice").unwrap();
assert_eq!(p.spec, "pgrep -f !-A");
assert_eq!(p.fix, "add -A");
}
#[test]
fn a_swapped_subcommand_is_one_token_edit() {
let p = pair("npm i", "npm ci").unwrap();
assert_eq!((p.spec.as_str(), p.fix.as_str()), ("npm i", "ci instead of i"));
}
#[test]
fn arguments_never_generalise() {
assert!(pair("cat /etc/hosts", "cat /etc/hostname").is_err());
assert!(pair("grep foo src", "grep bar src").is_err());
assert!(pair("curl https://a.test", "curl -s https://a.test").is_err(), "no flag anchor to keep it narrow");
}
#[test]
fn segments_split_on_unquoted_separators_only() {
assert_eq!(segments("cd x && pgrep -f 'a;b' | wc -l").len(), 3);
assert_eq!(w("FOO=1 sudo make -j4"), ["make", "-j4"]);
}
#[test]
fn dates_are_civil_days() {
assert_eq!(ymd(0), "1970-01-01");
assert_eq!(ymd(1_764_720_000), "2025-12-03");
}
}