instinct-cli 0.3.7

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
//! Command timing: how long each KIND of agent command takes on this machine.
//!
//! Three pieces share one small aggregate file, `<store>.timing` (mode 600, like the meter):
//! * `instinct guard` (PreToolUse) notes when a Bash call starts and, from the class's history, adds one advisory
//!   line when that class usually runs long in the foreground;
//! * `instinct timing` (PostToolUse / PostToolUseFailure) closes the call and folds its duration in;
//! * `instinct speed` reads the file and prints where the time goes.
//!
//! What is stored: per command CLASS (program, subcommand, and a fixed allow-list of flag names, for example
//! `cargo test --test`) a run count, a log-bucket histogram of foreground durations, a last-seen time and a few
//! counters. Never the command, its arguments, a path, a lesson or any output. The open calls live in
//! `<store>.timing-open` as `hash start_ms background`, where the hash is a one-way FNV of the call id; entries
//! older than an hour are dropped. `INSTINCT_TIMING=0` turns every write, and the advisory, off.
use super::*;
use std::path::Path;

/// A class whose median foreground run is over this many seconds gets the advisory.
pub const SLOW_SECS: u64 = 30;
/// Fewer runs than this and the median is a guess, so the guard stays quiet.
pub const MIN_SAMPLES: u32 = 3;
/// Classes kept; the least recently seen is dropped first.
const MAX_CLASSES: usize = 256;
/// Open calls kept, and how long one may stay open before it is forgotten.
const MAX_OPEN: usize = 128;
const OPEN_TTL_MS: u64 = 3_600_000;
/// Histogram buckets: bucket i holds durations of about 2^(i/2) ms, so 48 buckets reach past two days.
const BUCKETS: usize = 48;

pub fn enabled() -> bool {
    !matches!(
        std::env::var("INSTINCT_TIMING").as_deref(),
        Ok("0") | Ok("off") | Ok("false") | Ok("no")
    )
}

pub fn timing_path(store: &Path) -> PathBuf {
    let mut s = store.as_os_str().to_owned();
    s.push(".timing");
    PathBuf::from(s)
}

fn open_path(store: &Path) -> PathBuf {
    let mut s = store.as_os_str().to_owned();
    s.push(".timing-open");
    PathBuf::from(s)
}

