instinct-cli 0.3.10

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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! `instinct starter`: the community tripwire pack. Every lesson fires on dangerous commands through
//! `instinct guard` with Claude Code shaped payloads, safe neighbours stay silent, 200 everyday commands
//! produce no warning, and `--apply` is idempotent.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_instinct")
}

fn store(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("instinct-starter-{}-{}-{name}", std::process::id(), uniq()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("bank.hxdb")
}

fn instinct(store: &PathBuf, args: &[&str]) -> (i32, String) {
    let o = Command::new(bin())
        .args(args)
        .env("INSTINCT_STORE", store)
        .env("HOME", store.parent().unwrap())
        .env_remove("XDG_DATA_HOME")
        .output()
        .unwrap();
    (o.status.code().unwrap_or(-1), String::from_utf8_lossy(&o.stdout).into_owned())
}

fn applied(name: &str) -> PathBuf {
    let s = store(name);
    let (code, out) = instinct(&s, &["starter", "--apply"]);
    assert_eq!(code, 0, "{out}");
    s
}

fn esc(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The warning `instinct guard` prints for a Claude Code PreToolUse payload (empty when silent).
fn guard(store: &PathBuf, command: &str) -> String {
    let payload = format!(
        "{{\"cwd\":\"/home/dev/app\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{}\"}}}}",
        esc(command)
    );
    let mut child = Command::new(bin())
        .arg("guard")
        .env("INSTINCT_STORE", store)
        .env("HOME", store.parent().unwrap())
        .env_remove("XDG_DATA_HOME")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(payload.as_bytes()).ok();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success() && out.stderr.is_empty(), "guard failed on {command}");
    String::from_utf8(out.stdout).unwrap()
}

/// (pack id, dangerous commands). Every lesson in the pack needs at least two.
const DANGEROUS: &[(&str, &[&str])] = &[
    ("rm-unset-var", &["rm -rf \"$BUILD_DIR\"/*", "rm -rf $PREFIX/lib", "cd /srv && rm -fr \"$TMP\"/", "rm -rf $HOME/x $OTHER/*", "rm -rf $HOME/x && rm -rf $DIR/", "rm -rf $HOME/$SUB"]),
    ("rm-root-home-glob", &["rm -rf /", "rm -rf ~/", "rm -rf ./*", "rm -rf *"]),
    ("sudo-rm", &["sudo rm -rf /var/lib/docker", "sudo rm /etc/apt/sources.list.d/old.list"]),
    ("git-push-force", &["git push --force origin main", "git push -f", "git fetch && git push origin feature --force"]),
    ("git-reset-hard", &["git reset --hard HEAD~3", "git reset --hard origin/main"]),
    ("git-discard-all", &["git checkout .", "git restore .", "git checkout -- ."]),
    ("git-clean-force", &["git clean -fdx", "git clean -fd", "git clean -xfd"]),
    ("git-branch-force-delete", &["git branch -D feature/old", "git branch -D wip && git branch"]),
    ("git-push-delete", &["git push origin --delete old-branch", "git push -d origin v1.0"]),
    ("git-stash-drop", &["git stash drop", "git stash clear"]),
    ("git-history-rewrite", &["git reflog expire --expire=now --all", "git gc --prune=now", "git filter-branch --tree-filter 'rm -f secrets.txt' HEAD"]),
    ("git-add-secrets", &["git add .env", "git add -f dist/", "git add certs/server.pem"]),
    ("wait-no-deadline", &["until [ -f /tmp/done ]; do sleep 2; done", "while sleep 5; do echo waiting; done"]),
    ("pkill-killall", &["pkill -f server", "killall node", "pkill -f \"python app.py\""]),
    ("kill-all-pids", &["kill -9 -1", "kill -KILL -1"]),
    ("chmod-777", &["chmod -R 777 /var/www", "chmod 777 deploy.sh"]),
    ("chown-recursive-system", &["sudo chown -R $USER /usr/local", "chown -R root:root /", "chown -R www-data /var"]),
    ("dd-device", &["dd if=debian.iso of=/dev/sdb bs=4M", "dd if=/dev/zero of=/dev/nvme0n1", "cat disk.img > /dev/sdb"]),
    (
        "mkfs-wipefs",
        &["mkfs.ext4 /dev/sdb1", "sudo mkfs -t xfs /dev/sdc", "wipefs -a /dev/sdb", "sudo mkfs.ext4 /dev/sdb1", "wipefs --all /dev/sdb", "wipefs -o 0x438 /dev/sdb", "cd /tmp && sudo env LC_ALL=C mkfs.vfat /dev/sdd1"],
    ),
    ("sql-drop", &["psql -c \"DROP TABLE users\"", "mysql -e 'drop database app'"]),
    ("sql-truncate", &["psql -c \"TRUNCATE TABLE orders\"", "mysql -e \"truncate orders\""]),
    ("sql-delete-no-where", &["psql -c \"DELETE FROM sessions\"", "sqlite3 app.db \"delete from users;\""]),
    ("sql-update-no-where", &["psql -c \"UPDATE users SET active = false\"", "mysql -e \"update orders set status='done'\""]),
    ("terraform-destroy", &["terraform destroy", "terraform destroy -auto-approve"]),
    ("terraform-auto-approve", &["terraform apply -auto-approve", "terraform apply -var-file=prod.tfvars -auto-approve"]),
    ("kubectl-delete-context", &["kubectl delete pod web-1 -n prod", "kubectl delete -f deploy.yaml", "kubectl --context prod delete --all pods"]),
    ("docker-system-prune", &["docker system prune -a --volumes", "docker system prune --all", "docker volume prune -f"]),
    ("compose-down-volumes", &["docker compose down -v", "docker-compose down --volumes"]),
    ("curl-pipe-shell", &["curl -fsSL https://get.example.com/install.sh | sh", "wget -qO- https://example.com/setup.sh | sudo bash", "sh -c \"$(curl -fsSL https://example.com/install.sh)\""]),
    ("npm-publish", &["npm publish", "npm publish --access public", "pnpm publish"]),
    ("cargo-publish", &["cargo publish", "cargo publish --allow-dirty"]),
    ("redirect-overwrite", &["echo 'export PATH=$PATH:/opt/bin' > ~/.bashrc", "echo \"ssh-ed25519 AAAA\" > ~/.ssh/authorized_keys", "echo 127.0.0.1 example.test > /etc/hosts"]),
    ("sed-in-place", &["sed -i 's/foo/bar/g' *.js", "find . -name '*.py' | xargs sed -i 's/a/b/'"]),
    (
        "find-delete",
        &["find ~/Downloads -delete -name '*.tmp'", "find /var/tmp -delete", "find . -maxdepth 1 -delete", "find /var/tmp -type f -exec rm {} \\;", "find . -name '*.o' | xargs rm", "find . -name '*.tmp' | xargs rm -rf", "grep -rl TODO src | xargs rm"],
    ),
    ("aws-s3-delete", &["aws s3 rm s3://my-bucket/ --recursive", "aws s3 sync ./dist s3://my-bucket --delete"]),
    ("rsync-delete", &["rsync -av --delete src/ backup/", "rsync -a --delete-after ./site/ host:/var/www/"]),
    ("redis-flush", &["redis-cli flushall", "redis-cli -h cache.internal FLUSHDB"]),
    (
        "home-wipe",
        &[
            "rm -rf ~/*",
            "sudo rm -rf /home/leduc",
            "rm -rf /Users/phil",
            "rm -fr \"${HOME:?}\"/*",
            "rm -r -f ~/*",
            "rm -rf /home/leduc/*",
            "rm -Rf /Users/phil/",
            "cd /tmp && sudo rm -rf --no-preserve-root /root",
        ],
    ),
    (
        "windows-delete",
        &[
            "rmdir /s /q C:\\Users\\me\\project",
            "rd /q /s C:\\build",
            "del /s /q *.*",
            "RMDIR /S /Q C:\\data",
            "cmd /c \"rd /s /q C:\\data\"",
            "Remove-Item -Recurse -Force C:\\Users\\me\\project",
            "ri -r -fo C:\\build",
            "rm -Force -Recurse $env:TEMP\\out",
            "powershell -Command \"Remove-Item C:\\x -Recurse -Force\"",
            "REMOVE-ITEM -RECURSE -FORCE ..\\node_modules",
            "rmdir /s /q %USERPROFILE%",
            "del /s /q C:\\Users\\me\\*.*",
            "rd /s /q ..\\other",
            "Remove-Item -Recurse -Force ~",
            "Remove-Item C:\\Users\\me -Force -Recurse",
            "rmdir C:\\data /s /q",
        ],
    ),
    (
        "cloud-destroy",
        &[
            "aws ec2 terminate-instances --instance-ids i-0abc",
            "aws --profile prod ec2 terminate-instances --instance-ids i-1",
            "aws iam delete-user --user-name bob",
            "aws iam delete-role --role-name deploy",
            "aws rds delete-db-instance --db-instance-identifier prod --skip-final-snapshot",
            "aws rds delete-db-cluster --db-cluster-identifier c1",
            "aws cloudformation delete-stack --stack-name app",
            "gcloud projects delete my-proj",
            "gcloud compute instances delete vm1 --zone us-central1-a",
            "gcloud sql instances delete db1",
            "az group delete --name rg --yes",
        ],
    ),
    (
        "discard-files",
        &[
            "git restore src/main.rs",
            "git restore README.md src/lib.rs",
            "git restore --worktree src/a.rs",
            "git restore --source=HEAD~1 src/a.rs",
            "git checkout -- src/main.rs",
            "git checkout HEAD -- Cargo.toml",
        ],
    ),
    (
        "wait-pgrep-self-match",
        &[
            "until ! pgrep -f sales_report; do sleep 30; done; echo finished",
            "while pgrep -f train.py > /dev/null; do sleep 10; done",
            "until ! pgrep -f '[s]ales' >/dev/null; do sleep 60; done; cat sales.out | grep -c sales",
            "while pgrep -fa run_batch; do sleep 5; done",
            "while pkill -0 -f ingest.sh; do sleep 5; done",
            "bash -c 'until ! pgrep -f build_all; do sleep 2; done'",
            "timeout 600 bash -c 'until ! pgrep -f build_all; do sleep 2; done'",
            "while true; do pgrep -f worker || break; sleep 3; done",
        ],
    ),
    (
        "wait-pid-from-pgrep",
        &[
            "tail --pid=$(pgrep -f train.py | head -1) -f train.log",
            "tail -f out.log --pid=$(pgrep -n python)",
            "tail --pid $(pgrep -f job) -f out.log",
            "tail --pid=`pgrep -f job` -f out.log",
            "wait $(pgrep -f job)",
            "bash -c 'tail --pid=$(pgrep -f job | head -1) -f out.log'",
            "pid=$(pgrep -f job | head -1); tail --pid=$pid -f out.log",
            "p=$(pgrep -o -f job); wait $p",
        ],
    ),
    (
        "detached-launch-unbound",
        &[
            "nohup node server.js &",
            "nohup ./worker > worker.log 2>&1 &",
            "setsid ./job.sh",
            "python3 app.py & disown",
            "(./daemon --serve &)",
            "nohup sleep infinity > /dev/null 2>&1 &",
            "ssh -fN -L 8080:localhost:80 host",
        ],
    ),
    (
        "headless-browser-background",
        &[
            "chromium --headless --remote-debugging-port=9222 &",
            "google-chrome --headless=new --screenshot=/tmp/a.png https://example.com &",
        ],
    ),
];

/// Close to the dangerous forms, and safe. Each must stay silent.
const SAFE_NEIGHBOURS: &[&str] = &[
    "timeout 600 python3 -m http.server 8000 &",
    "node server.js & p=$!; trap \"kill $p\" EXIT",
    "make test & wait $!",
    "./job.sh & pid=$!; sleep 5; kill $pid",
    "nohup timeout 60 ./job.sh &",
    "systemd-run --user --scope -p RuntimeMaxSec=300 ./job.sh",
    "systemctl --user start myapp",
    "chromium --headless --dump-dom https://example.com",
    "timeout 120 chromium --headless --remote-debugging-port=9222 &",
    "python3 -m http.server 8000",
    "tail -f app.log",
    "sleep 5 &",
    "npm run build && npm test",
    "setsid -w ./job.sh",
    "git commit -m \"document setsid and nohup usage\"",
    "grep -r nohup docs/",
    "git push --force-with-lease",
    "git push --force-with-lease=main origin main",
    "git push origin main",
    "rm -rf ./target",
    "rm -rf node_modules dist",
    "rm -rf build/",
    "rm -rf \"${BUILD_DIR:?}\"/*",
    "rm file.txt",
    "git reset --soft HEAD~1",
    "git reset HEAD src/main.rs",
    "git restore --staged .",
    "git restore --staged src/main.rs",
    "git restore --staged --source=HEAD~1 src/main.rs",
    "git restore -S src/main.rs",
    "git restore -p",
    "cmd & p=$!; wait $p",
    "./train.sh & p=$!; tail --pid=$p -f train.log",
    "wait $pid",
    "wait",
    "tail --pid=$pid -f out.log",
    "tail -f out.log",
    "timeout 600 bash -c 'until [ -f result.done ]; do sleep 5; done'",
    "timeout 900 bash -c 'until grep -q DONE out.log; do sleep 5; done'",
    "for i in $(seq 1 120); do [ -f result.done ] && break; sleep 5; done",
    "for i in 1 2 3 4 5; do curl -sf localhost:8080/health && break; sleep 2; done",
    "i=0; while [ $i -lt 30 ]; do [ -f done ] && break; i=$((i+1)); sleep 2; done",
    "n=0; until [ -f done ]; do n=$((n+1)); [ $n -gt 60 ] && break; sleep 5; done",
    "pgrep -f train.py",
    "pgrep -af train.py | head",
    "if pgrep -f train.py; then echo running; fi",
    "pgrep -x python3",
    "gh pr checks --watch",
    "gh run watch 123",
    "while read -r line; do echo \"$line\"; sleep 1; done < list.txt",
    "sleep 5",
    "pid=$(cat app.pid); tail --pid=$pid -f out.log",
    "git checkout -b fix/typo",
    "git checkout --help",
    "git diff",
    "git diff -- src/main.rs",
    "git switch main",
    "rm -rf ~/project/build",
    "rm -rf ~/.cache/pip",
    "rm -rf \"${HOME:?}/project/tmp\"",
    "rm -rf /home/leduc/project/build",
    "rm -rf /Users/phil/Library/Caches/old",
    "rm ~/notes.txt",
    "ls ~/*",
    "rm -rf /homework",
    "rmdir build",
    "rmdir /q empty",
    "del file.txt",
    "del /q file.txt",
    "dir /s",
    "Remove-Item build\\out.log",
    "Remove-Item -Recurse -Force -WhatIf build",
    "Remove-Item -Recurse -Force -wh build",
    "Get-ChildItem -Recurse -Force",
    "aws ec2 describe-instances",
    "aws ec2 terminate-instances --instance-ids i-1 --dry-run",
    "aws iam list-users",
    "aws iam get-role --role-name deploy",
    "aws rds describe-db-instances",
    "aws rds describe-db-clusters",
    "aws cloudformation describe-stacks",
    "aws cloudformation list-stacks",
    "aws sts get-caller-identity",
    "gcloud projects list",
    "gcloud projects describe my-proj",
    "gcloud compute instances list",
    "gcloud compute instances describe vm1",
    "gcloud sql instances list",
    "gcloud config list",
    "az group list",
    "az group show --name rg",
    "az account show",
    "grep -rn mkfs docs/",
    "echo \"do not run mkfs here\"",
    "wipefs /dev/sdb",
    "wipefs --no-act -a /dev/sdb",
    "man dd",
    "man mkfs.ext4",
    "cat notes.md | grep 'git push --force'",
    "git log --grep=\"git reset --hard\"",
    "git grep -n 'rm -rf /' -- docs",
    "rg 'DROP TABLE' src",
    "rg -n \"terraform destroy\" .",
    "printf '%s\\n' \"kubectl delete ns prod\"",
    "echo 'echo hi > ~/.bashrc'",
    "ls /sbin/mkfs*",
    "head -20 docs/dd.md",
    "rm -rf $HOME/code/app/node_modules",
    "rm -rf \"$HOME\"/code/app/node_modules",
    "rm -rf \"$HOME/a\" \"$HOME/b\"",
    "rm -rf $HOME/x $HOME/y/z",
    "rm -rf ${HOME}/.cache/pip",
    "find ~/Downloads -name '*.tmp' -delete",
    "find . -type f -mtime +30 -delete",
    "find /var/tmp -newermt 2026-01-01 -delete",
    "find . -name '*.log' -delete",
    "rmdir /s /q .\\build",
    "rd /s /q build",
    "rd /q /s out\\obj",
    "del /s /q build\\cache.tmp",
    "Remove-Item -Recurse -Force .\\node_modules",
    "Remove-Item -Recurse -Force node_modules",
    "ri -r -fo .\\build",
    "rm -Force -Recurse .\\out",
    "git checkout main",
    "git checkout -b feature/x",
    "git clean -n",
    "git clean -nd",
    "git clean -ndx",
    "git branch -d merged-branch",
    "git branch -a",
    "git stash",
    "git stash list",
    "git stash pop",
    "git add src/main.rs",
    "git add .env.example",
    "git add -A",
    "git commit -m \"update docs\"",
    "kill 4242",
    "pgrep -af server",
    "chmod 644 notes.txt",
    "chmod +x run.sh",
    "chmod -R u+rwX,go-w ./dist",
    "chown user:user notes.txt",
    "chown -R user ./data",
    "dd if=/dev/zero of=./test.img bs=1M count=10",
    "dd if=input.bin of=output.bin",
    "dd if=/dev/urandom of=/dev/null bs=1M count=1",
    "lsblk",
    "man mkfs",
    "psql -c \"SELECT * FROM users\"",
    "psql -c \"DELETE FROM users WHERE id = 1\"",
    "mysql -e \"UPDATE users SET active = 0 WHERE id = 2\"",
    "psql -c \"CREATE TABLE t (id int)\"",
    "truncate -s 0 app.log",
    "terraform plan",
    "terraform apply tfplan",
    "terraform init",
    "kubectl get pods",
    "kubectl --context kind-dev delete pod web-1",
    "kubectl delete pod web-1 --context=dev",
    "kubectl describe deployment api",
    "docker ps",
    "docker system prune",
    "docker compose down",
    "docker compose up -d",
    "curl -fsSL https://example.com/data.json | jq .",
    "curl -fsSLo install.sh https://example.com/install.sh",
    "npm publish --dry-run",
    "npm test",
    "cargo publish --dry-run",
    "cargo build",
    "echo 'export A=1' >> ~/.bashrc",
    "echo hello > out.txt",
    "ls > files.txt",
    "sed -i.bak 's/a/b/' config.toml",
    "sed 's/a/b/' config.toml",
    "sed -n 1,10p README.md",
    "find . -name '*.rs'",
    "find . -type f -print",
    "aws s3 ls",
    "aws s3 sync ./dist s3://my-bucket",
    "aws s3 rm s3://my-bucket/old --recursive --dryrun",
    "rsync -av --dry-run --delete src/ dest/",
    "rsync -av src/ dest/",
    "redis-cli get session:1",
];

/// 200 everyday commands: families of tools with their usual arguments.
fn everyday() -> Vec<String> {
    let mut v: Vec<String> = Vec::new();
    let mut add = |prefix: &str, rest: &[&str]| {
        for r in rest {
            v.push(format!("{prefix} {r}").trim().to_string());
        }
    };
    add("ls", &["", "-la", "-lh src", "tests", "-R docs | head"]);
    add("cat", &["README.md", "Cargo.toml", "src/main.rs | head -50", "/etc/os-release"]);
    add("git", &[
        "status", "status --short", "diff", "diff --stat", "diff HEAD~1", "log --oneline -10", "log -p src/main.rs",
        "show HEAD", "fetch origin", "pull --rebase", "branch", "branch -vv", "remote -v", "tag -l", "blame src/main.rs",
        "add src/lib.rs", "add -p", "commit -m \"fix typo in docs\"", "commit --amend --no-edit", "switch main",
        "checkout -b feat/search", "rebase --continue", "merge --no-ff feature", "stash list", "diff --cached",
        "rev-parse HEAD", "describe --tags", "config user.name", "ls-files", "worktree list",
    ]);
    add("cargo", &[
        "build", "build --release", "build --locked --offline", "test", "test --locked --offline", "test -p instinct-cli",
        "check", "clippy --all-targets", "fmt --check", "doc --no-deps", "run -- --help", "tree", "bench", "package --list",
        "publish --dry-run", "update -p serde", "add anyhow", "metadata --format-version 1",
    ]);
    add("npm", &["install", "ci", "test", "run build", "run lint", "ls", "outdated", "pack --dry-run", "audit", "run dev"]);
    add("docker", &[
        "ps", "ps -a", "images", "logs web", "logs -f api", "build -t app .", "run --rm -it alpine sh", "compose up -d",
        "compose ps", "compose logs api", "compose down", "exec -it web bash", "inspect web", "stats --no-stream",
    ]);
    add("grep", &["-rn TODO src", "-r \"fn main\" .", "-i error app.log", "-c foo file.txt", "-n pattern *.rs", "-rl unsafe src"]);
    add("rg", &["TODO", "-n \"fn run\" src", "--files", "-t rust unsafe", "-l config"]);
    add("find", &[". -name '*.rs'", ". -type d -name target -prune", "src -type f -newer Cargo.toml", ". -maxdepth 2 -name README.md", "/var/log -name '*.log' -print"]);
    add("head", &["-20 README.md", "-n 5 Cargo.lock", "-c 100 file.bin"]);
    add("tail", &["-f app.log", "-n 50 build.log", "-100 syslog"]);
    add("wc", &["-l src/main.rs", "-w README.md", "-c data.csv"]);
    add("sort", &["data.txt | uniq -c", "-n numbers.txt", "-u names.txt"]);
    add("diff", &["a.txt b.txt", "-u old.rs new.rs", "-rq dir1 dir2"]);
    add("mkdir", &["-p build/out", "docs/new", "-p /tmp/work/a/b"]);
    add("cp", &["config.example.toml config.toml", "-r src backup/src", "README.md /tmp/readme.txt"]);
    add("mv", &["draft.md final.md", "old_name.rs new_name.rs"]);
    add("touch", &["notes.txt", "src/new.rs"]);
    add("echo", &["hello", "\"building...\"", "$PATH", "done >> log.txt"]);
    add("pwd", &[""]);
    add("which", &["cargo", "python3", "node"]);
    add("env", &["| sort", "| grep PATH"]);
    add("ps", &["aux | grep nginx", "-ef", "-p 1234"]);
    add("df", &["-h", "-h /home"]);
    add("du", &["-sh .", "-sh target", "-h --max-depth=1"]);
    add("curl", &["-s https://api.example.com/health", "-I https://example.com", "-fsSL https://example.com/data.json -o data.json", "-s localhost:8080/status | jq ."]);
    add("python3", &["--version", "script.py --input data.csv", "-m http.server 8000", "-m unittest discover"]);
    add("node", &["--version", "index.js", "scripts/build.js"]);
    add("make", &["", "test", "build", "lint"]);
    add("kubectl", &["get pods", "get pods -n staging", "logs deploy/api", "describe pod web-1", "config current-context", "apply -f deploy.yaml --dry-run=client", "get svc"]);
    add("terraform", &["fmt", "validate", "plan -out=tfplan", "show tfplan", "output"]);
    add("systemctl", &["status nginx", "list-units --failed", "is-active sshd"]);
    add("journalctl", &["-u nginx -n 50", "--since today"]);
    add("tar", &["-czf backup.tgz src", "-xzf archive.tgz", "-tf archive.tgz"]);
    add("ssh", &["dev-box uptime", "-T git@github.com"]);
    add("sqlite3", &["app.db \".tables\"", "app.db \"SELECT count(*) FROM users\""]);
    add("jq", &[". package.json", "'.version' Cargo.json"]);
    add("sed", &["-n '1,20p' README.md", "'s/foo/bar/' input.txt"]);
    add("awk", &["'{print $1}' data.txt", "-F, '{sum+=$2} END {print sum}' data.csv"]);
    add("chmod", &["+x scripts/run.sh", "644 README.md"]);
    add("sleep", &["1", "0.5"]);
    add("date", &["", "-u +%FT%TZ"]);
    add("uname", &["-a"]);
    add("whoami", &[""]);
    add("go", &["build ./...", "test ./...", "vet ./..."]);
    add("pip", &["install -r requirements.txt", "list", "freeze > requirements.txt"]);
    add("ls", &["-l /etc | head"]);
    v
}

#[test]
fn every_lesson_fires_on_at_least_two_dangerous_commands() {
    let s = applied("danger");
    let pack = std::fs::read_to_string(format!("{}/community/tripwires.json", env!("CARGO_MANIFEST_DIR"))).unwrap();
    let ids: Vec<&str> = pack.split("\"id\":\"").skip(1).map(|c| c.split('"').next().unwrap()).collect();
    assert!(ids.len() >= 25 && ids.len() <= 45, "{} lessons", ids.len());
    for id in &ids {
        let n = DANGEROUS.iter().find(|(d, _)| d == id).map(|(_, c)| c.len()).unwrap_or(0);
        assert!(n >= 2, "lesson {id} has {n} dangerous commands in the test, needs 2");
    }
    let (mut fired, mut total) = (0, 0);
    let mut misses = Vec::new();
    for (id, cmds) in DANGEROUS {
        let after = pack.split(&format!("\"id\":\"{id}\"")).nth(1).unwrap_or_else(|| panic!("{id} not in the pack"));
        let title = after.split("\"title\":\"").nth(1).unwrap().split("\",\"when\"").next().unwrap().replace("\\\"", "\"");
        for c in *cmds {
            total += 1;
            let out = guard(&s, c);
            if out.contains(&esc(&title)) {
                fired += 1;
            } else {
                misses.push(format!("{id}: {c}\n   got: {}", out.chars().take(160).collect::<String>()));
            }
        }
    }
    println!("starter precision: dangerous fired {fired} out of {total} ({} lessons)", ids.len());
    assert!(misses.is_empty(), "{} did not fire the right lesson:\n{}", misses.len(), misses.join("\n"));
}

#[test]
fn safe_neighbours_stay_silent() {
    let s = applied("neighbours");
    let loud: Vec<String> = SAFE_NEIGHBOURS
        .iter()
        .filter_map(|c| {
            let o = guard(&s, c);
            (!o.is_empty()).then(|| format!("{c}\n   got: {}", o.chars().take(200).collect::<String>()))
        })
        .collect();
    println!("starter precision: safe neighbours silent {} out of {}", SAFE_NEIGHBOURS.len() - loud.len(), SAFE_NEIGHBOURS.len());
    assert!(loud.is_empty(), "{} safe neighbours warned:\n{}", loud.len(), loud.join("\n"));
}

#[test]
fn two_hundred_everyday_commands_give_no_warning() {
    let s = applied("everyday");
    let cmds = everyday();
    assert!(cmds.len() >= 200, "{} commands", cmds.len());
    let loud: Vec<String> = cmds
        .iter()
        .filter_map(|c| {
            let o = guard(&s, c);
            (!o.is_empty()).then(|| format!("{c}\n   got: {}", o.chars().take(200).collect::<String>()))
        })
        .collect();
    println!("starter precision: everyday silent {} out of {}", cmds.len() - loud.len(), cmds.len());
    assert!(loud.is_empty(), "{} everyday commands warned:\n{}", loud.len(), loud.join("\n"));
}

fn lesson_lines(store: &PathBuf) -> usize {
    std::fs::read_to_string(store).map(|t| t.lines().filter(|l| l.contains("\"title\"")).count()).unwrap_or(0)
}

#[test]
fn apply_is_idempotent_and_dry_run_writes_nothing() {
    let s = store("idem");
    let (code, dry) = instinct(&s, &["starter"]);
    assert_eq!(code, 0, "{dry}");
    assert!(dry.contains("Dry run"), "{dry}");
    assert!(!s.exists(), "a dry run must not create the bank");
    let (_, first) = instinct(&s, &["starter", "--apply"]);
    let n = lesson_lines(&s);
    assert!(n >= 25, "{n} lessons banked\n{first}");
    assert!(first.contains(&format!("banked {n} as source: community")), "{first}");
    let (_, second) = instinct(&s, &["starter", "--apply"]);
    assert!(second.contains("banked 0 as source: community"), "{second}");
    assert_eq!(lesson_lines(&s), n, "a rerun must not add lines");
    let text = std::fs::read_to_string(&s).unwrap();
    assert!(text.contains("\"source\":\"community\""));
    let (_, json) = instinct(&s, &["starter", "--json"]);
    assert!(json.contains("\"new\":0"), "{json}");
}

#[test]
fn a_lesson_already_in_the_bank_is_skipped() {
    let s = store("present");
    let (code, _) = instinct(
        &s,
        &[
            "bank", "--title", "DELETE FROM without WHERE deletes every row", "--when", "mine",
            "--found", "A DELETE without WHERE removes every row in the table. A typo or a truncated command that loses its WHERE does the same.",
            "--how", "mine", "--evidence", "mine",
        ],
    );
    assert_eq!(code, 0);
    let before = lesson_lines(&s);
    let (_, out) = instinct(&s, &["starter", "--apply"]);
    assert_eq!(lesson_lines(&s), before + lesson_lines_in_pack() - 1, "{out}");
}

fn lesson_lines_in_pack() -> usize {
    let pack = std::fs::read_to_string(format!("{}/community/tripwires.json", env!("CARGO_MANIFEST_DIR"))).unwrap();
    pack.matches("\"id\":\"").count()
}

fn guard_in_session(store: &PathBuf, command: &str, session: &str) -> String {
    let payload = format!(
        "{{\"session_id\":\"{session}\",\"cwd\":\"/home/dev/app\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{}\"}}}}",
        esc(command)
    );
    let mut child = Command::new(bin())
        .arg("guard")
        .env("INSTINCT_STORE", store)
        .env("HOME", store.parent().unwrap())
        .env_remove("XDG_DATA_HOME")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(payload.as_bytes()).ok();
    String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap()
}

#[test]
fn eval_never_proposes_merging_command_lessons() {
    let s = applied("evaldups");
    let (code, out) = instinct(&s, &["eval"]);
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("Near-duplicates (0)"), "{out}");
    assert!(!out.contains("quarantined"), "{out}");
    for c in ["psql -c \"TRUNCATE TABLE users\"", "psql -c \"UPDATE users SET active = false\""] {
        assert!(!guard(&s, c).is_empty(), "{c} must still warn");
    }
}

