instinct-cli 0.3.7

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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! `instinct scan [--days N] [--json] [--share]`: what did my coding agent get wrong lately, and what would
//! Instinct have caught? A read-only report over the Claude Code and Codex transcripts already on this machine.
//!
//! No network, no bank needed, nothing written. It reuses the readers of `instinct mine` (one line at a time,
//! both formats), the starter pack with the tripwire matcher, the correction detector and the memory-file token
//! estimate of `instinct audit`. Prompt and reply text is only counted, never printed; a command is shown only
//! as a redacted snippet of at most 60 characters.
use super::*;
use mine::Kind;

pub const SCAN_HELP: &str = "usage: instinct scan [--days N] [--json] [--share]\n\
What did your coding agent get wrong in the last N days (default 30), and what would Instinct have caught?\n\
Reads ~/.claude/projects/*/*.jsonl and ~/.codex/sessions/**/*.jsonl. Read-only: no network, writes nothing,\n\
needs no bank. Prompt and reply text is never printed; commands appear only as redacted 60-character snippets.\n\
  1  risky commands   shell commands the starter tripwires would have warned about, by title\n\
  2  corrections      how often you corrected the agent, and how often the next message corrected it again\n\
  3  memory files     what CLAUDE.md and AGENTS.md cost across the prompts in the window\n\
  4  next steps       runnable lines\n\
  --days N   window in days, by file modification time (default 30)\n\
  --json     the counts and the same snippets as JSON\n\
  --share    print only a short plain-text summary (at most 280 characters); it is never uploaded";

const REPO: &str = "https://github.com/koscak-labs/instinct";
const SNIPPET: usize = 60;
const EXAMPLES: usize = 3;
/// Both reply groups need this many pairs before a ratio is printed.
const MIN_FOR_RATIO: u32 = 20;

#[derive(Default, Clone)]
pub struct Group {
    pub title: String,
    pub count: u32,
    pub examples: Vec<String>,
}

#[derive(Default, Clone, Copy)]
pub struct Pairs {
    /// Agent replies that were followed by another user message.
    pub n: u32,
    /// Of those, the next user message was a correction.
    pub repeated: u32,
}

impl Pairs {
    pub fn rate(&self) -> Option<f64> {
        (self.n > 0).then(|| self.repeated as f64 / self.n as f64)
    }
}

#[derive(Default)]
pub struct Report {
    pub days: u64,
    pub files: u32,
    pub claude_files: u32,
    pub codex_files: u32,
    pub skipped_old: u32,
    pub unreadable: u32,
    pub prompts: u32,
    pub claude_prompts: u32,
    pub codex_prompts: u32,
    pub commands: u32,
    pub flagged: u32,
    pub groups: Vec<Group>,
    pub corrections: u32,
    pub after_correction: Pairs,
    pub after_other: Pairs,
    /// (file name, estimated tokens per prompt)
    pub memory: Vec<(String, usize)>,
    pub memory_tokens_in_window: u64,
    /// Part of the total that comes from the user-level files alone.
    pub memory_user_tokens: u64,
    /// Prompts per working folder seen in the window: (folder, Claude Code prompts, Codex prompts).
    pub folders: Vec<(PathBuf, u32, u32)>,
    /// Projects with their own CLAUDE.md or AGENTS.md: (path shown with ~, tokens in the window, prompts).
    pub projects: Vec<(String, u64, u32)>,
    /// How many projects had memory files (the list above is cut to the top 5).
    pub projects_with_memory: u32,
    pub starter: Option<(usize, usize)>,
}

