@tokenroll/llmdoc 3.0.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.
- package/assets/viewer.html +554 -0
- package/dist/bin/llmdoc.js +24 -0
- package/dist/cli.js +261 -0
- package/dist/commands/context.js +78 -0
- package/dist/commands/delta.js +78 -0
- package/dist/commands/fingerprint.js +38 -0
- package/dist/commands/hook.js +84 -0
- package/dist/commands/index.js +53 -0
- package/dist/commands/mv.js +175 -0
- package/dist/commands/new.js +59 -0
- package/dist/commands/prune.js +171 -0
- package/dist/commands/search.js +44 -0
- package/dist/commands/serve.js +0 -0
- package/dist/commands/show.js +47 -0
- package/dist/commands/status.js +46 -0
- package/dist/commands/tree.js +96 -0
- package/dist/commands/upgrade.js +124 -0
- package/dist/commands/validate.js +30 -0
- package/dist/lib/constants.js +8 -0
- package/dist/lib/doc-shape.js +50 -0
- package/dist/lib/errors.js +8 -0
- package/dist/lib/format.js +24 -0
- package/dist/lib/fs.js +81 -0
- package/dist/lib/git.js +142 -0
- package/dist/lib/markdown.js +99 -0
- package/dist/lib/output-schema.js +56 -0
- package/dist/lib/package-root.js +16 -0
- package/dist/lib/pagination.js +65 -0
- package/dist/lib/rewrite.js +110 -0
- package/dist/lib/schema.js +63 -0
- package/dist/lib/search.js +157 -0
- package/dist/lib/state.js +251 -0
- package/dist/lib/workspace.js +421 -0
- package/dist/types.js +1 -0
- package/package.json +50 -0
- package/schemas/doc-frontmatter.schema.json +48 -0
- package/schemas/meta.schema.json +65 -0
- package/schemas/output.schema.json +908 -0
- package/templates/doc.mdx +7 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isDirectTopicDirectory, parseDocTargetShape, validateMoveTargetShape } from "../lib/doc-shape.js";
|
|
4
|
+
import { CliError } from "../lib/errors.js";
|
|
5
|
+
import { findProjectRoot, normalizeRepoRelativePath, repoPath, resolveInsideRoot } from "../lib/fs.js";
|
|
6
|
+
import { gitMove, gitRestorePaths } from "../lib/git.js";
|
|
7
|
+
import { updateDocumentForMove, writeFileIfChanged } from "../lib/rewrite.js";
|
|
8
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
9
|
+
export function runMove(options) {
|
|
10
|
+
const rootDir = findProjectRoot(options.cwd);
|
|
11
|
+
const fromRepoPath = normalizeRepoRelativePath(options.from.startsWith("llmdoc/") ? options.from : `llmdoc/${options.from}`);
|
|
12
|
+
const toRepoPath = normalizeRepoRelativePath(options.to.startsWith("llmdoc/") ? options.to : `llmdoc/${options.to}`);
|
|
13
|
+
const fromAbsolutePath = resolveInsideRoot(rootDir, fromRepoPath);
|
|
14
|
+
if (!fromRepoPath.startsWith("llmdoc/") || !toRepoPath.startsWith("llmdoc/")) {
|
|
15
|
+
throw new CliError("mv 仅支持 llmdoc/ 内部移动。");
|
|
16
|
+
}
|
|
17
|
+
if (fromRepoPath === "llmdoc/meta.json" || toRepoPath === "llmdoc/meta.json") {
|
|
18
|
+
throw new CliError("mv 不允许移动 meta.json。");
|
|
19
|
+
}
|
|
20
|
+
const fromStats = fs.statSync(fromAbsolutePath);
|
|
21
|
+
const beforeWorkspace = loadWorkspace(rootDir);
|
|
22
|
+
if (fromStats.isDirectory()) {
|
|
23
|
+
if (!isDirectTopicDirectory(fromRepoPath) || !isDirectTopicDirectory(toRepoPath)) {
|
|
24
|
+
throw new CliError("topic 目录重命名仅允许 llmdoc/<topic> -> llmdoc/<topic>。");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
if (!fromRepoPath.endsWith(".mdx") || !toRepoPath.endsWith(".mdx")) {
|
|
29
|
+
throw new CliError("mv 仅允许移动 .mdx 文档。");
|
|
30
|
+
}
|
|
31
|
+
const fromDocument = beforeWorkspace.documents.find((document) => document.repoPath === fromRepoPath);
|
|
32
|
+
if (!fromDocument) {
|
|
33
|
+
throw new CliError("mv 仅允许移动已索引的 llmdoc 文档。");
|
|
34
|
+
}
|
|
35
|
+
const targetShape = parseDocTargetShape(toRepoPath);
|
|
36
|
+
validateMoveTargetShape(targetShape);
|
|
37
|
+
}
|
|
38
|
+
const toAbsolutePath = resolveInsideRoot(rootDir, toRepoPath, { allowMissing: true });
|
|
39
|
+
if (fs.existsSync(toAbsolutePath)) {
|
|
40
|
+
throw new CliError(`目标已存在: ${toRepoPath}`);
|
|
41
|
+
}
|
|
42
|
+
const mapping = buildMoveMapping(beforeWorkspace.documents, beforeWorkspace.llmdocDir, fromAbsolutePath, toAbsolutePath);
|
|
43
|
+
// 目标 topic 目录不存在时自动创建(topic 即纯目录,没有入口节点前置要求)。
|
|
44
|
+
fs.mkdirSync(path.dirname(toAbsolutePath), { recursive: true });
|
|
45
|
+
gitMove(rootDir, fromRepoPath, toRepoPath);
|
|
46
|
+
const movedAfterPaths = new Map();
|
|
47
|
+
for (const item of mapping) {
|
|
48
|
+
movedAfterPaths.set(item.oldLlmdocPath, path.join(beforeWorkspace.llmdocDir, item.newLlmdocPath));
|
|
49
|
+
}
|
|
50
|
+
const documentTargets = new Set();
|
|
51
|
+
for (const document of beforeWorkspace.documents) {
|
|
52
|
+
if (documentTouchesMove(document, mapping)) {
|
|
53
|
+
documentTargets.add(document.absolutePath);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const nextAbsolute of movedAfterPaths.values()) {
|
|
57
|
+
documentTargets.add(nextAbsolute);
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
for (const document of beforeWorkspace.documents) {
|
|
61
|
+
if (!documentTouchesMove(document, mapping)) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const nextAbsolute = movedAfterPaths.get(document.llmdocPath) ?? document.absolutePath;
|
|
65
|
+
const nextContent = updateDocumentForMove(document, mapping);
|
|
66
|
+
writeFileIfChanged(nextAbsolute, nextContent);
|
|
67
|
+
}
|
|
68
|
+
const refreshedWorkspace = loadWorkspace(rootDir);
|
|
69
|
+
if (refreshedWorkspace.meta) {
|
|
70
|
+
const nextMeta = rewriteMeta(refreshedWorkspace.meta, mapping);
|
|
71
|
+
fs.writeFileSync(refreshedWorkspace.metaPath, `${JSON.stringify(nextMeta, null, 2)}\n`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const rolledBack = rollbackMove(rootDir, toAbsolutePath);
|
|
76
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
77
|
+
throw new CliError(rolledBack
|
|
78
|
+
? `mv 引用重写阶段失败,llmdoc/ 已回滚到移动前状态: ${reason}`
|
|
79
|
+
: `mv 引用重写阶段失败,且自动回滚未完成,请检查 git status -- llmdoc/ 后手动恢复: ${reason}`);
|
|
80
|
+
}
|
|
81
|
+
if (options.json) {
|
|
82
|
+
return {
|
|
83
|
+
moved: {
|
|
84
|
+
from: fromRepoPath,
|
|
85
|
+
to: toRepoPath
|
|
86
|
+
},
|
|
87
|
+
rewrittenDocuments: [...documentTargets].map((absolutePath) => repoPath(rootDir, absolutePath)).sort()
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return `moved: ${fromRepoPath} -> ${toRepoPath}`;
|
|
91
|
+
}
|
|
92
|
+
function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath) {
|
|
93
|
+
const mapping = [];
|
|
94
|
+
// llmdocDir 与待映射路径可能一边是 realpath 一边不是(如 macOS 的 /tmp symlink),
|
|
95
|
+
// 因此对两种 base 都尝试求相对路径。
|
|
96
|
+
const llmdocDirBases = [...new Set([llmdocDir, fs.realpathSync(llmdocDir)])];
|
|
97
|
+
const toLlmdocPath = (absolutePath) => {
|
|
98
|
+
for (const base of llmdocDirBases) {
|
|
99
|
+
const relative = path.relative(base, absolutePath);
|
|
100
|
+
if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
|
|
101
|
+
return relative.replaceAll(path.sep, "/");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
throw new CliError(`无法从路径推导 llmdoc 相对路径: ${absolutePath}`);
|
|
105
|
+
};
|
|
106
|
+
const fromPathIsDirectory = fs.statSync(fromAbsolutePath).isDirectory();
|
|
107
|
+
if (fromPathIsDirectory) {
|
|
108
|
+
const fromBase = fromAbsolutePath;
|
|
109
|
+
for (const document of documents) {
|
|
110
|
+
if (document.absolutePath === fromBase || document.absolutePath.startsWith(`${fromBase}${path.sep}`)) {
|
|
111
|
+
const suffix = path.relative(fromBase, document.absolutePath);
|
|
112
|
+
const nextAbsolute = path.join(toAbsolutePath, suffix);
|
|
113
|
+
mapping.push({
|
|
114
|
+
oldLlmdocPath: toLlmdocPath(document.absolutePath),
|
|
115
|
+
newLlmdocPath: toLlmdocPath(nextAbsolute)
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
mapping.push({
|
|
122
|
+
oldLlmdocPath: toLlmdocPath(fromAbsolutePath),
|
|
123
|
+
newLlmdocPath: toLlmdocPath(toAbsolutePath)
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return mapping.sort((left, right) => right.oldLlmdocPath.length - left.oldLlmdocPath.length);
|
|
127
|
+
}
|
|
128
|
+
function rollbackMove(rootDir, toAbsolutePath) {
|
|
129
|
+
try {
|
|
130
|
+
fs.rmSync(toAbsolutePath, { recursive: true, force: true });
|
|
131
|
+
gitRestorePaths(rootDir, ["llmdoc"]);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function documentTouchesMove(document, mapping) {
|
|
139
|
+
if (mapping.some((item) => document.llmdocPath === item.oldLlmdocPath)) {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
const relationTargets = [
|
|
143
|
+
...(document.frontmatter.relations?.requires ?? []),
|
|
144
|
+
...(document.frontmatter.relations?.related ?? [])
|
|
145
|
+
];
|
|
146
|
+
if (relationTargets.some((target) => mapping.some((item) => target === item.oldLlmdocPath || target.startsWith(`${item.oldLlmdocPath}/`)))) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
return document.links.some((target) => {
|
|
150
|
+
const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(document.llmdocPath), target));
|
|
151
|
+
return mapping.some((item) => resolved === item.oldLlmdocPath || resolved.startsWith(`${item.oldLlmdocPath}/`));
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
function rewriteMeta(meta, mapping) {
|
|
155
|
+
const nextDocuments = {};
|
|
156
|
+
for (const [docPath, value] of Object.entries(meta.documents)) {
|
|
157
|
+
const rewrittenPath = rewritePath(docPath, mapping);
|
|
158
|
+
nextDocuments[rewrittenPath] = value;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
...meta,
|
|
162
|
+
documents: nextDocuments
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function rewritePath(input, mapping) {
|
|
166
|
+
for (const item of mapping) {
|
|
167
|
+
if (input === item.oldLlmdocPath) {
|
|
168
|
+
return item.newLlmdocPath;
|
|
169
|
+
}
|
|
170
|
+
if (input.startsWith(`${item.oldLlmdocPath}/`)) {
|
|
171
|
+
return `${item.newLlmdocPath}${input.slice(item.oldLlmdocPath.length)}`;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return input;
|
|
175
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseDocTargetShape, assertDocKindMatchesShape, assertDocumentKind } from "../lib/doc-shape.js";
|
|
4
|
+
import { CliError } from "../lib/errors.js";
|
|
5
|
+
import { ensureDirectory, findProjectRoot, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
|
|
6
|
+
import { packageRootFromImport } from "../lib/package-root.js";
|
|
7
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
8
|
+
export function runNew(options) {
|
|
9
|
+
const rootDir = findProjectRoot(options.cwd);
|
|
10
|
+
const repoRelativePath = normalizeDocDestination(options.path);
|
|
11
|
+
const kind = assertDocumentKind(options.kind);
|
|
12
|
+
const shape = parseDocTargetShape(repoRelativePath);
|
|
13
|
+
assertDocKindMatchesShape(shape);
|
|
14
|
+
const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
|
|
15
|
+
if (fs.existsSync(absolutePath)) {
|
|
16
|
+
throw new CliError(`目标已存在: ${repoRelativePath}`);
|
|
17
|
+
}
|
|
18
|
+
ensureDirectory(absolutePath);
|
|
19
|
+
const template = readTemplate();
|
|
20
|
+
const title = path.basename(repoRelativePath, ".mdx").replaceAll("-", " ");
|
|
21
|
+
// description 经 JSON.stringify 得到合法的 YAML double-quoted scalar,防止引号/冒号/换行破坏 front matter;
|
|
22
|
+
// replace 一律用函数形式,避免 $& 等替换模式展开。
|
|
23
|
+
const content = template
|
|
24
|
+
.replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: 补充文档描述。"))
|
|
25
|
+
.replace("__KIND__", () => kind)
|
|
26
|
+
.replace("__TITLE__", () => title);
|
|
27
|
+
fs.writeFileSync(absolutePath, content);
|
|
28
|
+
syncMetaEntry(rootDir, shape.llmdocPath);
|
|
29
|
+
if (options.json) {
|
|
30
|
+
return {
|
|
31
|
+
created: repoRelativePath
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
return `created: ${repoRelativePath}`;
|
|
35
|
+
}
|
|
36
|
+
function normalizeDocDestination(input) {
|
|
37
|
+
const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
|
|
38
|
+
if (!repoRelativePath.startsWith("llmdoc/") || !repoRelativePath.endsWith(".mdx")) {
|
|
39
|
+
throw new CliError("new 只能创建 llmdoc/ 下的 .mdx 文档。");
|
|
40
|
+
}
|
|
41
|
+
return repoRelativePath;
|
|
42
|
+
}
|
|
43
|
+
function readTemplate() {
|
|
44
|
+
const packageRoot = packageRootFromImport(import.meta.url);
|
|
45
|
+
return fs.readFileSync(path.join(packageRoot, "templates", "doc.mdx"), "utf8");
|
|
46
|
+
}
|
|
47
|
+
function syncMetaEntry(rootDir, llmdocPath) {
|
|
48
|
+
const workspace = loadWorkspace(rootDir);
|
|
49
|
+
if (!workspace.meta) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (!workspace.meta.documents[llmdocPath]) {
|
|
53
|
+
// 新文档尚未经过任何验证,登记为 null;validatedRevision 只能由 fingerprint 在验证后写入。
|
|
54
|
+
workspace.meta.documents[llmdocPath] = {
|
|
55
|
+
validatedRevision: null
|
|
56
|
+
};
|
|
57
|
+
fs.writeFileSync(workspace.metaPath, `${JSON.stringify(workspace.meta, null, 2)}\n`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { FRAGMENT_TOKEN_THRESHOLD } from "../lib/constants.js";
|
|
2
|
+
import { computeGrowthState } from "../lib/state.js";
|
|
3
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
4
|
+
export function runPrune(options) {
|
|
5
|
+
if (!options.report) {
|
|
6
|
+
return options.json
|
|
7
|
+
? { status: "dry_run", message: "prune 当前仅支持 --report。", writable: false }
|
|
8
|
+
: "prune 当前仅支持 --report。";
|
|
9
|
+
}
|
|
10
|
+
const workspace = loadWorkspace(options.cwd);
|
|
11
|
+
const growth = computeGrowthState(workspace);
|
|
12
|
+
const duplicateCandidates = findDuplicateCandidates(workspace.documents);
|
|
13
|
+
const mergeCandidates = findMergeCandidates(workspace.documents);
|
|
14
|
+
if (options.json) {
|
|
15
|
+
return {
|
|
16
|
+
status: "dry_run",
|
|
17
|
+
writable: false,
|
|
18
|
+
growth,
|
|
19
|
+
duplicateCandidates: duplicateCandidates.map((candidate) => ({
|
|
20
|
+
paths: [`llmdoc/${candidate.left.llmdocPath}`, `llmdoc/${candidate.right.llmdocPath}`],
|
|
21
|
+
score: candidate.score,
|
|
22
|
+
reasons: candidate.reasons
|
|
23
|
+
})),
|
|
24
|
+
mergeCandidates: mergeCandidates.map((candidate) => ({
|
|
25
|
+
topic: candidate.topic,
|
|
26
|
+
paths: candidate.documents.map((document) => `llmdoc/${document.llmdocPath}`),
|
|
27
|
+
totalEstimatedTokens: candidate.totalEstimatedTokens,
|
|
28
|
+
reasons: candidate.reasons
|
|
29
|
+
}))
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const growthLine = growth.baselineDocumentCount === null
|
|
33
|
+
? `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (no convergence baseline)`
|
|
34
|
+
: `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens; baseline ${growth.baselineDocumentCount} docs, ~${growth.baselineTotalEstimatedTokens} tokens; delta ${growth.documentDelta}, ~${growth.tokenDelta} tokens; ${growth.exceedsGate ? "above gate" : "below gate"}`;
|
|
35
|
+
const lines = [growthLine, ""];
|
|
36
|
+
lines.push("duplicate candidates:");
|
|
37
|
+
if (duplicateCandidates.length === 0) {
|
|
38
|
+
lines.push(" none");
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
for (const candidate of duplicateCandidates) {
|
|
42
|
+
lines.push(` llmdoc/${candidate.left.llmdocPath} <-> llmdoc/${candidate.right.llmdocPath} (score ${candidate.score.toFixed(2)})`);
|
|
43
|
+
lines.push(` reasons: ${candidate.reasons.join("; ")}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
lines.push("", "fragment / merge candidates:");
|
|
47
|
+
if (mergeCandidates.length === 0) {
|
|
48
|
+
lines.push(" none");
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
for (const candidate of mergeCandidates) {
|
|
52
|
+
lines.push(` topic ${candidate.topic}: ${candidate.documents.length} small docs, ~${candidate.totalEstimatedTokens} tokens`);
|
|
53
|
+
lines.push(` paths: ${candidate.documents.map((document) => `llmdoc/${document.llmdocPath}`).join(", ")}`);
|
|
54
|
+
lines.push(` reasons: ${candidate.reasons.join("; ")}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return lines.join("\n");
|
|
58
|
+
}
|
|
59
|
+
function findDuplicateCandidates(documents) {
|
|
60
|
+
const results = [];
|
|
61
|
+
for (let index = 0; index < documents.length; index += 1) {
|
|
62
|
+
for (let nextIndex = index + 1; nextIndex < documents.length; nextIndex += 1) {
|
|
63
|
+
const left = documents[index];
|
|
64
|
+
const right = documents[nextIndex];
|
|
65
|
+
if (left.topic !== right.topic || left.frontmatter.kind !== right.frontmatter.kind) {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const reasons = [];
|
|
69
|
+
let score = 0;
|
|
70
|
+
if (normalizeText(left.frontmatter.description) === normalizeText(right.frontmatter.description)) {
|
|
71
|
+
reasons.push("description identical");
|
|
72
|
+
score += 0.45;
|
|
73
|
+
}
|
|
74
|
+
const titleSimilarity = diceCoefficient(normalizeText(left.title ?? ""), normalizeText(right.title ?? ""));
|
|
75
|
+
if (titleSimilarity >= 0.7) {
|
|
76
|
+
reasons.push(`title similarity ${titleSimilarity.toFixed(2)}`);
|
|
77
|
+
score += 0.25;
|
|
78
|
+
}
|
|
79
|
+
const codeOverlap = overlapRatio(left.frontmatter.code?.paths ?? [], right.frontmatter.code?.paths ?? []);
|
|
80
|
+
if (codeOverlap > 0) {
|
|
81
|
+
reasons.push(`code.paths overlap ${codeOverlap.toFixed(2)}`);
|
|
82
|
+
score += 0.3 * codeOverlap;
|
|
83
|
+
}
|
|
84
|
+
const relationOverlap = overlapRatio([...(left.frontmatter.relations?.requires ?? []), ...(left.frontmatter.relations?.related ?? [])], [...(right.frontmatter.relations?.requires ?? []), ...(right.frontmatter.relations?.related ?? [])]);
|
|
85
|
+
if (relationOverlap > 0.5) {
|
|
86
|
+
reasons.push(`relations overlap ${relationOverlap.toFixed(2)}`);
|
|
87
|
+
score += 0.15;
|
|
88
|
+
}
|
|
89
|
+
if (score >= 0.72) {
|
|
90
|
+
results.push({ left, right, score, reasons });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return results.sort((left, right) => right.score - left.score || left.left.llmdocPath.localeCompare(right.left.llmdocPath));
|
|
95
|
+
}
|
|
96
|
+
function findMergeCandidates(documents) {
|
|
97
|
+
const grouped = new Map();
|
|
98
|
+
for (const document of documents) {
|
|
99
|
+
if (!document.topic) {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const bucket = grouped.get(document.topic) ?? [];
|
|
103
|
+
bucket.push(document);
|
|
104
|
+
grouped.set(document.topic, bucket);
|
|
105
|
+
}
|
|
106
|
+
const results = [];
|
|
107
|
+
for (const [topic, docs] of grouped) {
|
|
108
|
+
const smallDocs = docs.filter((document) => document.estimatedTokens <= FRAGMENT_TOKEN_THRESHOLD);
|
|
109
|
+
if (smallDocs.length < 2) {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const totalEstimatedTokens = smallDocs.reduce((sum, document) => sum + document.estimatedTokens, 0);
|
|
113
|
+
results.push({
|
|
114
|
+
topic,
|
|
115
|
+
documents: smallDocs.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath)),
|
|
116
|
+
totalEstimatedTokens,
|
|
117
|
+
reasons: ["multiple small documents within one topic", "candidate for merge or route simplification"]
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return results.sort((left, right) => right.documents.length - left.documents.length || left.topic.localeCompare(right.topic));
|
|
121
|
+
}
|
|
122
|
+
function normalizeText(input) {
|
|
123
|
+
return input.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, " ").trim();
|
|
124
|
+
}
|
|
125
|
+
function diceCoefficient(left, right) {
|
|
126
|
+
if (!left || !right) {
|
|
127
|
+
return 0;
|
|
128
|
+
}
|
|
129
|
+
if (left === right) {
|
|
130
|
+
return 1;
|
|
131
|
+
}
|
|
132
|
+
const leftBigrams = bigrams(left);
|
|
133
|
+
const rightBigrams = bigrams(right);
|
|
134
|
+
let overlap = 0;
|
|
135
|
+
const counts = new Map();
|
|
136
|
+
for (const bigram of leftBigrams) {
|
|
137
|
+
counts.set(bigram, (counts.get(bigram) ?? 0) + 1);
|
|
138
|
+
}
|
|
139
|
+
for (const bigram of rightBigrams) {
|
|
140
|
+
const count = counts.get(bigram) ?? 0;
|
|
141
|
+
if (count > 0) {
|
|
142
|
+
overlap += 1;
|
|
143
|
+
counts.set(bigram, count - 1);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return (2 * overlap) / (leftBigrams.length + rightBigrams.length);
|
|
147
|
+
}
|
|
148
|
+
function bigrams(input) {
|
|
149
|
+
if (input.length < 2) {
|
|
150
|
+
return [input];
|
|
151
|
+
}
|
|
152
|
+
const result = [];
|
|
153
|
+
for (let index = 0; index < input.length - 1; index += 1) {
|
|
154
|
+
result.push(input.slice(index, index + 2));
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
function overlapRatio(left, right) {
|
|
159
|
+
const leftSet = new Set(left);
|
|
160
|
+
const rightSet = new Set(right);
|
|
161
|
+
if (leftSet.size === 0 || rightSet.size === 0) {
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
let overlap = 0;
|
|
165
|
+
for (const value of leftSet) {
|
|
166
|
+
if (rightSet.has(value)) {
|
|
167
|
+
overlap += 1;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return overlap / Math.min(leftSet.size, rightSet.size);
|
|
171
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { paginate, paginationMetadata } from "../lib/pagination.js";
|
|
2
|
+
import { assertDocumentKind } from "../lib/doc-shape.js";
|
|
3
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
4
|
+
import { formatPaginationSummary } from "../lib/format.js";
|
|
5
|
+
import { searchDocuments } from "../lib/search.js";
|
|
6
|
+
import { estimateTokens } from "../lib/markdown.js";
|
|
7
|
+
export function runSearch(options) {
|
|
8
|
+
const workspace = loadWorkspace(options.cwd);
|
|
9
|
+
const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
|
|
10
|
+
const results = searchDocuments(workspace, options.query, {
|
|
11
|
+
topic: options.topic,
|
|
12
|
+
kind
|
|
13
|
+
});
|
|
14
|
+
const paginated = paginate({
|
|
15
|
+
items: results,
|
|
16
|
+
estimate: (entry) => estimateTokens(JSON.stringify(toPayload(entry))),
|
|
17
|
+
options
|
|
18
|
+
});
|
|
19
|
+
if (options.json) {
|
|
20
|
+
return {
|
|
21
|
+
query: options.query,
|
|
22
|
+
results: paginated.items.map(toPayload),
|
|
23
|
+
pagination: paginationMetadata(paginated)
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const lines = [];
|
|
27
|
+
for (const entry of paginated.items) {
|
|
28
|
+
lines.push(`llmdoc/${entry.document.llmdocPath} [${entry.document.frontmatter.kind}]`);
|
|
29
|
+
lines.push(` ${entry.document.frontmatter.description}`);
|
|
30
|
+
lines.push(` ${entry.snippet}`);
|
|
31
|
+
lines.push("");
|
|
32
|
+
}
|
|
33
|
+
lines.push(...formatPaginationSummary(paginated));
|
|
34
|
+
return lines.join("\n");
|
|
35
|
+
}
|
|
36
|
+
function toPayload(entry) {
|
|
37
|
+
return {
|
|
38
|
+
path: `llmdoc/${entry.document.llmdocPath}`,
|
|
39
|
+
kind: entry.document.frontmatter.kind,
|
|
40
|
+
description: entry.document.frontmatter.description,
|
|
41
|
+
snippet: entry.snippet,
|
|
42
|
+
score: entry.score
|
|
43
|
+
};
|
|
44
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { paginate, paginationMetadata } from "../lib/pagination.js";
|
|
2
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
3
|
+
import { CliError } from "../lib/errors.js";
|
|
4
|
+
import { DEFAULT_SHOW_BUDGET } from "../lib/constants.js";
|
|
5
|
+
import { formatPaginationSummary } from "../lib/format.js";
|
|
6
|
+
import { estimateTokens } from "../lib/markdown.js";
|
|
7
|
+
export function runShow(options) {
|
|
8
|
+
const workspace = loadWorkspace(options.cwd);
|
|
9
|
+
const documents = options.paths.map((rawPath) => {
|
|
10
|
+
const normalized = rawPath.startsWith("llmdoc/") ? rawPath.slice("llmdoc/".length) : rawPath;
|
|
11
|
+
const document = workspace.documentsByLlmdocPath.get(normalized);
|
|
12
|
+
if (!document) {
|
|
13
|
+
throw new CliError(`文档不存在: ${rawPath}`);
|
|
14
|
+
}
|
|
15
|
+
return document;
|
|
16
|
+
});
|
|
17
|
+
const result = paginate({
|
|
18
|
+
items: documents,
|
|
19
|
+
estimate: (document) => estimateTokens(JSON.stringify(toDocumentPayload(document))),
|
|
20
|
+
options: {
|
|
21
|
+
...options,
|
|
22
|
+
budget: options.budget ?? DEFAULT_SHOW_BUDGET
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
if (options.json) {
|
|
26
|
+
return {
|
|
27
|
+
documents: result.items.map(toDocumentPayload),
|
|
28
|
+
pagination: paginationMetadata(result)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const lines = [];
|
|
32
|
+
for (const document of result.items) {
|
|
33
|
+
lines.push(`=== llmdoc/${document.llmdocPath} [${document.frontmatter.kind}] ===`);
|
|
34
|
+
lines.push(document.body);
|
|
35
|
+
lines.push("");
|
|
36
|
+
}
|
|
37
|
+
lines.push(...formatPaginationSummary(result));
|
|
38
|
+
return lines.join("\n");
|
|
39
|
+
}
|
|
40
|
+
function toDocumentPayload(document) {
|
|
41
|
+
return {
|
|
42
|
+
path: `llmdoc/${document.llmdocPath}`,
|
|
43
|
+
kind: document.frontmatter.kind,
|
|
44
|
+
description: document.frontmatter.description,
|
|
45
|
+
body: document.body
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { computeGrowthState, analyzeDelta } from "../lib/state.js";
|
|
2
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
3
|
+
export function runStatus(options) {
|
|
4
|
+
const workspace = loadWorkspace(options.cwd);
|
|
5
|
+
const delta = analyzeDelta(workspace);
|
|
6
|
+
const growth = computeGrowthState(workspace);
|
|
7
|
+
if (options.json) {
|
|
8
|
+
return {
|
|
9
|
+
baseline: workspace.meta?.baseline.revision ?? null,
|
|
10
|
+
head: delta.git.headRevision,
|
|
11
|
+
commitsBehindHead: delta.git.baselineBehindHead,
|
|
12
|
+
degradedReason: delta.git.degradedReason,
|
|
13
|
+
documents: {
|
|
14
|
+
total: workspace.documents.length,
|
|
15
|
+
impacted: delta.impacts.length,
|
|
16
|
+
needsReview: delta.needsReview.length,
|
|
17
|
+
dirty: delta.dirtyDocuments.length
|
|
18
|
+
},
|
|
19
|
+
unmapped: {
|
|
20
|
+
committed: delta.unmappedCommittedPaths,
|
|
21
|
+
dirty: delta.unmappedDirtyPaths
|
|
22
|
+
},
|
|
23
|
+
growth
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const baseline = workspace.meta?.baseline.revision ?? "missing";
|
|
27
|
+
const behind = delta.git.baselineBehindHead === null ? "unknown" : `${delta.git.baselineBehindHead} commits behind HEAD`;
|
|
28
|
+
const unmapped = [...delta.unmappedCommittedPaths, ...delta.unmappedDirtyPaths];
|
|
29
|
+
const growthLabel = growth.baselineDocumentCount === null
|
|
30
|
+
? `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (no convergence baseline)`
|
|
31
|
+
: `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (baseline ${growth.baselineDocumentCount} docs, ~${growth.baselineTotalEstimatedTokens} tokens) — ${growth.exceedsGate ? "above gate" : "below gate"}`;
|
|
32
|
+
const lines = [
|
|
33
|
+
`baseline: ${baseline} (${behind})`,
|
|
34
|
+
`documents: ${workspace.documents.length} total / ${delta.impacts.length} impacted / ${delta.needsReview.length} needs-review / ${delta.dirtyDocuments.length} dirty`
|
|
35
|
+
];
|
|
36
|
+
if (unmapped.length > 0) {
|
|
37
|
+
const shown = unmapped.slice(0, 5);
|
|
38
|
+
const rest = unmapped.length - shown.length;
|
|
39
|
+
lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (--json 查看全部)` : ""}`);
|
|
40
|
+
}
|
|
41
|
+
lines.push(growthLabel);
|
|
42
|
+
if (delta.git.degradedReason) {
|
|
43
|
+
lines.push(`degraded: ${delta.git.degradedReason}`);
|
|
44
|
+
}
|
|
45
|
+
return lines.join("\n");
|
|
46
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { paginate, paginationMetadata } from "../lib/pagination.js";
|
|
2
|
+
import { loadWorkspace } from "../lib/workspace.js";
|
|
3
|
+
import { formatPaginationSummary } from "../lib/format.js";
|
|
4
|
+
import { estimateTokens } from "../lib/markdown.js";
|
|
5
|
+
export function runTree(options) {
|
|
6
|
+
const workspace = loadWorkspace(options.cwd);
|
|
7
|
+
if (options.docs) {
|
|
8
|
+
const result = paginate({
|
|
9
|
+
items: workspace.documents,
|
|
10
|
+
estimate: (document) => estimateTokens(JSON.stringify(toDocumentSummary(document))),
|
|
11
|
+
options
|
|
12
|
+
});
|
|
13
|
+
if (options.json) {
|
|
14
|
+
return {
|
|
15
|
+
root: "llmdoc",
|
|
16
|
+
documents: result.items.map(toDocumentSummary),
|
|
17
|
+
pagination: paginationMetadata(result)
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const lines = [`llmdoc/ (${workspace.documents.length} docs, ~${workspace.documents.reduce((sum, document) => sum + document.estimatedTokens, 0)} tokens)`, ""];
|
|
21
|
+
for (const document of result.items) {
|
|
22
|
+
lines.push(` ${document.llmdocPath} [${document.frontmatter.kind}]`);
|
|
23
|
+
lines.push(` ${document.frontmatter.description}`);
|
|
24
|
+
}
|
|
25
|
+
lines.push("", ...formatPaginationSummary(result));
|
|
26
|
+
return lines.join("\n");
|
|
27
|
+
}
|
|
28
|
+
const topics = [...workspace.topics.entries()]
|
|
29
|
+
.map(([topic, docs]) => ({
|
|
30
|
+
topic,
|
|
31
|
+
docs,
|
|
32
|
+
// 无入口节点:topic 摘要由文档名聚合,详情用 `index --topic` 看各文档 description。
|
|
33
|
+
summary: docs.map((document) => document.basename.replace(/\.mdx$/, "")).join(", "),
|
|
34
|
+
estimatedTokens: docs.reduce((sum, document) => sum + document.estimatedTokens, 0)
|
|
35
|
+
}))
|
|
36
|
+
.sort((left, right) => left.topic.localeCompare(right.topic));
|
|
37
|
+
const rootSingletons = [...workspace.rootSingletons].sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
|
|
38
|
+
const entries = [
|
|
39
|
+
...rootSingletons.map((document) => ({ type: "rootSingleton", document })),
|
|
40
|
+
...topics.map((topic) => ({ type: "topic", topic }))
|
|
41
|
+
];
|
|
42
|
+
const result = paginate({
|
|
43
|
+
items: entries,
|
|
44
|
+
estimate: (entry) => entry.type === "rootSingleton"
|
|
45
|
+
? estimateTokens(JSON.stringify(toRootSingletonSummary(entry.document)))
|
|
46
|
+
: estimateTokens(JSON.stringify(toTopicSummary(entry.topic))),
|
|
47
|
+
options
|
|
48
|
+
});
|
|
49
|
+
if (options.json) {
|
|
50
|
+
return {
|
|
51
|
+
root: "llmdoc",
|
|
52
|
+
rootSingletons: result.items
|
|
53
|
+
.filter((entry) => entry.type === "rootSingleton")
|
|
54
|
+
.map((entry) => toRootSingletonSummary(entry.document)),
|
|
55
|
+
topics: result.items.filter((entry) => entry.type === "topic").map((entry) => toTopicSummary(entry.topic)),
|
|
56
|
+
pagination: paginationMetadata(result)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const lines = [`llmdoc/ (${workspace.documents.length} docs, ~${workspace.documents.reduce((sum, document) => sum + document.estimatedTokens, 0)} tokens)`, ""];
|
|
60
|
+
for (const entry of result.items) {
|
|
61
|
+
if (entry.type === "rootSingleton") {
|
|
62
|
+
lines.push(` ${entry.document.basename} [${entry.document.frontmatter.kind}]`);
|
|
63
|
+
lines.push(` ${entry.document.frontmatter.description}`);
|
|
64
|
+
lines.push("");
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
lines.push(` ${entry.topic.topic}/ (${entry.topic.docs.length} docs, ~${entry.topic.estimatedTokens} tokens)`);
|
|
68
|
+
lines.push(` ${entry.topic.summary}`);
|
|
69
|
+
}
|
|
70
|
+
lines.push("", ...formatPaginationSummary(result));
|
|
71
|
+
lines.push("hint: `llmdoc tree --docs` 展开文档级;`llmdoc index --topic <t>` 看文档元数据");
|
|
72
|
+
return lines.join("\n");
|
|
73
|
+
}
|
|
74
|
+
function toDocumentSummary(document) {
|
|
75
|
+
return {
|
|
76
|
+
path: `llmdoc/${document.llmdocPath}`,
|
|
77
|
+
kind: document.frontmatter.kind,
|
|
78
|
+
description: document.frontmatter.description,
|
|
79
|
+
topic: document.topic
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function toRootSingletonSummary(document) {
|
|
83
|
+
return {
|
|
84
|
+
path: `llmdoc/${document.llmdocPath}`,
|
|
85
|
+
kind: document.frontmatter.kind,
|
|
86
|
+
description: document.frontmatter.description
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function toTopicSummary(topic) {
|
|
90
|
+
return {
|
|
91
|
+
topic: topic.topic,
|
|
92
|
+
summary: topic.summary,
|
|
93
|
+
documentCount: topic.docs.length,
|
|
94
|
+
estimatedTokens: topic.estimatedTokens
|
|
95
|
+
};
|
|
96
|
+
}
|