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
//! `instinct starter [--apply] [--json] [--store PATH]`: the community tripwire pack (`community/tripwires.json`).
//!
//! A new bank is empty, so `instinct guard` has nothing to say. The pack is lessons for classic agent
//! disasters, each with its safe alternative. A dry run lists it; `--apply` banks it as `source: community`.
//! Idempotent: a lesson already in the bank (same id) is skipped, so a rerun banks 0.
//!
//! Command tags. A tag of the form `cmd:<tokens>` makes `instinct guard` match the lesson on the command
//! itself, because short commands (`rm`, `dd`, `-rf`) are never prose anchors. Words are the command split on
//! whitespace and `; | & ( )`, with quotes removed, and `>` and `>>` as words of their own.
//!   word    must appear as a whole word (`--force` does not match `--force-with-lease`), in order; flags and paths
//!           are case-sensitive (`-D` is not `-d`), a keyword of letters only (`where`, `flushall`) is not
//!   *text   a word containing `text` (`*$` is any word with a variable in it)
//!   !word   or `!*text`: the command must NOT contain it (`delete from !where`)
//!   =pat    a whole word, any case. `a|b` lists alternatives, `?` is one path segment (`=/home/?` is `/home/leduc`
//!           but not `/home/leduc/src`), `^` lets the word be cut short (`=-r^ecurse` is `-r`, `-rec`, `-recurse`)
//! Text that a reading command only prints is not a command: segments of grep, rg, echo, printf, man, cat, less, head,
//! tail, wc, ls, `git log` and `git grep` are dropped (their own `>` redirects stay), unless piped into a shell or a SQL client.
//! Several `cmd:` tags on one lesson are alternatives; the one with the most positive tokens wins.
//! Prose recall ignores `cmd:` lessons in `guard`, and `cmd:` tags are inert everywhere else.
//! Sibling access goes through `super::` because the playground compiles main.rs as a submodule.
use super::*;

const PACK: &str = include_str!("../community/tripwires.json");

pub const STARTER_HELP: &str = "usage: instinct starter [--apply] [--json] [--store PATH]\n\
The community tripwire pack: lessons for classic agent disasters, each with the safe alternative.\n\
  rm -rf on an unset variable, git push --force, git reset --hard, git clean -fdx, pkill -f, chmod -R 777,\n\
  dd of=/dev/..., DROP TABLE, DELETE without WHERE, terraform destroy, kubectl delete, curl | sh ...\n\
`instinct guard` (the pre-tool hook) shows the one that fits before the agent runs the command. It never blocks.\n\
  --apply       bank the lessons that are not in the bank yet, as source: community (default: dry run)\n\
  --store PATH  bank file to read and write (default: INSTINCT_STORE or the usual bank)\n\
  --json        print the pack, what is new and what is already banked as JSON\n\
Idempotent: lessons already in the bank are skipped, so a second --apply banks 0.";

struct Lesson {
    pack_id: String,
    title: String,
    when: String,
    found: String,
    how: String,
    evidence: String,
    reconsider: String,
    tags: String,
}

fn pack() -> Result<Vec<Lesson>, String> {
    let root = parse_json(PACK).map_err(|e| format!("community/tripwires.json: {e}"))?;
    let Json::Arr(items) = root else {
        return Err("community/tripwires.json: expected an array".into());
    };
    let mut out = Vec::new();
    for (i, it) in items.iter().enumerate() {
        let f = |k: &str| it.get(k).and_then(Json::as_str).unwrap_or("").to_string();
        let l = Lesson {
            pack_id: f("id"),
            title: f("title"),
            when: f("when"),
            found: f("found"),
            how: f("how"),
            evidence: f("evidence"),
            reconsider: f("reconsider"),
            tags: f("tags"),
        };
        if [&l.pack_id, &l.title, &l.when, &l.found, &l.how, &l.evidence, &l.tags].iter().any(|s| s.trim().is_empty()) {
            return Err(format!("community/tripwires.json: lesson {i} is missing a field"));
        }
        out.push(l);
    }
    Ok(out)
}

fn bank_in(l: &Lesson) -> BankIn {
    BankIn {
        title: l.title.clone(),
        when: l.when.clone(),
        found: l.found.clone(),
        how: l.how.clone(),
        evidence: l.evidence.clone(),
        reconsider: l.reconsider.clone(),
        tags: l.tags.clone(),
        project: String::new(),
        persona: String::new(),
        applicability_harness: String::new(),
        applicability_version: String::new(),
        applicability_machine: None,
    }
}

