Split corp-search module and tune match scoring

This commit is contained in:
gitea committed 2026-10-02 19:08:09 +08:00
1 parent 3918e3de43
commit 0a71674c64
15 files changed
+1046 -809

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
import type { CorpConfig } from "../config/types.js";
import { fuzzyMatchString } from "./engine.js";
import { isSubsequence } from "./distance.js";
import { matchTokenizedQuery } from "./tokens.js";
import type { FuzzyMatchOptions, MatchReason, MatchScoreResult } from "./types.js";
interface CorpField {
text: string | undefined;
weight: number;
}
function corpSearchFields(corp: CorpConfig): CorpField[] {
return [
{ text: corp.name, weight: 1.2 },
{ text: corp.id, weight: 1.1 },
{ text: corp.source.staffId, weight: 1.0 },
{ text: (corp.source as any).domain, weight: 1.0 },
{ text: (corp.source as any).corpId, weight: 1.0 },
{ text: corp.seal.tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantName, weight: 1.1 },
{ text: corp.testCorpId, weight: 1.0 },
{ text: corp.prodCorpId, weight: 1.0 },
{ text: corp.environment ?? "production", weight: 0.8 },
{ text: corp.source.type, weight: 0.8 },
{ text: (corp.source as any).provider, weight: 0.8 }
];
}
interface WeightedMatch {
score: number;
reason: MatchReason;
}
/** Keeps the higher-scoring candidate; ties stay with the earlier match. */
function strongerMatch(current: WeightedMatch, candidate: WeightedMatch): WeightedMatch {
return candidate.score > current.score ? candidate : current;
}
function matchCorpFields(
fields: CorpField[],
query: string,
options: FuzzyMatchOptions
): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = fuzzyMatchString(query, field.text, options);
if (res.matched) {
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
/**
* When a long Chinese query contains a compact enterprise name in order (for
* example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
* retain that candidate as a lower-confidence abbreviation match. This is
* deliberately below exact/substring/pinyin matches and disabled in strict mode.
*/
function matchCorpAbbreviation(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
if (queryChinese.length < 3) return best;
for (const field of fields) {
if (!field.text) continue;
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
const prefix = targetChinese.slice(0, 2);
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
best = strongerMatch(best, { score: 0.74 * field.weight, reason: "abbreviation" });
}
return best;
}
function matchCorpTokens(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = matchTokenizedQuery(query, field.text);
if (res.matched) {
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
/**
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
* returning the highest match score and reason.
*/
export function matchCorp(
corp: CorpConfig,
query: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const fields = corpSearchFields(corp);
let best = matchCorpFields(fields, query, options);
if (!options.strict) {
best = strongerMatch(best, matchCorpAbbreviation(fields, query));
best = strongerMatch(best, matchCorpTokens(fields, query));
}
return {
matched: best.score > 0,
score: best.score,
reason: best.reason
};
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test";
import { levenshteinDistance, minSubstringLevenshtein } from "./distance.js";
describe("distance primitives", () => {
describe("levenshteinDistance", () => {
test("calculates distance correctly", () => {
expect(levenshteinDistance("", "")).toBe(0);
expect(levenshteinDistance("abc", "abc")).toBe(0);
expect(levenshteinDistance("abc", "ab")).toBe(1);
expect(levenshteinDistance("abc", "abcd")).toBe(1);
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
});
});
describe("minSubstringLevenshtein", () => {
test("detects exact substring with distance 0", () => {
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
});
test("detects missing letter with distance 1", () => {
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
});
test("detects single substitution typo with distance 1", () => {
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
});
});
});
+72
View File
@@ -0,0 +1,72 @@
/**
* Standard Levenshtein distance between two strings.
*/
export function levenshteinDistance(a: string, b: string): number {
const m = a.length;
const n = b.length;
if (m === 0) return n;
if (n === 0) return m;
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
let currRow: number[] = Array.from({ length: n + 1 }, () => 0);
for (let i = 1; i <= m; i += 1) {
currRow[0] = i;
for (let j = 1; j <= n; j += 1) {
if (a[i - 1] === b[j - 1]) {
currRow[j] = prevRow[j - 1] ?? 0;
} else {
const sub = prevRow[j - 1] ?? 0;
const ins = currRow[j - 1] ?? 0;
const del = prevRow[j] ?? 0;
currRow[j] = Math.min(sub, ins, del) + 1;
}
}
const temp = prevRow;
prevRow = currRow;
currRow = temp;
}
return prevRow[n] ?? 0;
}
/**
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
* Supports queries missing a letter, having an extra letter, or having an internal typo.
*/
export function minSubstringLevenshtein(query: string, target: string): number {
if (!query || !target) return 999;
if (target.includes(query)) return 0;
const qLen = query.length;
if (target.length < qLen - 2) {
return levenshteinDistance(query, target);
}
let min = 999;
const minWindow = Math.max(1, qLen - 2);
const maxWindow = Math.min(target.length, qLen + 2);
for (let len = minWindow; len <= maxWindow; len += 1) {
for (let i = 0; i <= target.length - len; i += 1) {
const sub = target.slice(i, i + len);
const dist = levenshteinDistance(query, sub);
if (dist < min) min = dist;
if (min === 0) return 0;
}
}
return min;
}
/**
* Checks if all characters of `query` appear in order inside `target` (subsequence).
*/
export function isSubsequence(query: string, target: string): boolean {
if (!query || !target) return false;
let qIdx = 0;
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
if (query[qIdx] === target[tIdx]) {
qIdx += 1;
}
}
return qIdx === query.length;
}
+90
View File
@@ -0,0 +1,90 @@
import { describe, expect, test } from "bun:test";
import { fuzzyMatchString } from "./engine.js";
describe("fuzzyMatchString", () => {
test("exact match", () => {
const res = fuzzyMatchString("谢子豪", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("exact");
expect(res.score).toBe(1.0);
});
test("prefix substring keeps the 0.95 band", () => {
const res = fuzzyMatchString("谢子", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("substring");
expect(res.score).toBe(0.95);
});
test("mid-string substring ranks below prefix hits", () => {
const res = fuzzyMatchString("子豪", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("substring");
expect(res.score).toBe(0.92);
});
test("normalizes full-width characters (NFKC)", () => {
const res = fuzzyMatchString("GB", "GB科技");
expect(res.matched).toBe(true);
expect(res.reason).toBe("substring");
});
test("initials match (简拼)", () => {
const res = fuzzyMatchString("xzh", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("initials");
expect(res.score).toBe(0.9);
});
test("pinyin match (全拼)", () => {
const res = fuzzyMatchString("xiezihao", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("pinyin");
});
test("homophones (同音字)", () => {
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
expect(res1.matched).toBe(true);
expect(res1.reason).toBe("fuzzy_pinyin");
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
expect(res2.matched).toBe(true);
expect(res2.reason).toBe("fuzzy_pinyin");
});
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
const res1 = fuzzyMatchString("詹三", "张三");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
expect(res2.matched).toBe(true);
});
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
const res1 = fuzzyMatchString("xieziha", "谢子豪");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
expect(res2.matched).toBe(true);
const res3 = fuzzyMatchString("acme", "acm corp");
expect(res3.matched).toBe(true);
expect(res3.reason).toBe("levenshtein");
});
test("strict mode rejects fuzzy / homophone / typo matches", () => {
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
// But exact substring is allowed in strict mode
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
});
test("rejects completely unrelated terms", () => {
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
});
});
+178
View File
@@ -0,0 +1,178 @@
import { pinyin, match as pinyinMatch } from "pinyin-pro";
import { isSubsequence, minSubstringLevenshtein } from "./distance.js";
import { normalizeFuzzyPinyin } from "./pinyin.js";
import type { FuzzyMatchOptions, MatchScoreResult } from "./types.js";
/** Normalizes NFKC (full-width -> half-width), trims, and lowercases. */
function normalizeText(value: string): string {
return value.normalize("NFKC").trim().toLowerCase();
}
function noMatch(): MatchScoreResult {
return { matched: false, score: 0, reason: "none" };
}
interface PinyinPair {
query: string;
target: string;
}
/**
* Precomputed per (query, target) pair so every strategy can share the work.
*/
interface MatchContext {
targetHasChinese: boolean;
queryHasChinese: boolean;
/** Fuzzy pinyin of both sides, or null when neither side contains Chinese. */
fuzzyPinyin: PinyinPair | null;
maxDistance: number;
}
function buildMatchContext(
normQuery: string,
normTarget: string,
options: FuzzyMatchOptions
): MatchContext {
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
return {
targetHasChinese,
queryHasChinese,
fuzzyPinyin:
targetHasChinese || queryHasChinese
? { target: normalizeFuzzyPinyin(normTarget), query: normalizeFuzzyPinyin(normQuery) }
: null,
// Allowed edit distance based on query length:
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
// - 3..5: 1 (missing 1 letter or 1 typo)
// - >= 6: 2 (missing 1-2 letters)
maxDistance: options.maxDistance ?? (normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2)
};
}
/** Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产"). */
function matchByInitials(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese || query.length < 2) return null;
const targetInitials = pinyin(target, { pattern: "first", toneType: "none", type: "array" })
.join("")
.toLowerCase();
if (targetInitials.includes(query)) {
return { matched: true, score: 0.9, reason: "initials" };
}
return null;
}
/** Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets). */
function matchByPinyin(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese) return null;
try {
const pm = pinyinMatch(target, query, { precision: "start" });
if (pm && pm.length > 0) {
return { matched: true, score: 0.88, reason: "pinyin" };
}
} catch {
// ignore match errors if non-standard regex chars
}
return null;
}
/** Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音). */
function matchByFuzzyPinyin(ctx: MatchContext): MatchScoreResult | null {
const pair = ctx.fuzzyPinyin;
if (!pair || pair.query.length < 2) return null;
if (pair.target.includes(pair.query)) {
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
}
return null;
}
/** Missing letter / Typo tolerance (Levenshtein Distance), on raw strings then on fuzzy pinyin. */
function matchByEditDistance(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (ctx.maxDistance <= 0) return null;
// Check raw string distance
const rawDist = minSubstringLevenshtein(query, target);
if (rawDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.8 - rawDist * 0.1), reason: "levenshtein" };
}
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
const pair = ctx.fuzzyPinyin;
if (pair && pair.query.length >= 3 && pair.target.length >= 3) {
const pinyinDist = minSubstringLevenshtein(pair.query, pair.target);
if (pinyinDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" };
}
}
return null;
}
/** Subsequence match (loose character order, min query length 3). */
function matchBySubsequence(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (query.length < 3) return null;
if (isSubsequence(query, target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
const pair = ctx.fuzzyPinyin;
if (pair && isSubsequence(pair.query, pair.target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
return null;
}
/**
* Core fuzzy string match engine:
* Evaluates match across exact, substring (prefix hits outrank mid-string hits),
* initials, pinyin, homophone/fuzzy pinyin, sliding-window edit distance
* (missing/typo tolerance), and character subsequence.
* Strategies run in priority order; the first hit wins.
*/
export function fuzzyMatchString(
query: string,
target: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const normQuery = normalizeText(query);
const normTarget = normalizeText(target);
if (!normQuery || !normTarget) {
return noMatch();
}
// Exact match
if (normTarget === normQuery) {
return { matched: true, score: 1.0, reason: "exact" };
}
// Substring match: a query that opens the target is stronger evidence than a
// mid-string hit, so it keeps the historical 0.95 band while mid-string drops to 0.92.
if (normTarget.startsWith(normQuery)) {
return { matched: true, score: 0.95, reason: "substring" };
}
if (normTarget.includes(normQuery)) {
return { matched: true, score: 0.92, reason: "substring" };
}
// If strict mode is requested, only exact or substring matches are accepted.
if (options.strict) {
return noMatch();
}
const context = buildMatchContext(normQuery, normTarget, options);
return (
matchByInitials(normQuery, normTarget, context) ??
matchByPinyin(normQuery, normTarget, context) ??
matchByFuzzyPinyin(context) ??
matchByEditDistance(normQuery, normTarget, context) ??
matchBySubsequence(normQuery, normTarget, context) ??
noMatch()
);
}
-258
View File
@@ -1,258 +0,0 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../config/types.js";
import {
filterCorpsFuzzy,
fuzzyMatchString,
levenshteinDistance,
minSubstringLevenshtein,
normalizeFuzzyPinyin
} from "./fuzzy.js";
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
tenantSlug: `${id}-slug`,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "seal",
token: `${id}-token`,
sealUrl: `https://${id}.seal.test`,
expiresIn: 3600,
staffId: `staff-${id}`
},
auth: {
refreshTtl: 300
},
...overrides
};
}
describe("fuzzy search utilities", () => {
describe("levenshteinDistance", () => {
test("calculates distance correctly", () => {
expect(levenshteinDistance("", "")).toBe(0);
expect(levenshteinDistance("abc", "abc")).toBe(0);
expect(levenshteinDistance("abc", "ab")).toBe(1);
expect(levenshteinDistance("abc", "abcd")).toBe(1);
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
});
});
describe("minSubstringLevenshtein", () => {
test("detects exact substring with distance 0", () => {
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
});
test("detects missing letter with distance 1", () => {
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
});
test("detects single substitution typo with distance 1", () => {
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
});
});
describe("normalizeFuzzyPinyin", () => {
test("normalizes retroflex to flat consonants", () => {
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
expect(normalizeFuzzyPinyin("超")).toContain("cao");
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
});
test("normalizes front and back nasals", () => {
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
});
test("normalizes homophones to identical representations", () => {
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
});
});
describe("fuzzyMatchString", () => {
test("exact match", () => {
const res = fuzzyMatchString("谢子豪", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("exact");
expect(res.score).toBe(1.0);
});
test("substring match", () => {
const res = fuzzyMatchString("谢子", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("substring");
expect(res.score).toBe(0.95);
});
test("initials match (简拼)", () => {
const res = fuzzyMatchString("xzh", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("initials");
expect(res.score).toBe(0.9);
});
test("pinyin match (全拼)", () => {
const res = fuzzyMatchString("xiezihao", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("pinyin");
});
test("homophones (同音字)", () => {
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
expect(res1.matched).toBe(true);
expect(res1.reason).toBe("fuzzy_pinyin");
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
expect(res2.matched).toBe(true);
expect(res2.reason).toBe("fuzzy_pinyin");
});
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
const res1 = fuzzyMatchString("詹三", "张三");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
expect(res2.matched).toBe(true);
});
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
const res1 = fuzzyMatchString("xieziha", "谢子豪");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
expect(res2.matched).toBe(true);
const res3 = fuzzyMatchString("acme", "acm corp");
expect(res3.matched).toBe(true);
expect(res3.reason).toBe("levenshtein");
});
test("strict mode rejects fuzzy / homophone / typo matches", () => {
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
// But exact substring is allowed in strict mode
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
});
test("rejects completely unrelated terms", () => {
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
});
});
describe("filterCorpsFuzzy", () => {
const corp1 = makeCorp("xiezihao", "谢子豪", {
testCorpId: "test-xzh"
});
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
source: {
type: "hose",
corpId: "ID01VAdCnJEdFd",
staffId: "staff-channel",
domain: "https://app.ekuaibao.com"
} as any
});
const corp3 = makeCorp("acme-corp", "Acme Global", {
environment: "test"
});
const corps = [corp1, corp2, corp3];
test("finds enterprise by homophone", () => {
const results = filterCorpsFuzzy(corps, "鞋子豪");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by initials", () => {
const results = filterCorpsFuzzy(corps, "xzh");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by missing letter query", () => {
const results = filterCorpsFuzzy(corps, "xieziha");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by pinyin of Chinese name", () => {
const results = filterCorpsFuzzy(corps, "qudao");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("finds enterprise by hose corpId or staffId", () => {
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
expect(staffResults.length).toBe(1);
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("strict mode filtering excludes fuzzy homophone matches", () => {
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
expect(fuzzyRes.length).toBe(1);
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
expect(strictRes.length).toBe(0);
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
expect(strictExact.length).toBe(1);
});
test("ranks exact match higher than fuzzy matches", () => {
const cExact = makeCorp("test-qudao", "渠道");
const cFuzzy = makeCorp("test-other", "渠到另外一家");
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
expect(ranked[0]!.id).toBe("test-qudao");
});
test("finds a compact enterprise name inside a longer Chinese query", () => {
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
const unrelated = makeCorp("corp-other", "南京测绘");
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
expect(results[0]!.id).toBe("corp-yuan-ce");
expect(results).toHaveLength(1);
});
test("keeps strict search limited to exact substrings", () => {
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
expect(results).toEqual([]);
});
test("matches Chinese name and industry words despite a contextual name typo", () => {
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
const sameIndustry = makeCorp("corp-other", "华芯半导体股份有限公司");
for (const query of ["瑞泰半导体", "瑞泰 半导体", "半导体 瑞泰", "钰泰 半导体"]) {
expect(filterCorpsFuzzy([sameIndustry, target], query).map((corp) => corp.id))
.toEqual([target.id]);
}
});
test("requires another matching word before tolerating a typo in a short Chinese name", () => {
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
expect(filterCorpsFuzzy([target], "瑞泰")).toEqual([]);
expect(filterCorpsFuzzy([target], "瑞泰 半导体", { strict: true })).toEqual([]);
expect(filterCorpsFuzzy([target], "钰泰半导体", { strict: true })).toEqual([target]);
});
});
});
-551
View File
@@ -1,551 +0,0 @@
import { pinyin, match as pinyinMatch } from "pinyin-pro";
import type { CorpConfig } from "../config/types.js";
export interface FuzzyMatchOptions {
/**
* If true, disables fuzzy/soft matching and requires exact substring matching.
* Defaults to false (soft search by default).
*/
strict?: boolean;
/**
* Maximum edit distance allowed for typo / missing letter tolerance.
* Defaults based on query length:
* - length <= 2: 0 (no fuzzy edits)
* - length 3..5: 1 (missing 1 letter or 1 typo)
* - length >= 6: 2 (missing 1-2 letters)
*/
maxDistance?: number;
}
export type MatchReason =
| "exact"
| "substring"
| "initials"
| "pinyin"
| "fuzzy_pinyin"
| "levenshtein"
| "subsequence"
| "tokens"
| "abbreviation"
| "none";
export interface MatchScoreResult {
matched: boolean;
score: number;
reason: MatchReason;
}
// ---------------------------------------------------------------------------
// Edit-distance & character-order primitives
// ---------------------------------------------------------------------------
/**
* Standard Levenshtein distance between two strings.
*/
export function levenshteinDistance(a: string, b: string): number {
const m = a.length;
const n = b.length;
if (m === 0) return n;
if (n === 0) return m;
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
let currRow: number[] = Array.from({ length: n + 1 }, () => 0);
for (let i = 1; i <= m; i += 1) {
currRow[0] = i;
for (let j = 1; j <= n; j += 1) {
if (a[i - 1] === b[j - 1]) {
currRow[j] = prevRow[j - 1] ?? 0;
} else {
const sub = prevRow[j - 1] ?? 0;
const ins = currRow[j - 1] ?? 0;
const del = prevRow[j] ?? 0;
currRow[j] = Math.min(sub, ins, del) + 1;
}
}
const temp = prevRow;
prevRow = currRow;
currRow = temp;
}
return prevRow[n] ?? 0;
}
/**
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
* Supports queries missing a letter, having an extra letter, or having an internal typo.
*/
export function minSubstringLevenshtein(query: string, target: string): number {
if (!query || !target) return 999;
if (target.includes(query)) return 0;
const qLen = query.length;
if (target.length < qLen - 2) {
return levenshteinDistance(query, target);
}
let min = 999;
const minWindow = Math.max(1, qLen - 2);
const maxWindow = Math.min(target.length, qLen + 2);
for (let len = minWindow; len <= maxWindow; len += 1) {
for (let i = 0; i <= target.length - len; i += 1) {
const sub = target.slice(i, i + len);
const dist = levenshteinDistance(query, sub);
if (dist < min) min = dist;
if (min === 0) return 0;
}
}
return min;
}
/**
* Checks if all characters of `query` appear in order inside `target` (subsequence).
*/
export function isSubsequence(query: string, target: string): boolean {
if (!query || !target) return false;
let qIdx = 0;
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
if (query[qIdx] === target[tIdx]) {
qIdx += 1;
}
}
return qIdx === query.length;
}
// ---------------------------------------------------------------------------
// Pinyin normalization & Chinese segmentation
// ---------------------------------------------------------------------------
/**
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
* - Strips non-alphanumeric whitespace
*/
export function normalizeFuzzyPinyin(str: string): string {
if (!str) return "";
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
return pyTokens
.map((token) =>
token
.toLowerCase()
.replace(/zh/g, "z")
.replace(/ch/g, "c")
.replace(/sh/g, "s")
.replace(/iang/g, "ian")
.replace(/uang/g, "uan")
.replace(/ang/g, "an")
.replace(/eng/g, "en")
.replace(/ing/g, "in")
)
.join("");
}
function searchTerms(value: string): string[] {
const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
return chunks.flatMap((chunk) => {
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
if (chunk.length <= 2) return [chunk];
const terms: string[] = [];
for (let index = 0; index < chunk.length - 1; index += 1) {
terms.push(chunk.slice(index, index + 2));
}
return terms;
});
}
let wordSegmenter: Intl.Segmenter | undefined;
function searchWords(value: string): string[] {
wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" });
const words: string[] = [];
let nameChars = "";
const flushName = () => {
if (nameChars) words.push(nameChars);
nameChars = "";
};
for (const part of wordSegmenter.segment(value.trim().toLowerCase())) {
// Uncommon enterprise names are often segmented into individual characters.
if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) {
nameChars += part.segment;
} else {
flushName();
if (part.isWordLike) words.push(part.segment);
}
}
flushName();
return words;
}
// ---------------------------------------------------------------------------
// fuzzyMatchString: strategy cascade
// ---------------------------------------------------------------------------
function noMatch(): MatchScoreResult {
return { matched: false, score: 0, reason: "none" };
}
interface PinyinPair {
query: string;
target: string;
}
/**
* Precomputed per (query, target) pair so every strategy can share the work.
*/
interface MatchContext {
targetHasChinese: boolean;
queryHasChinese: boolean;
/** Fuzzy pinyin of both sides, or null when neither side contains Chinese. */
fuzzyPinyin: PinyinPair | null;
maxDistance: number;
}
function buildMatchContext(
normQuery: string,
normTarget: string,
options: FuzzyMatchOptions
): MatchContext {
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
return {
targetHasChinese,
queryHasChinese,
fuzzyPinyin:
targetHasChinese || queryHasChinese
? { target: normalizeFuzzyPinyin(normTarget), query: normalizeFuzzyPinyin(normQuery) }
: null,
// Allowed edit distance based on query length:
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
// - 3..5: 1 (missing 1 letter or 1 typo)
// - >= 6: 2 (missing 1-2 letters)
maxDistance: options.maxDistance ?? (normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2)
};
}
/** Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产"). */
function matchByInitials(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese || query.length < 2) return null;
const targetInitials = pinyin(target, { pattern: "first", toneType: "none", type: "array" })
.join("")
.toLowerCase();
if (targetInitials.includes(query)) {
return { matched: true, score: 0.9, reason: "initials" };
}
return null;
}
/** Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets). */
function matchByPinyin(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese) return null;
try {
const pm = pinyinMatch(target, query, { precision: "start" });
if (pm && pm.length > 0) {
return { matched: true, score: 0.88, reason: "pinyin" };
}
} catch {
// ignore match errors if non-standard regex chars
}
return null;
}
/** Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音). */
function matchByFuzzyPinyin(ctx: MatchContext): MatchScoreResult | null {
const pair = ctx.fuzzyPinyin;
if (!pair || pair.query.length < 2) return null;
if (pair.target.includes(pair.query)) {
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
}
return null;
}
/** Missing letter / Typo tolerance (Levenshtein Distance), on raw strings then on fuzzy pinyin. */
function matchByEditDistance(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (ctx.maxDistance <= 0) return null;
// Check raw string distance
const rawDist = minSubstringLevenshtein(query, target);
if (rawDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.8 - rawDist * 0.1), reason: "levenshtein" };
}
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
const pair = ctx.fuzzyPinyin;
if (pair && pair.query.length >= 3 && pair.target.length >= 3) {
const pinyinDist = minSubstringLevenshtein(pair.query, pair.target);
if (pinyinDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" };
}
}
return null;
}
/** Subsequence match (loose character order, min query length 3). */
function matchBySubsequence(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (query.length < 3) return null;
if (isSubsequence(query, target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
const pair = ctx.fuzzyPinyin;
if (pair && isSubsequence(pair.query, pair.target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
return null;
}
/**
* Core fuzzy string match engine:
* Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin,
* sliding-window edit distance (missing/typo tolerance), and character subsequence.
* Strategies run in priority order; the first hit wins.
*/
export function fuzzyMatchString(
query: string,
target: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const normQuery = query.trim().toLowerCase();
const normTarget = target.trim().toLowerCase();
if (!normQuery || !normTarget) {
return noMatch();
}
// Exact match
if (normTarget === normQuery) {
return { matched: true, score: 1.0, reason: "exact" };
}
// Substring match
if (normTarget.includes(normQuery)) {
return { matched: true, score: 0.95, reason: "substring" };
}
// If strict mode is requested, only exact or substring matches are accepted.
if (options.strict) {
return noMatch();
}
const context = buildMatchContext(normQuery, normTarget, options);
return (
matchByInitials(normQuery, normTarget, context) ??
matchByPinyin(normQuery, normTarget, context) ??
matchByFuzzyPinyin(context) ??
matchByEditDistance(normQuery, normTarget, context) ??
matchBySubsequence(normQuery, normTarget, context) ??
noMatch()
);
}
// ---------------------------------------------------------------------------
// Tokenized Chinese query matching
// ---------------------------------------------------------------------------
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
if (queryWords.length < 2) return null;
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
// A second matching word supplies context for a typo in a two-character
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
));
if (!allWordsMatch) return null;
return { matched: true, score: 0.76, reason: "tokens" };
}
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
function matchQueryTerms(
query: string,
queryWordCount: number,
target: string
): MatchScoreResult | null {
const queryTerms = searchTerms(query);
if (queryTerms.length < 2) return null;
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
if (matchedTerms.length === 0) return null;
const coverage = matchedTerms.length / queryTerms.length;
return {
matched: true,
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
reason: "tokens"
};
}
function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
if (!/[\u4e00-\u9fa5]/.test(query)) {
return noMatch();
}
const queryWords = searchWords(query);
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
}
// ---------------------------------------------------------------------------
// Corp-level matching
// ---------------------------------------------------------------------------
interface CorpField {
text: string | undefined;
weight: number;
}
function corpSearchFields(corp: CorpConfig): CorpField[] {
return [
{ text: corp.name, weight: 1.2 },
{ text: corp.id, weight: 1.1 },
{ text: corp.source.staffId, weight: 1.0 },
{ text: (corp.source as any).domain, weight: 1.0 },
{ text: (corp.source as any).corpId, weight: 1.0 },
{ text: corp.seal.tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantName, weight: 1.1 },
{ text: corp.testCorpId, weight: 1.0 },
{ text: corp.prodCorpId, weight: 1.0 },
{ text: corp.environment ?? "production", weight: 0.8 },
{ text: corp.source.type, weight: 0.8 },
{ text: (corp.source as any).provider, weight: 0.8 }
];
}
interface WeightedMatch {
score: number;
reason: MatchReason;
}
/** Keeps the higher-scoring candidate; ties stay with the earlier match. */
function strongerMatch(current: WeightedMatch, candidate: WeightedMatch): WeightedMatch {
return candidate.score > current.score ? candidate : current;
}
function matchCorpFields(
fields: CorpField[],
query: string,
options: FuzzyMatchOptions
): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = fuzzyMatchString(query, field.text, options);
if (res.matched) {
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
/**
* When a long Chinese query contains a compact enterprise name in order (for
* example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
* retain that candidate as a lower-confidence abbreviation match. This is
* deliberately below exact/substring/pinyin matches and disabled in strict mode.
*/
function matchCorpAbbreviation(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
if (queryChinese.length < 3) return best;
for (const field of fields) {
if (!field.text) continue;
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
const prefix = targetChinese.slice(0, 2);
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
best = strongerMatch(best, { score: 0.74 * field.weight, reason: "abbreviation" });
}
return best;
}
function matchCorpTokens(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = matchTokenizedQuery(query, field.text);
if (res.matched) {
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
/**
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
* returning the highest match score and reason.
*/
export function matchCorp(
corp: CorpConfig,
query: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const fields = corpSearchFields(corp);
let best = matchCorpFields(fields, query, options);
if (!options.strict) {
best = strongerMatch(best, matchCorpAbbreviation(fields, query));
best = strongerMatch(best, matchCorpTokens(fields, query));
}
return {
matched: best.score > 0,
score: best.score,
reason: best.reason
};
}
// ---------------------------------------------------------------------------
// Corpus filtering & ranking
// ---------------------------------------------------------------------------
/**
* Once a strong candidate exists, suppress weak token-only suggestions. This
* keeps a query such as "苏州园区测绘" focused on the compact-name match
* instead of also returning every enterprise that merely contains "测绘".
*/
function suppressWeakMatches(scored: Array<{ corp: CorpConfig; score: number }>): CorpConfig[] {
const strongMatches = scored.filter((item) => item.score >= 0.8);
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
}
/**
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
* and automatically sorts the matching results from highest relevance to lowest.
*/
export function filterCorpsFuzzy(
corps: CorpConfig[],
query: string,
options: FuzzyMatchOptions = {}
): CorpConfig[] {
const trimmed = query.trim();
if (!trimmed) return corps;
const scored: Array<{ corp: CorpConfig; score: number }> = [];
for (const corp of corps) {
const res = matchCorp(corp, trimmed, options);
if (res.matched) {
scored.push({ corp, score: res.score });
}
}
// Sort by match score descending (highest confidence first)
scored.sort((a, b) => b.score - a.score);
return suppressWeakMatches(scored);
}
+140
View File
@@ -0,0 +1,140 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../config/types.js";
import type { FuzzyMatchOptions } from "./types.js";
import { filterCorpsFuzzy } from "./rank.js";
// Golden evaluation set for corp search: real-shaped (query -> expected result)
// pairs collected from usage regressions and CLI tests. Every tuning change to
// scores/thresholds must keep this green; grow it with every real-world
// mis-hit or miss instead of re-tuning against a single complaint.
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
tenantSlug: `${id}-slug`,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "seal",
token: `${id}-token`,
sealUrl: `https://${id}.seal.test`,
expiresIn: 3600,
staffId: `staff-${id}`
},
auth: {
refreshTtl: 300
},
...overrides
};
}
const HOSE_SOURCE = {
type: "hose",
corpId: "ID01VAdCnJEdFd",
staffId: "staff-channel",
domain: "https://app.ekuaibao.com"
} as any;
const CORPUS: CorpConfig[] = [
makeCorp("corp-xiezihao", "谢子豪"),
makeCorp("corp-qudao", "渠道AI演示环境", { source: HOSE_SOURCE }),
makeCorp("corp-acme", "Acme Global", { environment: "test" }),
makeCorp("corp-yuance", "园测信息科技股份有限公司"),
makeCorp("corp-yutai", "钰泰半导体股份有限公司"),
makeCorp("corp-huaxin", "华芯半导体股份有限公司"),
makeCorp("corp-nanjing", "南京测绘"),
makeCorp("corp-pingan", "中国平安人寿保险股份有限公司"),
makeCorp("corp-gb", "GB国际(集团)有限公司"),
makeCorp("corp-shengchan", "生产正式企业", {
source: {
type: "seal",
token: "shengchan-token",
sealUrl: "https://shengchan.seal.test",
expiresIn: 3600,
staffId: "admin-zhangsan"
} as any
})
];
interface GoldenCase {
query: string;
/** The id that must rank first. */
top?: string;
/** Ids that must appear somewhere in the results. */
includes?: string[];
/** Ids that must not appear (noise suppression checks). */
excludes?: string[];
/** No corp may match at all. */
empty?: boolean;
options?: FuzzyMatchOptions;
}
const GOLDEN: GoldenCase[] = [
// Exact & substring bands
{ query: "园测信息科技股份有限公司", top: "corp-yuance" },
{ query: "园测信息", top: "corp-yuance" },
{ query: "信息科技", top: "corp-yuance" },
{ query: "平安", top: "corp-pingan" },
{ query: "渠道", top: "corp-qudao" },
// Initials / pinyin / homophones
{ query: "xzh", top: "corp-xiezihao" },
{ query: "xiezihao", top: "corp-xiezihao" },
{ query: "鞋子豪", top: "corp-xiezihao" },
{ query: "谢自豪", top: "corp-xiezihao" },
{ query: "qudao", top: "corp-qudao" },
{ query: "sc", top: "corp-shengchan" },
{ query: "盛产", top: "corp-shengchan" },
{ query: "yuan-ce", top: "corp-yuance" },
// Typo tolerance
{ query: "xieziha", top: "corp-xiezihao" },
{ query: "zhangsa", top: "corp-shengchan" },
// Tokenized Chinese queries with a contextual typo
{ query: "瑞泰半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
{ query: "瑞泰 半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
{ query: "半导体 瑞泰", top: "corp-yutai", excludes: ["corp-huaxin"] },
{ query: "钰泰 半导体", top: "corp-yutai" },
// Compact name inside a long query (abbreviation + weak suppression)
{ query: "苏州园区测绘", top: "corp-yuance", excludes: ["corp-nanjing"] },
// Identifier fields
{ query: "staff-channel", top: "corp-qudao" },
{ query: "ID01VAdCnJEdFd", top: "corp-qudao" },
{ query: "test", top: "corp-acme" },
// Full-width / half-width (NFKC)
{ query: "GB", top: "corp-gb" },
{ query: "gb", top: "corp-gb" },
// Strict mode
{ query: "钰泰半导体", options: { strict: true }, top: "corp-yutai" },
{ query: "瑞泰半导体", options: { strict: true }, empty: true },
{ query: "苏州园区测绘", options: { strict: true }, empty: true },
// Unrelated queries match nothing
{ query: "alibaba", empty: true },
{ query: "腾讯", empty: true }
];
describe("corp search golden set", () => {
for (const golden of GOLDEN) {
const label = `golden: ${golden.query}${golden.options?.strict ? " --strict" : ""}`;
test(label, () => {
const results = filterCorpsFuzzy(CORPUS, golden.query, golden.options ?? {});
const ids = results.map((corp) => corp.id);
if (golden.empty) {
expect(ids).toEqual([]);
}
if (golden.top) {
expect(ids[0]).toBe(golden.top);
}
for (const id of golden.includes ?? []) {
expect(ids).toContain(id);
}
for (const id of golden.excludes ?? []) {
expect(ids).not.toContain(id);
}
});
}
});
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import { normalizeFuzzyPinyin } from "./pinyin.js";
describe("normalizeFuzzyPinyin", () => {
test("normalizes retroflex to flat consonants", () => {
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
expect(normalizeFuzzyPinyin("超")).toContain("cao");
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
});
test("normalizes front and back nasals", () => {
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
});
test("normalizes homophones to identical representations", () => {
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
});
test("memoizes repeated inputs", () => {
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("谢子豪"));
});
});
+41
View File
@@ -0,0 +1,41 @@
import { pinyin } from "pinyin-pro";
// Query and target strings repeat across corps and fields within one search run
// (one query × N corps × 13 fields), so memoize by raw input. Bounded: queries
// per process are few, but clear instead of growing without limit.
const fuzzyPinyinCache = new Map<string, string>();
const PINYIN_CACHE_LIMIT = 128;
/**
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
* - Strips non-alphanumeric whitespace
*/
export function normalizeFuzzyPinyin(str: string): string {
const cached = fuzzyPinyinCache.get(str);
if (cached !== undefined) return cached;
let normalized = "";
if (str) {
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
normalized = pyTokens
.map((token) =>
token
.toLowerCase()
.replace(/zh/g, "z")
.replace(/ch/g, "c")
.replace(/sh/g, "s")
.replace(/iang/g, "ian")
.replace(/uang/g, "uan")
.replace(/ang/g, "an")
.replace(/eng/g, "en")
.replace(/ing/g, "in")
)
.join("");
}
if (fuzzyPinyinCache.size >= PINYIN_CACHE_LIMIT) fuzzyPinyinCache.clear();
fuzzyPinyinCache.set(str, normalized);
return normalized;
}
+156
View File
@@ -0,0 +1,156 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../config/types.js";
import { filterCorpsFuzzy } from "./rank.js";
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
tenantSlug: `${id}-slug`,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "seal",
token: `${id}-token`,
sealUrl: `https://${id}.seal.test`,
expiresIn: 3600,
staffId: `staff-${id}`
},
auth: {
refreshTtl: 300
},
...overrides
};
}
describe("filterCorpsFuzzy", () => {
const corp1 = makeCorp("xiezihao", "谢子豪", {
testCorpId: "test-xzh"
});
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
source: {
type: "hose",
corpId: "ID01VAdCnJEdFd",
staffId: "staff-channel",
domain: "https://app.ekuaibao.com"
} as any
});
const corp3 = makeCorp("acme-corp", "Acme Global", {
environment: "test"
});
const corps = [corp1, corp2, corp3];
test("finds enterprise by homophone", () => {
const results = filterCorpsFuzzy(corps, "鞋子豪");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by initials", () => {
const results = filterCorpsFuzzy(corps, "xzh");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by missing letter query", () => {
const results = filterCorpsFuzzy(corps, "xieziha");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by pinyin of Chinese name", () => {
const results = filterCorpsFuzzy(corps, "qudao");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("finds enterprise by hose corpId or staffId", () => {
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
expect(staffResults.length).toBe(1);
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("strict mode filtering excludes fuzzy homophone matches", () => {
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
expect(fuzzyRes.length).toBe(1);
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
expect(strictRes.length).toBe(0);
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
expect(strictExact.length).toBe(1);
});
test("ranks exact match higher than fuzzy matches", () => {
const cExact = makeCorp("test-qudao", "渠道");
const cFuzzy = makeCorp("test-other", "渠到另外一家");
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
expect(ranked[0]!.id).toBe("test-qudao");
});
test("finds a compact enterprise name inside a longer Chinese query", () => {
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
const unrelated = makeCorp("corp-other", "南京测绘");
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
expect(results[0]!.id).toBe("corp-yuan-ce");
expect(results).toHaveLength(1);
});
test("keeps strict search limited to exact substrings", () => {
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
expect(results).toEqual([]);
});
test("matches Chinese name and industry words despite a contextual name typo", () => {
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
const sameIndustry = makeCorp("corp-other", "华芯半导体股份有限公司");
for (const query of ["瑞泰半导体", "瑞泰 半导体", "半导体 瑞泰", "钰泰 半导体"]) {
expect(filterCorpsFuzzy([sameIndustry, target], query).map((corp) => corp.id))
.toEqual([target.id]);
}
});
test("requires another matching word before tolerating a typo in a short Chinese name", () => {
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
expect(filterCorpsFuzzy([target], "瑞泰")).toEqual([]);
expect(filterCorpsFuzzy([target], "瑞泰 半导体", { strict: true })).toEqual([]);
expect(filterCorpsFuzzy([target], "钰泰半导体", { strict: true })).toEqual([target]);
});
test("breaks relevance ties by recent usage", () => {
const a = makeCorp("corp-a", "匹配企业甲");
const b = makeCorp("corp-b", "匹配企业乙");
// Both names prefix-match at the same score; higher usage wins even against
// input order and zh-CN name collation (甲 < 乙 alphabetically).
const usage = new Map([["corp-a", 1], ["corp-b", 5]]);
const results = filterCorpsFuzzy([a, b], "匹配企业", {}, usage);
expect(results.map((corp) => corp.id)).toEqual(["corp-b", "corp-a"]);
});
test("usage never outranks a better match", () => {
const weak = makeCorp("corp-weak", "匹配企业甲");
const strong = makeCorp("corp-strong", "匹配企业");
const usage = new Map([["corp-weak", 99]]);
const results = filterCorpsFuzzy([weak, strong], "匹配企业", {}, usage);
expect(results[0]!.id).toBe("corp-strong");
});
test("falls back to name and id order when usage is absent", () => {
const second = makeCorp("corp-b", "匹配企业乙");
const first = makeCorp("corp-a", "匹配企业甲");
const results = filterCorpsFuzzy([second, first], "匹配企业");
expect(results.map((corp) => corp.id)).toEqual(["corp-a", "corp-b"]);
});
});
+54
View File
@@ -0,0 +1,54 @@
import type { CorpConfig } from "../config/types.js";
import { matchCorp } from "./corp.js";
import type { FuzzyMatchOptions } from "./types.js";
/**
* Once a strong candidate exists, suppress weak token-only suggestions. This
* keeps a query such as "苏州园区测绘" focused on the compact-name match
* instead of also returning every enterprise that merely contains "测绘".
*/
function suppressWeakMatches(scored: Array<{ corp: CorpConfig; score: number }>): CorpConfig[] {
const strongMatches = scored.filter((item) => item.score >= 0.8);
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
}
/**
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
* and automatically sorts the matching results from highest relevance to lowest.
*
* `usageScores` (optional, from `getRecentCorpUsageScores`) only breaks ties among
* equally-relevant results — recent usage can lift a corp within a score band but
* never above a better match.
*/
export function filterCorpsFuzzy(
corps: CorpConfig[],
query: string,
options: FuzzyMatchOptions = {},
usageScores?: ReadonlyMap<string, number>
): CorpConfig[] {
const trimmed = query.trim();
if (!trimmed) return corps;
const scored: Array<{ corp: CorpConfig; score: number }> = [];
for (const corp of corps) {
const res = matchCorp(corp, trimmed, options);
if (res.matched) {
scored.push({ corp, score: res.score });
}
}
// Sort by match score descending (highest confidence first); relevance ties
// fall back to recent usage, then name, then id for stable ordering.
scored.sort((a, b) => {
if (a.score !== b.score) return b.score - a.score;
const usageA = usageScores?.get(a.corp.id) ?? 0;
const usageB = usageScores?.get(b.corp.id) ?? 0;
if (usageA !== usageB) return usageB - usageA;
const byName = (a.corp.name ?? a.corp.id).localeCompare(b.corp.name ?? b.corp.id, "zh-CN");
if (byName !== 0) return byName;
return a.corp.id.localeCompare(b.corp.id);
});
return suppressWeakMatches(scored);
}
+61
View File
@@ -0,0 +1,61 @@
// Chinese query segmentation: word-level via Intl.Segmenter (with adjacent
// single-character run merging for uncommon enterprise names) and term-level
// via overlapping two-character windows.
let wordSegmenter: Intl.Segmenter | undefined;
// The same query string is segmented once per corp × field without memoization;
// cache by raw input (bounded like the pinyin cache).
const wordsCache = new Map<string, string[]>();
const termsCache = new Map<string, string[]>();
const SEGMENT_CACHE_LIMIT = 64;
function cached(key: string, cache: Map<string, string[]>, compute: () => string[]): string[] {
const hit = cache.get(key);
if (hit !== undefined) return hit;
const value = compute();
if (cache.size >= SEGMENT_CACHE_LIMIT) cache.clear();
cache.set(key, value);
return value;
}
export function searchTerms(value: string): string[] {
return cached(value, termsCache, () => {
const normalized = value.normalize("NFKC").trim().toLowerCase();
const chunks = normalized.match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
return chunks.flatMap((chunk) => {
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
if (chunk.length <= 2) return [chunk];
const terms: string[] = [];
for (let index = 0; index < chunk.length - 1; index += 1) {
terms.push(chunk.slice(index, index + 2));
}
return terms;
});
});
}
export function searchWords(value: string): string[] {
return cached(value, wordsCache, () => {
wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" });
const words: string[] = [];
let nameChars = "";
const flushName = () => {
if (nameChars) words.push(nameChars);
nameChars = "";
};
for (const part of wordSegmenter.segment(value.normalize("NFKC").trim().toLowerCase())) {
// Uncommon enterprise names are often segmented into individual characters.
if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) {
nameChars += part.segment;
} else {
flushName();
if (part.isWordLike) words.push(part.segment);
}
}
flushName();
return words;
});
}
+54
View File
@@ -0,0 +1,54 @@
import { minSubstringLevenshtein } from "./distance.js";
import { fuzzyMatchString } from "./engine.js";
import { searchTerms, searchWords } from "./segment.js";
import type { MatchScoreResult } from "./types.js";
function noMatch(): MatchScoreResult {
return { matched: false, score: 0, reason: "none" };
}
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
if (queryWords.length < 2) return null;
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
// A second matching word supplies context for a typo in a two-character
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
));
if (!allWordsMatch) return null;
return { matched: true, score: 0.76, reason: "tokens" };
}
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
function matchQueryTerms(
query: string,
queryWordCount: number,
target: string
): MatchScoreResult | null {
const queryTerms = searchTerms(query);
if (queryTerms.length < 2) return null;
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
if (matchedTerms.length === 0) return null;
const coverage = matchedTerms.length / queryTerms.length;
return {
matched: true,
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
reason: "tokens"
};
}
export function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
if (!/[\u4e00-\u9fa5]/.test(query)) {
return noMatch();
}
const queryWords = searchWords(query);
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
}
+34
View File
@@ -0,0 +1,34 @@
export interface FuzzyMatchOptions {
/**
* If true, disables fuzzy/soft matching and requires exact substring matching.
* Defaults to false (soft search by default).
*/
strict?: boolean;
/**
* Maximum edit distance allowed for typo / missing letter tolerance.
* Defaults based on query length:
* - length <= 2: 0 (no fuzzy edits)
* - length 3..5: 1 (missing 1 letter or 1 typo)
* - length >= 6: 2 (missing 1-2 letters)
*/
maxDistance?: number;
}
export type MatchReason =
| "exact"
| "substring"
| "initials"
| "pinyin"
| "fuzzy_pinyin"
| "levenshtein"
| "subsequence"
| "tokens"
| "abbreviation"
| "none";
export interface MatchScoreResult {
matched: boolean;
score: number;
reason: MatchReason;
}