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
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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
//! `instinct scan [--days N] [--json] [--share]`: what did my coding agent get wrong lately, and what would
//! Instinct have caught? A read-only report over the Claude Code and Codex transcripts already on this machine.
//!
//! No network, no bank needed, nothing written. It reuses the readers of `instinct mine` (one line at a time,
//! both formats), the starter pack with the tripwire matcher, the correction detector and the memory-file token
//! estimate of `instinct audit`. Prompt and reply text is only counted, never printed; a command is shown only
//! as a redacted snippet of at most 60 characters.
use super::*;
use mine::Kind;

pub const SCAN_HELP: &str = "usage: instinct scan [--days N] [--json | --format json] [--share]\n\
What did your coding agent get wrong in the last N days (default 30), and what would Instinct have caught?\n\
Reads ~/.claude/projects/*/*.jsonl and ~/.codex/sessions/**/*.jsonl. Read-only: no network, writes nothing,\n\
needs no bank. Prompt and reply text is never printed; commands appear only as redacted 60-character snippets.\n\
  1  risky commands   shell commands the starter tripwires would have warned about, by title, and what `instinct fix` would have rewritten, by rule\n\
  2  corrections      how often you corrected the agent, how often the next message corrected it again, failing commands retried the same way 3+ times, and done-claims with nothing run since the last change\n\
  3  memory files     what CLAUDE.md and AGENTS.md cost across the prompts in the window\n\
  4  waiting          wait loops that match themselves, guess a PID or have no deadline, and the wall time\n\
                      they took where the transcript lets it be measured (shown when there are any)\n\
  5  next steps       runnable lines\n\
  --days N   window in days, by file modification time (default 30)\n\
  --json     the counts and the same snippets as JSON (also --format json)\n\
  --share    print only a short plain-text summary (at most 280 characters); it is never uploaded";

const REPO: &str = "https://github.com/koscak-labs/instinct";
const SNIPPET: usize = 60;
const EXAMPLES: usize = 3;
/// Both reply groups need this many pairs before a ratio is printed.
const MIN_FOR_RATIO: u32 = 20;

#[derive(Default, Clone)]
pub struct Group {
    pub title: String,
    pub count: u32,
    pub examples: Vec<String>,
}

/// What the fix rules and the tripwire matcher do to every distinct shell command, run in this process (the same
/// logic as `instinct fix --dry-run` and `instinct guard` with the starter pack applied, without one process each).
#[derive(Default, Clone)]
pub struct Replay {
    /// Distinct shell commands in the window.
    pub unique: u32,
    pub rewritten_unique: u32,
    pub rewritten_runs: u32,
    /// Rewrites by rule, in runs.
    pub rules: Vec<(String, u32)>,
    pub warned_unique: u32,
    pub warned_runs: u32,
    /// Tripwire warnings by title, in runs (every starter tripwire, as `instinct guard` reads them).
    pub titles: Vec<(String, u32)>,
    /// (rules, changed window before, changed window after), most-run first, redacted.
    pub samples: Vec<(String, String, String)>,
}

#[derive(Default, Clone, Copy)]
pub struct Pairs {
    /// Agent replies that were followed by another user message.
    pub n: u32,
    /// Of those, the next user message was a correction.
    pub repeated: u32,
}

impl Pairs {
    pub fn rate(&self) -> Option<f64> {
        (self.n > 0).then(|| self.repeated as f64 / self.n as f64)
    }
}

#[derive(Default)]
pub struct Report {
    pub days: u64,
    pub files: u32,
    pub claude_files: u32,
    pub codex_files: u32,
    pub skipped_old: u32,
    pub unreadable: u32,
    pub prompts: u32,
    pub claude_prompts: u32,
    pub codex_prompts: u32,
    pub commands: u32,
    pub flagged: u32,
    pub groups: Vec<Group>,
    pub corrections: u32,
    pub after_correction: Pairs,
    pub after_other: Pairs,
    /// (file name, estimated tokens per prompt)
    pub memory: Vec<(String, usize)>,
    pub memory_tokens_in_window: u64,
    /// Part of the total that comes from the user-level files alone.
    pub memory_user_tokens: u64,
    /// Prompts per working folder seen in the window: (folder, Claude Code prompts, Codex prompts).
    pub folders: Vec<(PathBuf, u32, u32)>,
    /// Projects with their own CLAUDE.md or AGENTS.md: (path shown with ~, tokens in the window, prompts).
    pub projects: Vec<(String, u64, u32)>,
    /// How many projects had memory files (the list above is cut to the top 5).
    pub projects_with_memory: u32,
    pub starter: Option<(usize, usize)>,
    /// Failing Bash forms retried the same way 3 or more times in one transcript (Claude Code only).
    pub retried: u32,
    /// Final messages that claimed completion right after a correction with nothing run since the last change.
    pub claimed_done: u32,
    /// Wait commands by class A, B, C (see `WAIT_IDS`). A command that fits two classes is in both.
    pub waits: [WaitClass; 3],
    /// The same commands counted once each, whatever their class.
    pub wait_all: WaitClass,
    /// Fix rewrites and tripwire warnings over every distinct command, run in this process.
    pub replay: Replay,
    /// Shell commands by harness (their sum is `commands`).
    pub claude_commands: u32,
    pub codex_commands: u32,
}

/// The three wait tripwires of the starter pack, in the order the report lists them.
const WAIT_IDS: [&str; 3] = ["wait-pgrep-self-match", "wait-pid-from-pgrep", "wait-no-deadline"];
const WAIT_NAMES: [&str; 3] = [
    "pgrep -f loop that matches its own shell",
    "tail --pid or wait on a PID guessed with pgrep",
    "poll loop with no deadline and no counter",
];

/// One class of wait command. `count` is every command seen; the time is only for the ones where the
/// transcript has both ends, so `secs` is a floor.
#[derive(Default, Clone)]
pub struct WaitClass {
    pub count: u32,
    /// Commands whose start and end are both in the transcript.
    pub measured: u32,
    /// Of those, run in the background and ended by a completion notice.
    pub measured_background: u32,
    pub secs: u64,
    pub longest: u64,
    pub examples: Vec<String>,
}

