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,
}
}
fn bank_id(l: &Lesson) -> Result<String, String> {
bank_discovery(bank_in(l), &eligibility::Scope::default()).map(|d| d.id)
}
pub fn total() -> Option<usize> {
pack().ok().map(|p| p.len())
}
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(())
}
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."
)
}
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)
}
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;
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))
}
pub fn has_cmd(d: &Discovery) -> bool {
tripwire::has_cmd(&d.tags)
}
pub fn cmd_specs(d: &Discovery) -> Vec<String> {
tripwire::cmd_specs(&d.tags)
}
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())
}
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())
}
pub(crate) fn pack_matchers() -> Vec<(String, String)> {
pack().map(|p| p.into_iter().map(|l| (l.title, l.tags)).collect()).unwrap_or_default()
}
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());
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);
}
}
}