/// The id the lesson has once banked: unscoped, so the same on every machine.
fn bank_id(l: &Lesson) -> Result<String, String> {
    bank_discovery(bank_in(l), &eligibility::Scope::default()).map(|d| d.id)
}

/// How many lessons the starter pack has.
pub fn total() -> Option<usize> {
    pack().ok().map(|p| p.len())
}

/// How many lessons of the pack a bank does not hold yet, given the ids of the lessons it holds.
pub fn new_in(present: &HashSet<String>) -> Result<usize, String> {
    let mut n = 0;
    for l in &pack()? {
        if !present.contains(&bank_id(l)?) {
            n += 1;
        }
    }
    Ok(n)
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let (mut apply, mut json, mut store) = (false, false, None);
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--apply" => apply = true,
            "--json" => json = true,
            "--store" => store = Some(PathBuf::from(it.next().ok_or("--store needs a path")?)),
            "--help" | "-h" => {
                println!("{STARTER_HELP}");
                return Ok(());
            }
            other => return Err(format!("starter: unknown argument {other}\n\n{STARTER_HELP}")),
        }
    }
    let explicit = store.is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
    let path = match store {
        Some(p) => Some(p),
        None => default_store().ok(),
    };
    if apply && path.is_none() {
        return Err("no home directory found: --apply needs a bank; set INSTINCT_STORE".into());
    }
    let lessons = pack()?;
    let mut present: HashSet<String> = HashSet::new();
    if let Some(p) = path.as_ref().filter(|p| p.is_file()) {
        present = load(p)?.into_iter().map(|d| d.id).collect();
    }
    let mut ids = Vec::new();
    for l in &lessons {
        ids.push(bank_id(l)?);
    }
    let new: Vec<usize> = (0..lessons.len()).filter(|&i| !present.contains(&ids[i])).collect();
    let mut banked = 0;
    if apply {
        let p = path.as_ref().expect("apply has a store");
        if !explicit {
            ensure_default_dir(p)?;
        }
        for &i in &new {
            let msg = op_bank_in(p, bank_in(&lessons[i]), "community", &eligibility::Scope::default())?;
            if msg.starts_with("banked") {
                banked += 1;
            }
        }
    }
    if json {
        let row = |i: usize| {
            let l = &lessons[i];
            format!(
                "{{\"id\":\"{}\",\"bank_id\":\"{}\",\"title\":\"{}\",\"banked\":{}}}",
                escape_json(&l.pack_id),
                escape_json(&ids[i]),
                escape_json(&l.title),
                !new.contains(&i)
            )
        };
        let all: Vec<String> = (0..lessons.len()).map(row).collect();
        println!(
            "{{\"source\":\"community\",\"pack\":{},\"new\":{},\"already_banked\":{},\"applied\":{apply},\"banked_now\":{banked},\"lessons\":[{}]}}",
            lessons.len(),
            new.len() - if apply { banked } else { 0 } + if apply { 0 } else { 0 },
            lessons.len() - new.len() + banked,
            all.join(",")
        );
        return Ok(());
    }
    println!(
        "community tripwire pack: {} lessons, {} not in your bank yet, {} already there",
        lessons.len(),
        new.len(),
        lessons.len() - new.len()
    );
    for (i, l) in lessons.iter().enumerate() {
        let mark = if apply && new.contains(&i) {
            "banked "
        } else if present.contains(&ids[i]) {
            "present"
        } else {
            "new    "
        };
        println!("  {mark}  {:<26} {}", l.pack_id, l.title);
    }
    if apply {
        println!("banked {banked} as source: community. `instinct guard` now warns before these commands.");
    } else {
        println!("Dry run. `instinct starter --apply` banks the {} new lessons.", new.len());
    }
    Ok(())
}

// ---------------------------------------------------------------- first run

/// What the user is told, once, on the call that created their bank.
pub fn first_run_notice(count: usize) -> String {
    format!(
        "Instinct created your bank with {count} starter tripwires. They warn before risky commands such as rm -rf on an empty variable and never block anything. Set INSTINCT_STARTER=0 to start empty."
    )
}

/// `INSTINCT_STARTER=0` (or `off` / `false`) keeps a new bank empty.
fn seeding_off() -> bool {
    std::env::var("INSTINCT_STARTER")
        .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "off" | "false"))
        .unwrap_or(false)
}