fn now_ms() -> u64 {
    // Test seam: a fixed clock lets the tests build a 95 s run without waiting for it.
    if let Some(t) = std::env::var("INSTINCT_TIMING_NOW_MS")
        .ok()
        .and_then(|v| v.parse().ok())
    {
        return t;
    }
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// ---------------------------------------------------------------- class extraction

/// Subcommand-style programs: the first plain word after the program is part of the class.
const SUBCOMMAND_PROGRAMS: &[&str] = &[
    "cargo",
    "git",
    "npm",
    "pnpm",
    "yarn",
    "bun",
    "deno",
    "gh",
    "docker",
    "podman",
    "kubectl",
    "helm",
    "go",
    "make",
    "pip",
    "pip3",
    "uv",
    "poetry",
    "terraform",
    "dotnet",
    "gradle",
    "mvn",
    "brew",
    "apt",
    "apt-get",
    "pacman",
    "systemctl",
    "rustup",
    "flutter",
    "swift",
    "xcodebuild",
    "aws",
    "gcloud",
    "az",
    "npx",
    "pnpx",
    "turbo",
    "nx",
    "wrangler",
    "vercel",
];
/// Programs whose class takes a second word: `gh run watch`, `docker compose up`, `npm run build`.
const TWO_WORD: &[(&str, &[&str])] = &[
    (
        "gh",
        &["run", "pr", "workflow", "release", "repo", "issue", "api"],
    ),
    ("docker", &["compose", "buildx", "image"]),
    ("npm", &["run"]),
    ("pnpm", &["run"]),
    ("yarn", &["run"]),
    ("bun", &["run"]),
    ("kubectl", &["rollout"]),
    ("git", &["submodule", "stash", "worktree"]),
    ("cargo", &["install"]),
];
/// Flags whose NAME is kept in the class (never a value): the ones that change how long a command takes.
const SHAPE_FLAGS: &[&str] = &[
    "--test",
    "--lib",
    "--bin",
    "--bins",
    "--examples",
    "--doc",
    "--package",
    "-p",
    "--workspace",
    "--all",
    "--release",
    "--no-run",
    "--watch",
    "--required",
    "--auto",
    "--all-targets",
    "--all-features",
    "--ignored",
    "--no-cache",
    "--force",
    "--no-verify",
    "--follow",
    "--exit-status",
    "--frozen",
    "--locked",
    "--offline",
    "--no-deps",
    "--fail-fast",
];
/// Flags that take a separate value; the value is skipped, never stored.
const VALUE_FLAGS: &[&str] = &[
    "-C",
    "-c",
    "--test",
    "--bin",
    "--package",
    "-p",
    "--manifest-path",
    "--target",
    "--target-dir",
    "--features",
    "-F",
    "--jobs",
    "-j",
    "--profile",
    "--workflow",
    "--repo",
    "-R",
    "--branch",
    "-b",
    "--prefix",
    "--filter",
    "-f",
    "--file",
    "--tag",
    "-t",
    "--env",
    "-e",
    "--cwd",
    "--config",
    "--namespace",
    "-n",
    "--context",
];
/// Programs where a trailing positional argument names what to run, which narrows the work (`cargo test NAME`).
fn narrows_by_name(program: &str, sub: &str) -> bool {
    sub == "test"
        || matches!(
            program,
            "pytest" | "jest" | "vitest" | "mocha" | "rspec" | "phpunit"
        )
}
const WRAPPERS: &[&str] = &[
    "sudo", "time", "nohup", "nice", "env", "command", "exec", "builtin", "stdbuf", "ionice",
    "setsid",
];
const TRIVIAL: &[&str] = &[
    "cd", "export", "set", "unset", "source", ".", "echo", "printf", "true", "false", ":", "test",
    "[", "pushd", "popd", "ulimit", "umask", "wait", "sleep", "cat", "ls", "pwd",
];

/// Splits a shell line into simple commands on `&&`, `||`, `;`, `|` and newlines, outside quotes. The flag is true for
/// a segment that ends a pipeline stage (`|`), which does not make the line a chain.
fn segments(cmd: &str) -> Vec<(Vec<String>, bool)> {
    let mut out: Vec<(Vec<String>, bool)> = Vec::new();
    let (mut toks, mut cur): (Vec<String>, String) = (Vec::new(), String::new());
    let mut quote: Option<char> = None;
    let mut have = false;
    let chars: Vec<char> = cmd.chars().collect();
    let mut i = 0;
    let flush = |toks: &mut Vec<String>, cur: &mut String, have: &mut bool| {
        if *have {
            toks.push(std::mem::take(cur));
            *have = false;
        }
    };
    while i < chars.len() {
        let c = chars[i];
        if let Some(q) = quote {
            if c == q {
                quote = None;
            } else if c == '\\' && q == '"' && i + 1 < chars.len() {
                i += 1;
                cur.push(chars[i]);
            } else {
                cur.push(c);
            }
            i += 1;
            continue;
        }
        match c {
            '\'' | '"' => {
                quote = Some(c);
                have = true;
            }
            '\\' if i + 1 < chars.len() => {
                i += 1;
                cur.push(chars[i]);
                have = true;
            }
            ' ' | '\t' => flush(&mut toks, &mut cur, &mut have),
            '&' | '|' | ';' | '\n' => {
                // `2>&1`, `&>` and `>&` are redirections, not separators.
                let prev = if i > 0 { chars[i - 1] } else { ' ' };
                let next = chars.get(i + 1).copied().unwrap_or(' ');
                if c == '&' && (prev == '>' || prev == '<' || next == '>') {
                    cur.push(c);
                    have = true;
                } else {
                    flush(&mut toks, &mut cur, &mut have);
                    let piped = c == '|' && next != '|';
                    if (c == '&' || c == '|') && next == c {
                        i += 1;
                    }
                    if !toks.is_empty() {
                        out.push((std::mem::take(&mut toks), piped));
                    }
                }
            }
            _ => {
                cur.push(c);
                have = true;
            }
        }
        i += 1;
    }
    flush(&mut toks, &mut cur, &mut have);
    if !toks.is_empty() {
        out.push((toks, false));
    }
    out
}

fn plain_word(s: &str, max: usize) -> bool {
    !s.is_empty()
        && s.len() <= max
        && s.starts_with(|c: char| c.is_ascii_lowercase())
        && s.chars().all(|c| {
            c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_' || c == ':'
        })
}

fn class_of_segment(toks: &[String]) -> Option<String> {
    let mut i = 0;
    // VAR=value prefixes, wrappers and their own flags/values are not the program.
    loop {
        let t = toks.get(i)?;
        if t.contains('=')
            && !t.starts_with('-')
            && t.split('=').next().is_some_and(|k| {
                !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            })
        {
            i += 1;
        } else if WRAPPERS.contains(&t.as_str()) {
            i += 1;
            while toks
                .get(i)
                .is_some_and(|n| n.starts_with('-') || n.parse::<f64>().is_ok())
            {
                i += 1;
            }
        } else if t == "timeout" {
            i += 1;
            while toks.get(i).is_some_and(|n| n.starts_with('-')) {
                i += 1;
            }
            i += 1; // the duration
        } else {
            break;
        }
    }
    let first = toks.get(i)?;
    // A path or script is never stored by name.
    let base = first.rsplit('/').next().unwrap_or(first);
    let program = if first.contains('/') && !SUBCOMMAND_PROGRAMS.contains(&base) {
        return Some("<script>".to_string());
    } else if plain_word(base, 24) || base == "g++" || base == "c++" {
        base.to_string()
    } else if base.ends_with(".sh") || base.ends_with(".py") || base.ends_with(".js") {
        return Some("<script>".to_string());
    } else {
        return Some("<other>".to_string());
    };
    if TRIVIAL.contains(&program.as_str()) {
        return None;
    }
    let rest = &toks[i + 1..];
    let takes_sub = SUBCOMMAND_PROGRAMS.contains(&program.as_str());
    let mut class = program.clone();
    let mut sub = String::new();
    let mut flags: Vec<&str> = Vec::new();
    let mut positional = 0usize;
    let mut j = 0;
    let mut words_taken = 0;
    let max_words = if takes_sub { 1 } else { 0 };
    let mut want_second: Option<&[&str]> = None;
    while j < rest.len() {
        let t = rest[j].as_str();
        if t.contains('>') || t.contains('<') {
            // A redirection (`2>&1`, `> out.log`): never part of the class; a bare operator also takes its target.
            if t.trim_start_matches(|c: char| c.is_ascii_digit() || c == '&')
                .chars()
                .all(|c| c == '>' || c == '<')
            {
                j += 1;
            }
            j += 1;
            continue;
        }
        if t == "--" {
            break;
        }
        if let Some(name) = t
            .strip_prefix('-')
            .map(|_| t.split('=').next().unwrap_or(t))
        {
            if let Some(f) = SHAPE_FLAGS.iter().find(|f| **f == name) {
                if !flags.contains(f) {
                    flags.push(f);
                }
            }
            if VALUE_FLAGS.contains(&name) && !t.contains('=') {
                j += 1;
            }
        } else if t.starts_with('+') && words_taken == 0 {
            // a rustup toolchain such as `cargo +nightly`
        } else if words_taken < max_words && plain_word(t, 20) {
            sub = t.to_string();
            words_taken += 1;
            want_second = TWO_WORD
                .iter()
                .find(|(p, _)| *p == program)
                .map(|(_, s)| *s)
                .filter(|s| s.contains(&t));
        } else if want_second.is_some() && words_taken == 1 && plain_word(t, 20) {
            sub = format!("{sub} {t}");
            words_taken += 1;
            want_second = None;
        } else {
            positional += 1;
        }
        j += 1;
    }
    // `gh run watch ID` / `gh pr checks 12`: the verb is the second word already; `gh run` alone stays `gh run`.
    if !sub.is_empty() {
        class.push(' ');
        class.push_str(&sub);
    }
    // Flags that narrow or change the work, in a fixed order so the same command always gives the same class.
    flags.sort_by_key(|f| SHAPE_FLAGS.iter().position(|s| s == f));
    for f in &flags {
        class.push(' ');
        class.push_str(f);
    }
    if positional > 0 && narrows_by_name(&program, sub.split(' ').next().unwrap_or("")) {
        class.push_str(" +arg");
    }
    Some(class)
}

/// How slow a class tends to be, for picking the slowest part of a compound line. Higher is slower.
fn weight(class: &str) -> u8 {
    let c = class.trim_end_matches('+');
    let w: Vec<&str> = c.split(' ').collect();
    match (w[0], w.get(1).copied().unwrap_or("")) {
        ("wait", _) => 100,
        ("gh", "run") if c.contains("watch") => 100,
        ("cargo", "test" | "build" | "bench" | "check" | "clippy" | "install" | "doc") => 90,
        ("docker" | "podman", "build" | "compose" | "buildx") => 85,
        ("go", "test" | "build") | ("gradle" | "mvn" | "xcodebuild" | "terraform" | "make", _) => {
            80
        }
        ("npm" | "pnpm" | "yarn" | "bun", "install" | "ci" | "test" | "run" | "add")
        | ("pip" | "pip3" | "uv" | "poetry" | "brew" | "apt" | "apt-get", _) => 70,
        (
            "pytest" | "jest" | "vitest" | "mocha" | "rspec" | "phpunit" | "tsc" | "webpack"
            | "vite",
            _,
        ) => 70,
        ("git", "push" | "clone" | "fetch" | "pull")
        | ("gh", _)
        | ("curl" | "wget" | "ssh" | "scp" | "rsync", _) => 40,
        _ => 10,
    }
}

/// A polling loop is its own class: `until gh pr view ...; do sleep 5; done` is "wait ci", any other
/// `until`/`while`/`for` loop that sleeps or polls is "wait poll". Only keywords are read, nothing is stored.
fn wait_class(cmd: &str) -> Option<&'static str> {
    let words: Vec<&str> = cmd
        .split(|c: char| c.is_whitespace() || c == ';' || c == '(' || c == ')')
        .filter(|w| !w.is_empty())
        .collect();
    if !words
        .iter()
        .any(|w| matches!(*w, "until" | "while" | "for"))
    {
        return None;
    }
    if !words
        .iter()
        .any(|w| matches!(*w, "sleep" | "pgrep" | "pidof" | "wait" | "gh" | "tail"))
    {
        return None;
    }
    Some(if words.contains(&"gh") {
        "wait ci"
    } else {
        "wait poll"
    })
}

