use super::*;
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.";
const MEMORY_FILES: [&str; 5] = [
"CLAUDE.md",
"AGENTS.md",
"GEMINI.md",
".cursorrules",
".github/copilot-instructions.md",
];
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);
}
}
}
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,
}
}
struct Opts {
files: Vec<String>,
share: bool,
json: bool,
apply: bool,
help: bool,
project: String,
k: usize,
}
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()
}
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(())
}
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);
}
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");
}
}