instinct-cli 0.3.8

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
//! `instinct scan`: deterministic counts on synthetic Claude Code and Codex transcripts, redaction, the window
//! cut-off, empty and missing folders, `--share` length, and that nothing is written or leaked.
//! Every run uses a sandbox HOME; the real ~/.claude and ~/.codex are never read.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};

fn sandbox(name: &str) -> PathBuf {
    static N: AtomicUsize = AtomicUsize::new(0);
    let d = std::env::temp_dir().join(format!("instinct-scan-test-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
    let _ = fs::remove_dir_all(&d);
    fs::create_dir_all(&d).unwrap();
    d
}

fn scan(home: &Path, args: &[&str]) -> (i32, String, String) {
    let o = Command::new(env!("CARGO_BIN_EXE_instinct"))
        .env("HOME", home)
        .env("USERPROFILE", home)
        .env("LOCALAPPDATA", home.join(".local").join("share"))
        .env_remove("XDG_DATA_HOME")
        .env_remove("INSTINCT_STORE")
        .env_remove("CLAUDE_CONFIG_DIR")
        .env_remove("CODEX_HOME")
        .arg("scan")
        .args(args)
        .output()
        .unwrap();
    (
        o.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&o.stdout).into_owned(),
        String::from_utf8_lossy(&o.stderr).into_owned(),
    )
}

fn age(path: &Path, days: u64) {
    let t = SystemTime::now() - Duration::from_secs(days * 86_400);
    fs::OpenOptions::new().write(true).open(path).unwrap().set_modified(t).unwrap();
}

fn write(path: &Path, text: &str) {
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    fs::write(path, text).unwrap();
}

// ---- Claude Code lines
fn cu(text: &str) -> String {
    format!("{{\"type\":\"user\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}
fn cbash(id: &str, cmd: &str) -> String {
    let cmd = cmd.replace('\\', "\\\\").replace('"', "\\\"");
    format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"Bash\",\"input\":{{\"command\":\"{cmd}\"}}}}]}}}}\n")
}
fn cread(id: &str) -> String {
    format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"Read\",\"input\":{{\"file_path\":\"git push --force\"}}}}]}}}}\n")
}
fn cresult(id: &str) -> String {
    format!("{{\"type\":\"user\",\"message\":{{\"role\":\"user\",\"content\":[{{\"type\":\"tool_result\",\"tool_use_id\":\"{id}\",\"content\":\"ok\"}}]}}}}\n")
}
fn ctext(text: &str) -> String {
    format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"text\",\"text\":\"{text}\"}}]}}}}\n")
}