impl Report {
    pub fn ratio(&self) -> Option<f64> {
        let (a, b) = (self.after_correction, self.after_other);
        if a.n < MIN_FOR_RATIO || b.n < MIN_FOR_RATIO {
            return None;
        }
        let base = b.rate()?;
        (base > 0.0).then(|| a.rate().unwrap_or(0.0) / base)
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum Harness {
    Claude,
    Codex,
}

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

fn secret_key(name: &str) -> bool {
    let n = name.to_lowercase();
    ["key", "token", "secret", "passw", "pwd", "credential", "auth"].iter().any(|s| n.contains(s))
}

/// A value that looks like a credential on its own: a long hex run, or a long mixed-case base64-like run.
fn token_like(v: &str) -> bool {
    let n = v.chars().count();
    let digit = v.chars().any(|c| c.is_ascii_digit());
    if n >= 16 && digit && v.chars().all(|c| c.is_ascii_hexdigit()) {
        return true;
    }
    n >= 24
        && !v.starts_with(['/', '.', '~'])
        && digit
        && v.chars().any(|c| c.is_ascii_uppercase())
        && v.chars().any(|c| c.is_ascii_lowercase())
        && v.chars().all(|c| c.is_ascii_alphanumeric() || "+/_=-".contains(c))
}

/// Anything token-like becomes `***`: the redactor of `instinct mine` first, then a second pass for what it
/// lets through on purpose (bare 16+ character hex, short `KEY=` values).
pub fn redact_snippet(cmd: &str) -> String {
    let head: String = cmd.chars().take(2000).collect();
    let first = mine::redact(&url_userinfo(&head)).0.replace("[REDACTED]", "***");
    let mut out = String::with_capacity(first.len());
    for tok in first.split_inclusive(char::is_whitespace) {
        let word = tok.trim_end();
        let ws = &tok[word.len()..];
        out.push_str(&redact_word(word));
        out.push_str(ws);
    }
    out
}

/// `scheme://user:pass@host` becomes `scheme://***@host`. The userinfo ends at the last `@` before the path,
/// a quote or whitespace; only userinfo that has a `:` (a password) is replaced.
fn url_userinfo(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(i) = rest.find("://") {
        let (head, tail) = rest.split_at(i + 3);
        out.push_str(head);
        let end = tail.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '"' | '\'' | '`')).unwrap_or(tail.len());
        match tail[..end].rfind('@').filter(|at| tail[..*at].contains(':')) {
            Some(at) => {
                out.push_str("***");
                out.push_str(&tail[at..end]);
            }
            None => out.push_str(&tail[..end]),
        }
        rest = &tail[end..];
    }
    out.push_str(rest);
    out
}

fn redact_word(word: &str) -> String {
    let edge = |c: char| matches!(c, '"' | '\'' | '`' | ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}');
    let core = word.trim_matches(edge);
    if core.is_empty() || core.contains("***") {
        return word.to_string();
    }
    let at = word.find(core).unwrap_or(0);
    // mysql -psecret: the password is glued to the flag. Compiler flags that start with -p are left alone.
    if let Some(rest) = core.strip_prefix("-p").filter(|r| !r.is_empty() && !r.starts_with('-')) {
        const FLAGS: [&str; 6] = ["edantic", "thread", "ipe", "g", "ackage", "rofile"];
        let name = core.trim_start_matches('-');
        if !FLAGS.iter().any(|s| name.strip_prefix('p') == Some(*s)) && !rest.contains('=') {
            return format!("{}-p***{}", &word[..at], &word[at + core.len()..]);
        }
    }
    let (lead, tail) = (&word[..at], &word[at + core.len()..]);
    if let Some((name, value)) = core.split_once('=') {
        let named = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
        if (named && secret_key(name) && !value.is_empty()) || token_like(value.trim_matches(edge)) {
            return format!("{lead}{name}=***{tail}");
        }
        return word.to_string();
    }
    if token_like(core) {
        return format!("{lead}***{tail}");
    }
    word.to_string()
}

/// The text shown for a command: redacted first, then cut to 60 characters.
pub fn snippet(cmd: &str) -> String {
    mine::clip(&redact_snippet(cmd), SNIPPET)
}

// ---------------------------------------------------------------- scanning

/// Where transcripts live: (folder, harness). The Claude Code folder holds one folder per project.
pub(crate) fn roots() -> Vec<(PathBuf, Harness)> {
    outcomes::default_roots()
        .into_iter()
        .filter_map(|r| match r.file_name().and_then(|n| n.to_str()) {
            Some("projects") => Some((r, Harness::Claude)),
            Some("sessions") => Some((r, Harness::Codex)),
            _ => None,
        })
        .collect()
}

pub(crate) fn modified_secs(p: &Path) -> Option<u64> {
    fs::metadata(p).and_then(|m| m.modified()).ok()?.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs())
}

pub(crate) fn files_in(root: &Path, harness: Harness) -> Vec<PathBuf> {
    let mut out = Vec::new();
    match harness {
        Harness::Claude => {
            // one .jsonl per session; sub-agent logs sit deeper and are skipped, as in `instinct mine`
            let Ok(rd) = fs::read_dir(root) else { return out };
            for d in rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
                if let Ok(files) = fs::read_dir(&d) {
                    out.extend(files.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "jsonl")));
                }
            }
        }
        Harness::Codex => mine::collect(root, &mut out, 1),
    }
    out.sort();
    out
}

struct Matcher {
    title: String,
    tags: String,
    /// Which wait tripwire this is (index into `WAIT_IDS`): reported in the waiting section, so it is not one of the
    /// risky commands.
    wait: Option<usize>,
}

/// Every starter tripwire with a command matcher, the set `instinct guard` picks from. The risky-command report uses
/// the ones that are not waits, so a wait command is not counted twice.
fn all_matchers() -> Vec<Matcher> {
    starter::pack_matchers()
        .into_iter()
        .filter(|(_, _, tags)| tripwire::has_cmd(tags))
        .map(|(id, title, tags)| Matcher { title, tags, wait: WAIT_IDS.iter().position(|w| *w == id.as_str()) })
        .collect()
}

/// The tags of the three wait tripwires, in class order.
fn wait_matchers() -> Vec<String> {
    let all = starter::pack_matchers();
    WAIT_IDS.iter().map(|id| all.iter().find(|(i, _, _)| i == id).map(|(_, _, t)| t.clone()).unwrap_or_default()).collect()
}

/// Which wait tripwires the command fits, as a bit per class (A is 1, B is 2, C is 4); 0 for none.
/// Read as the guard reads it: text that only a reading command prints is not a command.
fn wait_classes(ws: &[String], cmd: &str) -> u8 {
    let w = tripwire::command_words(cmd);
    ws.iter().enumerate().filter(|(_, tags)| tripwire::best_match(tags, &w).is_some()).fold(0, |m, (i, _)| m | 1 << i)
}

/// A wait command seen in one transcript, until its end shows up.
struct Pending {
    classes: u8,
    start: u64,
    background: bool,
    done: bool,
}

/// For one command: the risky title (the best match among the non-wait tripwires), the title `instinct guard` would show
/// (the best match over every tripwire, first on a tie) and which wait tripwires it fits (a bit per class, as
/// `wait_classes`). One pass over the command's words serves all three.
fn tripwire_titles<'a>(all: &'a [Matcher], cmd: &str) -> (Option<&'a str>, Option<&'a str>, u8) {
    let w = tripwire::command_words(cmd);
    let (mut guard, mut risky): (Option<(usize, &str)>, Option<(usize, &str)>) = (None, None);
    let mut waits = 0u8;
    for m in all {
        if let Some(n) = tripwire::best_match(&m.tags, &w) {
            if guard.is_none_or(|(b, _)| n > b) {
                guard = Some((n, &m.title));
            }
            match m.wait {
                Some(i) => waits |= 1 << i,
                None => {
                    if risky.is_none_or(|(b, _)| n > b) {
                        risky = Some((n, &m.title));
                    }
                }
            }
        }
    }
    (risky.map(|(_, t)| t), guard.map(|(_, t)| t), waits)
}


