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
//! Differential test for the Helix tripwire matcher (src/tripwire.hlx, exported to src/tripwire.rs).
//! `original` below is a frozen copy of the hand-written Rust that lived in src/starter.rs before the port.
//! Do not edit it: it is the reference the Helix export has to match, byte for byte, on every case.
#[allow(dead_code)]
#[path = "../src/tripwire.rs"]
mod tripwire;

/// Frozen copy of the original matcher (src/starter.rs at 0.3.3, before the port).
mod original {
    pub fn has_cmd_tags(tags: &str) -> bool {
        tags.split(';').any(|t| t.trim().to_lowercase().starts_with("cmd:"))
    }

    pub fn cmd_specs_tags(tags: &str) -> Vec<String> {
        let mut v: Vec<String> = tags.split(';').map(str::trim).filter(|t| t.to_lowercase().starts_with("cmd:")).map(str::to_owned).collect();
        v.sort();
        v
    }

    pub fn words(command: &str) -> Vec<String> {
        let mut s = String::with_capacity(command.len() + 8);
        let mut chars = command.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '"' | '\'' | '`' => {}
                ';' | '|' | '&' | '(' | ')' => s.push(' '),
                '>' => {
                    if chars.peek() == Some(&'>') {
                        chars.next();
                        s.push_str(" >> ");
                    } else {
                        s.push_str(" > ");
                    }
                }
                c => s.push(c),
            }
        }
        s.split_whitespace().map(str::to_owned).collect()
    }

    fn token_hits(tok: &str, word: &str) -> bool {
        match tok.strip_prefix('*') {
            Some("") => word == "*",
            Some(sub) => word.contains(sub) || (!sub.starts_with('-') && word.to_lowercase().contains(&sub.to_lowercase())),
            None => word == tok || (tok.chars().all(|c| c.is_ascii_alphabetic()) && word.eq_ignore_ascii_case(tok)),
        }
    }

    pub fn spec_matches(spec: &str, words: &[String]) -> Option<usize> {
        let mut at = 0;
        let mut positive = 0;
        for tok in spec.split_whitespace() {
            if let Some(neg) = tok.strip_prefix('!') {
                if words.iter().any(|w| token_hits(neg, w)) {
                    return None;
                }
                continue;
            }
            let found = words.iter().skip(at).position(|w| token_hits(&tok, w))?;
            at += found + 1;
            positive += 1;
        }
        (positive > 0).then_some(positive)
    }

    /// The tag loop of the original `guard_pick`, for one lesson: best positive count over its `cmd:` tags.
    pub fn best_match(tags: &str, w: &[String]) -> Option<usize> {
        let mut best: Option<usize> = None;
        for t in tags.split(';') {
            let t = t.trim();
            let Some(spec) = t.get(..4).filter(|p| p.eq_ignore_ascii_case("cmd:")).map(|_| &t[4..]) else {
                continue;
            };
            if let Some(n) = spec_matches(spec, w) {
                if best.is_none_or(|b| n > b) {
                    best = Some(n);
                }
            }
        }
        best
    }
}

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
    fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
    fn pick<'a>(&mut self, v: &[&'a str]) -> &'a str {
        v[self.below(v.len())]
    }
}

const WORDS: &[&str] = &[
    "git", "push", "--force", "-f", "--force-with-lease", "origin", "main", "rm", "-rf", "-RF", "-r", "-D", "-d", "branch", "reset", "--hard",
    "DELETE", "delete", "FROM", "from", "users", "WHERE", "where", "id=1", "psql", "-c", "flushall", "FLUSHALL", "redis-cli", "chmod", "-R", "777",
    "/", "~", "~/.bashrc", ".bashrc", "$BUILD", "${BUILD:?}", "*", "./target", "/*", "docker", "system", "prune", "-a", "kubectl", "drop",
    "table", "DROP", "TABLE", "sudo", "curl", "|", "sh", "dd", "if=/dev/zero", "of=/dev/sda", "mkfs", "ls", "cat", "echo", "cd", "x", "&&", "||", ";",
    ">", ">>", "2>&1", "-9", "kill", "pkill", "-f", "server", "npm", "publish", "terraform", "destroy", "--force-push", "Ünï", "ÄÖ", "İ", "ß", "日本",
];

const TOKENS: &[&str] = &[
    "git", "push", "--force", "-f", "-D", "-d", "rm", "-rf", "-r", "*$", "*:?", "!*:?", "*", "!*", "!where", "!WHERE", "delete", "from", "DELETE", "FROM",
    "where", "flushall", "!--force-with-lease", ">", ">>", "*.bashrc", "*.BASHRC", "*-RF", "*-rf", "*日本", "*ß", "*SS", "*İ", "!", "!!", "*!", "chmod",
    "777", "*77", "!777", "drop", "TABLE", "table", "!table", "sudo", "!sudo", "*/", "/", "~", "origin", "main", "--hard", "reset", "dd", "if=*", "*=/dev/*",
    "ÄÖ", "äö", "ä", "x", "ls", "!ls", "docker", "prune", "-a", "kill", "-9",
];

