@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.
Files changed (121) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README-ZH.md +203 -0
  4. package/README.md +203 -0
  5. package/agent-pack/README.md +26 -0
  6. package/agent-pack/host-examples.md +71 -0
  7. package/agent-pack/mcp-config.example.json +14 -0
  8. package/agent-pack/mdgraph-agent-instructions.md +21 -0
  9. package/agent-pack/prompts/relationship-trace.md +12 -0
  10. package/agent-pack/prompts/status-doctor.md +13 -0
  11. package/agent-pack/prompts/task-start-context.md +15 -0
  12. package/dist/analysis/doctor-scope.d.ts +8 -0
  13. package/dist/analysis/doctor-scope.js +109 -0
  14. package/dist/analysis/doctor.d.ts +148 -0
  15. package/dist/analysis/doctor.js +919 -0
  16. package/dist/analysis/status-freshness.d.ts +13 -0
  17. package/dist/analysis/status-freshness.js +55 -0
  18. package/dist/benchmark/benchmark.d.ts +118 -0
  19. package/dist/benchmark/benchmark.js +357 -0
  20. package/dist/bin/mdgraph.d.ts +2 -0
  21. package/dist/bin/mdgraph.js +877 -0
  22. package/dist/bundle/bundle.d.ts +66 -0
  23. package/dist/bundle/bundle.js +320 -0
  24. package/dist/config/limits.d.ts +24 -0
  25. package/dist/config/limits.js +24 -0
  26. package/dist/config/load-config.d.ts +14 -0
  27. package/dist/config/load-config.js +177 -0
  28. package/dist/db/connection.d.ts +15 -0
  29. package/dist/db/connection.js +145 -0
  30. package/dist/db/repositories.d.ts +159 -0
  31. package/dist/db/repositories.js +929 -0
  32. package/dist/db/schema.sql +110 -0
  33. package/dist/db/sqlite-adapter.d.ts +18 -0
  34. package/dist/db/sqlite-adapter.js +60 -0
  35. package/dist/diff/graph-diff.d.ts +41 -0
  36. package/dist/diff/graph-diff.js +334 -0
  37. package/dist/evaluation/retrieval-eval.d.ts +115 -0
  38. package/dist/evaluation/retrieval-eval.js +399 -0
  39. package/dist/export/diagram.d.ts +11 -0
  40. package/dist/export/diagram.js +41 -0
  41. package/dist/export/graphjson.d.ts +89 -0
  42. package/dist/export/graphjson.js +299 -0
  43. package/dist/export/markdown-index.d.ts +21 -0
  44. package/dist/export/markdown-index.js +89 -0
  45. package/dist/export/source-bridge.d.ts +22 -0
  46. package/dist/export/source-bridge.js +83 -0
  47. package/dist/extraction/entity-extractor.d.ts +12 -0
  48. package/dist/extraction/entity-extractor.js +153 -0
  49. package/dist/extraction/graph-builder.d.ts +2 -0
  50. package/dist/extraction/graph-builder.js +168 -0
  51. package/dist/index.d.ts +28 -0
  52. package/dist/index.js +28 -0
  53. package/dist/indexer.d.ts +19 -0
  54. package/dist/indexer.js +100 -0
  55. package/dist/mcp/debug.d.ts +7 -0
  56. package/dist/mcp/debug.js +41 -0
  57. package/dist/mcp/server-instructions.d.ts +2 -0
  58. package/dist/mcp/server-instructions.js +40 -0
  59. package/dist/mcp/server.d.ts +28 -0
  60. package/dist/mcp/server.js +232 -0
  61. package/dist/mcp/tools.d.ts +31 -0
  62. package/dist/mcp/tools.js +506 -0
  63. package/dist/mcp/transport.d.ts +50 -0
  64. package/dist/mcp/transport.js +88 -0
  65. package/dist/parser/frontmatter.d.ts +10 -0
  66. package/dist/parser/frontmatter.js +191 -0
  67. package/dist/parser/links.d.ts +6 -0
  68. package/dist/parser/links.js +9 -0
  69. package/dist/parser/markdown-parser.d.ts +2 -0
  70. package/dist/parser/markdown-parser.js +267 -0
  71. package/dist/query/context-builder.d.ts +85 -0
  72. package/dist/query/context-builder.js +413 -0
  73. package/dist/query/search.d.ts +32 -0
  74. package/dist/query/search.js +237 -0
  75. package/dist/query/trace.d.ts +10 -0
  76. package/dist/query/trace.js +55 -0
  77. package/dist/reporting/report.d.ts +49 -0
  78. package/dist/reporting/report.js +143 -0
  79. package/dist/resolution/link-resolver.d.ts +17 -0
  80. package/dist/resolution/link-resolver.js +113 -0
  81. package/dist/scanner/file-scanner.d.ts +4 -0
  82. package/dist/scanner/file-scanner.js +144 -0
  83. package/dist/semantic/local-embedding.d.ts +4 -0
  84. package/dist/semantic/local-embedding.js +30 -0
  85. package/dist/semantic/status.d.ts +19 -0
  86. package/dist/semantic/status.js +70 -0
  87. package/dist/semantic/vector-codec.d.ts +3 -0
  88. package/dist/semantic/vector-codec.js +35 -0
  89. package/dist/types.d.ts +198 -0
  90. package/dist/types.js +15 -0
  91. package/dist/utils/bounded-json.d.ts +9 -0
  92. package/dist/utils/bounded-json.js +57 -0
  93. package/dist/utils/content-risk.d.ts +5 -0
  94. package/dist/utils/content-risk.js +20 -0
  95. package/dist/utils/fts.d.ts +3 -0
  96. package/dist/utils/fts.js +52 -0
  97. package/dist/utils/id.d.ts +2 -0
  98. package/dist/utils/id.js +8 -0
  99. package/dist/utils/path-safety.d.ts +4 -0
  100. package/dist/utils/path-safety.js +25 -0
  101. package/dist/utils/text.d.ts +7 -0
  102. package/dist/utils/text.js +36 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +11 -0
  105. package/dist/watcher/file-watcher.d.ts +11 -0
  106. package/dist/watcher/file-watcher.js +127 -0
  107. package/docs/EN/Agent_Integration.md +129 -0
  108. package/docs/EN/Architecture.md +135 -0
  109. package/docs/EN/Evaluation_Questions.md +68 -0
  110. package/docs/EN/Output_Contracts.md +274 -0
  111. package/docs/EN/Public_Contracts.md +88 -0
  112. package/docs/EN/Public_Contracts_1.0.md +234 -0
  113. package/docs/EN/Release_Checklist.md +82 -0
  114. package/docs/ZH/Agent_Integration.md +105 -0
  115. package/docs/ZH/Architecture.md +124 -0
  116. package/docs/ZH/Evaluation_Questions.md +66 -0
  117. package/docs/ZH/Output_Contracts.md +269 -0
  118. package/docs/ZH/Public_Contracts.md +81 -0
  119. package/docs/ZH/Public_Contracts_1.0.md +202 -0
  120. package/docs/ZH/Release_Checklist.md +83 -0
  121. package/package.json +94 -0