// ---- Codex lines
fn xmeta() -> String {
    "{\"type\":\"session_meta\",\"payload\":{\"id\":\"sess-1\"}}\n".to_string()
}
fn xu(text: &str) -> String {
    format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"user\",\"content\":[{{\"type\":\"input_text\",\"text\":\"{text}\"}}]}}}}\n")
}
fn xcmd(id: &str, cmd: &str) -> String {
    let inner = cmd.replace('\\', "\\\\").replace('"', "\\\"");
    let args_json = format!("{{\"command\":[\"bash\",\"-lc\",\"{inner}\"]}}");
    let args = args_json.replace('\\', "\\\\").replace('"', "\\\"");
    format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"function_call\",\"name\":\"shell\",\"call_id\":\"{id}\",\"arguments\":\"{args}\"}}}}\n")
}
fn xout(id: &str) -> String {
    format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"function_call_output\",\"call_id\":\"{id}\",\"output\":\"ok\"}}}}\n")
}
fn xa(text: &str) -> String {
    format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{{\"type\":\"output_text\",\"text\":\"{text}\"}}]}}}}\n")
}

/// 5 prompts, 2 corrections, 3 shell commands (2 risky). Reply pairs: other->corr, corr->corr, corr->other, other->other.
fn claude_session() -> String {
    [
        cu("ZEBRAMARKER build the thing"),
        cbash("a", "git push --force origin main"),
        cresult("a"),
        ctext("QUOKKAMARKER pushed"),
        cu("no, use pnpm not npm"),
        cbash("b", "rm -rf $BUILD/*"),
        cresult("b"),
        cread("r"),
        cresult("r"),
        cu("no, that's wrong, you broke the build"),
        cbash("c", "ls -la"),
        cresult("c"),
        cu("thanks, looks good"),
        ctext("done"),
        cu("now add tests"),
    ]
    .concat()
}

/// 2 prompts, 1 correction, 2 shell commands (1 risky).
fn codex_session() -> String {
    [
        xmeta(),
        xu("run the migration"),
        xcmd("x1", "psql -c \"DROP TABLE users\""),
        xout("x1"),
        xa("done"),
        xu("no, that's wrong, you broke it"),
        xcmd("x2", "echo hi"),
        xout("x2"),
    ]
    .concat()
}

fn fixture_home(name: &str) -> PathBuf {
    let home = sandbox(name);
    write(&home.join(".claude/projects/p1/s1.jsonl"), &claude_session());
    write(&home.join(".codex/sessions/2026/12/01/rollout-1.jsonl"), &codex_session());
    home
}

fn tree(dir: &Path, out: &mut Vec<String>) {
    let mut es: Vec<_> = fs::read_dir(dir).map(|r| r.flatten().map(|e| e.path()).collect()).unwrap_or_default();
    es.sort();
    for p in es {
        let m = fs::metadata(&p).unwrap();
        out.push(format!("{} {} {:?}", p.display(), m.len(), m.modified().unwrap()));
        if p.is_dir() {
            tree(&p, out);
        }
    }
}

#[test]
fn counts_are_deterministic_on_both_formats() {
    let home = fixture_home("counts");
    let (code, out, err) = scan(&home, &["--json"]);
    assert_eq!(code, 0, "{err}");
    assert!(out.contains("\"files\":{\"scanned\":2,\"claude_code\":1,\"codex\":1,\"skipped_old\":0,\"unreadable\":0}"), "{out}");
    assert!(out.contains("\"prompts\":7,\"commands\":5,"), "{out}");
    assert!(out.contains("\"risky\":{\"flagged\":3,"), "{out}");
    assert!(out.contains("\"title\":\"git push --force overwrites commits other people pushed\",\"count\":1"), "{out}");
    assert!(out.contains("\"corrections\":{\"count\":3,"), "{out}");
    // Claude: other->corr, corr->corr, corr->other, other->other. Codex: other->corr.
    assert!(out.contains("\"after_correction\":{\"replies\":2,\"repeated\":1,\"rate\":0.5000}"), "{out}");
    assert!(out.contains("\"after_other\":{\"replies\":3,\"repeated\":2,\"rate\":0.6667}"), "{out}");
    assert!(out.contains("\"ratio\":null"), "fewer than 20 pairs: no ratio: {out}");
    let (_, again, _) = scan(&home, &["--json"]);
    let strip = |s: &str| s.split("\"elapsed_ms\"").next().unwrap().to_string();
    assert_eq!(strip(&out), strip(&again));
    // Read-tool paths are not shell commands: the Read of "git push --force" is not counted.
    assert!(out.contains("\"count\":1,\"examples\":[\"git push --force origin main\"]"), "{out}");
}

#[test]
fn text_report_has_the_four_sections_and_a_footer() {
    let home = fixture_home("text");
    fs::write(home.join(".claude/CLAUDE.md"), "x".repeat(400)).unwrap();
    let (code, out, _) = scan(&home, &[]);
    assert_eq!(code, 0);
    for h in ["1. Risky commands: 3 of 5", "2. Corrections: 3 of 7 prompts", "3. Memory files", "4. Next steps"] {
        assert!(out.contains(h), "missing {h:?} in\n{out}");
    }
    assert!(out.contains("CLAUDE.md (user level): about 100 tokens on every prompt"), "{out}");
    // 100 tokens x 5 Claude Code prompts
    assert!(out.contains("about 500 tokens"), "{out}");
    assert!(out.contains("No ratio yet"), "{out}");
    assert!(out.contains("instinct starter --apply"), "{out}");
    assert!(out.contains("Scanned in ") && out.contains(" s. Nothing was written or uploaded."), "{out}");
}

#[test]
fn ratio_prints_when_both_groups_have_twenty() {
    let home = sandbox("ratio");
    let mut s = String::new();
    // 25 corrections each answered by a non-correction, then 25 plain prompts each answered by a plain one.
    for _ in 0..25 {
        s.push_str(&cu("no, that's wrong"));
        s.push_str(&ctext("ok"));
        s.push_str(&cu("fine, carry on"));
        s.push_str(&ctext("ok"));
    }
    // and 25 corrections answered by another correction (the repeat case)
    for _ in 0..25 {
        s.push_str(&cu("no, that's wrong"));
        s.push_str(&ctext("ok"));
        s.push_str(&cu("no, that's wrong again, you broke it"));
        s.push_str(&ctext("ok"));
    }
    write(&home.join(".claude/projects/p/s.jsonl"), &s);
    let (_, out, _) = scan(&home, &["--json"]);
    assert!(out.contains("\"ratio\":"), "{out}");
    assert!(!out.contains("\"ratio\":null"), "{out}");
    let (_, text, _) = scan(&home, &[]);
    assert!(text.contains("Ratio: ") && text.contains("x more likely"), "{text}");
}

#[test]
fn secrets_are_redacted_and_snippets_are_60_chars() {
    let home = sandbox("redact");
    let long = format!("git push --force origin {}", "feature/x".repeat(20));
    let s = [
        cu("go"),
        cbash("a", "git push --force https://user:hunter2pass@example.test/r.git"),
        cbash("b", "API_KEY=abc deploy.sh && git push --force origin main"),
        cbash("c", "git push --force origin 3f2a9c1d4b5e6f708192a3b4c5d6e7f801234567"),
        cbash("d", &long),
        cbash("e", "GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789 git push --force"),
        cbash("f", "git push --force sk-abcdefghijklmnopqrstuvwxyz1234"),
    ]
    .concat();
    write(&home.join(".claude/projects/p/s.jsonl"), &s);
    let (_, out, _) = scan(&home, &["--json"]);
    for secret in ["hunter2pass", "abc deploy", "API_KEY=abc", "3f2a9c1d", "ghp_", "sk-abc", "abcdefghijklmnop"] {
        assert!(!out.contains(secret), "{secret} leaked:\n{out}");
    }
    assert!(out.contains("***"), "{out}");
    let (_, text, _) = scan(&home, &[]);
    assert!(!text.contains("ghp_") && !text.contains("hunter2pass"), "{text}");
    // at most 3 examples per group, every one at most 60 chars
    let ex = out.split("\"examples\":[").nth(1).unwrap().split(']').next().unwrap();
    let items: Vec<&str> = ex.split("\",\"").collect();
    assert!(items.len() <= 3, "{ex}");
    for i in items {
        assert!(i.trim_matches('"').chars().count() <= 60, "{i}");
    }
}

#[test]
fn no_prompt_or_reply_text_is_ever_printed() {
    let home = fixture_home("privacy");
    for args in [&[][..], &["--json"][..], &["--share"][..]] {
        let (_, out, err) = scan(&home, args);
        for marker in ["ZEBRAMARKER", "QUOKKAMARKER", "build the thing", "use pnpm", "run the migration"] {
            assert!(!out.contains(marker) && !err.contains(marker), "{marker} printed with {args:?}:\n{out}");
        }
    }
}

#[test]
fn files_older_than_the_window_are_skipped() {
    let home = fixture_home("window");
    let old = home.join(".claude/projects/p2/old.jsonl");
    write(&old, &[cu("go"), cbash("o", "git push --force origin main"), cbash("o2", "git reset --hard")].concat());
    age(&old, 40);
    let (_, out, _) = scan(&home, &["--json"]);
    assert!(out.contains("\"scanned\":2,") && out.contains("\"skipped_old\":1,"), "{out}");
    assert!(out.contains("\"commands\":5,"), "old file not counted: {out}");
    let (_, wide, _) = scan(&home, &["--days", "60", "--json"]);
    assert!(wide.contains("\"scanned\":3,") && wide.contains("\"skipped_old\":0,"), "{wide}");
    assert!(wide.contains("\"commands\":7,"), "{wide}");
    let (_, narrow, _) = scan(&home, &["--days", "30", "--json"]);
    assert!(narrow.contains("\"days\":30"), "default is 30: {narrow}");
}

#[test]
fn missing_and_empty_folders_are_friendly_and_exit_zero() {
    let none = sandbox("missing");
    let (code, out, err) = scan(&none, &[]);
    assert_eq!(code, 0, "{err}");
    assert!(out.contains("No Claude Code or Codex transcripts"), "{out}");
    assert!(out.contains("Nothing was written or uploaded"), "{out}");
    let empty = sandbox("empty");
    fs::create_dir_all(empty.join(".claude/projects/p")).unwrap();
    fs::create_dir_all(empty.join(".codex/sessions")).unwrap();
    write(&empty.join(".claude/projects/p/blank.jsonl"), "");
    write(&empty.join(".claude/projects/p/junk.jsonl"), "not json\n{\"x\":1}\n");
    let (code, out, _) = scan(&empty, &[]);
    assert_eq!(code, 0);
    assert!(out.contains("prompts, 0 shell commands"), "{out}");
    for args in [&["--json"][..], &["--share"][..]] {
        let (code, out, _) = scan(&none, args);
        assert_eq!(code, 0);
        assert!(!out.trim().is_empty());
    }
}

#[test]
fn share_is_one_plain_block_of_at_most_280_chars() {
    let home = fixture_home("share");
    let (code, out, _) = scan(&home, &["--share"]);
    assert_eq!(code, 0);
    let t = out.trim_end();
    assert!(t.chars().count() <= 280, "{} chars: {t}", t.chars().count());
    assert!(t.contains("https://github.com/koscak-labs/instinct"), "{t}");
    assert!(t.contains("3 of 5"), "{t}");
    assert!(!t.contains('\n') && !t.contains('\u{2014}'), "{t}");
    let (_, empty, _) = scan(&sandbox("share-empty"), &["--share"]);
    assert!(empty.trim_end().chars().count() <= 280);
}

#[test]
fn it_writes_nothing() {
    let home = fixture_home("readonly");
    fs::write(home.join(".claude/CLAUDE.md"), "rules").unwrap();
    let (mut before, mut after) = (Vec::new(), Vec::new());
    tree(&home, &mut before);
    scan(&home, &[]);
    scan(&home, &["--json"]);
    scan(&home, &["--share"]);
    tree(&home, &mut after);
    assert_eq!(before, after);
    assert!(!home.join(".local").exists());
}

#[test]
fn bad_arguments_fail_with_a_message() {
    let home = sandbox("args");
    let (code, _, err) = scan(&home, &["--days", "0"]);
    assert_ne!(code, 0);
    assert!(err.contains("--days"), "{err}");
    let (code, _, err) = scan(&home, &["--nope"]);
    assert_ne!(code, 0);
    assert!(err.contains("unknown argument"), "{err}");
    let (code, out, _) = scan(&home, &["--help"]);
    assert_eq!(code, 0);
    assert!(out.contains("usage: instinct scan"));
}

// ---- review fixes: share threshold, project memory files, URL and flag credentials

/// `s` as the body of a JSON string: backslashes (Windows paths), quotes and control characters escaped.
fn jesc(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

/// A Claude Code prompt line that records where the session ran.
fn cuc(text: &str, cwd: &Path) -> String {
    let cwd = jesc(&cwd.display().to_string());
    format!("{{\"type\":\"user\",\"cwd\":\"{cwd}\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}

fn pairs_session(correction_pairs: usize, other_pairs: usize) -> String {
    let mut s = String::new();
    for _ in 0..correction_pairs {
        s.push_str(&cu("no, that's wrong"));
        s.push_str(&ctext("ok"));
        s.push_str(&cu("fine, carry on"));
        s.push_str(&ctext("ok"));
    }
    for _ in 0..other_pairs {
        s.push_str(&cu("carry on"));
        s.push_str(&ctext("ok"));
        s.push_str(&cu("and then"));
        s.push_str(&ctext("ok"));
    }
    s
}

#[test]
fn share_leaves_the_percentages_out_below_twenty_pairs() {
    // Below the threshold the report prints no ratio, so the share text carries no "X% vs Y%" either.
    let home = fixture_home("share-small");
    let (_, share, _) = scan(&home, &["--share"]);
    assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
    assert!(share.contains("I corrected it 3 times"), "{share}");
    let (_, json, _) = scan(&home, &["--json"]);
    assert!(json.contains("\"ratio\":null"), "{json}");
    assert!(!json.contains("\"share\":\"") || !json.split("\"share\":\"").nth(1).unwrap().contains(" vs "), "{json}");
    // 10 correction replies and plenty of other replies: still under the threshold for one group.
    let home = sandbox("share-10");
    write(&home.join(".claude/projects/p/s.jsonl"), &pairs_session(10, 40));
    let (_, share, _) = scan(&home, &["--share"]);
    assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
    // Both groups past 20: the report prints the ratio, but the share text still carries counts only, because
    // the rates depend on how many corrections the detector catches.
    let home = sandbox("share-30");
    write(&home.join(".claude/projects/p/s.jsonl"), &pairs_session(30, 30));
    let (_, share, _) = scan(&home, &["--share"]);
    assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
    assert!(share.chars().count() <= 280, "{share}");
    let (_, report, _) = scan(&home, &[]);
    assert!(report.contains("Ratio:") && report.contains("a floor"), "{report}");
}

#[test]
fn project_memory_files_are_counted_per_project() {
    let home = sandbox("projects");
    fs::create_dir_all(home.join(".claude")).unwrap();
    fs::write(home.join(".claude/CLAUDE.md"), "u".repeat(400)).unwrap(); // user level: 100 tokens
    fs::write(home.join("CLAUDE.md"), "h".repeat(40)).unwrap(); // also user level: 10 tokens
    // Seven projects with one Claude Code prompt each; CLAUDE.md of 10 * i tokens.
    for i in 1..=7u32 {
        let dir = home.join(format!("proj{i}"));
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("CLAUDE.md"), "m".repeat(40 * i as usize)).unwrap();
        write(&home.join(format!(".claude/projects/p{i}/s.jsonl")), &[cuc("hello", &dir), ctext("hi")].concat());
    }
    // proj7 also has an AGENTS.md (100 tokens) and a Codex session of 2 prompts there.
    fs::write(home.join("proj7/AGENTS.md"), "a".repeat(400)).unwrap();
    let cx = [
        format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"s\",\"cwd\":\"{}\"}}}}\n", jesc(&home.join("proj7").display().to_string())),
        xu("one"),
        xa("ok"),
        xu("two"),
    ]
    .concat();
    write(&home.join(".codex/sessions/2026/12/01/r.jsonl"), &cx);
    // A folder that no longer exists, and the home folder itself (counted at user level), cost nothing extra.
    write(&home.join(".claude/projects/gone/s.jsonl"), &[cuc("hello", &home.join("deleted-project")), ctext("hi")].concat());
    write(&home.join(".claude/projects/home/s.jsonl"), &[cuc("hello", &home), ctext("hi")].concat());

    let (code, out, err) = scan(&home, &["--json"]);
    assert_eq!(code, 0, "{err}");
    // 9 Claude Code prompts. User level: (100 + 10) x 9 = 990. Projects: 10+20+...+60 = 210, proj7 = 70 + 2 x 100 = 270.
    assert!(out.contains("\"user_tokens_in_window\":990,"), "{out}");
    assert!(out.contains("\"projects_with_memory\":7,"), "{out}");
    assert!(out.contains("\"tokens_in_window\":1470}"), "overall = 990 + 210 + 270: {out}");
    // Top 5 by total, paths shortened to ~.
    let top = out.split("\"top_projects\":[").nth(1).unwrap().split("],\"tokens_in_window\"").next().unwrap();
    let paths: Vec<&str> = top.split("\"path\":\"").skip(1).map(|p| p.split('"').next().unwrap()).collect();
    assert_eq!(paths, ["~/proj7", "~/proj6", "~/proj5", "~/proj4", "~/proj3"], "{top}");
    assert!(!out.contains(&home.display().to_string()) && !out.contains(&jesc(&home.display().to_string())), "full path leaked: {out}");
    let (_, text, _) = scan(&home, &[]);
    assert!(text.contains("top 5 of 7 projects"), "{text}");
    assert!(text.contains("~/proj7 (3 prompts)") && !text.contains("~/proj2"), "{text}");
    assert!(text.contains("Overall: about 1,470 tokens"), "{text}");
    assert!(!text.contains(&home.display().to_string()), "full path leaked: {text}");
}

#[test]
fn one_and_two_read_as_words_not_1_times() {
    let home = sandbox("singular");
    fs::write(home.join(".claude/CLAUDE.md"), "").ok();
    fs::create_dir_all(home.join(".claude")).unwrap();
    fs::write(home.join(".claude/CLAUDE.md"), "rule").unwrap(); // 1 token
    let proj = home.join("proj");
    fs::create_dir_all(&proj).unwrap();
    fs::write(proj.join("CLAUDE.md"), "rule").unwrap(); // 1 token
    write(
        &home.join(".claude/projects/p/s.jsonl"),
        &[cuc("no, that's wrong", &proj), cbash("a", "git push --force origin main")].concat(),
    );
    let old = home.join(".claude/projects/p/old.jsonl");
    write(&old, &cu("hello"));
    age(&old, 40);
    let (_, text, _) = scan(&home, &["--days", "1"]);
    for want in [
        "the last day (read-only",
        "Read 1 transcript (1 Claude Code, 0 Codex): 1 prompt, 1 shell command.",
        "1. Risky commands: 1 of 1 would have drawn",
        "2. Corrections: 1 of 1 prompt told the agent",
        "CLAUDE.md (user level): about 1 token on every prompt",
        "across 1 prompt (1 Claude Code, 0 Codex): about 1 token.",
        "top 1 of 1 project ",
        "(1 prompt)",
        "Overall: about 2 tokens",
        "(1 file skipped as older than the window, 0 unreadable)",
    ] {
        assert!(text.contains(want), "missing {want:?} in\n{text}");
    }
    let (_, share, _) = scan(&home, &["--days", "1", "--share"]);
    assert!(share.starts_with("My coding agent, last day: 1 of 1 shell command would have drawn"), "{share}");
    assert!(share.contains("I corrected it once."), "{share}");
    for s in [&text, &share] {
        for bad in ["1 times", "1 prompts", "1 transcripts", "1 shell commands", "1 tokens", "1 projects", "1 files", "1 days", "2 times"] {
            assert!(!s.contains(bad), "{bad:?} in {s}");
        }
    }
    // two corrections: "twice"; three: "3 times"
    write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong"), ctext("a"), cu("no, that's wrong")].concat());
    let (_, two, _) = scan(&home, &["--share"]);
    assert!(two.contains("I corrected it twice"), "{two}");
    write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong"), ctext("a"), cu("no, that's wrong"), ctext("b"), cu("no, that's wrong")].concat());
    let (_, three, _) = scan(&home, &["--share"]);
    assert!(three.contains("I corrected it 3 times"), "{three}");
}

fn json_scan(home: &Path) -> String {
    scan(home, &["--json"]).1
}

/// A raw Claude Code user line with extra top-level fields (`"isSidechain":true`, ...).
fn cu_with(extra: &str, text: &str) -> String {
    format!("{{\"type\":\"user\",{extra}\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}

#[test]
fn words_inside_pasted_blocks_are_not_corrections() {
    let home = sandbox("pasted");
    write(
        &home.join(".claude/projects/p/s.jsonl"),
        &[
            cu("please review <pasted_content id=\\\"1\\\">no, that's wrong, you broke it, stop doing that</pasted_content> thanks"),
            ctext("ok"),
            cu("<system-reminder>no, that's wrong</system-reminder>look at this <local-command-stdout>you broke it</local-command-stdout>"),
            ctext("ok"),
            cu("<pasted_content>no, that's wrong"), // unclosed block runs to the end
        ]
        .concat(),
    );
    let out = json_scan(&home);
    // 2 prompts: the unclosed pasted block strips to nothing, so it is not a prompt at all.
    assert!(out.contains("\"prompts\":2,"), "{out}");
    assert!(out.contains("\"corrections\":{\"count\":0,"), "{out}");
    // the control: the same words, typed
    write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong, you broke it, stop doing that"), ctext("ok")].concat());
    assert!(json_scan(&home).contains("\"corrections\":{\"count\":1,"));
    // A typed correction that follows a harness block in the same turn still counts.
    write(&home.join(".claude/projects/p/s.jsonl"), &[cu("<system-reminder>context</system-reminder>\\nno, that's wrong"), ctext("ok")].concat());
    let out = json_scan(&home);
    assert!(out.contains("\"prompts\":1,") && out.contains("\"corrections\":{\"count\":1,"), "{out}");
}

#[test]
fn a_notification_between_two_typed_messages_does_not_break_the_pair() {
    let home = sandbox("notification");
    write(
        &home.join(".claude/projects/p/s.jsonl"),
        &[
            cu("no, that's wrong"),
            ctext("ok"),
            cu("<task-notification>Task done: no, that's wrong</task-notification>"),
            cu("<cross-session-message>no, that's wrong</cross-session-message>"),
            cu_with("", "<command-name>/clear</command-name><command-message>clear</command-message>"),
            cu_with("\"toolUseResult\":{\"stdout\":\"x\"},", "no, that's wrong from a tool"),
            ctext("still working"),
            cu("no, that's wrong again"),
            ctext("ok"),
            cu("fine"),
        ]
        .concat(),
    );
    let out = json_scan(&home);
    // 3 typed prompts; the notifications are not prompts and not corrections.
    assert!(out.contains("\"prompts\":3,"), "{out}");
    assert!(out.contains("\"corrections\":{\"count\":2,"), "{out}");
    // correction -> (notifications) -> correction is one repeated pair; correction -> fine is not.
    assert!(out.contains("\"after_correction\":{\"replies\":2,\"repeated\":1,"), "{out}");
}

#[test]
fn subagent_and_meta_lines_are_ignored() {
    let home = sandbox("sidechain");
    write(
        &home.join(".claude/projects/p/s.jsonl"),
        &[
            cu("start"),
            cu_with("\"isSidechain\":true,", "no, that's wrong"),
            format!("{{\"type\":\"assistant\",\"isSidechain\":true,\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"s\",\"name\":\"Bash\",\"input\":{{\"command\":\"git push --force origin main\"}}}}]}}}}\n"),
            cu_with("\"isMeta\":true,", "no, that's wrong"),
            cbash("m", "ls"),
        ]
        .concat(),
    );
    let out = json_scan(&home);
    assert!(out.contains("\"prompts\":1,\"commands\":1,"), "{out}");
    assert!(out.contains("\"flagged\":0,"), "{out}");
    assert!(out.contains("\"corrections\":{\"count\":0,"), "{out}");
}

#[test]
fn codex_context_blocks_and_tool_output_are_not_typed() {
    let home = sandbox("codex-typed");
    write(
        &home.join(".codex/sessions/2026/12/01/r.jsonl"),
        &[
            xmeta(),
            xu("<environment_context>no, that's wrong</environment_context>"),
            xu("fix the build <user_instructions>no, that's wrong, you broke it</user_instructions>"),
            xcmd("x1", "echo hi"),
            xout("x1"),
            xa("done"),
            xu("no, that's wrong"),
        ]
        .concat(),
    );
    let out = json_scan(&home);
    assert!(out.contains("\"prompts\":2,"), "{out}");
    assert!(out.contains("\"corrections\":{\"count\":1,"), "{out}");
    assert!(out.contains("\"after_other\":{\"replies\":1,\"repeated\":1,"), "{out}");
}

#[test]
fn zero_shell_commands_drop_the_tripwire_clause() {
    let home = sandbox("no-commands");
    write(&home.join(".claude/projects/p/s.jsonl"), &[cu("hello"), ctext("hi"), cu("no, that's wrong"), ctext("ok")].concat());
    let (_, share, _) = scan(&home, &["--share"]);
    assert!(!share.contains("shell commands") && !share.contains("tripwire") && !share.contains("0 of 0"), "{share}");
    assert!(share.contains("I corrected it once") && share.contains("https://github.com/koscak-labs/instinct"), "{share}");
    let (_, text, _) = scan(&home, &[]);
    assert!(text.contains("1. Risky commands: No shell commands in the window.\n"), "{text}");
    assert!(!text.contains("0 of 0") && !text.contains("None matched"), "{text}");
    // With commands the original wording stays.
    let (_, with, _) = scan(&fixture_home("with-commands"), &["--share"]);
    assert!(with.contains("3 of 5 shell commands would have drawn an Instinct tripwire warning"), "{with}");
}

#[test]
fn credentials_in_urls_and_flags_are_redacted_end_to_end() {
    let home = sandbox("creds");
    let s = [
        cu("go"),
        cbash("a", "git push --force https://alice:s3cr3tpw@github.com/o/r.git"),
        cbash("b", "mysql -psupersecret -h db && git push --force"),
        cbash("c", "git push --force --password=topsecret1"),
        cbash("d", "PGPASSWORD=pgsecret1 psql -c 'DROP TABLE users'"),
    ]
    .concat();
    write(&home.join(".claude/projects/p/s.jsonl"), &s);
    let (_, out, _) = scan(&home, &["--json"]);
    for secret in ["s3cr3tpw", "alice:", "supersecret", "topsecret1", "pgsecret1"] {
        assert!(!out.contains(secret), "{secret} leaked:\n{out}");
    }
    for shown in ["https://***@github.com", "mysql -p*** -h db", "--password=***", "PGPASSWORD=*** psql"] {
        assert!(out.contains(shown), "{shown} missing:\n{out}");
    }
}