@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,13 @@
1
+ import type { GraphRepository } from "../db/repositories.js";
2
+ import type { MDGraphConfig } from "../types.js";
3
+ export interface StatusFreshness {
4
+ state: "fresh" | "stale" | "unknown";
5
+ lastIndexedAt?: string;
6
+ recommendation: string;
7
+ checkedAt?: string;
8
+ issues?: Array<{
9
+ path: string;
10
+ reason: "added" | "deleted" | "modified";
11
+ }>;
12
+ }
13
+ export declare function computeStatusFreshness(projectRoot: string, config: MDGraphConfig, repository: GraphRepository): StatusFreshness;
@@ -0,0 +1,55 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { scanMarkdownFilesSync } from "../scanner/file-scanner.js";
4
+ import { normalizePath } from "../utils/text.js";
5
+ export function computeStatusFreshness(projectRoot, config, repository) {
6
+ const lastIndexedAt = repository.latestIndexedAt();
7
+ const checkedAt = new Date().toISOString();
8
+ if (!lastIndexedAt) {
9
+ return {
10
+ state: "unknown",
11
+ checkedAt,
12
+ recommendation: "no indexed timestamp is available; run `mdgraph index` before relying on the graph"
13
+ };
14
+ }
15
+ try {
16
+ const indexedAtMs = Date.parse(lastIndexedAt);
17
+ const scanned = scanMarkdownFilesSync(projectRoot, config);
18
+ const indexed = repository.documentHashes();
19
+ const scannedByPath = new Map(scanned.map((filePath) => [normalizePath(path.relative(projectRoot, filePath)), filePath]));
20
+ const issues = [];
21
+ for (const [relativePath, absolutePath] of scannedByPath) {
22
+ if (!indexed.has(relativePath)) {
23
+ issues.push({ path: relativePath, reason: "added" });
24
+ continue;
25
+ }
26
+ if (Number.isFinite(indexedAtMs) && fs.statSync(absolutePath).mtimeMs > indexedAtMs + 1) {
27
+ issues.push({ path: relativePath, reason: "modified" });
28
+ }
29
+ }
30
+ for (const documentPath of indexed.keys()) {
31
+ if (!scannedByPath.has(documentPath)) {
32
+ issues.push({ path: documentPath, reason: "deleted" });
33
+ }
34
+ }
35
+ const sortedIssues = issues.sort((left, right) => left.path.localeCompare(right.path) || left.reason.localeCompare(right.reason));
36
+ return {
37
+ state: sortedIssues.length ? "stale" : "fresh",
38
+ lastIndexedAt,
39
+ checkedAt,
40
+ recommendation: sortedIssues.length
41
+ ? "Markdown files changed since indexing; run `mdgraph index` before relying on results"
42
+ : "indexed Markdown files match the lightweight status freshness check",
43
+ issues: sortedIssues.length ? sortedIssues.slice(0, 20) : undefined
44
+ };
45
+ }
46
+ catch (error) {
47
+ const message = error instanceof Error ? error.message : String(error);
48
+ return {
49
+ state: "unknown",
50
+ lastIndexedAt,
51
+ checkedAt,
52
+ recommendation: `freshness check failed: ${message}; run \`mdgraph doctor --json\` or \`mdgraph index\``
53
+ };
54
+ }
55
+ }
@@ -0,0 +1,118 @@
1
+ import { type EvaluationCase } from "../evaluation/retrieval-eval.js";
2
+ export type AgentRunMode = "with_mdgraph" | "without_mdgraph";
3
+ export interface AgentRunRecord {
4
+ id: string;
5
+ questionId: string;
6
+ question: string;
7
+ mode: AgentRunMode;
8
+ startedAt: string;
9
+ completedAt: string;
10
+ toolCalls: Array<{
11
+ name: string;
12
+ outputChars?: number;
13
+ }>;
14
+ directFileReads: Array<{
15
+ path: string;
16
+ chars?: number;
17
+ }>;
18
+ textSearches: Array<{
19
+ query: string;
20
+ resultCount?: number;
21
+ }>;
22
+ mdgraphCalls: Array<{
23
+ tool: string;
24
+ query?: string;
25
+ resultCount?: number;
26
+ chars?: number;
27
+ }>;
28
+ finalCitations: Array<{
29
+ path: string;
30
+ line?: number;
31
+ correct?: boolean | "unknown";
32
+ }>;
33
+ rawFileFallback: boolean;
34
+ tokenEstimate?: number;
35
+ characterBudget?: number;
36
+ latencyMs: number;
37
+ notes?: string[];
38
+ }
39
+ export interface BenchmarkRunMetrics {
40
+ toolCalls: {
41
+ count: number;
42
+ outputChars: number;
43
+ };
44
+ directFileReads: {
45
+ count: number;
46
+ chars: number;
47
+ };
48
+ textSearches: {
49
+ count: number;
50
+ resultCount: number;
51
+ };
52
+ mdgraphCalls: {
53
+ count: number;
54
+ chars: number;
55
+ resultCount: number;
56
+ };
57
+ tokenEstimate?: number;
58
+ characterBudget?: number;
59
+ latencyMs: number;
60
+ rawFileFallback: boolean;
61
+ citations: {
62
+ total: number;
63
+ correct: number;
64
+ incorrect: number;
65
+ unknown: number;
66
+ correctnessRate: number | null;
67
+ };
68
+ }
69
+ export interface BenchmarkDelta {
70
+ toolCalls: number;
71
+ toolCallOutputChars: number;
72
+ directFileReads: number;
73
+ directFileReadChars: number;
74
+ textSearches: number;
75
+ textSearchResults: number;
76
+ mdgraphCalls: number;
77
+ mdgraphCallChars: number;
78
+ mdgraphCallResults: number;
79
+ tokenEstimate: number | null;
80
+ characterBudget: number | null;
81
+ latencyMs: number;
82
+ rawFileFallback: number;
83
+ citationCorrectnessRate: number | null;
84
+ citationUnknown: number;
85
+ }
86
+ export interface BenchmarkPairReport {
87
+ questionId: string;
88
+ question: string;
89
+ withMdgraph: BenchmarkRunMetrics;
90
+ withoutMdgraph: BenchmarkRunMetrics;
91
+ delta: BenchmarkDelta;
92
+ }
93
+ export interface SkippedBenchmarkPair {
94
+ questionId: string;
95
+ reason: string;
96
+ recordIds: string[];
97
+ }
98
+ export interface BenchmarkReport {
99
+ format: "mdgraph-benchmark";
100
+ formatVersion: 1;
101
+ generatedAt: string;
102
+ querySets: string[];
103
+ records: number;
104
+ summary: {
105
+ questions: number;
106
+ completePairs: number;
107
+ skippedPairs: number;
108
+ aggregateDelta: BenchmarkDelta;
109
+ };
110
+ pairs: BenchmarkPairReport[];
111
+ skipped: SkippedBenchmarkPair[];
112
+ }
113
+ export declare function loadBenchmarkReport(filePath: string): BenchmarkReport;
114
+ export declare function parseAgentRunRecords(value: unknown): AgentRunRecord[];
115
+ export declare function generateBenchmarkReport(records: AgentRunRecord[], options?: {
116
+ cases?: EvaluationCase[];
117
+ }): BenchmarkReport;
118
+ export declare function formatBenchmarkReport(report: BenchmarkReport): string;
@@ -0,0 +1,357 @@
1
+ import { EVALUATION_QUERY_SET_NAMES, evaluationCasesForQuerySet } from "../evaluation/retrieval-eval.js";
2
+ import { readBoundedJsonFile } from "../utils/bounded-json.js";
3
+ import { normalizePath } from "../utils/text.js";
4
+ export function loadBenchmarkReport(filePath) {
5
+ return generateBenchmarkReport(parseAgentRunRecords(readBoundedJsonFile(filePath, "Benchmark input")));
6
+ }
7
+ export function parseAgentRunRecords(value) {
8
+ const records = Array.isArray(value) ? value : runsProperty(value);
9
+ return records.map((record, index) => validateRunRecord(record, index));
10
+ }
11
+ export function generateBenchmarkReport(records, options = {}) {
12
+ const cases = options.cases ?? defaultEvaluationCases();
13
+ const caseById = new Map(cases.map((evaluationCase) => [evaluationCase.id, evaluationCase]));
14
+ const groups = groupByQuestionId(records);
15
+ const pairs = [];
16
+ const skipped = [];
17
+ for (const [questionId, group] of [...groups.entries()].sort(([left], [right]) => left.localeCompare(right))) {
18
+ const skipReason = skippedPairReason(group);
19
+ if (skipReason) {
20
+ skipped.push({
21
+ questionId,
22
+ reason: skipReason,
23
+ recordIds: group.map((record) => record.id).sort()
24
+ });
25
+ continue;
26
+ }
27
+ const withRecord = group.find((record) => record.mode === "with_mdgraph");
28
+ const withoutRecord = group.find((record) => record.mode === "without_mdgraph");
29
+ const withMdgraph = runMetrics(withRecord, caseById.get(questionId));
30
+ const withoutMdgraph = runMetrics(withoutRecord, caseById.get(questionId));
31
+ pairs.push({
32
+ questionId,
33
+ question: withRecord.question,
34
+ withMdgraph,
35
+ withoutMdgraph,
36
+ delta: metricDelta(withMdgraph, withoutMdgraph)
37
+ });
38
+ }
39
+ return {
40
+ format: "mdgraph-benchmark",
41
+ formatVersion: 1,
42
+ generatedAt: new Date().toISOString(),
43
+ querySets: [...EVALUATION_QUERY_SET_NAMES],
44
+ records: records.length,
45
+ summary: {
46
+ questions: groups.size,
47
+ completePairs: pairs.length,
48
+ skippedPairs: skipped.length,
49
+ aggregateDelta: aggregateDelta(pairs.map((pair) => pair.delta))
50
+ },
51
+ pairs,
52
+ skipped
53
+ };
54
+ }
55
+ export function formatBenchmarkReport(report) {
56
+ const lines = [
57
+ "MDGraph benchmark",
58
+ `Records: ${report.records}, questions: ${report.summary.questions}, complete pairs: ${report.summary.completePairs}, skipped pairs: ${report.summary.skippedPairs}`,
59
+ `Aggregate delta (with - without): file reads ${formatSigned(report.summary.aggregateDelta.directFileReads)}, text searches ${formatSigned(report.summary.aggregateDelta.textSearches)}, tool calls ${formatSigned(report.summary.aggregateDelta.toolCalls)}, latency ${formatSigned(report.summary.aggregateDelta.latencyMs)} ms`
60
+ ];
61
+ if (report.pairs.length) {
62
+ lines.push("Pairs:");
63
+ for (const pair of report.pairs.slice(0, 10)) {
64
+ lines.push(`- ${pair.questionId}: file reads ${formatSigned(pair.delta.directFileReads)}, mdgraph calls ${formatSigned(pair.delta.mdgraphCalls)}, citation rate ${formatRate(pair.withMdgraph.citations.correctnessRate)} vs ${formatRate(pair.withoutMdgraph.citations.correctnessRate)}`);
65
+ }
66
+ }
67
+ if (report.skipped.length) {
68
+ lines.push("Skipped:", ...report.skipped.map((item) => `- ${item.questionId}: ${item.reason}`));
69
+ }
70
+ return lines.join("\n");
71
+ }
72
+ function runsProperty(value) {
73
+ if (value && typeof value === "object" && Array.isArray(value.runs)) {
74
+ return value.runs;
75
+ }
76
+ throw new Error("Benchmark input must be a JSON array of AgentRunRecord objects or an object with a runs array.");
77
+ }
78
+ function validateRunRecord(value, index) {
79
+ if (!value || typeof value !== "object") {
80
+ throw new Error(`Benchmark run record ${index} must be an object.`);
81
+ }
82
+ const record = value;
83
+ const mode = requiredString(record, "mode", index);
84
+ if (mode !== "with_mdgraph" && mode !== "without_mdgraph") {
85
+ throw new Error(`Benchmark run record ${index} mode must be with_mdgraph or without_mdgraph.`);
86
+ }
87
+ return {
88
+ id: requiredString(record, "id", index),
89
+ questionId: requiredString(record, "questionId", index),
90
+ question: requiredString(record, "question", index),
91
+ mode,
92
+ startedAt: requiredString(record, "startedAt", index),
93
+ completedAt: requiredString(record, "completedAt", index),
94
+ toolCalls: arrayOfObjects(record, "toolCalls", index).map((item, itemIndex) => ({
95
+ name: requiredString(item, "name", index, itemIndex),
96
+ outputChars: optionalNonNegativeNumber(item, "outputChars", index, itemIndex)
97
+ })),
98
+ directFileReads: arrayOfObjects(record, "directFileReads", index).map((item, itemIndex) => ({
99
+ path: normalizePath(requiredString(item, "path", index, itemIndex)),
100
+ chars: optionalNonNegativeNumber(item, "chars", index, itemIndex)
101
+ })),
102
+ textSearches: arrayOfObjects(record, "textSearches", index).map((item, itemIndex) => ({
103
+ query: requiredString(item, "query", index, itemIndex),
104
+ resultCount: optionalNonNegativeNumber(item, "resultCount", index, itemIndex)
105
+ })),
106
+ mdgraphCalls: arrayOfObjects(record, "mdgraphCalls", index).map((item, itemIndex) => ({
107
+ tool: requiredString(item, "tool", index, itemIndex),
108
+ query: optionalString(item, "query", index, itemIndex),
109
+ resultCount: optionalNonNegativeNumber(item, "resultCount", index, itemIndex),
110
+ chars: optionalNonNegativeNumber(item, "chars", index, itemIndex)
111
+ })),
112
+ finalCitations: arrayOfObjects(record, "finalCitations", index).map((item, itemIndex) => ({
113
+ path: normalizePath(requiredString(item, "path", index, itemIndex)),
114
+ line: optionalPositiveInteger(item, "line", index, itemIndex),
115
+ correct: optionalCitationCorrectness(item, index, itemIndex)
116
+ })),
117
+ rawFileFallback: requiredBoolean(record, "rawFileFallback", index),
118
+ tokenEstimate: optionalNonNegativeNumber(record, "tokenEstimate", index),
119
+ characterBudget: optionalNonNegativeNumber(record, "characterBudget", index),
120
+ latencyMs: requiredNonNegativeNumber(record, "latencyMs", index),
121
+ notes: optionalStringArray(record, "notes", index)
122
+ };
123
+ }
124
+ function runMetrics(record, evaluationCase) {
125
+ return {
126
+ toolCalls: {
127
+ count: record.toolCalls.length,
128
+ outputChars: sum(record.toolCalls.map((toolCall) => toolCall.outputChars))
129
+ },
130
+ directFileReads: {
131
+ count: record.directFileReads.length,
132
+ chars: sum(record.directFileReads.map((read) => read.chars))
133
+ },
134
+ textSearches: {
135
+ count: record.textSearches.length,
136
+ resultCount: sum(record.textSearches.map((search) => search.resultCount))
137
+ },
138
+ mdgraphCalls: {
139
+ count: record.mdgraphCalls.length,
140
+ chars: sum(record.mdgraphCalls.map((call) => call.chars)),
141
+ resultCount: sum(record.mdgraphCalls.map((call) => call.resultCount))
142
+ },
143
+ tokenEstimate: record.tokenEstimate,
144
+ characterBudget: record.characterBudget,
145
+ latencyMs: record.latencyMs,
146
+ rawFileFallback: record.rawFileFallback,
147
+ citations: citationMetrics(record, evaluationCase)
148
+ };
149
+ }
150
+ function citationMetrics(record, evaluationCase) {
151
+ const expectedPaths = evaluationCase ? expectedCitationPaths(evaluationCase) : undefined;
152
+ let correct = 0;
153
+ let incorrect = 0;
154
+ let unknown = 0;
155
+ for (const citation of record.finalCitations) {
156
+ if (expectedPaths) {
157
+ if (expectedPaths.has(normalizePath(citation.path))) {
158
+ correct += 1;
159
+ }
160
+ else {
161
+ incorrect += 1;
162
+ }
163
+ continue;
164
+ }
165
+ if (citation.correct === true) {
166
+ correct += 1;
167
+ }
168
+ else if (citation.correct === false) {
169
+ incorrect += 1;
170
+ }
171
+ else {
172
+ unknown += 1;
173
+ }
174
+ }
175
+ const rated = correct + incorrect;
176
+ return {
177
+ total: record.finalCitations.length,
178
+ correct,
179
+ incorrect,
180
+ unknown,
181
+ correctnessRate: rated ? round(correct / rated) : null
182
+ };
183
+ }
184
+ function expectedCitationPaths(evaluationCase) {
185
+ return new Set([
186
+ ...evaluationCase.expectedDocuments,
187
+ ...evaluationCase.expectedSections.map((section) => section.path)
188
+ ].map(normalizePath));
189
+ }
190
+ function metricDelta(withMdgraph, withoutMdgraph) {
191
+ return {
192
+ toolCalls: withMdgraph.toolCalls.count - withoutMdgraph.toolCalls.count,
193
+ toolCallOutputChars: withMdgraph.toolCalls.outputChars - withoutMdgraph.toolCalls.outputChars,
194
+ directFileReads: withMdgraph.directFileReads.count - withoutMdgraph.directFileReads.count,
195
+ directFileReadChars: withMdgraph.directFileReads.chars - withoutMdgraph.directFileReads.chars,
196
+ textSearches: withMdgraph.textSearches.count - withoutMdgraph.textSearches.count,
197
+ textSearchResults: withMdgraph.textSearches.resultCount - withoutMdgraph.textSearches.resultCount,
198
+ mdgraphCalls: withMdgraph.mdgraphCalls.count - withoutMdgraph.mdgraphCalls.count,
199
+ mdgraphCallChars: withMdgraph.mdgraphCalls.chars - withoutMdgraph.mdgraphCalls.chars,
200
+ mdgraphCallResults: withMdgraph.mdgraphCalls.resultCount - withoutMdgraph.mdgraphCalls.resultCount,
201
+ tokenEstimate: optionalDelta(withMdgraph.tokenEstimate, withoutMdgraph.tokenEstimate),
202
+ characterBudget: optionalDelta(withMdgraph.characterBudget, withoutMdgraph.characterBudget),
203
+ latencyMs: withMdgraph.latencyMs - withoutMdgraph.latencyMs,
204
+ rawFileFallback: Number(withMdgraph.rawFileFallback) - Number(withoutMdgraph.rawFileFallback),
205
+ citationCorrectnessRate: optionalDelta(withMdgraph.citations.correctnessRate, withoutMdgraph.citations.correctnessRate),
206
+ citationUnknown: withMdgraph.citations.unknown - withoutMdgraph.citations.unknown
207
+ };
208
+ }
209
+ function aggregateDelta(deltas) {
210
+ return {
211
+ toolCalls: sum(deltas.map((delta) => delta.toolCalls)),
212
+ toolCallOutputChars: sum(deltas.map((delta) => delta.toolCallOutputChars)),
213
+ directFileReads: sum(deltas.map((delta) => delta.directFileReads)),
214
+ directFileReadChars: sum(deltas.map((delta) => delta.directFileReadChars)),
215
+ textSearches: sum(deltas.map((delta) => delta.textSearches)),
216
+ textSearchResults: sum(deltas.map((delta) => delta.textSearchResults)),
217
+ mdgraphCalls: sum(deltas.map((delta) => delta.mdgraphCalls)),
218
+ mdgraphCallChars: sum(deltas.map((delta) => delta.mdgraphCallChars)),
219
+ mdgraphCallResults: sum(deltas.map((delta) => delta.mdgraphCallResults)),
220
+ tokenEstimate: optionalSum(deltas.map((delta) => delta.tokenEstimate)),
221
+ characterBudget: optionalSum(deltas.map((delta) => delta.characterBudget)),
222
+ latencyMs: sum(deltas.map((delta) => delta.latencyMs)),
223
+ rawFileFallback: sum(deltas.map((delta) => delta.rawFileFallback)),
224
+ citationCorrectnessRate: averageOptional(deltas.map((delta) => delta.citationCorrectnessRate)),
225
+ citationUnknown: sum(deltas.map((delta) => delta.citationUnknown))
226
+ };
227
+ }
228
+ function groupByQuestionId(records) {
229
+ const groups = new Map();
230
+ for (const record of records) {
231
+ groups.set(record.questionId, [...groups.get(record.questionId) ?? [], record]);
232
+ }
233
+ return groups;
234
+ }
235
+ function skippedPairReason(records) {
236
+ const withCount = records.filter((record) => record.mode === "with_mdgraph").length;
237
+ const withoutCount = records.filter((record) => record.mode === "without_mdgraph").length;
238
+ const questions = new Set(records.map((record) => record.question.trim()));
239
+ if (questions.size > 1) {
240
+ return "question_text_mismatch";
241
+ }
242
+ if (withCount !== 1 || withoutCount !== 1) {
243
+ return `expected one with_mdgraph and one without_mdgraph record; got with_mdgraph=${withCount}, without_mdgraph=${withoutCount}`;
244
+ }
245
+ return undefined;
246
+ }
247
+ function defaultEvaluationCases() {
248
+ return EVALUATION_QUERY_SET_NAMES.flatMap((querySet) => evaluationCasesForQuerySet(querySet));
249
+ }
250
+ function requiredString(record, key, recordIndex, itemIndex) {
251
+ const value = record[key];
252
+ if (typeof value !== "string" || !value.trim()) {
253
+ throw new Error(`${recordLabel(recordIndex, itemIndex)} must include non-empty string ${key}.`);
254
+ }
255
+ return value;
256
+ }
257
+ function optionalString(record, key, recordIndex, itemIndex) {
258
+ const value = record[key];
259
+ if (value === undefined) {
260
+ return undefined;
261
+ }
262
+ if (typeof value !== "string") {
263
+ throw new Error(`${recordLabel(recordIndex, itemIndex)} ${key} must be a string when present.`);
264
+ }
265
+ return value;
266
+ }
267
+ function requiredBoolean(record, key, recordIndex) {
268
+ const value = record[key];
269
+ if (typeof value !== "boolean") {
270
+ throw new Error(`${recordLabel(recordIndex)} must include boolean ${key}.`);
271
+ }
272
+ return value;
273
+ }
274
+ function requiredNonNegativeNumber(record, key, recordIndex) {
275
+ const value = record[key];
276
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
277
+ throw new Error(`${recordLabel(recordIndex)} must include non-negative number ${key}.`);
278
+ }
279
+ return value;
280
+ }
281
+ function optionalNonNegativeNumber(record, key, recordIndex, itemIndex) {
282
+ const value = record[key];
283
+ if (value === undefined) {
284
+ return undefined;
285
+ }
286
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
287
+ throw new Error(`${recordLabel(recordIndex, itemIndex)} ${key} must be a non-negative number when present.`);
288
+ }
289
+ return value;
290
+ }
291
+ function optionalPositiveInteger(record, key, recordIndex, itemIndex) {
292
+ const value = record[key];
293
+ if (value === undefined) {
294
+ return undefined;
295
+ }
296
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
297
+ throw new Error(`${recordLabel(recordIndex, itemIndex)} ${key} must be a positive integer when present.`);
298
+ }
299
+ return value;
300
+ }
301
+ function optionalCitationCorrectness(record, recordIndex, itemIndex) {
302
+ const value = record.correct;
303
+ if (value === undefined || value === true || value === false || value === "unknown") {
304
+ return value;
305
+ }
306
+ throw new Error(`${recordLabel(recordIndex, itemIndex)} correct must be boolean or "unknown" when present.`);
307
+ }
308
+ function optionalStringArray(record, key, recordIndex) {
309
+ const value = record[key];
310
+ if (value === undefined) {
311
+ return undefined;
312
+ }
313
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
314
+ throw new Error(`${recordLabel(recordIndex)} ${key} must be a string array when present.`);
315
+ }
316
+ return value;
317
+ }
318
+ function arrayOfObjects(record, key, recordIndex) {
319
+ const value = record[key];
320
+ if (!Array.isArray(value)) {
321
+ throw new Error(`${recordLabel(recordIndex)} must include array ${key}.`);
322
+ }
323
+ if (value.some((item) => !item || typeof item !== "object")) {
324
+ throw new Error(`${recordLabel(recordIndex)} ${key} must contain objects.`);
325
+ }
326
+ return value;
327
+ }
328
+ function recordLabel(recordIndex, itemIndex) {
329
+ return itemIndex === undefined ? `Benchmark run record ${recordIndex}` : `Benchmark run record ${recordIndex} item ${itemIndex}`;
330
+ }
331
+ function optionalDelta(left, right) {
332
+ return left === null || left === undefined || right === null || right === undefined ? null : round(left - right);
333
+ }
334
+ function optionalSum(values) {
335
+ const present = values.filter((value) => value !== null);
336
+ return present.length ? sum(present) : null;
337
+ }
338
+ function averageOptional(values) {
339
+ const present = values.filter((value) => value !== null);
340
+ return present.length ? round(sum(present) / present.length) : null;
341
+ }
342
+ function sum(values) {
343
+ let total = 0;
344
+ for (const value of values) {
345
+ total += value ?? 0;
346
+ }
347
+ return round(total);
348
+ }
349
+ function round(value) {
350
+ return Number(value.toFixed(4));
351
+ }
352
+ function formatSigned(value) {
353
+ return value > 0 ? `+${value}` : String(value);
354
+ }
355
+ function formatRate(value) {
356
+ return value === null ? "n/a" : `${(value * 100).toFixed(1)}%`;
357
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};