@tokenroll/llmdoc 3.5.2 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { normalizeRepoRelativePath, resolveInsideRoot } from "./fs.js";
4
+ import { validateLlmdocConfig } from "./schema.js";
5
+ export const LLMDOC_CONFIG_FILENAME = "llmdoc.config.json";
6
+ export function loadLlmdocConfig(rootDir, documentsByLlmdocPath) {
7
+ const configPath = path.join(rootDir, LLMDOC_CONFIG_FILENAME);
8
+ if (!fs.existsSync(configPath)) {
9
+ return { exists: false, config: null, preloadPaths: [], issues: [] };
10
+ }
11
+ let safeConfigPath;
12
+ try {
13
+ safeConfigPath = resolveInsideRoot(rootDir, LLMDOC_CONFIG_FILENAME);
14
+ }
15
+ catch (error) {
16
+ return invalidConfig(`The config file must remain inside the repository: ${error.message}`);
17
+ }
18
+ let input;
19
+ try {
20
+ input = JSON.parse(fs.readFileSync(safeConfigPath, "utf8"));
21
+ }
22
+ catch (error) {
23
+ return invalidConfig(`JSON parse failed: ${error.message}`);
24
+ }
25
+ const schemaErrors = validateLlmdocConfig(input);
26
+ if (schemaErrors.length > 0) {
27
+ return {
28
+ exists: true,
29
+ config: null,
30
+ preloadPaths: [],
31
+ issues: schemaErrors.map((message) => configIssue("config.invalid", `Invalid config: ${message}`))
32
+ };
33
+ }
34
+ const config = input;
35
+ const preloadPaths = [];
36
+ const issues = [];
37
+ const seen = new Set();
38
+ for (const rawPath of config.startup?.preload ?? []) {
39
+ let normalized;
40
+ try {
41
+ normalized = normalizePreloadPath(rawPath);
42
+ }
43
+ catch (error) {
44
+ issues.push(configIssue("config.startup.preload.path", error.message));
45
+ continue;
46
+ }
47
+ if (seen.has(normalized)) {
48
+ issues.push(configIssue("config.startup.preload.duplicate", `startup.preload contains the same normalized document more than once; duplicate ignored: llmdoc/${normalized}`, "warning"));
49
+ continue;
50
+ }
51
+ seen.add(normalized);
52
+ preloadPaths.push(normalized);
53
+ if (documentsByLlmdocPath && !documentsByLlmdocPath.has(normalized)) {
54
+ issues.push(configIssue("config.startup.preload.missing", `startup.preload document does not exist: llmdoc/${normalized}`));
55
+ }
56
+ }
57
+ return {
58
+ exists: true,
59
+ config,
60
+ preloadPaths: issues.some((issue) => issue.severity === "error") ? [] : preloadPaths,
61
+ issues
62
+ };
63
+ }
64
+ export function formatStartupPreloadDocuments(documents) {
65
+ if (documents.length === 0) {
66
+ return "";
67
+ }
68
+ const lines = [
69
+ `llmdoc startup preload begins (${documents.length} document(s)). The configured bodies are provided directly below. If the final completion marker is visible, these bodies are complete and do not need another search/show; otherwise retrieve any missing document with npx @tokenroll/llmdoc show.`
70
+ ];
71
+ for (const document of documents) {
72
+ lines.push("", `=== llmdoc/${document.llmdocPath} [${document.frontmatter.kind}] (startup preload) ===`, document.body);
73
+ }
74
+ lines.push("", "=== llmdoc startup preload complete ===");
75
+ return lines.join("\n");
76
+ }
77
+ export function formatCompactPreloadIndex(preloadPaths) {
78
+ if (preloadPaths.length === 0) {
79
+ return "";
80
+ }
81
+ return `Configured startup preload bodies were not re-injected after compaction. Document IDs: ${preloadPaths
82
+ .map((preloadPath) => `llmdoc/${preloadPath}`)
83
+ .join(", ")}. Retrieve a body with npx @tokenroll/llmdoc show only when the compacted context no longer contains what the task needs.`;
84
+ }
85
+ export function rewriteStartupPreloadForMove(config, mapping) {
86
+ const preload = config.startup?.preload;
87
+ if (!preload || preload.length === 0) {
88
+ return { config, changed: false };
89
+ }
90
+ const moveByPath = new Map(mapping.map((item) => [item.oldLlmdocPath, item.newLlmdocPath]));
91
+ let changed = false;
92
+ const rewritten = preload.map((rawPath) => {
93
+ let normalized;
94
+ try {
95
+ normalized = normalizePreloadPath(rawPath);
96
+ }
97
+ catch {
98
+ return rawPath;
99
+ }
100
+ const nextPath = moveByPath.get(normalized);
101
+ if (!nextPath) {
102
+ return rawPath;
103
+ }
104
+ changed = true;
105
+ const normalizedRaw = rawPath.trim().replaceAll("\\", "/");
106
+ return normalizedRaw.startsWith("llmdoc/") ? `llmdoc/${nextPath}` : nextPath;
107
+ });
108
+ return {
109
+ changed,
110
+ config: changed
111
+ ? {
112
+ ...config,
113
+ startup: {
114
+ ...config.startup,
115
+ preload: rewritten
116
+ }
117
+ }
118
+ : config
119
+ };
120
+ }
121
+ function normalizePreloadPath(rawPath) {
122
+ const trimmed = rawPath.trim().replaceAll("\\", "/");
123
+ const withoutPrefix = trimmed.startsWith("llmdoc/") ? trimmed.slice("llmdoc/".length) : trimmed;
124
+ const normalized = normalizeRepoRelativePath(withoutPrefix);
125
+ if (!normalized.endsWith(".mdx")) {
126
+ throw new Error(`startup.preload accepts only .mdx documents: ${rawPath}`);
127
+ }
128
+ return normalized;
129
+ }
130
+ function invalidConfig(message) {
131
+ return {
132
+ exists: true,
133
+ config: null,
134
+ preloadPaths: [],
135
+ issues: [configIssue("config.read", message)]
136
+ };
137
+ }
138
+ function configIssue(code, message, severity = "error") {
139
+ return {
140
+ severity,
141
+ code,
142
+ path: LLMDOC_CONFIG_FILENAME,
143
+ message
144
+ };
145
+ }
@@ -3,15 +3,15 @@ import { CliError } from "./errors.js";
3
3
  const DOCUMENT_KINDS = ["architecture", "guide", "reference"];