const SEPARATORS: &[&str] = &[" ", " ", " ", "  ", "\t", " && ", " | ", "; ", " > ", ">", ">>", " >> ", "(", ")", "\"", "'", "`", "\n"];

fn command(r: &mut Rng) -> String {
    let n = r.below(14);
    let mut s = String::new();
    for i in 0..n {
        if i > 0 || r.below(8) == 0 {
            s.push_str(r.pick(SEPARATORS));
        }
        if r.below(6) == 0 {
            s.push_str(r.pick(SEPARATORS));
        }
        s.push_str(r.pick(WORDS));
    }
    s
}

fn spec(r: &mut Rng) -> String {
    let n = r.below(6);
    let mut s = String::new();
    for i in 0..n {
        if i > 0 {
            s.push_str(r.pick(&[" ", " ", " ", "  ", "\t"]));
        }
        s.push_str(r.pick(TOKENS));
    }
    s
}

/// Tag text as the bank stores it: `;`-separated, mixed prose tags and `cmd:` tags with odd spacing and case.
fn tags(r: &mut Rng) -> String {
    let n = r.below(5);
    let mut parts: Vec<String> = Vec::new();
    for _ in 0..n {
        let body = spec(r);
        let t = match r.below(9) {
            0 => format!("cmd:{body}"),
            1 => format!("CMD:{body}"),
            2 => format!("Cmd: {body}"),
            3 => format!("  cmd:{body}  "),
            4 => format!("cmd {body}"),
            5 => format!("cmd:{body}ä"),
            6 => "ünï".to_string(),
            7 => "safety".to_string(),
            _ => format!("cmd:{body}"),
        };
        parts.push(t);
    }
    parts.join(r.pick(&[";", "; ", " ; ", ";"]))
}

fn pack_specs() -> Vec<String> {
    let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/community/tripwires.json")).unwrap();
    let mut out = Vec::new();
    for part in text.split("cmd:").skip(1) {
        let end = part.find([';', '"']).unwrap_or(part.len());
        out.push(part[..end].to_string());
    }
    // `=` tokens are newer than the frozen copy, which reads them as plain words; tests below cover them.
    out.retain(|s| !s.split_whitespace().any(|t| t.trim_start_matches(['!', '<']).starts_with('=') || t.starts_with('<')));
    out
}

#[test]
fn command_words_equal_words_when_no_segment_only_reads() {
    let mut r = Rng(0x51ED_270B_0F3A_9C17);
    let reading = ["echo", "cat", "ls"];
    let (mut same, mut skipped) = (0u32, 0u32);
    for _ in 0..30_000 {
        let cmd = command(&mut r);
        let w = tripwire::words(&cmd);
        if reading.iter().any(|r| cmd.contains(r)) {
            skipped += 1;
            continue;
        }
        assert_eq!(tripwire::command_words(&cmd), w, "{cmd:?}");
        same += 1;
    }
    println!("command_words equals words on {same} generated commands ({skipped} with a reading word skipped)");
    assert!(same > 10_000);
}

fn cw(cmd: &str) -> Vec<String> {
    tripwire::command_words(cmd)
}

#[test]
fn text_given_to_a_reading_command_is_not_a_command() {
    for c in [
        "grep -rn mkfs docs/",
        "echo \"do not run mkfs here\"",
        "echo 'rm -rf /' ; ls",
        "man dd",
        "cat notes.md | grep 'git push --force'",
        "git log --grep=\"git reset --hard\"",
        "sudo -u dev rg 'DROP TABLE' src",
        "FOO=1 printf '%s\\n' \"kubectl delete ns prod\"",
        "ls /sbin/mkfs*",
        "echo \"a; rm -rf /\"",
        "echo 'a | rm -rf /' | head -1",
        "find . -name x | xargs grep -n mkfs",
    ] {
        let w = cw(c);
        for bad in ["mkfs", "rm", "dd", "push", "reset", "DROP", "kubectl", "/sbin/mkfs*"] {
            assert!(!w.iter().any(|x| x == bad), "{c:?} kept {bad}: {w:?}");
        }
    }
}