@@ -0,0 +1,110 @@
1
+ PRAGMA journal_mode = WAL;
2
+ PRAGMA foreign_keys = ON;
3
+
4
+ CREATE TABLE IF NOT EXISTS schema_metadata (
5
+ key TEXT PRIMARY KEY,
6
+ value TEXT NOT NULL
7
+ );
8
+
9
+ CREATE TABLE IF NOT EXISTS schema_migrations (
10
+ id TEXT PRIMARY KEY,
11
+ from_version INTEGER NOT NULL,
12
+ to_version INTEGER NOT NULL,
13
+ applied_at TEXT NOT NULL,
14
+ mdgraph_version TEXT NOT NULL
15
+ );
16
+
17
+ CREATE TABLE IF NOT EXISTS documents (
18
+ id TEXT PRIMARY KEY,
19
+ path TEXT NOT NULL UNIQUE,
20
+ title TEXT NOT NULL,
21
+ type TEXT NOT NULL,
22
+ status TEXT NOT NULL,
23
+ hash TEXT NOT NULL,
24
+ trust_tier TEXT NOT NULL DEFAULT 'authored',
25
+ updated_at TEXT,
26
+ indexed_at TEXT NOT NULL,
27
+ metadata_json TEXT
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS sections (
31
+ id TEXT PRIMARY KEY,
32
+ document_id TEXT NOT NULL,
33
+ anchor TEXT NOT NULL,
34
+ heading TEXT NOT NULL,
35
+ level INTEGER NOT NULL,
36
+ start_line INTEGER NOT NULL,
37
+ end_line INTEGER NOT NULL,
38
+ content TEXT NOT NULL,
39
+ FOREIGN KEY(document_id) REFERENCES documents(id) ON DELETE CASCADE
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS entities (
43
+ id TEXT PRIMARY KEY,
44
+ name TEXT NOT NULL,
45
+ normalized_name TEXT NOT NULL,
46
+ kind TEXT NOT NULL,
47
+ namespace TEXT,
48
+ created_at TEXT NOT NULL,
49
+ metadata_json TEXT,
50
+ UNIQUE(normalized_name, kind)
51
+ );
52
+
53
+ CREATE TABLE IF NOT EXISTS source_refs (
54
+ id TEXT PRIMARY KEY,
55
+ path TEXT NOT NULL UNIQUE,
56
+ normalized_path TEXT NOT NULL,
57
+ created_at TEXT NOT NULL,
58
+ metadata_json TEXT
59
+ );
60
+
61
+ CREATE TABLE IF NOT EXISTS edges (
62
+ id TEXT PRIMARY KEY,
63
+ from_id TEXT NOT NULL,
64
+ to_id TEXT NOT NULL,
65
+ kind TEXT NOT NULL,
66
+ weight REAL NOT NULL,
67
+ confidence REAL NOT NULL,
68
+ provenance TEXT NOT NULL,
69
+ metadata_json TEXT,
70
+ created_at TEXT NOT NULL,
71
+ UNIQUE(from_id, to_id, kind, provenance)
72
+ );
73
+
74
+ CREATE TABLE IF NOT EXISTS chunks (
75
+ id TEXT PRIMARY KEY,
76
+ document_id TEXT NOT NULL,
77
+ section_id TEXT,
78
+ content TEXT NOT NULL,
79
+ token_estimate INTEGER NOT NULL,
80
+ metadata_json TEXT,
81
+ FOREIGN KEY(document_id) REFERENCES documents(id) ON DELETE CASCADE,
82
+ FOREIGN KEY(section_id) REFERENCES sections(id) ON DELETE CASCADE
83
+ );
84
+
85
+ CREATE TABLE IF NOT EXISTS chunk_vectors (
86
+ chunk_id TEXT PRIMARY KEY,
87
+ provider TEXT NOT NULL,
88
+ model TEXT NOT NULL,
89
+ dimensions INTEGER NOT NULL,
90
+ vector_blob BLOB NOT NULL,
91
+ created_at TEXT NOT NULL,
92
+ FOREIGN KEY(chunk_id) REFERENCES chunks(id) ON DELETE CASCADE
93
+ );
94
+
95
+ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
96
+ content,
97
+ content = 'chunks',
98
+ content_rowid = 'rowid',
99
+ detail = none,
100
+ tokenize = 'unicode61'
101
+ );
102
+
103
+ CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path);
104
+ CREATE INDEX IF NOT EXISTS idx_sections_document ON sections(document_id);
105
+ CREATE INDEX IF NOT EXISTS idx_entities_normalized ON entities(normalized_name);
106
+ CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id);
107
+ CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id);
108
+ CREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);
109
+ CREATE INDEX IF NOT EXISTS idx_chunks_document ON chunks(document_id);
110
+ CREATE INDEX IF NOT EXISTS idx_chunk_vectors_provider ON chunk_vectors(provider, model);
@@ -0,0 +1,18 @@
1
+ export interface SqliteStatement {
2
+ run(...params: unknown[]): {
3
+ changes: number;
4
+ lastInsertRowid: number | bigint;
5
+ };
6
+ get(...params: unknown[]): unknown;
7
+ all(...params: unknown[]): unknown[];
8
+ }
9
+ export interface SqliteDatabase {
10
+ prepare(sql: string): SqliteStatement;
11
+ exec(sql: string): void;
12
+ pragma(str: string, options?: {
13
+ simple?: boolean;
14
+ }): unknown;
15
+ transaction<T>(fn: (...args: unknown[]) => T): (...args: unknown[]) => T;
16
+ close(): void;
17
+ }
18
+ export declare function createDatabase(dbPath: string): SqliteDatabase;
@@ -0,0 +1,60 @@
1
+ import { createRequire } from "node:module";
2
+ class NodeSqliteAdapter {
3
+ db;
4
+ constructor(dbPath) {
5
+ const require = createRequire(import.meta.url);
6
+ const { DatabaseSync } = require("node:sqlite");
7
+ this.db = new DatabaseSync(dbPath);
8
+ }
9
+ prepare(sql) {
10
+ const statement = this.db.prepare(sql);
11
+ return {
12
+ run: (...params) => {
13
+ const result = statement.run(...params);
14
+ return {
15
+ changes: Number(result?.changes ?? 0),
16
+ lastInsertRowid: result?.lastInsertRowid ?? 0
17
+ };
18
+ },
19
+ get: (...params) => statement.get(...params),
20
+ all: (...params) => statement.all(...params)
21
+ };
22
+ }
23
+ exec(sql) {
24
+ this.db.exec(sql);
25
+ }
26
+ pragma(str, options) {
27
+ const trimmed = str.trim();
28
+ if (trimmed.includes("=")) {
29
+ this.db.exec(`PRAGMA ${trimmed}`);
30
+ return undefined;
31
+ }
32
+ const row = this.db.prepare(`PRAGMA ${trimmed}`).get();
33
+ if (options?.simple && row && typeof row === "object") {
34
+ return Object.values(row)[0];
35
+ }
36
+ return row;
37
+ }
38
+ transaction(fn) {
39
+ return (...args) => {
40
+ this.db.exec("BEGIN");
41
+ try {
42
+ const result = fn(...args);
43
+ this.db.exec("COMMIT");
44
+ return result;
45
+ }
46
+ catch (error) {
47
+ this.db.exec("ROLLBACK");
48
+ throw error;
49
+ }
50
+ };
51
+ }
52
+ close() {
53
+ if (this.db.isOpen) {
54
+ this.db.close();
55
+ }
56
+ }
57
+ }
58
+ export function createDatabase(dbPath) {
59
+ return new NodeSqliteAdapter(dbPath);
60
+ }
@@ -0,0 +1,41 @@
1
+ export interface GraphDiffReport {
2
+ mode: "base_ref";
3
+ base: {
4
+ ref: string;
5
+ revision: string;
6
+ sourceHash?: string;
7
+ };
8
+ head: {
9
+ sourceHash: string;
10
+ };
11
+ summary: {
12
+ documentsAdded: number;
13
+ documentsModified: number;
14
+ documentsDeleted: number;
15
+ documentsRenamed: number;
16
+ sectionsChanged: number;
17
+ sourceRefsChanged: number;
18
+ edgesChanged: number;
19
+ warningDelta: Record<string, number>;
20
+ };
21
+ documents: GraphDiffDocument[];
22
+ impact: {
23
+ changedSourceRefs: string[];
24
+ affectedDocs: string[];
25
+ prSummary: string[];
26
+ };
27
+ }
28
+ export interface GraphDiffDocument {
29
+ path: string;
30
+ previousPath?: string;
31
+ change: "added" | "modified" | "deleted" | "renamed";
32
+ hashChanged: boolean;
33
+ statusChanged?: boolean;
34
+ sectionDelta?: number;
35
+ sourceRefDelta?: number;
36
+ warningCodes?: string[];
37
+ }
38
+ export declare function generateGraphDiff(projectRoot: string, options: {
39
+ base: string;
40
+ }): Promise<GraphDiffReport>;
41
+ export declare function formatGraphDiff(report: GraphDiffReport): string;
@@ -0,0 +1,334 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { runDoctor } from "../analysis/doctor.js";
6
+ import { sourceSnapshot } from "../bundle/bundle.js";
7
+ import { configPath, loadConfig } from "../config/load-config.js";
8
+ import { openDatabase } from "../db/connection.js";
9
+ import { GraphRepository } from "../db/repositories.js";
10
+ import { indexProject } from "../indexer.js";
11
+ import { normalizePath } from "../utils/text.js";
12
+ export async function generateGraphDiff(projectRoot, options) {
13
+ const resolvedRoot = path.resolve(projectRoot);
14
+ const baseRevision = resolveBaseRevision(resolvedRoot, options.base);
15
+ const baseRoot = createBaseSnapshot(resolvedRoot, baseRevision);
16
+ try {
17
+ await indexProject(baseRoot, { full: true });
18
+ const baseSnapshot = await graphSnapshot(baseRoot);
19
+ const headSnapshot = await graphSnapshot(resolvedRoot);
20
+ const documents = diffDocuments(baseSnapshot, headSnapshot, gitRenames(resolvedRoot, baseRevision));
21
+ const warningDelta = countDelta(baseSnapshot.warningCounts, headSnapshot.warningCounts);
22
+ const changedSourceRefs = setSymmetricDifference(baseSnapshot.sourceRefs, headSnapshot.sourceRefs);
23
+ const affectedDocs = affectedDocumentPaths(documents, baseSnapshot, headSnapshot);
24
+ const report = {
25
+ mode: "base_ref",
26
+ base: {
27
+ ref: options.base,
28
+ revision: baseRevision,
29
+ sourceHash: baseSnapshot.sourceHash
30
+ },
31
+ head: {
32
+ sourceHash: headSnapshot.sourceHash
33
+ },
34
+ summary: {
35
+ documentsAdded: documents.filter((document) => document.change === "added").length,
36
+ documentsModified: documents.filter((document) => document.change === "modified").length,
37
+ documentsDeleted: documents.filter((document) => document.change === "deleted").length,
38
+ documentsRenamed: documents.filter((document) => document.change === "renamed").length,
39
+ sectionsChanged: headSnapshot.counts.sections - baseSnapshot.counts.sections,
40
+ sourceRefsChanged: headSnapshot.counts.sourceRefs - baseSnapshot.counts.sourceRefs,
41
+ edgesChanged: headSnapshot.counts.edges - baseSnapshot.counts.edges,
42
+ warningDelta
43
+ },
44
+ documents,
45
+ impact: {
46
+ changedSourceRefs,
47
+ affectedDocs,
48
+ prSummary: []
49
+ }
50
+ };
51
+ report.impact.prSummary = prSummary(report);
52
+ return report;
53
+ }
54
+ finally {
55
+ fs.rmSync(baseRoot, { recursive: true, force: true });
56
+ }
57
+ }
58
+ export function formatGraphDiff(report) {
59
+ const lines = [
60
+ "MDGraph diff",
61
+ `Base: ${report.base.ref} (${report.base.revision})`,
62
+ `Head source hash: ${report.head.sourceHash}`,
63
+ `Documents: +${report.summary.documentsAdded}, ~${report.summary.documentsModified}, -${report.summary.documentsDeleted}, renamed ${report.summary.documentsRenamed}`,
64
+ `Graph deltas: sections ${formatSigned(report.summary.sectionsChanged)}, source refs ${formatSigned(report.summary.sourceRefsChanged)}, edges ${formatSigned(report.summary.edgesChanged)}`
65
+ ];
66
+ const warningDelta = Object.entries(report.summary.warningDelta).map(([code, delta]) => `${code} ${formatSigned(delta)}`);
67
+ lines.push(`Warning delta: ${warningDelta.join(", ") || "none"}`);
68
+ if (report.impact.changedSourceRefs.length) {
69
+ lines.push("Changed source refs:", ...report.impact.changedSourceRefs.map((sourceRef) => `- ${sourceRef}`));
70
+ }
71
+ if (report.documents.length) {
72
+ lines.push("Changed documents:", ...report.documents.slice(0, 25).map(formatDiffDocument));
73
+ if (report.documents.length > 25) {
74
+ lines.push(`- ... ${report.documents.length - 25} more`);
75
+ }
76
+ }
77
+ if (report.impact.prSummary.length) {
78
+ lines.push("PR summary:", ...report.impact.prSummary.map((item) => `- ${item}`));
79
+ }
80
+ return lines.join("\n");
81
+ }
82
+ async function graphSnapshot(projectRoot) {
83
+ const config = loadConfig(projectRoot);
84
+ const repository = new GraphRepository(openDatabase(projectRoot, { createIfMissing: false, applySchema: false }));
85
+ try {
86
+ const documents = repository.allDocuments();
87
+ const sections = repository.allSections();
88
+ const sourceRefs = repository.allSourceRefs();
89
+ const edges = repository.allEdges();
90
+ const source = sourceSnapshot(config, documents.map((document) => ({ path: document.path, hash: document.hash })));
91
+ const doctor = await runDoctor(projectRoot, { applySchema: false });
92
+ return {
93
+ sourceHash: source.sourceHash,
94
+ counts: repository.counts(),
95
+ documents: new Map(documents.map((document) => [document.path, document])),
96
+ sectionCounts: sectionCountsByDocument(documents, sections),
97
+ sourceRefCounts: sourceRefCountsByDocument(documents, sourceRefs, edges),
98
+ sourceRefs: new Set(sourceRefs.map((sourceRef) => sourceRef.path)),
99
+ warningCounts: warningCounts(doctor),
100
+ warningCodesByDocument: warningCodesByDocument(doctor.warnings)
101
+ };
102
+ }
103
+ finally {
104
+ repository.close();
105
+ }
106
+ }
107
+ function diffDocuments(base, head, renames) {
108
+ const documents = [];
109
+ const consumedBase = new Set();
110
+ const consumedHead = new Set();
111
+ for (const [previousPath, nextPath] of renames) {
112
+ const previous = base.documents.get(previousPath);
113
+ const next = head.documents.get(nextPath);
114
+ if (!previous || !next) {
115
+ continue;
116
+ }
117
+ consumedBase.add(previousPath);
118
+ consumedHead.add(nextPath);
119
+ documents.push(documentDiff("renamed", nextPath, previous, next, base, head, previousPath));
120
+ }
121
+ for (const [documentPath, next] of head.documents) {
122
+ if (consumedHead.has(documentPath)) {
123
+ continue;
124
+ }
125
+ const previous = base.documents.get(documentPath);
126
+ if (!previous) {
127
+ documents.push(documentDiff("added", documentPath, undefined, next, base, head));
128
+ continue;
129
+ }
130
+ consumedBase.add(documentPath);
131
+ if (previous.hash !== next.hash || previous.status !== next.status || previous.type !== next.type) {
132
+ documents.push(documentDiff("modified", documentPath, previous, next, base, head));
133
+ }
134
+ }
135
+ for (const [documentPath, previous] of base.documents) {
136
+ if (!consumedBase.has(documentPath) && !head.documents.has(documentPath)) {
137
+ documents.push(documentDiff("deleted", documentPath, previous, undefined, base, head));
138
+ }
139
+ }
140
+ return documents.sort((left, right) => (left.previousPath ?? left.path).localeCompare(right.previousPath ?? right.path) || left.path.localeCompare(right.path));
141
+ }
142
+ function documentDiff(change, documentPath, previous, next, base, head, previousPath) {
143
+ const beforePath = previous?.path ?? previousPath ?? documentPath;
144
+ const afterPath = next?.path ?? documentPath;
145
+ const warningCodes = sortedWarningCodes([
146
+ ...base.warningCodesByDocument.get(beforePath) ?? [],
147
+ ...head.warningCodesByDocument.get(afterPath) ?? []
148
+ ]);
149
+ return {
150
+ path: documentPath,
151
+ previousPath,
152
+ change,
153
+ hashChanged: previous && next ? previous.hash !== next.hash : true,
154
+ statusChanged: previous && next ? previous.status !== next.status : undefined,
155
+ sectionDelta: (next ? head.sectionCounts.get(afterPath) ?? 0 : 0) - (previous ? base.sectionCounts.get(beforePath) ?? 0 : 0),
156
+ sourceRefDelta: (next ? head.sourceRefCounts.get(afterPath) ?? 0 : 0) - (previous ? base.sourceRefCounts.get(beforePath) ?? 0 : 0),
157
+ warningCodes: warningCodes.length ? warningCodes : undefined
158
+ };
159
+ }
160
+ function sectionCountsByDocument(documents, sections) {
161
+ const pathById = new Map(documents.map((document) => [document.id, document.path]));
162
+ const counts = new Map();
163
+ for (const section of sections) {
164
+ const documentPath = pathById.get(section.documentId);
165
+ if (documentPath) {
166
+ counts.set(documentPath, (counts.get(documentPath) ?? 0) + 1);
167
+ }
168
+ }
169
+ return counts;
170
+ }
171
+ function sourceRefCountsByDocument(documents, sourceRefs, edges) {
172
+ const pathByDocumentId = new Map(documents.map((document) => [document.id, document.path]));
173
+ const sourceRefIds = new Set(sourceRefs.map((sourceRef) => sourceRef.id));
174
+ const counts = new Map();
175
+ for (const edge of edges) {
176
+ if (edge.kind !== "REFERENCES_SOURCE") {
177
+ continue;
178
+ }
179
+ const documentPath = pathByDocumentId.get(edge.fromId);
180
+ if (documentPath && sourceRefIds.has(edge.toId)) {
181
+ counts.set(documentPath, (counts.get(documentPath) ?? 0) + 1);
182
+ }
183
+ }
184
+ return counts;
185
+ }
186
+ function warningCounts(report) {
187
+ const counts = {};
188
+ for (const warning of report.warnings) {
189
+ counts[warning.code] = (counts[warning.code] ?? 0) + 1;
190
+ }
191
+ return counts;
192
+ }
193
+ function warningCodesByDocument(warnings) {
194
+ const byDocument = new Map();
195
+ for (const warning of warnings) {
196
+ for (const node of warning.affectedNodes) {
197
+ if (!node.path || node.kind !== "document") {
198
+ continue;
199
+ }
200
+ const current = byDocument.get(node.path) ?? new Set();
201
+ current.add(warning.code);
202
+ byDocument.set(node.path, current);
203
+ }
204
+ }
205
+ return byDocument;
206
+ }
207
+ function countDelta(base, head) {
208
+ const delta = {};
209
+ for (const code of [...new Set([...Object.keys(base), ...Object.keys(head)])].sort()) {
210
+ const value = (head[code] ?? 0) - (base[code] ?? 0);
211
+ if (value !== 0) {
212
+ delta[code] = value;
213
+ }
214
+ }
215
+ return delta;
216
+ }
217
+ function setSymmetricDifference(base, head) {
218
+ return [...new Set([...base, ...head])]
219
+ .filter((value) => base.has(value) !== head.has(value))
220
+ .sort();
221
+ }
222
+ function affectedDocumentPaths(documents, base, head) {
223
+ return [...new Set([
224
+ ...documents.flatMap((document) => [document.previousPath, document.path]),
225
+ ...base.warningCodesByDocument.keys(),
226
+ ...head.warningCodesByDocument.keys()
227
+ ].filter((value) => Boolean(value)))].sort();
228
+ }
229
+ function prSummary(report) {
230
+ const summary = [
231
+ `Documents changed: +${report.summary.documentsAdded}, ~${report.summary.documentsModified}, -${report.summary.documentsDeleted}, renamed ${report.summary.documentsRenamed}.`,
232
+ `Graph deltas: sections ${formatSigned(report.summary.sectionsChanged)}, source refs ${formatSigned(report.summary.sourceRefsChanged)}, edges ${formatSigned(report.summary.edgesChanged)}.`
233
+ ];
234
+ const warningDelta = Object.entries(report.summary.warningDelta);
235
+ if (warningDelta.length) {
236
+ summary.push(`Doctor warning delta: ${warningDelta.map(([code, delta]) => `${code} ${formatSigned(delta)}`).join(", ")}.`);
237
+ }
238
+ if (report.impact.changedSourceRefs.length) {
239
+ summary.push(`Changed source refs: ${report.impact.changedSourceRefs.slice(0, 10).join(", ")}${report.impact.changedSourceRefs.length > 10 ? ", ..." : ""}.`);
240
+ }
241
+ return summary;
242
+ }
243
+ function createBaseSnapshot(projectRoot, revision) {
244
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mdgraph-diff-base-"));
245
+ const files = gitTrackedFiles(projectRoot, revision);
246
+ for (const filePath of files) {
247
+ writeBaseFile(projectRoot, tempRoot, revision, filePath);
248
+ }
249
+ const currentConfig = loadConfig(projectRoot);
250
+ fs.mkdirSync(path.dirname(configPath(tempRoot)), { recursive: true });
251
+ fs.writeFileSync(configPath(tempRoot), `${JSON.stringify(currentConfig, null, 2)}\n`, "utf8");
252
+ return tempRoot;
253
+ }
254
+ function writeBaseFile(projectRoot, tempRoot, revision, gitPath) {
255
+ const target = safeOutputPath(tempRoot, gitPath);
256
+ fs.mkdirSync(path.dirname(target), { recursive: true });
257
+ if (!needsContent(gitPath)) {
258
+ fs.writeFileSync(target, "");
259
+ return;
260
+ }
261
+ const result = spawnSync("git", ["show", `${revision}:${gitPath}`], {
262
+ cwd: projectRoot,
263
+ maxBuffer: 50 * 1024 * 1024,
264
+ windowsHide: true
265
+ });
266
+ if (result.status !== 0) {
267
+ throw new Error(`Failed to read ${gitPath} from ${revision}: ${bufferToString(result.stderr)}`);
268
+ }
269
+ fs.writeFileSync(target, result.stdout);
270
+ }
271
+ function needsContent(gitPath) {
272
+ return /\.(?:md|mdx)$/i.test(gitPath) || gitPath === ".gitignore";
273
+ }
274
+ function safeOutputPath(root, relativePath) {
275
+ const normalized = normalizePath(relativePath).replace(/^\/+/, "");
276
+ const resolved = path.resolve(root, normalized);
277
+ const relative = path.relative(root, resolved);
278
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
279
+ throw new Error(`Unsafe path in Git tree: ${relativePath}`);
280
+ }
281
+ return resolved;
282
+ }
283
+ function resolveBaseRevision(projectRoot, baseRef) {
284
+ return runGitText(projectRoot, ["rev-parse", "--verify", `${baseRef}^{commit}`]).trim();
285
+ }
286
+ function gitTrackedFiles(projectRoot, revision) {
287
+ return runGitText(projectRoot, ["ls-tree", "-r", "-z", "--name-only", revision])
288
+ .split("\0")
289
+ .filter(Boolean)
290
+ .map(normalizePath);
291
+ }
292
+ function gitRenames(projectRoot, revision) {
293
+ const output = runGitText(projectRoot, ["diff", "--name-status", "--find-renames", revision]);
294
+ const renames = new Map();
295
+ for (const line of output.split(/\r?\n/)) {
296
+ const parts = line.split("\t");
297
+ if (parts.length >= 3 && parts[0]?.startsWith("R") && isMarkdownPath(parts[1]) && isMarkdownPath(parts[2])) {
298
+ renames.set(normalizePath(parts[1]), normalizePath(parts[2]));
299
+ }
300
+ }
301
+ return renames;
302
+ }
303
+ function runGitText(projectRoot, args) {
304
+ const result = spawnSync("git", args, {
305
+ cwd: projectRoot,
306
+ encoding: "utf8",
307
+ windowsHide: true
308
+ });
309
+ if (result.status !== 0) {
310
+ throw new Error(`Git command failed: git ${args.join(" ")}\n${result.stderr}`);
311
+ }
312
+ return result.stdout;
313
+ }
314
+ function formatDiffDocument(document) {
315
+ const renamed = document.previousPath ? `${document.previousPath} -> ${document.path}` : document.path;
316
+ const details = [
317
+ `sections ${formatSigned(document.sectionDelta ?? 0)}`,
318
+ `source refs ${formatSigned(document.sourceRefDelta ?? 0)}`,
319
+ document.warningCodes?.length ? `warnings ${document.warningCodes.join(",")}` : ""
320
+ ].filter(Boolean);
321
+ return `- ${document.change}: ${renamed}${details.length ? ` (${details.join("; ")})` : ""}`;
322
+ }
323
+ function sortedWarningCodes(values) {
324
+ return [...new Set(values)].sort();
325
+ }
326
+ function formatSigned(value) {
327
+ return value > 0 ? `+${value}` : String(value);
328
+ }
329
+ function isMarkdownPath(value) {
330
+ return /\.(?:md|mdx)$/i.test(value);
331
+ }
332
+ function bufferToString(value) {
333
+ return Buffer.isBuffer(value) ? value.toString("utf8") : String(value ?? "");
334
+ }
@@ -0,0 +1,115 @@
1
+ import type { EdgeKind, SearchQueryMode } from "../types.js";
2
+ import type { GraphRepository } from "../db/repositories.js";
3
+ import type { MDGraphConfig } from "../types.js";
4
+ import { CONTEXT_PACKING_STRATEGY } from "../query/context-builder.js";
5
+ import { type TraceResult } from "../query/trace.js";
6
+ export interface EvaluationSectionExpectation {
7
+ path: string;
8
+ heading: string;
9
+ }
10
+ export interface EvaluationTraceExpectation {
11
+ from: string;
12
+ to: string;
13
+ depth?: number;
14
+ edgeKinds: EdgeKind[];
15
+ }
16
+ export interface EvaluationCase {
17
+ id: string;
18
+ query: string;
19
+ expectedDocuments: string[];
20
+ expectedSections: EvaluationSectionExpectation[];
21
+ expectedEntities: string[];
22
+ expectedEdges: EdgeKind[];
23
+ expectedSourceRefs: string[];
24
+ trace?: EvaluationTraceExpectation;
25
+ }
26
+ export interface EvaluationMetrics {
27
+ topKDocumentRecall: number;
28
+ expectedSectionRecall: number;
29
+ contextPrecision: number;
30
+ entityRecall: number;
31
+ sourceRefRecall: number;
32
+ edgeKindCoverage: number;
33
+ traceSuccess: boolean | null;
34
+ latencyMs: number;
35
+ returnedChars: number;
36
+ budgetFit: boolean;
37
+ fanout: {
38
+ seedNodes: number;
39
+ visitedNodes: number;
40
+ expandedEdges: number;
41
+ skippedByNodeLimit: number;
42
+ skippedByDepth: number;
43
+ };
44
+ reasonCoverage: boolean;
45
+ rankingReasonCoverage: boolean;
46
+ contextDiversity: number;
47
+ }
48
+ export interface EvaluationCaseResult {
49
+ id: string;
50
+ query: string;
51
+ passed: boolean;
52
+ expected: Omit<EvaluationCase, "id" | "query" | "trace">;
53
+ observed: {
54
+ searchDocuments: string[];
55
+ contextItems: Array<{
56
+ path: string;
57
+ heading?: string;
58
+ reason: string;
59
+ }>;
60
+ matchedEntities: string[];
61
+ resolvedEntities: string[];
62
+ resolvedSourceRefs: string[];
63
+ edgeKinds: EdgeKind[];
64
+ trace?: TraceResult;
65
+ ranking: {
66
+ queryMode: SearchQueryMode;
67
+ searchFusion: "rrf";
68
+ searchChannels: string[];
69
+ semanticActive: boolean;
70
+ optionalReranker: "none" | "local-hash";
71
+ contextPackingStrategy: typeof CONTEXT_PACKING_STRATEGY;
72
+ };
73
+ };
74
+ metrics: EvaluationMetrics;
75
+ }
76
+ export interface EvaluationSummary {
77
+ cases: number;
78
+ passed: number;
79
+ failed: number;
80
+ averageTopKDocumentRecall: number;
81
+ averageExpectedSectionRecall: number;
82
+ averageContextPrecision: number;
83
+ averageContextDiversity: number;
84
+ averageLatencyMs: number;
85
+ averageReturnedChars: number;
86
+ }
87
+ export interface EvaluationRankingReport {
88
+ queryMode: SearchQueryMode;
89
+ searchFusion: "rrf";
90
+ contextPackingStrategy: typeof CONTEXT_PACKING_STRATEGY;
91
+ optionalReranker: "none" | "local-hash";
92
+ semanticActiveCases: number;
93
+ searchChannels: string[];
94
+ rankingReasonCoverage: boolean;
95
+ averageContextDiversity: number;
96
+ }
97
+ export interface EvaluationReport {
98
+ querySet: string;
99
+ limit: number;
100
+ ranking: EvaluationRankingReport;
101
+ generatedAt: string;
102
+ summary: EvaluationSummary;
103
+ cases: EvaluationCaseResult[];
104
+ }
105
+ export declare const EVALUATION_QUERY_SET_NAMES: readonly ["alpha", "cjk"];
106
+ export type EvaluationQuerySet = typeof EVALUATION_QUERY_SET_NAMES[number];
107
+ export declare const ALPHA_EVALUATION_CASES: EvaluationCase[];
108
+ export declare const CJK_EVALUATION_CASES: EvaluationCase[];
109
+ export declare function evaluationCasesForQuerySet(querySet: string): EvaluationCase[];
110
+ export declare function evaluateRetrieval(repository: GraphRepository, config: MDGraphConfig, options?: {
111
+ cases?: EvaluationCase[];
112
+ limit?: number;
113
+ querySet?: string;
114
+ queryMode?: SearchQueryMode;
115
+ }): EvaluationReport;