/// The class of a shell command line: `None` for an empty line or one made only of `cd`, `echo` and the like.
/// A line of several commands is classed by its SLOWEST part (`cd X && sed ... && cargo test` is a `cargo test`);
/// a trailing `+` marks a line with more than one slow part (`cargo build && cargo test`).
pub fn class_of(cmd: &str) -> Option<String> {
    if let Some(w) = wait_class(cmd) {
        return Some(w.to_string());
    }
    let segs = segments(cmd);
    let real: Vec<String> = segs
        .iter()
        .filter_map(|(toks, _)| class_of_segment(toks))
        .collect();
    let best = real
        .iter()
        .enumerate()
        .max_by_key(|(i, c)| (weight(c), std::cmp::Reverse(*i)))?
        .1
        .clone();
    let slow_parts = real.iter().filter(|c| weight(c) >= 70).count();
    Some(if slow_parts > 1 {
        format!("{best}+")
    } else {
        best
    })
}

// ---------------------------------------------------------------- histogram

fn bucket_of(ms: u64) -> usize {
    let m = ms.max(1) as f64;
    ((m.log2() * 2.0).floor() as usize).min(BUCKETS - 1)
}

/// Midpoint of a bucket in milliseconds, within about 19% of any value the bucket holds.
fn bucket_mid_ms(i: usize) -> f64 {
    2f64.powf((i as f64 + 0.5) / 2.0)
}

