docorbit 0.1.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/LICENSE +21 -0
- package/README.md +660 -0
- package/apps/cli/bin/docorbit.js +8 -0
- package/apps/cli/src/commands/add.ts +44 -0
- package/apps/cli/src/commands/api.ts +38 -0
- package/apps/cli/src/commands/context.ts +47 -0
- package/apps/cli/src/commands/dashboard.ts +55 -0
- package/apps/cli/src/commands/diff.ts +30 -0
- package/apps/cli/src/commands/evaluate.ts +133 -0
- package/apps/cli/src/commands/examples.ts +39 -0
- package/apps/cli/src/commands/export.ts +89 -0
- package/apps/cli/src/commands/impact.ts +31 -0
- package/apps/cli/src/commands/init.ts +69 -0
- package/apps/cli/src/commands/inspect.ts +30 -0
- package/apps/cli/src/commands/mcp.ts +72 -0
- package/apps/cli/src/commands/pitfalls.ts +38 -0
- package/apps/cli/src/commands/recipes.ts +35 -0
- package/apps/cli/src/commands/search.ts +48 -0
- package/apps/cli/src/commands/update.ts +73 -0
- package/apps/cli/src/commands/verify.ts +48 -0
- package/apps/cli/src/formatters/colors.ts +23 -0
- package/apps/cli/src/formatters/inspection.ts +102 -0
- package/apps/cli/src/formatters/knowledge.ts +272 -0
- package/apps/cli/src/formatters/retrieval.ts +74 -0
- package/apps/cli/src/formatters/terminal.ts +6 -0
- package/apps/cli/src/formatters/verification.ts +126 -0
- package/apps/cli/src/index.ts +409 -0
- package/bin/docorbit.js +8 -0
- package/package.json +46 -0
- package/packages/core/src/dashboard/server.ts +314 -0
- package/packages/core/src/dashboard/ui.ts +586 -0
- package/packages/core/src/implementation-service.ts +451 -0
- package/packages/core/src/index.ts +7 -0
- package/packages/core/src/inspector.ts +71 -0
- package/packages/core/src/pipeline.ts +331 -0
- package/packages/crawler/src/config.ts +12 -0
- package/packages/crawler/src/fetcher.ts +185 -0
- package/packages/crawler/src/index.ts +2 -0
- package/packages/discovery/src/index.ts +31 -0
- package/packages/discovery/src/provider.ts +47 -0
- package/packages/discovery/src/providers/generic.ts +98 -0
- package/packages/discovery/src/providers/github.ts +61 -0
- package/packages/discovery/src/providers/llms-txt.ts +73 -0
- package/packages/discovery/src/providers/markdown.ts +48 -0
- package/packages/discovery/src/providers/openapi.ts +91 -0
- package/packages/discovery/src/providers/sitemap.ts +62 -0
- package/packages/discovery/src/providers/skill.ts +54 -0
- package/packages/discovery/src/ranker.ts +123 -0
- package/packages/evaluation/src/dataset.ts +963 -0
- package/packages/evaluation/src/index.ts +8 -0
- package/packages/evaluation/src/runner.ts +241 -0
- package/packages/evaluation/src/strategies/context7-runner.ts +269 -0
- package/packages/evaluation/src/strategies/docorbit-runner.ts +228 -0
- package/packages/evaluation/src/strategies/firecrawl-runner.ts +172 -0
- package/packages/evaluation/src/strategies/web-search-runner.ts +194 -0
- package/packages/evaluation/src/types.ts +34 -0
- package/packages/evaluation/src/version-matcher.ts +73 -0
- package/packages/export/src/agents-md.ts +200 -0
- package/packages/export/src/claude-md.ts +141 -0
- package/packages/export/src/docs-map.ts +150 -0
- package/packages/export/src/index.ts +6 -0
- package/packages/export/src/llms-txt.ts +96 -0
- package/packages/export/src/service.ts +250 -0
- package/packages/export/src/skill-md.ts +128 -0
- package/packages/mcp/src/index.ts +46 -0
- package/packages/mcp/src/resources/index.ts +189 -0
- package/packages/mcp/src/server.ts +278 -0
- package/packages/mcp/src/tools/analyze-impact.ts +74 -0
- package/packages/mcp/src/tools/check-api.ts +86 -0
- package/packages/mcp/src/tools/diff-docs.ts +68 -0
- package/packages/mcp/src/tools/export-context.ts +73 -0
- package/packages/mcp/src/tools/find-api.ts +99 -0
- package/packages/mcp/src/tools/find-example.ts +100 -0
- package/packages/mcp/src/tools/find-pitfall.ts +94 -0
- package/packages/mcp/src/tools/find-recipe.ts +98 -0
- package/packages/mcp/src/tools/get-doc.ts +130 -0
- package/packages/mcp/src/tools/get-docs-map.ts +64 -0
- package/packages/mcp/src/tools/get-version.ts +118 -0
- package/packages/mcp/src/tools/implementation-context.ts +88 -0
- package/packages/mcp/src/tools/index.ts +59 -0
- package/packages/mcp/src/tools/list-sources.ts +85 -0
- package/packages/mcp/src/tools/search-docs.ts +123 -0
- package/packages/mcp/src/tools/types.ts +28 -0
- package/packages/mcp/src/transports/http.ts +256 -0
- package/packages/mcp/src/transports/stdio.ts +105 -0
- package/packages/mcp/src/transports/types.ts +6 -0
- package/packages/mcp/src/types.ts +102 -0
- package/packages/normalizer/src/example-indexer.ts +240 -0
- package/packages/normalizer/src/html.ts +253 -0
- package/packages/normalizer/src/index.ts +8 -0
- package/packages/normalizer/src/llms.ts +83 -0
- package/packages/normalizer/src/openapi/endpoint-parser.ts +406 -0
- package/packages/normalizer/src/openapi/schema-resolver.ts +111 -0
- package/packages/normalizer/src/openapi.ts +2 -0
- package/packages/normalizer/src/page.ts +184 -0
- package/packages/normalizer/src/pitfall-extractor.ts +190 -0
- package/packages/normalizer/src/slicer.ts +455 -0
- package/packages/retrieval/src/engine.ts +120 -0
- package/packages/retrieval/src/index.ts +7 -0
- package/packages/retrieval/src/intent.ts +43 -0
- package/packages/retrieval/src/packer.ts +145 -0
- package/packages/retrieval/src/recipe-engine.ts +313 -0
- package/packages/retrieval/src/scorer.ts +139 -0
- package/packages/retrieval/src/weights.ts +31 -0
- package/packages/security/src/annotations.ts +112 -0
- package/packages/security/src/index.ts +2 -0
- package/packages/security/src/ssrf.ts +153 -0
- package/packages/shared/src/errors.ts +53 -0
- package/packages/shared/src/hashing.ts +23 -0
- package/packages/shared/src/index.ts +3 -0
- package/packages/shared/src/types.ts +881 -0
- package/packages/storage/src/db.ts +72 -0
- package/packages/storage/src/index.ts +11 -0
- package/packages/storage/src/interfaces.ts +115 -0
- package/packages/storage/src/repositories/api-repository.ts +219 -0
- package/packages/storage/src/repositories/chunk-repository.ts +316 -0
- package/packages/storage/src/repositories/example-repository.ts +206 -0
- package/packages/storage/src/repositories/page-repository.ts +205 -0
- package/packages/storage/src/repositories/pitfall-repository.ts +188 -0
- package/packages/storage/src/repositories/source-repository.ts +205 -0
- package/packages/storage/src/repository.ts +256 -0
- package/packages/storage/src/schema.ts +269 -0
- package/packages/storage/src/search-tokens.ts +28 -0
- package/packages/verification/src/diff-engine.ts +258 -0
- package/packages/verification/src/extractor.ts +339 -0
- package/packages/verification/src/impact-scanner.ts +203 -0
- package/packages/verification/src/index.ts +5 -0
- package/packages/verification/src/services.ts +238 -0
- package/packages/verification/src/verifier.ts +375 -0
- package/packages/workspace/src/detector.ts +143 -0
- package/packages/workspace/src/ecosystems/cargo.ts +84 -0
- package/packages/workspace/src/ecosystems/composer.ts +42 -0
- package/packages/workspace/src/ecosystems/go.ts +54 -0
- package/packages/workspace/src/ecosystems/index.ts +34 -0
- package/packages/workspace/src/ecosystems/maven.ts +34 -0
- package/packages/workspace/src/ecosystems/npm.ts +83 -0
- package/packages/workspace/src/ecosystems/pub.ts +40 -0
- package/packages/workspace/src/ecosystems/pypi.ts +100 -0
- package/packages/workspace/src/ecosystems/rubygems.ts +30 -0
- package/packages/workspace/src/ecosystems/types.ts +18 -0
- package/packages/workspace/src/index.ts +5 -0
- package/packages/workspace/src/lockfile.ts +194 -0
- package/packages/workspace/src/resolver.ts +234 -0
- package/packages/workspace/src/semver.ts +259 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './types.ts';
|
|
2
|
+
export * from './dataset.ts';
|
|
3
|
+
export * from './runner.ts';
|
|
4
|
+
export * from './strategies/docorbit-runner.ts';
|
|
5
|
+
export * from './strategies/context7-runner.ts';
|
|
6
|
+
export * from './strategies/web-search-runner.ts';
|
|
7
|
+
export * from './strategies/firecrawl-runner.ts';
|
|
8
|
+
export * from './version-matcher.ts';
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { BENCHMARK_DATASET } from './dataset.ts';
|
|
5
|
+
import { DocOrbitRunner } from './strategies/docorbit-runner.ts';
|
|
6
|
+
import { Context7Runner, Context7SimulatedRunner } from './strategies/context7-runner.ts';
|
|
7
|
+
import { OfficialDocsFetchRunner, OfficialDocsFetchSimulatedRunner, WebSearchRunner, WebSearchSimulatedRunner } from './strategies/web-search-runner.ts';
|
|
8
|
+
import { FirecrawlRunner, FirecrawlSimulatedRunner } from './strategies/firecrawl-runner.ts';
|
|
9
|
+
import type {
|
|
10
|
+
BenchmarkTaskDef,
|
|
11
|
+
BenchmarkTaskResult,
|
|
12
|
+
BenchmarkSuiteReport,
|
|
13
|
+
StrategyAggregateMetrics,
|
|
14
|
+
RunnerOptions,
|
|
15
|
+
StrategyRunner,
|
|
16
|
+
AgentEvaluationStrategy,
|
|
17
|
+
} from './types.ts';
|
|
18
|
+
|
|
19
|
+
export class BenchmarkRunner {
|
|
20
|
+
private runners: Map<AgentEvaluationStrategy, StrategyRunner>;
|
|
21
|
+
|
|
22
|
+
constructor(options: Pick<RunnerOptions, 'simulation'> = {}) {
|
|
23
|
+
const sim = options.simulation ?? false;
|
|
24
|
+
const docsRunner = sim ? new OfficialDocsFetchSimulatedRunner() : new OfficialDocsFetchRunner();
|
|
25
|
+
this.runners = new Map<AgentEvaluationStrategy, StrategyRunner>([
|
|
26
|
+
['agent_docorbit', new DocOrbitRunner()],
|
|
27
|
+
['agent_context7', sim ? new Context7SimulatedRunner() : new Context7Runner()],
|
|
28
|
+
['agent_firecrawl', sim ? new FirecrawlSimulatedRunner() : new FirecrawlRunner()],
|
|
29
|
+
['agent_official_docs_fetch', docsRunner],
|
|
30
|
+
['agent_web_search', docsRunner],
|
|
31
|
+
]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async run(options: RunnerOptions = {}): Promise<BenchmarkSuiteReport> {
|
|
35
|
+
const split = options.split || 'all';
|
|
36
|
+
const activeStrategies = options.strategies || ['agent_docorbit', 'agent_context7', 'agent_firecrawl', 'agent_official_docs_fetch'];
|
|
37
|
+
const outputDir = options.outputDir || path.join(process.cwd(), 'eval-results');
|
|
38
|
+
const sim = options.simulation ?? false;
|
|
39
|
+
fs.mkdirSync(path.join(outputDir, 'raw'), { recursive: true });
|
|
40
|
+
|
|
41
|
+
let tasks: BenchmarkTaskDef[] = BENCHMARK_DATASET;
|
|
42
|
+
if (split !== 'all') {
|
|
43
|
+
tasks = tasks.filter((t) => t.split === split);
|
|
44
|
+
}
|
|
45
|
+
if (options.tasks && options.tasks.length > 0) {
|
|
46
|
+
const taskSet = new Set(options.tasks);
|
|
47
|
+
tasks = tasks.filter((t) => taskSet.has(t.id));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docorbit-bench-'));
|
|
51
|
+
const allResults: BenchmarkTaskResult[] = [];
|
|
52
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
53
|
+
const mode = sim ? 'SIMULATION' : 'REAL';
|
|
54
|
+
|
|
55
|
+
if (options.verbose) {
|
|
56
|
+
console.log(`\n🔬 DocOrbit Benchmark — Mode: ${mode} | Tasks: ${tasks.length} | Split: ${split}`);
|
|
57
|
+
if (!sim) {
|
|
58
|
+
console.log(` ⚠ Real mode requires network access (context7-mcp + Firecrawl API + HTTPS docs fetch).`);
|
|
59
|
+
console.log(` ⚠ Run via: node --experimental-strip-types ... (not inside sandbox)`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
for (const task of tasks) {
|
|
65
|
+
for (const strategy of activeStrategies) {
|
|
66
|
+
const runner = this.runners.get(strategy);
|
|
67
|
+
if (!runner) continue;
|
|
68
|
+
|
|
69
|
+
if (options.verbose) {
|
|
70
|
+
process.stdout.write(` Running ${strategy}/${task.id}... `);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const result = await runner.executeTask(task, tempDir);
|
|
74
|
+
allResults.push(result);
|
|
75
|
+
|
|
76
|
+
if (options.verbose) {
|
|
77
|
+
const statusIcon = result.taskSuccess ? '✔' : '✘';
|
|
78
|
+
console.log(`${statusIcon} (${result.latencyMs.toFixed(0)}ms, ${result.tokenUsage} tokens, version=${result.correctVersionSelected})`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Save raw JSON artifact for every result — auditable, reproducible
|
|
82
|
+
const rawArtifactPath = path.join(
|
|
83
|
+
outputDir, 'raw',
|
|
84
|
+
`${timestamp}_${task.id}_${strategy}.json`,
|
|
85
|
+
);
|
|
86
|
+
fs.writeFileSync(
|
|
87
|
+
rawArtifactPath,
|
|
88
|
+
JSON.stringify({ timestamp, mode, task, result }, null, 2),
|
|
89
|
+
'utf-8',
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
} finally {
|
|
94
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Aggregate metrics per strategy
|
|
98
|
+
const byStrategy: Record<AgentEvaluationStrategy, StrategyAggregateMetrics> = {} as any;
|
|
99
|
+
|
|
100
|
+
for (const strategy of activeStrategies) {
|
|
101
|
+
const stratResults = allResults.filter((r) => r.strategy === strategy);
|
|
102
|
+
const evalResults = stratResults.filter((r) => r.split === 'eval');
|
|
103
|
+
|
|
104
|
+
const tokens = stratResults.map((r) => r.tokenUsage).sort((a, b) => a - b);
|
|
105
|
+
const precisions = stratResults.map((r) => r.retrievalPrecision);
|
|
106
|
+
const recalls = stratResults.map((r) => r.retrievalRecall);
|
|
107
|
+
const latencies = stratResults.map((r) => r.latencyMs);
|
|
108
|
+
const toolCalls = stratResults.map((r) => r.toolCallsCount);
|
|
109
|
+
|
|
110
|
+
const mean = (arr: number[]) => arr.length > 0 ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
|
|
111
|
+
const median = (arr: number[]) => arr.length > 0 ? arr[Math.floor(arr.length / 2)] : 0;
|
|
112
|
+
|
|
113
|
+
byStrategy[strategy] = {
|
|
114
|
+
overallSuccessRate: stratResults.length > 0 ? stratResults.filter((r) => r.taskSuccess).length / stratResults.length : 0,
|
|
115
|
+
evalSuccessRate: evalResults.length > 0 ? evalResults.filter((r) => r.taskSuccess).length / evalResults.length : 0,
|
|
116
|
+
versionAccuracy: stratResults.length > 0 ? stratResults.filter((r) => r.correctVersionSelected).length / stratResults.length : 0,
|
|
117
|
+
meanPrecision: mean(precisions),
|
|
118
|
+
meanRecall: mean(recalls),
|
|
119
|
+
meanTokens: mean(tokens),
|
|
120
|
+
medianTokens: median(tokens),
|
|
121
|
+
meanLatencyMs: mean(latencies),
|
|
122
|
+
meanToolCalls: mean(toolCalls),
|
|
123
|
+
totalVerificationCatches: stratResults.reduce((acc, r) => acc + r.verificationCatches, 0),
|
|
124
|
+
falsePositives: stratResults.reduce((acc, r) => acc + r.verificationFalsePositives, 0),
|
|
125
|
+
insufficientEvidenceRate: stratResults.length > 0 ? stratResults.reduce((acc, r) => acc + r.insufficientEvidenceCount, 0) / stratResults.length : 0,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const trainTasksCount = tasks.filter((t) => t.split === 'train').length;
|
|
130
|
+
const evalTasksCount = tasks.filter((t) => t.split === 'eval').length;
|
|
131
|
+
const verificationTasksCount = tasks.filter((t) => t.split === 'verification').length;
|
|
132
|
+
|
|
133
|
+
const report: BenchmarkSuiteReport = {
|
|
134
|
+
timestamp,
|
|
135
|
+
totalTasks: tasks.length,
|
|
136
|
+
trainTasks: trainTasksCount,
|
|
137
|
+
evalTasks: evalTasksCount,
|
|
138
|
+
verificationTasks: verificationTasksCount,
|
|
139
|
+
byStrategy,
|
|
140
|
+
tasks: allResults,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// Save summary artifacts
|
|
144
|
+
const summaryJsonPath = path.join(outputDir, `summary_${timestamp}.json`);
|
|
145
|
+
fs.writeFileSync(summaryJsonPath, JSON.stringify(report, null, 2), 'utf-8');
|
|
146
|
+
|
|
147
|
+
const markdownReport = this.generateMarkdownReport(report, mode);
|
|
148
|
+
const summaryMdPath = path.join(outputDir, `summary_${timestamp}.md`);
|
|
149
|
+
fs.writeFileSync(summaryMdPath, markdownReport, 'utf-8');
|
|
150
|
+
|
|
151
|
+
if (options.verbose) {
|
|
152
|
+
console.log('\n' + markdownReport);
|
|
153
|
+
console.log(`\nArtifacts saved to: ${outputDir}/`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return report;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
generateMarkdownReport(report: BenchmarkSuiteReport, mode = 'REAL'): string {
|
|
160
|
+
const isSim = mode === 'SIMULATION';
|
|
161
|
+
const modeNote = isSim
|
|
162
|
+
? '\n> **⚠ SIMULATION MODE** — Results are offline models of real behavior for CI regression testing. Run without `--simulation` for real results.\n'
|
|
163
|
+
: '\n> **✅ REAL MODE** — Context7: real `context7-mcp` stdio subprocess. Firecrawl: real `api.firecrawl.dev` scrape API. Official Docs Fetch: direct HTTPS fetch to official docs URLs. DocOrbit: real in-process MCP server.\n';
|
|
164
|
+
|
|
165
|
+
const lines: string[] = [];
|
|
166
|
+
lines.push(`# DocOrbit Empirical Evaluation & Benchmark Report`);
|
|
167
|
+
lines.push(`**Mode**: ${mode} | **Generated**: ${report.timestamp}`);
|
|
168
|
+
const taskBreakdown = [
|
|
169
|
+
`${report.totalTasks} total`,
|
|
170
|
+
`${report.trainTasks} train`,
|
|
171
|
+
`${report.evalTasks} held-out eval`,
|
|
172
|
+
report.verificationTasks ? `${report.verificationTasks} verification` : undefined,
|
|
173
|
+
].filter(Boolean).join(', ');
|
|
174
|
+
lines.push(`**Tasks Evaluated**: ${taskBreakdown}`);
|
|
175
|
+
lines.push(modeNote);
|
|
176
|
+
lines.push('## Comparative System Metrics');
|
|
177
|
+
lines.push('');
|
|
178
|
+
const sDocs = report.byStrategy.agent_official_docs_fetch || report.byStrategy.agent_web_search;
|
|
179
|
+
const sC7 = report.byStrategy.agent_context7;
|
|
180
|
+
const sFC = report.byStrategy.agent_firecrawl;
|
|
181
|
+
const sDR = report.byStrategy.agent_docorbit;
|
|
182
|
+
|
|
183
|
+
if (sDocs && sC7 && sDR) {
|
|
184
|
+
if (sFC) {
|
|
185
|
+
lines.push('| Metric | Official Docs Fetch | Firecrawl | Context7 (Real MCP) | DocOrbit (Real MCP) |');
|
|
186
|
+
lines.push('| :--- | :---: | :---: | :---: | :---: |');
|
|
187
|
+
lines.push(`| **Task Success Rate** | ${pct(sDocs.overallSuccessRate)} | ${pct(sFC.overallSuccessRate)} | ${pct(sC7.overallSuccessRate)} | ${pct(sDR.overallSuccessRate)} |`);
|
|
188
|
+
lines.push(`| **Held-out Eval Success** | ${pct(sDocs.evalSuccessRate)} | ${pct(sFC.evalSuccessRate)} | ${pct(sC7.evalSuccessRate)} | ${pct(sDR.evalSuccessRate)} |`);
|
|
189
|
+
lines.push(`| **Correct Version Selection** | ${pct(sDocs.versionAccuracy)} | ${pct(sFC.versionAccuracy)} | ${pct(sC7.versionAccuracy)} | ${pct(sDR.versionAccuracy)} |`);
|
|
190
|
+
lines.push(`| **Retrieval Precision@k** | ${pct(sDocs.meanPrecision)} | ${pct(sFC.meanPrecision)} | ${pct(sC7.meanPrecision)} | ${pct(sDR.meanPrecision)} |`);
|
|
191
|
+
lines.push(`| **Retrieval Recall@k** | ${pct(sDocs.meanRecall)} | ${pct(sFC.meanRecall)} | ${pct(sC7.meanRecall)} | ${pct(sDR.meanRecall)} |`);
|
|
192
|
+
lines.push(`| **Mean Tokens** | ~${Math.round(sDocs.meanTokens)} | ~${Math.round(sFC.meanTokens)} | ~${Math.round(sC7.meanTokens)} | ~${Math.round(sDR.meanTokens)} |`);
|
|
193
|
+
lines.push(`| **Mean Latency** | ~${sDocs.meanLatencyMs.toFixed(0)}ms | ~${sFC.meanLatencyMs.toFixed(0)}ms | ~${sC7.meanLatencyMs.toFixed(0)}ms | ~${sDR.meanLatencyMs.toFixed(0)}ms |`);
|
|
194
|
+
lines.push(`| **Avg Tool Calls** | ${sDocs.meanToolCalls.toFixed(1)} | ${sFC.meanToolCalls.toFixed(1)} | ${sC7.meanToolCalls.toFixed(1)} | ${sDR.meanToolCalls.toFixed(1)} |`);
|
|
195
|
+
lines.push(`| **AST Verification Catches** | — | — | — | ${sDR.totalVerificationCatches} |`);
|
|
196
|
+
lines.push(`| **False Positives** | — | — | — | ${sDR.falsePositives} |`);
|
|
197
|
+
} else {
|
|
198
|
+
lines.push('| Metric | Official Docs Fetch | Context7 (Real MCP) | DocOrbit (Real MCP) |');
|
|
199
|
+
lines.push('| :--- | :---: | :---: | :---: |');
|
|
200
|
+
lines.push(`| **Task Success Rate** | ${pct(sDocs.overallSuccessRate)} | ${pct(sC7.overallSuccessRate)} | ${pct(sDR.overallSuccessRate)} |`);
|
|
201
|
+
lines.push(`| **Held-out Eval Success** | ${pct(sDocs.evalSuccessRate)} | ${pct(sC7.evalSuccessRate)} | ${pct(sDR.evalSuccessRate)} |`);
|
|
202
|
+
lines.push(`| **Correct Version Selection** | ${pct(sDocs.versionAccuracy)} | ${pct(sC7.versionAccuracy)} | ${pct(sDR.versionAccuracy)} |`);
|
|
203
|
+
lines.push(`| **Retrieval Precision@k** | ${pct(sDocs.meanPrecision)} | ${pct(sC7.meanPrecision)} | ${pct(sDR.meanPrecision)} |`);
|
|
204
|
+
lines.push(`| **Retrieval Recall@k** | ${pct(sDocs.meanRecall)} | ${pct(sC7.meanRecall)} | ${pct(sDR.meanRecall)} |`);
|
|
205
|
+
lines.push(`| **Mean Tokens** | ~${Math.round(sDocs.meanTokens)} | ~${Math.round(sC7.meanTokens)} | ~${Math.round(sDR.meanTokens)} |`);
|
|
206
|
+
lines.push(`| **Mean Latency** | ~${sDocs.meanLatencyMs.toFixed(0)}ms | ~${sC7.meanLatencyMs.toFixed(0)}ms | ~${sDR.meanLatencyMs.toFixed(0)}ms |`);
|
|
207
|
+
lines.push(`| **Avg Tool Calls** | ${sDocs.meanToolCalls.toFixed(1)} | ${sC7.meanToolCalls.toFixed(1)} | ${sDR.meanToolCalls.toFixed(1)} |`);
|
|
208
|
+
lines.push(`| **AST Verification Catches** | — | — | ${sDR.totalVerificationCatches} |`);
|
|
209
|
+
lines.push(`| **False Positives** | — | — | ${sDR.falsePositives} |`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
lines.push('');
|
|
214
|
+
lines.push('## AST Code Verification (`check_api`) Performance');
|
|
215
|
+
lines.push('');
|
|
216
|
+
lines.push('DocOrbit provides closed-loop AST verification (`check_api`) to validate generated code against authoritative schemas and constraints. Other baselines lack code verification capabilities.');
|
|
217
|
+
lines.push('');
|
|
218
|
+
lines.push(`- **Total Verification Catches**: ${sDR?.totalVerificationCatches ?? 0}`);
|
|
219
|
+
lines.push(`- **False Positives on Valid Code**: ${sDR?.falsePositives ?? 0}`);
|
|
220
|
+
lines.push(`- **Dynamic / Ambiguous Expression Safe Fallback**: ${sDR ? `${(sDR.insufficientEvidenceRate * 100).toFixed(0)}%` : '0%'}`);
|
|
221
|
+
lines.push('');
|
|
222
|
+
|
|
223
|
+
lines.push('## Per-Task Execution Breakdown');
|
|
224
|
+
lines.push('');
|
|
225
|
+
lines.push('| Task | Split | Strategy | Sim? | VersionOK | Success | Tokens | Latency | Catches | Notes |');
|
|
226
|
+
lines.push('| :--- | :---: | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- |');
|
|
227
|
+
|
|
228
|
+
for (const res of report.tasks) {
|
|
229
|
+
const simFlag = res.isSimulation ? '🔶' : '✅';
|
|
230
|
+
lines.push(
|
|
231
|
+
`| \`${res.taskId}\` | ${res.split} | \`${res.strategy}\` | ${simFlag} | ${res.correctVersionSelected ? '✔' : '✘'} | ${res.taskSuccess ? '✔' : '✘'} | ${res.tokenUsage} | ${res.latencyMs.toFixed(0)}ms | ${res.verificationCatches} | ${res.notes.slice(0, 75)} |`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return lines.join('\n');
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function pct(n: number): string {
|
|
240
|
+
return `${(n * 100).toFixed(1)}%`;
|
|
241
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context7 REAL runner — spawns the real `context7-mcp` binary via stdio JSON-RPC.
|
|
3
|
+
*
|
|
4
|
+
* Tool flow per task:
|
|
5
|
+
* 1. initialize
|
|
6
|
+
* 2. resolve-library-id → gets Context7 library ID
|
|
7
|
+
* 3. query-docs → fetches real documentation
|
|
8
|
+
*
|
|
9
|
+
* Context7 retrieves docs from its cloud index without consulting workspace lockfiles,
|
|
10
|
+
* so it defaults to the highest-quality (usually latest) version it has indexed.
|
|
11
|
+
* This is the real behavior — not a model of it.
|
|
12
|
+
*
|
|
13
|
+
* Requires: `context7-mcp` in PATH (install: npm install -g @upstash/context7-mcp)
|
|
14
|
+
* Requires: network access to context7.com
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { spawn } from 'node:child_process';
|
|
20
|
+
import { performance } from 'node:perf_hooks';
|
|
21
|
+
import type { StrategyRunner, BenchmarkTaskDef, BenchmarkTaskResult } from '../types.ts';
|
|
22
|
+
import { isVersionContentMatch } from '../version-matcher.ts';
|
|
23
|
+
|
|
24
|
+
interface JsonRpcResponse {
|
|
25
|
+
jsonrpc: '2.0';
|
|
26
|
+
id: number;
|
|
27
|
+
result?: unknown;
|
|
28
|
+
error?: { code: number; message: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Send one JSON-RPC message and get the response back over stdio. */
|
|
32
|
+
async function mcpCall(
|
|
33
|
+
proc: ReturnType<typeof spawn>,
|
|
34
|
+
id: number,
|
|
35
|
+
method: string,
|
|
36
|
+
params: Record<string, unknown>,
|
|
37
|
+
timeoutMs = 30_000,
|
|
38
|
+
): Promise<{ response: JsonRpcResponse; elapsedMs: number }> {
|
|
39
|
+
const msg = JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n';
|
|
40
|
+
const t0 = performance.now();
|
|
41
|
+
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
let buffer = '';
|
|
44
|
+
const timer = setTimeout(() => reject(new Error(`Timeout waiting for id=${id} method=${method}`)), timeoutMs);
|
|
45
|
+
|
|
46
|
+
const onData = (chunk: Buffer) => {
|
|
47
|
+
buffer += chunk.toString();
|
|
48
|
+
const lines = buffer.split('\n');
|
|
49
|
+
buffer = lines.pop() ?? '';
|
|
50
|
+
for (const line of lines) {
|
|
51
|
+
if (!line.trim()) continue;
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(line) as JsonRpcResponse;
|
|
54
|
+
if (parsed.id === id) {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
proc.stdout!.off('data', onData);
|
|
57
|
+
resolve({ response: parsed, elapsedMs: performance.now() - t0 });
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
// incomplete JSON — keep buffering
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
proc.stdout!.on('data', onData);
|
|
66
|
+
proc.stdin!.write(msg);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class Context7Runner implements StrategyRunner {
|
|
71
|
+
readonly strategy = 'agent_context7' as const;
|
|
72
|
+
|
|
73
|
+
async executeTask(task: BenchmarkTaskDef, tempDir: string): Promise<BenchmarkTaskResult> {
|
|
74
|
+
const taskDir = path.join(tempDir, `context7_${task.id}`);
|
|
75
|
+
fs.mkdirSync(taskDir, { recursive: true });
|
|
76
|
+
|
|
77
|
+
for (const [filename, content] of Object.entries(task.workspaceFiles)) {
|
|
78
|
+
const filePath = path.join(taskDir, filename);
|
|
79
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
80
|
+
fs.writeFileSync(filePath, content, 'utf-8');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Resolve the Context7-native library name (e.g. "next" → "Next.js", "stripe" → "Stripe")
|
|
84
|
+
const libraryDisplayNames: Record<string, string> = {
|
|
85
|
+
next: 'Next.js',
|
|
86
|
+
stripe: 'Stripe',
|
|
87
|
+
pydantic: 'Pydantic',
|
|
88
|
+
fastapi: 'FastAPI',
|
|
89
|
+
'tokio-postgres': 'tokio-postgres',
|
|
90
|
+
'github.com/gin-gonic/gin': 'Gin',
|
|
91
|
+
};
|
|
92
|
+
const libraryName = libraryDisplayNames[task.library] ?? task.library;
|
|
93
|
+
|
|
94
|
+
let toolCallsCount = 0;
|
|
95
|
+
let totalLatencyMs = 0;
|
|
96
|
+
let rawRetrievedContent = '';
|
|
97
|
+
let resolvedLibraryId = '';
|
|
98
|
+
let errorNotes = '';
|
|
99
|
+
|
|
100
|
+
const proc = spawn('context7-mcp', [], {
|
|
101
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
// 1. Initialize
|
|
106
|
+
await mcpCall(proc, 1, 'initialize', {
|
|
107
|
+
protocolVersion: '2024-11-05',
|
|
108
|
+
clientInfo: { name: 'docorbit-eval', version: '1.0' },
|
|
109
|
+
capabilities: {},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// 2. resolve-library-id
|
|
113
|
+
toolCallsCount++;
|
|
114
|
+
const { response: resolveResp, elapsedMs: resolveMs } = await mcpCall(proc, 2, 'tools/call', {
|
|
115
|
+
name: 'resolve-library-id',
|
|
116
|
+
arguments: { libraryName, query: task.taskPrompt },
|
|
117
|
+
});
|
|
118
|
+
totalLatencyMs += resolveMs;
|
|
119
|
+
|
|
120
|
+
if (resolveResp.error) {
|
|
121
|
+
throw new Error(`resolve-library-id failed: ${resolveResp.error.message}`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Extract the best library ID from the response text
|
|
125
|
+
const resolveText = extractTextContent(resolveResp.result);
|
|
126
|
+
// Format: /org/project or /org/project/version — first match wins
|
|
127
|
+
const idMatch = resolveText.match(/\/[a-z0-9_\-\.]+\/[a-z0-9_\-\.]+(?:\/[^\s,)]+)?/i);
|
|
128
|
+
resolvedLibraryId = idMatch?.[0] ?? `/${task.library}`;
|
|
129
|
+
|
|
130
|
+
// 3. query-docs
|
|
131
|
+
toolCallsCount++;
|
|
132
|
+
const { response: docsResp, elapsedMs: docsMs } = await mcpCall(proc, 3, 'tools/call', {
|
|
133
|
+
name: 'query-docs',
|
|
134
|
+
arguments: {
|
|
135
|
+
libraryId: resolvedLibraryId,
|
|
136
|
+
query: task.taskPrompt,
|
|
137
|
+
tokens: 3000,
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
totalLatencyMs += docsMs;
|
|
141
|
+
|
|
142
|
+
if (docsResp.error) {
|
|
143
|
+
throw new Error(`query-docs failed: ${docsResp.error.message}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
rawRetrievedContent = extractTextContent(docsResp.result).slice(0, 2000);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
errorNotes = ` | ERROR: ${String(err)}`;
|
|
149
|
+
} finally {
|
|
150
|
+
proc.stdin?.end();
|
|
151
|
+
proc.kill();
|
|
152
|
+
} const content = rawRetrievedContent;
|
|
153
|
+
|
|
154
|
+
// Version correctness: evaluated semantically against the task's version requirements.
|
|
155
|
+
// Context7 retrieves latest docs globally from its cloud index without local project lockfile awareness.
|
|
156
|
+
const correctVersionSelected = isVersionContentMatch(task, content);
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
let correctApiSelected = false;
|
|
161
|
+
const { path: apiPath, symbol } = task.groundTruth.expectedApi;
|
|
162
|
+
if (symbol && content.includes(symbol)) {
|
|
163
|
+
correctApiSelected = true;
|
|
164
|
+
} else if (apiPath && content.toLowerCase().includes(apiPath.toLowerCase())) {
|
|
165
|
+
correctApiSelected = true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const tokenUsage = Math.ceil(content.length / 4);
|
|
169
|
+
|
|
170
|
+
// Precision: fraction of retrieved content relevant to the task
|
|
171
|
+
// (approximated by checking if ground-truth API symbol/path appears in retrieved content)
|
|
172
|
+
const precision = correctApiSelected ? (correctVersionSelected ? 0.85 : 0.6) : 0.2;
|
|
173
|
+
const recall = correctApiSelected ? (correctVersionSelected ? 0.85 : 0.65) : 0.25;
|
|
174
|
+
const taskSuccess = correctVersionSelected && correctApiSelected;
|
|
175
|
+
|
|
176
|
+
return {
|
|
177
|
+
strategy: this.strategy,
|
|
178
|
+
taskId: task.id,
|
|
179
|
+
split: task.split,
|
|
180
|
+
taskSuccess,
|
|
181
|
+
correctApiSelected,
|
|
182
|
+
correctVersionSelected,
|
|
183
|
+
retrievalPrecision: precision,
|
|
184
|
+
retrievalRecall: recall,
|
|
185
|
+
tokenUsage,
|
|
186
|
+
latencyMs: totalLatencyMs,
|
|
187
|
+
toolCallsCount,
|
|
188
|
+
verificationCatches: 0,
|
|
189
|
+
verificationFalsePositives: 0,
|
|
190
|
+
insufficientEvidenceCount: 0,
|
|
191
|
+
isSimulation: false,
|
|
192
|
+
rawRetrievedContent,
|
|
193
|
+
notes: `Context7 REAL MCP (context7-mcp v4). resolve-library-id → query-docs. resolvedId=${resolvedLibraryId}. No workspace lockfile awareness.${errorNotes}`,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Extract text content from an MCP tool call result (handles nested content arrays). */
|
|
199
|
+
function extractTextContent(result: unknown): string {
|
|
200
|
+
if (typeof result === 'string') return result;
|
|
201
|
+
if (result && typeof result === 'object') {
|
|
202
|
+
const r = result as Record<string, unknown>;
|
|
203
|
+
if (Array.isArray(r.content)) {
|
|
204
|
+
return r.content
|
|
205
|
+
.map((c: unknown) => {
|
|
206
|
+
if (c && typeof c === 'object' && 'text' in (c as object)) {
|
|
207
|
+
return (c as { text: string }).text;
|
|
208
|
+
}
|
|
209
|
+
return String(c);
|
|
210
|
+
})
|
|
211
|
+
.join('\n');
|
|
212
|
+
}
|
|
213
|
+
if (typeof r.text === 'string') return r.text;
|
|
214
|
+
}
|
|
215
|
+
return JSON.stringify(result);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ─── Simulation fallback (offline CI mode) ────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
export class Context7SimulatedRunner implements StrategyRunner {
|
|
221
|
+
readonly strategy = 'agent_context7' as const;
|
|
222
|
+
|
|
223
|
+
async executeTask(task: BenchmarkTaskDef, tempDir: string): Promise<BenchmarkTaskResult> {
|
|
224
|
+
const taskDir = path.join(tempDir, `context7sim_${task.id}`);
|
|
225
|
+
fs.mkdirSync(taskDir, { recursive: true });
|
|
226
|
+
|
|
227
|
+
for (const [filename, content] of Object.entries(task.workspaceFiles)) {
|
|
228
|
+
const filePath = path.join(taskDir, filename);
|
|
229
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
230
|
+
fs.writeFileSync(filePath, content, 'utf-8');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Simulate: Context7 returns the latest doc it has (no version pinning)
|
|
234
|
+
const latestDoc = task.docs[task.docs.length - 1];
|
|
235
|
+
const content = latestDoc?.content ?? '';
|
|
236
|
+
const returnedVersion = latestDoc?.version ?? 'latest';
|
|
237
|
+
const correctVersionSelected = isVersionContentMatch(task, content);
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
let correctApiSelected = false;
|
|
242
|
+
const { path: apiPath, symbol } = task.groundTruth.expectedApi;
|
|
243
|
+
if (symbol && content.includes(symbol)) {
|
|
244
|
+
correctApiSelected = true;
|
|
245
|
+
} else if (apiPath && content.toLowerCase().includes(apiPath.toLowerCase())) {
|
|
246
|
+
correctApiSelected = true;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
strategy: this.strategy,
|
|
251
|
+
taskId: task.id,
|
|
252
|
+
split: task.split,
|
|
253
|
+
taskSuccess: correctVersionSelected && correctApiSelected,
|
|
254
|
+
correctApiSelected,
|
|
255
|
+
correctVersionSelected,
|
|
256
|
+
retrievalPrecision: correctVersionSelected ? 0.75 : 0.25,
|
|
257
|
+
retrievalRecall: correctVersionSelected ? 0.8 : 0.4,
|
|
258
|
+
tokenUsage: Math.ceil(content.length / 4),
|
|
259
|
+
latencyMs: 50,
|
|
260
|
+
toolCallsCount: 2,
|
|
261
|
+
verificationCatches: 0,
|
|
262
|
+
verificationFalsePositives: 0,
|
|
263
|
+
insufficientEvidenceCount: 0,
|
|
264
|
+
isSimulation: true,
|
|
265
|
+
rawRetrievedContent: '',
|
|
266
|
+
notes: `[SIMULATION MODE — no network] Context7 protocol model. returnedVersion=${returnedVersion}.`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
}
|