/// Commands longer than this are not replayed (the `instinct scan` replay referee skips them too), in UTF-16 units.
const REPLAY_MAX_LEN: usize = 4000;
const REPLAY_SAMPLES: usize = 8;

/// The part of `old` and `new` that differs, with a little context, whitespace collapsed.
fn changed_window(old: &str, new: &str) -> (String, String) {
    let (a, b): (Vec<char>, Vec<char>) = (old.chars().collect(), new.chars().collect());
    let mut s = 0;
    while s < a.len() && s < b.len() && a[s] == b[s] {
        s += 1;
    }
    let mut e = 0;
    while e < a.len() - s && e < b.len() - s && a[a.len() - 1 - e] == b[b.len() - 1 - e] {
        e += 1;
    }
    let cut = |x: &[char], end: usize| -> String {
        let from = s.saturating_sub(30);
        let to = (end + 20).min(x.len());
        x[from.min(to)..to].iter().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")
    };
    (cut(&a, a.len() - e), cut(&b, b.len() - e))
}

/// Per distinct command: the risky-tripwire title (commands that are not waits), the title `instinct guard` would
/// show (every starter tripwire) and the fix rewrite (commands within the replay limit).
struct Row {
    risky: Option<String>,
    guard: Option<String>,
    rewrite: Option<(String, Vec<&'static str>)>,
}

/// Runs the fix rules and the tripwire matchers over each distinct command once, on worker threads, then weights the
/// results by how often each command ran. Also returns the risky tripwire groups and flagged-run total of the report.
fn replay(seen: &std::collections::BTreeMap<String, (u32, usize)>, all: &[Matcher]) -> (Replay, Vec<Group>, u32) {
    use std::sync::atomic::{AtomicUsize, Ordering};
    // first-seen order, so the examples shown are the first commands met
    let mut cmds: Vec<(&str, u32, usize)> = seen.iter().map(|(c, (n, i))| (c.as_str(), *n, *i)).collect();
    cmds.sort_by_key(|c| c.2);
    let next = AtomicUsize::new(0);
    let rows: Vec<std::sync::Mutex<Option<Row>>> = cmds.iter().map(|_| std::sync::Mutex::new(None)).collect();
    let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 16);
    std::thread::scope(|s| {
        for _ in 0..threads {
            s.spawn(|| loop {
                let i = next.fetch_add(1, Ordering::Relaxed);
                let Some((cmd, _, _)) = cmds.get(i) else { break };
                let (risky_title, guard_title, waits) = tripwire_titles(all, cmd);
                let risky = if waits == 0 { risky_title.map(str::to_string) } else { None };
                let short = cmd.encode_utf16().count() <= REPLAY_MAX_LEN;
                let guard = if short { guard_title.map(str::to_string) } else { None };
                let rewrite = if short {
                    fix::rewrite(cmd, &|_| true).filter(|(new, _)| new != cmd).map(|(new, fired)| (new, fired.iter().map(|a| a.rule).collect()))
                } else {
                    None
                };
                *rows[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(Row { risky, guard, rewrite });
            });
        }
    });
    let mut rp = Replay { unique: seen.len() as u32, ..Default::default() };
    let mut groups: Vec<Group> = Vec::new();
    let mut flagged = 0u32;
    let mut rules: std::collections::BTreeMap<String, u32> = Default::default();
    let mut titles: std::collections::BTreeMap<String, u32> = Default::default();
    let mut rewrites: Vec<(u32, &str, String, String)> = Vec::new();
    for ((cmd, n, _), row) in cmds.iter().zip(rows) {
        let Some(row) = row.into_inner().unwrap_or_else(|e| e.into_inner()) else { continue };
        if let Some(t) = &row.risky {
            flagged += n;
            let i = groups.iter().position(|g| &g.title == t).unwrap_or_else(|| {
                groups.push(Group { title: t.clone(), ..Default::default() });
                groups.len() - 1
            });
            let g = &mut groups[i];
            g.count += n;
            if g.examples.len() < EXAMPLES {
                let s = snippet(cmd);
                if !g.examples.contains(&s) {
                    g.examples.push(s);
                }
            }
        }
        if let Some(t) = &row.guard {
            rp.warned_unique += 1;
            rp.warned_runs += n;
            *titles.entry(t.chars().take(70).collect()).or_default() += n;
        }
        if let Some((new, names)) = row.rewrite {
            rp.rewritten_unique += 1;
            rp.rewritten_runs += n;
            for r in &names {
                *rules.entry((*r).to_string()).or_default() += n;
            }
            rewrites.push((*n, cmd, new, names.join(",")));
        }
    }
    let by_runs = |m: std::collections::BTreeMap<String, u32>| {
        let mut v: Vec<(String, u32)> = m.into_iter().collect();
        v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        v
    };
    rp.rules = by_runs(rules);
    rp.titles = by_runs(titles);
    rewrites.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
    // Redact the whole command first and cut the window after: a window that starts inside a secret would defeat the
    // redaction. A command too long for the redactor's 2,000-character head is counted but never shown.
    for (_, old, new, names) in rewrites.into_iter().filter(|r| r.1.chars().count() <= 2000 && r.2.chars().count() <= 2000).take(REPLAY_SAMPLES) {
        let (a, b) = changed_window(&redact_snippet(old), &redact_snippet(&new));
        rp.samples.push((names, a, b));
    }
    groups.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.title.cmp(&b.title)));
    (rp, groups, flagged)
}

/// Sub-agent transcripts sit below the session files (`<project>/<session>/subagents/*.jsonl`). They hold shell commands
/// the agents ran but no typed prompts, so only their commands are read.
fn nested_claude_files(root: &Path) -> Vec<PathBuf> {
    fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
        let Ok(rd) = fs::read_dir(dir) else { return };
        for p in rd.flatten().map(|e| e.path()) {
            if p.is_dir() {
                walk(&p, depth + 1, out);
            } else if depth >= 2 && p.extension().is_some_and(|e| e == "jsonl") {
                out.push(p);
            }
        }
    }
    let mut out = Vec::new();
    walk(root, 0, &mut out);
    out.sort();
    out
}

/// A Codex shell call, as `instinct mine` reads it: a `function_call` whose `command` is a string or
/// `["bash","-lc","the command"]`, or a code-mode `exec` cell's `exec_command` calls.
fn codex_command(e: &mine::Ev) -> Option<&str> {
    let c = e.cmd.trim();
    (!c.is_empty() && e.kind == Kind::ToolUse).then_some(c)
}

/// Every Claude Code `Bash` command one transcript records, read straight from the lines so sub-agent logs (whose lines
/// are flagged as side chains) count too.
fn raw_commands_in(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in text.lines() {
        if !line.contains("\"command\"") {
            continue;
        }
        let Ok(j) = parse_json(line) else { continue };
        let content = j.get("message").and_then(|m| m.get("content")).or_else(|| j.get("payload").and_then(|p| p.get("content")));
        if let Some(Json::Arr(items)) = content {
            for b in items {
                let is_bash = b.get("type").and_then(Json::as_str) == Some("tool_use") && b.get("name").and_then(Json::as_str) == Some("Bash");
                if let (true, Some(c)) = (is_bash, b.get("input").and_then(|i| i.get("command")).and_then(Json::as_str)) {
                    out.push(c.to_string());
                }
            }
        }
    }
    out
}

