@tokenroll/llmdoc 3.5.2 → 3.5.3

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.
package/dist/cli.js CHANGED
@@ -99,7 +99,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
99
99
  });
100
100
  program
101
101
  .command("search")
102
- .description("按词法检索 llmdoc 文档(front matter、标题与正文,返回 snippet)")
102
+ .description("按词法检索 llmdoc 文档(自动中文分词,必要时使用 CJK bigram 降级)")
103
103
  .argument("<query>", "检索词")
104
104
  .option("--topic <topic>", "限定 topic")
105
105
  .option("--kind <kind>", "限定类型: architecture | guide | reference")
@@ -160,6 +160,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
160
160
  program
161
161
  .command("init-state")
162
162
  .description("首次生成 llmdoc/meta.json 台账骨架(validatedRevision 全部为 null)")
163
+ .addHelpText("after", "\n前置: Git HEAD 必须已有真实 commit。生成后先 validate,再用 commit --all 完成 bootstrap。")
163
164
  .action(async () => {
164
165
  const { runInitState } = await import("./commands/init-state.js");
165
166
  const rootDir = findProjectRoot(cwd);
@@ -190,11 +191,11 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
190
191
  .argument("<path>", "目标相对路径,如 api-client/retry-policy.mdx")
191
192
  .requiredOption("--kind <kind>", "文档类型: architecture | guide | reference")
192
193
  .option("--description <description>", "front matter 一句话描述")
194
+ .addHelpText("after", "\n首次创建时会自动建立 llmdoc/;完成初始文档后运行 init-state → validate → commit --all。")
193
195
  .action((targetPath, commandOptions) => {
194
- const rootDir = findProjectRoot(cwd);
195
196
  output.push(writeOutput("new", runNew({
196
197
  ...globalOptions,
197
- cwd: rootDir,
198
+ cwd,
198
199
  path: targetPath,
199
200
  kind: commandOptions.kind,
200
201
  description: commandOptions.description
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import { CliError } from "../lib/errors.js";
3
3
  import { findProjectRoot } from "../lib/fs.js";
4
+ import { isUnbornHead } from "../lib/git.js";
4
5
  import { readWorkspaceGitState } from "../lib/state.js";
5
6
  import { loadWorkspace } from "../lib/workspace.js";
6
7
  // init/upgrade 场景的 meta.json 骨架生成:
@@ -13,8 +14,14 @@ export function runInitState(options) {
13
14
  throw new CliError("llmdoc/meta.json 已存在;init-state 只用于首次建立台账,不覆盖现有状态。");
14
15
  }
15
16
  const git = readWorkspaceGitState(workspace);
16
- if (!git.available || !git.headRevision) {
17
- throw new CliError(git.degradedReason ?? "无法解析 HEAD commit,init-state 需要 git 仓库。");
17
+ if (!git.available) {
18
+ throw new CliError("init-state 需要 Git 仓库;请先运行 `git init` 并创建一次真实的初始提交。");
19
+ }
20
+ if (!git.headRevision) {
21
+ if (isUnbornHead(rootDir)) {
22
+ throw new CliError("HEAD 尚无 commit(当前分支尚未创建首次提交)。请先创建一次真实的初始提交;空仓库可运行 `git commit --allow-empty -m \"chore: initial commit\"`。");
23
+ }
24
+ throw new CliError(`${git.degradedReason ?? "无法解析 HEAD commit。"}请先修复 Git HEAD,再运行 init-state。`);
18
25
  }
19
26
  const now = new Date().toISOString().replace(/\.\d+Z$/, "Z");
20
27
  const meta = {
@@ -37,8 +44,8 @@ export function runInitState(options) {
37
44
  status: "success",
38
45
  documents: workspace.documents.length,
39
46
  baselineRevision: git.headRevision,
40
- next: "npx @tokenroll/llmdoc fingerprint --all"
47
+ next: "npx -y @tokenroll/llmdoc validate && npx -y @tokenroll/llmdoc commit --all -m \"docs: bootstrap llmdoc\""
41
48
  };
42
49
  }
43
- return `initialized llmdoc/meta.json: ${workspace.documents.length} documents (validatedRevision: null), baseline ${git.headRevision.slice(0, 7)}\nnext: 验证文档内容后运行 \`npx @tokenroll/llmdoc fingerprint --all\` 烙印 revision`;
50
+ return `initialized llmdoc/meta.json: ${workspace.documents.length} documents (validatedRevision: null), baseline ${git.headRevision.slice(0, 7)}\nnext: 先运行 \`npx -y @tokenroll/llmdoc validate\`;全部通过后运行 \`npx -y @tokenroll/llmdoc commit --all -m "docs: bootstrap llmdoc"\` 收尾`;
44
51
  }
@@ -2,11 +2,11 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseDocTargetShape, assertDocKindMatchesShape, assertDocumentKind } from "../lib/doc-shape.js";
4
4
  import { CliError } from "../lib/errors.js";
5
- import { ensureDirectory, findProjectRoot, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
5
+ import { ensureDirectory, findProjectRootForNew, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
6
6
  import { packageRootFromImport } from "../lib/package-root.js";
7
7
  import { loadWorkspace } from "../lib/workspace.js";
8
8
  export function runNew(options) {
9
- const rootDir = findProjectRoot(options.cwd);
9
+ const rootDir = findProjectRootForNew(options.cwd);
10
10
  const repoRelativePath = normalizeDocDestination(options.path);
11
11
  const kind = assertDocumentKind(options.kind);
12
12
  const shape = parseDocTargetShape(repoRelativePath);
@@ -24,14 +24,20 @@ export function runNew(options) {
24
24
  .replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: 补充文档描述。"))
25
25
  .replace("__KIND__", () => kind)
26
26
  .replace("__TITLE__", () => title);
27
+ const metaExists = fs.existsSync(path.join(rootDir, "llmdoc", "meta.json"));
27
28
  fs.writeFileSync(absolutePath, content);
28
29
  syncMetaEntry(rootDir, shape.llmdocPath);
29
30
  if (options.json) {
30
31
  return {
31
- created: repoRelativePath
32
+ created: repoRelativePath,
33
+ next: metaExists
34
+ ? null
35
+ : "若 HEAD 尚无 commit,请先创建首次 Git 提交;然后运行 `npx -y @tokenroll/llmdoc init-state`。"
32
36
  };
33
37
  }
34
- return `created: ${repoRelativePath}`;
38
+ return metaExists
39
+ ? `created: ${repoRelativePath}`
40
+ : `created: ${repoRelativePath}\nnext: 若仓库尚无提交,请先创建首次 Git 提交;然后运行 \`npx -y @tokenroll/llmdoc init-state\` 建立台账。`;
35
41
  }
36
42
  function normalizeDocDestination(input) {
37
43
  const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
@@ -7,23 +7,27 @@ import { estimateTokens } from "../lib/markdown.js";
7
7
  export function runSearch(options) {
8
8
  const workspace = loadWorkspace(options.cwd);
9
9
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
10
- const results = searchDocuments(workspace, options.query, {
10
+ const search = searchDocuments(workspace, options.query, {
11
11
  topic: options.topic,
12
12
  kind
13
13
  });
14
14
  const paginated = paginate({
15
- items: results,
15
+ items: search.results,
16
16
  estimate: (entry) => estimateTokens(JSON.stringify(toPayload(entry))),
17
17
  options
18
18
  });
19
19
  if (options.json) {
20
20
  return {
21
21
  query: options.query,
22
+ searchMode: search.mode,
22
23
  results: paginated.items.map(toPayload),
23
24
  pagination: paginationMetadata(paginated)
24
25
  };
25
26
  }
26
27
  const lines = [];
28
+ if (search.mode === "cjk-bigram-fallback") {
29
+ lines.push("note: 中文分词未命中,已使用 CJK bigram 降级检索。", "");
30
+ }
27
31
  for (const entry of paginated.items) {
28
32
  lines.push(`llmdoc/${entry.document.llmdocPath} [${entry.document.frontmatter.kind}]`);
29
33
  lines.push(` ${entry.document.frontmatter.description}`);
package/dist/lib/fs.js CHANGED
@@ -8,6 +8,20 @@ export function findProjectRoot(startDir) {
8
8
  }
9
9
  throw new CliError("未找到 llmdoc/ 目录,请在仓库内运行该命令。", 2);
10
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("未找到 Git 仓库;请先运行 `git init`,再运行 `llmdoc new`。", 2);
24
+ }
11
25
  export function findProjectRootOrNull(startDir) {
12
26
  const start = path.resolve(startDir);
13
27
  const gitRoot = findNearestGitRootOrNull(start);
package/dist/lib/git.js CHANGED
@@ -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";
@@ -45,7 +51,7 @@ export function readGitState(rootDir, baselineRevision) {
45
51
  degradedReason: "当前目录不是 git 仓库,状态面降级为不可用。"
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,7 +65,7 @@ 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 尚无 commit(当前分支尚未创建首次提交)。" : "无法解析 HEAD commit。";
63
69
  }
64
70
  else if (baselineRevision && !gitCommitExists(rootDir, baselineRevision)) {
65
71
  degradedReason = `baseline.revision 不存在于当前 git 历史: ${baselineRevision}`;
@@ -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);
@@ -151,7 +151,7 @@ export function validateWorkspace(workspace) {
151
151
  severity: "error",
152
152
  code: "meta.missing",
153
153
  path: "llmdoc/meta.json",
154
- message: "缺少 llmdoc/meta.json。"
154
+ message: "缺少 llmdoc/meta.json。请运行 `npx -y @tokenroll/llmdoc init-state` 建立台账(若仓库尚无提交,请先创建首次 Git 提交)。"
155
155
  });
156
156
  }
157
157
  for (const document of workspace.documents) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenroll/llmdoc",
3
- "version": "3.5.2",
3
+ "version": "3.5.3",
4
4
  "description": "V3 runtime CLI for llmdoc repositories",
5
5
  "homepage": "https://github.com/TokenRollAI/llmdoc",
6
6
  "repository": {
@@ -374,6 +374,7 @@
374
374
  "additionalProperties": false,
375
375
  "required": [
376
376
  "query",
377
+ "searchMode",
377
378
  "results",
378
379
  "pagination"
379
380
  ],
@@ -382,6 +383,13 @@
382
383
  "type": "string",
383
384
  "minLength": 1
384
385
  },
386
+ "searchMode": {
387
+ "type": "string",
388
+ "enum": [
389
+ "lexical",
390
+ "cjk-bigram-fallback"
391
+ ]
392
+ },
385
393
  "results": {
386
394
  "type": "array",
387
395
  "items": {
@@ -859,12 +867,19 @@
859
867
  "type": "object",
860
868
  "additionalProperties": false,
861
869
  "required": [
862
- "created"
870
+ "created",
871
+ "next"
863
872
  ],
864
873
  "properties": {
865
874
  "created": {
866
875
  "type": "string",
867
876
  "minLength": 1
877
+ },
878
+ "next": {
879
+ "type": [
880
+ "string",
881
+ "null"
882
+ ]
868
883
  }
869
884
  }
870
885
  },