/// The q-quantile (0..1) of a histogram, in milliseconds; 0 when it is empty.
pub fn quantile_ms(hist: &[u32; BUCKETS], q: f64) -> u64 {
    let n: u64 = hist.iter().map(|c| *c as u64).sum();
    if n == 0 {
        return 0;
    }
    // Nearest rank: the smallest bucket whose cumulative count reaches ceil(q * n).
    let rank = ((q * n as f64).ceil() as u64).clamp(1, n);
    let mut seen = 0u64;
    for (i, c) in hist.iter().enumerate() {
        seen += *c as u64;
        if seen >= rank {
            return bucket_mid_ms(i).round() as u64;
        }
    }
    bucket_mid_ms(BUCKETS - 1).round() as u64
}

/// The 1-minute load average, so a slow command can be told from a busy machine. `INSTINCT_TIMING_LOAD1` is a test seam.
pub fn load1() -> Option<f64> {
    if let Ok(v) = std::env::var("INSTINCT_TIMING_LOAD1") {
        return v.parse().ok();
    }
    fs::read_to_string("/proc/loadavg")
        .ok()?
        .split_whitespace()
        .next()?
        .parse()
        .ok()
}

fn cores() -> f64 {
    std::thread::available_parallelism()
        .map(|n| n.get() as f64)
        .unwrap_or(1.0)
}

// ---------------------------------------------------------------- the aggregate file

#[derive(Clone, Debug, PartialEq)]
pub struct Stat {
    pub class: String,
    /// Foreground runs timed (the histogram's total).
    pub fg: u32,
    /// Calls run in the background: counted, never timed (the tool call returns at once).
    pub bg: u32,
    pub failed: u32,
    /// Foreground runs that took over SLOW_SECS.
    pub slow_fg: u32,
    pub total_ms: u64,
    pub last: u64,
    pub hist: [u32; BUCKETS],
    /// Foreground runs that started while the 1-minute load average was above the core count.
    pub loaded: u32,
    /// Sum of the 1-minute load average (times 100) at the start of each foreground run.
    pub load_sum: u64,
}

impl Stat {
    fn new(class: &str) -> Stat {
        Stat {
            class: class.to_string(),
            fg: 0,
            bg: 0,
            failed: 0,
            slow_fg: 0,
            total_ms: 0,
            last: 0,
            hist: [0; BUCKETS],
            loaded: 0,
            load_sum: 0,
        }
    }
    pub fn p50_ms(&self) -> u64 {
        quantile_ms(&self.hist, 0.5)
    }
    pub fn p95_ms(&self) -> u64 {
        quantile_ms(&self.hist, 0.95)
    }
    pub(crate) fn line(&self) -> String {
        let h: Vec<String> = self
            .hist
            .iter()
            .enumerate()
            .filter(|(_, c)| **c > 0)
            .map(|(i, c)| format!("{i}:{c}"))
            .collect();
        format!(
            "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
            self.class,
            self.fg,
            self.bg,
            self.failed,
            self.slow_fg,
            self.total_ms,
            self.last,
            h.join(","),
            self.loaded,
            self.load_sum
        )
    }
    fn parse(line: &str) -> Option<Stat> {
        let mut f = line.trim_end().split('\t');
        let mut s = Stat::new(f.next().filter(|c| !c.is_empty() && c.len() <= 120)?);
        s.fg = f.next()?.parse().ok()?;
        s.bg = f.next()?.parse().ok()?;
        s.failed = f.next()?.parse().ok()?;
        s.slow_fg = f.next()?.parse().ok()?;
        s.total_ms = f.next()?.parse().ok()?;
        s.last = f.next()?.parse().ok()?;
        for part in f.next().unwrap_or("").split(',').filter(|p| !p.is_empty()) {
            let (i, c) = part.split_once(':')?;
            let i: usize = i.parse().ok()?;
            *s.hist.get_mut(i)? = c.parse().ok()?;
        }
        // Older files end at the histogram.
        s.loaded = f.next().and_then(|v| v.parse().ok()).unwrap_or(0);
        s.load_sum = f.next().and_then(|v| v.parse().ok()).unwrap_or(0);
        Some(s)
    }
}

/// Missing, unreadable and malformed lines all read as "nothing recorded".
pub fn read_all(store: &Path) -> Vec<Stat> {
    match fs::read(timing_path(store)) {
        Ok(b) => String::from_utf8_lossy(&b)
            .lines()
            .filter_map(Stat::parse)
            .collect(),
        Err(_) => Vec::new(),
    }
}

pub(crate) fn write_atomic(path: &Path, body: &str) -> std::io::Result<()> {
    let mut tmp = path.as_os_str().to_owned();
    tmp.push(format!(".{}.tmp", std::process::id()));
    let tmp = PathBuf::from(tmp);
    let mut o = journal::private_options();
    o.write(true).create(true).truncate(true);
    let res = o.open(&tmp).and_then(|mut f| f.write_all(body.as_bytes()));
    if res.is_err() {
        let _ = fs::remove_file(&tmp);
        return res;
    }
    fs::rename(&tmp, path)
}

/// Folds one finished call in. Errors are swallowed: a lost sample never fails a hook.
pub fn record(
    store: &Path,
    class: &str,
    ms: u64,
    background: bool,
    failed: bool,
    now: u64,
    load1: Option<f64>,
) {
    let mut all = read_all(store);
    fold(&mut all, class, ms, background, failed, now, load1);
    let body: String = all.iter().map(Stat::line).collect();
    let _ = write_atomic(&timing_path(store), &body);
}

