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.
# Instinct tripwire matcher: does a shell command match a lesson's `cmd:` tags? Read this one file; nothing else decides.
# starter.rs and guard.rs call in. The tag text and the command are plain strings, so this unit has no dependencies.

# The command as lower-cased whole words: quotes dropped, `; | & ( )` as separators, `>` and `>>` apart.
AAA # pub fn words(command: &str) -> Vec<String>
AAC # let mut s = String::with_capacity(command.len() + 8)
AAC # let mut chars = command.chars().peekable()
CAA # while let Some(c) = chars.next()
TAC # match c {
TAC # '"' | '\'' | '`' => {}
TAC # ';' | '|' | '&' | '(' | ')' => s.push(' '),
TAC # '>' => {
CAA # if chars.peek() == Some(&'>')
AAC # chars.next()
AAC # s.push_str(" >> ")
CAC # else
AAC # s.push_str(" > ")
TTT # end
TAC # }
TAC # c => s.push(c),
TAC # }
TTT # end
TAC # s.split_whitespace().map(str::to_owned).collect()
TTT # end

# The word that runs in a segment: a leading sudo, env, xargs and the like, their options and VAR=value words are skipped. `git log` and `git grep` count as one name.
AAA # fn runner(w: &[String]) -> Option<String>
AAC # let mut i = 0
CAA # while i < w.len() && (matches!(w[i].as_str(), "sudo" | "doas" | "env" | "time" | "nohup" | "nice" | "command" | "exec" | "builtin" | "xargs") || w[i].starts_with('-') || w[i].contains('='))
CAA # if matches!(w[i].as_str(), "-u" | "-g" | "-I" | "-n" | "-P" | "-d" | "-E" | "-L")
AAC # i += 1
TTT # end
AAC # i += 1
TTT # end
AAC # let name = w.get(i)?.rsplit('/').next()?.to_lowercase()
CAA # if name == "git"
AAC # let sub = w.iter().skip(i + 1).find(|x| !x.starts_with('-'))?
TAC # return Some(["git ", sub.as_str()].concat())
TTT # end
TAC # Some(name)
TTT # end

# A segment that only reads or prints: its words are text, not a command to run. `tail --pid=...` waits on a process, so it is a command.
AAA # fn read_only(w: &[String]) -> bool
AAC # let Some(r) = runner(w) else { return false }
CAA # if r == "tail" && w.iter().any(|x| x.starts_with("--pid"))
TAC # return false
TTT # end
TAC # matches!(r.as_str(), "grep" | "egrep" | "fgrep" | "zgrep" | "rg" | "ag" | "ack" | "echo" | "printf" | "man" | "cat" | "bat" | "less" | "more" | "head" | "tail" | "wc" | "ls" | "stat" | "file" | "which" | "type" | "whereis" | "whatis" | "apropos" | "git log" | "git grep" | "git show" | "git diff" | "git blame" | "git status")
TTT # end

# A segment that runs the text it is given on stdin.
AAA # fn runs_input(w: &[String]) -> bool
AAC # let Some(r) = runner(w) else { return false }
TAC # matches!(r.as_str(), "sh" | "bash" | "zsh" | "dash" | "ksh" | "fish" | "psql" | "mysql" | "mariadb" | "sqlite3" | "sqlcmd" | "redis-cli" | "mongosh" | "pwsh" | "powershell" | "cmd" | "python" | "python3" | "node" | "perl" | "ruby")
TTT # end

