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
//! `instinct audit FILE...` and `instinct import FILE... [--project P] [--apply]`.
//!
//! Memory files (CLAUDE.md, AGENTS.md, .cursorrules) are pasted into every prompt. `audit` grades what that
//! costs and measures what the same rules would cost behind Instinct's lookup; `import` turns each rule
//! into a lesson. Both share one parser. Lookups use lexical (BM25) recall only, so the numbers do not
//! depend on an embedding service.
use super::*;

/// Grade thresholds on estimated tokens added to every prompt: (inclusive upper bound, letter).
const GRADES: [(usize, &str); 4] = [(400, "A"), (1000, "B"), (2500, "C"), (5000, "D")];
const GRADE_HELP: &str = "grade by tokens added to every prompt: A <= 400, B <= 1000, C <= 2500, D <= 5000, F above 5000";

pub const AUDIT_HELP: &str = "usage: instinct audit [FILE...] [--share] [--json]\n\
With no FILE: audits whichever of CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules and .github/copilot-instructions.md exist here.\n\
Grades memory files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules): bytes, estimated tokens added to every prompt\n\
(about 4 bytes per token), rules, sections, tokens per 100 prompts. Then imports the rules into a temporary\n\
bank and measures lookups: the mean bytes one lookup adds, and how often unrelated questions get nothing.\n\
Nothing is written outside a temporary directory.\n\
  --share  print one line you could post\n\
  --json   print the numbers as JSON\n\
  --k N    lessons a lookup returns (default 1, what the prompt hook hands over)\n\
grade by tokens added to every prompt: A <= 400, B <= 1000, C <= 2500, D <= 5000, F above 5000";

pub const IMPORT_HELP: &str = "usage: instinct import FILE... [--project P] [--apply]\n\
Turns each rule (bullet, numbered item or rule line) into a lesson: title from the first words,\n\
when = section heading + rule text, found = how = the rule, evidence = \"Imported from FILE line N\",\n\
tags from the heading. Code blocks, blank lines and pure headings are skipped.\n\
Dry run by default; --apply banks into the default bank (INSTINCT_STORE overrides). Importing the same file again adds nothing.";

/// Memory files `instinct audit` looks for in the current folder when no FILE is given.
const MEMORY_FILES: [&str; 5] = [
    "CLAUDE.md",
    "AGENTS.md",
    "GEMINI.md",
    ".cursorrules",
    ".github/copilot-instructions.md",
];

/// Questions with no connection to a coding-agent memory file.
const CONTROLS: [&str; 5] = [
    "how long should sourdough bread proof overnight",
    "best month to visit Lisbon for warm weather",
    "translate good morning into Japanese",
    "boiling point of liquid nitrogen in kelvin",
    "which hiking boots stay dry in heavy rain",
];

#[derive(Debug, Clone, PartialEq)]
pub struct Rule {
    pub heading: String,
    pub text: String,
    pub line: usize,
}

#[derive(Debug, Default, PartialEq)]
pub struct Parsed {
    pub rules: Vec<Rule>,
    pub sections: usize,
}

fn bullet_body(line: &str) -> Option<&str> {
    let t = line.trim_start();
    for m in ["- ", "* ", "+ "] {
        if let Some(r) = t.strip_prefix(m) {
            return Some(r);
        }
    }
    let digits = t.bytes().take_while(u8::is_ascii_digit).count();
    if digits > 0 && digits < t.len() {
        let rest = &t[digits..];
        for m in [". ", ") "] {
            if let Some(r) = rest.strip_prefix(m) {
                return Some(r);
            }
        }
    }
    None
}

fn clean_rule(s: &str) -> String {
    let s = s.trim();
    let s = ["[ ] ", "[x] ", "[X] "]
        .iter()
        .find_map(|p| s.strip_prefix(p))
        .unwrap_or(s);
    s.trim().to_string()
}

fn flush(cur: &mut Option<Rule>, out: &mut Parsed) {
    if let Some(r) = cur.take() {
        if !r.text.is_empty() {
            out.rules.push(r);
        }
    }
}

