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,455 @@
|
|
|
1
|
+
import {
|
|
2
|
+
computeSha256,
|
|
3
|
+
computeContentHash,
|
|
4
|
+
estimateTokenCount,
|
|
5
|
+
} from '../../shared/src/index.ts';
|
|
6
|
+
import type {
|
|
7
|
+
NormalizedPage,
|
|
8
|
+
DocumentChunk,
|
|
9
|
+
ChunkType,
|
|
10
|
+
ChunkCode,
|
|
11
|
+
SymbolReference,
|
|
12
|
+
ChunkRelationship,
|
|
13
|
+
ChunkingConfig,
|
|
14
|
+
Provenance,
|
|
15
|
+
} from '../../shared/src/index.ts';
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_CHUNKING_CONFIG: ChunkingConfig = {
|
|
18
|
+
targetTokens: 500,
|
|
19
|
+
maxTokens: 1000,
|
|
20
|
+
overlapTokens: 50,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface SlicingResult {
|
|
24
|
+
chunks: DocumentChunk[];
|
|
25
|
+
relationships: ChunkRelationship[];
|
|
26
|
+
codeSnippets: ChunkCode[];
|
|
27
|
+
symbols: SymbolReference[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface RawBlock {
|
|
31
|
+
type: 'heading' | 'code' | 'warning' | 'prose';
|
|
32
|
+
headingLevel?: number;
|
|
33
|
+
headingText?: string;
|
|
34
|
+
language?: string;
|
|
35
|
+
content: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface Section {
|
|
39
|
+
headingLevel: number;
|
|
40
|
+
headingText: string;
|
|
41
|
+
sectionPath: string[];
|
|
42
|
+
blocks: RawBlock[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Parses markdown into atomic blocks: headings, code fences, warnings/admonitions, and prose.
|
|
47
|
+
* Guarantees code fences and warnings are kept as atomic units that are never fractured.
|
|
48
|
+
*/
|
|
49
|
+
function parseAtomicBlocks(markdown: string): RawBlock[] {
|
|
50
|
+
const lines = markdown.split('\n');
|
|
51
|
+
const blocks: RawBlock[] = [];
|
|
52
|
+
let currentProseLines: string[] = [];
|
|
53
|
+
|
|
54
|
+
const flushProse = () => {
|
|
55
|
+
if (currentProseLines.length > 0) {
|
|
56
|
+
const text = currentProseLines.join('\n').trim();
|
|
57
|
+
if (text) {
|
|
58
|
+
blocks.push({ type: 'prose', content: text });
|
|
59
|
+
}
|
|
60
|
+
currentProseLines = [];
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
let i = 0;
|
|
65
|
+
while (i < lines.length) {
|
|
66
|
+
const line = lines[i];
|
|
67
|
+
|
|
68
|
+
// Check for code fence start
|
|
69
|
+
const codeMatch = line.match(/^```([a-zA-Z0-9_-]*)/);
|
|
70
|
+
if (codeMatch) {
|
|
71
|
+
flushProse();
|
|
72
|
+
const lang = codeMatch[1].trim() || 'text';
|
|
73
|
+
const codeLines: string[] = [line];
|
|
74
|
+
i++;
|
|
75
|
+
while (i < lines.length) {
|
|
76
|
+
codeLines.push(lines[i]);
|
|
77
|
+
if (lines[i].trim().startsWith('```')) {
|
|
78
|
+
i++;
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
blocks.push({
|
|
84
|
+
type: 'code',
|
|
85
|
+
language: lang,
|
|
86
|
+
content: codeLines.join('\n'),
|
|
87
|
+
});
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Check for heading outside code fence
|
|
92
|
+
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
|
|
93
|
+
if (headingMatch) {
|
|
94
|
+
flushProse();
|
|
95
|
+
const level = headingMatch[1].length;
|
|
96
|
+
const text = headingMatch[2].trim();
|
|
97
|
+
blocks.push({
|
|
98
|
+
type: 'heading',
|
|
99
|
+
headingLevel: level,
|
|
100
|
+
headingText: text,
|
|
101
|
+
content: line,
|
|
102
|
+
});
|
|
103
|
+
i++;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Check for admonition / warning blockquote (> [!NOTE], > [!WARNING], > Note:, > Warning:)
|
|
108
|
+
if (/^>\s*(\[!?(NOTE|WARNING|IMPORTANT|CAUTION|TIP)\]|Note:|Warning:|Caution:|Important:)/i.test(line)) {
|
|
109
|
+
flushProse();
|
|
110
|
+
const warningLines: string[] = [line];
|
|
111
|
+
i++;
|
|
112
|
+
while (i < lines.length && (lines[i].startsWith('>') || lines[i].trim() === '')) {
|
|
113
|
+
warningLines.push(lines[i]);
|
|
114
|
+
i++;
|
|
115
|
+
}
|
|
116
|
+
blocks.push({
|
|
117
|
+
type: 'warning',
|
|
118
|
+
content: warningLines.join('\n').trim(),
|
|
119
|
+
});
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Empty line separates paragraphs
|
|
124
|
+
if (line.trim() === '') {
|
|
125
|
+
flushProse();
|
|
126
|
+
i++;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Regular prose line within paragraph
|
|
131
|
+
currentProseLines.push(line);
|
|
132
|
+
i++;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
flushProse();
|
|
136
|
+
return blocks;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Groups atomic blocks into hierarchical sections tracking heading breadcrumbs.
|
|
142
|
+
*/
|
|
143
|
+
function groupIntoSections(blocks: RawBlock[], defaultTitle: string): Section[] {
|
|
144
|
+
const sections: Section[] = [];
|
|
145
|
+
const headingStack: Array<{ level: number; text: string }> = [];
|
|
146
|
+
|
|
147
|
+
let currentSection: Section = {
|
|
148
|
+
headingLevel: 1,
|
|
149
|
+
headingText: defaultTitle,
|
|
150
|
+
sectionPath: [defaultTitle],
|
|
151
|
+
blocks: [],
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
for (const block of blocks) {
|
|
155
|
+
if (block.type === 'heading') {
|
|
156
|
+
if (currentSection.blocks.length > 0) {
|
|
157
|
+
sections.push(currentSection);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const level = block.headingLevel || 1;
|
|
161
|
+
const text = block.headingText || defaultTitle;
|
|
162
|
+
|
|
163
|
+
while (headingStack.length > 0 && headingStack[headingStack.length - 1].level >= level) {
|
|
164
|
+
headingStack.pop();
|
|
165
|
+
}
|
|
166
|
+
headingStack.push({ level, text });
|
|
167
|
+
|
|
168
|
+
currentSection = {
|
|
169
|
+
headingLevel: level,
|
|
170
|
+
headingText: text,
|
|
171
|
+
sectionPath: headingStack.map(h => h.text),
|
|
172
|
+
blocks: [],
|
|
173
|
+
};
|
|
174
|
+
} else {
|
|
175
|
+
currentSection.blocks.push(block);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (currentSection.blocks.length > 0 || sections.length === 0) {
|
|
180
|
+
sections.push(currentSection);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return sections;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Shallow, deterministic symbol extractor using lightweight regex patterns.
|
|
188
|
+
* No external AST parsers or language runtimes.
|
|
189
|
+
*/
|
|
190
|
+
export function extractSymbols(content: string, chunkId: string): SymbolReference[] {
|
|
191
|
+
const symbols: SymbolReference[] = [];
|
|
192
|
+
const seen = new Set<string>();
|
|
193
|
+
|
|
194
|
+
const addSymbol = (name: string, kind: SymbolReference['kind']) => {
|
|
195
|
+
const clean = name.trim();
|
|
196
|
+
if (clean && !seen.has(clean) && clean.length > 1 && clean.length < 80) {
|
|
197
|
+
seen.add(clean);
|
|
198
|
+
symbols.push({
|
|
199
|
+
id: `sym_${chunkId}_${symbols.length + 1}`,
|
|
200
|
+
chunkId,
|
|
201
|
+
name: clean,
|
|
202
|
+
kind,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// 1. REST API endpoints: (GET|POST|PUT|DELETE|PATCH) /path
|
|
208
|
+
const endpointRegex = /\b(GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD)\s+([/][a-zA-Z0-9_{}/:.-]+)/g;
|
|
209
|
+
let match: RegExpExecArray | null;
|
|
210
|
+
while ((match = endpointRegex.exec(content)) !== null) {
|
|
211
|
+
addSymbol(`${match[1]} ${match[2]}`, 'endpoint');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// 2. Functions: function foo(...), def foo(...), fn foo(...), func foo(...)
|
|
215
|
+
const funcRegex = /\b(?:function|def|func|fn)\s+([a-zA-Z0-9_$]+)\s*\(/g;
|
|
216
|
+
while ((match = funcRegex.exec(content)) !== null) {
|
|
217
|
+
addSymbol(match[1], 'function');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// 3. Arrow function assignments: const foo = (...) => or const foo = async (...) =>
|
|
221
|
+
const arrowRegex = /\b(?:const|let|var)\s+([a-zA-Z0-9_$]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>/g;
|
|
222
|
+
while ((match = arrowRegex.exec(content)) !== null) {
|
|
223
|
+
addSymbol(match[1], 'function');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 4. Classes and interfaces: class Foo, interface Bar, struct Baz, type Qux =
|
|
227
|
+
const classRegex = /\b(?:class|interface|struct|enum)\s+([a-zA-Z0-9_$]+)/g;
|
|
228
|
+
while ((match = classRegex.exec(content)) !== null) {
|
|
229
|
+
addSymbol(match[1], match[0].startsWith('class') ? 'class' : 'interface');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const typeRegex = /\btype\s+([A-Z][a-zA-Z0-9_$]*)\s*=/g;
|
|
233
|
+
while ((match = typeRegex.exec(content)) !== null) {
|
|
234
|
+
addSymbol(match[1], 'type');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 5. Common config keys (YAML/JSON): key: value or "key":
|
|
238
|
+
const configRegex = /^[ \t]*([a-zA-Z0-9_.-]{3,30})\s*:\s*[^\s]/gm;
|
|
239
|
+
while ((match = configRegex.exec(content)) !== null) {
|
|
240
|
+
if (!['http', 'https', 'note', 'warning', 'tip', 'important', 'version'].includes(match[1].toLowerCase())) {
|
|
241
|
+
addSymbol(match[1], 'config');
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return symbols;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Detects chunk type based on block composition and content.
|
|
250
|
+
*/
|
|
251
|
+
export function detectChunkType(blocks: RawBlock[], content: string): ChunkType {
|
|
252
|
+
const hasWarning = blocks.some(b => b.type === 'warning') || />\s*\[!(WARNING|CAUTION|IMPORTANT)\]/i.test(content);
|
|
253
|
+
const codeBlocks = blocks.filter(b => b.type === 'code');
|
|
254
|
+
const hasEndpoint = /\b(GET|POST|PUT|DELETE|PATCH)\s+[/]/.test(content);
|
|
255
|
+
|
|
256
|
+
if (hasEndpoint) {
|
|
257
|
+
return 'api';
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (hasWarning && blocks.length <= 2) {
|
|
261
|
+
return 'warning';
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (codeBlocks.length > 0 && blocks.every(b => b.type === 'code' || b.type === 'heading')) {
|
|
265
|
+
return 'code';
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (codeBlocks.length > 0 && content.toLowerCase().includes('example')) {
|
|
269
|
+
return 'example';
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (codeBlocks.length > 0) {
|
|
273
|
+
return 'mixed';
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return 'prose';
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Slices a NormalizedPage into standalone, context-preserving DocumentChunks,
|
|
281
|
+
* maintaining section breadcrumbs, relationship links, code snippets, and symbols.
|
|
282
|
+
*/
|
|
283
|
+
export function slicePageIntoChunks(
|
|
284
|
+
page: NormalizedPage,
|
|
285
|
+
snapshotId: string,
|
|
286
|
+
config: ChunkingConfig = DEFAULT_CHUNKING_CONFIG
|
|
287
|
+
): SlicingResult {
|
|
288
|
+
const atomicBlocks = parseAtomicBlocks(page.content);
|
|
289
|
+
const sections = groupIntoSections(atomicBlocks, page.title);
|
|
290
|
+
|
|
291
|
+
const chunks: DocumentChunk[] = [];
|
|
292
|
+
const relationships: ChunkRelationship[] = [];
|
|
293
|
+
const codeSnippets: ChunkCode[] = [];
|
|
294
|
+
const symbols: SymbolReference[] = [];
|
|
295
|
+
|
|
296
|
+
const provenance: Provenance = page.provenance || {
|
|
297
|
+
sourceUrl: page.url,
|
|
298
|
+
targetUrl: page.url,
|
|
299
|
+
fetchedAt: page.fetchedAt,
|
|
300
|
+
discoveredBy: 'direct',
|
|
301
|
+
contentHash: page.contentHash,
|
|
302
|
+
snapshotId,
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
let globalOrdinal = 0;
|
|
306
|
+
const sectionRootChunkIds = new Map<string, string>();
|
|
307
|
+
|
|
308
|
+
for (const section of sections) {
|
|
309
|
+
const sectionTitle = section.headingText;
|
|
310
|
+
const sectionPathKey = section.sectionPath.join(' > ');
|
|
311
|
+
|
|
312
|
+
if (section.blocks.length === 0) continue;
|
|
313
|
+
|
|
314
|
+
const fullSectionText = section.blocks.map(b => b.content).join('\n\n');
|
|
315
|
+
const estimatedTokens = estimateTokenCount(fullSectionText);
|
|
316
|
+
|
|
317
|
+
let chunkBlockGroups: RawBlock[][] = [];
|
|
318
|
+
|
|
319
|
+
if (estimatedTokens <= config.maxTokens) {
|
|
320
|
+
chunkBlockGroups.push(section.blocks);
|
|
321
|
+
} else {
|
|
322
|
+
// Secondary splitting: split on atomic block boundaries
|
|
323
|
+
let currentGroup: RawBlock[] = [];
|
|
324
|
+
let currentTokens = 0;
|
|
325
|
+
|
|
326
|
+
for (let i = 0; i < section.blocks.length; i++) {
|
|
327
|
+
const block = section.blocks[i];
|
|
328
|
+
const blockTokens = estimateTokenCount(block.content);
|
|
329
|
+
const isWarning = block.type === 'warning';
|
|
330
|
+
|
|
331
|
+
if (currentGroup.length > 0 && (currentTokens + blockTokens > config.targetTokens) && !isWarning) {
|
|
332
|
+
chunkBlockGroups.push(currentGroup);
|
|
333
|
+
currentGroup = [block];
|
|
334
|
+
currentTokens = blockTokens;
|
|
335
|
+
} else {
|
|
336
|
+
currentGroup.push(block);
|
|
337
|
+
currentTokens += blockTokens;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (currentGroup.length > 0) {
|
|
342
|
+
chunkBlockGroups.push(currentGroup);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
let parentChunkId: string | undefined;
|
|
347
|
+
|
|
348
|
+
for (let gIdx = 0; gIdx < chunkBlockGroups.length; gIdx++) {
|
|
349
|
+
const group = chunkBlockGroups[gIdx];
|
|
350
|
+
const chunkContent = group.map(b => b.content).join('\n\n');
|
|
351
|
+
const chunkType = detectChunkType(group, chunkContent);
|
|
352
|
+
const codeBlock = group.find(b => b.type === 'code');
|
|
353
|
+
const dominantLanguage = codeBlock?.language;
|
|
354
|
+
|
|
355
|
+
const chunkHash = computeContentHash(chunkContent);
|
|
356
|
+
const chunkId = `chk_${computeSha256(`${page.id}:${globalOrdinal}:${chunkHash}`).slice(0, 16)}`;
|
|
357
|
+
const tokenEst = estimateTokenCount(chunkContent);
|
|
358
|
+
|
|
359
|
+
const chunk: DocumentChunk = {
|
|
360
|
+
id: chunkId,
|
|
361
|
+
pageId: page.id,
|
|
362
|
+
snapshotId,
|
|
363
|
+
title: sectionTitle,
|
|
364
|
+
sectionPath: [...section.sectionPath],
|
|
365
|
+
content: chunkContent,
|
|
366
|
+
chunkType,
|
|
367
|
+
language: dominantLanguage,
|
|
368
|
+
tokenEstimate: tokenEst,
|
|
369
|
+
ordinal: globalOrdinal,
|
|
370
|
+
contentHash: chunkHash,
|
|
371
|
+
provenance,
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
chunks.push(chunk);
|
|
375
|
+
|
|
376
|
+
if (gIdx === 0) {
|
|
377
|
+
parentChunkId = chunkId;
|
|
378
|
+
sectionRootChunkIds.set(sectionPathKey, chunkId);
|
|
379
|
+
|
|
380
|
+
if (section.sectionPath.length > 1) {
|
|
381
|
+
const parentPathKey = section.sectionPath.slice(0, -1).join(' > ');
|
|
382
|
+
const ancestorId = sectionRootChunkIds.get(parentPathKey);
|
|
383
|
+
if (ancestorId && ancestorId !== chunkId) {
|
|
384
|
+
relationships.push({
|
|
385
|
+
sourceChunkId: chunkId,
|
|
386
|
+
targetChunkId: ancestorId,
|
|
387
|
+
type: 'parent_section',
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} else if (parentChunkId) {
|
|
392
|
+
relationships.push({
|
|
393
|
+
sourceChunkId: chunkId,
|
|
394
|
+
targetChunkId: parentChunkId,
|
|
395
|
+
type: 'parent_section',
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (globalOrdinal > 0) {
|
|
400
|
+
const prevChunk = chunks[chunks.length - 2];
|
|
401
|
+
relationships.push({
|
|
402
|
+
sourceChunkId: prevChunk.id,
|
|
403
|
+
targetChunkId: chunkId,
|
|
404
|
+
type: 'next_chunk',
|
|
405
|
+
});
|
|
406
|
+
relationships.push({
|
|
407
|
+
sourceChunkId: chunkId,
|
|
408
|
+
targetChunkId: prevChunk.id,
|
|
409
|
+
type: 'previous_chunk',
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
if (prevChunk.chunkType === 'prose' && (chunkType === 'code' || chunkType === 'example')) {
|
|
413
|
+
relationships.push({
|
|
414
|
+
sourceChunkId: prevChunk.id,
|
|
415
|
+
targetChunkId: chunkId,
|
|
416
|
+
type: 'explains_code',
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Extract code snippets
|
|
422
|
+
for (const b of group) {
|
|
423
|
+
if (b.type === 'code') {
|
|
424
|
+
const codeSnippetId = `code_${chunkId}_${codeSnippets.length + 1}`;
|
|
425
|
+
codeSnippets.push({
|
|
426
|
+
id: codeSnippetId,
|
|
427
|
+
chunkId,
|
|
428
|
+
language: b.language,
|
|
429
|
+
code: b.content.replace(/^```[a-zA-Z0-9_-]*\n/, '').replace(/\n```$/, ''),
|
|
430
|
+
});
|
|
431
|
+
relationships.push({
|
|
432
|
+
sourceChunkId: chunkId,
|
|
433
|
+
targetChunkId: codeSnippetId,
|
|
434
|
+
type: 'contains_code',
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Extract symbols
|
|
440
|
+
const chunkSymbols = extractSymbols(chunkContent, chunkId);
|
|
441
|
+
for (const sym of chunkSymbols) {
|
|
442
|
+
symbols.push(sym);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
globalOrdinal++;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return {
|
|
450
|
+
chunks,
|
|
451
|
+
relationships,
|
|
452
|
+
codeSnippets,
|
|
453
|
+
symbols,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
SearchResult,
|
|
3
|
+
SearchOptions,
|
|
4
|
+
ContextPackage,
|
|
5
|
+
ContextOptions,
|
|
6
|
+
ScoringWeights,
|
|
7
|
+
SourceAuthority,
|
|
8
|
+
} from '../../shared/src/index.ts';
|
|
9
|
+
import { DocOrbitRepository } from '../../storage/src/index.ts';
|
|
10
|
+
import { resolveScoringWeights } from './weights.ts';
|
|
11
|
+
import { detectQueryIntent } from './intent.ts';
|
|
12
|
+
import { scoreChunkCandidate } from './scorer.ts';
|
|
13
|
+
import { packContext } from './packer.ts';
|
|
14
|
+
import { resolveProjectContext } from '../../workspace/src/index.ts';
|
|
15
|
+
|
|
16
|
+
export class RetrievalEngine {
|
|
17
|
+
private repository: DocOrbitRepository;
|
|
18
|
+
private defaultWeights: ScoringWeights;
|
|
19
|
+
|
|
20
|
+
constructor(repository: DocOrbitRepository, defaultWeights?: Partial<ScoringWeights>) {
|
|
21
|
+
this.repository = repository;
|
|
22
|
+
this.defaultWeights = resolveScoringWeights(defaultWeights);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Deterministic hybrid search combining FTS5 lexical matching, exact phrases,
|
|
27
|
+
* title/breadcrumb boosts, shallow symbol matches, intent weighting, and authority.
|
|
28
|
+
*/
|
|
29
|
+
async search(query: string, options: SearchOptions = {}): Promise<SearchResult[]> {
|
|
30
|
+
const intent = options.intent || detectQueryIntent(query);
|
|
31
|
+
const weights = resolveScoringWeights(options.weights || this.defaultWeights);
|
|
32
|
+
const limit = options.limit || 10;
|
|
33
|
+
|
|
34
|
+
let targetDocVersion = options.docVersion;
|
|
35
|
+
|
|
36
|
+
if (options.projectDir) {
|
|
37
|
+
const projContext = resolveProjectContext(options.projectDir, query, this.repository);
|
|
38
|
+
if (projContext.matchedDependency && !targetDocVersion) {
|
|
39
|
+
targetDocVersion = projContext.matchedDependency.targetDocVersion;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Fetch candidate pool from FTS5 with extra headroom for re-ranking
|
|
44
|
+
const candidates = this.repository.searchChunksFts(query, {
|
|
45
|
+
limit: Math.max(limit * 3, 30),
|
|
46
|
+
snapshotId: options.snapshotId,
|
|
47
|
+
chunkType: options.chunkType,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (candidates.length === 0) {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const scoredResults: SearchResult[] = [];
|
|
55
|
+
|
|
56
|
+
// Cache source authority per page
|
|
57
|
+
const pageAuthorityCache = new Map<string, SourceAuthority>();
|
|
58
|
+
|
|
59
|
+
for (const item of candidates) {
|
|
60
|
+
let authority: SourceAuthority = 'official';
|
|
61
|
+
const pageId = item.chunk.pageId;
|
|
62
|
+
|
|
63
|
+
if (!pageAuthorityCache.has(pageId)) {
|
|
64
|
+
const page = this.repository.getPage(pageId);
|
|
65
|
+
if (page?.sourceId) {
|
|
66
|
+
const src = this.repository.getSource(page.sourceId);
|
|
67
|
+
if (src?.authority) {
|
|
68
|
+
authority = src.authority;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
pageAuthorityCache.set(pageId, authority);
|
|
72
|
+
} else {
|
|
73
|
+
authority = pageAuthorityCache.get(pageId)!;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const scored = scoreChunkCandidate({
|
|
77
|
+
chunk: item.chunk,
|
|
78
|
+
ftsRank: item.ftsRank,
|
|
79
|
+
symbols: item.symbols,
|
|
80
|
+
codeSnippets: item.codeSnippets,
|
|
81
|
+
query,
|
|
82
|
+
intent,
|
|
83
|
+
authority,
|
|
84
|
+
targetDocVersion,
|
|
85
|
+
weights,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (options.minScore !== undefined && scored.score < options.minScore) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
scoredResults.push(scored);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Sort by score descending
|
|
96
|
+
scoredResults.sort((a, b) => b.score - a.score);
|
|
97
|
+
|
|
98
|
+
return scoredResults.slice(0, limit);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Assembles a context package tailored for AI coding agents, optimizing for
|
|
103
|
+
* relevance + coverage - redundancy within a strict token budget.
|
|
104
|
+
*/
|
|
105
|
+
async buildContext(task: string, options: ContextOptions = {}): Promise<ContextPackage> {
|
|
106
|
+
const intent = options.intent || detectQueryIntent(task);
|
|
107
|
+
|
|
108
|
+
// Retrieve broad candidate set
|
|
109
|
+
const candidates = await this.search(task, {
|
|
110
|
+
limit: (options.maxChunks || 15) * 2,
|
|
111
|
+
snapshotId: options.snapshotId,
|
|
112
|
+
docVersion: options.docVersion,
|
|
113
|
+
projectDir: options.projectDir,
|
|
114
|
+
weights: options.weights,
|
|
115
|
+
intent,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
return packContext(task, candidates, intent, options);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { QueryIntent } from '../../shared/src/index.ts';
|
|
2
|
+
|
|
3
|
+
const INTENT_PATTERNS: Array<{ intent: QueryIntent; regex: RegExp }> = [
|
|
4
|
+
{
|
|
5
|
+
intent: 'troubleshooting',
|
|
6
|
+
regex: /\b(error|failed|failure|exception|crash|fix|debug|issue|cannot|unable|why does|broken|invalid|429|401|403|404|500)\b/i,
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
intent: 'examples',
|
|
10
|
+
regex: /\b(example|examples|sample|samples|snippet|snippets|tutorial|how to|quickstart)\b/i,
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
intent: 'configuration',
|
|
14
|
+
regex: /\b(config|configuration|settings|setup|env|\.env|environment|options|flags?|port|credentials|apikey|api_key)\b/i,
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
intent: 'api',
|
|
18
|
+
regex: /\b(api|endpoint|endpoints|parameters?|request|response|headers?|payload|schema|rest|graphql|status code)\b/i,
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
intent: 'implementation',
|
|
22
|
+
regex: /\b(implement|implementation|build|create|integrate|integration|workflow|handler|webhook|callback|oauth|pipeline)\b/i,
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
intent: 'conceptual',
|
|
26
|
+
regex: /\b(architecture|overview|what is|concept|concepts|design|lifecycle|philosophy|background|understand)\b/i,
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Deterministically detects query intent from task or query text.
|
|
33
|
+
* Falls back to 'conceptual' when no specific pattern matches.
|
|
34
|
+
*/
|
|
35
|
+
export function detectQueryIntent(query: string): QueryIntent {
|
|
36
|
+
const normalized = query.toLowerCase();
|
|
37
|
+
for (const { intent, regex } of INTENT_PATTERNS) {
|
|
38
|
+
if (regex.test(normalized)) {
|
|
39
|
+
return intent;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return 'conceptual';
|
|
43
|
+
}
|