#[test]
fn eval_says_when_the_one_day_grace_hides_fresh_lessons() {
    let s = applied("evalgrace");
    let n = lesson_lines(&s);
    assert!(!guard_in_session(&s, "rm -rf /", "s1").is_empty());
    assert!(!guard_in_session(&s, "sudo rm -rf /var/lib/docker", "s1").is_empty());
    let (_, out) = instinct(&s, &["eval"]);
    assert!(!out.contains("Every banked lesson was delivered or judged"), "{out}");
    let want = format!("{} lessons were banked in the last day; they show here once they are a day old.", n - 2);
    assert!(out.contains(&want), "missing: {want}\n{out}");
}

#[test]
fn the_header_counts_before_applying() {
    let s = store("header");
    let n = lesson_lines_in_pack();
    let (_, first) = instinct(&s, &["starter", "--apply"]);
    assert!(first.contains(&format!("{n} lessons, {n} not in your bank yet, 0 already there")), "{first}");
    let (_, second) = instinct(&s, &["starter", "--apply"]);
    assert!(second.contains(&format!("{n} lessons, 0 not in your bank yet, {n} already there")), "{second}");
}

#[test]
fn warnings_do_not_show_the_internal_cmd_matchers() {
    let s = applied("render");
    let out = guard(&s, "rm -rf \"$BUILD_DIR\"/*");
    assert!(out.contains("rm -rf"), "the tripwire still fires: {out}");
    assert!(!out.contains("cmd:"), "cmd: matchers are internal and stay out of the warning: {out}");
    // Silence is unchanged: the stored tags still carry the matchers.
    assert!(guard(&s, "rm -rf ./target").is_empty());
}