/// Folds one finished call into the in-memory aggregate (`record` and the history import share it).
pub fn fold(
    all: &mut Vec<Stat>,
    class: &str,
    ms: u64,
    background: bool,
    failed: bool,
    now: u64,
    load1: Option<f64>,
) {
    let at = match all.iter().position(|s| s.class == class) {
        Some(i) => i,
        None => {
            if all.len() >= MAX_CLASSES {
                if let Some(old) = all
                    .iter()
                    .enumerate()
                    .min_by_key(|(_, s)| s.last)
                    .map(|(i, _)| i)
                {
                    all.remove(old);
                }
            }
            all.push(Stat::new(class));
            all.len() - 1
        }
    };
    let s = &mut all[at];
    s.last = s.last.max(now);
    if failed {
        s.failed = s.failed.saturating_add(1);
    }
    if background {
        s.bg = s.bg.saturating_add(1);
    } else {
        s.fg = s.fg.saturating_add(1);
        let b = bucket_of(ms);
        s.hist[b] = s.hist[b].saturating_add(1);
        s.total_ms = s.total_ms.saturating_add(ms);
        if let Some(l) = load1 {
            s.load_sum = s.load_sum.saturating_add((l * 100.0) as u64);
            if l > cores() {
                s.loaded = s.loaded.saturating_add(1);
            }
        }
        if ms > SLOW_SECS * 1000 {
            s.slow_fg = s.slow_fg.saturating_add(1);
        }
    }
}

// ---------------------------------------------------------------- pairing

fn fnv(parts: &[&str]) -> u64 {
    let mut h: u64 = 0xcbf29ce484222325;
    for p in parts {
        for b in p.bytes().chain([0u8]) {
            h ^= b as u64;
            h = h.wrapping_mul(0x100000001b3);
        }
    }
    h
}

/// The identity of one tool call: Claude Code's `tool_use_id` when the payload has it, else the session plus the
/// command text. Only the hash is ever written.
fn call_key(v: &Json, command: &str) -> String {
    let id = first_str(v, &["tool_use_id", "toolUseId", "tool_call_id"]);
    let session = first_str(v, &["session_id", "sessionId"]).unwrap_or("");
    let h = match id {
        Some(id) => fnv(&["id", id]),
        None => fnv(&["cmd", session, command]),
    };
    format!("{h:016x}")
}

fn first_str<'a>(v: &'a Json, keys: &[&str]) -> Option<&'a str> {
    keys.iter()
        .filter_map(|k| v.get(k).and_then(Json::as_str))
        .find(|s| !s.trim().is_empty())
}

struct Call {
    command: String,
    background: bool,
    key: String,
}

fn call_of(v: &Json) -> Option<Call> {
    let name = first_str(v, &["tool_name", "toolName"])?.to_lowercase();
    if !matches!(
        name.as_str(),
        "bash" | "shell" | "run_shell_command" | "exec_command"
    ) {
        return None;
    }
    let input = v.get("tool_input").or_else(|| v.get("toolArgs"))?;
    let command = first_str(input, &["command", "cmd"])?.to_string();
    let background = matches!(input.get("run_in_background"), Some(Json::Bool(true)));
    let key = call_key(v, &command);
    Some(Call {
        command,
        background,
        key,
    })
}

fn read_open(store: &Path) -> Vec<(String, u64, bool)> {
    let text = fs::read_to_string(open_path(store)).unwrap_or_default();
    text.lines()
        .filter_map(|l| {
            let mut f = l.split(' ');
            Some((
                f.next()?.to_string(),
                f.next()?.parse().ok()?,
                f.next()? == "1",
            ))
        })
        .collect()
}

fn write_open(store: &Path, open: &[(String, u64, bool)]) {
    let body: String = open
        .iter()
        .map(|(k, t, b)| format!("{k} {t} {}\n", u8::from(*b)))
        .collect();
    let _ = write_atomic(&open_path(store), &body);
}

/// PreToolUse side, called by `instinct guard` with its parsed payload text. Notes the start of a Bash call and
/// returns the advisory line when this class usually runs long in the foreground. Cheap by design: one small read
/// of the aggregate file and one append to the open-calls file.
pub fn before(store: &Path, input: &str) -> Option<String> {
    if !enabled() {
        return None;
    }
    let v = parse_json(input).ok()?;
    let call = call_of(&v)?;
    let class = class_of(&call.command)?;
    super::speed_import::auto(store);
    let now = now_ms();
    // Append-only on the hot path; the post hook does the pruning.
    let mut o = journal::private_options();
    o.append(true).create(true);
    if let Ok(mut f) = o.open(open_path(store)) {
        if f.metadata().map(|m| m.len()).unwrap_or(0) < 16 * 1024 {
            let _ = f.write_all(
                format!("{} {now} {}\n", call.key, u8::from(call.background)).as_bytes(),
            );
        }
    }
    if call.background {
        return None;
    }
    let stat = read_all(store).into_iter().find(|s| s.class == class)?;
    advisory(&stat)
}

/// ", the machine was busy for 3 of 4 of them" when most of a class's runs started under load, so a slow median is
/// not read as a slow command.
pub fn busy_note(s: &Stat) -> String {
    if s.fg > 0 && s.loaded * 2 > s.fg {
        format!(
            ", but the machine was busy for {} of {} of them",
            s.loaded, s.fg
        )
    } else {
        String::new()
    }
}