#[test]
fn commands_that_run_stay_whole() {
    let w = cw("sudo mkfs.ext4 /dev/sdb1");
    assert_eq!(w, ["sudo", "mkfs.ext4", "/dev/sdb1"]);
    assert_eq!(cw("find . -name x | xargs rm -rf"), ["find", ".", "-name", "x", "xargs", "rm", "-rf"]);
    assert_eq!(cw("echo 'rm -rf /' | sh"), ["echo", "rm", "-rf", "/", "sh"]);
    assert_eq!(cw("echo \"DROP TABLE users\" | sudo -u pg psql db"), ["echo", "DROP", "TABLE", "users", "sudo", "-u", "pg", "psql", "db"]);
    assert_eq!(cw("cd /tmp && rm -rf *"), ["cd", "/tmp", "rm", "-rf", "*"]);
}

#[test]
fn a_reading_command_keeps_its_real_redirects_only() {
    assert_eq!(cw("echo hi > ~/.bashrc"), [">", "~/.bashrc"]);
    assert_eq!(cw("cat disk.img >> /dev/sdb"), [">>", "/dev/sdb"]);
    assert!(cw("echo 'a > ~/.bashrc'").is_empty());
    assert!(cw("echo \"a > ~/.bashrc\" | wc -l").is_empty());
    // an escaped quote does not end the quoted text
    assert!(cw("echo \"say \\\"hi\\\" ; rm -rf /\"").is_empty());
}

fn fires(spec: &str, cmd: &str) -> bool {
    tripwire::spec_matches(spec, &tripwire::words(cmd)).is_some()
}

#[test]
fn equals_tokens_match_whole_words_without_case() {
    assert!(fires("rm =-rf|-fr", "rm -RF x"));
    assert!(fires("rm =-rf|-fr", "sudo rm -fr x"));
    assert!(!fires("rm =-rf|-fr", "rm -rfv x"));
    assert!(!fires("rm =-rf|-fr", "rm -r -f x"));
    // an empty alternative never matches
    assert!(!fires("rm =|", "rm x"));
    // a plain token is unchanged: `=` only means something at the start
    assert!(fires("dd *of=/dev/", "dd of=/dev/sdb"));
}

#[test]
fn question_mark_is_one_path_segment() {
    let spec = "rm =/home/?|/home/?/*";
    for yes in ["rm -rf /home/leduc", "rm -rf /HOME/Leduc/", "rm -rf /home/leduc/*", "rm /home/ünï"] {
        assert!(fires(spec, yes), "{yes}");
    }
    for no in ["rm -rf /home", "rm -rf /home/", "rm -rf /home/leduc/project", "rm -rf /home/leduc/*/x", "rm -rf /home/*", "rm -rf /homes/leduc", "rm -rf ~/home/leduc"] {
        assert!(!fires(spec, no), "{no}");
    }
}

#[test]
fn caret_accepts_every_cut_short_form() {
    let spec = "=remove-item =-r^ecurse";
    for yes in ["Remove-Item -r x", "Remove-Item -Rec x", "Remove-Item -RECURSE x", "Remove-Item x -recurse"] {
        assert!(fires(spec, yes), "{yes}");
    }
    for no in ["Remove-Item -rf x", "Remove-Item -recursed x", "Remove-Item -rx x", "Remove-Item x"] {
        assert!(!fires(spec, no), "{no}");
    }
    assert!(fires("x =-fo^rce", "x -fo") && fires("x =-fo^rce", "x -Force"));
    assert!(!fires("x =-fo^rce", "x -f") && !fires("x =-fo^rce", "x -fi"));
}

#[test]
fn star_and_plus_alternatives_in_equals_tokens() {
    let drive = "rd =*:\\|*:/|*%|**|\\+";
    for yes in ["rd C:\\", "rd c:/x", "rd %TEMP%\\x", "rd *.tmp", "rd \\\\srv\\share", "rd D:\\a\\b"] {
        assert!(fires(drive, yes), "{yes}");
    }
    for no in ["rd build", "rd .\\build", "rd out\\obj", "rd ./x"] {
        assert!(!fires(drive, no), "{no}");
    }
    let home = "rm =$home/+|${home}/+";
    for yes in ["rm $HOME/code", "rm \"$HOME\"/a/b/", "rm ${HOME}/.cache/pip", "rm $HOME/.cache"] {
        assert!(fires(home, yes), "{yes}");
    }
    for no in ["rm $HOME", "rm $HOME/", "rm $HOME/*", "rm $HOME/.*", "rm $HOME/.[a-z]*", "rm $HOMEDIR/x", "rm ${HOME}", "rm $BUILD/x"] {
        assert!(!fires(home, no), "{no}");
    }
}

