@tokenroll/llmdoc 3.5.1 → 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/assets/viewer-app.js +243 -0
- package/assets/viewer-detail.js +223 -0
- package/assets/viewer-graph.js +471 -0
- package/assets/viewer-model.js +127 -0
- package/assets/viewer.css +343 -0
- package/assets/viewer.html +51 -547
- package/dist/cli.js +4 -3
- package/dist/commands/context.js +14 -1
- package/dist/commands/init-state.js +11 -4
- package/dist/commands/new.js +10 -4
- package/dist/commands/search.js +6 -2
- package/dist/commands/serve.js +0 -0
- package/dist/commands/status.js +3 -19
- package/dist/lib/fs.js +14 -0
- package/dist/lib/git.js +8 -2
- package/dist/lib/repository-health.js +26 -0
- package/dist/lib/search.js +131 -21
- package/dist/lib/viewer-http.js +107 -0
- package/dist/lib/viewer-state.js +131 -0
- package/dist/lib/workspace.js +40 -1
- package/package.json +1 -1
- package/schemas/output.schema.json +24 -1
package/dist/commands/context.js
CHANGED
|
@@ -20,7 +20,15 @@ export function runContext(options) {
|
|
|
20
20
|
absolutePath
|
|
21
21
|
};
|
|
22
22
|
});
|
|
23
|
-
const
|
|
23
|
+
const documentsByFile = normalizedFiles.map((file) => ({
|
|
24
|
+
file,
|
|
25
|
+
documents: workspace.documents.filter((document) => (document.frontmatter.code?.paths ?? []).some((pattern) => matchesCodePathPattern(pattern, file.normalized)))
|
|
26
|
+
}));
|
|
27
|
+
const impactedPaths = new Set(documentsByFile.flatMap(({ documents }) => documents.map((document) => document.llmdocPath)));
|
|
28
|
+
const impacted = workspace.documents.filter((document) => impactedPaths.has(document.llmdocPath));
|
|
29
|
+
const unmappedFiles = documentsByFile
|
|
30
|
+
.filter(({ documents }) => documents.length === 0)
|
|
31
|
+
.map(({ file }) => file.normalized);
|
|
24
32
|
const prerequisites = collectRequires(workspace, impacted);
|
|
25
33
|
const rows = [
|
|
26
34
|
...impacted.map((document) => ({ role: "impacted", document })),
|
|
@@ -35,6 +43,7 @@ export function runContext(options) {
|
|
|
35
43
|
return {
|
|
36
44
|
impacted: result.items.filter((row) => row.role === "impacted").map((row) => toPayload(row.document)),
|
|
37
45
|
prerequisites: result.items.filter((row) => row.role === "requires").map((row) => toPayload(row.document)),
|
|
46
|
+
unmappedFiles,
|
|
38
47
|
pagination: paginationMetadata(result)
|
|
39
48
|
};
|
|
40
49
|
}
|
|
@@ -45,6 +54,10 @@ export function runContext(options) {
|
|
|
45
54
|
lines.push(`${prefix} llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`);
|
|
46
55
|
lines.push(` ${document.frontmatter.description}`);
|
|
47
56
|
}
|
|
57
|
+
lines.push("", `unmapped files: ${unmappedFiles.length}`);
|
|
58
|
+
for (const file of unmappedFiles) {
|
|
59
|
+
lines.push(` unmapped -> ${file}`);
|
|
60
|
+
}
|
|
48
61
|
lines.push("", ...formatPaginationSummary(result));
|
|
49
62
|
return lines.join("\n");
|
|
50
63
|
}
|
|
@@ -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
|
|
17
|
-
throw new CliError(
|
|
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
|
|
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:
|
|
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
|
}
|
package/dist/commands/new.js
CHANGED
|
@@ -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,
|
|
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 =
|
|
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
|
|
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}`);
|
package/dist/commands/search.js
CHANGED
|
@@ -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
|
|
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/commands/serve.js
CHANGED
|
Binary file
|
package/dist/commands/status.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { computeGrowthState, analyzeDelta
|
|
1
|
+
import { readRepositoryRevisionHealth } from "../lib/repository-health.js";
|
|
2
|
+
import { computeGrowthState, analyzeDelta } from "../lib/state.js";
|
|
3
3
|
import { loadWorkspace } from "../lib/workspace.js";
|
|
4
4
|
export function runStatus(options) {
|
|
5
5
|
const workspace = loadWorkspace(options.cwd);
|
|
6
6
|
const delta = analyzeDelta(workspace);
|
|
7
7
|
const growth = computeGrowthState(workspace);
|
|
8
|
-
const relevantCommitsBehindHead =
|
|
8
|
+
const relevantCommitsBehindHead = readRepositoryRevisionHealth(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta.git).relevantCommitsBehindHead;
|
|
9
9
|
if (options.json) {
|
|
10
10
|
return {
|
|
11
11
|
baseline: workspace.meta?.baseline.revision ?? null,
|
|
@@ -47,22 +47,6 @@ export function runStatus(options) {
|
|
|
47
47
|
}
|
|
48
48
|
return lines.join("\n");
|
|
49
49
|
}
|
|
50
|
-
// "有效源码落后"计数:baseline..HEAD 中至少触碰一个 implementation surface 路径的提交数。
|
|
51
|
-
// 只改 llmdoc/** 的提交(尤其 commit 收尾的 meta follow-up)不代表知识过期,不应计入。
|
|
52
|
-
function countRelevantCommitsBehindHead(rootDir, baselineRevision, delta) {
|
|
53
|
-
if (!baselineRevision || !delta.git.headRevision || delta.git.baselineBehindHead === null) {
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
if (delta.git.baselineBehindHead === 0) {
|
|
57
|
-
return 0;
|
|
58
|
-
}
|
|
59
|
-
const commits = readCommitsWithChangedPathsSince(rootDir, baselineRevision, delta.git.headRevision);
|
|
60
|
-
if (commits === null) {
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
const ignorePatterns = loadIgnorePatterns(rootDir);
|
|
64
|
-
return commits.filter((commit) => commit.paths.some((filePath) => isImplementationSurfacePath(filePath, ignorePatterns))).length;
|
|
65
|
-
}
|
|
66
50
|
function formatBehindLabel(commitsBehindHead, relevantCommitsBehindHead) {
|
|
67
51
|
if (commitsBehindHead === null) {
|
|
68
52
|
return "unknown";
|
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}`;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readCommitsWithChangedPathsSince } from "./git.js";
|
|
2
|
+
import { isImplementationSurfacePath, loadIgnorePatterns } from "./state.js";
|
|
3
|
+
/**
|
|
4
|
+
* 将原始 Git 落后与真正触碰 implementation surface 的落后分开。
|
|
5
|
+
* 只改 llmdoc/** 的收尾 commit 仍属于 Git 历史,但不代表知识过期。
|
|
6
|
+
*/
|
|
7
|
+
export function readRepositoryRevisionHealth(rootDir, baselineRevision, git) {
|
|
8
|
+
const commitsBehindHead = git.baselineBehindHead;
|
|
9
|
+
if (!baselineRevision || !git.headRevision || commitsBehindHead === null) {
|
|
10
|
+
return { commitsBehindHead, relevantCommitsBehindHead: null, metadataOnlyBehind: false };
|
|
11
|
+
}
|
|
12
|
+
if (commitsBehindHead === 0) {
|
|
13
|
+
return { commitsBehindHead, relevantCommitsBehindHead: 0, metadataOnlyBehind: false };
|
|
14
|
+
}
|
|
15
|
+
const commits = readCommitsWithChangedPathsSince(rootDir, baselineRevision, git.headRevision);
|
|
16
|
+
if (commits === null) {
|
|
17
|
+
return { commitsBehindHead, relevantCommitsBehindHead: null, metadataOnlyBehind: false };
|
|
18
|
+
}
|
|
19
|
+
const ignorePatterns = loadIgnorePatterns(rootDir);
|
|
20
|
+
const relevantCommitsBehindHead = commits.filter((commit) => commit.paths.some((filePath) => isImplementationSurfacePath(filePath, ignorePatterns))).length;
|
|
21
|
+
return {
|
|
22
|
+
commitsBehindHead,
|
|
23
|
+
relevantCommitsBehindHead,
|
|
24
|
+
metadataOnlyBehind: commitsBehindHead > 0 && relevantCommitsBehindHead === 0
|
|
25
|
+
};
|
|
26
|
+
}
|
package/dist/lib/search.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
82
|
+
return documents
|
|
29
83
|
.map((document) => {
|
|
30
84
|
const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
|
|
31
|
-
const wordCount =
|
|
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
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
|
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
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
.
|
|
132
|
-
|
|
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);
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { CliError } from "./errors.js";
|
|
5
|
+
import { packageRootFromImport } from "./package-root.js";
|
|
6
|
+
import { loadViewerState } from "./viewer-state.js";
|
|
7
|
+
import { loadWorkspace } from "./workspace.js";
|
|
8
|
+
const STATIC_ASSETS = new Map([
|
|
9
|
+
["/", { fileName: "viewer.html", contentType: "text/html; charset=utf-8" }],
|
|
10
|
+
["/assets/viewer.css", { fileName: "viewer.css", contentType: "text/css; charset=utf-8" }],
|
|
11
|
+
["/assets/viewer-model.js", { fileName: "viewer-model.js", contentType: "text/javascript; charset=utf-8" }],
|
|
12
|
+
["/assets/viewer-graph.js", { fileName: "viewer-graph.js", contentType: "text/javascript; charset=utf-8" }],
|
|
13
|
+
["/assets/viewer-detail.js", { fileName: "viewer-detail.js", contentType: "text/javascript; charset=utf-8" }],
|
|
14
|
+
["/assets/viewer-app.js", { fileName: "viewer-app.js", contentType: "text/javascript; charset=utf-8" }]
|
|
15
|
+
]);
|
|
16
|
+
/** 创建只读、显式路由的本地 Viewer handler。不会把 URL 路径拼接进文件系统。 */
|
|
17
|
+
export function createViewerRequestHandler(rootDir) {
|
|
18
|
+
const packageRoot = packageRootFromImport(import.meta.url);
|
|
19
|
+
const assetsRoot = path.join(packageRoot, "assets");
|
|
20
|
+
return (request, response) => {
|
|
21
|
+
const headOnly = request.method === "HEAD";
|
|
22
|
+
try {
|
|
23
|
+
if (request.method !== "GET" && !headOnly) {
|
|
24
|
+
sendJson(response, 405, { error: "method not allowed" }, headOnly, { allow: "GET, HEAD" });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
28
|
+
const staticAsset = STATIC_ASSETS.get(url.pathname);
|
|
29
|
+
if (staticAsset) {
|
|
30
|
+
sendStaticAsset(response, assetsRoot, staticAsset, headOnly);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (url.pathname === "/assets/marked.js") {
|
|
34
|
+
sendMarked(response, headOnly);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (url.pathname === "/favicon.ico") {
|
|
38
|
+
sendBody(response, 204, Buffer.alloc(0), "image/x-icon", headOnly);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (url.pathname === "/api/state") {
|
|
42
|
+
sendJson(response, 200, loadViewerState(rootDir), headOnly);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (url.pathname === "/api/doc") {
|
|
46
|
+
const docPath = url.searchParams.get("path") ?? "";
|
|
47
|
+
const workspace = loadWorkspace(rootDir);
|
|
48
|
+
// 仅按扫描产生的 canonical llmdocPath 查表,不接受任意文件系统路径。
|
|
49
|
+
const document = workspace.documentsByLlmdocPath.get(docPath);
|
|
50
|
+
if (!document) {
|
|
51
|
+
sendJson(response, 404, { error: `未找到文档: ${docPath}` }, headOnly);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
sendJson(response, 200, {
|
|
55
|
+
path: document.llmdocPath,
|
|
56
|
+
frontmatter: document.frontmatter,
|
|
57
|
+
body: document.body,
|
|
58
|
+
title: document.title,
|
|
59
|
+
estimatedTokens: document.estimatedTokens,
|
|
60
|
+
lineCount: document.lineCount
|
|
61
|
+
}, headOnly);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
sendJson(response, 404, { error: "not found" }, headOnly);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
68
|
+
sendJson(response, 500, { error: message }, headOnly);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function sendStaticAsset(response, assetsRoot, asset, headOnly) {
|
|
73
|
+
// fileName 只可能来自上方常量白名单;请求值不会参与路径解析。
|
|
74
|
+
const assetPath = path.join(assetsRoot, asset.fileName);
|
|
75
|
+
if (!fs.existsSync(assetPath)) {
|
|
76
|
+
throw new CliError(`viewer 资产缺失: ${asset.fileName}`);
|
|
77
|
+
}
|
|
78
|
+
sendBody(response, 200, fs.readFileSync(assetPath), asset.contentType, headOnly);
|
|
79
|
+
}
|
|
80
|
+
function sendMarked(response, headOnly) {
|
|
81
|
+
try {
|
|
82
|
+
const require = createRequire(import.meta.url);
|
|
83
|
+
const markedPath = require.resolve("marked/marked.min.js");
|
|
84
|
+
sendBody(response, 200, fs.readFileSync(markedPath), "text/javascript; charset=utf-8", headOnly);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// marked 缺失时降级为安全的纯文本展示,Viewer 的导航与状态功能仍可用。
|
|
88
|
+
const fallback = "window.marked={parse:(text)=>'<pre>'+text.replace(/&/g,'&').replace(/</g,'<')+'</pre>'};";
|
|
89
|
+
sendBody(response, 200, Buffer.from(fallback), "text/javascript; charset=utf-8", headOnly);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function sendJson(response, statusCode, payload, headOnly, extraHeaders = {}) {
|
|
93
|
+
sendBody(response, statusCode, Buffer.from(JSON.stringify(payload)), "application/json; charset=utf-8", headOnly, extraHeaders);
|
|
94
|
+
}
|
|
95
|
+
function sendBody(response, statusCode, body, contentType, headOnly, extraHeaders = {}) {
|
|
96
|
+
response.writeHead(statusCode, {
|
|
97
|
+
"content-type": contentType,
|
|
98
|
+
"content-length": String(body.byteLength),
|
|
99
|
+
"cache-control": "no-store",
|
|
100
|
+
"content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' http: https:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
|
|
101
|
+
"referrer-policy": "no-referrer",
|
|
102
|
+
"x-content-type-options": "nosniff",
|
|
103
|
+
"x-frame-options": "DENY",
|
|
104
|
+
...extraHeaders
|
|
105
|
+
});
|
|
106
|
+
response.end(headOnly ? undefined : body);
|
|
107
|
+
}
|