impl Report {
    pub fn ratio(&self) -> Option<f64> {
        let (a, b) = (self.after_correction, self.after_other);
        if a.n < MIN_FOR_RATIO || b.n < MIN_FOR_RATIO {
            return None;
        }
        let base = b.rate()?;
        (base > 0.0).then(|| a.rate().unwrap_or(0.0) / base)
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum Harness {
    Claude,
    Codex,
}

// ---------------------------------------------------------------- redaction

fn secret_key(name: &str) -> bool {
    let n = name.to_lowercase();
    ["key", "token", "secret", "passw", "pwd", "credential", "auth"].iter().any(|s| n.contains(s))
}

/// A value that looks like a credential on its own: a long hex run, or a long mixed-case base64-like run.
fn token_like(v: &str) -> bool {
    let n = v.chars().count();
    let digit = v.chars().any(|c| c.is_ascii_digit());
    if n >= 16 && digit && v.chars().all(|c| c.is_ascii_hexdigit()) {
        return true;
    }
    n >= 24
        && !v.starts_with(['/', '.', '~'])
        && digit
        && v.chars().any(|c| c.is_ascii_uppercase())
        && v.chars().any(|c| c.is_ascii_lowercase())
        && v.chars().all(|c| c.is_ascii_alphanumeric() || "+/_=-".contains(c))
}

/// Anything token-like becomes `***`: the redactor of `instinct mine` first, then a second pass for what it
/// lets through on purpose (bare 16+ character hex, short `KEY=` values).
pub fn redact_snippet(cmd: &str) -> String {
    let head: String = cmd.chars().take(2000).collect();
    let first = mine::redact(&url_userinfo(&head)).0.replace("[REDACTED]", "***");
    let mut out = String::with_capacity(first.len());
    for tok in first.split_inclusive(char::is_whitespace) {
        let word = tok.trim_end();
        let ws = &tok[word.len()..];
        out.push_str(&redact_word(word));
        out.push_str(ws);
    }
    out
}

/// `scheme://user:pass@host` becomes `scheme://***@host`. The userinfo ends at the last `@` before the path,
/// a quote or whitespace; only userinfo that has a `:` (a password) is replaced.
fn url_userinfo(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(i) = rest.find("://") {
        let (head, tail) = rest.split_at(i + 3);
        out.push_str(head);
        let end = tail.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '"' | '\'' | '`')).unwrap_or(tail.len());
        match tail[..end].rfind('@').filter(|at| tail[..*at].contains(':')) {
            Some(at) => {
                out.push_str("***");
                out.push_str(&tail[at..end]);
            }
            None => out.push_str(&tail[..end]),
        }
        rest = &tail[end..];
    }
    out.push_str(rest);
    out
}

fn redact_word(word: &str) -> String {
    let edge = |c: char| matches!(c, '"' | '\'' | '`' | ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}');
    let core = word.trim_matches(edge);
    if core.is_empty() || core.contains("***") {
        return word.to_string();
    }
    let at = word.find(core).unwrap_or(0);
    // mysql -psecret: the password is glued to the flag. Compiler flags that start with -p are left alone.
    if let Some(rest) = core.strip_prefix("-p").filter(|r| !r.is_empty() && !r.starts_with('-')) {
        const FLAGS: [&str; 6] = ["edantic", "thread", "ipe", "g", "ackage", "rofile"];
        let name = core.trim_start_matches('-');
        if !FLAGS.iter().any(|s| name.strip_prefix('p') == Some(*s)) && !rest.contains('=') {
            return format!("{}-p***{}", &word[..at], &word[at + core.len()..]);
        }
    }
    let (lead, tail) = (&word[..at], &word[at + core.len()..]);
    if let Some((name, value)) = core.split_once('=') {
        let named = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
        if (named && secret_key(name) && !value.is_empty()) || token_like(value.trim_matches(edge)) {
            return format!("{lead}{name}=***{tail}");
        }
        return word.to_string();
    }
    if token_like(core) {
        return format!("{lead}***{tail}");
    }
    word.to_string()
}

/// The text shown for a command: redacted first, then cut to 60 characters.
pub fn snippet(cmd: &str) -> String {
    mine::clip(&redact_snippet(cmd), SNIPPET)
}

// ---------------------------------------------------------------- scanning

/// Where transcripts live: (folder, harness). The Claude Code folder holds one folder per project.
pub(crate) fn roots() -> Vec<(PathBuf, Harness)> {
    outcomes::default_roots()
        .into_iter()
        .filter_map(|r| match r.file_name().and_then(|n| n.to_str()) {
            Some("projects") => Some((r, Harness::Claude)),
            Some("sessions") => Some((r, Harness::Codex)),
            _ => None,
        })
        .collect()
}

pub(crate) fn modified_secs(p: &Path) -> Option<u64> {
    fs::metadata(p).and_then(|m| m.modified()).ok()?.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs())
}

