use super::*;
use mine::Kind as EvKind;
#[cfg(test)]
mod tests;
pub const RETRY_LINE: &str = "Instinct: this exact command already failed twice in this session. Read the last error and change the approach before running it again.";
pub const DONE_REASON: &str = "You said it is fixed after the user's correction, but nothing ran since your last change. Run the check that proves it on the user's actual path, then report what you saw.";
pub const RETRY_AFTER: usize = 2;
const TAIL_BYTES: u64 = 2 << 20;
const CLAIM_TAIL: usize = 600;
pub fn retry_on() -> bool {
std::env::var("INSTINCT_RETRY").is_ok_and(|v| v.trim() == "1")
}
pub fn done_gate_on() -> bool {
std::env::var("INSTINCT_DONE_GATE").is_ok_and(|v| v.trim() == "1")
}
fn is_assignment(tok: &str) -> bool {
match tok.split_once('=') {
Some((k, _)) => {
!k.is_empty()
&& !k.starts_with(|c: char| c.is_ascii_digit())
&& k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
None => false,
}
}
fn is_duration(tok: &str) -> bool {
let t = tok.strip_suffix(['s', 'm', 'h', 'd']).unwrap_or(tok);
!t.is_empty() && t.chars().all(|c| c.is_ascii_digit() || c == '.')
}
fn word(s: &str) -> (&str, &str) {
let s = s.trim_start();
match s.find(char::is_whitespace) {
Some(i) => (&s[..i], &s[i..]),
None => (s, ""),
}
}
fn count_arg(x: &str) -> bool {
let d = x.trim_start_matches('-');
!d.is_empty() && d.chars().all(|c| c.is_ascii_digit())
}
fn strip_prefix_once(s: &str) -> Option<String> {
let (w, rest) = word(s);
let rest_t = rest.trim_start();
if w == "cd" {
let (_, after) = word(rest_t);
let after = after.trim_start();
return after.strip_prefix("&&").or_else(|| after.strip_prefix(';')).map(|r| r.trim_start().to_string());
}
if is_assignment(w) {
return Some(rest_t.to_string());
}
if w == "sudo" || w == "env" {
let mut r = rest_t;
loop {
let (w2, after) = word(r);
if w2.starts_with('-') && w2.len() > 1 {
r = after.trim_start();
} else {
break;
}
}
return Some(r.to_string());
}
if w == "timeout" {
let mut r = rest_t;
loop {
let (w2, after) = word(r);
if matches!(w2, "-s" | "-k" | "--signal" | "--kill-after") {
r = word(after).1.trim_start();
} else if w2.starts_with('-') && w2.len() > 1 {
r = after.trim_start();
} else {
break;
}
}
let (d, after) = word(r);
let rest = after.trim_start();
return (is_duration(d) && !rest.is_empty()).then(|| rest.to_string());
}
None
}
pub fn normalize(cmd: &str) -> String {
let mut s = cmd.trim().to_string();
while let Some(n) = strip_prefix_once(&s) {
if n == s {
break;
}
s = n;
}
loop {
let t = s.trim_end().to_string();
let mut out = t.clone();
if let Some(i) = t.rfind('|') {
if !t[..i].ends_with('|') {
let seg: Vec<&str> = t[i + 1..].split_whitespace().collect();
let cut = match seg.as_slice() {
[c, n] => matches!(*c, "tail" | "head") && count_arg(n),
[c, f, n] => matches!(*c, "tail" | "head") && *f == "-n" && count_arg(n),
_ => false,
};
if cut {
out = t[..i].trim_end().to_string();
}
}
}
if let Some(r) = out.strip_suffix("2>&1") {
out = r.trim_end().to_string();
}
if out == t {
break;
}
s = out;
}
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub fn hash(s: &str) -> String {
let mut h: u64 = 0xcbf29ce484222325;
for b in s.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
format!("{h:016x}")
}
pub fn form_id(cmd: &str) -> String {
hash(&normalize(cmd))
}
const CLAIMS: [&str; 7] = ["done", "fixed", "works now", "should work", "ready", "shipped", "all set"];
const NEGATORS: [&str; 18] = [
"not", "isn't", "wasn't", "aren't", "never", "no", "until", "when", "once", "if", "before", "be", "been", "get",
"gets", "getting", "unless", "won't",
];
fn norm_words(s: &str) -> Vec<String> {
s.to_lowercase()
.replace(['\u{2018}', '\u{2019}'], "'")
.split(|c: char| !(c.is_alphanumeric() || c == '\''))
.filter(|w| !w.is_empty())
.map(str::to_string)
.collect()
}
pub fn claims_done(text: &str) -> bool {
let n = text.chars().count();
let tail: String = text.chars().skip(n.saturating_sub(CLAIM_TAIL)).collect();
let mut sentences: Vec<(String, bool)> = Vec::new();
let mut cur = String::new();
for c in tail.chars() {
if matches!(c, '.' | '!' | '?' | '\n') {
sentences.push((std::mem::take(&mut cur), c == '?'));
} else {
cur.push(c);
}
}
sentences.push((cur, false));
for (sentence, question) in sentences {
if question {
continue;
}
let w = norm_words(&sentence);
for phrase in CLAIMS {
let p: Vec<&str> = phrase.split(' ').collect();
if w.len() < p.len() {
continue;
}
for i in 0..=(w.len() - p.len()) {
if w[i..i + p.len()].iter().map(String::as_str).eq(p.iter().copied()) {
let guarded = (1..=2).any(|k| i >= k && NEGATORS.contains(&w[i - k].as_str()));
if !guarded {
return true;
}
}
}
}
}
false
}
const READ_ONLY: [&str; 16] = [
"cat", "head", "tail", "ls", "grep", "rg", "find", "bfs", "wc", "file", "stat", "less", "jq", "echo", "pwd", "which",
];
const EDIT_TOOLS: [&str; 4] = ["Edit", "Write", "NotebookEdit", "MultiEdit"];
pub fn is_edit_tool(name: &str) -> bool {
EDIT_TOOLS.contains(&name)
}
pub fn read_only(cmd: &str) -> bool {
let n = normalize(cmd);
let mut it = n.split_whitespace();
let first = it.next().unwrap_or("");
let first = first.rsplit('/').next().unwrap_or(first);
if READ_ONLY.contains(&first) {
return true;
}
(first == "sed" && n.contains(" -n"))
|| (first == "git" && it.next().is_some_and(|s| matches!(s, "diff" | "status" | "log" | "show")))
}
#[derive(Default)]
pub struct DoneGate {
armed: bool,
verified: bool,
fired: bool,
pub correction_key: String,
}
impl DoneGate {
pub fn user(&mut self, text: &str) {
if corrections::correction(text) {
self.armed = true;
self.verified = false;
self.fired = false;
self.correction_key = hash(text);
}
}
pub fn edit(&mut self) {
self.verified = false;
}
pub fn bash(&mut self, cmd: &str) {
if !read_only(cmd) {
self.verified = true;
}
}
pub fn final_message(&mut self, text: &str) -> bool {
let fire = self.armed && !self.verified && !self.fired && claims_done(text);
if fire {
self.fired = true;
}
fire
}
}
pub fn run_gate(evs: &[mine::Ev], last_message: Option<&str>) -> Vec<(usize, String)> {
let mut g = DoneGate::default();
let mut fires: Vec<(usize, String)> = Vec::new();
let mut pending: Option<(&str, usize)> = None;
for e in evs {
match e.kind {
EvKind::User => {
if let Some((t, line)) = pending.take() {
if g.final_message(t) {
fires.push((line, g.correction_key.clone()));
}
}
g.user(&e.text);
}
EvKind::Assistant => pending = Some((&e.text, e.line)),
EvKind::ToolUse => {
if is_edit_tool(&e.text) {
g.edit();
} else if e.text == "Bash" {
g.bash(&e.cmd);
}
}
EvKind::ToolResult => {}
}
}
let last = match last_message {
Some(t) => Some((t, 0)),
None => pending,
};
if let Some((t, line)) = last {
if g.final_message(t) {
fires.push((line, g.correction_key.clone()));
}
}
fires
}
fn walk_failures(evs: &[mine::Ev], key: &dyn Fn(&str) -> String, mut on_call: impl FnMut(&mine::Ev, usize)) -> HashMap<String, usize> {
let mut open: HashMap<&str, String> = HashMap::new();
let mut counted: HashSet<&str> = HashSet::new();
let mut fails: HashMap<String, usize> = HashMap::new();
for e in evs {
match e.kind {
EvKind::ToolUse if e.text == "Bash" => {
if !e.id.is_empty() && open.contains_key(e.id.as_str()) {
continue;
}
let form = key(&e.cmd);
on_call(e, fails.get(&form).copied().unwrap_or(0));
if !e.id.is_empty() {
open.insert(&e.id, form);
}
}
EvKind::ToolResult if e.err => {
if let Some(f) = open.get(e.id.as_str()) {
if counted.insert(&e.id) {
*fails.entry(f.clone()).or_default() += 1;
}
}
}
_ => {}
}
}
fails
}
pub fn retry_points(evs: &[mine::Ev]) -> Vec<(usize, bool)> {
retry_points_by(evs, &form_id)
}
pub fn prefix_form(cmd: &str) -> String {
normalize(cmd).split_whitespace().take(2).collect::<Vec<_>>().join(" ")
}
pub fn retry_points_by(evs: &[mine::Ev], key: &dyn Fn(&str) -> String) -> Vec<(usize, bool)> {
let mut warned: HashSet<String> = HashSet::new();
let mut out = Vec::new();
walk_failures(evs, key, |e, before| {
if before >= RETRY_AFTER && warned.insert(key(&e.cmd)) {
out.push((e.line, e.cmd.contains("timeout ")));
}
});
out
}
pub fn trace(files: &[String]) {
if let Ok(v) = std::env::var("GATES_V2_SKIP") {
super::targets::set_skip(&v);
}
for (i, f) in files.iter().enumerate() {
let Ok(text) = fs::read_to_string(f) else { continue };
let evs = mine::gate_events(&text);
for (line, timeout) in retry_points(&evs) {
println!("{i}\tR\t{line}\t{}", timeout as u8);
}
for (line, timeout) in retry_points_by(&evs, &prefix_form) {
println!("{i}\tP\t{line}\t{}", timeout as u8);
}
for (line, _) in run_gate(&evs, None) {
println!("{i}\tD\t{line}\t0");
}
if std::env::var_os("GATES_V3").is_some() {
super::targets::v3_rows(&evs, i);
}
for (line, _) in super::targets::run(&evs, None) {
println!("{i}\tV\t{line}\t0");
}
}
}
pub fn retried_forms(evs: &[mine::Ev]) -> u32 {
walk_failures(evs, &form_id, |_, _| {}).values().filter(|n| **n >= 3).count() as u32
}
fn drain() -> Option<String> {
let mut input = String::new();
std::io::stdin().take(1 << 20).read_to_string(&mut input).ok()?;
Some(input)
}
fn exit_code(error: &str) -> Option<i32> {
error.lines().next()?.trim().strip_prefix("Exit code ")?.trim().parse().ok()
}
fn python_input(cmd: &str, cwd: Option<&str>) -> Option<PathBuf> {
let root = Path::new(cwd?);
if !root.is_absolute() || cmd.contains(['\n', '\r']) { return None; }
let mut words = cmd.split_ascii_whitespace();
let (python, script, name) = (words.next()?, words.next()?, words.next()?);
let literal = |s: &str| s.len() <= 255 && !s.starts_with(['-', '.']) &&
s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'));
if !matches!(python, "python" | "python3") || !literal(script) || !script.ends_with(".py")
|| !literal(name) || words.next().is_some() { return None; }
Some(root.join(name))
}
fn missing_input_witness(cmd: &str, cwd: Option<&str>, error: &str) -> Option<String> {
let message = error.lines().last()?.strip_prefix("FileNotFoundError: [Errno 2] No such file or directory: '")?
.strip_suffix('\'')?;
let path = python_input(cmd, cwd)?;
if Path::new(message) != path || !error.lines().any(|s| s == "Traceback (most recent call last):") { return None; }
let err = fs::symlink_metadata(&path).err()?;
(err.kind() == std::io::ErrorKind::NotFound).then(|| hash(&path.to_string_lossy()))
}
pub fn track(a: &Args) {
let Some(input) = drain() else { return };
if !retry_on() {
return;
}
let Ok(ev) = parse_json(&input) else { return };
if ev.get("tool_name").and_then(Json::as_str) != Some("Bash") {
return;
}
if matches!(ev.get("is_interrupt"), Some(Json::Bool(true))) {
return;
}
let Some(error) = ev.get("error").and_then(Json::as_str)
.or_else(|| ev.get("tool_response").and_then(Json::as_str)) else { return };
let Some(status) = exit_code(error).filter(|c| *c != 0) else { return };
let cmd = ev.get("tool_input").and_then(|i| i.get("command")).and_then(Json::as_str).unwrap_or("");
let Some(sid) = ev.get("session_id").and_then(Json::as_str).and_then(session::clean) else { return };
if cmd.trim().is_empty() {
return;
}
let Ok(path) = store_path(a) else { return };
let missing = if status == 1 {
missing_input_witness(cmd, ev.get("cwd").and_then(Json::as_str), error)
} else { None };
session::record_failure(&path, &sid, &form_id(cmd), status, missing);
}
pub fn retry_warning(path: &Path, sid: &str, cmd: &str, cwd: Option<&str>) -> Option<&'static str> {
if !retry_on() {
return None;
}
let form = form_id(cmd);
let failures = session::recent_failures(path, sid, &form, RETRY_AFTER);
if failures.len() < RETRY_AFTER {
return None;
}
if failures.iter().all(|failure| failure == &failures[0]) {
if let Some((_, witness)) = failures[0].split_once(":missing=") {
if let Some(input) = python_input(cmd, cwd) {
if hash(&input.to_string_lossy()) == witness && fs::symlink_metadata(input).is_ok_and(|m| m.is_file()) {
return None;
}
}
}
}
session::claim_warning(path, sid, &form).then_some(RETRY_LINE)
}
fn tail_text(f: &mut fs::File, len: u64, n: u64) -> Option<String> {
use std::io::{Seek, SeekFrom};
let start = len.saturating_sub(n);
f.seek(SeekFrom::Start(start)).ok()?;
let mut buf = Vec::with_capacity((len - start) as usize);
f.take(len - start).read_to_end(&mut buf).ok()?;
let text = String::from_utf8_lossy(&buf).into_owned();
Some(if start > 0 { text.split_once('\n').map(|(_, r)| r.to_string()).unwrap_or_default() } else { text })
}
fn window_since_correction(path: &str) -> Option<String> {
let mut f = fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let mut n: u64 = 64 << 10;
loop {
let text = tail_text(&mut f, len, n)?;
if let Some(w) = since_last_correction(&text) {
return Some(w);
}
if n >= len || n >= TAIL_BYTES {
return None;
}
n = (n * 2).min(TAIL_BYTES);
}
}
fn since_last_correction(text: &str) -> Option<String> {
let mut end = text.len();
while end > 0 {
let start = text[..end].rfind('\n').map_or(0, |i| i + 1);
let line = &text[start..end];
if mine::possible_user_line(line) {
let hit = mine::gate_events(line).iter().any(|e| e.kind == EvKind::User && corrections::correction(&e.text));
if hit {
let kept: Vec<&str> = text[start..].lines().filter(|l| !l.contains("\"tool_result\"")).collect();
return Some(kept.join("\n"));
}
}
if start == 0 {
break;
}
end = start - 1;
}
None
}
pub fn stop(a: &Args) {
let Some(input) = drain() else { return };
let v2 = super::targets::on();
if !done_gate_on() && !v2 {
return;
}
let Ok(ev) = parse_json(&input) else { return };
if matches!(ev.get("stop_hook_active"), Some(Json::Bool(true))) {
return;
}
let Some(msg) = ev.get("last_assistant_message").and_then(Json::as_str) else { return };
if !claims_done(msg) {
return;
}
let (Some(tp), Some(sid)) = (
ev.get("transcript_path").and_then(Json::as_str),
ev.get("session_id").and_then(Json::as_str).and_then(session::clean),
) else {
return;
};
if v2 {
super::targets::stop(a, &ev, &sid, msg);
return;
}
let Some(window) = window_since_correction(tp) else { return };
let evs = mine::gate_events(&window);
let Some((_, key)) = run_gate(&evs, Some(msg)).pop() else { return };
let Ok(path) = store_path(a) else { return };
if session::claim_block(&path, &sid, &key) {
println!("{{\"decision\":\"block\",\"reason\":\"{}\"}}", escape_json(DONE_REASON));
}
}