/// Two lessons with the same wording and the same command matcher, banked into one store with the given scope
/// values (an empty value means unscoped). Returns the `instinct eval` text.
fn eval_of_pair(name: &str, scopes: [(&str, &str); 2]) -> String {
    let s = store(name);
    for (i, (flag, value)) in scopes.iter().enumerate() {
        let found = format!("found {i}");
        let how = format!("use plan {i}");
        let mut args = vec![
            "bank", "--title", "Deploy cobalt widgets", "--when", "Deploying cobalt widgets to production",
            "--found", &found, "--how", &how, "--evidence", "seen twice", "--tags", "tool_bash;cmd:git push --force",
        ];
        if !value.is_empty() {
            args.extend([*flag, *value]);
        }
        let (code, out) = instinct(&s, &args);
        assert_eq!(code, 0, "{out}");
    }
    instinct(&s, &["eval", "--since", "all"]).1
}

#[test]
fn lessons_scoped_differently_are_never_offered_as_duplicates() {
    for flag in ["--project", "--persona", "--applicability-machine", "--applicability-harness", "--applicability-version"] {
        let name = format!("scope{}", flag.trim_start_matches('-'));
        let ev = eval_of_pair(&name, [(flag, "alpha"), (flag, "beta")]);
        assert!(!ev.contains("--reason \"duplicate of"), "{flag}: a scoped lesson was offered for quarantine: {ev}");
    }
    // Control: the same pair with the same scope is still flagged, so the check above is not vacuous.
    let ev = eval_of_pair("scope-same", [("--project", "alpha"), ("--project", "alpha")]);
    assert!(ev.contains("--reason \"duplicate of"), "same scope must still be offered as a duplicate: {ev}");
}

