Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 11 additions & 33 deletions pkgs/mcpx/internal/diagnose/diagnose.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"sort"
"strings"
"time"

"github.com/dezren39/mcpx/internal/nearmiss"
)

// Kind classifies a diagnostic, so a caller can act on one without reading
Expand Down Expand Up @@ -415,46 +417,22 @@ func sortedKeys(m map[string]string) []string {
}

// nearest is the closest tool name in the namespace, when one is close
// enough to be worth suggesting.
// enough to be worth suggesting. The definition of close — normalisation,
// Damerau-Levenshtein, the length-relative threshold, tie-breaking — is
// the shared one in internal/nearmiss (#1904); diagnostics used to keep a
// plainer Levenshtein here that scored a transposition as two edits and
// so disagreed with the launcher about the same typo.
func nearest(name string, cat Catalog, ns string) string {
best, bestD := "", 1<<30
var funcs []string
for _, t := range cat.Tools {
if t.Namespace != ns {
continue
}
d := editDistance(strings.ToLower(name), strings.ToLower(t.Func))
if d < bestD {
best, bestD = t.Func, d
if t.Namespace == ns {
funcs = append(funcs, t.Func)
}
}
// A third of the name may differ. Beyond that the suggestion is noise
// and reads as the tool having guessed.
if bestD > 1+len(name)/3 {
return ""
}
best, _ := nearmiss.Nearest(name, funcs)
return best
}

func editDistance(a, b string) int {
prev := make([]int, len(b)+1)
cur := make([]int, len(b)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(a); i++ {
cur[0] = i
for j := 1; j <= len(b); j++ {
cost := 1
if a[i-1] == b[j-1] {
cost = 0
}
cur[j] = min(min(cur[j-1]+1, prev[j]+1), prev[j-1]+cost)
}
prev, cur = cur, prev
}
return prev[len(b)]
}

// CallErrorInput is everything known about a call that failed upstream.
type CallErrorInput struct {
// Namespace and Tool name the call. Tool may be either spelling.
Expand Down
68 changes: 9 additions & 59 deletions pkgs/mcpx/internal/launcher/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"fmt"
"sort"
"strings"

"github.com/dezren39/mcpx/internal/nearmiss"
)

// Placeholder is a name that may appear in a launcher template as @name.
Expand Down Expand Up @@ -391,73 +393,21 @@ func checkUnknown(t Template, fill Fill) error {

// looksLikePlaceholder is a near-miss test against the known names. It is
// deliberately narrow: the cost of a false positive is refusing a valid
// launcher, which is worse than letting an odd @word through.
// launcher, which is worse than letting an odd @word through. The test
// itself is the shared one in internal/nearmiss (#1904): equality after
// normalisation, the prefix rule, or Damerau-Levenshtein distance at most
// one -- the transposition case ("entyr" for "entry") is one edit there,
// where this file used to keep its own pair of helpers to say the same
// thing.
func looksLikePlaceholder(name string) bool {
lower := strings.ToLower(name)
for _, p := range All {
known := strings.ToLower(string(p))
if lower == known {
return true
}
if len(lower) > 2 && (strings.HasPrefix(known, lower) || strings.HasPrefix(lower, known)) {
return true
}
if editDistanceAtMostOne(lower, known) || isTransposition(lower, known) {
if nearmiss.Near(name, string(p)) {
return true
}
}
return false
}

// isTransposition catches a swapped pair, which plain edit distance scores as
// two changes. Swaps are among the most common typos -- "entyr" for "entry" --
// so treating them as one is what makes the check useful.
func isTransposition(a, b string) bool {
if len(a) != len(b) {
return false
}
var diff []int
for i := range a {
if a[i] != b[i] {
diff = append(diff, i)
if len(diff) > 2 {
return false
}
}
}
return len(diff) == 2 && diff[1] == diff[0]+1 &&
a[diff[0]] == b[diff[1]] && a[diff[1]] == b[diff[0]]
}

func editDistanceAtMostOne(a, b string) bool {
if a == b {
return true
}
if len(a) > len(b) {
a, b = b, a
}
if len(b)-len(a) > 1 {
return false
}
i, j, edits := 0, 0, 0
for i < len(a) && j < len(b) {
if a[i] == b[j] {
i++
j++
continue
}
edits++
if edits > 1 {
return false
}
if len(a) == len(b) {
i++
}
j++
}
return true
}

func max(a, b int) int {
if a > b {
return a
Expand Down
118 changes: 118 additions & 0 deletions pkgs/mcpx/internal/nearmiss/nearmiss.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Package nearmiss owns the one definition of whether one name is
// "close" to another.
//
// mcpx grew two: diagnostics used plain Levenshtein (a transposition
// cost two edits, no prefix rule) and launcher placeholders used a
// distance-of-one test with a separate transposition check and a prefix
// rule. The same typo was therefore close in one place and not in the
// other, and search was about to add a third definition. Here the
// definition lives once (#1904): normalise, Damerau-Levenshtein, a
// length-relative threshold, deterministic tie-breaking.
package nearmiss

import (
"strings"
"unicode"
)

// Normalize folds a name to the form distances are measured on: case
// folded, with snake_case, kebab-case and camelCase boundaries removed,
// so the three spellings of one name are the same name. Digits and
// letters survive; every other rune is a boundary.
func Normalize(s string) string {
var b strings.Builder
prevLower := false
for _, r := range s {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
if unicode.IsUpper(r) && prevLower {
// A camel boundary: the split is recorded by dropping
// nothing -- the letters join -- because the boundary
// carries no more meaning than a separator does.
}
b.WriteRune(unicode.ToLower(r))
prevLower = unicode.IsLower(r) || unicode.IsDigit(r)
default:
prevLower = false
}
}
return b.String()
}

// Distance is the Damerau-Levenshtein distance between two names after
// normalisation: an adjacent transposition costs one edit, which is
// what makes "entyr" one step from "entry" rather than two.
func Distance(a, b string) int {
return damerau(Normalize(a), Normalize(b))
}

// damerau is optimal string alignment Damerau-Levenshtein over bytes of
// already-normalised (lowercase ASCII-folded) strings.
func damerau(a, b string) int {
la, lb := len(a), len(b)
d := make([][]int, la+1)
for i := range d {
d[i] = make([]int, lb+1)
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for i := 1; i <= la; i++ {
for j := 1; j <= lb; j++ {
cost := 1
if a[i-1] == b[j-1] {
cost = 0
}
d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost)
if i > 1 && j > 1 && a[i-1] == b[j-2] && a[i-2] == b[j-1] {
d[i][j] = min(d[i][j], d[i-2][j-2]+1)
}
}
}
return d[la][lb]
}

// Threshold is how far a name of this (normalised) length may drift and
// still count as a near miss: a third of the name may differ, and at
// least one edit always counts. Beyond it a suggestion is noise.
func Threshold(normalisedLen int) int {
if t := 1 + normalisedLen/3; t > 1 {
return t
}
return 1
}

// Near reports the strict near-miss: the names are equal after
// normalisation, one is a prefix of the other (for names longer than
// two characters), or their distance is at most one. This is the
// launcher's deliberately narrow test, unchanged in reach.
func Near(a, b string) bool {
na, nb := Normalize(a), Normalize(b)
if na == nb {
return true
}
if len(na) > 2 && (strings.HasPrefix(nb, na) || strings.HasPrefix(na, nb)) {
return true
}
return damerau(na, nb) <= 1
}

// Nearest returns the closest candidate to name, when one is within
// Threshold of it. Ties break deterministically: the smaller distance
// wins, then the lexicographically smaller candidate, so the answer
// never depends on the order candidates were enumerated in.
func Nearest(name string, candidates []string) (string, bool) {
nn := Normalize(name)
best, bestD := "", 1<<30
for _, c := range candidates {
d := damerau(nn, Normalize(c))
if d < bestD || (d == bestD && c < best) {
best, bestD = c, d
}
}
if best == "" || bestD > Threshold(len(nn)) {
return "", false
}
return best, true
}
81 changes: 81 additions & 0 deletions pkgs/mcpx/internal/nearmiss/nearmiss_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package nearmiss

import "testing"

func TestNormalizeFoldsSpellingsTogether(t *testing.T) {
for _, group := range [][]string{
{"listPets", "list_pets", "list-pets", "ListPets", "list pets"},
{"entry", "Entry", "ENTRY"},
} {
want := Normalize(group[0])
for _, s := range group[1:] {
if got := Normalize(s); got != want {
t.Errorf("Normalize(%q) = %q, want %q (same name as %q)", s, got, want, group[0])
}
}
}
}

func TestDistanceCountsTranspositionAsOneEdit(t *testing.T) {
cases := []struct {
a, b string
want int
}{
{"entry", "entry", 0},
{"entry", "entyr", 1}, // the launcher's example: a swapped pair
{"entry", "entr", 1},
{"entry", "antry", 1}, {"entry", "antri", 2},
{"listPets", "list_pets", 0}, // normalisation, not distance
{"call", "catalog", 4},
{"", "abc", 3},
}
for _, c := range cases {
if got := Distance(c.a, c.b); got != c.want {
t.Errorf("Distance(%q, %q) = %d, want %d", c.a, c.b, got, c.want)
}
}
}

func TestNearIsTheStrictTest(t *testing.T) {
for _, c := range []struct {
a, b string
want bool
}{
{"entry", "entry", true},
{"entry", "entyr", true},
{"entry", "entr", true}, // distance one
{"entry", "entries", false},
{"cat", "catalog", true}, // prefix rule, both longer than two
{"ab", "abcd", false}, // prefix rule needs length > 2
{"entry", "zebra", false},
} {
if got := Near(c.a, c.b); got != c.want {
t.Errorf("Near(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
}
}
}

func TestNearestThresholdAndTieBreaking(t *testing.T) {
// Diagnose's examples: a third of the name may differ.
if got, ok := Nearest("listpet", []string{"catalog", "listPets"}); !ok || got != "listPets" {
t.Errorf("Nearest(listpet) = %q, %v; want listPets, true", got, ok)
}
if _, ok := Nearest("zzzzzz", []string{"catalog", "listPets"}); ok {
t.Error("Nearest(zzzzzz) matched; beyond the threshold is noise")
}
// Deterministic ties: equal distances pick the lexicographically
// smaller candidate regardless of enumeration order.
a, _ := Nearest("abc", []string{"abd", "abb"})
b, _ := Nearest("abc", []string{"abb", "abd"})
if a != "abb" || b != "abb" {
t.Errorf("tie-breaking not deterministic: %q vs %q, want abb both ways", a, b)
}
}

func TestThreshold(t *testing.T) {
for n, want := range map[int]int{0: 1, 2: 1, 3: 2, 5: 2, 6: 3, 9: 4} {
if got := Threshold(n); got != want {
t.Errorf("Threshold(%d) = %d, want %d", n, got, want)
}
}
}
Loading