pub(crate) fn files_in(root: &Path, harness: Harness) -> Vec<PathBuf> {
    let mut out = Vec::new();
    match harness {
        Harness::Claude => {
            // one .jsonl per session; sub-agent logs sit deeper and are skipped, as in `instinct mine`
            let Ok(rd) = fs::read_dir(root) else { return out };
            for d in rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
                if let Ok(files) = fs::read_dir(&d) {
                    out.extend(files.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "jsonl")));
                }
            }
        }
        Harness::Codex => mine::collect(root, &mut out, 1),
    }
    out.sort();
    out
}

struct Matcher {
    title: String,
    tags: String,
}

fn matchers() -> Vec<Matcher> {
    starter::pack_matchers()
        .into_iter()
        .filter(|(_, tags)| tripwire::has_cmd(tags))
        .map(|(title, tags)| Matcher { title, tags })
        .collect()
}

/// The title of the tripwire that would have fired for this command: the best match, first on a tie.
fn tripwire_title<'a>(ms: &'a [Matcher], cmd: &str) -> Option<&'a str> {
    let w = tripwire::words(cmd);
    let mut best: Option<(usize, &str)> = None;
    for m in ms {
        if let Some(n) = tripwire::best_match(&m.tags, &w) {
            if best.is_none_or(|(b, _)| n > b) {
                best = Some((n, &m.title));
            }
        }
    }
    best.map(|(_, t)| t)
}

fn shell_command(e: &mine::Ev, harness: Harness) -> Option<&str> {
    let c = e.cmd.trim();
    if c.is_empty() || e.kind != Kind::ToolUse {
        return None;
    }
    // Claude Code: only the Bash tool runs shell. Codex: every function call that carries a command does.
    (harness == Harness::Codex || e.text == "Bash").then_some(c)
}

/// Scans the given transcript folders. `since` is the oldest modification time (unix seconds) a file may have.
pub fn scan(roots: &[(PathBuf, Harness)], days: u64, since: u64) -> Report {
    let mut r = Report { days, ..Default::default() };
    let ms = matchers();
    let mut folders: Vec<(PathBuf, u32, u32)> = Vec::new();
    let mut groups: Vec<Group> = Vec::new();
    for (root, harness) in roots {
        for path in files_in(root, *harness) {
            if modified_secs(&path).is_none_or(|m| m < since) {
                r.skipped_old += 1;
                continue;
            }
            let Ok(evs) = mine::read_events_with(&path, true) else {
                r.unreadable += 1;
                continue;
            };
            r.files += 1;
            match harness {
                Harness::Claude => r.claude_files += 1,
                Harness::Codex => r.codex_files += 1,
            }
            // (was the last user message a correction, has the agent acted since)
            let mut last: Option<(bool, bool)> = None;
            let mut file_prompts = 0u32;
            for e in &evs {
                match e.kind {
                    Kind::User => {
                        let corr = corrections::correction(&e.text);
                        r.prompts += 1;
                        file_prompts += 1;
                        match harness {
                            Harness::Claude => r.claude_prompts += 1,
                            Harness::Codex => r.codex_prompts += 1,
                        }
                        if corr {
                            r.corrections += 1;
                        }
                        if let Some((prev, true)) = last {
                            let p = if prev { &mut r.after_correction } else { &mut r.after_other };
                            p.n += 1;
                            p.repeated += corr as u32;
                        }
                        last = Some((corr, false));
                    }
                    Kind::Assistant | Kind::ToolUse => {
                        if let Some((_, acted)) = last.as_mut() {
                            *acted = true;
                        }
                        if let Some(cmd) = shell_command(e, *harness) {
                            r.commands += 1;
                            if let Some(title) = tripwire_title(&ms, cmd) {
                                r.flagged += 1;
                                let i = groups.iter().position(|g| g.title == title).unwrap_or_else(|| {
                                    groups.push(Group { title: title.to_string(), ..Default::default() });
                                    groups.len() - 1
                                });
                                let g = &mut groups[i];
                                g.count += 1;
                                if g.examples.len() < EXAMPLES {
                                    let s = snippet(cmd);
                                    if !g.examples.contains(&s) {
                                        g.examples.push(s);
                                    }
                                }
                            }
                        }
                    }
                    Kind::ToolResult => {}
                }
            }
            if let Some(cwd) = file_cwd(&path) {
                let i = folders.iter().position(|f| same_dir(&f.0, &cwd)).unwrap_or_else(|| {
                    folders.push((cwd, 0, 0));
                    folders.len() - 1
                });
                match harness {
                    Harness::Claude => folders[i].1 += file_prompts,
                    Harness::Codex => folders[i].2 += file_prompts,
                }
            }
        }
    }
    for (cwd, claude, codex) in &folders {
        r.folders.push((cwd.clone(), *claude, *codex));
    }
    groups.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.title.cmp(&b.title)));
    r.groups = groups;
    r
}

