@daogee/mdgraph 1.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/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README-ZH.md +203 -0
- package/README.md +203 -0
- package/agent-pack/README.md +26 -0
- package/agent-pack/host-examples.md +71 -0
- package/agent-pack/mcp-config.example.json +14 -0
- package/agent-pack/mdgraph-agent-instructions.md +21 -0
- package/agent-pack/prompts/relationship-trace.md +12 -0
- package/agent-pack/prompts/status-doctor.md +13 -0
- package/agent-pack/prompts/task-start-context.md +15 -0
- package/dist/analysis/doctor-scope.d.ts +8 -0
- package/dist/analysis/doctor-scope.js +109 -0
- package/dist/analysis/doctor.d.ts +148 -0
- package/dist/analysis/doctor.js +919 -0
- package/dist/analysis/status-freshness.d.ts +13 -0
- package/dist/analysis/status-freshness.js +55 -0
- package/dist/benchmark/benchmark.d.ts +118 -0
- package/dist/benchmark/benchmark.js +357 -0
- package/dist/bin/mdgraph.d.ts +2 -0
- package/dist/bin/mdgraph.js +877 -0
- package/dist/bundle/bundle.d.ts +66 -0
- package/dist/bundle/bundle.js +320 -0
- package/dist/config/limits.d.ts +24 -0
- package/dist/config/limits.js +24 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +177 -0
- package/dist/db/connection.d.ts +15 -0
- package/dist/db/connection.js +145 -0
- package/dist/db/repositories.d.ts +159 -0
- package/dist/db/repositories.js +929 -0
- package/dist/db/schema.sql +110 -0
- package/dist/db/sqlite-adapter.d.ts +18 -0
- package/dist/db/sqlite-adapter.js +60 -0
- package/dist/diff/graph-diff.d.ts +41 -0
- package/dist/diff/graph-diff.js +334 -0
- package/dist/evaluation/retrieval-eval.d.ts +115 -0
- package/dist/evaluation/retrieval-eval.js +399 -0
- package/dist/export/diagram.d.ts +11 -0
- package/dist/export/diagram.js +41 -0
- package/dist/export/graphjson.d.ts +89 -0
- package/dist/export/graphjson.js +299 -0
- package/dist/export/markdown-index.d.ts +21 -0
- package/dist/export/markdown-index.js +89 -0
- package/dist/export/source-bridge.d.ts +22 -0
- package/dist/export/source-bridge.js +83 -0
- package/dist/extraction/entity-extractor.d.ts +12 -0
- package/dist/extraction/entity-extractor.js +153 -0
- package/dist/extraction/graph-builder.d.ts +2 -0
- package/dist/extraction/graph-builder.js +168 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +28 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +100 -0
- package/dist/mcp/debug.d.ts +7 -0
- package/dist/mcp/debug.js +41 -0
- package/dist/mcp/server-instructions.d.ts +2 -0
- package/dist/mcp/server-instructions.js +40 -0
- package/dist/mcp/server.d.ts +28 -0
- package/dist/mcp/server.js +232 -0
- package/dist/mcp/tools.d.ts +31 -0
- package/dist/mcp/tools.js +506 -0
- package/dist/mcp/transport.d.ts +50 -0
- package/dist/mcp/transport.js +88 -0
- package/dist/parser/frontmatter.d.ts +10 -0
- package/dist/parser/frontmatter.js +191 -0
- package/dist/parser/links.d.ts +6 -0
- package/dist/parser/links.js +9 -0
- package/dist/parser/markdown-parser.d.ts +2 -0
- package/dist/parser/markdown-parser.js +267 -0
- package/dist/query/context-builder.d.ts +85 -0
- package/dist/query/context-builder.js +413 -0
- package/dist/query/search.d.ts +32 -0
- package/dist/query/search.js +237 -0
- package/dist/query/trace.d.ts +10 -0
- package/dist/query/trace.js +55 -0
- package/dist/reporting/report.d.ts +49 -0
- package/dist/reporting/report.js +143 -0
- package/dist/resolution/link-resolver.d.ts +17 -0
- package/dist/resolution/link-resolver.js +113 -0
- package/dist/scanner/file-scanner.d.ts +4 -0
- package/dist/scanner/file-scanner.js +144 -0
- package/dist/semantic/local-embedding.d.ts +4 -0
- package/dist/semantic/local-embedding.js +30 -0
- package/dist/semantic/status.d.ts +19 -0
- package/dist/semantic/status.js +70 -0
- package/dist/semantic/vector-codec.d.ts +3 -0
- package/dist/semantic/vector-codec.js +35 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +15 -0
- package/dist/utils/bounded-json.d.ts +9 -0
- package/dist/utils/bounded-json.js +57 -0
- package/dist/utils/content-risk.d.ts +5 -0
- package/dist/utils/content-risk.js +20 -0
- package/dist/utils/fts.d.ts +3 -0
- package/dist/utils/fts.js +52 -0
- package/dist/utils/id.d.ts +2 -0
- package/dist/utils/id.js +8 -0
- package/dist/utils/path-safety.d.ts +4 -0
- package/dist/utils/path-safety.js +25 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.js +36 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +11 -0
- package/dist/watcher/file-watcher.d.ts +11 -0
- package/dist/watcher/file-watcher.js +127 -0
- package/docs/EN/Agent_Integration.md +129 -0
- package/docs/EN/Architecture.md +135 -0
- package/docs/EN/Evaluation_Questions.md +68 -0
- package/docs/EN/Output_Contracts.md +274 -0
- package/docs/EN/Public_Contracts.md +88 -0
- package/docs/EN/Public_Contracts_1.0.md +234 -0
- package/docs/EN/Release_Checklist.md +82 -0
- package/docs/ZH/Agent_Integration.md +105 -0
- package/docs/ZH/Architecture.md +124 -0
- package/docs/ZH/Evaluation_Questions.md +66 -0
- package/docs/ZH/Output_Contracts.md +269 -0
- package/docs/ZH/Public_Contracts.md +81 -0
- package/docs/ZH/Public_Contracts_1.0.md +202 -0
- package/docs/ZH/Release_Checklist.md +83 -0
- package/package.json +94 -0
|
@@ -0,0 +1,919 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { loadConfig } from "../config/load-config.js";
|
|
4
|
+
import { openDatabase } from "../db/connection.js";
|
|
5
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
6
|
+
import { parseMarkdownDocument } from "../parser/markdown-parser.js";
|
|
7
|
+
import { LinkResolver } from "../resolution/link-resolver.js";
|
|
8
|
+
import { scanMarkdownFiles } from "../scanner/file-scanner.js";
|
|
9
|
+
import { scanContentRiskLines } from "../utils/content-risk.js";
|
|
10
|
+
import { relativePathInsideRoot, resolveInsideRoot } from "../utils/path-safety.js";
|
|
11
|
+
import { normalizeEntityName, normalizePath } from "../utils/text.js";
|
|
12
|
+
export const DOCTOR_WARNING_CODES = [
|
|
13
|
+
"index.stale",
|
|
14
|
+
"link.dead",
|
|
15
|
+
"source_ref.missing",
|
|
16
|
+
"definition.missing",
|
|
17
|
+
"definition.duplicate",
|
|
18
|
+
"content.risk",
|
|
19
|
+
"document.orphan",
|
|
20
|
+
"document.deleted",
|
|
21
|
+
"document.weakly_linked",
|
|
22
|
+
"document.deprecated_referenced",
|
|
23
|
+
"document.superseded_referenced",
|
|
24
|
+
"document.parse_failed",
|
|
25
|
+
"graph.missing_decision_link",
|
|
26
|
+
"storage.generated_path_indexed",
|
|
27
|
+
"storage.database_oversized",
|
|
28
|
+
"storage.fts_shadow_large",
|
|
29
|
+
"storage.high_degree_node",
|
|
30
|
+
"storage.vector_anomaly",
|
|
31
|
+
"front_matter.invalid_yaml",
|
|
32
|
+
"front_matter.not_mapping",
|
|
33
|
+
"front_matter.unclosed",
|
|
34
|
+
"front_matter.invalid_field",
|
|
35
|
+
"tag.invalid_format",
|
|
36
|
+
"link.non_posix_path"
|
|
37
|
+
];
|
|
38
|
+
const docsThatShouldDefine = new Set(["design", "adr", "api", "runbook", "spec"]);
|
|
39
|
+
const warningSeverityRank = { error: 0, warn: 1, info: 2 };
|
|
40
|
+
const generatedPathGroups = new Set(["node_modules", "dist", "build", "coverage", ".next", ".cache", "tmp", "temp", "vendor"]);
|
|
41
|
+
const oversizedDatabaseBytes = 100 * 1024 * 1024;
|
|
42
|
+
const largeFtsShadowBytes = 50 * 1024 * 1024;
|
|
43
|
+
const highDegreeWarningThreshold = 50;
|
|
44
|
+
const tagConventionPattern = /^[a-z0-9][a-z0-9._/-]*$/;
|
|
45
|
+
export function allDoctorScope() {
|
|
46
|
+
return {
|
|
47
|
+
mode: "all",
|
|
48
|
+
changedPaths: [],
|
|
49
|
+
deletedPaths: [],
|
|
50
|
+
renamedPaths: [],
|
|
51
|
+
untrackedPaths: [],
|
|
52
|
+
globalHealthIncluded: true
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export async function runDoctor(projectRoot, options = {}) {
|
|
56
|
+
const scope = options.scope ?? allDoctorScope();
|
|
57
|
+
const config = loadConfig(projectRoot);
|
|
58
|
+
const files = await scanMarkdownFiles(projectRoot, config);
|
|
59
|
+
const { parsedDocuments, parseFailures, scannedPaths } = parseDoctorDocuments(projectRoot, files);
|
|
60
|
+
const resolver = new LinkResolver(parsedDocuments);
|
|
61
|
+
const repository = new GraphRepository(openDatabase(projectRoot, { createIfMissing: false, applySchema: options.applySchema ?? true }));
|
|
62
|
+
try {
|
|
63
|
+
const scopePaths = buildScopePathSet(scope, parsedDocuments, repository);
|
|
64
|
+
const storageHealth = storageHealthForScope(buildStorageHealth(repository.storageDiagnostics(), repository.counts().chunks), scope);
|
|
65
|
+
const staleIndex = scopedStaleIndex(detectStaleIndex(parsedDocuments, repository.documentHashes(), scannedPaths), scope, scopePaths);
|
|
66
|
+
if (staleIndex.stale) {
|
|
67
|
+
return staleDoctorReport(projectRoot, scopedDocumentCount(parsedDocuments, scope, scopePaths), staleIndex, scope, storageHealth, parseFailures);
|
|
68
|
+
}
|
|
69
|
+
const stats = repository.documentLinkStats();
|
|
70
|
+
const scopedStats = filterStatsByScope(stats, scope, scopePaths);
|
|
71
|
+
const scopedParsedDocuments = filterParsedDocumentsByScope(parsedDocuments, scope, scopePaths);
|
|
72
|
+
const orphanDocs = scopedStats
|
|
73
|
+
.filter((item) => item.nonContainmentEdges === 0)
|
|
74
|
+
.map((item) => item.document);
|
|
75
|
+
const weaklyLinkedDocs = scopedStats
|
|
76
|
+
.filter((item) => item.nonContainmentEdges > 0 && item.nonContainmentEdges < 2)
|
|
77
|
+
.map((item) => ({ document: item.document, nonContainmentEdges: item.nonContainmentEdges }));
|
|
78
|
+
const missingDefinitions = scopedStats
|
|
79
|
+
.filter(shouldRequireDefinitions)
|
|
80
|
+
.map((item) => ({ document: item.document }));
|
|
81
|
+
const deadLinks = scopedParsedDocuments.flatMap((document) => [
|
|
82
|
+
...document.markdownLinks
|
|
83
|
+
.filter((link) => isLocalDocumentLink(link.url) && !resolver.resolveMarkdownUrl(link.url, document))
|
|
84
|
+
.map((link) => ({ documentPath: document.relativePath, line: link.line, target: link.url, kind: "markdown" })),
|
|
85
|
+
...document.wikiLinks
|
|
86
|
+
.filter((link) => !resolver.resolveDocumentRef(link.target, document, link.anchor))
|
|
87
|
+
.map((link) => ({ documentPath: document.relativePath, line: link.line, target: link.raw, kind: "wikilink" }))
|
|
88
|
+
]);
|
|
89
|
+
const sourceRefDocumentPaths = sourceRefDocumentPathMap(parsedDocuments);
|
|
90
|
+
const staleSourceRefs = repository.allSourceRefs()
|
|
91
|
+
.map((sourceRef) => staleSourceRefIssue(projectRoot, sourceRef, sourceRefDocumentPaths.get(sourceRef.normalizedPath) ?? []))
|
|
92
|
+
.filter((issue) => Boolean(issue))
|
|
93
|
+
.filter((issue) => scope.mode === "all" || issue.documentPaths.some((documentPath) => pathInScope(documentPath, scope, scopePaths)));
|
|
94
|
+
const collisionStopEntities = new Set(config.entities.stopEntities.map(normalizeEntityName));
|
|
95
|
+
const possibleContradictions = repository.definitionCollisions()
|
|
96
|
+
.filter((issue) => !collisionStopEntities.has(normalizeEntityName(issue.entity.name)))
|
|
97
|
+
.filter((issue) => scope.mode === "all" || issue.documents.some((document) => pathInScope(document.path, scope, scopePaths)));
|
|
98
|
+
const contentRisks = scopedParsedDocuments.flatMap((document) => scanDocumentContentRisks(document.relativePath, document.body));
|
|
99
|
+
const frontmatterDiagnostics = scopedParsedDocuments.flatMap((document) => document.frontmatterDiagnostics
|
|
100
|
+
.map((diagnostic) => ({ documentPath: document.relativePath, diagnostic })));
|
|
101
|
+
const tagConventionIssues = scopedParsedDocuments.flatMap(detectTagConventionIssues);
|
|
102
|
+
const linkConventionIssues = scopedParsedDocuments.flatMap(detectLinkConventionIssues);
|
|
103
|
+
const lifecycleReferences = detectLifecycleReferences(parsedDocuments, resolver)
|
|
104
|
+
.filter((issue) => scope.mode === "all" || pathInScope(issue.sourceDocument.relativePath, scope, scopePaths) || pathInScope(issue.targetDocument.relativePath, scope, scopePaths));
|
|
105
|
+
const missingDecisionLinks = detectMissingDecisionLinks(scopedParsedDocuments);
|
|
106
|
+
const health = buildDoctorHealth(scopedStats, possibleContradictions, missingDefinitions, missingDecisionLinks, storageHealth);
|
|
107
|
+
const warnings = buildDoctorWarnings({
|
|
108
|
+
staleIndex,
|
|
109
|
+
orphanDocs,
|
|
110
|
+
deadLinks,
|
|
111
|
+
staleSourceRefs,
|
|
112
|
+
missingDefinitions,
|
|
113
|
+
weaklyLinkedDocs,
|
|
114
|
+
possibleContradictions,
|
|
115
|
+
contentRisks,
|
|
116
|
+
frontmatterDiagnostics,
|
|
117
|
+
tagConventionIssues,
|
|
118
|
+
linkConventionIssues,
|
|
119
|
+
lifecycleReferences,
|
|
120
|
+
missingDecisionLinks,
|
|
121
|
+
scope,
|
|
122
|
+
parseFailures,
|
|
123
|
+
storageWarnings: storageHealth.warnings
|
|
124
|
+
});
|
|
125
|
+
return {
|
|
126
|
+
projectRoot,
|
|
127
|
+
scope,
|
|
128
|
+
summary: {
|
|
129
|
+
documents: scopedStats.length,
|
|
130
|
+
orphanDocs: orphanDocs.length,
|
|
131
|
+
deadLinks: deadLinks.length,
|
|
132
|
+
staleSourceRefs: staleSourceRefs.length,
|
|
133
|
+
missingDefinitions: missingDefinitions.length,
|
|
134
|
+
weaklyLinkedDocs: weaklyLinkedDocs.length,
|
|
135
|
+
possibleContradictions: possibleContradictions.length,
|
|
136
|
+
contentRisks: contentRisks.length,
|
|
137
|
+
staleIndex: 0
|
|
138
|
+
},
|
|
139
|
+
staleIndex,
|
|
140
|
+
orphanDocs,
|
|
141
|
+
deadLinks,
|
|
142
|
+
staleSourceRefs,
|
|
143
|
+
missingDefinitions,
|
|
144
|
+
weaklyLinkedDocs,
|
|
145
|
+
possibleContradictions,
|
|
146
|
+
contentRisks,
|
|
147
|
+
frontmatterDiagnostics,
|
|
148
|
+
warnings,
|
|
149
|
+
health
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
repository.close();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function formatDoctorReport(report) {
|
|
157
|
+
const lines = [
|
|
158
|
+
"MDGraph health report",
|
|
159
|
+
`Project: ${report.projectRoot}`,
|
|
160
|
+
`Scope: ${formatDoctorScope(report.scope)}`,
|
|
161
|
+
`Documents: ${report.summary.documents}`,
|
|
162
|
+
`Orphan docs: ${report.summary.orphanDocs}`,
|
|
163
|
+
`Dead links: ${report.summary.deadLinks}`,
|
|
164
|
+
`Stale source refs: ${report.summary.staleSourceRefs}`,
|
|
165
|
+
`Missing definitions: ${report.summary.missingDefinitions}`,
|
|
166
|
+
`Weakly linked docs: ${report.summary.weaklyLinkedDocs}`,
|
|
167
|
+
`Possible contradictions: ${report.summary.possibleContradictions}`,
|
|
168
|
+
`Content risks: ${report.summary.contentRisks}`,
|
|
169
|
+
`Stale index: ${report.summary.staleIndex}`,
|
|
170
|
+
`Warnings: ${report.warnings.length}`
|
|
171
|
+
];
|
|
172
|
+
if (report.staleIndex.stale) {
|
|
173
|
+
lines.push("", "Stale index:", `- ${report.staleIndex.recommendation}`);
|
|
174
|
+
for (const issue of report.staleIndex.issues.slice(0, 25)) {
|
|
175
|
+
lines.push(`- ${issue.path}: ${issue.reason}`);
|
|
176
|
+
}
|
|
177
|
+
if (report.staleIndex.issues.length > 25) {
|
|
178
|
+
lines.push(`- ... ${report.staleIndex.issues.length - 25} more`);
|
|
179
|
+
}
|
|
180
|
+
appendWarningGroups(lines, report.warnings);
|
|
181
|
+
return lines.join("\n");
|
|
182
|
+
}
|
|
183
|
+
appendSection(lines, "Graph health: most connected docs", report.health.graph.mostConnectedDocs.map((document) => `${document.path} (${document.nonContainmentEdges} non-containment edges)`));
|
|
184
|
+
appendSection(lines, "Graph health: missing decision links", report.health.graph.missingDecisionLinks.map((document) => document.path));
|
|
185
|
+
appendSection(lines, "Storage health: path groups", report.health.storage.pathGroups.slice(0, 10).map((group) => `${group.group}: ${group.documents} docs, ${group.chunks} chunks, ${group.contentBytes} bytes`));
|
|
186
|
+
appendSection(lines, "Dead links", report.deadLinks.map((issue) => `${issue.documentPath}:${issue.line} -> ${issue.target} (${issue.kind})`));
|
|
187
|
+
appendSection(lines, "Stale source refs", report.staleSourceRefs.map((issue) => `${issue.sourceRef.path} (missing at ${issue.expectedPath})`));
|
|
188
|
+
appendSection(lines, "Missing definitions", report.missingDefinitions.map((issue) => issue.document.path));
|
|
189
|
+
appendSection(lines, "Weakly linked docs", report.weaklyLinkedDocs.map((issue) => `${issue.document.path} (${issue.nonContainmentEdges} non-containment edge)`));
|
|
190
|
+
appendSection(lines, "Possible contradictions", report.possibleContradictions.map((issue) => `${issue.entity.name}: ${issue.documents.map((document) => document.path).join(", ")}`));
|
|
191
|
+
appendSection(lines, "Content risks", report.contentRisks.map((issue) => `${issue.documentPath}:${issue.line} ${issue.reason}`));
|
|
192
|
+
appendWarningGroups(lines, report.warnings);
|
|
193
|
+
return lines.join("\n");
|
|
194
|
+
}
|
|
195
|
+
function formatDoctorScope(scope) {
|
|
196
|
+
if (scope.mode === "all") {
|
|
197
|
+
return "all";
|
|
198
|
+
}
|
|
199
|
+
const changed = scope.changedPaths.length + scope.deletedPaths.length + scope.renamedPaths.length + scope.untrackedPaths.length;
|
|
200
|
+
return scope.mode === "since"
|
|
201
|
+
? `since ${scope.baseRef ?? "unknown"} (${changed} path(s), global health included: ${scope.globalHealthIncluded})`
|
|
202
|
+
: `changed (${changed} path(s), global health included: ${scope.globalHealthIncluded})`;
|
|
203
|
+
}
|
|
204
|
+
function parseDoctorDocuments(projectRoot, files) {
|
|
205
|
+
const parsedDocuments = [];
|
|
206
|
+
const parseFailures = [];
|
|
207
|
+
const scannedPaths = new Set();
|
|
208
|
+
for (const file of files) {
|
|
209
|
+
const relativePath = relativePathInsideRoot(projectRoot, file) ?? normalizePath(path.relative(projectRoot, file));
|
|
210
|
+
scannedPaths.add(relativePath);
|
|
211
|
+
try {
|
|
212
|
+
parsedDocuments.push(parseMarkdownDocument(projectRoot, file));
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
parseFailures.push({
|
|
216
|
+
documentPath: relativePath,
|
|
217
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { parsedDocuments, parseFailures, scannedPaths };
|
|
222
|
+
}
|
|
223
|
+
function staleSourceRefIssue(projectRoot, sourceRef, documentPaths) {
|
|
224
|
+
const expectedPath = resolveInsideRoot(projectRoot, sourceRef.path);
|
|
225
|
+
if (!expectedPath) {
|
|
226
|
+
return {
|
|
227
|
+
sourceRef,
|
|
228
|
+
expectedPath: "outside project root",
|
|
229
|
+
documentPaths
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (fs.existsSync(expectedPath)) {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
return { sourceRef, expectedPath, documentPaths };
|
|
236
|
+
}
|
|
237
|
+
function detectStaleIndex(parsedDocuments, indexed, currentPaths = new Set(parsedDocuments.map((document) => document.relativePath))) {
|
|
238
|
+
const issues = [];
|
|
239
|
+
const currentByPath = new Map(parsedDocuments.map((document) => [document.relativePath, document]));
|
|
240
|
+
for (const document of parsedDocuments) {
|
|
241
|
+
const existing = indexed.get(document.relativePath);
|
|
242
|
+
if (!existing) {
|
|
243
|
+
issues.push({ path: document.relativePath, reason: "added", currentId: document.id, currentHash: document.hash });
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (existing.id !== document.id) {
|
|
247
|
+
issues.push({
|
|
248
|
+
path: document.relativePath,
|
|
249
|
+
reason: "id_changed",
|
|
250
|
+
indexedId: existing.id,
|
|
251
|
+
currentId: document.id,
|
|
252
|
+
indexedHash: existing.hash,
|
|
253
|
+
currentHash: document.hash
|
|
254
|
+
});
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (existing.hash !== document.hash) {
|
|
258
|
+
issues.push({
|
|
259
|
+
path: document.relativePath,
|
|
260
|
+
reason: "modified",
|
|
261
|
+
indexedId: existing.id,
|
|
262
|
+
currentId: document.id,
|
|
263
|
+
indexedHash: existing.hash,
|
|
264
|
+
currentHash: document.hash
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
for (const [documentPath, existing] of indexed) {
|
|
269
|
+
if (!currentPaths.has(documentPath)) {
|
|
270
|
+
issues.push({ path: documentPath, reason: "deleted", indexedId: existing.id, indexedHash: existing.hash });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const sortedIssues = issues.sort((left, right) => left.path.localeCompare(right.path) || left.reason.localeCompare(right.reason));
|
|
274
|
+
return {
|
|
275
|
+
stale: sortedIssues.length > 0,
|
|
276
|
+
recommendation: sortedIssues.length > 0
|
|
277
|
+
? "Index is stale; run `mdgraph index` before relying on doctor health conclusions."
|
|
278
|
+
: "Index is fresh.",
|
|
279
|
+
issues: sortedIssues
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function staleDoctorReport(projectRoot, documentCount, staleIndex, scope, storage, parseFailures) {
|
|
283
|
+
return {
|
|
284
|
+
projectRoot,
|
|
285
|
+
scope,
|
|
286
|
+
summary: {
|
|
287
|
+
documents: documentCount,
|
|
288
|
+
orphanDocs: 0,
|
|
289
|
+
deadLinks: 0,
|
|
290
|
+
staleSourceRefs: 0,
|
|
291
|
+
missingDefinitions: 0,
|
|
292
|
+
weaklyLinkedDocs: 0,
|
|
293
|
+
possibleContradictions: 0,
|
|
294
|
+
contentRisks: 0,
|
|
295
|
+
staleIndex: staleIndex.issues.length
|
|
296
|
+
},
|
|
297
|
+
staleIndex,
|
|
298
|
+
orphanDocs: [],
|
|
299
|
+
deadLinks: [],
|
|
300
|
+
staleSourceRefs: [],
|
|
301
|
+
missingDefinitions: [],
|
|
302
|
+
weaklyLinkedDocs: [],
|
|
303
|
+
possibleContradictions: [],
|
|
304
|
+
contentRisks: [],
|
|
305
|
+
frontmatterDiagnostics: [],
|
|
306
|
+
warnings: sortWarnings([...staleIndexWarnings(staleIndex), ...parseFailures.map(parseFailureWarning)]),
|
|
307
|
+
health: buildEmptyDoctorHealth(storage)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
function buildDoctorWarnings(input) {
|
|
311
|
+
return sortWarnings([
|
|
312
|
+
...staleIndexWarnings(input.staleIndex),
|
|
313
|
+
...input.parseFailures.map(parseFailureWarning),
|
|
314
|
+
...input.frontmatterDiagnostics.map(frontmatterDiagnosticWarning),
|
|
315
|
+
...deletedDocumentWarnings(input.scope),
|
|
316
|
+
...input.tagConventionIssues.map(tagConventionWarning),
|
|
317
|
+
...input.linkConventionIssues.map(linkConventionWarning),
|
|
318
|
+
...input.lifecycleReferences.map(lifecycleReferenceWarning),
|
|
319
|
+
...input.missingDecisionLinks.map(missingDecisionLinkWarning),
|
|
320
|
+
...input.storageWarnings.map(storageHealthWarning),
|
|
321
|
+
...input.deadLinks.map(deadLinkWarning),
|
|
322
|
+
...input.staleSourceRefs.map(staleSourceRefWarning),
|
|
323
|
+
...input.missingDefinitions.map(missingDefinitionWarning),
|
|
324
|
+
...input.possibleContradictions.map(duplicateDefinitionWarning),
|
|
325
|
+
...input.contentRisks.map(contentRiskWarning),
|
|
326
|
+
...input.orphanDocs.map(orphanDocWarning),
|
|
327
|
+
...input.weaklyLinkedDocs.map(weakLinkWarning)
|
|
328
|
+
]);
|
|
329
|
+
}
|
|
330
|
+
function deletedDocumentWarnings(scope) {
|
|
331
|
+
if (scope.mode === "all") {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
return scope.deletedPaths.map((documentPath) => ({
|
|
335
|
+
code: "document.deleted",
|
|
336
|
+
severity: "info",
|
|
337
|
+
message: `Markdown document was deleted in scoped diff: ${documentPath}`,
|
|
338
|
+
evidence: { documentPath, scope: scope.mode, baseRef: scope.baseRef },
|
|
339
|
+
affectedNodes: [{ kind: "document", path: documentPath }],
|
|
340
|
+
remediation: "If this deletion is intentional, keep it; otherwise restore the Markdown file and re-run mdgraph index. Run a full doctor check to find remaining inbound links."
|
|
341
|
+
}));
|
|
342
|
+
}
|
|
343
|
+
function tagConventionWarning(issue) {
|
|
344
|
+
return {
|
|
345
|
+
code: "tag.invalid_format",
|
|
346
|
+
severity: "info",
|
|
347
|
+
message: `Front matter tag does not use lowercase slug format in ${issue.document.relativePath}: ${issue.tag}`,
|
|
348
|
+
evidence: { documentPath: issue.document.relativePath, tag: issue.tag, expected: "lowercase slug using a-z, 0-9, dot, underscore, slash, or hyphen" },
|
|
349
|
+
affectedNodes: [parsedDocumentNode(issue.document)],
|
|
350
|
+
remediation: "Rename the tag to a lowercase slug, for example docs/governance or release-checklist."
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
function linkConventionWarning(issue) {
|
|
354
|
+
return {
|
|
355
|
+
code: "link.non_posix_path",
|
|
356
|
+
severity: "info",
|
|
357
|
+
message: `Local Markdown link should use forward slashes in ${issue.document.relativePath}`,
|
|
358
|
+
evidence: { documentPath: issue.document.relativePath, line: issue.line, target: issue.target },
|
|
359
|
+
affectedNodes: [{ kind: "document", id: issue.document.id, path: issue.document.relativePath, line: issue.line, label: issue.document.title }],
|
|
360
|
+
remediation: "Use POSIX-style / separators in Markdown links so the path is portable across platforms."
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function buildDoctorHealth(stats, duplicateDefinitions, missingDefinitions, missingDecisionLinks, storage) {
|
|
364
|
+
return {
|
|
365
|
+
graph: {
|
|
366
|
+
mostConnectedDocs: stats
|
|
367
|
+
.filter((item) => item.nonContainmentEdges > 0)
|
|
368
|
+
.sort((left, right) => right.nonContainmentEdges - left.nonContainmentEdges || left.document.path.localeCompare(right.document.path))
|
|
369
|
+
.slice(0, 10)
|
|
370
|
+
.map(documentHealthFromStats),
|
|
371
|
+
weaklyLinkedDocs: stats
|
|
372
|
+
.filter((item) => item.nonContainmentEdges > 0 && item.nonContainmentEdges < 2)
|
|
373
|
+
.map(documentHealthFromStats),
|
|
374
|
+
duplicateDefinitions: duplicateDefinitions.map((issue) => ({
|
|
375
|
+
entityName: issue.entity.name,
|
|
376
|
+
documentPaths: issue.documents.map((document) => document.path)
|
|
377
|
+
})),
|
|
378
|
+
missingDefinitions: missingDefinitions.map((issue) => documentHealth(issue.document, 0)),
|
|
379
|
+
missingDecisionLinks: missingDecisionLinks.map((issue) => parsedDocumentHealth(issue.document))
|
|
380
|
+
},
|
|
381
|
+
storage
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function buildEmptyDoctorHealth(storage) {
|
|
385
|
+
return {
|
|
386
|
+
graph: {
|
|
387
|
+
mostConnectedDocs: [],
|
|
388
|
+
weaklyLinkedDocs: [],
|
|
389
|
+
duplicateDefinitions: [],
|
|
390
|
+
missingDefinitions: [],
|
|
391
|
+
missingDecisionLinks: []
|
|
392
|
+
},
|
|
393
|
+
storage
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
function documentHealthFromStats(item) {
|
|
397
|
+
return documentHealth(item.document, item.nonContainmentEdges);
|
|
398
|
+
}
|
|
399
|
+
function documentHealth(document, nonContainmentEdges) {
|
|
400
|
+
return {
|
|
401
|
+
path: document.path,
|
|
402
|
+
title: document.title,
|
|
403
|
+
type: document.type,
|
|
404
|
+
status: document.status,
|
|
405
|
+
nonContainmentEdges
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function parsedDocumentHealth(document) {
|
|
409
|
+
return {
|
|
410
|
+
path: document.relativePath,
|
|
411
|
+
title: document.title,
|
|
412
|
+
type: document.frontmatter.type ?? "other",
|
|
413
|
+
status: documentStatus(document),
|
|
414
|
+
nonContainmentEdges: 0
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
function buildStorageHealth(storage, expectedChunks) {
|
|
418
|
+
const ftsShadowBytes = sumDefined(storage.objects.entries
|
|
419
|
+
.filter((entry) => entry.category === "fts_shadow")
|
|
420
|
+
.map((entry) => entry.bytes));
|
|
421
|
+
const base = {
|
|
422
|
+
estimatedBytes: storage.database.estimatedBytes,
|
|
423
|
+
pageCount: storage.database.pageCount,
|
|
424
|
+
freelistCount: storage.database.freelistCount,
|
|
425
|
+
journalMode: storage.database.journalMode,
|
|
426
|
+
ftsShadowBytes,
|
|
427
|
+
pathGroups: storage.pathGroups,
|
|
428
|
+
highDegreeNodes: storage.highDegreeNodes,
|
|
429
|
+
vectorSummary: { ...storage.vectors, expectedChunks },
|
|
430
|
+
warnings: []
|
|
431
|
+
};
|
|
432
|
+
return { ...base, warnings: buildStorageWarnings(base) };
|
|
433
|
+
}
|
|
434
|
+
function buildStorageWarnings(storage) {
|
|
435
|
+
return [
|
|
436
|
+
...storage.pathGroups
|
|
437
|
+
.filter((group) => generatedPathGroups.has(group.group))
|
|
438
|
+
.map((group) => ({
|
|
439
|
+
code: "storage.generated_path_indexed",
|
|
440
|
+
severity: "warn",
|
|
441
|
+
message: `Generated or dependency path group is indexed: ${group.group}`,
|
|
442
|
+
evidence: { ...group },
|
|
443
|
+
affectedNodes: [{ kind: "path_group", path: group.group }],
|
|
444
|
+
remediation: "Add this path group to docs.exclude unless these Markdown files are authored project documentation."
|
|
445
|
+
})),
|
|
446
|
+
...(storage.estimatedBytes > oversizedDatabaseBytes ? [{
|
|
447
|
+
code: "storage.database_oversized",
|
|
448
|
+
severity: "warn",
|
|
449
|
+
message: `Graph database is larger than ${oversizedDatabaseBytes} bytes.`,
|
|
450
|
+
evidence: { estimatedBytes: storage.estimatedBytes, thresholdBytes: oversizedDatabaseBytes },
|
|
451
|
+
affectedNodes: [{ kind: "database" }],
|
|
452
|
+
remediation: "Review indexed path groups and run a full reindex after excluding generated or dependency folders."
|
|
453
|
+
}] : []),
|
|
454
|
+
...(storage.ftsShadowBytes !== undefined && (storage.ftsShadowBytes > largeFtsShadowBytes || storage.ftsShadowBytes > storage.estimatedBytes * 0.6) ? [{
|
|
455
|
+
code: "storage.fts_shadow_large",
|
|
456
|
+
severity: "info",
|
|
457
|
+
message: "FTS shadow tables dominate database storage.",
|
|
458
|
+
evidence: { ftsShadowBytes: storage.ftsShadowBytes, estimatedBytes: storage.estimatedBytes },
|
|
459
|
+
affectedNodes: [{ kind: "database" }],
|
|
460
|
+
remediation: "Run a full reindex or review unusually large Markdown content if search storage keeps growing."
|
|
461
|
+
}] : []),
|
|
462
|
+
...storage.highDegreeNodes
|
|
463
|
+
.filter((node) => node.degree >= highDegreeWarningThreshold)
|
|
464
|
+
.map((node) => ({
|
|
465
|
+
code: "storage.high_degree_node",
|
|
466
|
+
severity: "info",
|
|
467
|
+
message: `High-degree graph node: ${node.label}`,
|
|
468
|
+
evidence: { ...node },
|
|
469
|
+
affectedNodes: [{ kind: node.kind, id: node.id, label: node.label }],
|
|
470
|
+
remediation: "Review whether this node is a broad utility concept that should be scoped, renamed, or ignored."
|
|
471
|
+
})),
|
|
472
|
+
...(storage.vectorSummary.total > 0 && storage.vectorSummary.total !== storage.vectorSummary.expectedChunks ? [{
|
|
473
|
+
code: "storage.vector_anomaly",
|
|
474
|
+
severity: "warn",
|
|
475
|
+
message: "Chunk vector count does not match indexed chunk count.",
|
|
476
|
+
evidence: { vectors: storage.vectorSummary.total, expectedChunks: storage.vectorSummary.expectedChunks },
|
|
477
|
+
affectedNodes: [{ kind: "database" }],
|
|
478
|
+
remediation: "Run a full semantic reindex so vector rows match current chunks."
|
|
479
|
+
}] : [])
|
|
480
|
+
];
|
|
481
|
+
}
|
|
482
|
+
function storageHealthForScope(storage, scope) {
|
|
483
|
+
return scope.globalHealthIncluded ? storage : { ...storage, warnings: [] };
|
|
484
|
+
}
|
|
485
|
+
function sumDefined(values) {
|
|
486
|
+
const defined = values.filter((value) => typeof value === "number");
|
|
487
|
+
return defined.length ? defined.reduce((total, value) => total + value, 0) : undefined;
|
|
488
|
+
}
|
|
489
|
+
function lifecycleReferenceWarning(issue) {
|
|
490
|
+
const supersededBy = issue.supersededBy?.length ? ` Superseded by: ${issue.supersededBy.join(", ")}.` : "";
|
|
491
|
+
return {
|
|
492
|
+
code: issue.code,
|
|
493
|
+
severity: "warn",
|
|
494
|
+
message: `Active document ${issue.sourceDocument.relativePath} references ${issue.targetDocument.relativePath}.${supersededBy}`,
|
|
495
|
+
evidence: {
|
|
496
|
+
sourceDocumentPath: issue.sourceDocument.relativePath,
|
|
497
|
+
targetDocumentPath: issue.targetDocument.relativePath,
|
|
498
|
+
target: issue.target,
|
|
499
|
+
line: issue.line,
|
|
500
|
+
supersededBy: issue.supersededBy
|
|
501
|
+
},
|
|
502
|
+
affectedNodes: [
|
|
503
|
+
parsedDocumentNode(issue.sourceDocument, issue.line),
|
|
504
|
+
parsedDocumentNode(issue.targetDocument)
|
|
505
|
+
],
|
|
506
|
+
remediation: issue.code === "document.deprecated_referenced"
|
|
507
|
+
? "Update the link to an active replacement document or remove the deprecated reference."
|
|
508
|
+
: "Update the link to the superseding document or mark the target document status appropriately."
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
function missingDecisionLinkWarning(issue) {
|
|
512
|
+
return {
|
|
513
|
+
code: "graph.missing_decision_link",
|
|
514
|
+
severity: "info",
|
|
515
|
+
message: `Decision document has no explicit graph relationship links: ${issue.document.relativePath}`,
|
|
516
|
+
evidence: { documentPath: issue.document.relativePath, documentType: issue.document.frontmatter.type ?? "other" },
|
|
517
|
+
affectedNodes: [parsedDocumentNode(issue.document)],
|
|
518
|
+
remediation: "Add depends_on, supersedes, deprecated_by, a Markdown link, or a WikiLink to connect this decision to related docs."
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
function storageHealthWarning(issue) {
|
|
522
|
+
return {
|
|
523
|
+
code: issue.code,
|
|
524
|
+
severity: issue.severity,
|
|
525
|
+
message: issue.message,
|
|
526
|
+
evidence: issue.evidence,
|
|
527
|
+
affectedNodes: issue.affectedNodes,
|
|
528
|
+
remediation: issue.remediation
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
function frontmatterDiagnosticWarning(issue) {
|
|
532
|
+
return {
|
|
533
|
+
code: issue.diagnostic.code,
|
|
534
|
+
severity: "warn",
|
|
535
|
+
message: `Front matter diagnostic in ${issue.documentPath}: ${issue.diagnostic.message}`,
|
|
536
|
+
evidence: {
|
|
537
|
+
documentPath: issue.documentPath,
|
|
538
|
+
line: issue.diagnostic.line,
|
|
539
|
+
field: issue.diagnostic.field,
|
|
540
|
+
expected: issue.diagnostic.expected,
|
|
541
|
+
actual: issue.diagnostic.actual
|
|
542
|
+
},
|
|
543
|
+
affectedNodes: [{ kind: "document", path: issue.documentPath, line: issue.diagnostic.line }],
|
|
544
|
+
remediation: frontmatterRemediation(issue.diagnostic)
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function parseFailureWarning(issue) {
|
|
548
|
+
return {
|
|
549
|
+
code: "document.parse_failed",
|
|
550
|
+
severity: "error",
|
|
551
|
+
message: `Markdown document could not be parsed: ${issue.documentPath}`,
|
|
552
|
+
evidence: { documentPath: issue.documentPath, reason: issue.reason },
|
|
553
|
+
affectedNodes: [{ kind: "document", path: issue.documentPath }],
|
|
554
|
+
remediation: "Reduce extreme Markdown nesting/size or fix malformed content, then re-run mdgraph index and doctor."
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function frontmatterRemediation(diagnostic) {
|
|
558
|
+
if (diagnostic.code === "front_matter.invalid_field") {
|
|
559
|
+
return "Use the documented MDGraph front matter field shape, or move project-specific metadata to a custom field name.";
|
|
560
|
+
}
|
|
561
|
+
if (diagnostic.code === "front_matter.unclosed") {
|
|
562
|
+
return "Close the YAML front matter block with a standalone --- delimiter, or remove the opening delimiter.";
|
|
563
|
+
}
|
|
564
|
+
return "Fix the YAML front matter so it parses as a mapping, or remove the front matter block.";
|
|
565
|
+
}
|
|
566
|
+
function staleIndexWarnings(staleIndex) {
|
|
567
|
+
return sortWarnings(staleIndex.issues.map((issue) => ({
|
|
568
|
+
code: "index.stale",
|
|
569
|
+
severity: "error",
|
|
570
|
+
message: `Indexed document is ${issue.reason}: ${issue.path}`,
|
|
571
|
+
evidence: {
|
|
572
|
+
path: issue.path,
|
|
573
|
+
reason: issue.reason,
|
|
574
|
+
indexedId: issue.indexedId,
|
|
575
|
+
currentId: issue.currentId,
|
|
576
|
+
indexedHash: issue.indexedHash,
|
|
577
|
+
currentHash: issue.currentHash
|
|
578
|
+
},
|
|
579
|
+
affectedNodes: [{ kind: "document", path: issue.path }],
|
|
580
|
+
remediation: staleIndex.recommendation
|
|
581
|
+
})));
|
|
582
|
+
}
|
|
583
|
+
function deadLinkWarning(issue) {
|
|
584
|
+
return {
|
|
585
|
+
code: "link.dead",
|
|
586
|
+
severity: "error",
|
|
587
|
+
message: `Dead ${issue.kind} link in ${issue.documentPath}`,
|
|
588
|
+
evidence: { target: issue.target, kind: issue.kind, documentPath: issue.documentPath, line: issue.line },
|
|
589
|
+
affectedNodes: [{ kind: "document", path: issue.documentPath, line: issue.line }],
|
|
590
|
+
remediation: "Update the link target or create the referenced Markdown document."
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
function staleSourceRefWarning(issue) {
|
|
594
|
+
return {
|
|
595
|
+
code: "source_ref.missing",
|
|
596
|
+
severity: "error",
|
|
597
|
+
message: `Source reference does not exist: ${issue.sourceRef.path}`,
|
|
598
|
+
evidence: { sourcePath: issue.sourceRef.path, expectedPath: issue.expectedPath },
|
|
599
|
+
affectedNodes: [{ kind: "source_ref", id: issue.sourceRef.id, path: issue.sourceRef.path }],
|
|
600
|
+
remediation: "Create the referenced source path, or update/remove the source_refs or implements front matter entry."
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
function missingDefinitionWarning(issue) {
|
|
604
|
+
return {
|
|
605
|
+
code: "definition.missing",
|
|
606
|
+
severity: "warn",
|
|
607
|
+
message: `Document has no definition edges: ${issue.document.path}`,
|
|
608
|
+
evidence: { documentPath: issue.document.path, documentType: issue.document.type },
|
|
609
|
+
affectedNodes: [documentNode(issue.document)],
|
|
610
|
+
remediation: "Add a defines front matter entry or high-confidence definition heading, or change the document type."
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
function duplicateDefinitionWarning(issue) {
|
|
614
|
+
return {
|
|
615
|
+
code: "definition.duplicate",
|
|
616
|
+
severity: "warn",
|
|
617
|
+
message: `Definition appears in multiple active documents: ${issue.entity.name}`,
|
|
618
|
+
evidence: { entityName: issue.entity.name, documentPaths: issue.documents.map((document) => document.path) },
|
|
619
|
+
affectedNodes: [
|
|
620
|
+
{ kind: "entity", id: issue.entity.id, label: issue.entity.name },
|
|
621
|
+
...issue.documents.map(documentNode)
|
|
622
|
+
],
|
|
623
|
+
remediation: "Keep one authoritative definition, or rename/scope the duplicated entity definitions."
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function contentRiskWarning(issue) {
|
|
627
|
+
return {
|
|
628
|
+
code: "content.risk",
|
|
629
|
+
severity: "warn",
|
|
630
|
+
message: `Potentially risky document content in ${issue.documentPath}`,
|
|
631
|
+
evidence: { reason: issue.reason, documentPath: issue.documentPath, line: issue.line },
|
|
632
|
+
affectedNodes: [{ kind: "document", path: issue.documentPath, line: issue.line }],
|
|
633
|
+
remediation: "Review the content and remove or isolate prompt-injection text, active HTML, data URIs, or hidden characters."
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
function orphanDocWarning(document) {
|
|
637
|
+
return {
|
|
638
|
+
code: "document.orphan",
|
|
639
|
+
severity: "info",
|
|
640
|
+
message: `Document has no non-containment graph edges: ${document.path}`,
|
|
641
|
+
evidence: { documentPath: document.path, nonContainmentEdges: 0 },
|
|
642
|
+
affectedNodes: [documentNode(document)],
|
|
643
|
+
remediation: "Link this document from related docs, add source_refs, or add explicit front matter relationships."
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
function weakLinkWarning(issue) {
|
|
647
|
+
return {
|
|
648
|
+
code: "document.weakly_linked",
|
|
649
|
+
severity: "info",
|
|
650
|
+
message: `Document has few non-containment graph edges: ${issue.document.path}`,
|
|
651
|
+
evidence: { documentPath: issue.document.path, nonContainmentEdges: issue.nonContainmentEdges },
|
|
652
|
+
affectedNodes: [documentNode(issue.document)],
|
|
653
|
+
remediation: "Add links, source_refs, or front matter relationships when this document should participate in the graph."
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function documentNode(document) {
|
|
657
|
+
return { kind: "document", id: document.id, path: document.path, label: document.title };
|
|
658
|
+
}
|
|
659
|
+
function parsedDocumentNode(document, line) {
|
|
660
|
+
return { kind: "document", id: document.id, path: document.relativePath, line, label: document.title };
|
|
661
|
+
}
|
|
662
|
+
function detectLifecycleReferences(documents, resolver) {
|
|
663
|
+
const documentById = new Map(documents.map((document) => [document.id, document]));
|
|
664
|
+
const superseded = supersededDocuments(documents, resolver, documentById);
|
|
665
|
+
const issues = [];
|
|
666
|
+
for (const document of documents) {
|
|
667
|
+
if (!isActiveDocument(document)) {
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
const references = [
|
|
671
|
+
...document.markdownLinks.map((link) => ({
|
|
672
|
+
line: link.line,
|
|
673
|
+
target: link.url,
|
|
674
|
+
resolved: resolver.resolveMarkdownUrl(link.url, document)
|
|
675
|
+
})),
|
|
676
|
+
...document.wikiLinks.map((link) => ({
|
|
677
|
+
line: link.line,
|
|
678
|
+
target: link.raw,
|
|
679
|
+
resolved: resolver.resolveDocumentRef(link.target, document, link.anchor)
|
|
680
|
+
}))
|
|
681
|
+
];
|
|
682
|
+
for (const reference of references) {
|
|
683
|
+
const targetDocument = reference.resolved ? documentById.get(reference.resolved.documentId) : undefined;
|
|
684
|
+
if (!targetDocument || targetDocument.id === document.id) {
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (documentStatus(targetDocument) === "deprecated") {
|
|
688
|
+
issues.push({
|
|
689
|
+
code: "document.deprecated_referenced",
|
|
690
|
+
sourceDocument: document,
|
|
691
|
+
targetDocument,
|
|
692
|
+
line: reference.line,
|
|
693
|
+
target: reference.target
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
if (superseded.ids.has(targetDocument.id)) {
|
|
697
|
+
issues.push({
|
|
698
|
+
code: "document.superseded_referenced",
|
|
699
|
+
sourceDocument: document,
|
|
700
|
+
targetDocument,
|
|
701
|
+
line: reference.line,
|
|
702
|
+
target: reference.target,
|
|
703
|
+
supersededBy: superseded.supersededBy.get(targetDocument.id)
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return issues;
|
|
709
|
+
}
|
|
710
|
+
function supersededDocuments(documents, resolver, documentById) {
|
|
711
|
+
const ids = new Set();
|
|
712
|
+
const supersededBy = new Map();
|
|
713
|
+
for (const document of documents) {
|
|
714
|
+
if (documentStatus(document) === "superseded" || document.frontmatter.deprecated_by?.length) {
|
|
715
|
+
ids.add(document.id);
|
|
716
|
+
}
|
|
717
|
+
for (const reference of document.frontmatter.deprecated_by ?? []) {
|
|
718
|
+
const resolved = resolver.resolveDocumentRef(reference, document);
|
|
719
|
+
const replacementDocument = resolved ? documentById.get(resolved.documentId) : undefined;
|
|
720
|
+
if (replacementDocument && replacementDocument.id !== document.id) {
|
|
721
|
+
addSupersedingDocument(supersededBy, document.id, replacementDocument.relativePath);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (!isActiveDocument(document)) {
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
for (const reference of document.frontmatter.supersedes ?? []) {
|
|
728
|
+
const resolved = resolver.resolveDocumentRef(reference, document);
|
|
729
|
+
const targetDocument = resolved ? documentById.get(resolved.documentId) : undefined;
|
|
730
|
+
if (!targetDocument || targetDocument.id === document.id) {
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
ids.add(targetDocument.id);
|
|
734
|
+
addSupersedingDocument(supersededBy, targetDocument.id, document.relativePath);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return { ids, supersededBy };
|
|
738
|
+
}
|
|
739
|
+
function addSupersedingDocument(supersededBy, targetDocumentId, replacementPath) {
|
|
740
|
+
const existing = supersededBy.get(targetDocumentId) ?? [];
|
|
741
|
+
supersededBy.set(targetDocumentId, [...new Set([...existing, replacementPath])].sort());
|
|
742
|
+
}
|
|
743
|
+
function detectMissingDecisionLinks(documents) {
|
|
744
|
+
return documents
|
|
745
|
+
.filter((document) => document.frontmatter.type === "adr" && isActiveDocument(document))
|
|
746
|
+
.filter((document) => !hasDecisionRelationship(document))
|
|
747
|
+
.map((document) => ({ document }));
|
|
748
|
+
}
|
|
749
|
+
function detectTagConventionIssues(document) {
|
|
750
|
+
return [...new Set(document.frontmatter.tags ?? [])]
|
|
751
|
+
.filter((tag) => !tagConventionPattern.test(tag))
|
|
752
|
+
.map((tag) => ({ document, tag }));
|
|
753
|
+
}
|
|
754
|
+
function detectLinkConventionIssues(document) {
|
|
755
|
+
return document.markdownLinks
|
|
756
|
+
.filter((link) => isLocalDocumentLink(link.url) && link.url.includes("\\"))
|
|
757
|
+
.map((link) => ({ document, line: link.line, target: link.url }));
|
|
758
|
+
}
|
|
759
|
+
function hasDecisionRelationship(document) {
|
|
760
|
+
return Boolean(document.frontmatter.depends_on?.length
|
|
761
|
+
|| document.frontmatter.supersedes?.length
|
|
762
|
+
|| document.frontmatter.deprecated_by?.length
|
|
763
|
+
|| document.markdownLinks.some((link) => isLocalDocumentLink(link.url))
|
|
764
|
+
|| document.wikiLinks.length);
|
|
765
|
+
}
|
|
766
|
+
function scopedStaleIndex(staleIndex, scope, scopePaths) {
|
|
767
|
+
if (scope.mode === "all") {
|
|
768
|
+
return staleIndex;
|
|
769
|
+
}
|
|
770
|
+
const issues = staleIndex.issues.filter((issue) => pathInScope(issue.path, scope, scopePaths));
|
|
771
|
+
return {
|
|
772
|
+
stale: issues.length > 0,
|
|
773
|
+
recommendation: issues.length > 0
|
|
774
|
+
? "Scoped index is stale; run `mdgraph index` before relying on scoped doctor results."
|
|
775
|
+
: "Scoped index is fresh.",
|
|
776
|
+
issues
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
function filterStatsByScope(stats, scope, scopePaths) {
|
|
780
|
+
return scope.mode === "all" ? stats : stats.filter((item) => pathInScope(item.document.path, scope, scopePaths));
|
|
781
|
+
}
|
|
782
|
+
function filterParsedDocumentsByScope(documents, scope, scopePaths) {
|
|
783
|
+
return scope.mode === "all" ? documents : documents.filter((document) => pathInScope(document.relativePath, scope, scopePaths));
|
|
784
|
+
}
|
|
785
|
+
function scopedDocumentCount(documents, scope, scopePaths) {
|
|
786
|
+
return filterParsedDocumentsByScope(documents, scope, scopePaths).length;
|
|
787
|
+
}
|
|
788
|
+
function pathInScope(documentPath, scope, scopePaths) {
|
|
789
|
+
if (scope.mode === "all") {
|
|
790
|
+
return true;
|
|
791
|
+
}
|
|
792
|
+
return scopePaths.has(normalizePath(documentPath));
|
|
793
|
+
}
|
|
794
|
+
function buildScopePathSet(scope, documents, repository) {
|
|
795
|
+
const paths = baseScopePathSet(scope);
|
|
796
|
+
if (scope.mode === "all") {
|
|
797
|
+
return paths;
|
|
798
|
+
}
|
|
799
|
+
const documentsByPath = new Map(documents.map((document) => [normalizePath(document.relativePath), document]));
|
|
800
|
+
for (const documentPath of [...paths]) {
|
|
801
|
+
const document = documentsByPath.get(documentPath);
|
|
802
|
+
if (document) {
|
|
803
|
+
for (const relatedPath of relatedDocumentPaths(document, repository)) {
|
|
804
|
+
paths.add(relatedPath);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return paths;
|
|
809
|
+
}
|
|
810
|
+
function baseScopePathSet(scope) {
|
|
811
|
+
return new Set([
|
|
812
|
+
...scope.changedPaths,
|
|
813
|
+
...scope.deletedPaths,
|
|
814
|
+
...scope.untrackedPaths,
|
|
815
|
+
...scope.renamedPaths.flatMap((rename) => [rename.from, rename.to])
|
|
816
|
+
].map(normalizePath));
|
|
817
|
+
}
|
|
818
|
+
function relatedDocumentPaths(document, repository) {
|
|
819
|
+
const nodeIds = [document.id, ...document.sections.map((section) => section.id)];
|
|
820
|
+
const paths = nodeIds.flatMap((nodeId) => repository.edgesForNode(nodeId)
|
|
821
|
+
.flatMap((edge) => [documentPathForNode(edge.fromId, repository), documentPathForNode(edge.toId, repository)]));
|
|
822
|
+
return [...new Set(paths.filter((value) => Boolean(value)).map(normalizePath))].sort();
|
|
823
|
+
}
|
|
824
|
+
function documentPathForNode(nodeId, repository) {
|
|
825
|
+
const node = repository.getNode(nodeId);
|
|
826
|
+
if (!node) {
|
|
827
|
+
return undefined;
|
|
828
|
+
}
|
|
829
|
+
const data = node.data;
|
|
830
|
+
if (node.kind === "document" && typeof data.path === "string") {
|
|
831
|
+
return data.path;
|
|
832
|
+
}
|
|
833
|
+
if ((node.kind === "section" || node.kind === "chunk") && typeof data.documentId === "string") {
|
|
834
|
+
const documentNode = repository.getNode(data.documentId);
|
|
835
|
+
const documentData = documentNode?.data;
|
|
836
|
+
return documentNode?.kind === "document" && typeof documentData?.path === "string" ? documentData.path : undefined;
|
|
837
|
+
}
|
|
838
|
+
return undefined;
|
|
839
|
+
}
|
|
840
|
+
function sourceRefDocumentPathMap(documents) {
|
|
841
|
+
const bySourceRef = new Map();
|
|
842
|
+
for (const document of documents) {
|
|
843
|
+
for (const sourcePath of [...(document.frontmatter.implements ?? []), ...(document.frontmatter.source_refs ?? [])]) {
|
|
844
|
+
const key = normalizePath(sourcePath.trim()).toLowerCase();
|
|
845
|
+
if (!key) {
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
const existing = bySourceRef.get(key) ?? [];
|
|
849
|
+
bySourceRef.set(key, [...new Set([...existing, document.relativePath])].sort());
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
return bySourceRef;
|
|
853
|
+
}
|
|
854
|
+
function isActiveDocument(document) {
|
|
855
|
+
return documentStatus(document) === "active";
|
|
856
|
+
}
|
|
857
|
+
function documentStatus(document) {
|
|
858
|
+
return (document.frontmatter.status ?? "active").trim().toLowerCase();
|
|
859
|
+
}
|
|
860
|
+
function sortWarnings(warnings) {
|
|
861
|
+
return [...warnings].sort((left, right) => warningSortKey(left).localeCompare(warningSortKey(right)));
|
|
862
|
+
}
|
|
863
|
+
function warningSortKey(warning) {
|
|
864
|
+
const node = warning.affectedNodes[0];
|
|
865
|
+
return [
|
|
866
|
+
warningSeverityRank[warning.severity],
|
|
867
|
+
warning.code,
|
|
868
|
+
node?.path ?? node?.label ?? node?.id ?? "",
|
|
869
|
+
node?.line ?? 0,
|
|
870
|
+
warning.message
|
|
871
|
+
].join("|");
|
|
872
|
+
}
|
|
873
|
+
function shouldRequireDefinitions(item) {
|
|
874
|
+
return docsThatShouldDefine.has(item.document.type) && item.definitionEdges === 0;
|
|
875
|
+
}
|
|
876
|
+
function isLocalDocumentLink(url) {
|
|
877
|
+
return !/^(?:https?:|mailto:|#)/i.test(url) && /(?:\.mdx?|#)/i.test(url);
|
|
878
|
+
}
|
|
879
|
+
function scanDocumentContentRisks(documentPath, content) {
|
|
880
|
+
return scanContentRiskLines(content).map((risk) => ({ documentPath, ...risk }));
|
|
881
|
+
}
|
|
882
|
+
function appendSection(lines, title, items) {
|
|
883
|
+
if (!items.length) {
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
lines.push("", `${title}:`);
|
|
887
|
+
for (const item of items.slice(0, 25)) {
|
|
888
|
+
lines.push(`- ${item}`);
|
|
889
|
+
}
|
|
890
|
+
if (items.length > 25) {
|
|
891
|
+
lines.push(`- ... ${items.length - 25} more`);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
function appendWarningGroups(lines, warnings) {
|
|
895
|
+
if (!warnings.length) {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
lines.push("", "Warnings by severity/code:");
|
|
899
|
+
const groups = new Map();
|
|
900
|
+
for (const warning of warnings) {
|
|
901
|
+
const key = `${warning.severity}:${warning.code}`;
|
|
902
|
+
groups.set(key, [...groups.get(key) ?? [], warning]);
|
|
903
|
+
}
|
|
904
|
+
const sortedGroups = [...groups.entries()].sort(([leftKey], [rightKey]) => {
|
|
905
|
+
const [leftSeverity, leftCode] = leftKey.split(":", 2);
|
|
906
|
+
const [rightSeverity, rightCode] = rightKey.split(":", 2);
|
|
907
|
+
return warningSeverityRank[leftSeverity] - warningSeverityRank[rightSeverity] || leftCode.localeCompare(rightCode);
|
|
908
|
+
});
|
|
909
|
+
for (const [key, groupWarnings] of sortedGroups) {
|
|
910
|
+
const [severity, code] = key.split(":", 2);
|
|
911
|
+
lines.push(`${severity.toUpperCase()} ${code} (${groupWarnings.length}):`);
|
|
912
|
+
for (const warning of groupWarnings.slice(0, 25)) {
|
|
913
|
+
lines.push(`- ${warning.message}`);
|
|
914
|
+
}
|
|
915
|
+
if (groupWarnings.length > 25) {
|
|
916
|
+
lines.push(`- ... ${groupWarnings.length - 25} more`);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|