fn add_wait(dst: &mut WaitClass, src: &WaitClass) {
    dst.count += src.count;
    dst.measured += src.measured;
    dst.measured_background += src.measured_background;
    dst.secs += src.secs;
    dst.longest = dst.longest.max(src.longest);
    if dst.examples.is_empty() {
        dst.examples.extend(src.examples.iter().take(1).cloned());
    }
}

/// What one transcript contributes. It is built on a worker thread, so the reading runs in parallel and only these
/// small counts are kept, and merged in file order.
#[derive(Default)]
struct FileStats {
    /// False when the events could not be read.
    read: bool,
    prompts: u32,
    corrections: u32,
    after_correction: Pairs,
    after_other: Pairs,
    cmds: Vec<String>,
    waits: [WaitClass; 3],
    wait_all: WaitClass,
    retried: u32,
    claimed_done: u32,
    cwd: Option<PathBuf>,
}

/// Counts a wait command (once per run) in the file's wait classes.
fn count_wait(f: &mut FileStats, c: u8, cmd: &str) {
    if c == 0 {
        return;
    }
    f.wait_all.count += 1;
    for i in (0..3).filter(|i| c >> i & 1 == 1) {
        let w = &mut f.waits[i];
        w.count += 1;
        if w.examples.is_empty() {
            w.examples.push(snippet(cmd));
        }
    }
}

/// Reads one transcript. `commands_only` is for sub-agent logs: their shell commands, nothing else.
fn analyze(path: &Path, harness: Harness, commands_only: bool, ws: &[String]) -> FileStats {
    let mut f = FileStats::default();
    let evs = if commands_only {
        None
    } else {
        match mine::read_events_timed(path) {
            Ok(evs) => Some(evs),
            Err(_) => return f,
        }
    };
    f.read = true;
    if harness == Harness::Claude {
        let Ok(bytes) = fs::read(path) else { return f };
        let text = String::from_utf8_lossy(&bytes);
        f.cmds = raw_commands_in(&text);
        for c in &f.cmds.clone() {
            count_wait(&mut f, wait_classes(ws, c), c);
        }
        if evs.is_some() {
            let g = mine::gate_events(&text);
            f.retried = gates::retried_forms(&g);
            f.claimed_done = gates::run_gate(&g, None).len() as u32;
        }
    }
    let Some(evs) = evs else { return f };
    // (was the last user message a correction, has the agent acted since)
    let mut last: Option<(bool, bool)> = None;
    let mut pending: HashMap<String, Pending> = HashMap::new();
    for e in &evs {
        match e.kind {
            Kind::User => {
                let corr = corrections::correction(&e.text);
                f.prompts += 1;
                if corr {
                    f.corrections += 1;
                }
                if let Some((prev, true)) = last {
                    let p = if prev { &mut f.after_correction } else { &mut f.after_other };
                    p.n += 1;
                    p.repeated += corr as u32;
                }
                last = Some((corr, false));
            }
            Kind::Assistant | Kind::ToolUse => {
                if let Some((_, acted)) = last.as_mut() {
                    *acted = true;
                }
                let cmd = match harness {
                    // Claude Code: only the Bash tool runs shell; the commands themselves were read above
                    Harness::Claude => (e.kind == Kind::ToolUse && e.text == "Bash").then_some(e.cmd.trim()).filter(|c| !c.is_empty()),
                    Harness::Codex => codex_command(e),
                };
                if let Some(cmd) = cmd {
                    let c = wait_classes(ws, cmd);
                    if harness == Harness::Codex {
                        f.cmds.push(cmd.to_string());
                        count_wait(&mut f, c, cmd);
                    }
                    if c != 0 && !e.id.is_empty() && e.ts > 0 {
                        pending.insert(e.id.clone(), Pending { classes: c, start: e.ts, background: e.bg == 1, done: false });
                    }
                }
            }
            Kind::ToolResult => {
                let Some(p) = pending.get_mut(&e.id) else { continue };
                if p.done {
                    continue;
                }
                let end = |p: &mut Pending, f: &mut FileStats, background: bool| {
                    p.done = true;
                    if e.ts >= p.start {
                        let d = e.ts - p.start;
                        let (a, b) = (&mut f.wait_all, &mut f.waits);
                        for w in std::iter::once(a).chain(b.iter_mut().enumerate().filter(|(i, _)| p.classes >> i & 1 == 1).map(|(_, w)| w)) {
                            w.measured += 1;
                            w.measured_background += background as u32;
                            w.secs += d;
                            w.longest = w.longest.max(d);
                        }
                    }
                };
                match e.bg {
                    // "running in background": the call returned at once, the wait is still going
                    1 => p.background = true,
                    // the completion notice of a background task
                    2 if p.background => end(p, &mut f, true),
                    0 if !p.background => end(p, &mut f, false),
                    _ => {}
                }
            }
        }
    }
    f.cwd = file_cwd(path);
    f
}

/// `analyze` over every job, on up to 16 threads; the results come back in job order.
fn analyze_all(jobs: &[(PathBuf, Harness, bool)], ws: &[String]) -> Vec<FileStats> {
    use std::sync::{atomic::AtomicUsize, Mutex};
    let next = AtomicUsize::new(0);
    let slots: Vec<Mutex<Option<FileStats>>> = jobs.iter().map(|_| Mutex::new(None)).collect();
    let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 16);
    std::thread::scope(|s| {
        for _ in 0..threads {
            s.spawn(|| loop {
                let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let Some((path, harness, only)) = jobs.get(i) else { break };
                *slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(analyze(path, *harness, *only, ws));
            });
        }
    });
    slots.into_iter().map(|m| m.into_inner().unwrap_or_else(|e| e.into_inner()).unwrap_or_default()).collect()
}