/// Memory files at user level, per harness: (name, bytes). Project files are not guessed at.
fn memory_files() -> Vec<(Harness, String, usize)> {
    let home = home_dir();
    let mut out = Vec::new();
    for (root, harness) in roots() {
        let (name, dir) = match harness {
            Harness::Claude => ("CLAUDE.md", root.parent().map(Path::to_path_buf)),
            Harness::Codex => ("AGENTS.md", root.parent().map(Path::to_path_buf)),
        };
        let mut candidates: Vec<PathBuf> = dir.into_iter().map(|d| d.join(name)).collect();
        candidates.extend(home.iter().map(|h| h.join(name)));
        candidates.dedup();
        for c in candidates {
            if let Ok(m) = fs::metadata(&c) {
                if m.is_file() {
                    out.push((harness, name.to_string(), m.len() as usize));
                }
            }
        }
    }
    out
}

/// The working folder a transcript was recorded in: Claude Code lines carry `cwd`, Codex puts it in the
/// `session_meta` payload. Only the first lines are read.
fn file_cwd(path: &Path) -> Option<PathBuf> {
    let file = fs::File::open(path).ok()?;
    let mut reader = std::io::BufReader::new(file);
    let mut buf = Vec::new();
    for _ in 0..60 {
        buf.clear();
        if reader.read_until(b'\n', &mut buf).ok()? == 0 {
            break;
        }
        let line = String::from_utf8_lossy(&buf);
        if !line.contains("\"cwd\"") {
            continue;
        }
        let Ok(j) = parse_json(line.trim()) else { continue };
        let found = j
            .get("cwd")
            .or_else(|| j.get("payload").and_then(|p| p.get("cwd")))
            .and_then(Json::as_str)
            .filter(|c| !c.is_empty());
        if let Some(c) = found {
            return Some(PathBuf::from(c));
        }
    }
    None
}

/// The user's home folder: `USERPROFILE` on Windows, `HOME` elsewhere (each falls back to the other).
fn home_dir() -> Option<PathBuf> {
    let (first, second) = if cfg!(windows) { ("USERPROFILE", "HOME") } else { ("HOME", "USERPROFILE") };
    std::env::var_os(first)
        .filter(|v| !v.is_empty())
        .or_else(|| std::env::var_os(second).filter(|v| !v.is_empty()))
        .map(PathBuf::from)
}

/// Same folder? Windows paths differ only by case or by a trailing separator without meaning a different folder.
fn same_dir(a: &Path, b: &Path) -> bool {
    if cfg!(windows) {
        let n = |p: &Path| p.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase();
        n(a) == n(b)
    } else {
        a == b
    }
}

/// `/home/me/proj` shown as `~/proj`, with `/` between parts on every platform.
fn tilde(p: &Path, home: Option<&Path>) -> String {
    let rest = home.and_then(|h| {
        if same_dir(p, h) {
            return Some(PathBuf::new());
        }
        // Windows compares case-insensitively: peel the home components off one by one.
        let (mut pc, mut hc) = (p.components(), h.components());
        loop {
            let Some(a) = hc.next() else { return Some(pc.as_path().to_path_buf()) };
            match pc.next() {
                Some(b) if same_dir(Path::new(a.as_os_str()), Path::new(b.as_os_str())) => {}
                _ => return None,
            }
        }
    });
    match rest {
        Some(r) if r.as_os_str().is_empty() => "~".to_string(),
        Some(r) => {
            let parts: Vec<String> = r.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
            format!("~/{}", parts.join("/"))
        }
        None => p.display().to_string(),
    }
}