/// The advisory for a class, or `None` when it is not slow enough or has too few runs.
pub fn advisory(s: &Stat) -> Option<String> {
    let p50 = s.p50_ms();
    if s.fg < MIN_SAMPLES || p50 <= SLOW_SECS * 1000 {
        return None;
    }
    Some(format!(
        "Instinct timing: `{}` usually takes {} here (p50 of {} runs{}). {}",
        s.class,
        human(p50),
        s.fg,
        busy_note(s),
        faster_route(&s.class)
    ))
}

/// A faster route for a class that is slow in the foreground. Always safe advice: it names the route, it does not run it.
pub fn faster_route(class: &str) -> String {
    let c = class.trim_end_matches('+');
    let has = |f: &str| c.split(' ').any(|w| w == f);
    if c == "wait ci" || c.starts_with("gh run watch") || c.starts_with("gh pr checks") {
        return "Do not wait for CI: push, dispatch, report and end. Or `gh pr merge --auto --merge` (or `gh pr checks --required --watch` in the background).".into();
    }
    if c == "wait poll" {
        return "Run the long step with run_in_background and act on the notification, or save its PID and `wait` for it; no sleep or pgrep poll loops.".into();
    }
    if c.starts_with("cargo test")
        && !has("--test")
        && !has("--lib")
        && !has("--bin")
        && !has("--doc")
        && !c.ends_with("+arg")
    {
        return "Run it in the background, or narrow it to the affected target (e.g. `cargo test --test NAME`) and let CI's required run do the full suite.".into();
    }
    if c.starts_with("cargo test")
        || c.starts_with("go test")
        || c.starts_with("npm test")
        || c.starts_with("pytest")
    {
        return "Run it in the background, or narrow it further to the one test you changed."
            .into();
    }
    if c.starts_with("cargo build") || c.starts_with("cargo check") || c.starts_with("cargo clippy")
    {
        return "Run it in the background (run_in_background) and act on the notification, or use `cargo check -p CRATE`.".into();
    }
    "Run it in the background (run_in_background) and act on the notification.".into()
}

pub fn human(ms: u64) -> String {
    match ms {
        0..=999 => format!("{ms} ms"),
        1000..=59_999 => format!("{:.0} s", ms as f64 / 1000.0),
        60_000..=3_599_999 => format!("{}m{:02}s", ms / 60_000, (ms / 1000) % 60),
        _ => format!("{:.1} h", ms as f64 / 3_600_000.0),
    }
}

/// `instinct timing`: the PostToolUse / PostToolUseFailure hook. Reads the payload, closes the matching open call,
/// records the duration. Silent, exit 0, always.
pub fn run_post(a: &Args) {
    let mut input = String::new();
    if std::io::stdin()
        .take(1 << 20)
        .read_to_string(&mut input)
        .is_err()
        || !enabled()
    {
        return;
    }
    let Ok(store) = store_path(a) else { return };
    let Ok(v) = parse_json(&input) else { return };
    let Some(call) = call_of(&v) else { return };
    let Some(class) = class_of(&call.command) else {
        return;
    };
    let now = now_ms();
    let mut open = read_open(&store);
    open.retain(|(_, t, _)| now.saturating_sub(*t) <= OPEN_TTL_MS);
    // Newest match: a repeated identical command in one session pairs with its own latest start.
    let at = open.iter().rposition(|(k, _, _)| *k == call.key);
    let started = at.map(|i| open.remove(i).1);
    if open.len() > MAX_OPEN {
        open.drain(..open.len() - MAX_OPEN);
    }
    write_open(&store, &open);
    // Claude Code (2.1+) reports the tool's own `duration_ms` in the PostToolUse payload: it excludes hook start-up, so it wins;
    // the paired start is the fallback for versions and harnesses without it.
    let reported = v
        .get("duration_ms")
        .and_then(Json::as_f64)
        .filter(|d| *d >= 0.0)
        .map(|d| d as u64);
    let Some(ms) = reported.or(started.map(|t| now.saturating_sub(t))) else {
        return;
    };
    let hook = first_str(&v, &["hook_event_name"]).unwrap_or("");
    let resp = v.get("tool_response");
    let nonzero =
        |k: &str| matches!(resp.and_then(|r| r.get(k)).and_then(Json::as_f64), Some(n) if n != 0.0);
    let failed = hook == "PostToolUseFailure"
        || nonzero("exit_code")
        || nonzero("exitCode")
        || matches!(resp.and_then(|r| r.get("is_error")), Some(Json::Bool(true)))
        || matches!(
            resp.and_then(|r| r.get("interrupted")),
            Some(Json::Bool(true))
        );
    record(
        &store,
        &class,
        ms,
        call.background,
        failed,
        now_ms() / 1000,
        load1(),
    );
}

// ---------------------------------------------------------------- the report

