instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Verify-before-done v2 (`INSTINCT_DONE_GATE=2`): did the agent's checks touch what the user will use?
//!
//! Targets come from typed user messages (URLs and domains, hosts and IPs, file paths, version and model strings,
//! and a short list of device and channel words) and from project lessons whose HOW says "verify on" or "check
//! on". At Stop, on a completion claim in a turn that changed something, if targets exist and no tool call since
//! the last edit touched any of them, the final message is sent back once. Rules are pre-registered in
//! `bench/premortem-gates/PROTOCOL.md` (addendum). Pure and deterministic; the hook reads a bounded transcript tail.
use super::*;
use gates::{claims_done, hash, is_edit_tool, read_only};
use mine::Kind as EvKind;

/// Targets kept, newest first.
pub const MAX_TARGETS: usize = 12;
/// Targets named in the block message.
const SHOWN: usize = 3;
/// Transcript tail read by the hook.
const TAIL: u64 = 1 << 20;
/// Typed messages read from the tail.
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"];

/// Replay-only switch (post-hoc analysis): kinds of target to ignore, set by `gates-trace` from `GATES_V2_SKIP`
/// (comma list of word, version, path, url, ip). Never read by the hooks.
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 {
    /// What the user typed (shown in the message).
    pub shown: String,
    /// Normalized form the calls are matched against.
    norm: String,
    /// A device or channel word: matched as a whole word.
    word: bool,
    /// A file path: its last component also matches.
    base: Option<String>,
}

/// Lowercase, scheme and `www.` removed, leading `./` and `~/` removed, trailing `/` removed.
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 }
}

/// The targets named in one typed message, in order of appearance, without repeats.
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)
}

/// True when one normalized call text touches the target.
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()))
}

/// The words after "verify on" or "check on" in a lesson's HOW, up to the end of the sentence, at most 60 chars.
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
}

/// The gate state over one session, in transcript order.
#[derive(Default)]
pub struct V2 {
    /// Newest first.
    targets: Vec<Target>,
    active: bool,
    calls: Vec<String>,
}

impl V2 {
    /// A typed user message: new targets go first, and a new turn starts.
    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);
            }
        }
    }
    /// A tool call: an edit starts a new window; any other call is a candidate check.
    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());
    }
    /// An edit call was made: the turn is active and earlier calls no longer count.
    pub fn edit(&mut self) {
        self.active = true;
        self.calls.clear();
    }
    pub fn active(&self) -> bool {
        self.active
    }
    /// The final message of a turn: the targets (up to three, newest first) when the gate fires.
    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()
}

/// Replay support for v3 (`gates-trace` with `GATES_V3=1`): one `C` row per typed correction that names a target
/// (`norm US word US base`, targets joined by RS) and one `K` row per completion claim in a turn that changed
/// something (the lowercase calls since the last edit, joined by RS). The script does the chronological learning.
/// Rows go to stdout of the private replay only.
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(", "))
}

/// Runs v2 over parsed events: one entry per firing claim, `(transcript line of the claim, targets shown)`.
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)
}

/// The V2 state at the end of the transcript: typed messages (oldest first) up to the last one, then that turn's calls.
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 {
        // Skip traffic before the last real edit. Parse that whole line because one record can
        // contain both the edit and a subsequent check. Field spacing is irrelevant.
        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 })
}

/// "verify on" / "check on" targets from the project bank, in the scope of the event's folder.
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()
}

/// `instinct stop` with `INSTINCT_DONE_GATE=2`. Called by `gates::stop`, which has checked the flag, the
/// `stop_hook_active` field and that the message claims completion.
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() {
        // targets may still come from the project bank
        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;