4
4
  export function parseDocTargetShape(repoRelativePath) {
5
5
  if (!repoRelativePath.startsWith("llmdoc/")) {
6
- throw new CliError("目标必须位于 llmdoc/ 下。");
6
+ throw new CliError("The target must be under llmdoc/.");
7
7
  }
8
8
  if (!repoRelativePath.endsWith(".mdx")) {
9
- throw new CliError("目标必须是 .mdx 文档。");
9
+ throw new CliError("The target must be an .mdx document.");
10
10
  }
11
11
  const llmdocPath = repoRelativePath.slice("llmdoc/".length);
12
12
  const segments = llmdocPath.split("/");
13
13
  if (segments.length !== 1 && segments.length !== 2) {
14
- throw new CliError("V3 文档路径仅允许根 singleton 或 topic/file 两层。");
14
+ throw new CliError("V3 document paths allow only a root singleton or topic/file depth.");
15
15
  }
16
16
  const basename = path.posix.basename(llmdocPath);
17
17
  const topic = segments.length === 2 ? (segments[0] ?? null) : null;
@@ -28,7 +28,7 @@ export function parseDocTargetShape(repoRelativePath) {
28
28
  export function assertDocKindMatchesShape(shape) {
29
29
  // V3 不设入口节点:topic 即纯目录,描述由 CLI 从文档 front matter 聚合。
30
30
  if (shape.basename === "index.mdx") {
31
- throw new CliError("V3 不使用 index.mdx 入口节点;请使用普通命名,topic 描述由 llmdoc tree 聚合。");
31
+ throw new CliError("V3 does not use index.mdx entry nodes. Use a regular name; llmdoc tree derives topic descriptions.");
32
32
  }
33
33
  }
34
34
  export function validateMoveTargetShape(shape) {
@@ -46,5 +46,5 @@ export function assertDocumentKind(input) {
46
46
  if (DOCUMENT_KINDS.includes(input)) {
47
47
  return input;
48
48
  }
49
- throw new CliError(`非法 kind: ${input}。允许值: ${DOCUMENT_KINDS.join(", ")}`);
49
+ throw new CliError(`Invalid kind: ${input}. Allowed values: ${DOCUMENT_KINDS.join(", ")}`);
50
50
  }
package/dist/lib/fs.js CHANGED
@@ -6,7 +6,21 @@ export function findProjectRoot(startDir) {
6
6
  if (found) {
7
7
  return found;
8
8
  }
9
- throw new CliError("未找到 llmdoc/ 目录,请在仓库内运行该命令。", 2);
9
+ throw new CliError("No llmdoc/ directory was found. Run this command inside an llmdoc repository.", 2);
10
+ }
11
+ // new 是唯一允许在 llmdoc/ 尚不存在时运行的结构改写命令。
12
+ // 首次创建严格锁定最近 Git 根;无 Git 但已有 llmdoc/ 时保留原有兼容路径。
13
+ export function findProjectRootForNew(startDir) {
14
+ const start = path.resolve(startDir);
15
+ const existingWorkspace = findProjectRootOrNull(start);
16
+ if (existingWorkspace) {
17
+ return existingWorkspace;
18
+ }
19
+ const gitRoot = findNearestGitRootOrNull(start);
20
+ if (gitRoot) {
21
+ return gitRoot;
22
+ }
23
+ throw new CliError("No Git repository was found. Run `git init` before `llmdoc new`.", 2);
10
24
  }
11
25
  export function findProjectRootOrNull(startDir) {
12
26
  const start = path.resolve(startDir);
@@ -52,14 +66,14 @@ function isDirectory(candidate) {
52
66
  export function normalizeRepoRelativePath(input) {
53
67
  const normalized = input.replaceAll("\\", "/");
54
68
  if (!normalized || normalized.startsWith("/") || normalized.includes("\0")) {
55
- throw new CliError(`非法路径: ${input}`);
69
+ throw new CliError(`Invalid path: ${input}`);
56
70
  }
57
71
  const parts = normalized.split("/").filter((part) => part !== ".");
58
72
  if (parts.length === 0) {
59
- throw new CliError(`非法路径: ${input}`);
73
+ throw new CliError(`Invalid path: ${input}`);
60
74
  }
61
75
  if (parts.some((part) => part === ".." || part === "")) {
62
- throw new CliError(`路径必须是仓库内规范化相对路径: ${input}`);
76
+ throw new CliError(`Path must be a normalized repository-relative path: ${input}`);
63
77
  }
64
78
  return parts.join("/");
65
79
  }
@@ -70,19 +84,19 @@ export function resolveInsideRoot(rootDir, repoRelativePath, options) {
70
84
  const nearestExistingAncestor = findNearestExistingAncestor(candidate);
71
85
  const ancestorRealPath = fs.realpathSync(nearestExistingAncestor);
72
86
  if (!isWithinRoot(rootRealPath, ancestorRealPath)) {
73
- throw new CliError(`路径越界或经由符号链接逃逸: ${repoRelativePath}`);
87
+ throw new CliError(`Path escapes the repository directly or through a symlink: ${repoRelativePath}`);
74
88
  }
75
89
  if (fs.existsSync(candidate)) {
76
90
  const candidateRealPath = fs.realpathSync(candidate);
77
91
  if (!isWithinRoot(rootRealPath, candidateRealPath)) {
78
- throw new CliError(`路径越界或经由符号链接逃逸: ${repoRelativePath}`);
92
+ throw new CliError(`Path escapes the repository directly or through a symlink: ${repoRelativePath}`);
79
93
  }
80
94
  return candidateRealPath;
81
95
  }
82
96
  if (options?.allowMissing) {
83
97
  return candidate;
84
98
  }
85
- throw new CliError(`路径不存在: ${repoRelativePath}`);
99
+ throw new CliError(`Path does not exist: ${repoRelativePath}`);
86
100
  }
87
101
  export function isWithinRoot(rootRealPath, candidateRealPath) {
88
102
  return candidateRealPath === rootRealPath || candidateRealPath.startsWith(`${rootRealPath}${path.sep}`);
package/dist/lib/git.js CHANGED
@@ -8,7 +8,7 @@ function runGit(rootDir, args) {
8
8
  encoding: "utf8"
9
9
  });
10
10
  if (result.status !== 0) {
11
- throw new CliError((result.stderr || result.stdout || "git 命令失败").trim());
11
+ throw new CliError((result.stderr || result.stdout || "Git command failed").trim());
12
12
  }
13
13
  return result.stdout.trim();
14
14
  }
@@ -26,6 +26,12 @@ export function gitCommitExists(rootDir, revision) {
26
26
  });
27
27
  return result.status === 0;
28
28
  }
29
+ export function isUnbornHead(rootDir) {
30
+ if (!isGitRepository(rootDir) || runGitSafe(rootDir, ["rev-parse", "--verify", "HEAD"]) !== null) {
31
+ return false;
32
+ }
33
+ return runGitSafe(rootDir, ["symbolic-ref", "--quiet", "HEAD"]) !== null;
34
+ }
29
35
  // shallow clone(CI 常态)里历史 commit 不可达,revision 校验需要据此降级而不是误报陈旧。
30
36
  export function isShallowRepository(rootDir) {
31
37
  return runGitSafe(rootDir, ["rev-parse", "--is-shallow-repository"]) === "true";
@@ -42,10 +48,10 @@ export function readGitState(rootDir, baselineRevision) {
42
48
  stagedPaths: [],
43
49
  unstagedPaths: [],
44
50
  untrackedPaths: [],
45
- degradedReason: "当前目录不是 git 仓库,状态面降级为不可用。"
51
+ degradedReason: "The current directory is not a Git repository; state diagnostics are unavailable."
46
52
  };
47
53
  }
48
- const headRevision = runGitSafe(rootDir, ["rev-parse", "HEAD"]);
54
+ const headRevision = runGitSafe(rootDir, ["rev-parse", "--verify", "HEAD"]);
49
55
  const detached = runGitSafe(rootDir, ["symbolic-ref", "--quiet", "--short", "HEAD"]) === null;
50
56
  const inProgressOperation = detectInProgressOperation(rootDir);
51
57
  const stagedPaths = readPathList(rootDir, ["diff", "--name-only", "--no-renames", "--cached"]);
@@ -59,10 +65,10 @@ export function readGitState(rootDir, baselineRevision) {
59
65
  : null;
60
66
  let degradedReason = null;
61
67
  if (!headRevision) {
62
- degradedReason = "无法解析 HEAD commit。";
68
+ degradedReason = isUnbornHead(rootDir) ? "HEAD has no commit (the current branch is unborn)." : "Unable to resolve the HEAD commit.";
63
69
  }
64
70
  else if (baselineRevision && !gitCommitExists(rootDir, baselineRevision)) {
65
- degradedReason = `baseline.revision 不存在于当前 git 历史: ${baselineRevision}`;
71
+ degradedReason = `baseline.revision does not exist in current Git history: ${baselineRevision}`;
66
72
  }
67
73
  return {
68
74
  available: true,
@@ -110,10 +116,10 @@ export function readCommitsWithChangedPathsSince(rootDir, revision, headRevision
110
116
  }
111
117
  export function canAdvanceRevisions(gitState) {
112
118
  if (!gitState.available || !gitState.headRevision) {
113
- return { ok: false, reason: gitState.degradedReason ?? "git 状态不可用。" };
119
+ return { ok: false, reason: gitState.degradedReason ?? "Git state is unavailable." };
114
120
  }
115
121
  if (gitState.inProgressOperation) {
116
- return { ok: false, reason: `${gitState.inProgressOperation} 进行中,不推进 revision。` };
122
+ return { ok: false, reason: `${gitState.inProgressOperation} is in progress; revisions cannot advance.` };
117
123
  }
118
124
  return { ok: true };
119
125
  }
@@ -64,27 +64,27 @@ export function validateCodeRefTags(body) {
64
64
  const raw = match[0] ?? "";
65
65
  const attributes = match[1] ?? "";
66
66
  if (!raw.endsWith("/>")) {
67
- issues.push("CodeRef 必须使用自闭合写法 <CodeRef ... />。");
67
+ issues.push("CodeRef must use the self-closing form <CodeRef ... />.");
68
68
  continue;
69
69
  }
70
70
  const attrMatches = [...attributes.matchAll(/([A-Za-z]+)="([^"]*)"/g)];
71
71
  const consumed = attrMatches.map((attr) => attr[0]).join(" ").trim();
72
72
  const normalized = attributes.replace(/\s+/g, " ").trim().replace(/\/$/, "").trim();
73
73
  if (normalized && consumed !== normalized) {
74
- issues.push("CodeRef 仅允许双引号属性 path 和可选 symbol。");
74
+ issues.push("CodeRef allows only the double-quoted path attribute and optional symbol attribute.");
75
75
  continue;
76
76
  }
77
77
  const names = attrMatches.map((attr) => attr[1]);
78
78
  const duplicates = names.filter((name, index) => names.indexOf(name) !== index);
79
79
  if (duplicates.length > 0) {
80
- issues.push(`CodeRef 存在重复属性: ${[...new Set(duplicates)].join(", ")}`);
80
+ issues.push(`CodeRef contains duplicate attributes: ${[...new Set(duplicates)].join(", ")}`);
81
81
  }
82
82
  if (!names.includes("path")) {
83
- issues.push("CodeRef 缺少必填属性 path。");
83
+ issues.push("CodeRef is missing the required path attribute.");
84
84
  }
85
85
  for (const name of names) {
86
86
  if (name !== "path" && name !== "symbol") {
87
- issues.push(`CodeRef 存在未知属性: ${name}`);
87
+ issues.push(`CodeRef contains an unknown attribute: ${name}`);
88
88
  }
89
89
  }
90
90
  }
@@ -13,7 +13,7 @@ export function assertOutputSchema(name, payload) {
13
13
  if (ok) {
14
14
  return;
15
15
  }
16
- throw new CliError(`内部输出契约错误(${name}): ${formatErrors(validator.errors ?? [])}`, 70);
16
+ throw new CliError(`Internal output contract error (${name}): ${formatErrors(validator.errors ?? [])}`, 70);
17
17
  }
18
18
  export function stringifyValidatedOutput(name, payload) {
19
19
  assertOutputSchema(name, payload);
@@ -25,7 +25,7 @@ export function parseAndValidateJsonString(name, input) {
25
25
  payload = JSON.parse(input);
26
26
  }
27
27
  catch (error) {
28
- throw new CliError(`内部输出契约错误(${name}): JSON 解析失败: ${error.message}`, 70);
28
+ throw new CliError(`Internal output contract error (${name}): JSON parse failed: ${error.message}`, 70);
29
29
  }
30
30
  return stringifyValidatedOutput(name, payload);
31
31
  }
@@ -36,7 +36,7 @@ function getValidator(name) {
36
36
  }
37
37
  const defs = schemaDocument.$defs;
38
38
  if (!defs?.[name]) {
39
- throw new CliError(`内部输出契约错误: 未找到 schema ${name}`, 70);
39
+ throw new CliError(`Internal output contract error: schema ${name} was not found`, 70);
40
40
  }
41
41
  const validator = ajv.compile({
42
42
  $schema: "https://json-schema.org/draft/2020-12/schema",
@@ -9,7 +9,7 @@ export function packageRootFromImport(metaUrl) {
9
9
  }
10
10
  const parent = path.dirname(current);
11
11
  if (parent === current) {
12
- throw new Error(`无法从 ${metaUrl} 向上定位 package root。`);
12
+ throw new Error(`Unable to locate the package root above ${metaUrl}.`);
13
13
  }
14
14
  current = parent;
15
15
  }
@@ -6,7 +6,7 @@ export function paginate({ items, estimate, options }) {
6
6
  const budget = options.budget ?? DEFAULT_BUDGET;
7
7
  const offset = decodeCursor(options.cursor);
8
8
  if (offset < 0 || offset > items.length) {
9
- throw new CliError("cursor 非法或已失效。");
9
+ throw new CliError("The cursor is invalid or expired.");
10
10
  }
11
11
  const selected = [];
12
12
  let usedBudget = 0;
@@ -60,6 +60,6 @@ function decodeCursor(cursor) {
60
60
  return payload.offset;
61
61
  }
62
62
  catch {
63
- throw new CliError("cursor 非法或已损坏。");
63
+ throw new CliError("The cursor is invalid or corrupted.");
64
64
  }
65
65
  }
@@ -11,6 +11,7 @@ function readSchema(fileName) {
11
11
  }
12
12
  const docValidator = ajv.compile(readSchema("doc-frontmatter.schema.json"));
13
13
  const metaValidator = ajv.compile(readSchema("meta.schema.json"));
14
+ const configValidator = ajv.compile(readSchema("config.schema.json"));
14
15
  export function validateDocFrontmatter(input) {
15
16
  const ok = docValidator(input);
16
17
  if (ok) {
@@ -33,6 +34,13 @@ export function validateMeta(input) {
33
34
  }
34
35
  return errors;
35
36
  }
37
+ export function validateLlmdocConfig(input) {
38
+ const ok = configValidator(input);
39
+ if (ok) {
40
+ return [];
41
+ }
42
+ return (configValidator.errors ?? []).map(formatAjvError);
43
+ }
36
44
  function formatAjvError(error) {
37
45
  return `${error.instancePath || "/"} ${error.message ?? "invalid"}`;
38
46
  }
@@ -2,8 +2,35 @@ import fs from "node:fs";
2
2
  import { Minimatch } from "minimatch";
3
3
  import { CACHE_DIR, SEARCH_CACHE_FILE } from "./constants.js";
4
4
  import { ensureDirectory, resolveInsideRoot } from "./fs.js";
5
+ const WORD_SEGMENTER = new Intl.Segmenter("zh-CN", { granularity: "word" });
6
+ const CJK_CHARACTER = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]$/u;
7
+ const CJK_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]{2,}/gu;
8
+ const QUERY_STOP_WORDS = new Set([
9
+ "的",
10
+ "了",
11
+ "呢",
12
+ "吗",
13
+ "啊",
14
+ "吧",
15
+ "是",
16
+ "在",
17
+ "与",
18
+ "和",
19
+ "或",
20
+ "及",
21
+ "把",
22
+ "被",
23
+ "从",
24
+ "到",
25
+ "为",
26
+ "怎么",
27
+ "如何",
28
+ "什么",
29
+ "为何"
30
+ ]);
5
31
  export function searchDocuments(workspace, query, filters) {
6
- const tokens = tokenize(query);
32
+ const normalizedQuery = query.trim().toLowerCase();
33
+ const lexicalTokens = tokenizeQuery(query).map((value) => ({ value, weight: 1 }));
7
34
  const cache = loadSearchCache(workspace);
8
35
  const filteredDocs = workspace.documents.filter((document) => {
9
36
  if (filters?.topic && document.topic !== filters.topic) {
@@ -14,38 +41,75 @@ export function searchDocuments(workspace, query, filters) {
14
41
  }
15
42
  return true;
16
43
  });
44
+ const lexicalResults = scoreDocuments(filteredDocs, cache, lexicalTokens, {
45
+ minimumMatchedTokens: 1,
46
+ normalizedQuery
47
+ });
48
+ if (lexicalResults.length > 0) {
49
+ return {
50
+ results: lexicalResults,
51
+ mode: "lexical"
52
+ };
53
+ }
54
+ const bigrams = cjkBigrams(query);
55
+ if (bigrams.length === 0) {
56
+ return {
57
+ results: [],
58
+ mode: "lexical"
59
+ };
60
+ }
61
+ const minimumMatchedTokens = bigrams.length >= 4 ? Math.max(2, Math.ceil(bigrams.length * 0.25)) : 1;
62
+ return {
63
+ results: scoreDocuments(filteredDocs, cache, bigrams.map((value) => ({ value, weight: 0.55 })), { minimumMatchedTokens, normalizedQuery }),
64
+ mode: "cjk-bigram-fallback"
65
+ };
66
+ }
67
+ function scoreDocuments(documents, cache, tokens, options) {
68
+ if (tokens.length === 0) {
69
+ return [];
70
+ }
17
71
  const documentFrequency = new Map();
18
72
  for (const token of tokens) {
19
73
  let count = 0;
20
- for (const document of filteredDocs) {
74
+ for (const document of documents) {
21
75
  const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
22
- if (searchableText.includes(token)) {
76
+ if (searchableText.includes(token.value)) {
23
77
  count += 1;
24
78
  }
25
79
  }
26
- documentFrequency.set(token, count);
80
+ documentFrequency.set(token.value, count);
27
81
  }
28
- return filteredDocs
82
+ return documents
29
83
  .map((document) => {
30
84
  const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
31
- const wordCount = tokenize(searchableText).length || 1;
85
+ const wordCount = cache.entries[document.llmdocPath]?.wordCount ?? countWords(searchableText);
32
86
  let score = 0;
87
+ let matchedTokenCount = 0;
33
88
  for (const token of tokens) {
34
- const frequency = countSubstring(searchableText, token);
89
+ const frequency = countSubstring(searchableText, token.value);
35
90
  if (frequency === 0) {
36
91
  continue;
37
92
  }
38
- const df = documentFrequency.get(token) ?? 0;
39
- const idf = Math.log(1 + (filteredDocs.length - df + 0.5) / (df + 0.5));
40
- score += idf * ((frequency * 2.2) / (frequency + 1.2 * (1 - 0.75 + 0.75 * (wordCount / 200))));
93
+ matchedTokenCount += 1;
94
+ const df = documentFrequency.get(token.value) ?? 0;
95
+ const idf = Math.log(1 + (documents.length - df + 0.5) / (df + 0.5));
96
+ score +=
97
+ token.weight *
98
+ idf *
99
+ ((frequency * 2.2) / (frequency + 1.2 * (1 - 0.75 + 0.75 * (wordCount / 200))));
100
+ }
101
+ if (options.normalizedQuery.length > 1) {
102
+ const phraseFrequency = countSubstring(searchableText, options.normalizedQuery);
103
+ score += phraseFrequency * (tokens.length + 1) * 2;
41
104
  }
42
105
  return {
43
106
  document,
44
107
  score,
45
- snippet: buildSnippet(document.body, tokens)
108
+ matchedTokenCount,
109
+ snippet: buildSnippet(document.body, tokens.map((token) => token.value))
46
110
  };
47
111
  })
48
- .filter((entry) => entry.score > 0)
112
+ .filter((entry) => entry.score > 0 && entry.matchedTokenCount >= options.minimumMatchedTokens)
49
113
  .sort((left, right) => right.score - left.score || left.document.llmdocPath.localeCompare(right.document.llmdocPath));
50
114
  }
51
115
  export function matchesCodePathPattern(pattern, repoRelativePath) {
@@ -67,7 +131,7 @@ function normalizeCodePathPattern(pattern) {
67
131
  }
68
132
  function loadSearchCache(workspace) {
69
133
  const next = {
70
- version: 1,
134
+ version: 2,
71
135
  entries: {}
72
136
  };
73
137
  const cachePath = resolveCachePath(workspace);
@@ -75,14 +139,16 @@ function loadSearchCache(workspace) {
75
139
  for (const document of workspace.documents) {
76
140
  const stats = fs.statSync(document.absolutePath);
77
141
  const cachedEntry = existing?.entries[document.llmdocPath];
78
- if (cachedEntry && cachedEntry.mtimeMs === stats.mtimeMs) {
142
+ if (existing?.version === 2 && cachedEntry && cachedEntry.mtimeMs === stats.mtimeMs) {
79
143
  next.entries[document.llmdocPath] = cachedEntry;
80
144
  continue;
81
145
  }
146
+ const searchableText = buildSearchableText(document);
82
147
  next.entries[document.llmdocPath] = {
83
148
  llmdocPath: document.llmdocPath,
84
149
  mtimeMs: stats.mtimeMs,
85
- searchableText: buildSearchableText(document)
150
+ searchableText,
151
+ wordCount: countWords(searchableText)
86
152
  };
87
153
  }
88
154
  if (cachePath) {
@@ -124,12 +190,56 @@ function buildSearchableText(document) {
124
190
  .join("\n")
125
191
  .toLowerCase();
126
192
  }
127
- function tokenize(input) {
128
- return input
129
- .toLowerCase()
130
- .split(/[^a-z0-9\u4e00-\u9fff_-]+/)
131
- .map((token) => token.trim())
132
- .filter(Boolean);
193
+ function tokenizeQuery(input) {
194
+ const tokens = [];
195
+ let singleCjkBuffer = [];
196
+ const flushSingleCjkBuffer = () => {
197
+ if (singleCjkBuffer.length > 0) {
198
+ tokens.push(singleCjkBuffer.join(""));
199
+ singleCjkBuffer = [];
200
+ }
201
+ };
202
+ for (const part of WORD_SEGMENTER.segment(input.toLowerCase())) {
203
+ const value = part.segment.trim();
204
+ if (!part.isWordLike || !value) {
205
+ flushSingleCjkBuffer();
206
+ continue;
207
+ }
208
+ if (QUERY_STOP_WORDS.has(value)) {
209
+ flushSingleCjkBuffer();
210
+ continue;
211
+ }
212
+ if (CJK_CHARACTER.test(value)) {
213
+ singleCjkBuffer.push(value);
214
+ continue;
215
+ }
216
+ flushSingleCjkBuffer();
217
+ tokens.push(value);
218
+ }
219
+ flushSingleCjkBuffer();
220
+ return unique(tokens);
221
+ }
222
+ function cjkBigrams(input) {
223
+ const bigrams = [];
224
+ for (const match of input.toLowerCase().matchAll(CJK_RUN)) {
225
+ const characters = [...match[0]];
226
+ for (let index = 0; index < characters.length - 1; index += 1) {
227
+ bigrams.push(`${characters[index]}${characters[index + 1]}`);
228
+ }
229
+ }
230
+ return unique(bigrams);
231
+ }
232
+ function countWords(input) {
233
+ let count = 0;
234
+ for (const part of WORD_SEGMENTER.segment(input)) {
235
+ if (part.isWordLike && part.segment.trim()) {
236
+ count += 1;
237
+ }
238
+ }
239
+ return count || 1;
240
+ }
241
+ function unique(values) {
242
+ return [...new Set(values)];
133
243
  }
134
244
  function buildSnippet(body, tokens) {
135
245
  const lines = body.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);