/// The lesson id a slow class could be linked to: a lesson that names the program (and subcommand) in its situation,
/// title or tags and whose HOW gives a faster route. Best hit-minus-miss record first.
fn route_lesson(lessons: &[Discovery], class: &str) -> Option<(String, u32, u32)> {
    let mut words = class
        .trim_end_matches('+')
        .split(' ')
        .filter(|w| !w.starts_with('-') && *w != "+arg");
    let program = words.next()?.to_lowercase();
    let sub = words.next().map(str::to_lowercase);
    const FASTER: &[&str] = &[
        "background",
        "faster",
        "narrow",
        "quicker",
        "instead",
        "--test",
        "--required",
        "--auto",
        "-p ",
        "only the",
        "skip",
    ];
    lessons
        .iter()
        .filter(|d| !matches!(d.meta.state.as_str(), "quarantined" | "retracted"))
        .filter(|d| {
            let about = format!("{} {} {}", d.when, d.title, d.tags).to_lowercase();
            let how = d.how.to_lowercase();
            about
                .split(|c: char| !c.is_alphanumeric() && c != '-')
                .any(|w| w == program)
                && sub.as_ref().map_or(true, |s| about.contains(s.as_str()))
                && FASTER.iter().any(|f| how.contains(f))
        })
        .max_by_key(|d| (d.hits as i64 - d.misses as i64, d.ts))
        .map(|d| (d.id.clone(), d.hits, d.misses))
}

pub fn run(a: &Args) {
    if a.opt("import").is_some() {
        super::speed_import::run(a);
        return;
    }
    let Ok(store) = store_path(a) else {
        eprintln!("no bank location found (set INSTINCT_STORE or HOME)");
        return;
    };
    let mut stats = read_all(&store);
    stats.sort_by(|x, y| y.total_ms.cmp(&x.total_ms).then(y.fg.cmp(&x.fg)));
    let lessons = if stats.iter().any(|s| s.p50_ms() > SLOW_SECS * 1000) {
        load(&store).unwrap_or_default()
    } else {
        Vec::new()
    };
    let limit: usize = a.opt("limit").and_then(|v| v.parse().ok()).unwrap_or(15);
    stats.truncate(limit.max(1));
    let rows: Vec<(Stat, Option<String>, Option<(String, u32, u32)>)> = stats
        .into_iter()
        .map(|s| {
            let slow = s.fg >= 1 && s.p50_ms() > SLOW_SECS * 1000 || s.slow_fg > 0;
            let route = slow.then(|| faster_route(&s.class));
            let lesson = slow.then(|| route_lesson(&lessons, &s.class)).flatten();
            (s, route, lesson)
        })
        .collect();
    if a.opt("json").is_some() {
        let items: Vec<String> = rows
            .iter()
            .map(|(s, route, lesson)| {
                format!(
                    "{{\"class\":\"{}\",\"foreground_runs\":{},\"background_runs\":{},\"failed\":{},\"p50_ms\":{},\"p95_ms\":{},\"total_ms\":{},\"slow_foreground_runs\":{},\"loaded_runs\":{},\"avg_load1\":{:.2},\"last_seen\":{},\"faster_route\":{},\"lesson\":{}}}",
                    escape_json(&s.class),
                    s.fg,
                    s.bg,
                    s.failed,
                    s.p50_ms(),
                    s.p95_ms(),
                    s.total_ms,
                    s.slow_fg,
                    s.loaded,
                    if s.fg > 0 { s.load_sum as f64 / 100.0 / s.fg as f64 } else { 0.0 },
                    s.last,
                    route.as_ref().map_or("null".to_string(), |r| format!("\"{}\"", escape_json(r))),
                    lesson.as_ref().map_or("null".to_string(), |(id, h, m)| format!("{{\"id\":\"{}\",\"hits\":{h},\"misses\":{m}}}", escape_json(id))),
                )
            })
            .collect();
        println!(
            "{{\"timing\":{},\"slow_threshold_s\":{SLOW_SECS},\"min_samples\":{MIN_SAMPLES},\"classes\":[{}]}}",
            enabled(),
            items.join(",")
        );
        return;
    }
    if rows.is_empty() {
        println!(
            "No command timings yet ({}). The PostToolUse hook `instinct timing` records how long each kind of Bash command takes; see docs/speed.md.",
            if enabled() { "timing is on" } else { "timing is off: INSTINCT_TIMING=0" }
        );
        return;
    }
    println!(
        "{:<28} {:>5} {:>8} {:>8} {:>9} {:>8}",
        "command class", "runs", "p50", "p95", "total", ">30s fg"
    );
    for (s, route, lesson) in &rows {
        println!(
            "{:<28} {:>5} {:>8} {:>8} {:>9} {:>8}",
            s.class,
            s.fg + s.bg,
            if s.fg > 0 {
                human(s.p50_ms())
            } else {
                "-".into()
            },
            if s.fg > 0 {
                human(s.p95_ms())
            } else {
                "-".into()
            },
            human(s.total_ms),
            s.slow_fg
        );
        if s.loaded > 0 {
            println!("    load: {} of {} runs started with the machine overloaded (average load {:.1}); read that p50 with care", s.loaded, s.fg, s.load_sum as f64 / 100.0 / s.fg.max(1) as f64);
        }
        if let Some(r) = route {
            println!("    faster: {r}");
        }
        if let Some((id, h, m)) = lesson {
            println!("    lesson {id} ({h} hit, {m} miss): if it helped run `instinct hit {id}`, if not `instinct miss {id}`");
        }
    }
    println!(
        "\nTimes are foreground wall-clock per command class (p50/p95 within about 20%); background calls are counted, not timed. Nothing but the class is stored.{}",
        if enabled() { "" } else { " Timing is off (INSTINCT_TIMING=0): nothing new is recorded." }
    );
}