/// Parse markdown or plain rule lines. Skips front matter, code fences, blank lines, pure headings,
/// tables, rules and comments. A bullet's indented follow-on lines belong to it.
pub fn parse(text: &str) -> Parsed {
    let mut out = Parsed::default();
    let mut heading = String::new();
    let mut fence = false;
    let mut cur: Option<Rule> = None;
    let lines: Vec<&str> = text.lines().collect();
    let mut start = 0;
    if lines.first().map(|l| l.trim_end()) == Some("---") {
        if let Some(end) = lines.iter().skip(1).position(|l| l.trim_end() == "---") {
            start = end + 2;
        }
    }
    for (i, raw) in lines.iter().enumerate().skip(start) {
        let line = raw.trim_end();
        let t = line.trim_start();
        if t.starts_with("```") || t.starts_with("~~~") {
            flush(&mut cur, &mut out);
            fence = !fence;
            continue;
        }
        if fence {
            continue;
        }
        if t.is_empty() {
            flush(&mut cur, &mut out);
            continue;
        }
        let hashes = t.bytes().take_while(|b| *b == b'#').count();
        if (1..=6).contains(&hashes) && t[hashes..].starts_with(' ') && line.len() == t.len() {
            flush(&mut cur, &mut out);
            let h = t[hashes..].trim().trim_end_matches('#').trim();
            if !h.is_empty() {
                heading = h.to_string();
                out.sections += 1;
            }
            continue;
        }
        if let Some(body) = bullet_body(line) {
            flush(&mut cur, &mut out);
            cur = Some(Rule {
                heading: heading.clone(),
                text: clean_rule(body),
                line: i + 1,
            });
            continue;
        }
        let indented = line.len() - t.len() >= 2;
        if indented {
            if let Some(r) = cur.as_mut() {
                r.text.push(' ');
                r.text.push_str(t);
                continue;
            }
        }
        flush(&mut cur, &mut out);
        let body = t.strip_prefix("> ").unwrap_or(t).trim();
        let noise = body.starts_with('|')
            || body.starts_with("<!--")
            || body.starts_with("-->")
            || body.chars().all(|c| matches!(c, '-' | '=' | '*' | '_' | ' '));
        if !noise && body.split_whitespace().count() >= 3 {
            cur = Some(Rule {
                heading: heading.clone(),
                text: body.to_string(),
                line: i + 1,
            });
        }
    }
    flush(&mut cur, &mut out);
    out
}

fn plain(s: &str) -> String {
    s.chars().filter(|c| !matches!(c, '*' | '`' | '_')).collect()
}

fn title_of(text: &str) -> String {
    let t = plain(text);
    let mut title = String::new();
    for w in t.split_whitespace().take(8) {
        if !title.is_empty() && title.len() + 1 + w.len() > 60 {
            break;
        }
        if !title.is_empty() {
            title.push(' ');
        }
        title.push_str(w);
    }
    title.trim_end_matches([',', ';', ':', '.']).to_string()
}

fn tags_of(heading: &str) -> String {
    const STOP: [&str; 8] = ["the", "and", "for", "with", "when", "this", "that", "your"];
    let mut tags: Vec<String> = Vec::new();
    for w in plain(heading).split(|c: char| !c.is_alphanumeric()) {
        let w = w.to_lowercase();
        if w.chars().count() >= 3 && !STOP.contains(&w.as_str()) && !tags.contains(&w) {
            tags.push(w);
        }
    }
    tags.truncate(4);
    tags.join(",")
}

pub fn lesson(rule: &Rule, file: &str, project: &str) -> BankIn {
    let when = if rule.heading.is_empty() {
        rule.text.clone()
    } else {
        format!("{}: {}", rule.heading, rule.text)
    };
    BankIn {
        title: title_of(&rule.text),
        when,
        found: rule.text.clone(),
        how: rule.text.clone(),
        evidence: format!("Imported from {file} line {}", rule.line),
        reconsider: String::new(),
        tags: tags_of(&rule.heading),
        project: project.to_string(),
        persona: String::new(),
        applicability_harness: String::new(),
        applicability_version: String::new(),
        applicability_machine: None,
    }
}

// ---------------------------------------------------------------- CLI plumbing

struct Opts {
    files: Vec<String>,
    share: bool,
    json: bool,
    apply: bool,
    help: bool,
    project: String,
    k: usize,
}

/// Own parser: the shared one would let `--share FILE` swallow the file as the switch's value.
fn opts(argv: &[String]) -> Result<Opts, String> {
    let mut o = Opts {
        files: Vec::new(),
        share: false,
        json: false,
        apply: false,
        help: false,
        project: String::new(),
        k: 1,
    };
    let mut i = 0;
    while i < argv.len() {
        let a = argv[i].as_str();
        match a {
            "--share" => o.share = true,
            "--json" => o.json = true,
            "--apply" => o.apply = true,
            "--help" | "-h" => o.help = true,
            "--project" => {
                i += 1;
                o.project = argv.get(i).ok_or("--project needs a value")?.clone();
            }
            "--k" => {
                i += 1;
                o.k = argv.get(i).and_then(|v| v.parse().ok()).filter(|n: &usize| *n >= 1).ok_or("--k needs a number of 1 or more")?;
            }
            _ if a.starts_with("--project=") => o.project = a["--project=".len()..].to_string(),
            _ if a.starts_with("--") => return Err(format!("unknown option {a}")),
            _ => o.files.push(a.to_string()),
        }
        i += 1;
    }
    Ok(o)
}

