use super::*;
use std::path::Path;
pub const SLOW_SECS: u64 = 30;
pub const MIN_SAMPLES: u32 = 3;
const MAX_CLASSES: usize = 256;
const MAX_OPEN: usize = 128;
const OPEN_TTL_MS: u64 = 3_600_000;
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 {
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)
}
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",
];
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"]),
];
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",
];
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",
];
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",
];
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' => {
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;
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; } else {
break;
}
}
let first = toks.get(i)?;
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('<') {
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 {
} 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;
}
if !sub.is_empty() {
class.push(' ');
class.push_str(&sub);
}
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)
}
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,
}
}
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"
})
}
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
})
}
fn bucket_of(ms: u64) -> usize {
let m = ms.max(1) as f64;
((m.log2() * 2.0).floor() as usize).min(BUCKETS - 1)
}
fn bucket_mid_ms(i: usize) -> f64 {
2f64.powf((i as f64 + 0.5) / 2.0)
}
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;
}
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
}
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)
}
#[derive(Clone, Debug, PartialEq)]
pub struct Stat {
pub class: String,
pub fg: u32,
pub bg: u32,
pub failed: u32,
pub slow_fg: u32,
pub total_ms: u64,
pub last: u64,
pub hist: [u32; BUCKETS],
pub loaded: u32,
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()?;
}
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)
}
}
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)
}
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);
}
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);
}
}
}
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
}
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);
}
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();
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)
}
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()
}
}
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)
))
}
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),
}
}
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);
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);
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(),
);
}
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." }
);
}
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");
}
}