@tokenroll/llmdoc 3.5.1 → 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.
@@ -1,11 +1,11 @@
1
- import { readCommitsWithChangedPathsSince } from "../lib/git.js";
2
- import { computeGrowthState, analyzeDelta, isImplementationSurfacePath, loadIgnorePatterns } from "../lib/state.js";
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 = countRelevantCommitsBehindHead(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta);
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,'&amp;').replace(/</g,'&lt;')+'</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
+ }
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenroll/llmdoc",
3
- "version": "3.5.1",
3
+ "version": "3.5.2",
4
4
  "description": "V3 runtime CLI for llmdoc repositories",
5
5
  "homepage": "https://github.com/TokenRollAI/llmdoc",
6
6
  "repository": {
@@ -425,6 +425,7 @@
425
425
  "required": [
426
426
  "impacted",
427
427
  "prerequisites",
428
+ "unmappedFiles",
428
429
  "pagination"
429
430
  ],
430
431
  "properties": {
@@ -440,6 +441,13 @@
440
441
  "$ref": "#/$defs/docRef"
441
442
  }
442
443
  },
444
+ "unmappedFiles": {
445
+ "type": "array",
446
+ "items": {
447
+ "type": "string",
448
+ "minLength": 1
449
+ }
450
+ },
443
451
  "pagination": {
444
452
  "$ref": "#/$defs/pagination"
445
453
  }