@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,55 @@
|
|
|
1
|
+
export function traceNodes(repository, fromQuery, toQuery, maxDepth = 6) {
|
|
2
|
+
const from = repository.resolveNode(fromQuery);
|
|
3
|
+
const to = repository.resolveNode(toQuery);
|
|
4
|
+
if (!from || !to) {
|
|
5
|
+
return {
|
|
6
|
+
from: fromQuery,
|
|
7
|
+
to: toQuery,
|
|
8
|
+
found: false,
|
|
9
|
+
steps: [],
|
|
10
|
+
message: !from ? `Start node not found: ${fromQuery}` : `End node not found: ${toQuery}`
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const queue = [{ nodeId: from.id, path: [] }];
|
|
14
|
+
const visited = new Set([from.id]);
|
|
15
|
+
while (queue.length) {
|
|
16
|
+
const current = queue.shift();
|
|
17
|
+
if (current.nodeId === to.id) {
|
|
18
|
+
return { from: from.label, to: to.label, found: true, steps: toTraceSteps(repository, from.id, current.path) };
|
|
19
|
+
}
|
|
20
|
+
if (current.path.length >= maxDepth) {
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
for (const edge of repository.edgesForNode(current.nodeId)) {
|
|
24
|
+
const nextId = edge.fromId === current.nodeId ? edge.toId : edge.fromId;
|
|
25
|
+
if (visited.has(nextId)) {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
visited.add(nextId);
|
|
29
|
+
queue.push({ nodeId: nextId, path: [...current.path, edge] });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { from: from.label, to: to.label, found: false, steps: [], message: "No path found within the trace depth budget." };
|
|
33
|
+
}
|
|
34
|
+
function toTraceSteps(repository, startId, path) {
|
|
35
|
+
const steps = [];
|
|
36
|
+
let currentId = startId;
|
|
37
|
+
for (const edge of path) {
|
|
38
|
+
const nextId = edge.fromId === currentId ? edge.toId : edge.fromId;
|
|
39
|
+
const traversalDirection = edge.fromId === currentId ? "forward" : "reverse";
|
|
40
|
+
steps.push({
|
|
41
|
+
fromId: currentId,
|
|
42
|
+
fromLabel: repository.getNode(currentId)?.label ?? currentId,
|
|
43
|
+
edgeFromId: edge.fromId,
|
|
44
|
+
edgeToId: edge.toId,
|
|
45
|
+
edgeKind: edge.kind,
|
|
46
|
+
toId: nextId,
|
|
47
|
+
toLabel: repository.getNode(nextId)?.label ?? nextId,
|
|
48
|
+
traversalDirection,
|
|
49
|
+
confidence: edge.confidence,
|
|
50
|
+
provenance: edge.provenance
|
|
51
|
+
});
|
|
52
|
+
currentId = nextId;
|
|
53
|
+
}
|
|
54
|
+
return steps;
|
|
55
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { runDoctor } from "../analysis/doctor.js";
|
|
2
|
+
import { type BenchmarkReport } from "../benchmark/benchmark.js";
|
|
3
|
+
import { type BundleVerificationResult } from "../bundle/bundle.js";
|
|
4
|
+
import { GraphRepository, type StatusCounts, type StorageDiagnostics } from "../db/repositories.js";
|
|
5
|
+
import { type GraphDiffReport } from "../diff/graph-diff.js";
|
|
6
|
+
import { type EvaluationReport } from "../evaluation/retrieval-eval.js";
|
|
7
|
+
export interface MDGraphReport {
|
|
8
|
+
projectRoot: string;
|
|
9
|
+
generatedAt: string;
|
|
10
|
+
mdgraphVersion: string;
|
|
11
|
+
indexed: boolean;
|
|
12
|
+
schema?: ReturnType<GraphRepository["schemaMetadata"]>;
|
|
13
|
+
counts?: StatusCounts;
|
|
14
|
+
storage?: StorageDiagnostics;
|
|
15
|
+
source?: {
|
|
16
|
+
sourceHash: string;
|
|
17
|
+
configHash: string;
|
|
18
|
+
documents: number;
|
|
19
|
+
documentsHash: string;
|
|
20
|
+
};
|
|
21
|
+
doctor?: {
|
|
22
|
+
summary: Awaited<ReturnType<typeof runDoctor>>["summary"];
|
|
23
|
+
warningCounts: Record<string, number>;
|
|
24
|
+
topWarnings: Array<{
|
|
25
|
+
code: string;
|
|
26
|
+
count: number;
|
|
27
|
+
}>;
|
|
28
|
+
};
|
|
29
|
+
eval?: {
|
|
30
|
+
querySet: string;
|
|
31
|
+
summary: EvaluationReport["summary"];
|
|
32
|
+
ranking: EvaluationReport["ranking"];
|
|
33
|
+
};
|
|
34
|
+
bundle?: BundleVerificationResult;
|
|
35
|
+
diff?: GraphDiffReport;
|
|
36
|
+
benchmark?: BenchmarkReport;
|
|
37
|
+
trend: {
|
|
38
|
+
state: "first_run" | "previous_report_loaded" | "previous_report_missing";
|
|
39
|
+
previousReport?: string;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export declare function generateReport(projectRoot: string, options?: {
|
|
43
|
+
eval?: boolean;
|
|
44
|
+
bundle?: string;
|
|
45
|
+
base?: string;
|
|
46
|
+
benchmark?: string;
|
|
47
|
+
previousReport?: string;
|
|
48
|
+
}): Promise<MDGraphReport>;
|
|
49
|
+
export declare function formatReport(report: MDGraphReport): string;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { runDoctor } from "../analysis/doctor.js";
|
|
4
|
+
import { formatBenchmarkReport, loadBenchmarkReport } from "../benchmark/benchmark.js";
|
|
5
|
+
import { verifyGraphBundle, sourceSnapshot } from "../bundle/bundle.js";
|
|
6
|
+
import { databasePath, loadConfig } from "../config/load-config.js";
|
|
7
|
+
import { openExistingDatabase } from "../db/connection.js";
|
|
8
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
9
|
+
import { generateGraphDiff } from "../diff/graph-diff.js";
|
|
10
|
+
import { evaluateRetrieval } from "../evaluation/retrieval-eval.js";
|
|
11
|
+
import { packageVersion } from "../version.js";
|
|
12
|
+
export async function generateReport(projectRoot, options = {}) {
|
|
13
|
+
const resolvedRoot = path.resolve(projectRoot);
|
|
14
|
+
const generatedAt = new Date().toISOString();
|
|
15
|
+
const report = {
|
|
16
|
+
projectRoot: resolvedRoot,
|
|
17
|
+
generatedAt,
|
|
18
|
+
mdgraphVersion: packageVersion(),
|
|
19
|
+
indexed: fs.existsSync(databasePath(resolvedRoot)),
|
|
20
|
+
trend: trendState(options.previousReport)
|
|
21
|
+
};
|
|
22
|
+
if (!report.indexed) {
|
|
23
|
+
if (options.bundle) {
|
|
24
|
+
report.bundle = verifyGraphBundle(options.bundle, { projectRoot: resolvedRoot });
|
|
25
|
+
}
|
|
26
|
+
if (options.benchmark) {
|
|
27
|
+
report.benchmark = loadBenchmarkReport(options.benchmark);
|
|
28
|
+
}
|
|
29
|
+
return report;
|
|
30
|
+
}
|
|
31
|
+
const config = loadConfig(resolvedRoot);
|
|
32
|
+
const repository = new GraphRepository(openExistingDatabase(resolvedRoot));
|
|
33
|
+
try {
|
|
34
|
+
report.schema = repository.schemaMetadata();
|
|
35
|
+
report.counts = repository.counts();
|
|
36
|
+
report.storage = repository.storageDiagnostics();
|
|
37
|
+
const source = sourceSnapshot(config, repository.allDocuments().map((document) => ({ path: document.path, hash: document.hash })));
|
|
38
|
+
report.source = {
|
|
39
|
+
sourceHash: source.sourceHash,
|
|
40
|
+
configHash: source.configHash,
|
|
41
|
+
documents: source.documents.length,
|
|
42
|
+
documentsHash: source.documentsHash
|
|
43
|
+
};
|
|
44
|
+
if (options.eval) {
|
|
45
|
+
const evalReport = evaluateRetrieval(repository, config);
|
|
46
|
+
report.eval = {
|
|
47
|
+
querySet: evalReport.querySet,
|
|
48
|
+
summary: evalReport.summary,
|
|
49
|
+
ranking: evalReport.ranking
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
repository.close();
|
|
55
|
+
}
|
|
56
|
+
const doctor = await runDoctor(resolvedRoot);
|
|
57
|
+
report.doctor = {
|
|
58
|
+
summary: doctor.summary,
|
|
59
|
+
warningCounts: warningCounts(doctor.warnings),
|
|
60
|
+
topWarnings: topWarningCounts(doctor.warnings)
|
|
61
|
+
};
|
|
62
|
+
if (options.bundle) {
|
|
63
|
+
report.bundle = verifyGraphBundle(options.bundle, { projectRoot: resolvedRoot });
|
|
64
|
+
}
|
|
65
|
+
if (options.base) {
|
|
66
|
+
report.diff = await generateGraphDiff(resolvedRoot, { base: options.base });
|
|
67
|
+
}
|
|
68
|
+
if (options.benchmark) {
|
|
69
|
+
report.benchmark = loadBenchmarkReport(options.benchmark);
|
|
70
|
+
}
|
|
71
|
+
return report;
|
|
72
|
+
}
|
|
73
|
+
export function formatReport(report) {
|
|
74
|
+
const lines = [
|
|
75
|
+
"MDGraph report",
|
|
76
|
+
`Project: ${report.projectRoot}`,
|
|
77
|
+
`Generated: ${report.generatedAt}`,
|
|
78
|
+
`Version: ${report.mdgraphVersion}`,
|
|
79
|
+
`Indexed: ${report.indexed}`
|
|
80
|
+
];
|
|
81
|
+
if (!report.indexed) {
|
|
82
|
+
lines.push("Run `mdgraph index` before relying on graph health or evaluation summaries.");
|
|
83
|
+
if (report.benchmark) {
|
|
84
|
+
lines.push(formatBenchmarkReport(report.benchmark));
|
|
85
|
+
}
|
|
86
|
+
lines.push(`Trend: ${report.trend.state}.`);
|
|
87
|
+
return lines.join("\n");
|
|
88
|
+
}
|
|
89
|
+
if (report.counts) {
|
|
90
|
+
lines.push(`Documents: ${report.counts.documents}, sections: ${report.counts.sections}, entities: ${report.counts.entities}, edges: ${report.counts.edges}.`);
|
|
91
|
+
}
|
|
92
|
+
if (report.schema) {
|
|
93
|
+
lines.push(`Schema: v${report.schema.schemaVersion} (${report.schema.baseline} baseline).`);
|
|
94
|
+
}
|
|
95
|
+
if (report.doctor) {
|
|
96
|
+
lines.push(`Doctor issues: ${doctorIssueCount(report.doctor.summary)}.`);
|
|
97
|
+
lines.push(`Top warnings: ${report.doctor.topWarnings.map((item) => `${item.code}=${item.count}`).join(", ") || "none"}.`);
|
|
98
|
+
}
|
|
99
|
+
if (report.eval) {
|
|
100
|
+
lines.push(`Eval ${report.eval.querySet}: ${report.eval.summary.passed}/${report.eval.summary.cases} passed, average latency ${report.eval.summary.averageLatencyMs.toFixed(1)} ms.`);
|
|
101
|
+
}
|
|
102
|
+
if (report.bundle) {
|
|
103
|
+
lines.push(`Bundle: ${report.bundle.valid ? "valid" : "invalid"} (${report.bundle.freshness.state}: ${report.bundle.freshness.reason}).`);
|
|
104
|
+
if (report.bundle.errors.length) {
|
|
105
|
+
lines.push(...report.bundle.errors.map((error) => `- ${error}`));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (report.diff) {
|
|
109
|
+
lines.push(`Diff ${report.diff.base.ref}: +${report.diff.summary.documentsAdded}, ~${report.diff.summary.documentsModified}, -${report.diff.summary.documentsDeleted}, renamed ${report.diff.summary.documentsRenamed}.`);
|
|
110
|
+
lines.push(...report.diff.impact.prSummary.map((item) => `- ${item}`));
|
|
111
|
+
}
|
|
112
|
+
if (report.benchmark) {
|
|
113
|
+
lines.push(formatBenchmarkReport(report.benchmark));
|
|
114
|
+
}
|
|
115
|
+
lines.push(`Trend: ${report.trend.state}.`);
|
|
116
|
+
return lines.join("\n");
|
|
117
|
+
}
|
|
118
|
+
function trendState(previousReport) {
|
|
119
|
+
if (!previousReport) {
|
|
120
|
+
return { state: "first_run" };
|
|
121
|
+
}
|
|
122
|
+
return fs.existsSync(previousReport)
|
|
123
|
+
? { state: "previous_report_loaded", previousReport: path.resolve(previousReport) }
|
|
124
|
+
: { state: "previous_report_missing", previousReport: path.resolve(previousReport) };
|
|
125
|
+
}
|
|
126
|
+
function warningCounts(warnings) {
|
|
127
|
+
const counts = {};
|
|
128
|
+
for (const warning of warnings) {
|
|
129
|
+
counts[warning.code] = (counts[warning.code] ?? 0) + 1;
|
|
130
|
+
}
|
|
131
|
+
return counts;
|
|
132
|
+
}
|
|
133
|
+
function topWarningCounts(warnings) {
|
|
134
|
+
return Object.entries(warningCounts(warnings))
|
|
135
|
+
.map(([code, count]) => ({ code, count }))
|
|
136
|
+
.sort((left, right) => right.count - left.count || left.code.localeCompare(right.code))
|
|
137
|
+
.slice(0, 5);
|
|
138
|
+
}
|
|
139
|
+
function doctorIssueCount(summary) {
|
|
140
|
+
return Object.entries(summary)
|
|
141
|
+
.filter(([key]) => key !== "documents")
|
|
142
|
+
.reduce((total, [, value]) => total + Number(value), 0);
|
|
143
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ParsedDocument } from "../types.js";
|
|
2
|
+
export interface ResolvedReference {
|
|
3
|
+
nodeId: string;
|
|
4
|
+
documentId: string;
|
|
5
|
+
sectionId?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class LinkResolver {
|
|
8
|
+
private readonly documentAliases;
|
|
9
|
+
private readonly ambiguousAliases;
|
|
10
|
+
private readonly sectionsByDocumentAndAnchor;
|
|
11
|
+
constructor(documents: ParsedDocument[]);
|
|
12
|
+
resolveDocumentRef(reference: string, fromDocument?: ParsedDocument, anchor?: string): ResolvedReference | undefined;
|
|
13
|
+
resolveMarkdownUrl(url: string, fromDocument: ParsedDocument): ResolvedReference | undefined;
|
|
14
|
+
private addSectionAnchor;
|
|
15
|
+
private resolveSectionAnchor;
|
|
16
|
+
private resolveAlias;
|
|
17
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { normalizePath, slugifyHeading } from "../utils/text.js";
|
|
3
|
+
export class LinkResolver {
|
|
4
|
+
documentAliases = new Map();
|
|
5
|
+
ambiguousAliases = new Set();
|
|
6
|
+
sectionsByDocumentAndAnchor = new Map();
|
|
7
|
+
constructor(documents) {
|
|
8
|
+
const aliases = new Map();
|
|
9
|
+
for (const document of documents) {
|
|
10
|
+
for (const alias of new Set(documentAliases(document))) {
|
|
11
|
+
const candidates = aliases.get(alias) ?? [];
|
|
12
|
+
candidates.push(document);
|
|
13
|
+
aliases.set(alias, candidates);
|
|
14
|
+
}
|
|
15
|
+
for (const section of document.sections) {
|
|
16
|
+
this.addSectionAnchor(document.id, section.anchor, section.id, true);
|
|
17
|
+
this.addSectionAnchor(document.id, slugifyHeading(section.heading), section.id, false);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
for (const [alias, candidates] of aliases) {
|
|
21
|
+
const uniqueCandidates = [...new Map(candidates.map((document) => [document.id, document])).values()];
|
|
22
|
+
if (uniqueCandidates.length === 1) {
|
|
23
|
+
this.documentAliases.set(alias, uniqueCandidates[0]);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
this.ambiguousAliases.add(alias);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
resolveDocumentRef(reference, fromDocument, anchor) {
|
|
31
|
+
const parsedReference = splitReferenceAnchor(reference, anchor);
|
|
32
|
+
const portableReference = normalizePath(parsedReference.reference);
|
|
33
|
+
const normalizedReference = normalizeReference(portableReference);
|
|
34
|
+
if (!normalizedReference && !(fromDocument && parsedReference.anchor)) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
const joinedReference = fromDocument && normalizedReference && isRelativeMarkdownPath(portableReference)
|
|
38
|
+
? normalizeReference(path.posix.normalize(path.posix.join(path.posix.dirname(fromDocument.relativePath), portableReference)))
|
|
39
|
+
: normalizedReference;
|
|
40
|
+
const document = joinedReference
|
|
41
|
+
? this.resolveAlias(joinedReference) ?? this.resolveAlias(stripMarkdownExtension(joinedReference))
|
|
42
|
+
: fromDocument;
|
|
43
|
+
if (!document) {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const sectionId = parsedReference.anchor ? this.resolveSectionAnchor(document.id, parsedReference.anchor) : undefined;
|
|
47
|
+
if (parsedReference.anchor && !sectionId) {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
return { nodeId: sectionId ?? document.id, documentId: document.id, sectionId };
|
|
51
|
+
}
|
|
52
|
+
resolveMarkdownUrl(url, fromDocument) {
|
|
53
|
+
if (/^(?:https?:|mailto:)/i.test(url)) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const [targetPath, rawAnchor] = url.split("#");
|
|
57
|
+
if (!targetPath && rawAnchor) {
|
|
58
|
+
const sectionId = this.resolveSectionAnchor(fromDocument.id, rawAnchor);
|
|
59
|
+
return sectionId ? { nodeId: sectionId, documentId: fromDocument.id, sectionId } : undefined;
|
|
60
|
+
}
|
|
61
|
+
return this.resolveDocumentRef(targetPath, fromDocument, rawAnchor);
|
|
62
|
+
}
|
|
63
|
+
addSectionAnchor(documentId, anchor, sectionId, canonical) {
|
|
64
|
+
const key = `${documentId}:${anchor}`;
|
|
65
|
+
if (canonical || !this.sectionsByDocumentAndAnchor.has(key)) {
|
|
66
|
+
this.sectionsByDocumentAndAnchor.set(key, sectionId);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
resolveSectionAnchor(documentId, anchor) {
|
|
70
|
+
return this.sectionsByDocumentAndAnchor.get(`${documentId}:${slugifyHeading(anchor)}`);
|
|
71
|
+
}
|
|
72
|
+
resolveAlias(alias) {
|
|
73
|
+
if (this.ambiguousAliases.has(alias)) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
return this.documentAliases.get(alias);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function documentAliases(document) {
|
|
80
|
+
const withoutExtension = stripMarkdownExtension(document.relativePath);
|
|
81
|
+
const basename = path.posix.basename(withoutExtension);
|
|
82
|
+
return [
|
|
83
|
+
document.relativePath,
|
|
84
|
+
withoutExtension,
|
|
85
|
+
basename,
|
|
86
|
+
document.frontmatter.id,
|
|
87
|
+
document.title
|
|
88
|
+
]
|
|
89
|
+
.filter((value) => Boolean(value))
|
|
90
|
+
.map(normalizeReference);
|
|
91
|
+
}
|
|
92
|
+
function normalizeReference(value) {
|
|
93
|
+
return stripMarkdownExtension(normalizePath(value).trim().replace(/^\.\//, "")).toLowerCase();
|
|
94
|
+
}
|
|
95
|
+
function splitReferenceAnchor(reference, anchor) {
|
|
96
|
+
if (anchor !== undefined) {
|
|
97
|
+
return { reference, anchor };
|
|
98
|
+
}
|
|
99
|
+
const hashIndex = reference.indexOf("#");
|
|
100
|
+
if (hashIndex < 0) {
|
|
101
|
+
return { reference };
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
reference: reference.slice(0, hashIndex),
|
|
105
|
+
anchor: reference.slice(hashIndex + 1) || undefined
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function stripMarkdownExtension(value) {
|
|
109
|
+
return value.replace(/\.(?:md|mdx)$/i, "");
|
|
110
|
+
}
|
|
111
|
+
function isRelativeMarkdownPath(value) {
|
|
112
|
+
return /^\.?\.?\//.test(value) || /\.(?:md|mdx)(?:#|$)/i.test(value);
|
|
113
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { MDGraphConfig } from "../types.js";
|
|
2
|
+
export declare function scanMarkdownFiles(projectRoot: string, config: MDGraphConfig): Promise<string[]>;
|
|
3
|
+
export declare function scanMarkdownFilesSync(projectRoot: string, config: MDGraphConfig): string[];
|
|
4
|
+
export declare function resolveIgnorePatterns(projectRoot: string, config: MDGraphConfig): Promise<string[]>;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fg from "fast-glob";
|
|
5
|
+
import { BUILT_IN_DOC_EXCLUDES } from "../config/load-config.js";
|
|
6
|
+
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
7
|
+
export async function scanMarkdownFiles(projectRoot, config) {
|
|
8
|
+
const ignore = await resolveIgnorePatterns(projectRoot, config);
|
|
9
|
+
let entries;
|
|
10
|
+
try {
|
|
11
|
+
entries = await fg(config.docs.include, {
|
|
12
|
+
cwd: projectRoot,
|
|
13
|
+
absolute: true,
|
|
14
|
+
onlyFiles: true,
|
|
15
|
+
unique: true,
|
|
16
|
+
dot: false,
|
|
17
|
+
followSymbolicLinks: false,
|
|
18
|
+
ignore
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
23
|
+
throw new Error(`Failed to scan Markdown files from ${projectRoot}: ${message}. Check docs.include and docs.exclude globs in ${path.join(projectRoot, ".mdgraph", "config.json")}.`);
|
|
24
|
+
}
|
|
25
|
+
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
26
|
+
const accepted = [];
|
|
27
|
+
for (const entry of entries.sort()) {
|
|
28
|
+
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (!allowedExtensions.some((extension) => entry.toLowerCase().endsWith(extension))) {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const stat = await safeStat(entry);
|
|
35
|
+
if (stat && stat.size <= config.index.maxFileBytes) {
|
|
36
|
+
accepted.push(entry);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return accepted;
|
|
40
|
+
}
|
|
41
|
+
export function scanMarkdownFilesSync(projectRoot, config) {
|
|
42
|
+
const ignore = resolveIgnorePatternsSync(projectRoot, config);
|
|
43
|
+
let entries;
|
|
44
|
+
try {
|
|
45
|
+
entries = fg.sync(config.docs.include, {
|
|
46
|
+
cwd: projectRoot,
|
|
47
|
+
absolute: true,
|
|
48
|
+
onlyFiles: true,
|
|
49
|
+
unique: true,
|
|
50
|
+
dot: false,
|
|
51
|
+
followSymbolicLinks: false,
|
|
52
|
+
ignore
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
57
|
+
throw new Error(`Failed to scan Markdown files from ${projectRoot}: ${message}. Check docs.include and docs.exclude globs in ${path.join(projectRoot, ".mdgraph", "config.json")}.`);
|
|
58
|
+
}
|
|
59
|
+
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
60
|
+
return entries.sort().filter((entry) => {
|
|
61
|
+
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (!allowedExtensions.some((extension) => entry.toLowerCase().endsWith(extension))) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const stat = safeStatSync(entry);
|
|
68
|
+
return Boolean(stat && stat.size <= config.index.maxFileBytes);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
export async function resolveIgnorePatterns(projectRoot, config) {
|
|
72
|
+
return uniquePatterns([
|
|
73
|
+
...BUILT_IN_DOC_EXCLUDES,
|
|
74
|
+
...config.docs.exclude,
|
|
75
|
+
...(config.index.followGitignore ? await readGitignorePatterns(projectRoot) : [])
|
|
76
|
+
]);
|
|
77
|
+
}
|
|
78
|
+
function resolveIgnorePatternsSync(projectRoot, config) {
|
|
79
|
+
return uniquePatterns([
|
|
80
|
+
...BUILT_IN_DOC_EXCLUDES,
|
|
81
|
+
...config.docs.exclude,
|
|
82
|
+
...(config.index.followGitignore ? readGitignorePatternsSync(projectRoot) : [])
|
|
83
|
+
]);
|
|
84
|
+
}
|
|
85
|
+
function uniquePatterns(patterns) {
|
|
86
|
+
return [...new Set(patterns)];
|
|
87
|
+
}
|
|
88
|
+
async function safeStat(filePath) {
|
|
89
|
+
try {
|
|
90
|
+
return await fs.stat(filePath);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function safeStatSync(filePath) {
|
|
97
|
+
try {
|
|
98
|
+
return statSync(filePath);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function readGitignorePatterns(projectRoot) {
|
|
105
|
+
const target = path.join(projectRoot, ".gitignore");
|
|
106
|
+
let content;
|
|
107
|
+
try {
|
|
108
|
+
content = await fs.readFile(target, "utf8");
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
return content
|
|
114
|
+
.split(/\r?\n/)
|
|
115
|
+
.map((line) => line.trim())
|
|
116
|
+
.filter((line) => line && !line.startsWith("#") && !line.startsWith("!"))
|
|
117
|
+
.flatMap(toFastGlobIgnorePatterns);
|
|
118
|
+
}
|
|
119
|
+
function readGitignorePatternsSync(projectRoot) {
|
|
120
|
+
const target = path.join(projectRoot, ".gitignore");
|
|
121
|
+
let content;
|
|
122
|
+
try {
|
|
123
|
+
content = readFileSync(target, "utf8");
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
return content
|
|
129
|
+
.split(/\r?\n/)
|
|
130
|
+
.map((line) => line.trim())
|
|
131
|
+
.filter((line) => line && !line.startsWith("#") && !line.startsWith("!"))
|
|
132
|
+
.flatMap(toFastGlobIgnorePatterns);
|
|
133
|
+
}
|
|
134
|
+
function toFastGlobIgnorePatterns(pattern) {
|
|
135
|
+
const normalized = pattern.replace(/\\/g, "/").replace(/^\//, "");
|
|
136
|
+
const base = normalized.replace(/\/+$/, "");
|
|
137
|
+
if (!base) {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
const directoryPattern = normalized.endsWith("/") ? `${base}/**` : base;
|
|
141
|
+
return base.includes("/")
|
|
142
|
+
? [directoryPattern]
|
|
143
|
+
: [directoryPattern, `**/${directoryPattern}`];
|
|
144
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { MDGraphConfig } from "../types.js";
|
|
2
|
+
export declare const LOCAL_EMBEDDING_PROVIDER = "local-hash";
|
|
3
|
+
export declare function supportsLocalEmbedding(config: MDGraphConfig): boolean;
|
|
4
|
+
export declare function embedTextLocal(content: string, dimensions: number): number[];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ftsQueryTokens } from "../utils/fts.js";
|
|
2
|
+
export const LOCAL_EMBEDDING_PROVIDER = "local-hash";
|
|
3
|
+
export function supportsLocalEmbedding(config) {
|
|
4
|
+
return config.embedding.enabled && config.embedding.provider === LOCAL_EMBEDDING_PROVIDER;
|
|
5
|
+
}
|
|
6
|
+
export function embedTextLocal(content, dimensions) {
|
|
7
|
+
const vector = Array.from({ length: dimensions }, () => 0);
|
|
8
|
+
const tokens = ftsQueryTokens(content);
|
|
9
|
+
for (const token of tokens) {
|
|
10
|
+
const index = positiveHash(token) % dimensions;
|
|
11
|
+
const sign = positiveHash(`sign:${token}`) % 2 === 0 ? 1 : -1;
|
|
12
|
+
vector[index] += sign * (1 + Math.log(token.length));
|
|
13
|
+
}
|
|
14
|
+
return normalizeVector(vector);
|
|
15
|
+
}
|
|
16
|
+
function positiveHash(value) {
|
|
17
|
+
let hash = 2166136261;
|
|
18
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
19
|
+
hash ^= value.charCodeAt(index);
|
|
20
|
+
hash = Math.imul(hash, 16777619);
|
|
21
|
+
}
|
|
22
|
+
return hash >>> 0;
|
|
23
|
+
}
|
|
24
|
+
function normalizeVector(vector) {
|
|
25
|
+
const magnitude = Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
|
|
26
|
+
if (magnitude === 0) {
|
|
27
|
+
return vector;
|
|
28
|
+
}
|
|
29
|
+
return vector.map((value) => Number((value / magnitude).toFixed(6)));
|
|
30
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { StorageDiagnostics, StatusCounts } from "../db/repositories.js";
|
|
2
|
+
import type { MDGraphConfig } from "../types.js";
|
|
3
|
+
export type SemanticStatusState = "disabled" | "not_indexed" | "ready" | "unsupported_provider" | "needs_reindex";
|
|
4
|
+
export interface SemanticStatusReport {
|
|
5
|
+
state: SemanticStatusState;
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
provider: string;
|
|
8
|
+
model: string;
|
|
9
|
+
dimensions: number;
|
|
10
|
+
providerSupported: boolean;
|
|
11
|
+
indexed: boolean;
|
|
12
|
+
chunks: number;
|
|
13
|
+
vectors: number;
|
|
14
|
+
vectorStorageFormat: StorageDiagnostics["vectors"]["format"];
|
|
15
|
+
indexedProviders: StorageDiagnostics["vectors"]["providers"];
|
|
16
|
+
guidance: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare const SUPPORTED_EMBEDDING_PROVIDERS: readonly ["local-hash"];
|
|
19
|
+
export declare function semanticStatusReport(config: MDGraphConfig, counts: StatusCounts | undefined, storage: StorageDiagnostics | undefined): SemanticStatusReport;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { LOCAL_EMBEDDING_PROVIDER } from "./local-embedding.js";
|
|
2
|
+
export const SUPPORTED_EMBEDDING_PROVIDERS = [LOCAL_EMBEDDING_PROVIDER];
|
|
3
|
+
export function semanticStatusReport(config, counts, storage) {
|
|
4
|
+
const providerSupported = isSupportedEmbeddingProvider(config.embedding.provider);
|
|
5
|
+
const indexed = Boolean(counts);
|
|
6
|
+
const chunks = counts?.chunks ?? 0;
|
|
7
|
+
const vectors = counts?.vectors ?? 0;
|
|
8
|
+
const indexedProviders = storage?.vectors.providers ?? [];
|
|
9
|
+
const vectorStorageFormat = storage?.vectors.format ?? "unknown";
|
|
10
|
+
const matchingProvider = indexedProviders.find((provider) => (provider.provider === config.embedding.provider
|
|
11
|
+
&& provider.model === config.embedding.model
|
|
12
|
+
&& provider.dimensions === config.embedding.dimensions));
|
|
13
|
+
const guidance = [];
|
|
14
|
+
if (!config.embedding.enabled) {
|
|
15
|
+
guidance.push("Semantic search is disabled by default; pass `search --semantic` or set embedding.enabled=true to use indexed vectors automatically.");
|
|
16
|
+
}
|
|
17
|
+
if (!indexed) {
|
|
18
|
+
guidance.push("No index is available; run `mdgraph index` before checking semantic coverage.");
|
|
19
|
+
}
|
|
20
|
+
if (!providerSupported) {
|
|
21
|
+
guidance.push(`Provider '${config.embedding.provider}' is not available in this build; semantic search degrades to FTS5 and graph search.`);
|
|
22
|
+
}
|
|
23
|
+
if (config.embedding.enabled && indexed && providerSupported && !matchingProvider) {
|
|
24
|
+
guidance.push("Run `mdgraph index --semantic` to build vectors for the configured provider/model/dimensions.");
|
|
25
|
+
}
|
|
26
|
+
if (config.embedding.enabled && indexed && vectors > 0 && vectors !== chunks) {
|
|
27
|
+
guidance.push("Vector count does not match chunk count; run `mdgraph index --full --semantic` to re-embed current chunks.");
|
|
28
|
+
}
|
|
29
|
+
if (indexed && vectorStorageFormat === "legacy_json") {
|
|
30
|
+
guidance.push("Vector storage uses legacy JSON arrays; reopen the index with this version or run `mdgraph index --full --semantic` to migrate to Float32 BLOB storage.");
|
|
31
|
+
}
|
|
32
|
+
if (indexed && vectorStorageFormat === "float32_blob") {
|
|
33
|
+
guidance.push("Vector storage uses compact Float32 BLOB rows.");
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
state: semanticState({ config, indexed, providerSupported, matchingProvider: Boolean(matchingProvider), chunks, vectors }),
|
|
37
|
+
enabled: config.embedding.enabled,
|
|
38
|
+
provider: config.embedding.provider,
|
|
39
|
+
model: config.embedding.model,
|
|
40
|
+
dimensions: config.embedding.dimensions,
|
|
41
|
+
providerSupported,
|
|
42
|
+
indexed,
|
|
43
|
+
chunks,
|
|
44
|
+
vectors,
|
|
45
|
+
vectorStorageFormat,
|
|
46
|
+
indexedProviders,
|
|
47
|
+
guidance
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function isSupportedEmbeddingProvider(provider) {
|
|
51
|
+
return SUPPORTED_EMBEDDING_PROVIDERS.includes(provider);
|
|
52
|
+
}
|
|
53
|
+
function semanticState(input) {
|
|
54
|
+
if (!input.indexed) {
|
|
55
|
+
return input.config.embedding.enabled ? "not_indexed" : "disabled";
|
|
56
|
+
}
|
|
57
|
+
if (!input.providerSupported) {
|
|
58
|
+
return "unsupported_provider";
|
|
59
|
+
}
|
|
60
|
+
if (input.matchingProvider && input.vectors === input.chunks) {
|
|
61
|
+
return "ready";
|
|
62
|
+
}
|
|
63
|
+
if (!input.config.embedding.enabled) {
|
|
64
|
+
return "disabled";
|
|
65
|
+
}
|
|
66
|
+
if (!input.matchingProvider || input.vectors !== input.chunks) {
|
|
67
|
+
return "needs_reindex";
|
|
68
|
+
}
|
|
69
|
+
return "ready";
|
|
70
|
+
}
|