/// Scans the given transcript folders. `since` is the oldest modification time (unix seconds) a file may have.
pub fn scan(roots: &[(PathBuf, Harness)], days: u64, since: u64) -> Report {
    let mut r = Report { days, ..Default::default() };
    let all = all_matchers();
    let ws = wait_matchers();
    let mut seen: std::collections::BTreeMap<String, (u32, usize)> = Default::default();
    let mut folders: Vec<(PathBuf, u32, u32)> = Vec::new();
    // The reading is the cost, so it runs on worker threads; counting stays here, in file order.
    let mut jobs: Vec<(PathBuf, Harness, bool)> = Vec::new();
    for (root, harness) in roots {
        for path in files_in(root, *harness) {
            if modified_secs(&path).is_none_or(|m| m < since) {
                r.skipped_old += 1;
            } else {
                jobs.push((path, *harness, false));
            }
        }
    }
    let top = jobs.len();
    for (root, harness) in roots {
        if *harness == Harness::Claude {
            jobs.extend(nested_claude_files(root).into_iter().filter(|p| modified_secs(p).is_some_and(|m| m >= since)).map(|p| (p, Harness::Claude, true)));
        }
    }
    let stats = analyze_all(&jobs, &ws);
    for (i, (f, (_, harness, _))) in stats.into_iter().zip(&jobs).enumerate() {
        if i < top {
            if !f.read {
                r.unreadable += 1;
                continue;
            }
            r.files += 1;
            match harness {
                Harness::Claude => {
                    r.claude_files += 1;
                    r.claude_prompts += f.prompts;
                }
                Harness::Codex => {
                    r.codex_files += 1;
                    r.codex_prompts += f.prompts;
                }
            }
            r.prompts += f.prompts;
            r.corrections += f.corrections;
            r.after_correction.n += f.after_correction.n;
            r.after_correction.repeated += f.after_correction.repeated;
            r.after_other.n += f.after_other.n;
            r.after_other.repeated += f.after_other.repeated;
            r.retried += f.retried;
            r.claimed_done += f.claimed_done;
            if let Some(cwd) = &f.cwd {
                let k = folders.iter().position(|x| same_dir(&x.0, cwd)).unwrap_or_else(|| {
                    folders.push((cwd.clone(), 0, 0));
                    folders.len() - 1
                });
                match harness {
                    Harness::Claude => folders[k].1 += f.prompts,
                    Harness::Codex => folders[k].2 += f.prompts,
                }
            }
        }
        for cmd in &f.cmds {
            r.commands += 1;
            match harness {
                Harness::Claude => r.claude_commands += 1,
                Harness::Codex => r.codex_commands += 1,
            }
            let next = seen.len();
            seen.entry(cmd.clone()).or_insert((0, next)).0 += 1;
        }
        for k in 0..3 {
            add_wait(&mut r.waits[k], &f.waits[k]);
        }
        add_wait(&mut r.wait_all, &f.wait_all);
    }
    for (cwd, claude, codex) in &folders {
        r.folders.push((cwd.clone(), *claude, *codex));
    }
    (r.replay, r.groups, r.flagged) = replay(&seen, &all);
    r
}

/// Memory files at user level, per harness: (name, bytes). Project files are not guessed at.
fn memory_files() -> Vec<(Harness, String, usize)> {
    let home = home_dir();
    let mut out = Vec::new();
    for (root, harness) in roots() {
        let (name, dir) = match harness {
            Harness::Claude => ("CLAUDE.md", root.parent().map(Path::to_path_buf)),
            Harness::Codex => ("AGENTS.md", root.parent().map(Path::to_path_buf)),
        };
        let mut candidates: Vec<PathBuf> = dir.into_iter().map(|d| d.join(name)).collect();
        candidates.extend(home.iter().map(|h| h.join(name)));
        candidates.dedup();
        for c in candidates {
            if let Ok(m) = fs::metadata(&c) {
                if m.is_file() {
                    out.push((harness, name.to_string(), m.len() as usize));
                }
            }
        }
    }
    out
}

/// The working folder a transcript was recorded in: Claude Code lines carry `cwd`, Codex puts it in the
/// `session_meta` payload. Only the first lines are read.
fn file_cwd(path: &Path) -> Option<PathBuf> {
    let file = fs::File::open(path).ok()?;
    let mut reader = std::io::BufReader::new(file);
    let mut buf = Vec::new();
    for _ in 0..60 {
        buf.clear();
        if reader.read_until(b'\n', &mut buf).ok()? == 0 {
            break;
        }
        let line = String::from_utf8_lossy(&buf);
        if !line.contains("\"cwd\"") {
            continue;
        }
        let Ok(j) = parse_json(line.trim()) else { continue };
        let found = j
            .get("cwd")
            .or_else(|| j.get("payload").and_then(|p| p.get("cwd")))
            .and_then(Json::as_str)
            .filter(|c| !c.is_empty());
        if let Some(c) = found {
            return Some(PathBuf::from(c));
        }
    }
    None
}

/// The user's home folder: `USERPROFILE` on Windows, `HOME` elsewhere (each falls back to the other).
fn home_dir() -> Option<PathBuf> {
    let (first, second) = if cfg!(windows) { ("USERPROFILE", "HOME") } else { ("HOME", "USERPROFILE") };
    std::env::var_os(first)
        .filter(|v| !v.is_empty())
        .or_else(|| std::env::var_os(second).filter(|v| !v.is_empty()))
        .map(PathBuf::from)
}

/// Same folder? Windows paths differ only by case or by a trailing separator without meaning a different folder.
fn same_dir(a: &Path, b: &Path) -> bool {
    if cfg!(windows) {
        let n = |p: &Path| p.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase();
        n(a) == n(b)
    } else {
        a == b
    }
}

/// `/home/me/proj` shown as `~/proj`, with `/` between parts on every platform.
fn tilde(p: &Path, home: Option<&Path>) -> String {
    let rest = home.and_then(|h| {
        if same_dir(p, h) {
            return Some(PathBuf::new());
        }
        // Windows compares case-insensitively: peel the home components off one by one.
        let (mut pc, mut hc) = (p.components(), h.components());
        loop {
            let Some(a) = hc.next() else { return Some(pc.as_path().to_path_buf()) };
            match pc.next() {
                Some(b) if same_dir(Path::new(a.as_os_str()), Path::new(b.as_os_str())) => {}
                _ => return None,
            }
        }
    });
    match rest {
        Some(r) if r.as_os_str().is_empty() => "~".to_string(),
        Some(r) => {
            let parts: Vec<String> = r.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
            format!("~/{}", parts.join("/"))
        }
        None => p.display().to_string(),
    }
}

fn add_memory_cost(r: &mut Report) {
    for (harness, name, bytes) in memory_files() {
        let tokens = audit::tokens_of(bytes);
        let prompts = if harness == Harness::Claude { r.claude_prompts } else { r.codex_prompts };
        r.memory_tokens_in_window += tokens as u64 * prompts as u64;
        r.memory.push((name, tokens));
    }
    r.memory_user_tokens = r.memory_tokens_in_window;
    // Project files: CLAUDE.md for the Claude Code prompts and AGENTS.md for the Codex prompts of each folder
    // that still exists. The home folder itself is already counted above.
    let home = home_dir();
    let mut projects: Vec<(String, u64, u32)> = Vec::new();
    for (cwd, claude, codex) in &r.folders {
        if !cwd.is_dir() || home.as_ref().is_some_and(|h| same_dir(h, cwd)) {
            continue;
        }
        let size = |name: &str| fs::metadata(cwd.join(name)).ok().filter(|m| m.is_file()).map(|m| audit::tokens_of(m.len() as usize) as u64);
        let total = size("CLAUDE.md").unwrap_or(0) * *claude as u64 + size("AGENTS.md").unwrap_or(0) * *codex as u64;
        if total > 0 {
            projects.push((tilde(cwd, home.as_deref()), total, claude + codex));
        }
    }
    projects.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    r.projects_with_memory = projects.len() as u32;
    r.memory_tokens_in_window += projects.iter().map(|p| p.1).sum::<u64>();
    projects.truncate(5);
    r.projects = projects;
}