#[test]
fn a_bang_alternative_vetoes_the_word() {
    let spec = "rm =*$|!$home/+|!${home}/+";
    for yes in ["rm $OTHER/*", "rm $HOME", "rm $HOME/*", "rm $HOME/$SUB", "rm $HOME/x $OTHER/*", "rm $HOME/x && rm $DIR/"] {
        assert!(fires(spec, yes), "{yes}");
    }
    for no in ["rm $HOME/x", "rm \"$HOME/a\" \"$HOME/b\"", "rm ${HOME}/a/b", "rm build"] {
        assert!(!fires(spec, no), "{no}");
    }
}

#[test]
fn a_gap_token_forbids_words_before_the_next_match() {
    let spec = "find <=-name|-type <*-newer -delete";
    assert!(fires(spec, "find . -delete"));
    assert!(fires(spec, "find ~/x -delete -name '*.tmp'"));
    assert!(fires(spec, "find . -maxdepth 1 -delete"));
    assert!(!fires(spec, "find . -name '*.tmp' -delete"));
    assert!(!fires(spec, "find . -type f -delete"));
    assert!(!fires(spec, "find . -newermt 2026-01-01 -delete"));
    // the gap is the words between the previous match and the next one
    assert!(fires("find <=-name -prune -delete", "find -prune -delete"));
    assert!(!fires("find -prune <=-name -delete", "find -prune -name x -delete"));
}

#[test]
fn a_negated_equals_token_silences_the_spec() {
    let spec = "=remove-item =-r^ecurse !=-w^hatif";
    assert!(fires(spec, "Remove-Item -Recurse build"));
    assert!(!fires(spec, "Remove-Item -Recurse -WhatIf build"));
    assert!(!fires(spec, "Remove-Item -Recurse -wh build"));
}

#[test]
fn helix_matcher_equals_the_frozen_rust_matcher_on_over_a_hundred_thousand_cases() {
    let mut r = Rng(0x9E37_79B9_7F4A_7C15);
    let mut cases = 0u64;
    let mut matched = 0u64;
    let mut diffs: Vec<String> = Vec::new();
    let mut check = |cmd: &str, spec: &str| {
        let (a, b) = (original::words(cmd), tripwire::words(cmd));
        cases += 1;
        if a != b {
            diffs.push(format!("words({cmd:?})"));
            return;
        }
        let (x, y) = (original::spec_matches(spec, &a), tripwire::spec_matches(spec, &b));
        if x.is_some() {
            matched += 1;
        }
        if x != y {
            diffs.push(format!("spec_matches({spec:?}, {cmd:?}): {x:?} vs {y:?}"));
        }
    };

    // Generated commands against generated specs.
    for _ in 0..10_000 {
        let cmd = command(&mut r);
        for _ in 0..16 {
            let sp = spec(&mut r);
            check(&cmd, &sp);
        }
    }
    // The real pack's specs against generated commands, and against the same commands with a spec word planted in.
    let pack = pack_specs();
    assert!(pack.len() >= 25, "pack specs read: {}", pack.len());
    for _ in 0..2_000 {
        let base = command(&mut r);
        for sp in &pack {
            check(&base, sp);
            let mut planted = base.clone();
            for tok in sp.split_whitespace().filter(|t| !t.starts_with('!')) {
                planted.push(' ');
                planted.push_str(tok.trim_start_matches('*'));
            }
            check(&planted, sp);
        }
    }
    println!("tripwire differential: {cases} command x spec cases, {matched} matched, {} differences", diffs.len());
    assert!(cases >= 100_000, "only {cases} cases");
    assert!(matched >= 10_000, "only {matched} matching cases: the generator must reach the match path");
    assert!(diffs.is_empty(), "{} differences, first: {:?}", diffs.len(), &diffs[..diffs.len().min(5)]);
}

#[test]
fn helix_tag_helpers_equal_the_frozen_rust_on_generated_tag_lists() {
    let mut r = Rng(0xD1B5_4A32_D192_ED03);
    let mut cases = 0u64;
    let mut with_match = 0u64;
    for _ in 0..30_000 {
        let tg = tags(&mut r);
        assert_eq!(original::has_cmd_tags(&tg), tripwire::has_cmd(&tg), "has_cmd({tg:?})");
        assert_eq!(original::cmd_specs_tags(&tg), tripwire::cmd_specs(&tg), "cmd_specs({tg:?})");
        for _ in 0..4 {
            let w = original::words(&command(&mut r));
            let (x, y) = (original::best_match(&tg, &w), tripwire::best_match(&tg, &w));
            assert_eq!(x, y, "best_match({tg:?}, {w:?})");
            cases += 1;
            if x.is_some() {
                with_match += 1;
            }
        }
    }
    println!("tripwire differential: {cases} tag-list x command cases for best_match, {with_match} matched");
    assert!(with_match >= 1_000, "only {with_match} matching tag lists");
}