instinct-cli 0.3.10

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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Two advisory gates, both off unless enabled, deterministic, no model calls.
//!
//! 1. Retry tripwire (`INSTINCT_RETRY=1`): `instinct track` (PostToolUseFailure / PostToolUse) records each failed
//!    Bash command as a hash of its normalized form; `instinct guard` (PreToolUse) adds one line of context the
//!    first time a form that already failed twice in this session is about to run again. Never blocks.
//! 2. Verify-before-done gate (`INSTINCT_DONE_GATE=1`): `instinct stop` (Stop). After a typed user correction, a
//!    final message that claims completion with nothing run since the last change is sent back once per correction.
//!
//! The decision logic is pure ([`normalize`], [`claims_done`], [`DoneGate`]) so that `instinct scan` and the
//! replay in `bench/premortem-gates/replay.mjs` apply the rules the hooks apply. The ledger rows hold hashes
//! and counts only, never command text.
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.";

/// Failures of one form in a session before the warning (the warning comes before the third attempt).
pub const RETRY_AFTER: usize = 2;
/// The transcript tail the Stop hook reads, in bytes.
const TAIL_BYTES: u64 = 2 << 20;
/// A completion claim is looked for in the last this-many characters of the message.
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")
}

// ------------------------------------------------------------ normalization

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 == '.')
}

/// Splits off the first whitespace-delimited word.
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())
}

/// One prefix wrapper removed, or `None` when the command starts with none.
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
}

/// The command with wrappers that do not change what is being retried removed:
/// `timeout [--foreground] [-s SIG] [-k D] N`, `sudo`, `env`, leading `VAR=val`, `cd X &&`, trailing `2>&1`,
/// trailing `| tail|head [-n] [-]N`. Whitespace is collapsed. Everything else stays verbatim.
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(" ")
}

/// 64-bit FNV-1a, 16 hex digits.
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))
}

// ------------------------------------------------------------ completion claims

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()
}

/// True when the end of `text` claims completion: one of the phrases as whole words, not within two words after
/// a negator or a conditional, and not inside a question.
pub fn claims_done(text: &str) -> bool {
    let n = text.chars().count();
    let tail: String = text.chars().skip(n.saturating_sub(CLAIM_TAIL)).collect();
    // split keeping the terminator, so a sentence that ends in `?` is skipped
    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
}

// ------------------------------------------------------------ verify-before-done

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)
}

/// A Bash command that only looks at files or history and runs nothing: it does not verify a change.
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,
    /// Identity of the last correction (hash of its text), for once-per-correction bookkeeping.
    pub correction_key: String,
}

impl DoneGate {
    /// A typed user message. A correction arms the gate and opens a new verification window.
    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);
        }
    }
    /// A file edit invalidates earlier verification.
    pub fn edit(&mut self) {
        self.verified = false;
    }
    /// A Bash command. Anything that is not read-only counts as running something.
    pub fn bash(&mut self, cmd: &str) {
        if !read_only(cmd) {
            self.verified = true;
        }
    }
    /// The final assistant message of a turn. True when the gate fires (at most once per correction).
    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
    }
}

/// Runs the gate over parsed events, the way `scan` and the Stop hook both do. Returns how many turns end in
/// a firing final message, and the correction key of the last firing. `last_message` replaces the text of the last
/// turn's final message when given (the Stop payload carries it before the transcript does).
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
}

/// Walks the Bash calls of a transcript in order. For each call it reports the failure count its form had
/// before the call started; failures are counted once per tool-use id (a resumed transcript repeats lines).
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
}

/// Where the retry tripwire would have warned: (transcript line of the command about to run again, whether the
/// command carried a `timeout` wrapper). Same counting as the hooks: a form is warned about once, after its
/// second failure.
pub fn retry_points(evs: &[mine::Ev]) -> Vec<(usize, bool)> {
    retry_points_by(evs, &form_id)
}

/// Post-hoc variant for the replay only: the form is the first two words of the normalized command.
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
}

/// `instinct gates-trace FILE...` (hidden, used by `bench/premortem-gates/replay.mjs`): one row per decision
/// point, `file-index TAB R|D TAB line TAB flag`. Line numbers and flags only, no transcript text.
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");
        }
    }
}

/// Failed Bash forms with 3 or more failures in one transcript.
pub fn retried_forms(evs: &[mine::Ev]) -> u32 {
    walk_failures(evs, &form_id, |_, _| {}).values().filter(|n| **n >= 3).count() as u32
}

// ------------------------------------------------------------ hooks

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()
}

/// A direct Python script with one literal input in the event workspace. This excludes shell
/// expansions, wrappers, path traversal and nested symlink components.
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)?;
    // A script can chdir before opening a relative operand. Only the absolute error identifies
    // the same path the hook checks, even when both directories have a file with that name.
    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()))
}

/// `instinct track`: PostToolUseFailure / PostToolUse. Records one row (form hash and exit status) for a failed
/// Bash command. Silent, exit 0, nothing on stdout.
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);
}

/// For `guard`: the one warning line when this Bash command's form already failed twice in the session and
/// has not been warned about yet. Records the warning so it is given once.
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)
}

/// The last `n` bytes of the file as whole lines (a cut start drops its partial first 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 })
}

/// Reads backward in growing steps (64 KiB, doubling, up to `TAIL_BYTES`) until the last correction is in view.
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);
    }
}

/// The transcript from the last typed correction to the end, without the tool-result lines the gate does not
/// read, or `None` when the tail holds no correction. Walks backward and parses only typed user lines, so the
/// cost follows the length of the window, not of the tail.
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
}

/// `instinct stop`: Stop hook. Prints the block JSON at most once per correction; otherwise silent, exit 0.
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 };
    // Documented: true when Claude Code is already continuing because of a stop hook. Never block again.
    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));
    }
}