use super::*;
const MAX_CONTEXT: usize = 8000;
#[derive(Debug, PartialEq)]
pub enum Format {
Json,
Text,
Silent,
}
pub struct Event {
pub situation: String,
pub payload: Json,
pub tool: String,
pub codex: bool,
pub cwd: Option<String>,
pub format: Format,
pub session: Option<String>,
pub bash: Option<String>,
}
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())
}
pub fn parse(input: &str) -> Option<Event> {
let event = parse_json(input).ok()?;
let name = first_str(&event, &["tool_name", "toolName"])?;
let args = event.get("tool_input").or_else(|| event.get("toolArgs"));
let reparsed;
let args = match args {
Some(Json::Str(raw)) => {
reparsed = parse_json(raw)
.unwrap_or_else(|_| Json::Obj(vec![("command".into(), Json::Str(raw.clone()))]));
Some(&reparsed)
}
other => other,
};
let target = args
.and_then(|a| {
first_str(
a,
&["command", "cmd", "file_path", "filePath", "path", "pattern", "url", "query"],
)
})
.unwrap_or("");
if target.is_empty() {
return None;
}
let hook = first_str(&event, &["hook_event_name"]).unwrap_or("");
let format = if hook == "BeforeTool" || event.get("toolName").is_some() {
Format::Silent
} else {
Format::Json
};
Some(Event {
tool: name.to_string(),
codex: event.get("turn_id").is_some(),
payload: event.clone(),
situation: format!("tool_{} {target}", name.to_lowercase()),
cwd: event.get("cwd").and_then(Json::as_str).map(str::to_owned),
format,
session: first_str(&event, &["session_id", "sessionId"]).and_then(session::clean),
bash: (name == "Bash").then(|| target.to_string()),
})
}
fn to_json(v: &Json) -> String {
match v {
Json::Null => "null".into(),
Json::Bool(b) => b.to_string(),
Json::Num(n) if n.fract() == 0.0 && n.abs() < 1e15 => format!("{}", *n as i64),
Json::Num(n) => n.to_string(),
Json::Str(s) => format!("\"{}\"", escape_json(s)),
Json::Arr(a) => format!("[{}]", a.iter().map(to_json).collect::<Vec<_>>().join(",")),
Json::Obj(o) => format!(
"{{{}}}",
o.iter().map(|(k, v)| format!("\"{}\":{}", escape_json(k), to_json(v))).collect::<Vec<_>>().join(",")
),
}
}
fn set_field(obj: &mut Json, key: &str, val: Json) {
if let Json::Obj(fields) = obj {
match fields.iter_mut().find(|(k, _)| k == key) {
Some(f) => f.1 = val,
None => fields.push((key.to_string(), val)),
}
}
}
struct Fixed {
tool_input: Option<Json>,
payload: Json,
notes: Vec<String>,
}
fn fix_step(path: &PathBuf, scope: &eligibility::Scope, event: &Event, store_input: &str) -> Option<Fixed> {
if !fix::enabled() || event.format != Format::Json || event.tool != "Bash" {
return None;
}
let args = event.payload.get("tool_input")?;
let cmd = args.get("command").and_then(Json::as_str)?;
let rewritten = fix::rewrite(cmd, &|_| true);
let slow = speed::bg_fix_enabled() && speed::slow_foreground(path, store_input);
if rewritten.is_none() && !slow {
return None;
}
let on = super::starter::fix_rules_on(path, scope);
let rewritten = rewritten.and_then(|_| fix::rewrite(cmd, &|r| on.contains(r)));
let background = slow && on.contains("bg-slow") && !event.codex;
if rewritten.is_none() && !background {
return None;
}
let mut tool_input = args.clone();
let mut notes = Vec::new();
if let Some((new, fired)) = &rewritten {
let lesson = super::starter::fix_lesson(fired[0].rule);
if event.codex {
notes.push(format!(
"Instinct would rewrite: {} -> {} (lesson {lesson}). Codex accepts a rewrite only with auto-approval, so this is a warning: run the safe form.",
cmd.split_whitespace().collect::<Vec<_>>().join(" "),
new.split_whitespace().collect::<Vec<_>>().join(" ")
));
} else {
set_field(&mut tool_input, "command", Json::Str(new.clone()));
notes.push(fix::note(cmd, new, fired, &lesson));
}
}
if background {
set_field(&mut tool_input, "run_in_background", Json::Bool(true));
notes.push(format!(
"Instinct ran this call in the background: its class usually takes over {} s in the foreground here (lesson {}). You will be told when it finishes.",
speed::SLOW_SECS,
super::starter::fix_lesson("bg-slow")
));
}
if tool_input == *args {
return Some(Fixed { tool_input: None, payload: event.payload.clone(), notes });
}
let mut payload = event.payload.clone();
set_field(&mut payload, "tool_input", tool_input.clone());
Some(Fixed { tool_input: Some(tool_input), payload, notes })
}
fn render_fixed(lesson: &str, retry: Option<&str>, note: Option<&str>, format: &Format, updated: Option<&Json>) -> String {
let mut text = if lesson.trim().is_empty() {
retry.unwrap_or("").to_string()
} else {
let head = retry.map(|n| format!("{n}\n")).unwrap_or_default();
format!("{head}Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\n{lesson}")
};
if let Some(n) = note {
if !text.is_empty() {
text.push('\n');
}
text.push_str(n);
}
if text.len() > MAX_CONTEXT {
let mut end = MAX_CONTEXT;
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
}
match format {
Format::Json => {
let upd = updated.map(|u| format!("\"updatedInput\":{},", to_json(u))).unwrap_or_default();
format!(
"{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",{upd}\"additionalContext\":\"{}\"}}}}",
escape_json(&text)
)
}
Format::Text => text,
Format::Silent => String::new(),
}
}
pub fn with_notice(out: String, format: &Format, notice: &str) -> String {
match format {
Format::Json if out.is_empty() => format!("{{\"systemMessage\":\"{}\"}}", escape_json(notice)),
Format::Json => match out.strip_prefix('{') {
Some(rest) => format!("{{\"systemMessage\":\"{}\",{rest}", escape_json(notice)),
None => out,
},
Format::Text if out.is_empty() => notice.to_string(),
Format::Text => format!("{notice}\n{out}"),
Format::Silent => out,
}
}
pub fn run(a: &Args) {
let mut input = String::new();
if std::io::stdin().take(1 << 20).read_to_string(&mut input).is_err() {
return;
}
let Ok(path) = store_path(a) else { return };
let Some(mut event) = parse(&input) else { return };
match a.opt("format") {
Some("text") => event.format = Format::Text,
Some("json") => event.format = Format::Json,
_ => {}
}
let explicit = a.opt("store").is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
let seeded = super::starter::seed_first_run(&path, explicit);
if event.format == Format::Silent {
return;
}
super::team::set_cwd(event.cwd.as_deref());
let scope = eligibility::prompt_scope(a.opt("project"), event.cwd.as_deref());
let fixed = fix_step(&path, &scope, &event, &input);
let timing_input = fixed.as_ref().map(|f| to_json(&f.payload));
let timing_note = super::speed::before(&path, timing_input.as_deref().unwrap_or(&input));
let note = match (&fixed, timing_note) {
(Some(f), t) => {
let mut n = f.notes.clone();
n.extend(t);
Some(n.join("\n"))
}
(None, t) => t,
};
let updated = fixed.as_ref().and_then(|f| f.tool_input.as_ref());
let timer = meter::start(&path, "guard");
let sid = event.session.as_deref();
let seen = sid.map(|s| session::seen(&path, s).lesson_ids()).unwrap_or_default();
let recalled = match super::starter::guard_pick(&path, &event.situation, &scope, &seen, event.cwd.as_deref()) {
Some(d) => Ok(vec![d]),
None => recall_methods(&path, &event.situation, 41 + seen.len().min(10), &scope).map(|mut m| {
m.retain(|d| !super::starter::has_cmd(d));
m
}),
};
{
let mut methods = recalled.unwrap_or_default();
methods.retain(|d| !seen.contains(&d.id));
methods.truncate(1);
if let Some(s) = sid {
methods.retain(|d| session::claim_lesson(&path, s, &d.id, session::Source::Guard));
}
let (lesson, ids) = render_recall(&methods);
let retry = match (event.bash.as_deref(), sid) {
(Some(c), Some(s)) => super::gates::retry_warning(&path, s, c, event.cwd.as_deref()),
_ => None,
};
let out = if lesson.trim().is_empty() && retry.is_none() && note.is_none() {
String::new()
} else {
render_fixed(&lesson, retry, note.as_deref(), &event.format, updated)
};
if let Some(t) = timer {
t.finish(if out.is_empty() { 0 } else { ids.len() }, out.len());
}
let mut said: Vec<String> = Vec::new();
if let (Format::Json, false, Some(d)) = (&event.format, out.is_empty(), methods.first()) {
let title = d.title.split_whitespace().collect::<Vec<_>>().join(" ");
said.push(format!("Instinct tripwire: {title} (advisory, nothing was blocked)"));
}
if let (Format::Json, Some(n)) = (&event.format, ¬e) {
said.push(n.clone());
}
if let Some(n) = seeded {
said.push(super::starter::first_run_notice(n));
}
let out = if said.is_empty() { out } else { with_notice(out, &event.format, &said.join("\n")) };
if !out.is_empty() {
println!("{out}");
}
}
}