/// `cmd` as one quoted word for the shell, or None when it holds both quote kinds or an expansion.
fn quoted(cmd: &str) -> Option<String> {
    if !cmd.contains('\'') {
        Some(format!("'{cmd}'"))
    } else if !cmd.contains(['"', '$', '\\', '`']) {
        Some(format!("\"{cmd}\""))
    } else {
        None
    }
}

#[test]
fn a_dangerous_command_only_mentioned_by_a_reading_command_stays_silent_across_the_pack() {
    let s = applied("mentions");
    let (mut tried, mut loud) = (0, Vec::new());
    for (id, cmds) in DANGEROUS {
        for c in *cmds {
            let Some(q) = quoted(c) else { continue };
            for wrap in [
                format!("echo {q}"),
                format!("grep -rn {q} docs/"),
                format!("rg {q} src"),
                format!("printf '%s\\n' {q}"),
                format!("man -k {q}"),
                format!("git log --grep={q}"),
                format!("cat notes.md | grep {q} | wc -l"),
                format!("sudo grep -rn {q} /etc"),
            ] {
                tried += 1;
                if !guard(&s, &wrap).is_empty() {
                    loud.push(format!("{id}: {wrap}"));
                }
            }
        }
    }
    println!("starter mentions: {tried} wrapped commands, {} warned", loud.len());
    assert!(tried >= 400, "only {tried} wrapped commands");
    assert!(loud.is_empty(), "{} mentions warned:\n{}", loud.len(), loud.join("\n"));
}