fn add_memory_cost(r: &mut Report) {
    for (harness, name, bytes) in memory_files() {
        let tokens = audit::tokens_of(bytes);
        let prompts = if harness == Harness::Claude { r.claude_prompts } else { r.codex_prompts };
        r.memory_tokens_in_window += tokens as u64 * prompts as u64;
        r.memory.push((name, tokens));
    }
    r.memory_user_tokens = r.memory_tokens_in_window;
    // Project files: CLAUDE.md for the Claude Code prompts and AGENTS.md for the Codex prompts of each folder
    // that still exists. The home folder itself is already counted above.
    let home = home_dir();
    let mut projects: Vec<(String, u64, u32)> = Vec::new();
    for (cwd, claude, codex) in &r.folders {
        if !cwd.is_dir() || home.as_ref().is_some_and(|h| same_dir(h, cwd)) {
            continue;
        }
        let size = |name: &str| fs::metadata(cwd.join(name)).ok().filter(|m| m.is_file()).map(|m| audit::tokens_of(m.len() as usize) as u64);
        let total = size("CLAUDE.md").unwrap_or(0) * *claude as u64 + size("AGENTS.md").unwrap_or(0) * *codex as u64;
        if total > 0 {
            projects.push((tilde(cwd, home.as_deref()), total, claude + codex));
        }
    }
    projects.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    r.projects_with_memory = projects.len() as u32;
    r.memory_tokens_in_window += projects.iter().map(|p| p.1).sum::<u64>();
    projects.truncate(5);
    r.projects = projects;
}

// ---------------------------------------------------------------- output