/// Called by the `prompt` and `guard` hooks only. When the resolved bank file does not exist yet, banks exactly
/// what `instinct starter --apply` banks (same ids, state `community`, source `community`) and returns how many
/// lessons it banked. Returns `None` when nothing was seeded: opted out, the bank already exists, or any error
/// (hooks must never fail, so every error is swallowed). A missing folder for an explicit store is not created.
/// A `<store>.seed.lock` serialises two first calls: the second waits, sees the bank, and seeds nothing.
pub fn seed_first_run(path: &PathBuf, explicit: bool) -> Option<usize> {
    if seeding_off() || path.exists() {
        return None;
    }
    let seeded = std::panic::catch_unwind(|| seed_locked(path, explicit)).ok()?;
    seeded.ok().flatten()
}

fn seed_locked(path: &PathBuf, explicit: bool) -> Result<Option<usize>, String> {
    if explicit {
        if path.parent().is_some_and(|d| !d.as_os_str().is_empty() && !d.is_dir()) {
            return Ok(None);
        }
    } else {
        ensure_default_dir(path)?;
    }
    let mut lock_path = path.as_os_str().to_owned();
    lock_path.push(".seed.lock");
    let lock_path = PathBuf::from(lock_path);
    let lock = journal::private_options()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&lock_path)
        .map_err(|e| e.to_string())?;
    lock.lock().map_err(|e| e.to_string())?;
    let mut banked = 0;
    // Re-check under the lock: the call that held it first has already created the bank.
    if !path.exists() {
        for l in &pack()? {
            if let Ok(m) = op_bank_in(path, bank_in(l), "community", &eligibility::Scope::default()) {
                if m.starts_with("banked") {
                    banked += 1;
                }
            }
        }
    }
    drop(lock);
    let _ = std::fs::remove_file(&lock_path);
    Ok((banked > 0).then_some(banked))
}

// ---------------------------------------------------------------- command tags for `instinct guard`
// The matcher itself is authored in src/tripwire.hlx; this file only reads a lesson's tags and picks.

/// A lesson that matches on the command rather than on prose.
pub fn has_cmd(d: &Discovery) -> bool {
    tripwire::has_cmd(&d.tags)
}

/// The lesson's `cmd:` matchers, trimmed and sorted; empty for a prose lesson.
pub fn cmd_specs(d: &Discovery) -> Vec<String> {
    tripwire::cmd_specs(&d.tags)
}

/// The `cmd:` matchers a banked lesson is judged by. A lesson banked from the starter pack uses the pack's
/// current tags, so a matcher fix reaches banks made by an older version (the lesson id does not change).
fn current_tags(d: &Discovery) -> &str {
    static PACK_TAGS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
    if d.meta.source != "community" {
        return &d.tags;
    }
    let tags = PACK_TAGS.get_or_init(|| {
        let mut m = HashMap::new();
        for l in pack().unwrap_or_default() {
            if let Ok(id) = bank_id(&l) {
                m.insert(id, l.tags);
            }
        }
        m
    });
    tags.get(&d.id).map_or(d.tags.as_str(), |t| t.as_str())
}

/// The best deliverable `cmd:` lesson for a `tool_bash <command>` situation, or None.
pub fn guard_pick(
    path: &PathBuf,
    situation: &str,
    scope: &eligibility::Scope,
    seen: &[String],
) -> Option<Discovery> {
    let command = situation.strip_prefix("tool_bash ")?;
    let w = tripwire::command_words(command);
    let now = now_secs();
    let all = load_scoped_for_cmd(path, scope, now).ok()?;
    let quiet = quiet_ids(path);
    let mut best: Option<(usize, usize)> = None;
    for (i, d) in all.iter().enumerate() {
        if seen.contains(&d.id)
            || eligibility::eligible(&d.meta, scope, now, None, d.hits, quiet.contains(&d.id)).is_err()
            || eligibility::quiet(d.hits, d.misses)
        {
            continue;
        }
        if let Some(n) = tripwire::best_match(current_tags(d), &w) {
            if best.is_none_or(|(_, b)| n > b) {
                best = Some((i, n));
            }
        }
    }
    best.map(|(i, _)| all[i].clone())
}


// ---------------------------------------------------------------- fixes for `instinct guard`

/// The `fix:<rule>` names a tag string carries.
fn fix_tags(tags: &str) -> Vec<String> {
    tags.split(';').filter_map(|t| t.trim().strip_prefix("fix:")).map(str::to_owned).collect()
}