struct Source {
    name: String,
    bytes: usize,
    parsed: Parsed,
}

fn read_sources(files: &[String]) -> Result<Vec<Source>, String> {
    if files.is_empty() {
        return Err("no FILE given".into());
    }
    files
        .iter()
        .map(|f| {
            let raw = fs::read(f).map_err(|e| format!("{f}: {e}"))?;
            if raw.iter().all(|b| b.is_ascii_whitespace()) {
                return Err(format!("{f}: file is empty"));
            }
            let bytes = raw.len();
            let text = String::from_utf8(raw).map_err(|_| format!("{f}: not UTF-8 text"))?;
            Ok(Source {
                name: f.clone(),
                bytes,
                parsed: parse(&text),
            })
        })
        .collect()
}

// ---------------------------------------------------------------- import

pub fn run_import(argv: &[String]) -> Result<(), String> {
    let o = opts(argv)?;
    if o.help {
        println!("{IMPORT_HELP}");
        return Ok(());
    }
    let sources = read_sources(&o.files)?;
    let env_store = super::default_store().ok();
    if o.apply {
        match &env_store {
            Some(p) if std::env::var_os("INSTINCT_STORE").map_or(true, |v| v.is_empty()) => super::ensure_default_dir(p)?,
            Some(_) => {}
            None => return Err("no home directory found: --apply needs a bank; set INSTINCT_STORE".into()),
        }
    }
    let existing: HashSet<String> = match &env_store {
        Some(p) if p.is_file() => load(p)?.into_iter().map(|d| d.id).collect(),
        _ => HashSet::new(),
    };
    let scope = eligibility::Scope {
        project: o.project.clone(),
        ..Default::default()
    };
    let (mut new, mut dup) = (0, 0);
    let mut seen: HashSet<String> = HashSet::new();
    for s in &sources {
        println!(
            "{}: {} rule(s) in {} section(s){}",
            s.name,
            s.parsed.rules.len(),
            s.parsed.sections,
            if o.apply { "" } else { " (dry run, add --apply to bank)" }
        );
        for r in &s.parsed.rules {
            let d = bank_discovery(lesson(r, &s.name, &o.project), &scope)?;
            let known = existing.contains(&d.id) || !seen.insert(d.id.clone());
            if known {
                dup += 1;
            } else {
                new += 1;
            }
            println!(
                "  {}  line {:<4} {}  [{}]",
                d.id,
                r.line,
                d.title,
                if known { "already banked" } else { "new" }
            );
            if o.apply && !known {
                let msg = op_bank(
                    env_store.as_ref().expect("apply has a store"),
                    lesson(r, &s.name, &o.project),
                )?;
                if !msg.starts_with("banked") {
                    return Err(format!("unexpected bank result: {msg}"));
                }
            }
        }
    }
    println!(
        "{} {new} new, {dup} already banked",
        if o.apply { "banked:" } else { "would bank:" },
    );
    Ok(())
}

// ---------------------------------------------------------------- audit

pub fn tokens_of(bytes: usize) -> usize {
    bytes.div_ceil(4)
}

pub fn grade(tokens: usize) -> &'static str {
    GRADES
        .iter()
        .find(|(max, _)| tokens <= *max)
        .map(|(_, g)| *g)
        .unwrap_or("F")
}

struct Measure {
    lookups: usize,
    mean_bytes: f64,
    hits: usize,
    controls: usize,
    controls_empty: usize,
}

fn query_words(text: &str) -> String {
    plain(text).split_whitespace().take(12).collect::<Vec<_>>().join(" ")
}