/// One line for `instinct doctor`.
pub fn doctor_line(store: &Path) -> String {
    let stats = read_all(store);
    let runs: u32 = stats.iter().map(|s| s.fg + s.bg).sum();
    if !enabled() {
        return format!(
            "timing    off (INSTINCT_TIMING=0); {} classes, {runs} runs already on file\n",
            stats.len()
        );
    }
    if stats.is_empty() {
        return "timing    on, nothing recorded yet (needs the PostToolUse hook `instinct timing`; see docs/speed.md)\n".to_string();
    }
    format!(
        "timing    on: {} command classes, {runs} runs timed (see `instinct speed`)\n",
        stats.len()
    )
}

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

    fn c(s: &str) -> Option<String> {
        class_of(s)
    }

    #[test]
    fn classes_keep_program_subcommand_and_shape_only() {
        assert_eq!(c("cargo test").as_deref(), Some("cargo test"));
        assert_eq!(
            c("cargo test --test guard -- --nocapture").as_deref(),
            Some("cargo test --test")
        );
        assert_eq!(
            c("cargo test --release my_secret_test").as_deref(),
            Some("cargo test --release +arg")
        );
        assert_eq!(
            c("CARGO_TARGET_DIR=/home/me/x cargo build --release").as_deref(),
            Some("cargo build --release")
        );
        assert_eq!(
            c("cd /home/me/proj && gh run watch 123 --exit-status").as_deref(),
            Some("gh run watch --exit-status")
        );
        assert_eq!(
            c("git -C /home/me/repo push origin main").as_deref(),
            Some("git push")
        );
        assert_eq!(c("npm install").as_deref(), Some("npm install"));
        assert_eq!(c("npm run build").as_deref(), Some("npm run build"));
        assert_eq!(c("cargo +nightly fmt").as_deref(), Some("cargo fmt"));
        assert_eq!(
            c("cargo test 2>&1 | tail -20").as_deref(),
            Some("cargo test")
        );
        assert_eq!(
            c("cargo build && cargo test").as_deref(),
            Some("cargo build+")
        );
        assert_eq!(
            c("sudo -n timeout 30 make test").as_deref(),
            Some("make test")
        );
        assert_eq!(c("echo hi").as_deref(), None);
        assert_eq!(c("cd /tmp").as_deref(), None);
        assert_eq!(c("").as_deref(), None);
    }

    #[test]
    fn no_argument_or_path_ever_reaches_a_class() {
        let secret = "hunter2-acme-payroll";
        for cmd in [
            format!("./deploy-{secret}.sh --token {secret}"),
            format!("/opt/{secret}/bin/tool run {secret}"),
            format!("curl -H 'Authorization: {secret}' https://{secret}.example.com/x"),
            format!("psql postgres://u:{secret}@db/{secret} -c 'select 1'"),
            format!("git commit -m \"{secret}\""),
            format!("python3 /home/me/{secret}.py {secret}"),
            format!("{secret}=1 FOO=bar make {secret}"),
            format!("cargo test {secret} --features {secret}"),
            format!("Weird-{secret}"),
        ] {
            let class = c(&cmd).unwrap();
            assert!(
                !class.contains(secret) && !class.contains('/') && !class.contains("example"),
                "{cmd:?} -> {class:?}"
            );
            assert!(class.len() <= 60, "{class}");
        }
    }

    #[test]
    fn percentiles_are_within_one_bucket_of_the_truth() {
        let mut h = [0u32; BUCKETS];
        for ms in [1_000u64, 2_000, 4_000, 90_000, 95_000, 100_000, 120_000] {
            h[bucket_of(ms)] += 1;
        }
        let p50 = quantile_ms(&h, 0.5);
        assert!((p50 as f64 / 90_000.0 - 1.0).abs() < 0.25, "p50 {p50}");
        let p95 = quantile_ms(&h, 0.95);
        assert!((p95 as f64 / 120_000.0 - 1.0).abs() < 0.25, "p95 {p95}");
        assert_eq!(quantile_ms(&[0; BUCKETS], 0.5), 0);
        let mut one = [0u32; BUCKETS];
        one[bucket_of(50_000)] = 1;
        assert!((quantile_ms(&one, 0.5) as f64 / 50_000.0 - 1.0).abs() < 0.25);
        assert_eq!(bucket_of(u64::MAX), BUCKETS - 1);
    }

    #[test]
    fn stat_lines_round_trip() {
        let mut s = Stat::new("cargo test");
        s.fg = 4;
        s.hist[bucket_of(95_000)] = 4;
        s.total_ms = 380_000;
        s.last = 1_800_000_000;
        assert_eq!(Stat::parse(&s.line()).as_ref(), Some(&s));
        assert!(Stat::parse("garbage").is_none());
    }

    #[test]
    fn advisory_needs_a_slow_median_and_enough_runs() {
        let mut s = Stat::new("cargo test");
        s.fg = 2;
        s.hist[bucket_of(95_000)] = 2;
        assert!(advisory(&s).is_none(), "two runs are a guess");
        s.fg = 3;
        s.hist[bucket_of(95_000)] = 3;
        let line = advisory(&s).unwrap();
        assert!(
            line.contains("usually takes")
                && line.contains("p50 of 3 runs")
                && line.contains("cargo test --test NAME"),
            "{line}"
        );
        let mut fast = Stat::new("git status");
        fast.fg = 50;
        fast.hist[bucket_of(20)] = 50;
        assert!(advisory(&fast).is_none());
        let mut edge = Stat::new("make");
        edge.fg = 5;
        edge.hist[bucket_of(29_000)] = 5;
        assert!(advisory(&edge).is_none(), "29 s is under the line");
    }
}