Psychosonic Lab · Experiment 09
What finds the right note?
When an AI asks a memory app something, the app picks a few notes out of thousands, and the AI reads them in order. This page draws how Notesmith and AgentScribe make that pick, then takes the search apart on 391 real searches made by AI agents. The script is below and runs on your own notes. This page says which builds it matches and what the test cannot see.
The question
What is being asked
When an AI searches your notes, does the note it needed come back first? And which parts of the search decide that? Lab 02 found that memory only helps when the AI looks. This is the other half, what comes back when it does.
Why first matters
Results are read in order. A right note in sixth place can lose to a wrong one in first, so each search is scored by where its answer landed, and landing first is counted on its own.
Why take it apart
Notesmith used to search its two stores apart, and AgentScribe searched everything as one list. They differed in five ways at once, so one comparison could not say which of them mattered. Each part was switched on alone, with the rule for what to keep written down before each run.
How a search picks a note
Before the first question
AgentScribe hands the AI a short brief once, when a session starts: pinned memories, then what changed since that AI's last session, then preferences, decisions and facts, most used first, cut to about 800 tokens. Search is for everything else. Notesmith has no brief, so the AI starts by searching.
The words
The search is cut into words. Common words such as the, which and about are dropped, at most 12 are kept, and each matches as the start of a word, so index also finds indexing. Notesmith matches words of one or two letters exactly, because as a prefix AI pulled in aim, air and aid.
Sections, not whole notes
Every note is cut into sections of about 800 characters, and the sections are what get ranked. A fact on one line of a long note is judged by the lines around it.
Two lists, one ranking
One list holds the sections that contain any of the words, best first by SQLite's bm25 score. A second holds the sections that contain all of them. A note scores 1 / (60 + its place) in each list it appears in, and the scores add up, so a note that says every word rises above one that repeats a single word. The 60 comes from the paper that introduced this way of merging lists, reciprocal rank fusion.
Both stores in one list
Your own notes and the notes AI apps keep for you are ranked together, so whichever matches best comes first, wherever it is kept.
Meaning comes last
AgentScribe can also search by meaning, with an embedding model that runs on the Mac. A note found only that way is placed after every keyword match, because in an earlier test an equal vote for meaning put wrong notes first. It still answers a search that shares no words with its note. Each result says how it matched and who wrote it.
What may come back
Before anything reaches the AI, the app checks what that AI is allowed to read, and AgentScribe also drops memories past their expiry date. Notesmith checks whether any note changed since its index was built, rebuilds it if so, and reads each result again from its store, so a deleted or hidden note cannot come back from an old index. AgentScribe hands over eight results unless the AI asks for more.
Method
The searches
391 searches that AI agents typed into Notesmith during our memory A/B runs, each with the note that answers it worked out by hand. They run against 1,656 real notes, 244 of them written by agents, copied and frozen on 2026-10-08 so every run sees exactly the same thing.
Two sets
145 of the searches come from earlier batches that an older Notesmith change was tuned on. So every choice here was made on the other 246, which nothing was tuned on, and the stemming choice was then checked on the 145 with that rule also written down first. Both sets are reported.
One part at a time
Starting from each store searched on its own, the parts were added one at a time: stemming, sections, then one list over both stores. Then stemming was taken back out of the one list, and last come Notesmith's two small differences, short words matched exactly and identical notes kept apart. Every setup handles words the same way and merges the same two lists, so the table compares the other three parts.
The score
Where the answer landed in the top 20, for each search. First counts the searches whose answer came first, and top 8 those in the first eight. MRR averages one over the place, so first scores 1, second 0.5, and a miss 0.
Checked against the apps
Before any figure here was read, this script's rank for every search was matched against the earlier copy of the search each setup came from: same rank on 391 of 391, every setup. That earlier copy gave the same rank as AgentScribe's own Swift code on all 391 searches, and Notesmith's Swift port gives the same rank as it.
Materials
The script
One file of Python, 233 lines, using only what ships with Python, sqlite3 and its full text search included. It reads your notes folder, never writes to it, and makes no network connection. Read it before you run it. It is shown in full below with its checksum.
What you need
A folder of your notes as text or Markdown files, and a list of searches, each with the note you know answers it. Put notes kept in different places in different subfolders to compare searching them apart with searching them as one.
Show the script in full
#!/usr/bin/env python3
"""What finds the right note? Take a memory search apart on your own notes.
Rebuilds the keyword search Notesmith and AgentScribe use, then turns its parts on one at a time
and reports where the right note lands for each of your searches. Python's own sqlite3 and its
full text search (FTS5), nothing to install, and nothing leaves your Mac.
python3 -B memory-search-check.py NOTES SEARCHES OUT
NOTES a folder of .md or .txt notes. Subfolders are stores (for example your notes in one and
an AI's notes in another); with only one, the "each store on its own" rows are skipped.
A note whose first line starts with "# " uses that line as its title.
SEARCHES a text file, one search per line: the search, a tab, then the answer note's path inside
NOTES (several answers separated by ";"), and optionally a tab and a set name, so a set
kept back from any decision can be reported on its own.
OUT a folder for summary.csv (one row per setup and set) and ranks.csv (where the answer
landed for each search line, 1 to 20, blank when it was not in the top 20). Neither file
holds a search or a note's text, so both can be shared.
The setups, in order:
1 per-store each store searched on its own, whole notes, title weighted 10 to 1,
results merged by score
2 per-store-stem the same, with stemming (porter: "decisions" also matches "decision")
3 per-store-sections the same as 1, notes cut into sections of about 800 characters
4 one-list-stem one list over every store, sections, stemming (AgentScribe 2.0.3)
5 one-list one list over every store, sections, no stemming
6 notesmith 5, with words of one or two letters matched exactly and identical notes
kept apart (Notesmith 1.0.1 and later)
Every setup drops common words, matches each word as a prefix, and merges two lists (sections with
any of the words, sections with all of them) by reciprocal rank: 1 / (60 + place) from each list.
"""
from __future__ import annotations
import csv
import hashlib
import json
import pathlib
import platform
import re
import sqlite3
import sys
# AgentScribe's and Notesmith's stopwords, verbatim.
STOPWORDS = set("""the and for are but not you all any can had her was one our out has his how its who did get she too
use with that this from have what when where which does into about your they them then than there their will would
could should been being were his him her is it in on of to as at by an be or if do so we my me no up""".split())
SETUPS = ("per-store", "per-store-stem", "per-store-sections", "one-list-stem", "one-list", "notesmith")
def words(search: str) -> list[str]:
"""Lowercased, split on anything not a letter or digit, longer than one character, no stopwords, at most 12."""
return [w for w in re.split(r"[^\w]|_", search.lower()) if len(w) > 1 and w not in STOPWORDS][:12]
def pattern(ws: list[str], joiner: str, exact_short: bool) -> str | None:
if not ws or (joiner == " " and len(ws) < 2):
return None
return joiner.join(f'"{w}"' if exact_short and len(w) < 3 else f'"{w}"*' for w in ws)
def sections(body: str, limit: int = 800) -> list[str]:
"""Paragraphs packed into sections of at most `limit` characters; a longer paragraph is cut at words."""
out, current = [], ""
for para in body.split("\n\n"):
p = para.strip()
if not p:
continue
if len(p) > limit:
if current:
out.append(current); current = ""
piece = ""
for word in [w for w in p.split(" ") if w]:
if len(piece) + len(word) + 1 > limit:
out.append(piece); piece = ""
piece += word if not piece else " " + word
if piece:
out.append(piece)
elif len(current) + len(p) + 2 > limit:
if current:
out.append(current)
current = p
else:
current += p if not current else "\n\n" + p
if current:
out.append(current)
return out or [body]
class Index:
"""One FTS5 table: a row per section, or a row per note with title and body columns."""
def __init__(self, docs: list[dict], tokenizer: str, by_section: bool):
self.db = sqlite3.connect(":memory:")
self.by_section = by_section
if by_section:
self.db.execute(f"CREATE VIRTUAL TABLE f USING fts5(doc UNINDEXED, text, tokenize='{tokenizer}')")
self.db.executemany("INSERT INTO f(doc, text) VALUES(?,?)", [(d["doc"], s) for d in docs for s in sections(d["text"])])
else:
self.db.execute(f"CREATE VIRTUAL TABLE f USING fts5(doc UNINDEXED, title, body, tokenize='{tokenizer}')")
self.db.executemany("INSERT INTO f(doc, title, body) VALUES(?,?,?)", [(d["doc"], d["title"], d["body"]) for d in docs])
def ranked(self, pat: str | None, limit: int) -> list[tuple[int, float]]:
"""Distinct notes, best bm25 first, each with its best bm25."""
if not pat:
return []
rank = "bm25(f)" if self.by_section else "bm25(f, 0.0, 10.0, 1.0)"
try:
rows = self.db.execute(f"SELECT doc, {rank} FROM f WHERE f MATCH ? ORDER BY {rank} LIMIT ?", (pat, limit)).fetchall()
except sqlite3.OperationalError:
return []
seen, out = set(), []
for doc, score in rows:
if doc not in seen:
seen.add(doc); out.append((doc, score))
return out
def fused(index: Index, search: str, exact_short: bool = False) -> list[tuple[int, float, float]]:
"""(note, fused score, best bm25), best first: any-word list (60) and every-word list (30), 1 / (60 + place) each."""
ws = words(search)
score: dict[int, float] = {}
best: dict[int, float] = {}
for lst in (index.ranked(pattern(ws, " OR ", exact_short), 60), index.ranked(pattern(ws, " ", exact_short), 30)):
for place, (doc, b) in enumerate(lst):
score[doc] = score.get(doc, 0) + 1 / (60 + place + 1)
best[doc] = min(best.get(doc, b), b)
return sorted(((d, score[d], best[d]) for d in sorted(score)), key=lambda t: -t[1])
def per_store(indexes: list[Index], search: str) -> list[int]:
"""Each store ranked on its own, then one list by fused score; a tie goes to the stronger bm25, then the first store."""
rows = [(-s, b, i, doc) for i, idx in enumerate(indexes) for doc, s, b in fused(idx, search)]
return [doc for *_, doc in sorted(rows)]
def read_notes(root: pathlib.Path) -> list[dict]:
notes = []
for path in sorted(p for p in root.rglob("*") if p.suffix in (".md", ".txt") and p.is_file()):
rel = path.relative_to(root).as_posix()
content = path.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
title, body = "", content
if content.startswith("# "):
first, _, rest = content.partition("\n")
title, body = first[2:], rest[1:] if rest.startswith("\n") else rest
notes.append({"path": rel, "store": rel.split("/")[0] if "/" in rel else "", "title": title, "body": body,
"text": body if not title else title if not body else f"{title}\n\n{body}"})
return notes
def main() -> int:
if len(sys.argv) != 4:
sys.exit(__doc__)
root, searches_file, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])
notes = read_notes(root)
by_path = {n["path"]: i for i, n in enumerate(notes)}
searches = []
for line_no, line in enumerate(searches_file.read_text(encoding="utf-8").splitlines(), 1):
if not line.strip():
continue
parts = line.split("\t")
answers = {a.strip() for a in parts[1].split(";") if a.strip()} if len(parts) > 1 else set()
missing = answers - by_path.keys()
if not answers or missing:
sys.exit(f"{searches_file}:{line_no}: answer not found in {root}: {sorted(missing) or 'none given'}")
searches.append({"line": line_no, "text": parts[0], "answers": {by_path[a] for a in answers},
"set": parts[2].strip() if len(parts) > 2 and parts[2].strip() else "all"})
# Identical notes become one, as AgentScribe stores them; Notesmith keeps every note.
merged, members, seen = [], {}, {}
for i, n in enumerate(notes):
h = hashlib.sha256(" ".join(n["text"].lower().split()).encode()).hexdigest()
if h not in seen:
seen[h] = len(merged)
merged.append(dict(n, doc=len(merged)))
members[seen[h]] = set()
members[seen[h]].add(i)
each = [dict(n, doc=i) for i, n in enumerate(notes)]
stores = sorted({n["store"] for n in notes})
per = {(tok, sec): [Index([d for d in merged if d["store"] == s], tok, sec) for s in stores]
for tok, sec in (("unicode61", False), ("porter unicode61", False), ("unicode61", True))}
one_stem, one = Index(merged, "porter unicode61", True), Index(merged, "unicode61", True)
ns = Index(each, "unicode61", True)
run = {
"per-store": lambda q: per_store(per[("unicode61", False)], q),
"per-store-stem": lambda q: per_store(per[("porter unicode61", False)], q),
"per-store-sections": lambda q: per_store(per[("unicode61", True)], q),
"one-list-stem": lambda q: [d for d, *_ in fused(one_stem, q)],
"one-list": lambda q: [d for d, *_ in fused(one, q)],
"notesmith": lambda q: [d for d, *_ in fused(ns, q, exact_short=True)],
}
setups = [s for s in SETUPS if len(stores) > 1 or not s.startswith("per-store")]
def landed(order: list[int], answers: set[int], kept_apart: bool) -> int | None:
for place, doc in enumerate(order[:20], 1):
if ({doc} if kept_apart else members[doc]) & answers:
return place
return None
for s in searches:
for name in setups:
s[name] = landed(run[name](s["text"]), s["answers"], name == "notesmith")
out.mkdir(parents=True, exist_ok=True)
with open(out / "ranks.csv", "w", encoding="utf-8", newline="") as f:
w = csv.writer(f)
w.writerow(["line", "set"] + setups)
for s in searches:
w.writerow([s["line"], s["set"]] + [s[n] or "" for n in setups])
rows = []
for set_name in sorted({s["set"] for s in searches}):
group = [s for s in searches if s["set"] == set_name]
for name in setups:
ranks = [s[name] for s in group]
rows.append({"set": set_name, "setup": name, "searches": len(group), "first": sum(1 for r in ranks if r == 1),
"top_8": sum(1 for r in ranks if r and r <= 8), "top_20": sum(1 for r in ranks if r),
"mrr": f"{sum(1 / r for r in ranks if r) / len(group):.4f}"})
with open(out / "summary.csv", "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader(); w.writerows(rows)
(out / "run.json").write_text(json.dumps({
"notes": len(notes), "merged_notes": len(merged), "stores": len(stores), "searches": len(searches),
"python": platform.python_version(), "sqlite": sqlite3.sqlite_version,
"searches_sha256": hashlib.sha256(searches_file.read_bytes()).hexdigest()}, indent=1) + "\n")
print(f"{len(notes)} notes ({len(merged)} after merging identical ones) in {len(stores)} store(s), {len(searches)} searches")
print(f"{'set':10} {'setup':20} {'first':>6} {'top 8':>6} {'MRR':>7}")
for r in rows:
print(f"{r['set']:10} {r['setup']:20} {r['first']:>6} {r['top_8']:>6} {r['mrr']:>7}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Results
The 246 searches every choice was made on
| Setup | First | Top 8 | MRR |
|---|---|---|---|
| Each store on its own | 72 | 171 | 0.444 |
| Each store on its own, stemming | 76 | 155 | 0.428 |
| Each store on its own, by section | 90 | 182 | 0.502 |
| One list, by section, stemming (AgentScribe 2.0.3 and earlier) | 97 | 187 | 0.535 |
| One list, by section (AgentScribe 2.1.0) | 102 | 198 | 0.569 |
| One list, by section, short words exact (Notesmith) | 102 | 203 | 0.572 |
The 145 searches kept back
| Setup | First | Top 8 | MRR |
|---|---|---|---|
| Each store on its own | 52 | 95 | 0.455 |
| Each store on its own, stemming | 52 | 88 | 0.447 |
| Each store on its own, by section | 56 | 99 | 0.487 |
| One list, by section, stemming (AgentScribe 2.0.3 and earlier) | 63 | 99 | 0.532 |
| One list, by section (AgentScribe 2.1.0) | 66 | 101 | 0.554 |
| One list, by section, short words exact (Notesmith) | 64 | 103 | 0.550 |
Data: summary.csv, and ranks.csv with where the answer landed for every search, by line number. The searches and the notes are not published, because they are one person's private notes.
What this shows
One list helped most
Ranking both stores as one list, instead of ranking each and merging, was the biggest single step. On the 246 searches nothing was tuned on, MRR went from 0.50 to 0.57 and the answer came first 102 times instead of 90. Scores from two separate indexes do not compare well, so any merge is partly a guess about which store should lead.
Sections helped next
Cutting notes into sections took MRR from 0.44 to 0.50 with each store on its own, and the answer came first 90 times instead of 72.
Stemming hurt
Stemming lowered MRR each time it was tried, on both sets. With each store on its own it went from 0.44 to 0.43, as one list from 0.57 to 0.54, and on the 145 kept back from 0.55 to 0.53. With each store on its own it did put more answers first, 76 against 72, while pushing more out of the top eight, which kept 155 against 171. Notesmith never shipped it. AgentScribe 2.0.3 and earlier stemmed. AgentScribe 2.1.0, released after this test, does not.
The small parts are small
Notesmith's two differences, short words matched exactly and identical notes kept apart, moved the score by less than a hundredth on either set.
What this does not show
One person's notes
Every note and search here comes from one person's notes and the agents working for that person. Notes written differently could reorder these results.
Keyword search only
The script tests the keyword part of the search. AgentScribe's meaning search needs Apple's on-device embedding model, so it is left out. In AgentScribe it only adds notes after the keyword matches, so it cannot move a keyword match out of first place.
The words agents chose
These are the words the agents actually typed. No ranking rescues a search for the wrong thing, and another model may search differently.
Answers marked by hand
Which note answers each search was decided by us. A different reader might accept a different note for some of them.
Ranking is not answering
A right note in first place still has to be read and used well. Lab 02 measures that part.
English words
The common word list is English. In Notesmith a search with no usable words, Chinese or Japanese among them, falls back to an older search that this script does not copy.
We built both apps
The people who built Notesmith and AgentScribe ran this test. Each rule was committed before its run, and the script is published so you can check the result on notes of your own.
Run it yourself
Download it and read it
Save memory-search-check.py from this page and read it.
Write your searches
One line per search: the search, a tab, then the answer note's path inside your folder. Write them the way you would ask, before looking at how the notes are worded.
which cache did we pick for tides decisions/tides.md
Run it
python3 -B memory-search-check.py notes/ searches.tsv out/It prints one row per setup and writes
summary.csv and ranks.csv to out/. Neither file holds a search or a note.If yours differs
If your result is not ours, send summary.csv to info@psychosonicconsulting.com and we will look.
The Lab
Notesmith and AgentScribe are made by Psychosonic Consulting. Apple and Mac are trademarks of Apple Inc. SQLite is in the public domain. Apple is not affiliated with and does not endorse this page.
The Signal
A short note on building privacy-first software, plus the day each new app ships. No spam, unsubscribe anytime.
Free · ~1 email a week · your address stays yours · RSS feed