use super::scan::{files_in, modified_secs, roots, Harness};
use super::*;
use std::collections::HashMap;
use std::io::Seek;
use std::time::Instant;
const AUTO_BUDGET: Duration = Duration::from_secs(2);
const MAX_MS: u64 = 7 * 24 * 3_600_000;
pub struct Summary {
pub files: usize,
pub runs: u32,
pub complete: bool,
}
fn ledger_path(store: &Path) -> PathBuf {
let mut s = store.as_os_str().to_owned();
s.push(".timing-import");
PathBuf::from(s)
}
fn read_ledger(store: &Path) -> (HashMap<String, u64>, bool) {
let mut m = HashMap::new();
let mut done = false;
if let Ok(t) = fs::read_to_string(ledger_path(store)) {
for l in t.lines() {
if l == "#done" {
done = true;
} else if let Some((p, n)) = l.rsplit_once('\t') {
if let Ok(n) = n.parse() {
m.insert(p.to_string(), n);
}
}
}
}
(m, done)
}
fn parse_ts(s: &str) -> Option<u64> {
let b = s.as_bytes();
if b.len() < 19 || b[4] != b'-' || b[7] != b'-' || (b[10] != b'T' && b[10] != b' ') {
return None;
}
let n = |a: usize, z: usize| s.get(a..z)?.parse::<i64>().ok();
let (y, mo, d, h, mi, se) = (n(0, 4)?, n(5, 7)?, n(8, 10)?, n(11, 13)?, n(14, 16)?, n(17, 19)?);
let ms = if b.get(19) == Some(&b'.') {
let frac: String = s[20..].chars().take_while(|c| c.is_ascii_digit()).take(3).collect();
format!("{frac:0<3}").parse::<i64>().ok()?
} else {
0
};
let y2 = if mo <= 2 { y - 1 } else { y };
let era = y2.div_euclid(400);
let yoe = y2 - era * 400;
let doy = (153 * (if mo > 2 { mo - 3 } else { mo + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146097 + doe - 719468;
let secs = days * 86400 + h * 3600 + mi * 60 + se;
u64::try_from(secs * 1000 + ms).ok()
}
struct Open {
at: u64,
class: String,
background: bool,
}
fn command_of(args: &Json) -> Option<String> {
for k in ["cmd", "command"] {
match args.get(k) {
Some(Json::Str(s)) if !s.trim().is_empty() => return Some(s.clone()),
Some(Json::Arr(a)) => {
if let Some(Json::Str(s)) = a.last() {
if !s.trim().is_empty() {
return Some(s.clone());
}
}
}
_ => {}
}
}
None
}
fn fold_lines(lines: &mut dyn Iterator<Item = String>, harness: Harness, all: &mut Vec<speed::Stat>) -> u32 {
let mut open: HashMap<String, Open> = HashMap::new();
let mut n = 0;
for line in lines {
if !(line.contains("tool_use") || line.contains("tool_result") || line.contains("function_call")) {
continue;
}
let Ok(top) = parse_json(line.trim()) else { continue };
let Some(at) = top.get("timestamp").and_then(Json::as_str).and_then(parse_ts) else { continue };
let mut starts: Vec<(String, String, bool)> = Vec::new();
let mut ends: Vec<(String, bool)> = Vec::new();
match harness {
Harness::Claude => {
let Some(Json::Arr(items)) = top.get("message").and_then(|m| m.get("content")) else { continue };
for it in items {
match it.get("type").and_then(Json::as_str) {
Some("tool_use") if it.get("name").and_then(Json::as_str) == Some("Bash") => {
let (Some(id), Some(inp)) = (it.get("id").and_then(Json::as_str), it.get("input")) else { continue };
let Some(cmd) = command_of(inp) else { continue };
let bg = matches!(inp.get("run_in_background"), Some(Json::Bool(true)));
starts.push((id.to_string(), cmd, bg));
}
Some("tool_result") => {
if let Some(id) = it.get("tool_use_id").and_then(Json::as_str) {
ends.push((id.to_string(), matches!(it.get("is_error"), Some(Json::Bool(true)))));
}
}
_ => {}
}
}
}
Harness::Codex => {
let Some(p) = top.get("payload") else { continue };
let Some(id) = p.get("call_id").and_then(Json::as_str) else { continue };
match p.get("type").and_then(Json::as_str) {
Some("function_call") if matches!(p.get("name").and_then(Json::as_str), Some("shell" | "exec_command" | "shell_command" | "local_shell")) => {
let Some(Json::Str(raw)) = p.get("arguments") else { continue };
let Ok(args) = parse_json(raw) else { continue };
if let Some(cmd) = command_of(&args) {
starts.push((id.to_string(), cmd, false));
}
}
Some("function_call_output") => ends.push((id.to_string(), false)),
_ => {}
}
}
}
for (id, cmd, bg) in starts {
if let Some(class) = speed::class_of(&cmd) {
open.insert(id, Open { at, class, background: bg });
}
}
for (id, failed) in ends {
let Some(o) = open.remove(&id) else { continue };
let ms = at.saturating_sub(o.at);
if ms > MAX_MS {
continue;
}
speed::fold(all, &o.class, ms, o.background, failed, at, None);
n += 1;
}
}
n
}
fn read_file(path: &Path, from: u64, harness: Harness, all: &mut Vec<speed::Stat>) -> Option<(u32, u64)> {
let mut f = fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
if len <= from {
return Some((0, len.max(from)));
}
f.seek(std::io::SeekFrom::Start(from)).ok()?;
let reader = std::io::BufReader::new(f.take(len - from));
let mut lines = reader.split(b'\n').map_while(Result::ok).map(|b| String::from_utf8_lossy(&b).into_owned());
Some((fold_lines(&mut lines, harness, all), len))
}
pub fn import(store: &Path, days: u64, deadline: Option<Instant>) -> Summary {
let (mut seen, _) = read_ledger(store);
let since = now_secs().saturating_sub(days.saturating_mul(86400));
let mut all = speed::read_all(store);
let mut s = Summary { files: 0, runs: 0, complete: true };
let mut any = false;
'roots: for (root, harness) in roots() {
for path in files_in(&root, harness) {
let key = path.display().to_string();
if modified_secs(&path).is_none_or(|m| m < since) && !seen.contains_key(&key) {
continue;
}
if deadline.is_some_and(|d| Instant::now() >= d) {
s.complete = false;
break 'roots;
}
let from = seen.get(&key).copied().unwrap_or(0);
let Some((n, upto)) = read_file(&path, from, harness, &mut all) else { continue };
any = true;
if upto != from || !seen.contains_key(&key) {
s.files += 1;
}
s.runs += n;
seen.insert(key, upto);
}
}
if !any {
return s;
}
let mut keys: Vec<&String> = seen.keys().collect();
keys.sort();
let mut body: String = keys.iter().map(|k| format!("{k}\t{}\n", seen[*k])).collect();
if s.complete {
body.push_str("#done\n");
}
let _ = speed::write_atomic(&ledger_path(store), &body);
if s.runs > 0 {
let text: String = all.iter().map(|x| x.line()).collect();
let _ = speed::write_atomic(&speed::timing_path(store), &text);
}
s
}
pub fn auto(store: &Path) {
if !speed::enabled() || read_ledger(store).1 {
return;
}
let _ = import(store, 30, Some(Instant::now() + AUTO_BUDGET));
}
pub fn run(a: &Args) {
let Ok(store) = store_path(a) else {
eprintln!("no bank location found (set INSTINCT_STORE or HOME)");
return;
};
if !speed::enabled() {
println!("timing is off (INSTINCT_TIMING=0): nothing imported");
return;
}
let days = a.opt("days").and_then(|v| v.parse().ok()).unwrap_or(30);
let s = import(&store, days, None);
if s.files == 0 {
println!("nothing new to import from the Claude Code and Codex transcripts of the last {days} days");
} else {
println!(
"imported {} timed shell calls from {} transcript(s) of the last {days} days into {}. See them with `instinct speed`.",
s.runs,
s.files,
speed::timing_path(&store).display()
);
}
}