pub const LOOP_DEADLINE_SECS: u32 = 600;
#[derive(Debug, PartialEq, Clone)]
pub struct Applied {
pub rule: &'static str,
pub why: &'static str,
}
pub const RULES: &[(&str, &str, &str)] = &[
("guard-var", "rm-unset-var", "an empty variable would delete the wrong path; the guard aborts instead"),
("force-lease", "git-push-force", "--force-with-lease refuses to overwrite commits you have not seen"),
("pgrep-A", "wait-no-deadline", "pgrep -f in a loop matches the loop's own command line; -A ignores ancestors"),
("loop-timeout", "wait-no-deadline", "a poll loop with no deadline can run forever; timeout 600 ends it"),
];
pub fn enabled() -> bool {
!matches!(
std::env::var("INSTINCT_FIX").as_deref(),
Ok("0") | Ok("off") | Ok("false") | Ok("no")
)
}
#[derive(Debug, Clone)]
struct Word {
start: usize,
end: usize,
plain: bool,
}
struct Seg {
words: Vec<Word>,
}
fn split(cmd: &str) -> Option<Vec<Seg>> {
let b = cmd.as_bytes();
let mut segs: Vec<Seg> = vec![Seg { words: vec![] }];
let mut i = 0;
let mut cur: Option<Word> = None;
macro_rules! flush {
() => {
if let Some(w) = cur.take() {
segs.last_mut().unwrap().words.push(w);
}
};
}
while i < b.len() {
let c = b[i];
match c {
b' ' | b'\t' => {
flush!();
i += 1;
}
b'\n' | b';' | b'|' | b'&' | b'(' | b')' => {
flush!();
if segs.last().is_some_and(|s| !s.words.is_empty()) {
segs.push(Seg { words: vec![] });
}
i += 1;
}
b'#' if cur.is_none() => {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
}
b'`' => return None,
b'<' if b.get(i + 1) == Some(&b'<') => return None,
_ => {
let w = cur.get_or_insert(Word { start: i, end: i, plain: true });
match c {
b'\\' => {
w.plain = false;
i += 2;
}
b'\'' => {
w.plain = false;
i += 1;
while i < b.len() && b[i] != b'\'' {
i += 1;
}
if i >= b.len() {
return None;
}
i += 1;
}
b'"' => {
w.plain = false;
i += 1;
while i < b.len() && b[i] != b'"' {
if b[i] == b'\\' {
i += 1;
} else if b[i] == b'`' {
return None;
}
i += 1;
}
if i >= b.len() {
return None;
}
i += 1;
}
b'$' if b.get(i + 1) == Some(&b'(') && b.get(i + 2) == Some(&b'(') => {
w.plain = false;
let mut depth = 0usize;
i += 1;
loop {
match b.get(i) {
None => return None,
Some(b'(') => depth += 1,
Some(b')') => {
depth -= 1;
if depth == 0 {
i += 1;
break;
}
}
Some(_) => {}
}
i += 1;
}
}
_ => i += 1,
}
if i > b.len() {
return None;
}
if let Some(w) = cur.as_mut() {
w.end = i.min(b.len());
}
}
}
}
flush!();
segs.retain(|s| !s.words.is_empty());
Some(segs)
}
fn text<'a>(cmd: &'a str, w: &Word) -> &'a str {
&cmd[w.start..w.end]
}
const KEYWORDS: &[&str] = &["!", "command", "nohup", "if", "then", "do", "else", "elif", "while", "until", "{", "time"];
fn command_index(cmd: &str, s: &Seg) -> Option<usize> {
let mut i = 0;
while i < s.words.len() {
let t = text(cmd, &s.words[i]);
let assign = t
.split_once('=')
.is_some_and(|(n, _)| !n.is_empty() && n.chars().enumerate().all(|(k, c)| c == '_' || c.is_ascii_alphabetic() || (k > 0 && c.is_ascii_digit())));
if KEYWORDS.contains(&t) || assign || t == "sudo" {
i += 1;
} else {
return Some(i);
}
}
None
}
fn is_loop_open(cmd: &str, s: &Seg) -> bool {
matches!(text(cmd, &s.words[0]), "until" | "while" | "for" | "select")
}
fn is_done(cmd: &str, s: &Seg) -> bool {
text(cmd, &s.words[0]) == "done"
}
#[derive(Debug)]
struct Edit {
start: usize,
end: usize,
with: String,
}
fn apply(cmd: &str, mut edits: Vec<Edit>) -> String {
edits.sort_by_key(|e| e.start);
let mut out = String::with_capacity(cmd.len() + 16);
let mut at = 0;
for e in edits {
out.push_str(&cmd[at..e.start]);
out.push_str(&e.with);
at = e.end;
}
out.push_str(&cmd[at..]);
out
}
fn is_name(n: &str) -> bool {
let mut ch = n.chars();
ch.next().is_some_and(|c| c == '_' || c.is_ascii_alphabetic()) && ch.all(|c| c == '_' || c.is_ascii_alphanumeric())
}
fn guard_word(t: &str) -> Option<String> {
if t.contains('\\') {
return None;
}
let b = t.as_bytes();
let mut out = String::with_capacity(t.len() + 8);
let (mut i, mut dq, mut changed) = (0, false, false);
while i < b.len() {
match b[i] {
b'\'' if !dq => {
let close = t[i + 1..].find('\'')? + i + 1;
out.push_str(&t[i..=close]);
i = close + 1;
}
b'"' => {
dq = !dq;
out.push('"');
i += 1;
}
b'$' => {
let rest = &t[i + 1..];
let (name, len) = if let Some(inner) = rest.strip_prefix('{') {
match inner.find('}') {
Some(c) if is_name(&inner[..c]) => (Some(&inner[..c]), c + 2),
_ => (None, 0),
}
} else {
let n = rest.find(|c: char| !(c == '_' || c.is_ascii_alphanumeric())).unwrap_or(rest.len());
(Some(&rest[..n]).filter(|n| is_name(n)), n)
};
match name {
Some(n) if n != "HOME" => {
if dq {
out.push_str(&format!("${{{n}:?}}"));
} else {
out.push_str(&format!("\"${{{n}:?}}\""));
}
changed = true;
i += 1 + len;
}
Some(_) => {
out.push_str(&t[i..i + 1 + len]);
i += 1 + len;
}
None => {
out.push('$');
i += 1;
}
}
}
_ => {
let c = t[i..].chars().next()?;
out.push(c);
i += c.len_utf8();
}
}
}
(changed && !dq).then_some(out)
}
fn rm_recursive_force(cmd: &str, s: &Seg, from: usize) -> bool {
let (mut r, mut f) = (false, false);
for w in &s.words[from..] {
let t = text(cmd, w);
if t == "--" {
break;
}
match t {
"--recursive" => r = true,
"--force" => f = true,
_ => {
if w.plain && t.starts_with('-') && !t.starts_with("--") {
r |= t.contains('r') || t.contains('R');
f |= t.contains('f');
}
}
}
}
r && f
}
fn rule_guard_var(cmd: &str, segs: &[Seg]) -> Option<Vec<Edit>> {
let mut edits = Vec::new();
for s in segs {
let Some(ci) = command_index(cmd, s) else { continue };
if !matches!(text(cmd, &s.words[ci]), "rm" | "/bin/rm" | "/usr/bin/rm") || !rm_recursive_force(cmd, s, ci + 1) {
continue;
}
for w in &s.words[ci + 1..] {
let t = text(cmd, w);
if t.starts_with('-') {
continue;
}
if let Some(new) = guard_word(t) {
edits.push(Edit { start: w.start, end: w.end, with: new });
}
}
}
(!edits.is_empty()).then_some(edits)
}
fn rule_force_lease(cmd: &str, segs: &[Seg]) -> Option<Vec<Edit>> {
let mut edits = Vec::new();
for s in segs {
let Some(ci) = command_index(cmd, s) else { continue };
if text(cmd, &s.words[ci]) != "git" {
continue;
}
let mut i = ci + 1;
while i < s.words.len() {
let t = text(cmd, &s.words[i]);
if matches!(t, "-C" | "-c") {
i += 2;
} else if t.starts_with('-') {
i += 1;
} else {
break;
}
}
if i >= s.words.len() || text(cmd, &s.words[i]) != "push" {
continue;
}
let rest = &s.words[i + 1..];
if rest.iter().any(|w| {
let t = text(cmd, w);
t.starts_with("--force-with-lease") || t.starts_with("--force-if-includes")
}) {
continue;
}
for w in rest {
let t = text(cmd, w);
if t == "--" {
break;
}
if w.plain && (t == "--force" || t == "-f") {
edits.push(Edit { start: w.start, end: w.end, with: "--force-with-lease".into() });
}
}
}
(!edits.is_empty()).then_some(edits)
}
fn rule_pgrep_a(cmd: &str, segs: &[Seg]) -> Option<Vec<Edit>> {
let mut edits = Vec::new();
let mut depth = 0usize;
let mut depth_seen = false;
for s in segs {
if is_done(cmd, s) {
depth = depth.saturating_sub(1);
continue;
}
if is_loop_open(cmd, s) {
depth += 1;
depth_seen = true;
}
if depth == 0 {
continue;
}
let Some(ci) = command_index(cmd, s) else { continue };
let name = text(cmd, &s.words[ci]);
if name != "pgrep" && name != "pkill" {
continue;
}
let flags: Vec<&str> = s.words[ci + 1..]
.iter()
.filter(|w| w.plain)
.map(|w| text(cmd, w))
.filter(|t| t.starts_with('-') && !t.starts_with("--") && t.len() > 1)
.collect();
let has_f = flags.iter().any(|t| t.contains('f'));
let has_a = flags.iter().any(|t| t.contains('A')) || s.words[ci + 1..].iter().any(|w| text(cmd, w) == "--ignore-ancestors");
if has_f && !has_a {
let w = &s.words[ci];
edits.push(Edit { start: w.end, end: w.end, with: " -A".into() });
}
}
if depth_seen {
let mut from = 0;
while let Some(p) = cmd[from..].find("$(") {
let at = from + p + 2;
from = at;
let rest = &cmd[at..];
let name = ["pgrep", "pkill"].iter().find(|n| rest.starts_with(**n) && rest[n.len()..].starts_with(' '));
let Some(name) = name else { continue };
let end = at + name.len();
let args: Vec<&str> = cmd[end..].split(|c: char| c == ')' || c == ';' || c == '|' || c == '&').next().unwrap_or("").split_whitespace().collect();
let flags: Vec<&&str> = args.iter().take_while(|t| t.starts_with('-')).collect();
let has_f = flags.iter().any(|t| !t.starts_with("--") && t.contains('f'));
let has_a = flags.iter().any(|t| t.contains('A') || **t == "--ignore-ancestors");
if has_f && !has_a && !edits.iter().any(|e: &Edit| e.start == end) {
edits.push(Edit { start: end, end, with: " -A".into() });
}
}
}
(!edits.is_empty()).then_some(edits)
}
fn has_deadline(cmd: &str, segs: &[Seg]) -> bool {
if cmd.contains("$((") || cmd.contains("((") {
return true;
}
const OUT: &[&str] = &["timeout", "SECONDS", "date", "break", "exit", "return", "seq", "let", "expr", "RANDOM"];
if cmd
.split(|c: char| !(c == '_' || c.is_ascii_alphanumeric()))
.any(|t| OUT.contains(&t))
{
return true;
}
segs.iter().flat_map(|s| s.words.iter()).any(|w| {
let t = text(cmd, w);
t.split_once('=').is_some_and(|(n, _)| is_name(n))
})
}
fn quote_single(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
fn rule_loop_timeout(cmd: &str, segs: &[Seg]) -> Option<String> {
let first = segs.first()?;
let last = segs.last()?;
if !matches!(text(cmd, &first.words[0]), "until" | "while") || !is_done(cmd, last) || last.words.len() != 1 {
return None;
}
let trimmed = cmd.trim();
let body = trimmed.strip_suffix(';').unwrap_or(trimmed).trim_end();
if !body.ends_with("done") {
return None;
}
let mut depth = 0usize;
for (k, s) in segs.iter().enumerate() {
if is_loop_open(cmd, s) {
depth += 1;
} else if is_done(cmd, s) {
depth = depth.checked_sub(1)?;
if depth == 0 && k + 1 != segs.len() {
return None;
}
} else if depth == 0 {
return None;
}
}
if depth != 0 || has_deadline(cmd, segs) {
return None;
}
let sleeps = segs.iter().any(|s| command_index(cmd, s).is_some_and(|i| text(cmd, &s.words[i]) == "sleep"));
if !sleeps {
return None;
}
Some(format!("timeout {LOOP_DEADLINE_SECS} bash -c {}", quote_single(trimmed)))
}
pub fn rewrite(cmd: &str, on: &dyn Fn(&str) -> bool) -> Option<(String, Vec<Applied>)> {
let mut cur = cmd.to_string();
let mut fired: Vec<Applied> = Vec::new();
type EditRule = fn(&str, &[Seg]) -> Option<Vec<Edit>>;
let edit_rules: [(&'static str, EditRule); 3] = [
("guard-var", rule_guard_var),
("force-lease", rule_force_lease),
("pgrep-A", rule_pgrep_a),
];
for (name, f) in edit_rules {
if !on(name) {
continue;
}
let segs = split(&cur)?;
if let Some(edits) = f(&cur, &segs) {
cur = apply(&cur, edits);
fired.push(applied(name));
}
}
if on("loop-timeout") && !fired.iter().any(|a| a.rule == "pgrep-A") {
let segs = split(&cur)?;
if let Some(w) = rule_loop_timeout(&cur, &segs) {
cur = w;
fired.push(applied("loop-timeout"));
}
}
(!fired.is_empty() && cur != cmd).then_some((cur, fired))
}
fn applied(rule: &str) -> Applied {
let (r, _, why) = RULES.iter().find(|(r, _, _)| *r == rule).expect("known rule");
Applied { rule: r, why }
}
pub fn note(old: &str, new: &str, fired: &[Applied], lesson_id: &str) -> String {
let why = fired.iter().map(|a| format!("{}: {}", a.rule, a.why)).collect::<Vec<_>>().join("; ");
format!("Instinct rewrote: {} -> {} (lesson {lesson_id}: {why})", one_line(old), one_line(new))
}
fn one_line(s: &str) -> String {
let t = s.split_whitespace().collect::<Vec<_>>().join(" ");
if t.chars().count() > 200 {
format!("{}...", t.chars().take(200).collect::<String>())
} else {
t
}
}
pub const FIX_HELP: &str = "usage: instinct fix --dry-run COMMAND\n\
Shows what `instinct guard` would rewrite before COMMAND runs (nothing is executed or changed).\n\
Rules: rm -rf $VAR/x -> \"${VAR:?}\"/x, git push --force -> --force-with-lease, pgrep -f in a loop -> -A,\n\
a deadline-less until/while sleep loop -> timeout 600 bash -c '...'.\n\
Off for the hook with INSTINCT_FIX=0. The dry run shows the starter rules whatever INSTINCT_FIX says.";
pub fn run(argv: &[String]) -> Result<(), String> {
let mut dry = false;
let mut rest: Vec<&str> = Vec::new();
for a in argv {
match a.as_str() {
"--help" | "-h" => {
println!("{FIX_HELP}");
return Ok(());
}
"--dry-run" if rest.is_empty() => dry = true,
other => rest.push(other),
}
}
if !dry || rest.is_empty() {
return Err(format!("fix: needs --dry-run COMMAND\n\n{FIX_HELP}"));
}
let cmd = rest.join(" ");
let on = super::default_store().ok().filter(|p| p.is_file()).map(|p| super::starter::fix_rules_on(&p, &super::eligibility::Scope::default()));
let none_yet = on.is_none();
match rewrite(&cmd, &|r| on.as_ref().is_none_or(|s| s.contains(r))) {
Some((new, fired)) => {
println!("rewrite: {new}");
for a in fired {
println!(" {}: {}", a.rule, a.why);
}
}
None => println!("no change: {cmd}"),
}
if none_yet {
println!("note: no bank yet, so this shows the starter pack's rules; the hook rewrites once `instinct starter --apply` has banked them");
}
if !enabled() {
println!("note: INSTINCT_FIX=0 is set, so the hook would leave this command alone");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn all(_: &str) -> bool {
true
}
fn fix(c: &str) -> String {
rewrite(c, &all).map(|r| r.0).unwrap_or_else(|| c.to_string())
}
#[test]
fn guards_unset_variable_in_rm() {
assert_eq!(fix("rm -rf $BUILD/out"), "rm -rf \"${BUILD:?}\"/out");
assert_eq!(fix("rm -rf ${BUILD}/out/*"), "rm -rf \"${BUILD:?}\"/out/*");
assert_eq!(fix("cd x && rm -fr $D"), "cd x && rm -fr \"${D:?}\"");
assert_eq!(fix("sudo rm -r -f $D/a"), "sudo rm -r -f \"${D:?}\"/a");
}
#[test]
fn rm_leaves_safe_forms() {
for c in [
"rm -rf \"${BUILD:?}\"/out",
"rm -rf ./build",
"rm -r $BUILD/out",
"rm -rf $HOME/.cache/x",
"echo rm -rf $BUILD/out",
"echo 'rm -rf $BUILD/out'",
"bash -c 'rm -rf $BUILD/out'",
"# rm -rf $BUILD/out",
"xargs rm -rf $BUILD",
"rm -rf ${BUILD:-x}/y",
] {
assert_eq!(fix(c), c, "{c}");
}
}
#[test]
fn variables_after_a_prefix_quoted_and_braced_are_guarded() {
assert_eq!(fix("rm -rf ~/$DIR"), "rm -rf ~/\"${DIR:?}\"");
assert_eq!(fix("rm -rf /tmp/$DIR/cache"), "rm -rf /tmp/\"${DIR:?}\"/cache");
assert_eq!(fix("rm -rf \"$BUILD\"/out"), "rm -rf \"${BUILD:?}\"/out");
assert_eq!(fix("rm -rf \"$BUILD/out\""), "rm -rf \"${BUILD:?}/out\"");
assert_eq!(fix("rm -rf \"${BUILD}\"/out"), "rm -rf \"${BUILD:?}\"/out");
assert_eq!(fix("rm -rf $A/x $B/y"), "rm -rf \"${A:?}\"/x \"${B:?}\"/y");
assert_eq!(fix("rm -r -f -- $A"), "rm -r -f -- \"${A:?}\"");
assert_eq!(fix("rm --recursive --force $A/x"), "rm --recursive --force \"${A:?}\"/x");
assert_eq!(fix("rm -rf $BUILD.bak"), "rm -rf \"${BUILD:?}\".bak");
assert_eq!(fix("rm -rf \"$HOME/$SUB\""), "rm -rf \"$HOME/${SUB:?}\"");
for c in ["rm -rf $HOME", "rm -rf \"$HOME\"/x", "rm -rf '$X'/y", "rm -rf $1/x", "rm -f $X/y", "rm -rf \"${X:?}\"", "rm -rf \"${X:-/tmp/z}\""] {
assert_eq!(fix(c), c, "{c}");
}
}
#[test]
fn pgrep_loop_shapes() {
for (c, want) in [
("until ! pgrep -f \"my pat\"; do sleep 5; done", "until ! pgrep -A -f \"my pat\"; do sleep 5; done"),
("while pgrep -f foo >/dev/null 2>&1; do sleep 2; done", "while pgrep -A -f foo >/dev/null 2>&1; do sleep 2; done"),
("while pgrep -fa foo; do sleep 2; done", "while pgrep -A -fa foo; do sleep 2; done"),
("while pkill -0 -f foo; do sleep 1; done", "while pkill -A -0 -f foo; do sleep 1; done"),
("until pgrep -f done-marker > /dev/null; do sleep 1; done; echo ok", "until pgrep -A -f done-marker > /dev/null; do sleep 1; done; echo ok"),
("cd /x && while pgrep -f foo; do sleep 3; done", "cd /x && while pgrep -A -f foo; do sleep 3; done"),
("while [ -n \"$(pgrep -f foo)\" ]; do sleep 1; done", "while [ -n \"$(pgrep -A -f foo)\" ]; do sleep 1; done"),
] {
assert_eq!(fix(c), want, "{c}");
}
}
#[test]
fn force_push_becomes_lease() {
assert_eq!(fix("git push --force origin main"), "git push --force-with-lease origin main");
assert_eq!(fix("git push origin main -f"), "git push origin main --force-with-lease");
assert_eq!(fix("git -C repo push -f"), "git -C repo push --force-with-lease");
for c in [
"git push --force-with-lease",
"git push origin main",
"git push -fu origin x",
"echo \"git push --force\"",
"git log -f",
"git commit -f",
] {
assert_eq!(fix(c), c, "{c}");
}
}
#[test]
fn pgrep_f_gets_a_anywhere_in_a_counter_bounded_loop() {
assert_eq!(
fix("n=0; while [ $n -lt 60 ]; do pgrep -f \"cargo test\" >/dev/null && break; sleep 5; n=$((n+1)); done"),
"n=0; while [ $n -lt 60 ]; do pgrep -A -f \"cargo test\" >/dev/null && break; sleep 5; n=$((n+1)); done"
);
assert_eq!(
fix("i=0; until [ $i -ge 30 ]; do if pgrep -f foo >/dev/null; then sleep 2; else break; fi; i=$((i+1)); done"),
"i=0; until [ $i -ge 30 ]; do if pgrep -A -f foo >/dev/null; then sleep 2; else break; fi; i=$((i+1)); done"
);
assert_eq!(
fix("for i in 1 2 3; do echo wait; pkill -0 -f foo || break; sleep 1; done"),
"for i in 1 2 3; do echo wait; pkill -A -0 -f foo || break; sleep 1; done"
);
assert_eq!(
fix("n=0; while [ $n -lt 9 ]; do ! pgrep -f foo > /dev/null && break; sleep 1; n=$((n+1)); done"),
"n=0; while [ $n -lt 9 ]; do ! pgrep -A -f foo > /dev/null && break; sleep 1; n=$((n+1)); done"
);
assert_eq!(fix("pgrep -f foo"), "pgrep -f foo");
assert_eq!(
fix("pgrep -f foo; n=0; while [ $n -lt 3 ]; do sleep 1; n=$((n+1)); done; pgrep -f bar"),
"pgrep -f foo; n=0; while [ $n -lt 3 ]; do sleep 1; n=$((n+1)); done; pgrep -f bar"
);
}
#[test]
fn pgrep_in_loop_gets_a() {
assert_eq!(
fix("until ! pgrep -f foo; do sleep 1; i=1; done"),
"until ! pgrep -A -f foo; do sleep 1; i=1; done"
);
assert_eq!(fix("pgrep -f foo"), "pgrep -f foo");
assert_eq!(fix("while pgrep -A -f x; do sleep 1; i=2; done"), "while pgrep -A -f x; do sleep 1; i=2; done");
}
#[test]
fn deadline_less_loop_is_wrapped() {
assert_eq!(
fix("until [ -f /tmp/x ]; do sleep 2; done"),
"timeout 600 bash -c 'until [ -f /tmp/x ]; do sleep 2; done'"
);
assert_eq!(
fix("until ! pgrep -f foo; do sleep 1; done"),
"until ! pgrep -A -f foo; do sleep 1; done"
);
assert_eq!(
fix("while true; do echo 'hi'; sleep 1; done"),
"timeout 600 bash -c 'while true; do echo '\\''hi'\\''; sleep 1; done'"
);
for c in [
"until [ -f /tmp/x ]; do sleep 2; n=$((n+1)); done",
"timeout 60 bash -c 'until [ -f x ]; do sleep 1; done'",
"cd x && until [ -f y ]; do sleep 1; done",
"until [ -f y ]; do sleep 1; done; echo ok",
"until [ -f y ]; do sleep 1; done &",
"while read l; do echo $l; done < f",
"until [ -f y ]; do sleep 1; [ $SECONDS -gt 9 ] && break; done",
] {
assert_eq!(fix(c), c, "{c}");
}
}
#[test]
fn unparseable_is_untouched() {
for c in ["rm -rf $X/y 'unclosed", "rm -rf $X/y `date`", "cat <<EOF\nrm -rf $X/y\nEOF", "rm -rf $(echo $X)/y"] {
assert_eq!(fix(c), c, "{c}");
}
}
#[test]
fn rules_can_be_switched_off() {
let only_push = |r: &str| r == "force-lease";
assert!(rewrite("rm -rf $X/y", &only_push).is_none());
assert!(rewrite("git push -f", &only_push).is_some());
}
}