// ---------------------------------------------------------------- output

fn commas(n: u64) -> String {
    let s = n.to_string();
    let mut out = String::new();
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

/// `1 prompt`, `2 prompts`, `1,204 prompts`.
fn noun(n: u64, one: &str, many: &str) -> String {
    format!("{} {}", commas(n), if n == 1 { one } else { many })
}

/// `once`, `twice`, `3 times`.
fn times(n: u32) -> String {
    match n {
        1 => "once".to_string(),
        2 => "twice".to_string(),
        n => format!("{} times", commas(n as u64)),
    }
}

/// `day` or `30 days`, for "the last ...".
fn span(days: u64) -> String {
    if days == 1 { "day".to_string() } else { format!("{days} days") }
}

fn pct(x: Option<f64>) -> String {
    x.map_or("n/a".to_string(), |v| format!("{:.1}%", v * 100.0))
}

/// At most 280 characters, plain text, headline numbers and the repo link.
pub fn share_text(r: &Report) -> String {
    let mut s = if r.commands == 0 {
        format!("My coding agent, last {}: I corrected it {}", span(r.days), times(r.corrections))
    } else {
        format!(
            "My coding agent, last {}: {} of {} would have drawn an Instinct tripwire warning; I corrected it {}",
            span(r.days), r.flagged, noun(r.commands as u64, "shell command", "shell commands"), times(r.corrections)
        )
    };
    // Posted publicly, so it carries counts only. The repeat rates depend on how many corrections the detector
    // catches, and on real sessions that is a floor, so they stay in the report with that caveat.
    s.push_str(&format!(". `instinct scan` {REPO}"));
    if s.chars().count() > 280 {
        s = format!("Coding agent, last {}: {}, {}. `instinct scan` {REPO}", span(r.days), noun(r.flagged as u64, "risky command", "risky commands"), noun(r.corrections as u64, "correction", "corrections"));
    }
    s.chars().take(280).collect()
}

fn next_steps(r: &Report) -> Vec<String> {
    let mut v = Vec::new();
    match r.starter {
        Some((all, have)) if have >= all => v.push(format!(
            "Your bank already holds all {all} starter tripwires; `instinct doctor` checks the hooks that deliver them."
        )),
        Some((all, have)) => v.push(format!(
            "Your bank holds {have} of {all} starter tripwires: `instinct starter --apply` adds the rest."
        )),
        None => v.push("No bank yet: `instinct starter --apply` banks the starter tripwires (run `instinct starter` first to read them).".into()),
    }
    if r.corrections > 0 {
        v.push(format!("`instinct mine --since {}d` turns your corrections into lesson candidates (a dry run).", r.days));
    }
    if r.memory_tokens_in_window > 0 {
        v.push("`instinct audit ~/.claude/CLAUDE.md` grades the memory file and measures the same rules behind Instinct.".into());
    }
    v.truncate(3);
    v
}

/// "1 h 05 min", "42 min", "30 s".
fn duration(secs: u64) -> String {
    match secs {
        0..=59 => format!("{secs} s"),
        60..=3599 => format!("{} min", secs / 60),
        _ => format!("{} h {:02} min", secs / 3600, secs % 3600 / 60),
    }
}

/// Section 4, only when the window holds at least one wait command of the three classes.
fn render_waiting(r: &Report) -> String {
    let total = r.wait_all.count;
    if total == 0 {
        return String::new();
    }
    let (measured, secs) = (r.wait_all.measured, r.wait_all.secs);
    let mut o = format!(
        "\n4. Waiting: {} that wait badly (a tripwire would have warned before each; one that fits two classes is listed under both)\n",
        noun(total as u64, "shell command", "shell commands")
    );
    for (i, w) in r.waits.iter().enumerate() {
        if w.count == 0 {
            continue;
        }
        o.push_str(&format!("   {:>4}  {}\n", w.count, WAIT_NAMES[i]));
        for e in &w.examples {
            o.push_str(&format!("          {e}\n"));
        }
    }
    if measured == 0 {
        o.push_str("   Time: none of these had both a start and an end in the transcripts, so no time is reported.\n");
    } else {
        o.push_str(&format!(
            "   Time: at least {} of wall time across {} of the {} (longest {}).\n",
            duration(secs),
            measured,
            total,
            duration(r.wait_all.longest)
        ));
    }
    for l in [
        "How: a foreground command is timed from its tool call to its result; a background command from its",
        "launch to the completion notice in the transcript. Commands with no end on record add nothing, so",
        "this is a floor. It is how long the command ran, not how much of that was avoidable.",
    ] {
        o.push_str(&format!("   {l}\n"));
    }
    o
}

fn render_replay(r: &Report) -> String {
    let p = &r.replay;
    let mut o = String::new();
    if r.commands == 0 {
        return o;
    }
    let share = 100.0 * p.rewritten_runs as f64 / r.commands as f64;
    o.push_str(&format!(
        "   Safe rewrites: instinct fix would have changed {} of {} distinct commands ({}, {share:.2}% of all runs)\n",
        commas(p.rewritten_unique as u64),
        commas(p.unique as u64),
        noun(p.rewritten_runs as u64, "run", "runs")
    ));
    for (rule, n) in &p.rules {
        o.push_str(&format!("   {n:>4}  rule {rule}\n"));
    }
    for (rules, a, b) in &p.samples {
        o.push_str(&format!("          [{rules}] - {a}\n          {}   + {b}\n", " ".repeat(rules.len())));
    }
    o
}

pub fn render_text(r: &Report, secs: f64) -> String {
    let mut o = String::new();
    o.push_str(&format!("instinct scan: the last {} (read-only, nothing leaves this machine)\n", span(r.days)));
    if r.files == 0 {
        o.push_str(&format!(
            "\nNo Claude Code or Codex transcripts changed in the last {} (looked in ~/.claude/projects and ~/.codex/sessions).\n\
Nothing to report. Run it again after a few sessions, or widen the window with --days.\n",
            span(r.days)
        ));
        o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
        return o;
    }
    o.push_str(&format!(
        "Read {} ({} Claude Code, {} Codex): {}, {}.\n",
        noun(r.files as u64, "transcript", "transcripts"),
        r.claude_files,
        r.codex_files,
        noun(r.prompts as u64, "prompt", "prompts"),
        noun(r.commands as u64, "shell command", "shell commands")
    ));
    if r.commands > 0 {
        o.push_str(&format!("Shell commands by harness: {} Claude Code, {} Codex.\n", commas(r.claude_commands as u64), commas(r.codex_commands as u64)));
    }
    if r.commands == 0 {
        o.push_str("\n1. Risky commands: No shell commands in the window.\n");
    } else {
        o.push_str(&format!("\n1. Risky commands: {} of {} would have drawn a tripwire warning\n", r.flagged, commas(r.commands as u64)));
    }
    if r.commands > 0 && r.groups.is_empty() {
        o.push_str("   None matched the starter tripwires.\n");
    }
    for g in &r.groups {
        o.push_str(&format!("   {:>4}  {}\n", g.count, g.title));
        for e in &g.examples {
            o.push_str(&format!("          {e}\n"));
        }
    }
    o.push_str(&render_replay(r));
    o.push_str(&format!(
        "\n2. Corrections: {} of {} told the agent it went wrong ({})\n",
        r.corrections,
        noun(r.prompts as u64, "prompt", "prompts"),
        pct(if r.prompts > 0 { Some(r.corrections as f64 / r.prompts as f64) } else { None })
    ));
    let (a, b) = (r.after_correction, r.after_other);
    o.push_str(&format!(
        "   Next message corrected again, after a correction:  {}/{}  {}\n",
        a.repeated, a.n, pct(a.rate())
    ));
    o.push_str(&format!(
        "   Next message corrected, after any other message:   {}/{}  {}\n",
        b.repeated, b.n, pct(b.rate())
    ));
    match r.ratio() {
        Some(x) => o.push_str(&format!("   Ratio: {x:.1}x more likely to be corrected again right after a correction.\n")),
        None => o.push_str(&format!("   No ratio yet: it needs at least {MIN_FOR_RATIO} reply pairs in each group.\n")),
    }
    o.push_str("   Only clear corrections are counted, so these numbers are a floor, not a measurement.\n");
    o.push_str(&format!("   Retried a failing command the same way 3+ times: {}\n", r.retried));
    o.push_str(&format!(
        "   Claimed done with nothing run since the last change, right after a correction: {}\n",
        r.claimed_done
    ));
    o.push_str("\n3. Memory files\n");
    if r.memory.is_empty() && r.projects.is_empty() {
        o.push_str("   No CLAUDE.md or AGENTS.md at user level or in the project folders of these sessions.\n");
    } else {
        for (name, t) in &r.memory {
            o.push_str(&format!("   {name} (user level): about {} on every prompt\n", noun(*t as u64, "token", "tokens")));
        }
        if !r.memory.is_empty() {
            o.push_str(&format!(
                "   User-level files across {} ({} Claude Code, {} Codex): about {}.\n",
                noun(r.prompts as u64, "prompt", "prompts"),
                commas(r.claude_prompts as u64),
                commas(r.codex_prompts as u64),
                noun(r.memory_user_tokens, "token", "tokens")
            ));
        }
        if !r.projects.is_empty() {
            o.push_str(&format!(
                "   Project files, top {} of {} (tokens x that project's prompts):\n",
                r.projects.len(),
                noun(r.projects_with_memory as u64, "project", "projects")
            ));
            for (path, tokens, prompts) in &r.projects {
                o.push_str(&format!("   {:>10}  {path} ({})\n", commas(*tokens), noun(*prompts as u64, "prompt", "prompts")));
            }
        }
        o.push_str(&format!(
            "   Overall: about {} of memory files sent in the window (an estimate, bytes / 4).\n",
            noun(r.memory_tokens_in_window, "token", "tokens")
        ));
    }
    let waiting = render_waiting(r);
    o.push_str(&waiting);
    o.push_str(&format!("\n{}. Next steps\n", if waiting.is_empty() { 4 } else { 5 }));
    for l in next_steps(r) {
        o.push_str(&format!("   {l}\n"));
    }
    if r.skipped_old > 0 || r.unreadable > 0 {
        o.push_str(&format!(
            "\n({} skipped as older than the window, {} unreadable)\n",
            noun(r.skipped_old as u64, "file", "files"),
            r.unreadable
        ));
    }
    o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
    o
}

fn f(x: Option<f64>) -> String {
    x.map_or("null".to_string(), |v| format!("{v:.4}"))
}

pub fn render_json(r: &Report, secs: f64) -> String {
    let groups: Vec<String> = r
        .groups
        .iter()
        .map(|g| {
            let ex: Vec<String> = g.examples.iter().map(|e| format!("\"{}\"", escape_json(e))).collect();
            format!("{{\"title\":\"{}\",\"count\":{},\"examples\":[{}]}}", escape_json(&g.title), g.count, ex.join(","))
        })
        .collect();
    let pairs = |p: Pairs| format!("{{\"replies\":{},\"repeated\":{},\"rate\":{}}}", p.n, p.repeated, f(p.rate()));
    let mem: Vec<String> =
        r.memory.iter().map(|(n, t)| format!("{{\"file\":\"{}\",\"tokens_per_prompt\":{t}}}", escape_json(n))).collect();
    let proj: Vec<String> = r
        .projects
        .iter()
        .map(|(p, t, n)| format!("{{\"path\":\"{}\",\"tokens_in_window\":{t},\"prompts\":{n}}}", escape_json(p)))
        .collect();
    let wait_all = format!(
        "{{\"count\":{},\"measured\":{},\"measured_background\":{},\"seconds\":{},\"longest_seconds\":{}}}",
        r.wait_all.count, r.wait_all.measured, r.wait_all.measured_background, r.wait_all.secs, r.wait_all.longest
    );
    let waits: Vec<String> = r
        .waits
        .iter()
        .enumerate()
        .map(|(i, w)| {
            let ex: Vec<String> = w.examples.iter().map(|e| format!("\"{}\"", escape_json(e))).collect();
            format!(
                "{{\"id\":\"{}\",\"count\":{},\"measured\":{},\"measured_background\":{},\"seconds\":{},\"longest_seconds\":{},\"examples\":[{}]}}",
                WAIT_IDS[i], w.count, w.measured, w.measured_background, w.secs, w.longest, ex.join(",")
            )
        })
        .collect();
    let named = |v: &[(String, u32)], key: &str| -> String {
        v.iter().map(|(n, c)| format!("{{\"{key}\":\"{}\",\"runs\":{c}}}", escape_json(n))).collect::<Vec<_>>().join(",")
    };
    let samples: Vec<String> = r
        .replay
        .samples
        .iter()
        .map(|(rules, a, b)| format!("{{\"rules\":\"{}\",\"before\":\"{}\",\"after\":\"{}\"}}", escape_json(rules), escape_json(a), escape_json(b)))
        .collect();
    let replay = format!(
        "{{\"unique\":{},\"rewritten\":{{\"unique\":{},\"runs\":{},\"by_rule\":[{}]}},\"warned\":{{\"unique\":{},\"runs\":{},\"by_title\":[{}]}},\"samples\":[{}]}}",
        r.replay.unique,
        r.replay.rewritten_unique,
        r.replay.rewritten_runs,
        named(&r.replay.rules, "rule"),
        r.replay.warned_unique,
        r.replay.warned_runs,
        named(&r.replay.titles, "title"),
        samples.join(",")
    );
    let next: Vec<String> = next_steps(r).iter().map(|l| format!("\"{}\"", escape_json(l))).collect();
    format!(
        "{{\"days\":{},\"files\":{{\"scanned\":{},\"claude_code\":{},\"codex\":{},\"skipped_old\":{},\"unreadable\":{}}},\
\"prompts\":{},\"commands\":{},\"commands_by_harness\":{{\"claude_code\":{},\"codex\":{}}},\
\"risky\":{{\"flagged\":{},\"groups\":[{}]}},\"replay\":{},\
\"corrections\":{{\"count\":{},\"after_correction\":{},\"after_other\":{},\"ratio\":{},\"retried_same_command_3plus\":{},\"claimed_done_unverified\":{}}},\
\"waiting\":{{\"measured_as\":\"floor: foreground call to result, background launch to completion notice\",\"total\":{},\"classes\":[{}]}},\
\"memory\":{{\"files\":[{}],\"user_tokens_in_window\":{},\"projects_with_memory\":{},\"top_projects\":[{}],\"tokens_in_window\":{}}},\
\"next\":[{}],\"share\":\"{}\",\"elapsed_ms\":{}}}",
        r.days,
        r.files,
        r.claude_files,
        r.codex_files,
        r.skipped_old,
        r.unreadable,
        r.prompts,
        r.commands,
        r.claude_commands,
        r.codex_commands,
        r.flagged,
        groups.join(","),
        replay,
        r.corrections,
        pairs(r.after_correction),
        pairs(r.after_other),
        f(r.ratio()),
        r.retried,
        r.claimed_done,
        wait_all,
        waits.join(","),
        mem.join(","),
        r.memory_user_tokens,
        r.projects_with_memory,
        proj.join(","),
        r.memory_tokens_in_window,
        next.join(","),
        escape_json(&share_text(r)),
        (secs * 1000.0).round() as u64
    )
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let (mut days, mut json, mut share) = (30u64, false, false);
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--json" => json = true,
            "--share" => share = true,
            "--format" => match it.next().map(String::as_str) {
                Some("json") => json = true,
                Some("text") => json = false,
                _ => return Err("scan: --format needs json or text".into()),
            },
            "--days" => {
                days = it
                    .next()
                    .and_then(|v| v.parse().ok())
                    .filter(|d| *d > 0)
                    .ok_or("scan: --days needs a whole number of days, 1 or more")?
            }
            "--help" | "-h" => {
                println!("{SCAN_HELP}");
                return Ok(());
            }
            other => return Err(format!("scan: unknown argument {other}\n\n{SCAN_HELP}")),
        }
    }
    let started = std::time::Instant::now();
    let since = now_secs().saturating_sub(days.saturating_mul(86_400));
    let mut r = scan(&roots(), days, since);
    add_memory_cost(&mut r);
    r.starter = starter::banked_in_default();
    let secs = started.elapsed().as_secs_f64();
    if json {
        println!("{}", render_json(&r, secs));
    } else if share {
        println!("{}", share_text(&r));
    } else {
        print!("{}", render_text(&r, secs));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redaction_hides_tokens_and_keeps_commands() {
        let s = redact_snippet("curl -H 'Authorization: Bearer abcdef0123456789abcdef' https://x.test");
        assert!(!s.contains("abcdef0123456789abcdef"), "{s}");
        let s = redact_snippet("API_KEY=abc deploy.sh");
        assert_eq!(s, "API_KEY=*** deploy.sh");
        let s = redact_snippet("export GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789");
        assert!(s.contains("GITHUB_TOKEN=***") && !s.contains("ghp_"), "{s}");
        let s = redact_snippet("docker login -p sk-abcdefghijklmnopqrstuv");
        assert!(!s.contains("sk-abc"), "{s}");
        let s = redact_snippet("git checkout 3f2a9c1d4b5e6f708192a3b4c5d6e7f801234567");
        assert_eq!(s, "git checkout ***");
        let s = redact_snippet("echo QUtJQTEyMzQ1Njc4OTBhYmNkZWZnaGlqa2xt");
        assert_eq!(s, "echo ***");
        assert_eq!(redact_snippet("rm -rf ./target/debug/build-output"), "rm -rf ./target/debug/build-output");
        assert_eq!(redact_snippet("cargo build --release --locked"), "cargo build --release --locked");
    }

    #[test]
    fn url_credentials_become_stars() {
        assert_eq!(redact_snippet("git clone https://alice:s3cr3t@github.com/o/r.git"), "git clone https://***@github.com/o/r.git");
        assert_eq!(redact_snippet("psql postgres://app:hunter22@db.internal:5432/prod"), "psql postgres://***@db.internal:5432/prod");
        assert_eq!(redact_snippet("curl http://a:b@h1/x https://c:d@h2/y"), "curl http://***@h1/x https://***@h2/y");
        assert_eq!(redact_snippet("curl 'https://u:p@host.test/a?b=c'"), "curl 'https://***@host.test/a?b=c'");
        // a password containing @ ends at the last @ before the path
        assert_eq!(redact_snippet("git fetch https://u:p@ss@host.test/r"), "git fetch https://***@host.test/r");
        // no password: nothing to hide, left as it is
        assert_eq!(redact_snippet("git clone ssh://git@github.com/o/r.git"), "git clone ssh://git@github.com/o/r.git");
        assert_eq!(redact_snippet("curl https://example.com/a@b:c"), "curl https://example.com/a@b:c");
    }

    #[test]
    fn password_flags_and_variables_become_stars() {
        assert_eq!(redact_snippet("mysql -psupersecret -h db"), "mysql -p*** -h db");
        assert_eq!(redact_snippet("mysql -u root --password=topsecret1 db"), "mysql -u root --password=*** db");
        assert_eq!(redact_snippet("PGPASSWORD=pgsecret1 psql -c 'select 1'"), "PGPASSWORD=*** psql -c 'select 1'");
        assert_eq!(redact_snippet("MYSQL_PWD=abcd1234 mysqldump db"), "MYSQL_PWD=*** mysqldump db");
        // compiler flags and an ordinary -p with a separate argument are not passwords
        assert_eq!(redact_snippet("gcc -pedantic -pthread -pipe -o a a.c"), "gcc -pedantic -pthread -pipe -o a a.c");
        assert_eq!(redact_snippet("cargo test -p instinct-cli"), "cargo test -p instinct-cli");
        assert_eq!(redact_snippet("mkdir -p a/b"), "mkdir -p a/b");
    }

    #[test]
    fn snippet_is_at_most_60_chars() {
        let s = snippet(&format!("git push --force {}", "origin/very-long-branch-name-".repeat(5)));
        assert!(s.chars().count() <= SNIPPET, "{s}");
        assert!(s.starts_with("git push --force"));
    }

    #[test]
    fn share_fits_280_even_with_huge_numbers() {
        let r = Report {
            days: 3650,
            commands: u32::MAX,
            flagged: u32::MAX,
            corrections: u32::MAX,
            after_correction: Pairs { n: u32::MAX, repeated: u32::MAX },
            after_other: Pairs { n: u32::MAX, repeated: u32::MAX },
            ..Default::default()
        };
        let s = share_text(&r);
        assert!(s.chars().count() <= 280, "{} {s}", s.chars().count());
        assert!(s.contains(REPO));
    }

    #[test]
    fn ratio_needs_twenty_each() {
        let mut r = Report {
            after_correction: Pairs { n: 19, repeated: 10 },
            after_other: Pairs { n: 100, repeated: 10 },
            ..Default::default()
        };
        assert!(r.ratio().is_none());
        r.after_correction = Pairs { n: 20, repeated: 10 };
        assert!((r.ratio().unwrap() - 5.0).abs() < 1e-9);
    }
}