# The words of a command that can do something. The command is cut into segments at `; | & ( )` and newlines outside quotes. The words of a read-only segment (grep, echo, man, cat ...) are dropped, as text, except its own `>` and `>>` redirects, unless it is piped into a shell or a SQL client. Everything else is `words`, unchanged.
AAA # pub fn command_words(command: &str) -> Vec<String>
AAC # let mut segs: Vec<(String, String, bool)> = Vec::new()
AAC # let mut raw = String::new()
AAC # let mut bare = String::new()
AAC # let mut quote = ' '
AAC # let mut prev = ' '
AAC # let mut it = command.chars()
CAA # while let Some(c) = it.next()
CAA # if quote == ' ' && matches!(c, ';' | '|' | '&' | '(' | ')' | '\n')
# A lone `&` (not `&&`, `>&`, `&>` or `|&`) sends the segment to the background: its words end with `__bg__`, and `__subbg__` too when a `)` follows, as in `(cmd &)`.
CAA # if c == '&' && prev != '&' && prev != '>' && prev != '|' && !matches!(it.as_str().chars().next(), Some('&' | '>'))
AAC # raw.push_str(" __bg__")
AAC # bare.push_str(" __bg__")
CAA # if it.as_str().trim_start().starts_with(')')
AAC # raw.push_str(" __subbg__")
AAC # bare.push_str(" __subbg__")
TTT # end
TTT # end
AAC # segs.push((raw.clone(), bare.clone(), c == '|' && prev != '|' && it.as_str().chars().next() != Some('|')))
AAC # raw.clear()
AAC # bare.clear()
AAC # prev = c
GAG # continue
TTT # end
AAC # prev = c
CAA # if c == '\\' && quote != '\''
AAC # raw.push(c)
AAC # bare.push(c)
CAA # if let Some(n) = it.next()
AAC # raw.push(n)
AAC # bare.push(n)
TTT # end
GAG # continue
TTT # end
CAA # if quote != ' '
AAC # raw.push(c)
AAC # bare.push(if c == '>' { '_' } else { c })
CAA # if c == quote
AAC # quote = ' '
TTT # end
GAG # continue
TTT # end
CAA # if c == '"' || c == '\'' || c == '`'
AAC # quote = c
TTT # end
AAC # raw.push(c)
AAC # bare.push(c)
TTT # end
AAC # segs.push((raw, bare, false))
AAC # let mut out: Vec<String> = Vec::new()
AGA # for i in 0..segs.len()
AAC # let w = words(&segs[i].0)
CAA # if w.is_empty()
GAG # continue
TTT # end
CAA # if read_only(&w) && !w.iter().any(|x| x == "__bg__") && !(segs[i].2 && segs.get(i + 1).is_some_and(|s| runs_input(&words(&s.0))))
AAC # let b = words(&segs[i].1)
AGA # for j in 0..b.len()
CAA # if b[j] == ">" || b[j] == ">>"
AAC # out.push(b[j].clone())
CAA # if let Some(t) = b.get(j + 1)
AAC # out.push(t.clone())
TTT # end
TTT # end
TTT # end
GAG # continue
TTT # end
AAC # out.extend(w)
TTT # end
TAC # out
TTT # end

# An `=` token is a whole word compared without case; `a|b` lists alternatives. `?` stands for one path segment (no / \ or *), and a word may end in / or \. `^` ends a word that may be cut short, so `-r^ecurse` is `-r`, `-rec` or `-recurse`. An alternative that starts with `*` is a contained text (`*:\` is any drive path). One that ends with `+` is a prefix followed by at least one more character, with no glob in its first segment and no `$` in it (`$home/+` is `$HOME/code`, not `$HOME/*` or `$HOME/$X`). An alternative that starts with `!` vetoes the word: `=*$|!$home/+` is a word with a `$` that is not a HOME subpath.
AAA # fn alt_hits(pat: &str, word: &str) -> bool
AAC # let w = word.trim_end_matches(['/', '\\']).to_lowercase()
AAC # let p = pat.to_lowercase()
CAA # if let Some(sub) = p.strip_prefix('*')
TAC # return !sub.is_empty() && word.to_lowercase().contains(sub)
TTT # end
CAA # if let Some(head) = p.strip_suffix('+')
CAA # if let Some(rest) = w.strip_prefix(head)
AAC # let seg = rest.split(['/', '\\']).next().unwrap_or("")
TAC # return !rest.is_empty() && !seg.contains(['*', '?', '[']) && !rest.contains('$')
TTT # end
TAC # return false
TTT # end
CAA # if let Some((head, rest)) = p.split_once('^')
TAC # return w.starts_with(head) && [head, rest].concat().starts_with(w.as_str())
TTT # end
CAA # if let Some((a, b)) = p.split_once('?')
CAA # if w.len() <= a.len() + b.len() || !w.starts_with(a) || !w.ends_with(b)
TAC # return false
TTT # end
AAC # let mid = &w[a.len()..w.len() - b.len()]
TAC # return !mid.contains(['/', '\\', '*'])
TTT # end
TAC # w == p
TTT # end