#[test]
fn a_command_in_command_position_still_warns() {
    let s = applied("position");
    for c in [
        "sudo mkfs.ext4 /dev/sdb1",
        "find . -name '*.tmp' | xargs rm -rf",
        "ls && sudo rm -rf /var/lib/docker",
        "echo done; git push --force origin main",
        "echo 'DROP TABLE users;' | psql app",
        "echo 'rm -rf /' | sh",
        "grep -rl x . | xargs sed -i s/a/b/",
        "cd /srv && wipefs -a /dev/sdb",
    ] {
        assert!(!guard(&s, c).is_empty(), "{c} must warn");
    }
}

#[test]
fn home_variable_forms_warn_with_or_without_a_guard() {
    let s = applied("homevars");
    for c in ["rm -rf $HOME/*", "rm -rf \"$HOME\"/*", "sudo rm -rf \"$HOME\"", "rm -rf ${HOME}/", "rm -rf \"${HOME:?}\""] {
        assert!(!guard(&s, c).is_empty(), "{c} must warn");
    }
}

const NEW_IN_THIS_PACK: [&str; 7] = [
    "A poll loop with no deadline, or a slow command in the foreground, stalls the agent",
    "rm -rf on a whole home directory or everything in it",
    "rmdir /s /q, del /s /q and Remove-Item -Recurse -Force delete a tree with no prompt",
    "aws, gcloud and az delete commands destroy cloud resources",
    "git restore PATH and git checkout -- PATH throw away uncommitted edits",
    "A wait loop on pgrep -f never ends: it matches its own shell",
    "tail --pid or wait on a PID taken from pgrep follows the wrong process",
];