fn commas(n: u64) -> String {
    let s = n.to_string();
    let mut out = String::new();
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

/// `1 prompt`, `2 prompts`, `1,204 prompts`.
fn noun(n: u64, one: &str, many: &str) -> String {
    format!("{} {}", commas(n), if n == 1 { one } else { many })
}

/// `once`, `twice`, `3 times`.
fn times(n: u32) -> String {
    match n {
        1 => "once".to_string(),
        2 => "twice".to_string(),
        n => format!("{} times", commas(n as u64)),
    }
}

/// `day` or `30 days`, for "the last ...".
fn span(days: u64) -> String {
    if days == 1 { "day".to_string() } else { format!("{days} days") }
}

fn pct(x: Option<f64>) -> String {
    x.map_or("n/a".to_string(), |v| format!("{:.1}%", v * 100.0))
}

/// At most 280 characters, plain text, headline numbers and the repo link.
pub fn share_text(r: &Report) -> String {
    let mut s = if r.commands == 0 {
        format!("My coding agent, last {}: I corrected it {}", span(r.days), times(r.corrections))
    } else {
        format!(
            "My coding agent, last {}: {} of {} would have drawn an Instinct tripwire warning; I corrected it {}",
            span(r.days), r.flagged, noun(r.commands as u64, "shell command", "shell commands"), times(r.corrections)
        )
    };
    // Posted publicly, so it carries counts only. The repeat rates depend on how many corrections the detector
    // catches, and on real sessions that is a floor, so they stay in the report with that caveat.
    s.push_str(&format!(". `instinct scan` {REPO}"));
    if s.chars().count() > 280 {
        s = format!("Coding agent, last {}: {}, {}. `instinct scan` {REPO}", span(r.days), noun(r.flagged as u64, "risky command", "risky commands"), noun(r.corrections as u64, "correction", "corrections"));
    }
    s.chars().take(280).collect()
}

fn next_steps(r: &Report) -> Vec<String> {
    let mut v = Vec::new();
    match r.starter {
        Some((all, have)) if have >= all => v.push(format!(
            "Your bank already holds all {all} starter tripwires; `instinct doctor` checks the hooks that deliver them."
        )),
        Some((all, have)) => v.push(format!(
            "Your bank holds {have} of {all} starter tripwires: `instinct starter --apply` adds the rest."
        )),
        None => v.push("No bank yet: `instinct starter --apply` banks the starter tripwires (run `instinct starter` first to read them).".into()),
    }
    if r.corrections > 0 {
        v.push(format!("`instinct mine --since {}d` turns your corrections into lesson candidates (a dry run).", r.days));
    }
    if r.memory_tokens_in_window > 0 {
        v.push("`instinct audit ~/.claude/CLAUDE.md` grades the memory file and measures the same rules behind Instinct.".into());
    }
    v.truncate(3);
    v
}

pub fn render_text(r: &Report, secs: f64) -> String {
    let mut o = String::new();
    o.push_str(&format!("instinct scan: the last {} (read-only, nothing leaves this machine)\n", span(r.days)));
    if r.files == 0 {
        o.push_str(&format!(
            "\nNo Claude Code or Codex transcripts changed in the last {} (looked in ~/.claude/projects and ~/.codex/sessions).\n\
Nothing to report. Run it again after a few sessions, or widen the window with --days.\n",
            span(r.days)
        ));
        o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
        return o;
    }
    o.push_str(&format!(
        "Read {} ({} Claude Code, {} Codex): {}, {}.\n",
        noun(r.files as u64, "transcript", "transcripts"),
        r.claude_files,
        r.codex_files,
        noun(r.prompts as u64, "prompt", "prompts"),
        noun(r.commands as u64, "shell command", "shell commands")
    ));
    if r.commands == 0 {
        o.push_str("\n1. Risky commands: No shell commands in the window.\n");
    } else {
        o.push_str(&format!("\n1. Risky commands: {} of {} would have drawn a tripwire warning\n", r.flagged, commas(r.commands as u64)));
    }
    if r.commands > 0 && r.groups.is_empty() {
        o.push_str("   None matched the starter tripwires.\n");
    }
    for g in &r.groups {
        o.push_str(&format!("   {:>4}  {}\n", g.count, g.title));
        for e in &g.examples {
            o.push_str(&format!("          {e}\n"));
        }
    }
    o.push_str(&format!(
        "\n2. Corrections: {} of {} told the agent it went wrong ({})\n",
        r.corrections,
        noun(r.prompts as u64, "prompt", "prompts"),
        pct(if r.prompts > 0 { Some(r.corrections as f64 / r.prompts as f64) } else { None })
    ));
    let (a, b) = (r.after_correction, r.after_other);
    o.push_str(&format!(
        "   Next message corrected again, after a correction:  {}/{}  {}\n",
        a.repeated, a.n, pct(a.rate())
    ));
    o.push_str(&format!(
        "   Next message corrected, after any other message:   {}/{}  {}\n",
        b.repeated, b.n, pct(b.rate())
    ));
    match r.ratio() {
        Some(x) => o.push_str(&format!("   Ratio: {x:.1}x more likely to be corrected again right after a correction.\n")),
        None => o.push_str(&format!("   No ratio yet: it needs at least {MIN_FOR_RATIO} reply pairs in each group.\n")),
    }
    o.push_str("   Only clear corrections are counted, so these numbers are a floor, not a measurement.\n");
    o.push_str("\n3. Memory files\n");
    if r.memory.is_empty() && r.projects.is_empty() {
        o.push_str("   No CLAUDE.md or AGENTS.md at user level or in the project folders of these sessions.\n");
    } else {
        for (name, t) in &r.memory {
            o.push_str(&format!("   {name} (user level): about {} on every prompt\n", noun(*t as u64, "token", "tokens")));
        }
        if !r.memory.is_empty() {
            o.push_str(&format!(
                "   User-level files across {} ({} Claude Code, {} Codex): about {}.\n",
                noun(r.prompts as u64, "prompt", "prompts"),
                commas(r.claude_prompts as u64),
                commas(r.codex_prompts as u64),
                noun(r.memory_user_tokens, "token", "tokens")
            ));
        }
        if !r.projects.is_empty() {
            o.push_str(&format!(
                "   Project files, top {} of {} (tokens x that project's prompts):\n",
                r.projects.len(),
                noun(r.projects_with_memory as u64, "project", "projects")
            ));
            for (path, tokens, prompts) in &r.projects {
                o.push_str(&format!("   {:>10}  {path} ({})\n", commas(*tokens), noun(*prompts as u64, "prompt", "prompts")));
            }
        }
        o.push_str(&format!(
            "   Overall: about {} of memory files sent in the window (an estimate, bytes / 4).\n",
            noun(r.memory_tokens_in_window, "token", "tokens")
        ));
    }
    o.push_str("\n4. Next steps\n");
    for l in next_steps(r) {
        o.push_str(&format!("   {l}\n"));
    }
    if r.skipped_old > 0 || r.unreadable > 0 {
        o.push_str(&format!(
            "\n({} skipped as older than the window, {} unreadable)\n",
            noun(r.skipped_old as u64, "file", "files"),
            r.unreadable
        ));
    }
    o.push_str(&format!("\nScanned in {secs:.1} s. Nothing was written or uploaded.\n"));
    o
}

fn f(x: Option<f64>) -> String {
    x.map_or("null".to_string(), |v| format!("{v:.4}"))
}

pub fn render_json(r: &Report, secs: f64) -> String {
    let groups: Vec<String> = r
        .groups
        .iter()
        .map(|g| {
            let ex: Vec<String> = g.examples.iter().map(|e| format!("\"{}\"", escape_json(e))).collect();
            format!("{{\"title\":\"{}\",\"count\":{},\"examples\":[{}]}}", escape_json(&g.title), g.count, ex.join(","))
        })
        .collect();
    let pairs = |p: Pairs| format!("{{\"replies\":{},\"repeated\":{},\"rate\":{}}}", p.n, p.repeated, f(p.rate()));
    let mem: Vec<String> =
        r.memory.iter().map(|(n, t)| format!("{{\"file\":\"{}\",\"tokens_per_prompt\":{t}}}", escape_json(n))).collect();
    let proj: Vec<String> = r
        .projects
        .iter()
        .map(|(p, t, n)| format!("{{\"path\":\"{}\",\"tokens_in_window\":{t},\"prompts\":{n}}}", escape_json(p)))
        .collect();
    let next: Vec<String> = next_steps(r).iter().map(|l| format!("\"{}\"", escape_json(l))).collect();
    format!(
        "{{\"days\":{},\"files\":{{\"scanned\":{},\"claude_code\":{},\"codex\":{},\"skipped_old\":{},\"unreadable\":{}}},\
\"prompts\":{},\"commands\":{},\
\"risky\":{{\"flagged\":{},\"groups\":[{}]}},\
\"corrections\":{{\"count\":{},\"after_correction\":{},\"after_other\":{},\"ratio\":{}}},\
\"memory\":{{\"files\":[{}],\"user_tokens_in_window\":{},\"projects_with_memory\":{},\"top_projects\":[{}],\"tokens_in_window\":{}}},\
\"next\":[{}],\"share\":\"{}\",\"elapsed_ms\":{}}}",
        r.days,
        r.files,
        r.claude_files,
        r.codex_files,
        r.skipped_old,
        r.unreadable,
        r.prompts,
        r.commands,
        r.flagged,
        groups.join(","),
        r.corrections,
        pairs(r.after_correction),
        pairs(r.after_other),
        f(r.ratio()),
        mem.join(","),
        r.memory_user_tokens,
        r.projects_with_memory,
        proj.join(","),
        r.memory_tokens_in_window,
        next.join(","),
        escape_json(&share_text(r)),
        (secs * 1000.0).round() as u64
    )
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let (mut days, mut json, mut share) = (30u64, false, false);
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--json" => json = true,
            "--share" => share = true,
            "--days" => {
                days = it
                    .next()
                    .and_then(|v| v.parse().ok())
                    .filter(|d| *d > 0)
                    .ok_or("scan: --days needs a whole number of days, 1 or more")?
            }
            "--help" | "-h" => {
                println!("{SCAN_HELP}");
                return Ok(());
            }
            other => return Err(format!("scan: unknown argument {other}\n\n{SCAN_HELP}")),
        }
    }
    let started = std::time::Instant::now();
    let since = now_secs().saturating_sub(days.saturating_mul(86_400));
    let mut r = scan(&roots(), days, since);
    add_memory_cost(&mut r);
    r.starter = starter::banked_in_default();
    let secs = started.elapsed().as_secs_f64();
    if json {
        println!("{}", render_json(&r, secs));
    } else if share {
        println!("{}", share_text(&r));
    } else {
        print!("{}", render_text(&r, secs));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redaction_hides_tokens_and_keeps_commands() {
        let s = redact_snippet("curl -H 'Authorization: Bearer abcdef0123456789abcdef' https://x.test");
        assert!(!s.contains("abcdef0123456789abcdef"), "{s}");
        let s = redact_snippet("API_KEY=abc deploy.sh");
        assert_eq!(s, "API_KEY=*** deploy.sh");
        let s = redact_snippet("export GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789");
        assert!(s.contains("GITHUB_TOKEN=***") && !s.contains("ghp_"), "{s}");
        let s = redact_snippet("docker login -p sk-abcdefghijklmnopqrstuv");
        assert!(!s.contains("sk-abc"), "{s}");
        let s = redact_snippet("git checkout 3f2a9c1d4b5e6f708192a3b4c5d6e7f801234567");
        assert_eq!(s, "git checkout ***");
        let s = redact_snippet("echo QUtJQTEyMzQ1Njc4OTBhYmNkZWZnaGlqa2xt");
        assert_eq!(s, "echo ***");
        assert_eq!(redact_snippet("rm -rf ./target/debug/build-output"), "rm -rf ./target/debug/build-output");
        assert_eq!(redact_snippet("cargo build --release --locked"), "cargo build --release --locked");
    }

    #[test]
    fn url_credentials_become_stars() {
        assert_eq!(redact_snippet("git clone https://alice:s3cr3t@github.com/o/r.git"), "git clone https://***@github.com/o/r.git");
        assert_eq!(redact_snippet("psql postgres://app:hunter22@db.internal:5432/prod"), "psql postgres://***@db.internal:5432/prod");
        assert_eq!(redact_snippet("curl http://a:b@h1/x https://c:d@h2/y"), "curl http://***@h1/x https://***@h2/y");
        assert_eq!(redact_snippet("curl 'https://u:p@host.test/a?b=c'"), "curl 'https://***@host.test/a?b=c'");
        // a password containing @ ends at the last @ before the path
        assert_eq!(redact_snippet("git fetch https://u:p@ss@host.test/r"), "git fetch https://***@host.test/r");
        // no password: nothing to hide, left as it is
        assert_eq!(redact_snippet("git clone ssh://git@github.com/o/r.git"), "git clone ssh://git@github.com/o/r.git");
        assert_eq!(redact_snippet("curl https://example.com/a@b:c"), "curl https://example.com/a@b:c");
    }

    #[test]
    fn password_flags_and_variables_become_stars() {
        assert_eq!(redact_snippet("mysql -psupersecret -h db"), "mysql -p*** -h db");
        assert_eq!(redact_snippet("mysql -u root --password=topsecret1 db"), "mysql -u root --password=*** db");
        assert_eq!(redact_snippet("PGPASSWORD=pgsecret1 psql -c 'select 1'"), "PGPASSWORD=*** psql -c 'select 1'");
        assert_eq!(redact_snippet("MYSQL_PWD=abcd1234 mysqldump db"), "MYSQL_PWD=*** mysqldump db");
        // compiler flags and an ordinary -p with a separate argument are not passwords
        assert_eq!(redact_snippet("gcc -pedantic -pthread -pipe -o a a.c"), "gcc -pedantic -pthread -pipe -o a a.c");
        assert_eq!(redact_snippet("cargo test -p instinct-cli"), "cargo test -p instinct-cli");
        assert_eq!(redact_snippet("mkdir -p a/b"), "mkdir -p a/b");
    }

    #[test]
    fn snippet_is_at_most_60_chars() {
        let s = snippet(&format!("git push --force {}", "origin/very-long-branch-name-".repeat(5)));
        assert!(s.chars().count() <= SNIPPET, "{s}");
        assert!(s.starts_with("git push --force"));
    }

    #[test]
    fn share_fits_280_even_with_huge_numbers() {
        let r = Report {
            days: 3650,
            commands: u32::MAX,
            flagged: u32::MAX,
            corrections: u32::MAX,
            after_correction: Pairs { n: u32::MAX, repeated: u32::MAX },
            after_other: Pairs { n: u32::MAX, repeated: u32::MAX },
            ..Default::default()
        };
        let s = share_text(&r);
        assert!(s.chars().count() <= 280, "{} {s}", s.chars().count());
        assert!(s.contains(REPO));
    }

    #[test]
    fn ratio_needs_twenty_each() {
        let mut r = Report {
            after_correction: Pairs { n: 19, repeated: 10 },
            after_other: Pairs { n: 100, repeated: 10 },
            ..Default::default()
        };
        assert!(r.ratio().is_none());
        r.after_correction = Pairs { n: 20, repeated: 10 };
        assert!((r.ratio().unwrap() - 5.0).abs() < 1e-9);
    }
}