# Flags and paths compare exactly (`-D` is not `-d`); a token of letters only (a keyword such as `where` or `flushall`) ignores case, and so does `*text` unless it starts with `-`. A token starting with `=` is a case-blind word pattern, see alt_hits.
AAA # fn token_hits(tok: &str, word: &str) -> bool
CAA # if let Some(p) = tok.strip_prefix('=')
TAC # return p.split('|').all(|a| a.strip_prefix('!').is_none_or(|n| n.is_empty() || !alt_hits(n, word))) && p.split('|').any(|a| !a.is_empty() && !a.starts_with('!') && alt_hits(a, word))
TTT # end
TAC # match tok.strip_prefix('*') {
TAC # Some("") => word == "*",
TAC # Some(sub) => word.contains(sub) || (!sub.starts_with('-') && word.to_lowercase().contains(&sub.to_lowercase())),
TAC # None => word == tok || (tok.chars().all(|c| c.is_ascii_alphabetic()) && word.eq_ignore_ascii_case(tok)),
TAC # }
TTT # end

# Number of positive tokens when the spec matches the words in order, else None. `!tok` must match no word at all; `<tok` must match none of the words skipped before the next positive token.
AAA # pub fn spec_matches(spec: &str, words: &[String]) -> Option<usize>
AAC # let mut at = 0
AAC # let mut positive = 0
AAC # let mut gap: Vec<&str> = Vec::new()
AGA # for tok in spec.split_whitespace()
CAA # if let Some(g) = tok.strip_prefix('<')
AAC # gap.push(g)
GAG # continue
TTT # end
CAA # if let Some(neg) = tok.strip_prefix('!')
CAA # if words.iter().any(|w| token_hits(neg, w))
AAC # return None
TTT # end
GAG # continue
TTT # end
AAC # let found = words.iter().skip(at).position(|w| token_hits(tok, w))?
CAA # if words[at..at + found].iter().any(|w| gap.iter().any(|g| token_hits(g, w)))
AAC # return None
TTT # end
AAC # gap.clear()
AAC # at += found + 1
AAC # positive += 1
TTT # end
TAC # (positive > 0).then_some(positive)
TTT # end

# The spec of a `cmd:` tag (prefix matched without case, not trimmed), else None.
AAA # fn tag_spec(tag: &str) -> Option<&str>
TAC # tag.get(..4).filter(|p| p.eq_ignore_ascii_case("cmd:")).map(|_| &tag[4..])
TTT # end

# Whether a lesson's `;`-separated tags carry a `cmd:` matcher.
AAA # pub fn has_cmd(tags: &str) -> bool
TAC # tags.split(';').any(|t| t.trim().to_lowercase().starts_with("cmd:"))
TTT # end

# The `cmd:` matchers of a lesson, trimmed and sorted; empty for a prose lesson.
AAA # pub fn cmd_specs(tags: &str) -> Vec<String>
AAC # let mut v: Vec<String> = tags.split(';').map(str::trim).filter(|t| t.to_lowercase().starts_with("cmd:")).map(str::to_owned).collect()
AAC # v.sort()
TAC # v
TTT # end

# The most positive tokens any `cmd:` tag of the lesson matches in the words, else None.
AAA # pub fn best_match(tags: &str, words: &[String]) -> Option<usize>
AAC # let mut best: Option<usize> = None
AGA # for t in tags.split(';')
AAC # let Some(spec) = tag_spec(t.trim()) else { continue }
CAA # if let Some(n) = spec_matches(spec, words)
CAA # if best.is_none_or(|b| n > b)
AAC # best = Some(n)
TTT # end
TTT # end
TTT # end
TAC # best
TTT # end