@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,124 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findProjectRootOrNull, resolveInsideRoot } from "../lib/fs.js";
|
|
4
|
+
import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
|
|
5
|
+
export async function runUpgrade(options) {
|
|
6
|
+
const rootDir = findProjectRootOrNull(options.cwd) ?? options.cwd;
|
|
7
|
+
const configuredLlmdocDir = path.join(rootDir, "llmdoc");
|
|
8
|
+
if (fs.existsSync(configuredLlmdocDir)) {
|
|
9
|
+
resolveInsideRoot(rootDir, "llmdoc");
|
|
10
|
+
}
|
|
11
|
+
const report = fs.existsSync(configuredLlmdocDir) ? inspectLlmdocDirectory(configuredLlmdocDir) : inspectMissingLlmdoc();
|
|
12
|
+
if (options.json) {
|
|
13
|
+
return report;
|
|
14
|
+
}
|
|
15
|
+
const lines = [`status: ${report.status}`, `summary: ${report.summary}`];
|
|
16
|
+
if (report.legacyPaths.length > 0) {
|
|
17
|
+
lines.push(`legacy paths: ${report.legacyPaths.join(", ")}`);
|
|
18
|
+
}
|
|
19
|
+
if (report.targetStructure.length > 0) {
|
|
20
|
+
lines.push("target structure:");
|
|
21
|
+
for (const item of report.targetStructure) {
|
|
22
|
+
lines.push(` - ${item}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
lines.push(`recorder semantic migration required: ${report.requiresRecorderSemanticMigration ? "yes" : "no"}`);
|
|
26
|
+
if (report.notes.length > 0) {
|
|
27
|
+
lines.push("notes:");
|
|
28
|
+
for (const note of report.notes) {
|
|
29
|
+
lines.push(` - ${note}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return lines.join("\n");
|
|
33
|
+
}
|
|
34
|
+
function inspectMissingLlmdoc() {
|
|
35
|
+
return {
|
|
36
|
+
status: "no_change",
|
|
37
|
+
summary: "当前仓库不存在 llmdoc/,没有可升级的 V2/V3 知识面。",
|
|
38
|
+
legacyPaths: [],
|
|
39
|
+
targetStructure: [],
|
|
40
|
+
requiresRecorderSemanticMigration: false,
|
|
41
|
+
notes: ["如需首次建立知识面,请走 init,而不是 upgrade。"]
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function inspectLlmdocDirectory(llmdocDir) {
|
|
45
|
+
const allFiles = walkFiles(llmdocDir);
|
|
46
|
+
const legacyMarkers = ["index.md", "startup.md", "must", "overview", "memory", "records", "state/sync.md", "architecture", "guides", "reference"];
|
|
47
|
+
const legacyPaths = [
|
|
48
|
+
...legacyMarkers.filter((entry) => fs.existsSync(path.join(llmdocDir, entry))),
|
|
49
|
+
...allFiles
|
|
50
|
+
.filter((filePath) => filePath.endsWith(".md"))
|
|
51
|
+
.map((filePath) => path.relative(llmdocDir, filePath).replaceAll(path.sep, "/"))
|
|
52
|
+
].filter((value, index, items) => items.indexOf(value) === index);
|
|
53
|
+
const hasV3Meta = fs.existsSync(path.join(llmdocDir, "meta.json"));
|
|
54
|
+
const hasMdx = walkFiles(llmdocDir).some((filePath) => filePath.endsWith(".mdx"));
|
|
55
|
+
if (hasV3Meta && hasMdx && legacyPaths.length === 0) {
|
|
56
|
+
const rootDir = path.dirname(llmdocDir);
|
|
57
|
+
try {
|
|
58
|
+
const workspace = loadWorkspace(rootDir);
|
|
59
|
+
const errors = validateWorkspace(workspace).filter((issue) => issue.severity === "error");
|
|
60
|
+
if (errors.length > 0) {
|
|
61
|
+
return {
|
|
62
|
+
status: "dry_run",
|
|
63
|
+
summary: "检测到部分 V3 结构,但当前知识面未通过 V3 校验。",
|
|
64
|
+
legacyPaths: [],
|
|
65
|
+
targetStructure: ["修复现有 V3 结构错误后再判断是否需要 upgrade"],
|
|
66
|
+
requiresRecorderSemanticMigration: false,
|
|
67
|
+
notes: errors.slice(0, 5).map((issue) => `${issue.path ?? "unknown"}: ${issue.message}`)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return {
|
|
73
|
+
status: "dry_run",
|
|
74
|
+
summary: "检测到部分 V3 结构,但当前知识面无法稳定装载。",
|
|
75
|
+
legacyPaths: [],
|
|
76
|
+
targetStructure: ["修复现有 V3 结构错误后再判断是否需要 upgrade"],
|
|
77
|
+
requiresRecorderSemanticMigration: false,
|
|
78
|
+
notes: [error.message]
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
status: "no_change",
|
|
83
|
+
summary: "检测到现有知识面已经是 V3 结构,无需 upgrade。",
|
|
84
|
+
legacyPaths: [],
|
|
85
|
+
targetStructure: [],
|
|
86
|
+
requiresRecorderSemanticMigration: false,
|
|
87
|
+
notes: ["upgrade 当前只输出盘点,不会改写 V3 知识。"]
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (legacyPaths.length === 0 && !hasV3Meta && !hasMdx) {
|
|
91
|
+
return {
|
|
92
|
+
status: "dry_run",
|
|
93
|
+
summary: "检测到 llmdoc/ 目录,但没有明确的 V2 或 V3 结构特征。",
|
|
94
|
+
legacyPaths: [],
|
|
95
|
+
targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/index.mdx"],
|
|
96
|
+
requiresRecorderSemanticMigration: false,
|
|
97
|
+
notes: ["需要人工确认该目录是否为遗留知识面。"]
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
status: "dry_run",
|
|
102
|
+
summary: "检测到 legacy/V2 结构,需要 Recorder 参与语义迁移到 V3。",
|
|
103
|
+
legacyPaths,
|
|
104
|
+
targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/index.mdx", "llmdoc/<topic>/*.mdx"],
|
|
105
|
+
requiresRecorderSemanticMigration: true,
|
|
106
|
+
notes: [
|
|
107
|
+
hasV3Meta ? "存在部分 V3 迹象,但 legacy 结构仍在,需要整理边界后再迁移。" : "未发现完整 V3 ledger,需要生成新的 meta.json baseline。",
|
|
108
|
+
legacyPaths.includes("state/sync.md") ? "state/sync.md 需要迁移为 meta.json baseline.revision。" : "未发现 state/sync.md watermark。"
|
|
109
|
+
]
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function walkFiles(currentDir) {
|
|
113
|
+
const results = [];
|
|
114
|
+
for (const entry of fs.readdirSync(currentDir, { withFileTypes: true })) {
|
|
115
|
+
const absolutePath = path.join(currentDir, entry.name);
|
|
116
|
+
if (entry.isDirectory()) {
|
|
117
|
+
results.push(...walkFiles(absolutePath));
|
|
118
|
+
}
|
|
119
|
+
else if (entry.isFile()) {
|
|
120
|
+
results.push(absolutePath);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return results;
|
|
124
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
|
|
2
|
+
import { formatIssues } from "../lib/format.js";
|
|
3
|
+
export function runValidate(options) {
|
|
4
|
+
const workspace = loadWorkspace(options.cwd);
|
|
5
|
+
const issues = validateWorkspace(workspace);
|
|
6
|
+
const errors = issues.filter((issue) => issue.severity === "error");
|
|
7
|
+
const warnings = issues.filter((issue) => issue.severity === "warning");
|
|
8
|
+
const payload = {
|
|
9
|
+
ok: errors.length === 0,
|
|
10
|
+
errors,
|
|
11
|
+
warnings
|
|
12
|
+
};
|
|
13
|
+
if (options.json) {
|
|
14
|
+
return {
|
|
15
|
+
ok: payload.ok,
|
|
16
|
+
output: payload,
|
|
17
|
+
exitCode: payload.ok ? 0 : 1
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const output = issues.length === 0
|
|
21
|
+
? "validate: ok"
|
|
22
|
+
: [errors.length ? "errors:" : "", errors.length ? formatIssues(errors) : "", warnings.length ? "warnings:" : "", warnings.length ? formatIssues(warnings) : ""]
|
|
23
|
+
.filter(Boolean)
|
|
24
|
+
.join("\n");
|
|
25
|
+
return {
|
|
26
|
+
ok: payload.ok,
|
|
27
|
+
output,
|
|
28
|
+
exitCode: payload.ok ? 0 : 1
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const DEFAULT_BUDGET = 1200;
|
|
2
|
+
export const DEFAULT_SHOW_BUDGET = 2000;
|
|
3
|
+
export const DEFAULT_LIMIT = 50;
|
|
4
|
+
export const DOC_LINE_WARNING_LIMIT = 150;
|
|
5
|
+
export const CACHE_DIR = ".llmdoc-tmp/cache";
|
|
6
|
+
export const SEARCH_CACHE_FILE = "search-index.json";
|
|
7
|
+
export const FRAGMENT_TOKEN_THRESHOLD = 180;
|
|
8
|
+
export const DUPLICATE_SIMILARITY_THRESHOLD = 0.72;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { CliError } from "./errors.js";
|
|
3
|
+
const DOCUMENT_KINDS = ["architecture", "guide", "reference"];
|
|
4
|
+
export function parseDocTargetShape(repoRelativePath) {
|
|
5
|
+
if (!repoRelativePath.startsWith("llmdoc/")) {
|
|
6
|
+
throw new CliError("目标必须位于 llmdoc/ 下。");
|
|
7
|
+
}
|
|
8
|
+
if (!repoRelativePath.endsWith(".mdx")) {
|
|
9
|
+
throw new CliError("目标必须是 .mdx 文档。");
|
|
10
|
+
}
|
|
11
|
+
const llmdocPath = repoRelativePath.slice("llmdoc/".length);
|
|
12
|
+
const segments = llmdocPath.split("/");
|
|
13
|
+
if (segments.length !== 1 && segments.length !== 2) {
|
|
14
|
+
throw new CliError("V3 文档路径仅允许根 singleton 或 topic/file 两层。");
|
|
15
|
+
}
|
|
16
|
+
const basename = path.posix.basename(llmdocPath);
|
|
17
|
+
const topic = segments.length === 2 ? (segments[0] ?? null) : null;
|
|
18
|
+
const isRootSingleton = segments.length === 1;
|
|
19
|
+
return {
|
|
20
|
+
repoRelativePath,
|
|
21
|
+
llmdocPath,
|
|
22
|
+
segments,
|
|
23
|
+
basename,
|
|
24
|
+
topic,
|
|
25
|
+
isRootSingleton
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function assertDocKindMatchesShape(shape) {
|
|
29
|
+
// V3 不设入口节点:topic 即纯目录,描述由 CLI 从文档 front matter 聚合。
|
|
30
|
+
if (shape.basename === "index.mdx") {
|
|
31
|
+
throw new CliError("V3 不使用 index.mdx 入口节点;请使用普通命名,topic 描述由 llmdoc tree 聚合。");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function validateMoveTargetShape(shape) {
|
|
35
|
+
assertDocKindMatchesShape(shape);
|
|
36
|
+
}
|
|
37
|
+
export function isDirectTopicDirectory(repoRelativePath) {
|
|
38
|
+
if (!repoRelativePath.startsWith("llmdoc/")) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
const llmdocPath = repoRelativePath.slice("llmdoc/".length).replace(/\/+$/, "");
|
|
42
|
+
const segments = llmdocPath.split("/").filter(Boolean);
|
|
43
|
+
return segments.length === 1;
|
|
44
|
+
}
|
|
45
|
+
export function assertDocumentKind(input) {
|
|
46
|
+
if (DOCUMENT_KINDS.includes(input)) {
|
|
47
|
+
return input;
|
|
48
|
+
}
|
|
49
|
+
throw new CliError(`非法 kind: ${input}。允许值: ${DOCUMENT_KINDS.join(", ")}`);
|
|
50
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
export function formatDocumentLine(document) {
|
|
3
|
+
return `llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`;
|
|
4
|
+
}
|
|
5
|
+
export function formatPaginationSummary(result) {
|
|
6
|
+
const lines = [
|
|
7
|
+
`returned: ${result.returnedItems}/${result.totalItems} items (~${result.returnedEstimatedTokens}/${result.totalEstimatedTokens} tokens)`
|
|
8
|
+
];
|
|
9
|
+
if (result.nextCursor) {
|
|
10
|
+
lines.push(`cursor: ${result.nextCursor}`);
|
|
11
|
+
}
|
|
12
|
+
return lines;
|
|
13
|
+
}
|
|
14
|
+
export function formatIssues(issues) {
|
|
15
|
+
return issues
|
|
16
|
+
.map((issue) => {
|
|
17
|
+
const location = issue.path ? ` (${issue.path})` : "";
|
|
18
|
+
return `${issue.severity}: ${issue.code}${location} ${issue.message}`;
|
|
19
|
+
})
|
|
20
|
+
.join("\n");
|
|
21
|
+
}
|
|
22
|
+
export function toRepoDocPath(llmdocPath) {
|
|
23
|
+
return path.posix.join("llmdoc", llmdocPath);
|
|
24
|
+
}
|
package/dist/lib/fs.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { CliError } from "./errors.js";
|
|
4
|
+
export function findProjectRoot(startDir) {
|
|
5
|
+
const found = findProjectRootOrNull(startDir);
|
|
6
|
+
if (found) {
|
|
7
|
+
return found;
|
|
8
|
+
}
|
|
9
|
+
throw new CliError("未找到 llmdoc/ 目录,请在仓库内运行该命令。", 2);
|
|
10
|
+
}
|
|
11
|
+
export function findProjectRootOrNull(startDir) {
|
|
12
|
+
let current = path.resolve(startDir);
|
|
13
|
+
while (true) {
|
|
14
|
+
if (fs.existsSync(path.join(current, "llmdoc")) && fs.statSync(path.join(current, "llmdoc")).isDirectory()) {
|
|
15
|
+
return current;
|
|
16
|
+
}
|
|
17
|
+
const parent = path.dirname(current);
|
|
18
|
+
if (parent === current) {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
current = parent;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function normalizeRepoRelativePath(input) {
|
|
25
|
+
const normalized = input.replaceAll("\\", "/");
|
|
26
|
+
if (!normalized || normalized.startsWith("/") || normalized.includes("\0")) {
|
|
27
|
+
throw new CliError(`非法路径: ${input}`);
|
|
28
|
+
}
|
|
29
|
+
const parts = normalized.split("/").filter((part) => part !== ".");
|
|
30
|
+
if (parts.length === 0) {
|
|
31
|
+
throw new CliError(`非法路径: ${input}`);
|
|
32
|
+
}
|
|
33
|
+
if (parts.some((part) => part === ".." || part === "")) {
|
|
34
|
+
throw new CliError(`路径必须是仓库内规范化相对路径: ${input}`);
|
|
35
|
+
}
|
|
36
|
+
return parts.join("/");
|
|
37
|
+
}
|
|
38
|
+
export function resolveInsideRoot(rootDir, repoRelativePath, options) {
|
|
39
|
+
const safeRelativePath = normalizeRepoRelativePath(repoRelativePath);
|
|
40
|
+
const candidate = path.join(rootDir, safeRelativePath);
|
|
41
|
+
const rootRealPath = fs.realpathSync(rootDir);
|
|
42
|
+
const nearestExistingAncestor = findNearestExistingAncestor(candidate);
|
|
43
|
+
const ancestorRealPath = fs.realpathSync(nearestExistingAncestor);
|
|
44
|
+
if (!isWithinRoot(rootRealPath, ancestorRealPath)) {
|
|
45
|
+
throw new CliError(`路径越界或经由符号链接逃逸: ${repoRelativePath}`);
|
|
46
|
+
}
|
|
47
|
+
if (fs.existsSync(candidate)) {
|
|
48
|
+
const candidateRealPath = fs.realpathSync(candidate);
|
|
49
|
+
if (!isWithinRoot(rootRealPath, candidateRealPath)) {
|
|
50
|
+
throw new CliError(`路径越界或经由符号链接逃逸: ${repoRelativePath}`);
|
|
51
|
+
}
|
|
52
|
+
return candidateRealPath;
|
|
53
|
+
}
|
|
54
|
+
if (options?.allowMissing) {
|
|
55
|
+
return candidate;
|
|
56
|
+
}
|
|
57
|
+
throw new CliError(`路径不存在: ${repoRelativePath}`);
|
|
58
|
+
}
|
|
59
|
+
export function isWithinRoot(rootRealPath, candidateRealPath) {
|
|
60
|
+
return candidateRealPath === rootRealPath || candidateRealPath.startsWith(`${rootRealPath}${path.sep}`);
|
|
61
|
+
}
|
|
62
|
+
export function toPosixRelative(fromDir, toPath) {
|
|
63
|
+
return path.relative(fromDir, toPath).replaceAll(path.sep, "/");
|
|
64
|
+
}
|
|
65
|
+
export function ensureDirectory(filePath) {
|
|
66
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
67
|
+
}
|
|
68
|
+
export function repoPath(rootDir, absolutePath) {
|
|
69
|
+
return path.relative(rootDir, absolutePath).replaceAll(path.sep, "/");
|
|
70
|
+
}
|
|
71
|
+
function findNearestExistingAncestor(candidatePath) {
|
|
72
|
+
let current = path.resolve(path.dirname(candidatePath));
|
|
73
|
+
while (!fs.existsSync(current)) {
|
|
74
|
+
const parent = path.dirname(current);
|
|
75
|
+
if (parent === current) {
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
current = parent;
|
|
79
|
+
}
|
|
80
|
+
return current;
|
|
81
|
+
}
|
package/dist/lib/git.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { CliError } from "./errors.js";
|
|
5
|
+
function runGit(rootDir, args) {
|
|
6
|
+
const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
|
|
7
|
+
cwd: rootDir,
|
|
8
|
+
encoding: "utf8"
|
|
9
|
+
});
|
|
10
|
+
if (result.status !== 0) {
|
|
11
|
+
throw new CliError((result.stderr || result.stdout || "git 命令失败").trim());
|
|
12
|
+
}
|
|
13
|
+
return result.stdout.trim();
|
|
14
|
+
}
|
|
15
|
+
export function gitMove(rootDir, fromRepoPath, toRepoPath) {
|
|
16
|
+
runGit(rootDir, ["mv", "--", fromRepoPath, toRepoPath]);
|
|
17
|
+
}
|
|
18
|
+
export function gitRestorePaths(rootDir, repoRelativePaths) {
|
|
19
|
+
runGit(rootDir, ["reset", "--quiet", "--", ...repoRelativePaths]);
|
|
20
|
+
runGit(rootDir, ["checkout", "--quiet", "--", ...repoRelativePaths]);
|
|
21
|
+
}
|
|
22
|
+
export function gitCommitExists(rootDir, revision) {
|
|
23
|
+
const result = spawnSync("git", ["cat-file", "-e", `${revision}^{commit}`], {
|
|
24
|
+
cwd: rootDir,
|
|
25
|
+
encoding: "utf8"
|
|
26
|
+
});
|
|
27
|
+
return result.status === 0;
|
|
28
|
+
}
|
|
29
|
+
export function readGitState(rootDir, baselineRevision) {
|
|
30
|
+
if (!isGitRepository(rootDir)) {
|
|
31
|
+
return {
|
|
32
|
+
available: false,
|
|
33
|
+
headRevision: null,
|
|
34
|
+
detached: false,
|
|
35
|
+
inProgressOperation: null,
|
|
36
|
+
baselineBehindHead: null,
|
|
37
|
+
committedChangedPaths: [],
|
|
38
|
+
stagedPaths: [],
|
|
39
|
+
unstagedPaths: [],
|
|
40
|
+
untrackedPaths: [],
|
|
41
|
+
degradedReason: "当前目录不是 git 仓库,状态面降级为不可用。"
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const headRevision = runGitSafe(rootDir, ["rev-parse", "HEAD"]);
|
|
45
|
+
const detached = runGitSafe(rootDir, ["symbolic-ref", "--quiet", "--short", "HEAD"]) === null;
|
|
46
|
+
const inProgressOperation = detectInProgressOperation(rootDir);
|
|
47
|
+
const stagedPaths = readPathList(rootDir, ["diff", "--name-only", "--no-renames", "--cached"]);
|
|
48
|
+
const unstagedPaths = readPathList(rootDir, ["diff", "--name-only", "--no-renames"]);
|
|
49
|
+
const untrackedPaths = readPathList(rootDir, ["ls-files", "--others", "--exclude-standard"]);
|
|
50
|
+
const committedChangedPaths = baselineRevision && headRevision && gitCommitExists(rootDir, baselineRevision)
|
|
51
|
+
? readPathList(rootDir, ["diff", "--name-only", "--no-renames", `${baselineRevision}..${headRevision}`])
|
|
52
|
+
: [];
|
|
53
|
+
const baselineBehindHead = baselineRevision && headRevision && gitCommitExists(rootDir, baselineRevision)
|
|
54
|
+
? readBehindCount(rootDir, baselineRevision, headRevision)
|
|
55
|
+
: null;
|
|
56
|
+
let degradedReason = null;
|
|
57
|
+
if (!headRevision) {
|
|
58
|
+
degradedReason = "无法解析 HEAD commit。";
|
|
59
|
+
}
|
|
60
|
+
else if (baselineRevision && !gitCommitExists(rootDir, baselineRevision)) {
|
|
61
|
+
degradedReason = `baseline.revision 不存在于当前 git 历史: ${baselineRevision}`;
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
available: true,
|
|
65
|
+
headRevision,
|
|
66
|
+
detached,
|
|
67
|
+
inProgressOperation,
|
|
68
|
+
baselineBehindHead,
|
|
69
|
+
committedChangedPaths,
|
|
70
|
+
stagedPaths,
|
|
71
|
+
unstagedPaths,
|
|
72
|
+
untrackedPaths,
|
|
73
|
+
degradedReason
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function readChangedPathsSince(rootDir, revision, headRevision) {
|
|
77
|
+
if (!gitCommitExists(rootDir, revision)) {
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
return readPathList(rootDir, ["diff", "--name-only", "--no-renames", `${revision}..${headRevision}`]);
|
|
81
|
+
}
|
|
82
|
+
export function canAdvanceRevisions(gitState) {
|
|
83
|
+
if (!gitState.available || !gitState.headRevision) {
|
|
84
|
+
return { ok: false, reason: gitState.degradedReason ?? "git 状态不可用。" };
|
|
85
|
+
}
|
|
86
|
+
if (gitState.inProgressOperation) {
|
|
87
|
+
return { ok: false, reason: `${gitState.inProgressOperation} 进行中,不推进 revision。` };
|
|
88
|
+
}
|
|
89
|
+
return { ok: true };
|
|
90
|
+
}
|
|
91
|
+
function isGitRepository(rootDir) {
|
|
92
|
+
const result = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
|
|
93
|
+
cwd: rootDir,
|
|
94
|
+
encoding: "utf8"
|
|
95
|
+
});
|
|
96
|
+
return result.status === 0 && result.stdout.trim() === "true";
|
|
97
|
+
}
|
|
98
|
+
function runGitSafe(rootDir, args) {
|
|
99
|
+
const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
|
|
100
|
+
cwd: rootDir,
|
|
101
|
+
encoding: "utf8"
|
|
102
|
+
});
|
|
103
|
+
if (result.status !== 0) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
return result.stdout.trim();
|
|
107
|
+
}
|
|
108
|
+
function readPathList(rootDir, args) {
|
|
109
|
+
const output = runGitSafe(rootDir, args);
|
|
110
|
+
if (!output) {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
return output
|
|
114
|
+
.split(/\r?\n/)
|
|
115
|
+
.map((line) => line.trim())
|
|
116
|
+
.filter(Boolean);
|
|
117
|
+
}
|
|
118
|
+
function readBehindCount(rootDir, baselineRevision, headRevision) {
|
|
119
|
+
const output = runGitSafe(rootDir, ["rev-list", "--count", `${baselineRevision}..${headRevision}`]);
|
|
120
|
+
if (!output) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const count = Number.parseInt(output, 10);
|
|
124
|
+
return Number.isNaN(count) ? null : count;
|
|
125
|
+
}
|
|
126
|
+
function detectInProgressOperation(rootDir) {
|
|
127
|
+
const gitDir = runGitSafe(rootDir, ["rev-parse", "--git-dir"]);
|
|
128
|
+
if (!gitDir) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const resolvedGitDir = path.resolve(rootDir, gitDir);
|
|
132
|
+
if (fs.existsSync(path.join(resolvedGitDir, "rebase-merge")) || fs.existsSync(path.join(resolvedGitDir, "rebase-apply"))) {
|
|
133
|
+
return "rebase";
|
|
134
|
+
}
|
|
135
|
+
if (fs.existsSync(path.join(resolvedGitDir, "MERGE_HEAD"))) {
|
|
136
|
+
return "merge";
|
|
137
|
+
}
|
|
138
|
+
if (fs.existsSync(path.join(resolvedGitDir, "CHERRY_PICK_HEAD"))) {
|
|
139
|
+
return "cherry-pick";
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
const LINK_PATTERN = /(?<!!)\[[^\]]*]\(([^)]+)\)/g;
|
|
3
|
+
const CODE_REF_PATTERN = /<CodeRef\b([\s\S]*?)\/>/g;
|
|
4
|
+
const INLINE_CODE_PATTERN = /`[^`\n]*`/g;
|
|
5
|
+
export function extractTitle(body) {
|
|
6
|
+
const match = body.match(/^#\s+(.+)$/m);
|
|
7
|
+
return match ? match[1].trim() : null;
|
|
8
|
+
}
|
|
9
|
+
export function estimateTokens(text) {
|
|
10
|
+
return Math.max(1, Math.ceil(text.length / 4));
|
|
11
|
+
}
|
|
12
|
+
export function extractLinks(body) {
|
|
13
|
+
const text = stripMarkdownLiterals(body);
|
|
14
|
+
const links = [];
|
|
15
|
+
for (const match of text.matchAll(LINK_PATTERN)) {
|
|
16
|
+
const rawTarget = match[1]?.trim();
|
|
17
|
+
if (!rawTarget) {
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (rawTarget.startsWith("http://") ||
|
|
21
|
+
rawTarget.startsWith("https://") ||
|
|
22
|
+
rawTarget.startsWith("mailto:") ||
|
|
23
|
+
rawTarget.startsWith("#")) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const targetWithoutAnchor = rawTarget.split("#")[0] ?? rawTarget;
|
|
27
|
+
const targetWithoutQuery = targetWithoutAnchor.split("?")[0] ?? targetWithoutAnchor;
|
|
28
|
+
if (targetWithoutQuery) {
|
|
29
|
+
links.push(targetWithoutQuery);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return links;
|
|
33
|
+
}
|
|
34
|
+
export function extractCodeRefs(body) {
|
|
35
|
+
const text = stripMarkdownLiterals(body);
|
|
36
|
+
const refs = [];
|
|
37
|
+
for (const match of text.matchAll(CODE_REF_PATTERN)) {
|
|
38
|
+
const attributes = parseCodeRefAttributes(match[1] ?? "");
|
|
39
|
+
const codePath = attributes.path?.trim();
|
|
40
|
+
if (!codePath) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
refs.push({
|
|
44
|
+
path: codePath,
|
|
45
|
+
symbol: attributes.symbol?.trim() || undefined
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return refs;
|
|
49
|
+
}
|
|
50
|
+
export function resolveDocLink(sourceLlmdocPath, linkTarget) {
|
|
51
|
+
const sourceDir = path.posix.dirname(sourceLlmdocPath);
|
|
52
|
+
return path.posix.normalize(path.posix.join(sourceDir, linkTarget));
|
|
53
|
+
}
|
|
54
|
+
export function stripFencedCodeBlocks(input) {
|
|
55
|
+
return input.replace(/```[\s\S]*?```/g, "").replace(/~~~[\s\S]*?~~~/g, "");
|
|
56
|
+
}
|
|
57
|
+
export function stripMarkdownLiterals(input) {
|
|
58
|
+
return stripFencedCodeBlocks(input).replace(INLINE_CODE_PATTERN, "");
|
|
59
|
+
}
|
|
60
|
+
export function validateCodeRefTags(body) {
|
|
61
|
+
const text = stripMarkdownLiterals(body);
|
|
62
|
+
const issues = [];
|
|
63
|
+
for (const match of text.matchAll(/<CodeRef\b([\s\S]*?)\/?>/g)) {
|
|
64
|
+
const raw = match[0] ?? "";
|
|
65
|
+
const attributes = match[1] ?? "";
|
|
66
|
+
if (!raw.endsWith("/>")) {
|
|
67
|
+
issues.push("CodeRef 必须使用自闭合写法 <CodeRef ... />。");
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const attrMatches = [...attributes.matchAll(/([A-Za-z]+)="([^"]*)"/g)];
|
|
71
|
+
const consumed = attrMatches.map((attr) => attr[0]).join(" ").trim();
|
|
72
|
+
const normalized = attributes.replace(/\s+/g, " ").trim().replace(/\/$/, "").trim();
|
|
73
|
+
if (normalized && consumed !== normalized) {
|
|
74
|
+
issues.push("CodeRef 仅允许双引号属性 path 和可选 symbol。");
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const names = attrMatches.map((attr) => attr[1]);
|
|
78
|
+
const duplicates = names.filter((name, index) => names.indexOf(name) !== index);
|
|
79
|
+
if (duplicates.length > 0) {
|
|
80
|
+
issues.push(`CodeRef 存在重复属性: ${[...new Set(duplicates)].join(", ")}`);
|
|
81
|
+
}
|
|
82
|
+
if (!names.includes("path")) {
|
|
83
|
+
issues.push("CodeRef 缺少必填属性 path。");
|
|
84
|
+
}
|
|
85
|
+
for (const name of names) {
|
|
86
|
+
if (name !== "path" && name !== "symbol") {
|
|
87
|
+
issues.push(`CodeRef 存在未知属性: ${name}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return [...new Set(issues)];
|
|
92
|
+
}
|
|
93
|
+
function parseCodeRefAttributes(input) {
|
|
94
|
+
const attributes = {};
|
|
95
|
+
for (const match of input.matchAll(/([A-Za-z]+)="([^"]*)"/g)) {
|
|
96
|
+
attributes[match[1]] = match[2] ?? "";
|
|
97
|
+
}
|
|
98
|
+
return attributes;
|
|
99
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import Ajv2020Module from "ajv/dist/2020.js";
|
|
4
|
+
import { CliError } from "./errors.js";
|
|
5
|
+
import { packageRootFromImport } from "./package-root.js";
|
|
6
|
+
const Ajv2020 = Ajv2020Module;
|
|
7
|
+
const ajv = new Ajv2020({ allErrors: true, strict: false });
|
|
8
|
+
const validators = new Map();
|
|
9
|
+
const schemaDocument = readOutputSchema();
|
|
10
|
+
export function assertOutputSchema(name, payload) {
|
|
11
|
+
const validator = getValidator(name);
|
|
12
|
+
const ok = validator(payload);
|
|
13
|
+
if (ok) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
throw new CliError(`内部输出契约错误(${name}): ${formatErrors(validator.errors ?? [])}`, 70);
|
|
17
|
+
}
|
|
18
|
+
export function stringifyValidatedOutput(name, payload) {
|
|
19
|
+
assertOutputSchema(name, payload);
|
|
20
|
+
return JSON.stringify(payload, null, 2);
|
|
21
|
+
}
|
|
22
|
+
export function parseAndValidateJsonString(name, input) {
|
|
23
|
+
let payload;
|
|
24
|
+
try {
|
|
25
|
+
payload = JSON.parse(input);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
throw new CliError(`内部输出契约错误(${name}): JSON 解析失败: ${error.message}`, 70);
|
|
29
|
+
}
|
|
30
|
+
return stringifyValidatedOutput(name, payload);
|
|
31
|
+
}
|
|
32
|
+
function getValidator(name) {
|
|
33
|
+
const existing = validators.get(name);
|
|
34
|
+
if (existing) {
|
|
35
|
+
return existing;
|
|
36
|
+
}
|
|
37
|
+
const defs = schemaDocument.$defs;
|
|
38
|
+
if (!defs?.[name]) {
|
|
39
|
+
throw new CliError(`内部输出契约错误: 未找到 schema ${name}`, 70);
|
|
40
|
+
}
|
|
41
|
+
const validator = ajv.compile({
|
|
42
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
43
|
+
$ref: `#/$defs/${name}`,
|
|
44
|
+
$defs: defs
|
|
45
|
+
});
|
|
46
|
+
validators.set(name, validator);
|
|
47
|
+
return validator;
|
|
48
|
+
}
|
|
49
|
+
function readOutputSchema() {
|
|
50
|
+
const packageRoot = packageRootFromImport(import.meta.url);
|
|
51
|
+
const schemaPath = path.join(packageRoot, "schemas", "output.schema.json");
|
|
52
|
+
return JSON.parse(fs.readFileSync(schemaPath, "utf8"));
|
|
53
|
+
}
|
|
54
|
+
function formatErrors(errors) {
|
|
55
|
+
return errors.map((error) => `${error.instancePath || "/"} ${error.message ?? "invalid"}`).join("; ");
|
|
56
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
export function packageRootFromImport(metaUrl) {
|
|
5
|
+
let current = path.dirname(fileURLToPath(metaUrl));
|
|
6
|
+
while (true) {
|
|
7
|
+
if (fs.existsSync(path.join(current, "package.json"))) {
|
|
8
|
+
return current;
|
|
9
|
+
}
|
|
10
|
+
const parent = path.dirname(current);
|
|
11
|
+
if (parent === current) {
|
|
12
|
+
throw new Error(`无法从 ${metaUrl} 向上定位 package root。`);
|
|
13
|
+
}
|
|
14
|
+
current = parent;
|
|
15
|
+
}
|
|
16
|
+
}
|