diff --git a/.agents/rules/branch-naming.md b/.agents/rules/branch-naming.md new file mode 100644 index 0000000..3156f2d --- /dev/null +++ b/.agents/rules/branch-naming.md @@ -0,0 +1,32 @@ +--- +description: "本设备创建分支的命名规范(设备前缀)与 git hook 机械强制" +trigger: "always" +--- + +# 分支命名规范 (设备前缀 + 机械强制) + +为了让"哪台设备/哪个 Agent 开的分支"一眼可辨,本仓库的分支命名按创建设备加前缀。规则文档随仓库走,前缀的值留在各设备本地。 + +## 1. 命名规则 + +- **格式**:`<设备键>/<小写连字符主题>`。本机(这台 Mac)的设备键是 `mac15`,例如:`mac15/improve-corp-search`。 +- **设备键声明**:每个克隆只声明一次,写入本地 git 配置(存于 `.git/config`,不提交、随设备走): + ```bash + git config seal.branchPrefix mac15 # 这台 Mac;其他设备换自己的键,不设置则本规则休眠 + ``` +- **Agent 行为要求**:任何 Agent(Codex/ZCode/Claude 等)创建分支前,先执行 `git config seal.branchPrefix`;有值则分支名必须以 `<值>/` 开头,没有值时用普通主题名即可。 + +## 2. 保留名(不受设备前缀约束) + +- `main`:主分支。 +- `codex/release-vX.Y.Z`:发版自动化专用(`bun run release` 创建),沿用既有约定。 + +## 3. 机械强制(不依赖 Agent 自觉) + +- 钩子:`.githooks/pre-commit` 与 `.githooks/pre-push` 通过 `.githooks/branch-guard.sh` 校验分支名,违规即拒绝并给出改名命令。`package.json` 的 `prepare` 脚本在 `bun install` 时自动设置 `core.hooksPath=.githooks`,新克隆无需手动接线。 +- **存量分支豁免**:已存在于 origin 的旧分支(如云端 Agent 创建的 `codex/*`)不拦,避免影响在途 PR。 +- **逃生门**:`git commit --no-verify` / `git push --no-verify` 可一次性绕过,仅用于特殊情况,不要养成习惯。 + +## 4. 相关规则 + +- 分支/工作树清理见 `.agents/rules/workspace-hygiene.md`;PR 工作流见 `.agents/rules/issue-pr-workflow.md`。 diff --git a/.githooks/branch-guard.sh b/.githooks/branch-guard.sh new file mode 100755 index 0000000..8dc84f6 --- /dev/null +++ b/.githooks/branch-guard.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Shared branch-naming guard: .agents/rules/branch-naming.md +# Devices opt in per clone: git config seal.branchPrefix (e.g. mac15) +# Sourced by pre-commit and pre-push. + +# guard_branch_name — returns 1 with guidance when the name breaks the rule. +guard_branch_name() { + local branch="$1" + [ -n "$branch" ] || return 0 + + # Reserved names: mainline branches and the release automation. + case "$branch" in + main|master|develop) return 0 ;; + codex/release-*) return 0 ;; + esac + + # Enforcement is opt-in per device; without a configured prefix this guard is dormant. + local prefix + prefix="$(git config seal.branchPrefix 2>/dev/null || true)" + [ -n "$prefix" ] || return 0 + + case "$branch" in + "$prefix"/*) return 0 ;; + esac + + # Branches that already exist on origin (created elsewhere, e.g. cloud agents) stay usable. + if git rev-parse -q --verify "refs/remotes/origin/$branch" >/dev/null 2>&1; then + return 0 + fi + + echo "" >&2 + echo "🛑 [branch-guard] Branch '$branch' violates the device branch-prefix rule (.agents/rules/branch-naming.md)." >&2 + echo " Branches created on this device must start with '${prefix}/'." >&2 + echo " 👉 Rename and retry: git branch -m '${prefix}/${branch##*/}'" >&2 + echo " (One-off bypass: git commit --no-verify / git push --no-verify)" >&2 + echo "" >&2 + return 1 +} diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..457fe5c --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,6 @@ +#!/bin/bash +# Git pre-commit hook: enforce the device branch-prefix rule +# (.agents/rules/branch-naming.md) via .githooks/branch-guard.sh +source "$(dirname "$0")/branch-guard.sh" + +guard_branch_name "$(git branch --show-current)" diff --git a/.githooks/pre-push b/.githooks/pre-push index 30d76b3..3e48796 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -1,12 +1,24 @@ #!/bin/bash # Git pre-push hook: Prevent accidental direct push to origin/main or GitHub/main # Enforces the PR workflow required by AGENTS.md & .agents/rules/issue-pr-workflow.md +# Also enforces the device branch-prefix rule via .githooks/branch-guard.sh + +source "$(dirname "$0")/branch-guard.sh" remote="$1" url="$2" zero="0000000000000000000000000000000000000000" while read local_ref local_oid remote_ref remote_oid; do + # Device branch-prefix rule (.agents/rules/branch-naming.md); deletions are exempt + case "$local_ref" in + refs/heads/*) + if [ "$local_oid" != "$zero" ]; then + guard_branch_name "${local_ref#refs/heads/}" || exit 1 + fi + ;; + esac + # If pushing the main branch (or pushing to remote main) if [ "$remote_ref" = "refs/heads/main" ] || [ "$local_ref" = "refs/heads/main" ]; then # When pushing to origin or GitHub (main repository) diff --git a/AGENTS.md b/AGENTS.md index 460177a..c6c2554 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,7 +51,8 @@ Use `bun:test` with `describe`, `test`, and `expect`. Place tests next to covere ## Commit & Pull Request Guidelines -Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Specific workflows and domain guidelines are maintained in `.agents/rules/`: +Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Branches created on a workstation must carry that device's prefix from `git config seal.branchPrefix` (e.g. `mac15/improve-corp-search` on this Mac), enforced by the `.githooks` pre-commit/pre-push guards. Specific workflows and domain guidelines are maintained in `.agents/rules/`: +- Branch naming (device-prefix rule & mechanical enforcement): `.agents/rules/branch-naming.md` - Issue triage & PR workflow (No premature release): `.agents/rules/issue-pr-workflow.md` - CLI stream & exit code protocol: `.agents/rules/cli-protocol.md` - Testing conventions & isolation: `.agents/rules/testing.md` diff --git a/src/cli/commands/corps.test.ts b/src/cli/commands/corps.test.ts index 269f267..7a0ad7d 100644 --- a/src/cli/commands/corps.test.ts +++ b/src/cli/commands/corps.test.ts @@ -349,6 +349,32 @@ describe("corps get and search", () => { expect(data.source.tokenMasked).toContain("..."); }); + test("corps search ranks a Chinese name typo above industry-only matches", async () => { + const enterprises = setupConfigEnv(); + mkdirSync(enterprises, { recursive: true }); + for (const [id, name] of [ + ["corp-yutai", "钰泰半导体股份有限公司"], + ["corp-other", "华芯半导体股份有限公司"] + ]) { + writeFileSync(join(enterprises, `${id}.json`), JSON.stringify({ + id, + name, + seal: { url: `https://${id}.seal.test` }, + source: { type: "hose", appKey: "fixture-key", appSecurity: "fixture-secret", corpId: id, staffId: "fixture-staff" }, + auth: { refreshTtl: 300 } + })); + } + + for (const query of ["瑞泰半导体", "瑞泰 半导体"]) { + const result = await runCli(["corps", "search", query]); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).map((corp: { id: string }) => corp.id)).toEqual(["corp-yutai"]); + } + const strict = await runCli(["corps", "search", "瑞泰半导体", "--strict"]); + expect(strict.exitCode).toBe(0); + expect(JSON.parse(strict.stdout)).toEqual([]); + }); + test("corps search filters across name, staffId, environment, and keywords", async () => { const enterprises = setupConfigEnv(); mkdirSync(enterprises, { recursive: true }); diff --git a/src/core/search/fuzzy.test.ts b/src/core/search/fuzzy.test.ts index 9e630c1..b3d3e97 100644 --- a/src/core/search/fuzzy.test.ts +++ b/src/core/search/fuzzy.test.ts @@ -238,5 +238,21 @@ describe("fuzzy search utilities", () => { 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]); + }); }); }); diff --git a/src/core/search/fuzzy.ts b/src/core/search/fuzzy.ts index e8d5528..d87b066 100644 --- a/src/core/search/fuzzy.ts +++ b/src/core/search/fuzzy.ts @@ -36,6 +36,10 @@ export interface MatchScoreResult { reason: MatchReason; } +// --------------------------------------------------------------------------- +// Edit-distance & character-order primitives +// --------------------------------------------------------------------------- + /** * Standard Levenshtein distance between two strings. */ @@ -95,6 +99,24 @@ export function minSubstringLevenshtein(query: string, target: string): number { 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 @@ -120,20 +142,6 @@ export function normalizeFuzzyPinyin(str: string): string { .join(""); } -/** - * 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; -} - function searchTerms(value: string): string[] { const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? []; return chunks.flatMap((chunk) => { @@ -148,31 +156,159 @@ function searchTerms(value: string): string[] { }); } -function matchTokenizedQuery(query: string, target: string): MatchScoreResult { - if (!/[\u4e00-\u9fa5]/.test(query)) { - return { matched: false, score: 0, reason: "none" }; +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; +} - const queryTerms = searchTerms(query); - if (queryTerms.length < 2) return { matched: false, score: 0, reason: "none" }; - - const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched); - if (matchedTerms.length > 0) { - const coverage = matchedTerms.length / queryTerms.length; - return { - matched: true, - score: 0.56 + coverage * 0.2, - reason: "tokens" - }; - } +// --------------------------------------------------------------------------- +// 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, @@ -183,120 +319,96 @@ export function fuzzyMatchString( const normTarget = target.trim().toLowerCase(); if (!normQuery || !normTarget) { - return { matched: false, score: 0, reason: "none" }; + return noMatch(); } - // 1. Exact match + // Exact match if (normTarget === normQuery) { return { matched: true, score: 1.0, reason: "exact" }; } - // 2. Substring match + // 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 { matched: false, score: 0, reason: "none" }; + return noMatch(); } - const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget); - const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery); - - // 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产") - if (targetHasChinese && normQuery.length >= 2) { - const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" }) - .join("") - .toLowerCase(); - if (targetInitials.includes(normQuery)) { - return { matched: true, score: 0.9, reason: "initials" }; - } - } - - // 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets) - if (targetHasChinese) { - try { - const pm = pinyinMatch(normTarget, normQuery, { precision: "start" }); - if (pm && pm.length > 0) { - return { matched: true, score: 0.88, reason: "pinyin" }; - } - } catch { - // ignore match errors if non-standard regex chars - } - } - - // 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音) - let targetFuzzyPinyin = ""; - let queryFuzzyPinyin = ""; - if (targetHasChinese || queryHasChinese) { - targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget); - queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery); - - if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) { - return { matched: true, score: 0.85, reason: "fuzzy_pinyin" }; - } - } - - // 6. Missing letter / Typo tolerance (Levenshtein Distance) - // Determine allowed 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) - const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2; - const maxAllowedDist = options.maxDistance ?? defaultMaxDist; - - if (maxAllowedDist > 0) { - // Check raw string distance - const rawDist = minSubstringLevenshtein(normQuery, normTarget); - if (rawDist <= maxAllowedDist) { - 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) - if ( - (targetHasChinese || queryHasChinese) && - queryFuzzyPinyin.length >= 3 && - targetFuzzyPinyin.length >= 3 - ) { - const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin); - if (pinyinDist <= maxAllowedDist) { - return { - matched: true, - score: Math.max(0.6, 0.78 - pinyinDist * 0.1), - reason: "levenshtein" - }; - } - } - } - - // 7. Subsequence match (loose character order, min query length 3) - if (normQuery.length >= 3) { - if ( - isSubsequence(normQuery, normTarget) || - ((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin)) - ) { - return { matched: true, score: 0.65, reason: "subsequence" }; - } - } - - return { matched: false, score: 0, reason: "none" }; + 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() + ); } -/** - * Matches an enterprise (`CorpConfig`) against a query across all its searchable fields, - * returning the highest match score and reason. - */ -export function matchCorp( - corp: CorpConfig, +// --------------------------------------------------------------------------- +// 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, - options: FuzzyMatchOptions = {} -): MatchScoreResult { - const fields: Array<{ text: string | undefined; weight: number }> = [ + 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 }, @@ -311,63 +423,106 @@ export function matchCorp( { text: corp.source.type, weight: 0.8 }, { text: (corp.source as any).provider, weight: 0.8 } ]; +} - let bestScore = 0; - let bestReason: MatchReason = "none"; +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) { - const weightedScore = res.score * field.weight; - if (weightedScore > bestScore) { - bestScore = weightedScore; - bestReason = res.reason; - } + 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. +/** + * 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) { - const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? ""; - if (queryChinese.length >= 3) { - 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; - - const weightedScore = 0.74 * field.weight; - if (weightedScore > bestScore) { - bestScore = weightedScore; - bestReason = "abbreviation"; - } - } - } - - for (const field of fields) { - if (!field.text) continue; - const res = matchTokenizedQuery(query, field.text); - if (res.matched) { - const weightedScore = res.score * field.weight; - if (weightedScore > bestScore) { - bestScore = weightedScore; - bestReason = res.reason; - } - } - } + best = strongerMatch(best, matchCorpAbbreviation(fields, query)); + best = strongerMatch(best, matchCorpTokens(fields, query)); } return { - matched: bestScore > 0, - score: bestScore, - reason: bestReason + 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. @@ -392,9 +547,5 @@ export function filterCorpsFuzzy( // Sort by match score descending (highest confidence first) scored.sort((a, b) => b.score - a.score); - // 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 "测绘". - const strongMatches = scored.filter((item) => item.score >= 0.8); - return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp); + return suppressWeakMatches(scored); }