use super::*;
use gates::{claims_done, hash, is_edit_tool, read_only};
use mine::Kind as EvKind;
pub const MAX_TARGETS: usize = 12;
const SHOWN: usize = 3;
const TAIL: u64 = 1 << 20;
const MAX_MESSAGES: usize = 40;
pub const DONE_V2_PREFIX: &str = "You said it is done, but your checks did not touch what the user will use: ";
pub const DONE_V2_SUFFIX: &str = ". Check there and report what you saw.";
const TLDS: [&str; 13] = ["com", "ai", "io", "net", "org", "dev", "app", "sk", "cz", "co", "me", "sh", "local"];
const FAMILIES: [&str; 12] =
["claude", "opus", "sonnet", "haiku", "gpt", "gemini", "llama", "qwen", "mujoco", "grok", "deepseek", "mistral"];
const WORDS: [&str; 8] = ["phone", "iphone", "android", "telegram", "browser", "live", "prod", "production"];
pub static SKIP: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
const SK_WORD: u8 = 1;
const SK_VERSION: u8 = 2;
const SK_PATH: u8 = 4;
const SK_URL: u8 = 8;
const SK_IP: u8 = 16;
pub fn set_skip(list: &str) {
let mut m = 0;
for k in list.split(',') {
m |= match k.trim() {
"word" => SK_WORD,
"version" => SK_VERSION,
"path" => SK_PATH,
"url" => SK_URL,
"ip" => SK_IP,
_ => 0,
};
}
SKIP.store(m, std::sync::atomic::Ordering::Relaxed);
}
fn skipped(bit: u8) -> bool {
SKIP.load(std::sync::atomic::Ordering::Relaxed) & bit != 0
}
pub fn on() -> bool {
std::env::var("INSTINCT_DONE_GATE").is_ok_and(|v| v.trim() == "2")
}
#[derive(Clone, Debug, PartialEq)]
pub struct Target {
pub shown: String,
norm: String,
word: bool,
base: Option<String>,
}
pub fn norm(s: &str) -> String {
let mut t = s.trim().to_lowercase();
for p in ["https://", "http://"] {
if let Some(r) = t.strip_prefix(p) {
t = r.to_string();
}
}
for p in ["www.", "./", "~/"] {
if let Some(r) = t.strip_prefix(p) {
t = r.to_string();
}
}
t.trim_end_matches('/').to_string()
}
fn all_digits(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
}
fn host_like(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
}
fn is_ipv4(s: &str) -> bool {
let p: Vec<&str> = s.split('.').collect();
p.len() == 4 && p.iter().all(|x| all_digits(x) && x.len() <= 3)
}
fn is_domain(host: &str) -> bool {
let parts: Vec<&str> = host.split('.').collect();
parts.len() >= 2
&& host_like(host)
&& parts.iter().all(|p| !p.is_empty())
&& TLDS.contains(&parts[parts.len() - 1].to_lowercase().as_str())
}
fn is_version(t: &str) -> bool {
let l = t.to_lowercase();
if let Some(r) = l.strip_prefix('v') {
if !r.is_empty() && r.split('.').all(all_digits) {
return true;
}
}
let p: Vec<&str> = l.split('.').collect();
if p.len() >= 3 && p.iter().all(|x| all_digits(x)) {
return !is_ipv4(&l);
}
if let Some((fam, rest)) = l.split_once('-') {
return FAMILIES.contains(&fam)
&& !rest.is_empty()
&& rest.split(['-', '.']).all(all_digits);
}
false
}
fn has_extension(last: &str) -> bool {
match last.rsplit_once('.') {
Some((stem, ext)) => !stem.is_empty() && (1..=5).contains(&ext.len()) && ext.chars().all(|c| c.is_ascii_alphanumeric()),
None => false,
}
}
fn file_path(t: &str) -> bool {
if t.starts_with("//") || t.len() < 3 {
return false;
}
if t.starts_with('/') || t.starts_with("~/") || t.starts_with("./") || t.starts_with("../") {
return t.trim_matches(['/', '.', '~']).len() >= 2;
}
t.contains('/') && has_extension(t.rsplit('/').next().unwrap_or(""))
}
fn clean(tok: &str) -> &str {
let t = tok.trim_matches(|c: char| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']' | '<' | '>' | ',' | ';' | '{' | '}'));
t.trim_end_matches(['.', ':', '!', '?'])
}
fn make(shown: &str, word: bool) -> Target {
let shown: String = shown.chars().take(80).collect();
let n = norm(&shown);
let base = (!word && n.contains('/'))
.then(|| n.rsplit('/').next().unwrap_or("").to_string())
.filter(|b| has_extension(b));
Target { shown, norm: n, word, base }
}
pub fn extract(text: &str) -> Vec<Target> {
let mut out: Vec<Target> = Vec::new();
let mut push = |t: Target| {
if t.norm.len() >= 2 && !out.iter().any(|o| o.norm == t.norm) {
out.push(t);
}
};
let toks: Vec<&str> = text.split_whitespace().take(400).collect();
for (i, raw) in toks.iter().enumerate() {
let t = clean(raw);
if t.is_empty() || t.len() > 120 {
continue;
}
let low = t.to_lowercase();
if low.starts_with("http://") || low.starts_with("https://") {
if !skipped(SK_URL) {
push(make(t, false));
}
} else if is_ipv4(&low) {
if !skipped(SK_IP) {
push(make(t, false));
}
} else if let Some((h, port)) = low.split_once(':').filter(|(h, p)| all_digits(p) && p.len() <= 5 && host_like(h) && !h.is_empty()) {
let _ = port;
if is_ipv4(h) || is_domain(h) || h == "localhost" {
push(make(t, false));
}
} else if file_path(t) {
if !skipped(SK_PATH) {
push(make(t, false));
}
} else if is_domain(low.split('/').next().unwrap_or("")) {
push(make(t, false));
} else if is_version(t) {
if !skipped(SK_VERSION) {
push(make(t, false));
}
} else if WORDS.contains(&low.as_str()) {
if !skipped(SK_WORD) {
push(make(&low, true));
}
} else if !skipped(SK_WORD) && low == "public" && toks.get(i + 1).is_some_and(|n| clean(n).eq_ignore_ascii_case("link")) {
push(make("public link", true));
}
}
out
}
fn has_word(hay: &str, w: &str) -> bool {
if w.contains(' ') {
return hay.contains(w);
}
hay.split(|c: char| !c.is_alphanumeric()).any(|x| x == w)
}
pub fn touches(t: &Target, call: &str) -> bool {
if t.word {
return has_word(call, &t.norm);
}
call.contains(&t.norm) || t.base.as_ref().is_some_and(|b| call.contains(b.as_str()))
}
pub fn lesson_targets(how: &str) -> Vec<Target> {
let low = how.to_lowercase();
let mut out = Vec::new();
for phrase in ["verify on ", "check on "] {
let mut from = 0;
while let Some(i) = low[from..].find(phrase).map(|i| i + from) {
let rest = &how[i + phrase.len()..];
let end = rest
.char_indices()
.find(|&(j, c)| c == '\n' || c == ';' || (c == '.' && rest[j + 1..].chars().next().is_none_or(char::is_whitespace)))
.map_or(rest.len(), |(j, _)| j);
let s: String = rest[..end].trim().chars().take(60).collect();
if !s.is_empty() {
let w = !s.contains(['/', '.']) && s.split_whitespace().count() <= 3;
out.push(make(&s.to_lowercase(), w && s.split_whitespace().count() == 1));
}
from = i + phrase.len();
}
}
out
}
#[derive(Default)]
pub struct V2 {
targets: Vec<Target>,
active: bool,
calls: Vec<String>,
}
impl V2 {
pub fn user(&mut self, text: &str) {
let new = extract(text);
if !new.is_empty() {
self.targets.retain(|t| !new.iter().any(|n| n.norm == t.norm));
let mut v = new;
v.append(&mut self.targets);
v.truncate(MAX_TARGETS);
self.targets = v;
}
self.active = false;
self.calls.clear();
}
pub fn add_targets(&mut self, extra: Vec<Target>) {
for t in extra {
if !self.targets.iter().any(|o| o.norm == t.norm) && self.targets.len() < MAX_TARGETS {
self.targets.push(t);
}
}
}
pub fn call(&mut self, e: &mine::Ev) {
if is_edit_tool(&e.text) {
self.edit();
return;
}
if e.text == "Bash" && !read_only(&e.cmd) {
self.active = true;
}
let t = if e.cmd.is_empty() { e.text.clone() } else { e.cmd.clone() };
self.calls.push(t.to_lowercase());
}
pub fn edit(&mut self) {
self.active = true;
self.calls.clear();
}
pub fn active(&self) -> bool {
self.active
}
pub fn final_message(&self, text: &str) -> Option<Vec<String>> {
if !self.active || self.targets.is_empty() || !claims_done(text) {
return None;
}
if self.targets.iter().any(|t| self.calls.iter().any(|c| touches(t, c))) {
return None;
}
Some(self.targets.iter().take(SHOWN).map(|t| t.shown.clone()).collect())
}
}
fn clean_field(s: &str, n: usize) -> String {
s.chars().take(n).map(|c| if c.is_control() { ' ' } else { c }).collect()
}
pub fn v3_rows(evs: &[mine::Ev], file: usize) {
let mut g = V2::default();
let mut pending: Option<(&str, usize)> = None;
let flush = |g: &V2, pending: Option<(&str, usize)>| {
if let Some((t, line)) = pending {
if g.active && claims_done(t) {
let calls: Vec<String> = g.calls.iter().take(60).map(|c| clean_field(c, 600)).collect();
println!("{file}\tK\t{line}\t{}", calls.join("\u{1e}"));
}
}
};
for e in evs {
match e.kind {
EvKind::User => {
flush(&g, pending.take());
if corrections::correction(&e.text) {
let t = extract(&e.text);
if !t.is_empty() {
let rows: Vec<String> = t
.iter()
.map(|x| format!("{}\u{1f}{}\u{1f}{}", clean_field(&x.norm, 120), x.word as u8, clean_field(x.base.as_deref().unwrap_or(""), 120)))
.collect();
println!("{file}\tC\t{}\t{}", e.line, rows.join("\u{1e}"));
}
}
g.user("");
}
EvKind::Assistant => pending = Some((&e.text, e.line)),
EvKind::ToolUse => g.call(e),
EvKind::ToolResult => {}
}
}
flush(&g, pending);
}
pub fn reason(shown: &[String]) -> String {
format!("{DONE_V2_PREFIX}{}{DONE_V2_SUFFIX}", shown.join(", "))
}
pub fn run(evs: &[mine::Ev], last_message: Option<&str>) -> Vec<(usize, Vec<String>)> {
let mut g = V2::default();
let mut out = 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 let Some(s) = g.final_message(t) {
out.push((line, s));
}
}
g.user(&e.text);
}
EvKind::Assistant => pending = Some((&e.text, e.line)),
EvKind::ToolUse => g.call(e),
EvKind::ToolResult => {}
}
}
let last = match last_message {
Some(t) => Some((t, 0)),
None => pending,
};
if let Some((t, line)) = last {
if let Some(s) = g.final_message(t) {
out.push((line, s));
}
}
out
}
fn typed_text(line: &str) -> Option<String> {
mine::gate_events(line).into_iter().find(|e| e.kind == EvKind::User).map(|e| e.text)
}
fn state_from_tail(text: &str) -> V2 {
let lines: Vec<&str> = text.lines().collect();
let mut g = V2::default();
let mut turn_start = None;
let mut typed: Vec<String> = Vec::new();
for (i, l) in lines.iter().enumerate().rev() {
if typed.len() >= MAX_MESSAGES {
break;
}
if mine::possible_user_line(l) {
if let Some(t) = typed_text(l) {
if turn_start.is_none() {
turn_start = Some(i);
}
typed.push(t);
}
}
}
for t in typed.iter().rev() {
g.user(t);
}
if let Some(i) = turn_start {
let turn = &lines[i + 1..];
let last_edit = turn.iter().rposition(|line| {
["\"Edit\"", "\"Write\"", "\"MultiEdit\"", "\"NotebookEdit\""].iter().any(|name| line.contains(name))
&& mine::gate_events(line).iter().any(|e| e.kind == EvKind::ToolUse && is_edit_tool(&e.text))
});
for line in turn[last_edit.unwrap_or(0)..].iter().filter(|line| line.contains("\"tool_use\"")) {
for event in mine::gate_events(line) {
if event.kind == EvKind::ToolUse {
g.call(&event);
}
}
}
}
g
}
fn tail(path: &str) -> Option<String> {
use std::io::{Seek, SeekFrom};
let mut f = fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let start = len.saturating_sub(TAIL);
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 bank_targets(a: &Args, cwd: Option<&str>) -> Vec<Target> {
let Ok(path) = store_path(a) else { return Vec::new() };
team::set_cwd(cwd);
let Some(shared) = team::find(&path) else { return Vec::new() };
if !(team::mentions(&shared, "erify on") || team::mentions(&shared, "heck on") || team::mentions(&shared, "ERIFY ON") || team::mentions(&shared, "HECK ON")) {
return Vec::new();
}
let scope = eligibility::prompt_scope(a.opt("project"), cwd);
team::scoped(&shared, &scope, now_secs()).iter().flat_map(|d| lesson_targets(&d.how)).collect()
}
pub fn stop(a: &Args, ev: &Json, sid: &str, msg: &str) {
let Some(tp) = ev.get("transcript_path").and_then(Json::as_str) else { return };
let Some(text) = tail(tp) else { return };
let mut g = state_from_tail(&text);
if !g.active() {
return;
}
if g.final_message(msg).is_none() {
g.add_targets(bank_targets(a, ev.get("cwd").and_then(Json::as_str)));
}
let Some(shown) = g.final_message(msg) else { return };
let Ok(path) = store_path(a) else { return };
if session::claim_block(&path, sid, &format!("v2:{}", hash(msg))) {
println!("{{\"decision\":\"block\",\"reason\":\"{}\"}}", escape_json(&reason(&shown)));
}
}
#[cfg(test)]
mod tests;