instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! `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");
    }
}