/// The fix rules that are on for this bank: those whose pack lesson is in the bank and still deliverable (not
/// retracted, quiet or out of scope). A bank without the starter lessons gets no rewrites, like it gets no
/// tripwires; `instinct starter --apply` adds them.
pub fn fix_rules_on(path: &PathBuf, scope: &eligibility::Scope) -> HashSet<String> {
    let mut on = HashSet::new();
    let Ok(lessons) = pack() else { return on };
    let Ok(plain) = load_plain(path) else { return on };
    let present: HashSet<String> = plain.into_iter().map(|d| d.id).collect();
    let now = now_secs();
    let live = load_scoped_for_cmd(path, scope, now).unwrap_or_default();
    let quiet = quiet_ids(path);
    for l in lessons {
        let rules = fix_tags(&l.tags);
        let Ok(id) = bank_id(&l) else { continue };
        if rules.is_empty() || !present.contains(&id) {
            continue;
        }
        let ok = live.iter().find(|d| d.id == id).is_some_and(|d| {
            eligibility::eligible(&d.meta, scope, now, None, d.hits, quiet.contains(&d.id)).is_ok()
                && !eligibility::quiet(d.hits, d.misses)
        });
        if ok {
            on.extend(rules);
        }
    }
    on
}

/// The pack lesson id that carries a fix rule, for the "Instinct rewrote" line.
pub fn fix_lesson(rule: &str) -> String {
    pack()
        .unwrap_or_default()
        .into_iter()
        .find(|l| fix_tags(&l.tags).iter().any(|r| r == rule))
        .map(|l| l.pack_id)
        .unwrap_or_default()
}
// ---------------------------------------------------------------- for `instinct scan`

/// The pack as (id, title, tags) triples, for matching past commands against the tripwires. Empty if the pack is unreadable.
pub(crate) fn pack_matchers() -> Vec<(String, String, String)> {
    pack().map(|p| p.into_iter().map(|l| (l.pack_id, l.title, l.tags)).collect()).unwrap_or_default()
}

/// (pack size, how many of its lessons the bank at the default location already holds); `None` when there is no
/// bank file to read. Reads only: no snapshot, no folder, no write.
pub(crate) fn banked_in_default() -> Option<(usize, usize)> {
    let lessons = pack().ok()?;
    let path = default_store().ok().filter(|p| p.is_file())?;
    let present: HashSet<String> = load_plain(&path).ok()?.into_iter().map(|d| d.id).collect();
    let n = lessons.iter().filter(|l| bank_id(l).is_ok_and(|id| present.contains(&id))).count();
    Some((lessons.len(), n))
}

#[cfg(test)]
mod tests {
    use super::*;

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

    #[test]
    fn a_pack_lesson_banked_with_older_tags_is_judged_by_the_current_ones() {
        let l = pack().unwrap().into_iter().find(|l| l.pack_id == "mkfs-wipefs").unwrap();
        let mut d = bank_discovery(bank_in(&l), &eligibility::Scope::default()).unwrap();
        d.meta.source = "community".into();
        d.tags = "tool_bash;cmd:wipefs".into();
        assert_eq!(current_tags(&d), l.tags);
        assert!(tripwire::best_match(current_tags(&d), &tripwire::command_words("wipefs /dev/sdb")).is_none());
        assert!(tripwire::best_match(current_tags(&d), &tripwire::command_words("wipefs -a /dev/sdb")).is_some());
        // a lesson of the user's own, even with the same id, keeps its own tags
        d.meta.source = "banked".into();
        assert_eq!(current_tags(&d), "tool_bash;cmd:wipefs");
    }

    #[test]
    fn whole_words_in_order() {
        assert!(m("git push --force", "git push --force origin main"));
        assert!(m("git push --force", "cd x && git push origin main --force"));
        assert!(!m("git push --force", "git push --force-with-lease"));
        assert!(!m("git push --force", "git --force push"));
    }

    #[test]
    fn contains_and_negation() {
        assert!(m("rm -rf *$", "rm -rf \"$BUILD\"/*"));
        assert!(!m("rm -rf *$", "rm -rf ./target"));
        assert!(!m("rm -rf *$ !*:?", "rm -rf \"${BUILD:?}\"/*"));
        assert!(m("delete from !where", "psql -c \"DELETE FROM users\""));
        assert!(!m("delete from !where", "psql -c \"DELETE FROM users WHERE id = 1\""));
    }

    #[test]
    fn redirects_are_words() {
        assert!(m("> *.bashrc", "echo 'export A=1' >~/.bashrc"));
        assert!(!m("> *.bashrc", "echo 'export A=1' >> ~/.bashrc"));
    }

    #[test]
    fn the_pack_parses_and_every_cmd_spec_has_a_positive_token() {
        let lessons = pack().unwrap();
        assert!(lessons.len() >= 25);
        for l in lessons {
            assert!(l.tags.split(';').any(|t| t.trim().starts_with("cmd:")), "{}", l.pack_id);
        }
    }
}