diff --git a/.claude/skills/nt/SKILL.md b/.claude/skills/nt/SKILL.md index 7f447b63..5b704ea6 100644 --- a/.claude/skills/nt/SKILL.md +++ b/.claude/skills/nt/SKILL.md @@ -61,8 +61,11 @@ differs (it's paraphrase-aware, unlike substring `nt search`): nt recall "adding concurrent token refresh" # MCP: nt_recall(context: "...") ``` -An empty result means nothing relevant is recorded (recall has a precision -floor) — proceed, don't retry with looser words. +An empty result usually means nothing relevant is recorded — proceed. If the +query was long and oddly specific, one **shorter** retry is worth it: recall +weighs how many distinct concepts a note shares with the query, so a wordy +question can dilute the two or three that actually carry the meaning. Retry +shorter, not looser — more synonyms of the same idea won't help. When `NT_WORKSTREAM` is set, your own project's notes get a soft ranking preference (`projectMatch: true` in JSON) — cross-project results stay visible diff --git a/internal/recall/paraphrase_corpus_test.go b/internal/recall/paraphrase_corpus_test.go new file mode 100644 index 00000000..7074fea1 --- /dev/null +++ b/internal/recall/paraphrase_corpus_test.go @@ -0,0 +1,92 @@ +package recall + +import ( + "fmt" + "testing" + + "github.com/navbytes/nt/internal/note" +) + +// A paraphrase corpus with a measured HIT@1 floor. +// +// Why it exists: a field test found HIT@1 on a fixed query set fell from 65% to +// 41% purely as the store grew from 20 to 30 notes — nothing would have caught +// that, and there was no way to tell whether a scoring change (length +// normalization, a new synonym group) helped or hurt. recall_precision_test.go +// uses 2-3 note corpora, where the ranking failure modes that matter are +// invisible: a long note winning on coincidental overlap, or a glossary note +// acting as a universal attractor. +// +// Each query is worded to share no verbatim content word with its target. +func corpusNotes() []*note.Note { + n := func(title, body string, tags ...string) *note.Note { return mk(title, body, tags...) } + notes := []*note.Note{ + n("Trash overwrites an identically named file", "Deleting the same path twice leaves only the second copy; the first is unrecoverable.", "lesson"), + n("Archive applies before it validates its input", "A bad handle late in the list still leaves earlier notes retired.", "lesson"), + n("Nested Go module escapes the vulnerability scan", "Tooling run from the repo root never reaches it, so advisories go unnoticed.", "lesson"), + n("Concurrent writers time out behind the store lock", "Twenty-five goroutines serialize; the tail exceeds the default budget on slow hardware.", "lesson"), + n("A slash in a title is read as a folder", "The leading token is consumed as a directory and vanishes from the heading.", "lesson"), + n("Backticks in a one-line summary are expanded by the shell", "The value silently truncates and the command still reports success.", "lesson"), + n("Short identifiers in double brackets resolve one way only", "The reverse index misses them, so the target looks unreferenced.", "lesson"), + n("Renaming pins the previous heading into metadata", "The stored heading then beats the one in the document text.", "lesson"), + // Distractors: plausible neighbours, plus a glossary note (a known + // universal attractor because it enumerates everyone else's terms). + n("Weekly planning", "Review the board, update estimates, groom the queue, and reschedule anything stale.", "note"), + n("Vocabulary of the ranking layer", "Terms in use: clobber, overwrite, duplicate, lock, timeout, folder, heading, shell, bracket, metadata, scanner, module.", "ref"), + n("Editor setup", "Fonts, themes, key bindings and pane layout for the terminal.", "note"), + n("Release checklist", "Tag, build the artefacts, publish notes, announce.", "note"), + } + return notes +} + +var paraphraseCases = []struct{ query, want string }{ + {"deleting something twice destroys the earlier copy", "Trash overwrites an identically named file"}, + {"a bad name partway through still retires the earlier ones", "Archive applies before it validates its input"}, + {"advisories are missed for the sub-project", "Nested Go module escapes the vulnerability scan"}, + {"many simultaneous writers exceed the wait budget", "Concurrent writers time out behind the store lock"}, + {"the first word of my heading disappeared into a directory", "A slash in a title is read as a folder"}, + {"my summary got cut off because of quoting", "Backticks in a one-line summary are expanded by the shell"}, + {"the target claims nothing points at it", "Short identifiers in double brackets resolve one way only"}, + {"the stored heading disagrees with the document", "Renaming pins the previous heading into metadata"}, +} + +// minHitAtOne is the floor this corpus must clear. Raise it when a scoring +// change genuinely improves the number — never lower it to make a change pass. +const minHitAtOne = 8 + +func TestParaphraseCorpusHitAtOne(t *testing.T) { + notes := corpusNotes() + hits, misses := 0, []string{} + for _, c := range paraphraseCases { + got := Rank(notes, c.query, 5) + if len(got) > 0 && got[0].Note.Title == c.want { + hits++ + continue + } + top := "(nothing)" + if len(got) > 0 { + top = got[0].Note.Title + } + misses = append(misses, fmt.Sprintf("%q\n want %q\n got %q", c.query, c.want, top)) + } + t.Logf("HIT@1 = %d/%d", hits, len(paraphraseCases)) + if hits < minHitAtOne { + for _, m := range misses { + t.Errorf("miss: %s", m) + } + t.Fatalf("HIT@1 %d/%d is below the floor of %d", hits, len(paraphraseCases), minHitAtOne) + } +} + +// The glossary note enumerates other notes' vocabulary, which made it a +// universal attractor in the field test — it out-ranked the specific lessons +// about its own terms. It must never take #1 on a query aimed elsewhere. +func TestGlossaryNoteIsNotAUniversalAttractor(t *testing.T) { + notes := corpusNotes() + for _, c := range paraphraseCases { + got := Rank(notes, c.query, 5) + if len(got) > 0 && got[0].Note.Title == "Vocabulary of the ranking layer" { + t.Errorf("glossary note took #1 for %q", c.query) + } + } +} diff --git a/internal/recall/recall.go b/internal/recall/recall.go index 32db7d86..3133da96 100644 --- a/internal/recall/recall.go +++ b/internal/recall/recall.go @@ -52,7 +52,7 @@ type Result struct { // worded differently. Small and dev-focused on purpose — precision matters too. // // Groups are kept NARROW and non-overlapping: ambiguous cross-domain tokens -// (column, index, origin, lock, database) are deliberately NOT grouped, because +// (column, index, origin, lock, database, gc) are deliberately NOT grouped, because // one overloaded word ("column" → migration) would otherwise drag a whole wrong // domain into an unrelated query (a CSS-column question surfacing DB migrations). // nil/null and panic/crash are separate groups so distinct failure modes don't @@ -69,11 +69,24 @@ var synGroups = [][]string{ {"config", "configuration", "setting", "dotenv"}, {"panic", "crash", "segfault", "stacktrace"}, {"nil", "null", "nullpointer", "npe", "nullptr"}, - {"leak", "oom", "allocation", "gc"}, + {"leak", "oom", "allocation", "heap"}, // Domains a coding agent hits that the map was previously blind to: {"css", "flexbox", "flex", "grid", "layout", "overflow", "responsive", "viewport", "zindex"}, {"billing", "payment", "invoice", "charge", "webhook", "idempotency", "refund", "stripe", "subscription"}, {"i18n", "l10n", "locale", "translation", "rtl", "localization"}, + // Everyday software-engineering vocabulary the table was blind to: a field + // test of 48 natural paraphrase pairs from a Go CLI codebase linked only 3. + // Same rule as above — narrow, and no token that carries a second domain + // (flag/option and module/package are deliberately absent: a feature flag + // and a CLI flag are not the same thing). + {"undo", "revert", "rollback", "undelete"}, + {"lint", "linter", "vet", "staticcheck", "gofmt", "formatter"}, + {"duplicate", "dedupe", "deduplicate", "duplication", "clobber", "overwrite"}, + {"regex", "regexp", "matcher"}, + {"serialize", "serialization", "marshal", "unmarshal", "encode", "decode"}, + {"dependency", "dependabot", "vendoring", "bump", "upgrade"}, + {"ci", "cicd", "pipeline"}, + {"frontmatter", "yaml", "toml"}, } // buildConceptOf maps each group's stemmed words to a shared group id ("g0", @@ -407,14 +420,33 @@ func RankProject(notes []*note.Note, context string, limit int, project string) // note on a SINGLE concept is topical noise, not a memory hit — the lesson // boost was promoting exactly those to the top of adjacent-topic queries. For // short queries a single shared concept is legitimately all the signal there is. + // + // The floor applies ONLY when something actually clears it. As an + // unconditional filter it was a cliff in both directions: a heavily + // paraphrased query that shares just one concept with its target returned + // NOTHING, while the same intent in three words returned the right note — + // so the documented recovery ("an empty result means nothing is recorded; + // don't retry with looser words") was backwards, and the fix was to retry + // SHORTER. When no candidate reaches two concepts, one shared concept is all + // the signal the query carries, and the ranked list beats an empty answer; + // the score the caller sees already reflects how weak the match is. if len(q.words) >= 4 { - kept := out[:0] + anyClears := false for _, s := range out { if s.matched >= 2 { - kept = append(kept, s) + anyClears = true + break } } - out = kept + if anyClears { + kept := out[:0] + for _, s := range out { + if s.matched >= 2 { + kept = append(kept, s) + } + } + out = kept + } } sort.SliceStable(out, func(i, j int) bool { if out[i].f != out[j].f {