@tokenroll/llmdoc 3.4.0 → 3.5.2
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 +3 -1
- package/dist/commands/commit.js +84 -6
- package/dist/commands/context.js +14 -1
- package/dist/commands/hook.js +64 -13
- package/dist/commands/serve.js +0 -0
- package/dist/commands/status.js +3 -19
- package/dist/lib/repository-health.js +26 -0
- package/dist/lib/viewer-http.js +107 -0
- package/dist/lib/viewer-state.js +131 -0
- package/dist/lib/workspace.js +39 -0
- package/package.json +1 -1
- package/schemas/output.schema.json +8 -0
package/dist/commands/commit.js
CHANGED
|
@@ -8,13 +8,23 @@ import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
|
|
|
8
8
|
export function runCommit(options) {
|
|
9
9
|
const rootDir = findProjectRoot(options.cwd);
|
|
10
10
|
const preflightWorkspace = loadWorkspace(rootDir);
|
|
11
|
+
const verifiedPaths = uniquePaths((options.verified ?? []).map((value) => (value.startsWith("llmdoc/") ? value.slice("llmdoc/".length) : value)));
|
|
12
|
+
if (options.all && verifiedPaths.length > 0) {
|
|
13
|
+
throw new CliError("commit 不能同时使用 --all 与 --verified。");
|
|
14
|
+
}
|
|
15
|
+
for (const docPath of verifiedPaths) {
|
|
16
|
+
if (!preflightWorkspace.documentsByLlmdocPath.has(docPath)) {
|
|
17
|
+
throw new CliError(`文档不存在: ${docPath}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
11
20
|
const issues = validateWorkspace(preflightWorkspace);
|
|
12
21
|
const errors = issues.filter((issue) => issue.severity === "error");
|
|
13
22
|
if (errors.length > 0) {
|
|
14
23
|
throw new CliError(`validate 未通过,拒绝提交:\n${errors.map((issue) => ` ${issue.code} (${issue.path})`).join("\n")}`);
|
|
15
24
|
}
|
|
16
25
|
const porcelain = runGit(rootDir, ["status", "--porcelain", "--", "llmdoc"]);
|
|
17
|
-
|
|
26
|
+
const hasLlmdocChanges = Boolean(porcelain.trim());
|
|
27
|
+
if (!hasLlmdocChanges && !options.all && verifiedPaths.length === 0) {
|
|
18
28
|
return options.json ? { status: "no_change", commits: [], updated: [] } : "no_change: llmdoc/ 无待提交变更";
|
|
19
29
|
}
|
|
20
30
|
const changedDocPaths = porcelain
|
|
@@ -23,22 +33,34 @@ export function runCommit(options) {
|
|
|
23
33
|
.map((line) => line.slice(3).trim())
|
|
24
34
|
.map((filePath) => (filePath.includes(" -> ") ? filePath.split(" -> ").pop() : filePath))
|
|
25
35
|
.filter((filePath) => filePath.startsWith("llmdoc/") && filePath.endsWith(".mdx"));
|
|
36
|
+
const existingChangedDocPaths = changedDocPaths
|
|
37
|
+
.map((filePath) => filePath.slice("llmdoc/".length))
|
|
38
|
+
.filter((llmdocPath) => preflightWorkspace.documentsByLlmdocPath.has(llmdocPath));
|
|
39
|
+
const targetPaths = uniquePaths([...existingChangedDocPaths, ...verifiedPaths]);
|
|
26
40
|
const verifyFlags = options.noVerify ? ["--no-verify"] : [];
|
|
27
41
|
// 在创建任何 commit 前预检 fingerprint 的全部前置条件(git 可推进、关联源码无 dirty):
|
|
28
42
|
// 预检失败时 fail-closed,工作树保持调用前状态,避免留下 docs 已提交但 meta 未刷新的半完成状态。
|
|
29
|
-
const preflightDocPaths = changedDocPaths
|
|
30
|
-
.map((filePath) => filePath.slice("llmdoc/".length))
|
|
31
|
-
.filter((llmdocPath) => preflightWorkspace.documentsByLlmdocPath.has(llmdocPath));
|
|
32
43
|
try {
|
|
33
44
|
assertRevisionAdvancePreconditions({
|
|
34
45
|
workspace: preflightWorkspace,
|
|
35
|
-
llmdocPaths:
|
|
46
|
+
llmdocPaths: targetPaths,
|
|
36
47
|
updateAll: options.all ?? false
|
|
37
48
|
});
|
|
38
49
|
}
|
|
39
50
|
catch (error) {
|
|
40
51
|
throw new CliError(`fingerprint 预检未通过,未创建任何 commit: ${error.message}`, 70);
|
|
41
52
|
}
|
|
53
|
+
if (changedDocPaths.length === 0) {
|
|
54
|
+
return commitMetaOnly({
|
|
55
|
+
rootDir,
|
|
56
|
+
workspace: preflightWorkspace,
|
|
57
|
+
verifiedPaths,
|
|
58
|
+
updateAll: options.all ?? false,
|
|
59
|
+
hasLlmdocChanges,
|
|
60
|
+
verifyFlags,
|
|
61
|
+
json: options.json ?? false
|
|
62
|
+
});
|
|
63
|
+
}
|
|
42
64
|
runGit(rootDir, ["add", "--", "llmdoc"]);
|
|
43
65
|
runGit(rootDir, ["commit", ...verifyFlags, "-m", options.message ?? "docs(llmdoc): update knowledge", "--", "llmdoc"]);
|
|
44
66
|
const docsCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
@@ -49,7 +71,7 @@ export function runCommit(options) {
|
|
|
49
71
|
.filter((llmdocPath) => workspace.documentsByLlmdocPath.has(llmdocPath));
|
|
50
72
|
const { meta, updatedPaths } = updateMetaRevisions({
|
|
51
73
|
workspace,
|
|
52
|
-
llmdocPaths: existingDocPaths,
|
|
74
|
+
llmdocPaths: uniquePaths([...existingDocPaths, ...verifiedPaths]),
|
|
53
75
|
updateAll: options.all ?? false
|
|
54
76
|
});
|
|
55
77
|
writeMeta(workspace.metaPath, meta);
|
|
@@ -69,6 +91,62 @@ export function runCommit(options) {
|
|
|
69
91
|
`fingerprints: ${updatedPaths.length} document(s)${options.all ? ", baseline advanced" : ""}`
|
|
70
92
|
].join("\n");
|
|
71
93
|
}
|
|
94
|
+
function commitMetaOnly(input) {
|
|
95
|
+
const { rootDir, workspace, verifiedPaths, updateAll, hasLlmdocChanges, verifyFlags, json } = input;
|
|
96
|
+
const headRevision = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
97
|
+
const requestedPaths = updateAll ? workspace.documents.map((document) => document.llmdocPath) : verifiedPaths;
|
|
98
|
+
const refreshNeeded = updateAll
|
|
99
|
+
? !revisionIsCurrent(rootDir, workspace.meta.baseline.revision, headRevision) ||
|
|
100
|
+
requestedPaths.some((docPath) => !revisionIsCurrent(rootDir, workspace.meta.documents[docPath]?.validatedRevision ?? null, headRevision))
|
|
101
|
+
: requestedPaths.some((docPath) => !revisionIsCurrent(rootDir, workspace.meta.documents[docPath]?.validatedRevision ?? null, headRevision));
|
|
102
|
+
if (!hasLlmdocChanges && !refreshNeeded) {
|
|
103
|
+
return json
|
|
104
|
+
? { status: "no_change", commits: [], updated: [] }
|
|
105
|
+
: "no_change: requested fingerprints are already current";
|
|
106
|
+
}
|
|
107
|
+
let updatedPaths = [];
|
|
108
|
+
if (refreshNeeded) {
|
|
109
|
+
const result = updateMetaRevisions({
|
|
110
|
+
workspace,
|
|
111
|
+
llmdocPaths: verifiedPaths,
|
|
112
|
+
updateAll
|
|
113
|
+
});
|
|
114
|
+
writeMeta(workspace.metaPath, result.meta);
|
|
115
|
+
updatedPaths = result.updatedPaths;
|
|
116
|
+
}
|
|
117
|
+
runGit(rootDir, ["add", "--", "llmdoc/meta.json"]);
|
|
118
|
+
runGit(rootDir, ["commit", ...verifyFlags, "-m", "chore(llmdoc): refresh fingerprints", "--", "llmdoc/meta.json"]);
|
|
119
|
+
const metaCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
120
|
+
if (json) {
|
|
121
|
+
return {
|
|
122
|
+
status: "success",
|
|
123
|
+
commits: [metaCommit],
|
|
124
|
+
updated: updatedPaths,
|
|
125
|
+
baselineAdvanced: updateAll
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return [
|
|
129
|
+
`committed: ${metaCommit.slice(0, 7)} (meta)`,
|
|
130
|
+
`fingerprints: ${updatedPaths.length} document(s)${updateAll ? ", baseline advanced" : ""}`
|
|
131
|
+
].join("\n");
|
|
132
|
+
}
|
|
133
|
+
// commit 自身会在 fingerprint 锚点之后创建一个只修改 meta.json 的 follow-up commit。
|
|
134
|
+
// 这种差异不代表知识又过期了,否则重复 commit 会无限追逐自己创建的 meta commit。
|
|
135
|
+
function revisionIsCurrent(rootDir, revision, headRevision) {
|
|
136
|
+
if (!revision) {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
if (revision === headRevision) {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
const changedPaths = runGit(rootDir, ["diff", "--name-only", `${revision}..${headRevision}`, "--"])
|
|
143
|
+
.split(/\r?\n/)
|
|
144
|
+
.filter(Boolean);
|
|
145
|
+
return changedPaths.every((filePath) => filePath === "llmdoc/meta.json");
|
|
146
|
+
}
|
|
147
|
+
function uniquePaths(paths) {
|
|
148
|
+
return [...new Set(paths)].sort();
|
|
149
|
+
}
|
|
72
150
|
function runGit(rootDir, args) {
|
|
73
151
|
const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], { cwd: rootDir, encoding: "utf8" });
|
|
74
152
|
if (result.status !== 0) {
|
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
|
}
|
package/dist/commands/hook.js
CHANGED
|
@@ -33,14 +33,31 @@ function runSessionStart(cwd, stdin) {
|
|
|
33
33
|
try {
|
|
34
34
|
const workspace = loadWorkspace(cwd);
|
|
35
35
|
const delta = analyzeDelta(workspace);
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
-
const parts = [`llmdoc ${lifecycle}
|
|
39
|
-
|
|
36
|
+
const signal = summarizeHookDelta(delta);
|
|
37
|
+
const pendingLessonCandidates = countPendingLessonCandidates(cwd);
|
|
38
|
+
const parts = [`llmdoc ${lifecycle}`];
|
|
39
|
+
// fingerprint/commit 正常收尾会让 HEAD 前进到仅修改 llmdoc/meta.json 的 follow-up commit。
|
|
40
|
+
// 没有可执行影响时不展示 raw baseline 落后数,避免把知识面自身更新误报成需要再次 update。
|
|
41
|
+
if (!signal.shouldUpdate) {
|
|
40
42
|
parts.push("文档无待处理影响");
|
|
43
|
+
if (pendingLessonCandidates > 0) {
|
|
44
|
+
parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
|
|
45
|
+
}
|
|
46
|
+
return parts.join("; ");
|
|
41
47
|
}
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "缺失";
|
|
49
|
+
const freshness = delta.git.baselineBehindHead === null ? "落后未知" : delta.git.baselineBehindHead === 0 ? "与 HEAD 同步" : `落后 HEAD ${delta.git.baselineBehindHead} commit`;
|
|
50
|
+
parts.push(`baseline ${baseline}(${freshness})`);
|
|
51
|
+
const summary = [
|
|
52
|
+
signal.impactedCount > 0 ? `受影响 ${signal.impactedCount} 篇` : null,
|
|
53
|
+
signal.needsReviewCount > 0 ? `待复核 ${signal.needsReviewCount} 篇` : null,
|
|
54
|
+
signal.unmappedCount > 0 ? `未映射代码路径 ${signal.unmappedCount} 个` : null
|
|
55
|
+
]
|
|
56
|
+
.filter(Boolean)
|
|
57
|
+
.join(", ");
|
|
58
|
+
parts.push(`${summary} → 建议先看 npx @tokenroll/llmdoc delta`);
|
|
59
|
+
if (pendingLessonCandidates > 0) {
|
|
60
|
+
parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
|
|
44
61
|
}
|
|
45
62
|
return parts.join("; ");
|
|
46
63
|
}
|
|
@@ -52,21 +69,29 @@ function runStop(cwd) {
|
|
|
52
69
|
try {
|
|
53
70
|
const workspace = loadWorkspace(cwd);
|
|
54
71
|
const delta = analyzeDelta(workspace);
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
if (!shouldUpdate) {
|
|
72
|
+
const signal = summarizeHookDelta(delta);
|
|
73
|
+
const pendingLessonCandidates = countPendingLessonCandidates(cwd);
|
|
74
|
+
if (!signal.shouldUpdate && pendingLessonCandidates === 0) {
|
|
58
75
|
return { continue: true };
|
|
59
76
|
}
|
|
60
77
|
const summary = [
|
|
61
|
-
|
|
62
|
-
|
|
78
|
+
signal.impactedCount > 0 ? `${signal.impactedCount} 篇文档受代码变更影响` : null,
|
|
79
|
+
signal.needsReviewCount > 0 ? `${signal.needsReviewCount} 篇文档需要复核` : null,
|
|
80
|
+
signal.unmappedCount > 0 ? `${signal.unmappedCount} 个代码路径未映射到任何文档` : null,
|
|
81
|
+
pendingLessonCandidates > 0 ? `${pendingLessonCandidates} 个反思候选待处理` : null
|
|
63
82
|
]
|
|
64
83
|
.filter(Boolean)
|
|
65
84
|
.join(", ");
|
|
66
85
|
const reasons = delta.reasons.length > 0 ? `信号: ${delta.reasons.join("; ")}` : "";
|
|
86
|
+
const updateCommand = pendingLessonCandidates > 0 ? "/llmdoc:update --reflection" : "/llmdoc:update";
|
|
87
|
+
const guidance = pendingLessonCandidates > 0
|
|
88
|
+
? signal.shouldUpdate
|
|
89
|
+
? "workflow 会读取 pending 候选;代码影响面可先用 npx @tokenroll/llmdoc delta 查看"
|
|
90
|
+
: "workflow 会读取 pending 候选"
|
|
91
|
+
: "先用 npx @tokenroll/llmdoc delta 查看影响面";
|
|
67
92
|
return {
|
|
68
93
|
continue: true,
|
|
69
|
-
systemMessage: `llmdoc: ${summary},建议运行
|
|
94
|
+
systemMessage: `llmdoc: ${summary},建议运行 ${updateCommand}(${guidance})。${reasons}`
|
|
70
95
|
};
|
|
71
96
|
}
|
|
72
97
|
catch (error) {
|
|
@@ -76,12 +101,38 @@ function runStop(cwd) {
|
|
|
76
101
|
};
|
|
77
102
|
}
|
|
78
103
|
}
|
|
104
|
+
function summarizeHookDelta(delta) {
|
|
105
|
+
const impactedCount = delta.impacts.length;
|
|
106
|
+
const needsReviewCount = delta.needsReview.length;
|
|
107
|
+
const unmappedCount = delta.unmappedCommittedPaths.length + delta.unmappedDirtyPaths.length;
|
|
108
|
+
return {
|
|
109
|
+
shouldUpdate: impactedCount > 0 || needsReviewCount > 0 || unmappedCount > 0,
|
|
110
|
+
impactedCount,
|
|
111
|
+
needsReviewCount,
|
|
112
|
+
unmappedCount
|
|
113
|
+
};
|
|
114
|
+
}
|
|
79
115
|
function runCompact() {
|
|
80
116
|
return {
|
|
81
117
|
continue: true,
|
|
82
|
-
systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
|
|
118
|
+
systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、lesson_candidates、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
|
|
83
119
|
};
|
|
84
120
|
}
|
|
121
|
+
function countPendingLessonCandidates(cwd) {
|
|
122
|
+
const pendingDir = path.join(cwd, ".llmdoc-tmp", "reflections", "pending");
|
|
123
|
+
try {
|
|
124
|
+
return fs
|
|
125
|
+
.readdirSync(pendingDir, { withFileTypes: true })
|
|
126
|
+
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md")).length;
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
const code = error.code;
|
|
130
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
85
136
|
function inferSource(stdin) {
|
|
86
137
|
const text = stdin.trim();
|
|
87
138
|
if (!text) {
|
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";
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { resolveDocLink } from "./markdown.js";
|
|
3
|
+
import { readRepositoryRevisionHealth } from "./repository-health.js";
|
|
4
|
+
import { analyzeDelta, computeGrowthState } from "./state.js";
|
|
5
|
+
import { loadWorkspace, validateWorkspace } from "./workspace.js";
|
|
6
|
+
const EDGE_PRIORITY = {
|
|
7
|
+
requires: 3,
|
|
8
|
+
related: 2,
|
|
9
|
+
link: 1
|
|
10
|
+
};
|
|
11
|
+
export function loadViewerState(rootDir, generatedAt = new Date().toISOString()) {
|
|
12
|
+
const workspace = loadWorkspace(rootDir);
|
|
13
|
+
const delta = analyzeDelta(workspace);
|
|
14
|
+
return projectViewerState({
|
|
15
|
+
workspace,
|
|
16
|
+
delta,
|
|
17
|
+
growth: computeGrowthState(workspace),
|
|
18
|
+
issues: validateWorkspace(workspace),
|
|
19
|
+
revisionHealth: readViewerRevisionHealth(workspace, delta),
|
|
20
|
+
generatedAt
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 把已读取的工作区事实投影成稳定、可序列化的 Viewer DTO。
|
|
25
|
+
* 此函数不读文件、不调用 git,便于独立验证状态优先级和 API 契约。
|
|
26
|
+
*/
|
|
27
|
+
export function projectViewerState(input) {
|
|
28
|
+
const { workspace, delta, growth, issues, revisionHealth, generatedAt } = input;
|
|
29
|
+
const impactedPaths = new Set(delta.impacts.map((impact) => impact.document.llmdocPath));
|
|
30
|
+
const dirtyPaths = new Set(delta.dirtyDocuments.map((document) => document.llmdocPath));
|
|
31
|
+
const needsReviewPaths = new Set(delta.needsReview.map((document) => document.llmdocPath));
|
|
32
|
+
const nodes = workspace.documents
|
|
33
|
+
.map((document) => {
|
|
34
|
+
const documentPath = document.llmdocPath;
|
|
35
|
+
return {
|
|
36
|
+
path: documentPath,
|
|
37
|
+
topic: document.topic,
|
|
38
|
+
title: document.title,
|
|
39
|
+
kind: normalizeDocumentKind(document.frontmatter.kind),
|
|
40
|
+
description: typeof document.frontmatter.description === "string" ? document.frontmatter.description : "",
|
|
41
|
+
estimatedTokens: document.estimatedTokens,
|
|
42
|
+
lineCount: document.lineCount,
|
|
43
|
+
codePaths: stringList(document.frontmatter.code?.paths),
|
|
44
|
+
status: dirtyPaths.has(documentPath)
|
|
45
|
+
? "dirty"
|
|
46
|
+
: impactedPaths.has(documentPath)
|
|
47
|
+
? "impacted"
|
|
48
|
+
: needsReviewPaths.has(documentPath)
|
|
49
|
+
? "needs-review"
|
|
50
|
+
: "fresh"
|
|
51
|
+
};
|
|
52
|
+
})
|
|
53
|
+
.sort((left, right) => compareText(left.path, right.path));
|
|
54
|
+
return {
|
|
55
|
+
repository: path.basename(workspace.rootDir),
|
|
56
|
+
generatedAt,
|
|
57
|
+
baseline: {
|
|
58
|
+
revision: workspace.meta?.baseline.revision ?? null,
|
|
59
|
+
headRevision: delta.git.headRevision,
|
|
60
|
+
behindHead: delta.git.baselineBehindHead,
|
|
61
|
+
relevantBehindHead: revisionHealth.relevantCommitsBehindHead,
|
|
62
|
+
metadataOnlyBehind: revisionHealth.metadataOnlyBehind,
|
|
63
|
+
degradedReason: delta.git.degradedReason
|
|
64
|
+
},
|
|
65
|
+
growth,
|
|
66
|
+
validate: {
|
|
67
|
+
ok: issues.every((issue) => issue.severity !== "error"),
|
|
68
|
+
errors: issues.filter((issue) => issue.severity === "error").length,
|
|
69
|
+
warnings: issues.filter((issue) => issue.severity === "warning").length,
|
|
70
|
+
issues: issues.map((issue) => ({ ...issue }))
|
|
71
|
+
},
|
|
72
|
+
delta: {
|
|
73
|
+
suggestedMode: delta.suggestedMode,
|
|
74
|
+
reasons: [...delta.reasons],
|
|
75
|
+
unmappedCommittedPaths: [...delta.unmappedCommittedPaths],
|
|
76
|
+
unmappedDirtyPaths: [...delta.unmappedDirtyPaths]
|
|
77
|
+
},
|
|
78
|
+
nodes,
|
|
79
|
+
edges: buildViewerEdges(workspace.documents, workspace.documentsByLlmdocPath)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* 构建有向关系图。同一有向文档对只保留最强关系,反向关系保留为独立边。
|
|
84
|
+
* Map 替换与最终排序让结果不依赖扫描和 frontmatter 中的声明顺序。
|
|
85
|
+
*/
|
|
86
|
+
export function buildViewerEdges(documents, knownDocuments) {
|
|
87
|
+
const edgesByDirection = new Map();
|
|
88
|
+
const addEdge = (from, to, type) => {
|
|
89
|
+
if (from === to || !knownDocuments.has(to)) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const key = `${from}\u0000${to}`;
|
|
93
|
+
const current = edgesByDirection.get(key);
|
|
94
|
+
if (!current || EDGE_PRIORITY[type] > EDGE_PRIORITY[current.type]) {
|
|
95
|
+
edgesByDirection.set(key, { from, to, type });
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
for (const document of documents) {
|
|
99
|
+
const from = document.llmdocPath;
|
|
100
|
+
for (const target of stringList(document.frontmatter.relations?.requires)) {
|
|
101
|
+
addEdge(from, target, "requires");
|
|
102
|
+
}
|
|
103
|
+
for (const target of stringList(document.frontmatter.relations?.related)) {
|
|
104
|
+
addEdge(from, target, "related");
|
|
105
|
+
}
|
|
106
|
+
for (const target of document.links) {
|
|
107
|
+
addEdge(from, resolveDocLink(from, target), "link");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return [...edgesByDirection.values()].sort((left, right) => compareText(left.from, right.from) || compareText(left.to, right.to) || EDGE_PRIORITY[right.type] - EDGE_PRIORITY[left.type]);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 与 status 命令一致,只把实际触碰 implementation surface 的 commit 计入知识落后。
|
|
114
|
+
* 纯 llmdoc/meta.json follow-up 会保留原始 behindHead,但 relevant 为 0。
|
|
115
|
+
*/
|
|
116
|
+
export function readViewerRevisionHealth(workspace, delta) {
|
|
117
|
+
const health = readRepositoryRevisionHealth(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta.git);
|
|
118
|
+
return {
|
|
119
|
+
relevantCommitsBehindHead: health.relevantCommitsBehindHead,
|
|
120
|
+
metadataOnlyBehind: health.metadataOnlyBehind
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function compareText(left, right) {
|
|
124
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
125
|
+
}
|
|
126
|
+
function normalizeDocumentKind(value) {
|
|
127
|
+
return value === "architecture" || value === "guide" || value === "reference" ? value : "unknown";
|
|
128
|
+
}
|
|
129
|
+
function stringList(value) {
|
|
130
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
131
|
+
}
|
package/dist/lib/workspace.js
CHANGED
|
@@ -7,6 +7,7 @@ import { estimateTokens, extractCodeRefs, extractLinks, extractTitle, resolveDoc
|
|
|
7
7
|
import { assertDocKindMatchesShape, parseDocTargetShape } from "./doc-shape.js";
|
|
8
8
|
import { normalizeRepoRelativePath, repoPath, resolveInsideRoot } from "./fs.js";
|
|
9
9
|
import { gitCommitExists, isShallowRepository } from "./git.js";
|
|
10
|
+
import { matchesCodePathPattern } from "./search.js";
|
|
10
11
|
import { validateDocFrontmatter, validateMeta } from "./schema.js";
|
|
11
12
|
export function loadWorkspace(rootDir) {
|
|
12
13
|
const configuredLlmdocDir = path.join(rootDir, "llmdoc");
|
|
@@ -297,6 +298,15 @@ export function validateWorkspace(workspace) {
|
|
|
297
298
|
message: `code.paths 指向不存在的路径: ${codePath}`
|
|
298
299
|
});
|
|
299
300
|
}
|
|
301
|
+
else if (normalized.isGlob &&
|
|
302
|
+
!globMatchesExistingFile(workspace.rootDir, normalized.absolutePath, normalized.normalized)) {
|
|
303
|
+
issues.push({
|
|
304
|
+
severity: "error",
|
|
305
|
+
code: "code.paths.unmatched",
|
|
306
|
+
path: document.repoPath,
|
|
307
|
+
message: `code.paths glob 未命中任何现有文件: ${codePath}`
|
|
308
|
+
});
|
|
309
|
+
}
|
|
300
310
|
}
|
|
301
311
|
if (document.lineCount > DOC_LINE_WARNING_LIMIT) {
|
|
302
312
|
issues.push({
|
|
@@ -432,3 +442,32 @@ function validateCodePathPattern(rootDir, input) {
|
|
|
432
442
|
return { ok: false, message: error.message };
|
|
433
443
|
}
|
|
434
444
|
}
|
|
445
|
+
function globMatchesExistingFile(rootDir, staticPrefixPath, pattern) {
|
|
446
|
+
const pending = [staticPrefixPath];
|
|
447
|
+
while (pending.length > 0) {
|
|
448
|
+
const currentPath = pending.pop();
|
|
449
|
+
const stat = fs.lstatSync(currentPath);
|
|
450
|
+
if (stat.isSymbolicLink()) {
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (stat.isFile()) {
|
|
454
|
+
if (matchesCodePathPattern(pattern, repoPath(rootDir, currentPath))) {
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (!stat.isDirectory()) {
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
for (const entry of fs.readdirSync(currentPath, { withFileTypes: true })) {
|
|
463
|
+
if (entry.isSymbolicLink()) {
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
if (entry.isDirectory() && [".git", ".llmdoc-tmp", "node_modules"].includes(entry.name)) {
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
pending.push(path.join(currentPath, entry.name));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return false;
|
|
473
|
+
}
|