fn measure(sources: &[Source], k: usize) -> Result<Option<Measure>, String> {
    let rules: Vec<(&Source, &Rule)> = sources
        .iter()
        .flat_map(|s| s.parsed.rules.iter().map(move |r| (s, r)))
        .collect();
    if rules.is_empty() {
        return Ok(None);
    }
    // Lexical only: an embedding service would make the numbers depend on the machine.
    std::env::remove_var("INSTINCT_OLLAMA");
    let dir = std::env::temp_dir().join(format!("instinct-audit-{}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).map_err(|e| format!("temp dir: {e}"))?;
    let result = measure_in(&dir.join("bank.hxdb"), &rules, k);
    let _ = fs::remove_dir_all(&dir);
    result.map(Some)
}

fn measure_in(path: &PathBuf, rules: &[(&Source, &Rule)], k: usize) -> Result<Measure, String> {
    const PROJECT: &str = "instinct-audit";
    let scope = eligibility::Scope {
        project: PROJECT.into(),
        ..Default::default()
    };
    let mut ids = Vec::new();
    for (s, r) in rules {
        ids.push(bank_discovery(lesson(r, &s.name, PROJECT), &scope)?.id);
        op_bank(path, lesson(r, &s.name, PROJECT))?;
    }
    let (mut bytes, mut lookups, mut hits) = (0usize, 0usize, 0usize);
    for ((_, r), id) in rules.iter().zip(&ids) {
        let own = query_words(&r.text);
        let mut qs = vec![own.clone()];
        if !r.heading.is_empty() {
            qs.push(plain(&r.heading));
        }
        for q in qs {
            let found = recall_methods(path, &q, k, &scope)?;
            bytes += render_recall(&found).0.len();
            lookups += 1;
            if q == own && found.iter().any(|d| &d.id == id) {
                hits += 1;
            }
        }
    }
    let mut empty = 0;
    for q in CONTROLS {
        if recall_methods(path, q, k, &scope)?.is_empty() {
            empty += 1;
        }
    }
    Ok(Measure {
        lookups,
        mean_bytes: bytes as f64 / lookups as f64,
        hits,
        controls: CONTROLS.len(),
        controls_empty: empty,
    })
}

fn commas(n: usize) -> 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
}

pub fn run_audit(argv: &[String]) -> Result<(), String> {
    let mut o = opts(argv)?;
    if o.help {
        println!("{AUDIT_HELP}");
        return Ok(());
    }
    if o.files.is_empty() {
        o.files = MEMORY_FILES
            .iter()
            .filter(|f| std::path::Path::new(f).is_file())
            .map(|f| f.to_string())
            .collect();
        if o.files.is_empty() {
            let cwd = std::env::current_dir().map(|d| d.display().to_string()).unwrap_or_else(|_| ".".into());
            return Err(format!(
                "no memory file found in {cwd} (looked for {}). Name one instead: instinct audit path/to/CLAUDE.md",
                MEMORY_FILES.join(", ")
            ));
        }
    }
    let sources = read_sources(&o.files)?;
    let bytes: usize = sources.iter().map(|s| s.bytes).sum();
    let tokens = tokens_of(bytes);
    let rules: usize = sources.iter().map(|s| s.parsed.rules.len()).sum();
    let sections: usize = sources.iter().map(|s| s.parsed.sections).sum();
    let letter = grade(tokens);
    let m = measure(&sources, o.k)?;
    let m_tokens = m.as_ref().map(|m| (m.mean_bytes / 4.0).ceil() as usize);

    if o.json {
        let files = sources
            .iter()
            .map(|s| {
                format!(
                    "{{\"file\":\"{}\",\"bytes\":{},\"rules\":{},\"sections\":{}}}",
                    escape_json(&s.name),
                    s.bytes,
                    s.parsed.rules.len(),
                    s.parsed.sections
                )
            })
            .collect::<Vec<_>>()
            .join(",");
        let inst = match &m {
            Some(m) => format!(
                "{{\"method\":\"lexical recall, top {}, temporary bank\",\"lookups\":{},\"mean_lookup_bytes\":{:.1},\"mean_lookup_tokens\":{},\"own_rule_found\":{},\"unrelated_questions\":{},\"unrelated_empty\":{}}}",
                o.k,
                m.lookups,
                m.mean_bytes,
                m_tokens.unwrap_or(0),
                m.hits,
                m.controls,
                m.controls_empty
            ),
            None => "null".to_string(),
        };
        println!(
            "{{\"files\":[{files}],\"bytes\":{bytes},\"bytes_per_token\":4,\"tokens_per_prompt\":{tokens},\"tokens_per_100_prompts\":{},\"rules\":{rules},\"sections\":{sections},\"grade\":\"{letter}\",\"instinct\":{inst}}}",
            tokens * 100
        );
        return Ok(());
    }
    if o.share {
        let plural = sources.len() > 1;
        let mut line = format!(
            "My memory file{} cost{} about {} tokens on every prompt (grade {letter}).",
            if plural { "s" } else { "" },
            if plural { "" } else { "s" },
            commas(tokens)
        );
        if let (Some(m), Some(mt)) = (&m, m_tokens) {
            line.push_str(&format!(
                " Looked up through Instinct, a lookup adds about {} tokens, and {} of {} unrelated questions got nothing.",
                commas(mt),
                m.controls_empty,
                m.controls
            ));
        }
        line.push_str(" Measured with `instinct audit` (about 4 bytes per token).");
        println!("{line}");
        return Ok(());
    }

    for s in &sources {
        println!(
            "{}  {} bytes, {} rules, {} sections",
            s.name,
            commas(s.bytes),
            s.parsed.rules.len(),
            s.parsed.sections
        );
    }
    println!();
    println!("Pasted into every prompt");
    println!("  size        {} bytes", commas(bytes));
    println!(
        "  per prompt  about {} tokens added (about 4 bytes per token)",
        commas(tokens)
    );
    println!("  per 100     about {} tokens", commas(tokens * 100));
    println!("  structure   {rules} rules in {sections} sections");
    println!("  grade       {letter}");
    println!("              {GRADE_HELP}");
    println!();
    match (&m, m_tokens) {
        (Some(m), Some(mt)) => {
            println!(
                "Through Instinct (measured: rules imported into a temporary bank, {} lookups, lexical recall, top {})",
                m.lookups,
                o.k
            );
            println!(
                "  one lookup  adds {:.0} bytes on average, about {} tokens ({}% of the file)",
                m.mean_bytes,
                commas(mt),
                (m.mean_bytes * 100.0 / bytes as f64).round()
            );
            println!(
                "  per 100     about {} tokens if every prompt looked something up",
                commas(mt * 100)
            );
            println!(
                "  own rule    came back in the top {} for {} of {} rule-word lookups (best case: the query is the rule's own wording)",
                o.k, m.hits, rules
            );
            println!(
                "  unrelated   {} of {} control questions got nothing",
                m.controls_empty, m.controls
            );
        }
        _ => println!("Through Instinct: no rules found to import, nothing to measure."),
    }
    Ok(())
}

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

    #[test]
    fn parses_bullets_numbers_nesting_fences_headings() {
        let md = "# Title\n\nIntro line that is prose here.\n\n## Testing\n- Run cargo test first\n  - nested rule about fixtures\n    continued here\n1. numbered one\n2) numbered two\n* [ ] unchecked item\n\n```sh\n- not a rule in code\n# not a heading\n```\n\n### Style\n+ Keep lines short\n";
        let p = parse(md);
        let texts: Vec<&str> = p.rules.iter().map(|r| r.text.as_str()).collect();
        assert_eq!(
            texts,
            vec![
                "Intro line that is prose here.",
                "Run cargo test first",
                "nested rule about fixtures continued here",
                "numbered one",
                "numbered two",
                "unchecked item",
                "Keep lines short"
            ]
        );
        assert_eq!(p.sections, 3);
        assert_eq!(p.rules[1].heading, "Testing");
        assert_eq!(p.rules[1].line, 6);
        assert_eq!(p.rules[6].heading, "Style");
    }

    #[test]
    fn plain_rule_files_and_front_matter() {
        let p = parse("---\nname: x\n---\nAlways use tabs for indentation\nok\n\n---\nNever commit secrets to git\n");
        let texts: Vec<&str> = p.rules.iter().map(|r| r.text.as_str()).collect();
        assert_eq!(texts, vec!["Always use tabs for indentation", "Never commit secrets to git"]);
        assert_eq!(p.sections, 0);
    }

    #[test]
    fn lesson_fields() {
        let r = Rule {
            heading: "Error Handling".into(),
            text: "Never swallow errors with `unwrap` in library code, return a Result instead".into(),
            line: 9,
        };
        let b = lesson(&r, "CLAUDE.md", "p");
        assert_eq!(b.title, "Never swallow errors with unwrap in library code");
        assert_eq!(b.when, format!("Error Handling: {}", r.text));
        assert_eq!(b.evidence, "Imported from CLAUDE.md line 9");
        assert_eq!(b.tags, "error,handling");
        assert_eq!(b.project, "p");
    }

    #[test]
    fn grades_and_tokens() {
        assert_eq!(tokens_of(0), 0);
        assert_eq!(tokens_of(1), 1);
        assert_eq!(tokens_of(1600), 400);
        assert_eq!(grade(400), "A");
        assert_eq!(grade(401), "B");
        assert_eq!(grade(1000), "B");
        assert_eq!(grade(2500), "C");
        assert_eq!(grade(5000), "D");
        assert_eq!(grade(5001), "F");
    }
}