instinct-cli 0.3.8

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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
//! `instinct mine [PATHS...] [--since 7d] [--project P] [--apply] [--json]`.
//!
//! Reads Claude Code transcripts (~/.claude/projects/*/*.jsonl) and Codex sessions (~/.codex/sessions/**/*.jsonl),
//! or the paths given, and turns two kinds of evidence into candidate lessons without any model:
//!   * a correction window: the user rejects what the agent did ("no, don't ...", "that's wrong", "actually ..."),
//!     and a later step succeeds (a test or build passes, or the user confirms);
//!   * a recovery window: a tool call fails, then a changed call of the same command succeeds.
//! Dry run by default. `--apply` banks the candidates as `source: mined`, which the engine only recalls once the
//! lesson has a hit or matches very closely (see eligibility: candidate_match_unproven).
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)
}

// ---------------------------------------------------------------- transcript model

#[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,
}

/// Cheap prefilter for both Stop gates. The event parser checks the actual roles and block types.
pub(crate) fn possible_user_line(line: &str) -> bool {
    line.contains("\"user\"") && !line.contains("\"tool_result\"")
}

/// Claude Code transcript lines as events for the gates: typed user text only (harness blocks stripped, tool
/// echoes dropped), full assistant text, tool calls, and tool results with their error flag. Nothing is redacted
/// or printed by the caller.
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);
    }
    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,
    }
}

/// Text of a `content` value: a string, or an array of {type:text,text} blocks.
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(),
    }
}

/// Real user text, not harness chatter (task notices, slash commands, interrupts, injected context).
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")
}

/// Blocks the harness puts into user turns that the person never typed.
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",
];

/// `t` without the harness blocks (`<tag ...>...</tag>`; an unclosed block runs to the end). Words inside a
/// pasted block or a notification were not typed, so a detector must never see them.
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
}

/// The user text to keep, or `None`. `typed` also strips harness blocks first, so a turn that was only a
/// notification or a pasted block is not a prompt at all.
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())
    }
}

/// Same typed-user boundary used by scan, without reading a transcript or retaining its text.
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); }
    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) {
    if matches!(top.get("isSidechain"), Some(Json::Bool(true)))
        || matches!(top.get("isMeta"), Some(Json::Bool(true)))
    {
        return;
    }
    // Tool output echoed as a user turn, and the summary written when a session is compacted, are not typed.
    if typed
        && top.get("type").and_then(Json::as_str) == Some("user")
        && (top.get("toolUseResult").is_some()
            || 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 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" => {
                        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(),
                            ..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(),
                // ["bash","-lc","the command"]: the last element is the command itself
                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("function_call_output") => {
            let raw = p.get("output").and_then(Json::as_str).unwrap_or("");
            // older sessions wrap the result: {"output": "...", "metadata": {"exit_code": N}}
            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)
}

/// `lite` is for read-only reports (`instinct scan`): tool results are dropped, assistant text is cleared and
/// nothing is redacted, because the caller only counts and redacts what it prints. Same parsers, a lot less work.
pub(crate) fn read_events_with(path: &Path, lite: 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);
        if codex.is_none() && line.contains("\"payload\"") {
            codex = Some(true);
        }
        let Ok(top) = parse_json(line.trim()) else {
            continue;
        };
        let from = out.len();
        if codex == Some(true) {
            codex_events(&top, n, &mut out, lite);
        } else {
            claude_events(&top, n, &mut out, lite);
        }
        if lite {
            let mut keep = from;
            for i in from..out.len() {
                if out[i].kind == Kind::ToolResult {
                    continue;
                }
                if out[i].kind == Kind::Assistant {
                    out[i].text.clear();
                }
                out.swap(keep, i);
                keep += 1;
            }
            out.truncate(keep);
            continue;
        }
        // Redact before anything clips the text: a clip through the middle of a key would leave half of it.
        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)
}

// ---------------------------------------------------------------- redaction

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, '"' | '\'' | ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '`')
}

/// A bare string that is a credential on its own: known prefixes, AWS ids, JWTs, long mixed random runs.
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());
        // a 40-character hex string is a git commit, not a key
        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))
}

/// One whitespace-delimited token. `prev` are the preceding tokens (lowercased) for `Bearer X` and `--password X`.
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}")
    };
    // user:password@host in a URL
    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..]));
                }
            }
        }
    }
    // NAME=value and "name":"value"
    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()
}

/// Redacts credentials; returns the text and how many were replaced.
pub(crate) fn redact(s: &str) -> (String, usize) {
    let mut count = 0;
    let mut text = s.to_string();
    // PEM blocks, through the END line or the end of the text
    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)
}

/// Four or more NAME=value lines: an environment dump, never a lesson.
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
}

// ---------------------------------------------------------------- text helpers

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))
}

/// A result that reads as success for a build or test run.
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")
}

// ---------------------------------------------------------------- windows

#[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;
    }
    // "no" answering the agent's own yes/no question is a choice, not a correction
    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))
}

/// Commands or paths that change credentials or access. Such windows are never mined, whatever happened next.
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;
    }
    // .env, .env.local, /app/.env : a dotenv file, not words like ".envelope"
    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;
    }
    // events are redacted as they are read, so count what the lesson carries
    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();

    // recovery windows: a failed call, then a changed call of the same command that succeeds
    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;
        }
        // a heredoc or multi-line script is a one-off program, not a command someone would reuse
        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;
        }
    }

    // correction windows: the user rejects, a later step succeeds
    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;
        };
        // what happened after: stop at the next correction
        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
}

// ---------------------------------------------------------------- files

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);
        }
    }
}

fn default_files() -> Vec<PathBuf> {
    let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let mut out = Vec::new();
    // Claude Code: one folder per project, one .jsonl per session (sub-agent logs sit deeper and are skipped)
    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
}

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())
}

// ---------------------------------------------------------------- run

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(); // (id, lesson, already banked)
    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(())
}