/// A bank made before these seven lessons existed: the full pack with their lines taken out.
fn older_bank(name: &str) -> PathBuf {
    let s = applied(name);
    let text = std::fs::read_to_string(&s).unwrap();
    let kept: Vec<&str> = text.lines().filter(|l| !NEW_IN_THIS_PACK.iter().any(|t| l.contains(&esc(t)))).collect();
    assert_eq!(kept.len() + 7, text.lines().count(), "the seven new lessons are one line each");
    std::fs::write(&s, format!("{}\n", kept.join("\n"))).unwrap();
    s
}

#[test]
fn apply_on_an_older_bank_adds_only_the_missing_tripwires() {
    let s = older_bank("upgrade");
    let n = lesson_lines_in_pack();
    assert_eq!(lesson_lines(&s), n - 7);
    assert!(guard(&s, "rm -rf ~/*").is_empty(), "the older bank does not know home wipes");
    assert!(guard(&s, "until ! pgrep -f job; do sleep 5; done").is_empty(), "the older bank does not know wait loops");
    let (_, dry) = instinct(&s, &["starter"]);
    assert!(dry.contains(&format!("{n} lessons, 7 not in your bank yet, {} already there", n - 7)), "{dry}");
    let (_, first) = instinct(&s, &["starter", "--apply"]);
    assert!(first.contains("banked 7 as source: community"), "{first}");
    assert_eq!(lesson_lines(&s), n);
    let (_, second) = instinct(&s, &["starter", "--apply"]);
    assert!(second.contains("banked 0 as source: community"), "{second}");
    let text = std::fs::read_to_string(&s).unwrap();
    for t in NEW_IN_THIS_PACK.iter().map(|t| esc(t)) {
        assert_eq!(text.matches(&format!("\"title\":\"{t}\"")).count(), 1, "{t} must be banked once");
    }
    assert!(!guard(&s, "until ! pgrep -f job; do sleep 5; done").is_empty(), "the upgraded bank warns");
}

#[test]
fn doctor_says_how_many_starter_tripwires_are_missing() {
    let s = older_bank("doctorline");
    let (code, out) = instinct(&s, &["doctor"]);
    assert_eq!(code, 0, "{out}");
    assert_eq!(out.matches("new starter tripwires").count(), 1, "{out}");
    assert!(out.contains("7 new starter tripwires: instinct starter --apply"), "{out}");
    let (_, json) = instinct(&s, &["doctor", "--json"]);
    assert!(json.contains("\"starter_new\":7"), "{json}");
    instinct(&s, &["starter", "--apply"]);
    let (_, after) = instinct(&s, &["doctor"]);
    assert!(!after.contains("new starter tripwires"), "{after}");
    let (_, json) = instinct(&s, &["doctor", "--json"]);
    assert!(!json.contains("starter_new"), "{json}");
}

/// A number no other call in this test process has seen, so parallel tests never share a folder.
fn uniq() -> usize {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}