@daogee/mdgraph 1.0.0 → 1.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/CHANGELOG.md +22 -0
- package/README-ZH.md +54 -2
- package/README.md +73 -21
- package/dist/bin/mdgraph.js +136 -19
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/repositories.d.ts +27 -0
- package/dist/db/repositories.js +310 -6
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +14 -5
- package/dist/evaluation/retrieval-eval.js +44 -6
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +17 -4
- package/dist/index.js +9 -4
- package/dist/indexer.js +20 -2
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +16 -7
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +93 -9
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +31 -2
- package/dist/query/context-builder.js +162 -12
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +77 -13
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +131 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +75 -10
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/docs/EN/Agent_Integration.md +1 -1
- package/docs/EN/Architecture.md +39 -16
- package/docs/EN/Evaluation_Questions.md +21 -5
- package/docs/EN/Operations.md +91 -0
- package/docs/EN/Output_Contracts.md +41 -7
- package/docs/EN/Public_Contracts.md +23 -16
- package/docs/EN/Public_Contracts_1.0.md +28 -18
- package/docs/EN/README.md +23 -0
- package/docs/EN/Release_Checklist.md +26 -13
- package/docs/EN/Retrieval_and_Context.md +112 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +1 -1
- package/docs/ZH/Architecture.md +39 -19
- package/docs/ZH/Evaluation_Questions.md +22 -6
- package/docs/ZH/Operations.md +91 -0
- package/docs/ZH/Output_Contracts.md +41 -7
- package/docs/ZH/Public_Contracts.md +22 -15
- package/docs/ZH/Public_Contracts_1.0.md +27 -17
- package/docs/ZH/README.md +23 -0
- package/docs/ZH/Release_Checklist.md +26 -13
- package/docs/ZH/Retrieval_and_Context.md +112 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +44 -18
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { runDoctor } from "../analysis/doctor.js";
|
|
2
|
+
import { embeddingCapability } from "../semantic/provider-registry.js";
|
|
3
|
+
import { EDGE_WEIGHTS } from "../types.js";
|
|
4
|
+
import { stableId } from "../utils/id.js";
|
|
5
|
+
export const RELATED_TO_ALGORITHM_VERSION = "document-chunk-reciprocal-v1";
|
|
6
|
+
export const RELATED_TO_QUALITY_GATE = "semantic-relatedness-v1";
|
|
7
|
+
export const RELATED_TO_DEFAULT_THRESHOLD = 0.86;
|
|
8
|
+
export const RELATED_TO_MIN_THRESHOLD = 0.75;
|
|
9
|
+
export const RELATED_TO_DEFAULT_MAX_NEIGHBORS = 3;
|
|
10
|
+
export const RELATED_TO_DEFAULT_MIN_EVIDENCE = 2;
|
|
11
|
+
export const RELATED_TO_MAX_DOCUMENT_PAIRS = 250_000;
|
|
12
|
+
export const RELATED_TO_MAX_VECTOR_COMPARISONS = 2_000_000;
|
|
13
|
+
export const RELATED_TO_MAX_COMPONENT_COMPARISONS = 100_000_000;
|
|
14
|
+
export const RELATED_TO_MAX_CHUNKS_PER_DOCUMENT = 12;
|
|
15
|
+
export class DerivedRelationshipError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
name = "DerivedRelationshipError";
|
|
18
|
+
constructor(code, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.code = code;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function deriveRelatedRelationships(repository, projectRoot, config, options = {}) {
|
|
24
|
+
const normalized = normalizeOptions(options);
|
|
25
|
+
validateProvider(config);
|
|
26
|
+
const doctor = await runDoctor(projectRoot, { applySchema: false });
|
|
27
|
+
const parseFailures = doctor.warnings.filter((warning) => warning.code === "document.parse_failed");
|
|
28
|
+
if (doctor.staleIndex.stale || parseFailures.length) {
|
|
29
|
+
throw new DerivedRelationshipError("stale_index", parseFailures.length
|
|
30
|
+
? `RELATED_TO derivation requires every indexed Markdown file to be readable; doctor reported ${parseFailures.length} parse failure(s).`
|
|
31
|
+
: `RELATED_TO derivation requires a fresh index; ${doctor.staleIndex.recommendation}.`);
|
|
32
|
+
}
|
|
33
|
+
const counts = repository.counts();
|
|
34
|
+
const corpus = repository.semanticRelationshipCorpus(config.embedding.provider, config.embedding.model, config.embedding.dimensions);
|
|
35
|
+
if (corpus.invalidVectors > 0 || corpus.chunks.length !== counts.chunks || counts.vectors !== counts.chunks) {
|
|
36
|
+
throw new DerivedRelationshipError("incomplete_vector_coverage", `RELATED_TO derivation requires complete ${config.embedding.provider}/${config.embedding.model}/${config.embedding.dimensions} vector coverage; found ${corpus.chunks.length} valid matching vector(s) for ${counts.chunks} chunk(s), with ${corpus.invalidVectors} invalid vector(s). Run \`mdgraph index --semantic --full\`.`);
|
|
37
|
+
}
|
|
38
|
+
const grouped = groupDocumentVectors(corpus.chunks, normalized.minEvidence);
|
|
39
|
+
const pairBudget = grouped.documents.length * (grouped.documents.length - 1) / 2;
|
|
40
|
+
if (pairBudget > RELATED_TO_MAX_DOCUMENT_PAIRS) {
|
|
41
|
+
throw new DerivedRelationshipError("corpus_too_large", `RELATED_TO derivation would evaluate ${pairBudget} document pairs, above the ${RELATED_TO_MAX_DOCUMENT_PAIRS} safety limit.`);
|
|
42
|
+
}
|
|
43
|
+
const centroidComponentComparisons = pairBudget * config.embedding.dimensions;
|
|
44
|
+
if (centroidComponentComparisons > RELATED_TO_MAX_COMPONENT_COMPARISONS) {
|
|
45
|
+
throw new DerivedRelationshipError("corpus_too_large", `RELATED_TO centroid evaluation would compare ${centroidComponentComparisons} vector components, above the ${RELATED_TO_MAX_COMPONENT_COMPARISONS} safety limit.`);
|
|
46
|
+
}
|
|
47
|
+
let documentPairsEvaluated = 0;
|
|
48
|
+
let evidenceVectorComparisons = 0;
|
|
49
|
+
const candidates = [];
|
|
50
|
+
const centroidFloor = Math.max(0, normalized.threshold - 0.12);
|
|
51
|
+
for (let leftIndex = 0; leftIndex < grouped.documents.length; leftIndex += 1) {
|
|
52
|
+
for (let rightIndex = leftIndex + 1; rightIndex < grouped.documents.length; rightIndex += 1) {
|
|
53
|
+
documentPairsEvaluated += 1;
|
|
54
|
+
const left = grouped.documents[leftIndex];
|
|
55
|
+
const right = grouped.documents[rightIndex];
|
|
56
|
+
if (cosine(left.centroid, right.centroid) < centroidFloor) {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const comparisons = left.chunks.length * right.chunks.length;
|
|
60
|
+
evidenceVectorComparisons += comparisons;
|
|
61
|
+
if (evidenceVectorComparisons > RELATED_TO_MAX_VECTOR_COMPARISONS) {
|
|
62
|
+
throw new DerivedRelationshipError("corpus_too_large", `RELATED_TO evidence evaluation exceeds the ${RELATED_TO_MAX_VECTOR_COMPARISONS} vector-comparison safety limit; increase the threshold or derive on a smaller graph.`);
|
|
63
|
+
}
|
|
64
|
+
if (evidenceVectorComparisons * config.embedding.dimensions > RELATED_TO_MAX_COMPONENT_COMPARISONS) {
|
|
65
|
+
throw new DerivedRelationshipError("corpus_too_large", `RELATED_TO evidence evaluation exceeds the ${RELATED_TO_MAX_COMPONENT_COMPARISONS} vector-component safety limit; increase the threshold or derive on a smaller graph.`);
|
|
66
|
+
}
|
|
67
|
+
const evidenceSections = independentEvidence(left.chunks, right.chunks, normalized.threshold, normalized.minEvidence);
|
|
68
|
+
if (evidenceSections.length < normalized.minEvidence) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const confidence = rounded(evidenceSections
|
|
72
|
+
.slice(0, normalized.minEvidence)
|
|
73
|
+
.reduce((total, evidence) => total + evidence.similarity, 0) / normalized.minEvidence);
|
|
74
|
+
candidates.push({
|
|
75
|
+
key: relationshipKey(left.document.id, right.document.id),
|
|
76
|
+
fromDocumentId: left.document.id,
|
|
77
|
+
fromPath: left.document.path,
|
|
78
|
+
toDocumentId: right.document.id,
|
|
79
|
+
toPath: right.document.path,
|
|
80
|
+
confidence,
|
|
81
|
+
evidenceSections
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const relationships = reciprocalRelationships(candidates, normalized.maxNeighbors)
|
|
86
|
+
.sort((left, right) => left.fromPath.localeCompare(right.fromPath) || left.toPath.localeCompare(right.toPath));
|
|
87
|
+
const generatedAt = new Date().toISOString();
|
|
88
|
+
const edges = relationships.flatMap((relationship) => relationshipEdges(relationship, config, normalized, generatedAt));
|
|
89
|
+
const mutation = normalized.dryRun
|
|
90
|
+
? { dryRun: true, removed: 0, inserted: 0 }
|
|
91
|
+
: { dryRun: false, ...repository.replaceEmbeddingSimilarityEdges(edges) };
|
|
92
|
+
return {
|
|
93
|
+
algorithmVersion: RELATED_TO_ALGORITHM_VERSION,
|
|
94
|
+
generatedAt,
|
|
95
|
+
provider: config.embedding.provider,
|
|
96
|
+
model: config.embedding.model,
|
|
97
|
+
dimensions: config.embedding.dimensions,
|
|
98
|
+
options: normalized,
|
|
99
|
+
qualityGate: {
|
|
100
|
+
id: RELATED_TO_QUALITY_GATE,
|
|
101
|
+
passed: true,
|
|
102
|
+
checks: {
|
|
103
|
+
freshIndex: true,
|
|
104
|
+
semanticModelProvider: true,
|
|
105
|
+
completeVectorCoverage: true,
|
|
106
|
+
thresholdFloor: true,
|
|
107
|
+
multipleIndependentEvidenceSections: true,
|
|
108
|
+
reciprocalTopK: true
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
corpus: {
|
|
112
|
+
documents: counts.documents,
|
|
113
|
+
eligibleDocuments: grouped.documents.length,
|
|
114
|
+
chunks: counts.chunks,
|
|
115
|
+
vectors: counts.vectors,
|
|
116
|
+
invalidVectors: corpus.invalidVectors,
|
|
117
|
+
sampledChunks: grouped.sampledChunks,
|
|
118
|
+
documentsWithSampledChunkTruncation: grouped.truncatedDocuments,
|
|
119
|
+
documentPairsEvaluated,
|
|
120
|
+
centroidComponentComparisons,
|
|
121
|
+
evidenceVectorComparisons,
|
|
122
|
+
evidenceComponentComparisons: evidenceVectorComparisons * config.embedding.dimensions
|
|
123
|
+
},
|
|
124
|
+
relationships: relationships.map(({ key: _key, ...relationship }) => relationship),
|
|
125
|
+
relationshipPairs: relationships.length,
|
|
126
|
+
directedEdges: edges.length,
|
|
127
|
+
mutation
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function normalizeOptions(options) {
|
|
131
|
+
const threshold = options.threshold ?? RELATED_TO_DEFAULT_THRESHOLD;
|
|
132
|
+
const maxNeighbors = options.maxNeighbors ?? RELATED_TO_DEFAULT_MAX_NEIGHBORS;
|
|
133
|
+
const minEvidence = options.minEvidence ?? RELATED_TO_DEFAULT_MIN_EVIDENCE;
|
|
134
|
+
if (!Number.isFinite(threshold) || threshold < RELATED_TO_MIN_THRESHOLD || threshold > 1) {
|
|
135
|
+
throw new DerivedRelationshipError("invalid_options", `RELATED_TO threshold must be between ${RELATED_TO_MIN_THRESHOLD} and 1.`);
|
|
136
|
+
}
|
|
137
|
+
if (!Number.isSafeInteger(maxNeighbors) || maxNeighbors < 1 || maxNeighbors > 10) {
|
|
138
|
+
throw new DerivedRelationshipError("invalid_options", "RELATED_TO maxNeighbors must be an integer from 1 to 10.");
|
|
139
|
+
}
|
|
140
|
+
if (!Number.isSafeInteger(minEvidence) || minEvidence < 2 || minEvidence > 4) {
|
|
141
|
+
throw new DerivedRelationshipError("invalid_options", "RELATED_TO minEvidence must be an integer from 2 to 4.");
|
|
142
|
+
}
|
|
143
|
+
return { threshold, maxNeighbors, minEvidence, dryRun: options.dryRun === true };
|
|
144
|
+
}
|
|
145
|
+
function validateProvider(config) {
|
|
146
|
+
if (!config.embedding.enabled) {
|
|
147
|
+
throw new DerivedRelationshipError("embedding_disabled", "RELATED_TO derivation is disabled because embedding.enabled is false. Enable a semantic-model provider and rebuild vectors first.");
|
|
148
|
+
}
|
|
149
|
+
if (embeddingCapability(config.embedding.provider) !== "semantic-model") {
|
|
150
|
+
throw new DerivedRelationshipError("provider_not_semantic", `Embedding provider '${config.embedding.provider}' is not a semantic-model provider and cannot emit RELATED_TO.`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function groupDocumentVectors(chunks, minEvidence) {
|
|
154
|
+
const byDocument = new Map();
|
|
155
|
+
for (const chunk of chunks) {
|
|
156
|
+
const current = byDocument.get(chunk.document.id) ?? [];
|
|
157
|
+
current.push(chunk);
|
|
158
|
+
byDocument.set(chunk.document.id, current);
|
|
159
|
+
}
|
|
160
|
+
const documents = [];
|
|
161
|
+
let sampledChunks = 0;
|
|
162
|
+
let truncatedDocuments = 0;
|
|
163
|
+
for (const documentChunks of byDocument.values()) {
|
|
164
|
+
if (documentChunks.length < minEvidence) {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const sampled = sampleEvenly(documentChunks, RELATED_TO_MAX_CHUNKS_PER_DOCUMENT);
|
|
168
|
+
const centroid = normalizedCentroid(sampled.map((chunk) => chunk.vector));
|
|
169
|
+
if (!centroid.length) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
sampledChunks += sampled.length;
|
|
173
|
+
truncatedDocuments += documentChunks.length > sampled.length ? 1 : 0;
|
|
174
|
+
documents.push({ document: sampled[0].document, chunks: sampled, centroid });
|
|
175
|
+
}
|
|
176
|
+
documents.sort((left, right) => left.document.path.localeCompare(right.document.path));
|
|
177
|
+
return { documents, sampledChunks, truncatedDocuments };
|
|
178
|
+
}
|
|
179
|
+
function sampleEvenly(items, limit) {
|
|
180
|
+
if (items.length <= limit) {
|
|
181
|
+
return items;
|
|
182
|
+
}
|
|
183
|
+
const indexes = new Set();
|
|
184
|
+
for (let index = 0; index < limit; index += 1) {
|
|
185
|
+
indexes.add(Math.round(index * (items.length - 1) / (limit - 1)));
|
|
186
|
+
}
|
|
187
|
+
return [...indexes].sort((left, right) => left - right).map((index) => items[index]);
|
|
188
|
+
}
|
|
189
|
+
function independentEvidence(left, right, threshold, minEvidence) {
|
|
190
|
+
const candidates = [];
|
|
191
|
+
for (const from of left) {
|
|
192
|
+
for (const to of right) {
|
|
193
|
+
const similarity = rounded(cosine(from.vector, to.vector));
|
|
194
|
+
if (similarity >= threshold) {
|
|
195
|
+
candidates.push({
|
|
196
|
+
fromChunkId: from.chunk.id,
|
|
197
|
+
fromSectionId: from.section?.id,
|
|
198
|
+
toChunkId: to.chunk.id,
|
|
199
|
+
toSectionId: to.section?.id,
|
|
200
|
+
similarity
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
candidates.sort((first, second) => (second.similarity - first.similarity
|
|
206
|
+
|| first.fromChunkId.localeCompare(second.fromChunkId)
|
|
207
|
+
|| first.toChunkId.localeCompare(second.toChunkId)));
|
|
208
|
+
const usedFrom = new Set();
|
|
209
|
+
const usedTo = new Set();
|
|
210
|
+
const evidence = [];
|
|
211
|
+
const maximumEvidence = Math.max(minEvidence, 4);
|
|
212
|
+
for (const candidate of candidates) {
|
|
213
|
+
if (usedFrom.has(candidate.fromChunkId) || usedTo.has(candidate.toChunkId)) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
evidence.push(candidate);
|
|
217
|
+
usedFrom.add(candidate.fromChunkId);
|
|
218
|
+
usedTo.add(candidate.toChunkId);
|
|
219
|
+
if (evidence.length >= maximumEvidence) {
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return evidence;
|
|
224
|
+
}
|
|
225
|
+
function reciprocalRelationships(candidates, maxNeighbors) {
|
|
226
|
+
const byDocument = new Map();
|
|
227
|
+
for (const candidate of candidates) {
|
|
228
|
+
pushNeighbor(byDocument, candidate.fromDocumentId, candidate.key, candidate.toPath, candidate.confidence);
|
|
229
|
+
pushNeighbor(byDocument, candidate.toDocumentId, candidate.key, candidate.fromPath, candidate.confidence);
|
|
230
|
+
}
|
|
231
|
+
const selected = new Map();
|
|
232
|
+
for (const [documentId, neighbors] of byDocument) {
|
|
233
|
+
neighbors.sort((left, right) => right.confidence - left.confidence || left.otherPath.localeCompare(right.otherPath));
|
|
234
|
+
selected.set(documentId, new Set(neighbors.slice(0, maxNeighbors).map((neighbor) => neighbor.key)));
|
|
235
|
+
}
|
|
236
|
+
return candidates.filter((candidate) => (selected.get(candidate.fromDocumentId)?.has(candidate.key)
|
|
237
|
+
&& selected.get(candidate.toDocumentId)?.has(candidate.key)));
|
|
238
|
+
}
|
|
239
|
+
function pushNeighbor(target, documentId, key, otherPath, confidence) {
|
|
240
|
+
const neighbors = target.get(documentId) ?? [];
|
|
241
|
+
neighbors.push({ key, otherPath, confidence });
|
|
242
|
+
target.set(documentId, neighbors);
|
|
243
|
+
}
|
|
244
|
+
function relationshipEdges(relationship, config, options, generatedAt) {
|
|
245
|
+
return [
|
|
246
|
+
relationshipEdge(relationship, false, config, options, generatedAt),
|
|
247
|
+
relationshipEdge(relationship, true, config, options, generatedAt)
|
|
248
|
+
];
|
|
249
|
+
}
|
|
250
|
+
function relationshipEdge(relationship, reverse, config, options, generatedAt) {
|
|
251
|
+
const fromId = reverse ? relationship.toDocumentId : relationship.fromDocumentId;
|
|
252
|
+
const toId = reverse ? relationship.fromDocumentId : relationship.toDocumentId;
|
|
253
|
+
const evidenceSections = reverse
|
|
254
|
+
? relationship.evidenceSections.map((evidence) => ({
|
|
255
|
+
fromChunkId: evidence.toChunkId,
|
|
256
|
+
fromSectionId: evidence.toSectionId,
|
|
257
|
+
toChunkId: evidence.fromChunkId,
|
|
258
|
+
toSectionId: evidence.fromSectionId,
|
|
259
|
+
similarity: evidence.similarity
|
|
260
|
+
}))
|
|
261
|
+
: relationship.evidenceSections;
|
|
262
|
+
return {
|
|
263
|
+
id: stableId("edge", `${fromId}:RELATED_TO:${toId}:embedding_similarity`),
|
|
264
|
+
fromId,
|
|
265
|
+
toId,
|
|
266
|
+
kind: "RELATED_TO",
|
|
267
|
+
weight: EDGE_WEIGHTS.RELATED_TO,
|
|
268
|
+
confidence: relationship.confidence,
|
|
269
|
+
provenance: "embedding_similarity",
|
|
270
|
+
metadata: {
|
|
271
|
+
provider: config.embedding.provider,
|
|
272
|
+
model: config.embedding.model,
|
|
273
|
+
dimensions: config.embedding.dimensions,
|
|
274
|
+
algorithmVersion: RELATED_TO_ALGORITHM_VERSION,
|
|
275
|
+
qualityGate: RELATED_TO_QUALITY_GATE,
|
|
276
|
+
threshold: options.threshold,
|
|
277
|
+
minEvidence: options.minEvidence,
|
|
278
|
+
reciprocalTopK: options.maxNeighbors,
|
|
279
|
+
symmetric: true,
|
|
280
|
+
evidenceSections,
|
|
281
|
+
generatedAt
|
|
282
|
+
},
|
|
283
|
+
createdAt: generatedAt
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
function relationshipKey(leftId, rightId) {
|
|
287
|
+
return leftId < rightId ? `${leftId}\u0000${rightId}` : `${rightId}\u0000${leftId}`;
|
|
288
|
+
}
|
|
289
|
+
function normalizedCentroid(vectors) {
|
|
290
|
+
if (!vectors.length) {
|
|
291
|
+
return [];
|
|
292
|
+
}
|
|
293
|
+
const dimensions = vectors[0].length;
|
|
294
|
+
const centroid = Array.from({ length: dimensions }, () => 0);
|
|
295
|
+
for (const vector of vectors) {
|
|
296
|
+
const normalized = normalizeVector(vector);
|
|
297
|
+
if (!normalized.length) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
for (let index = 0; index < dimensions; index += 1) {
|
|
301
|
+
centroid[index] += normalized[index];
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return normalizeVector(centroid);
|
|
305
|
+
}
|
|
306
|
+
function normalizeVector(vector) {
|
|
307
|
+
const magnitude = Math.sqrt(vector.reduce((total, value) => total + value * value, 0));
|
|
308
|
+
return magnitude > 0 ? vector.map((value) => value / magnitude) : [];
|
|
309
|
+
}
|
|
310
|
+
function cosine(left, right) {
|
|
311
|
+
if (!left.length || left.length !== right.length) {
|
|
312
|
+
return 0;
|
|
313
|
+
}
|
|
314
|
+
let dot = 0;
|
|
315
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
316
|
+
dot += left[index] * right[index];
|
|
317
|
+
}
|
|
318
|
+
return Math.max(-1, Math.min(1, dot));
|
|
319
|
+
}
|
|
320
|
+
function rounded(value) {
|
|
321
|
+
return Number(value.toFixed(6));
|
|
322
|
+
}
|
package/dist/reporting/report.js
CHANGED
|
@@ -7,7 +7,7 @@ import { databasePath, loadConfig } from "../config/load-config.js";
|
|
|
7
7
|
import { openExistingDatabase } from "../db/connection.js";
|
|
8
8
|
import { GraphRepository } from "../db/repositories.js";
|
|
9
9
|
import { generateGraphDiff } from "../diff/graph-diff.js";
|
|
10
|
-
import {
|
|
10
|
+
import { evaluateRetrievalAsync } from "../evaluation/retrieval-eval.js";
|
|
11
11
|
import { packageVersion } from "../version.js";
|
|
12
12
|
export async function generateReport(projectRoot, options = {}) {
|
|
13
13
|
const resolvedRoot = path.resolve(projectRoot);
|
|
@@ -42,7 +42,7 @@ export async function generateReport(projectRoot, options = {}) {
|
|
|
42
42
|
documentsHash: source.documentsHash
|
|
43
43
|
};
|
|
44
44
|
if (options.eval) {
|
|
45
|
-
const evalReport =
|
|
45
|
+
const evalReport = await evaluateRetrievalAsync(repository, config);
|
|
46
46
|
report.eval = {
|
|
47
47
|
querySet: evalReport.querySet,
|
|
48
48
|
summary: evalReport.summary,
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createEmbeddingProvider } from "./provider-registry.js";
|
|
2
|
+
import { EmbeddingProviderError, validateEmbeddingVector } from "./provider.js";
|
|
3
|
+
import { DEFAULT_EMBEDDING_BATCH_SIZE } from "./ollama-provider.js";
|
|
4
|
+
export async function embedChunks(chunks, config) {
|
|
5
|
+
if (!config.embedding.enabled || !chunks.length) {
|
|
6
|
+
return [];
|
|
7
|
+
}
|
|
8
|
+
const provider = createEmbeddingProvider(config.embedding);
|
|
9
|
+
const batchSize = config.embedding.batchSize ?? DEFAULT_EMBEDDING_BATCH_SIZE;
|
|
10
|
+
const createdAt = new Date().toISOString();
|
|
11
|
+
const vectors = [];
|
|
12
|
+
for (let offset = 0; offset < chunks.length; offset += batchSize) {
|
|
13
|
+
const batch = chunks.slice(offset, offset + batchSize);
|
|
14
|
+
const embedded = await provider.embedDocuments(batch.map((chunk) => chunk.content));
|
|
15
|
+
if (embedded.length !== batch.length) {
|
|
16
|
+
throw new EmbeddingProviderError("invalid_response", provider.id, `Embedding provider '${provider.id}' returned ${embedded.length} vector(s) for ${batch.length} chunk(s).`);
|
|
17
|
+
}
|
|
18
|
+
embedded.forEach((vector, index) => {
|
|
19
|
+
validateEmbeddingVector(provider.id, vector, config.embedding.dimensions);
|
|
20
|
+
vectors.push({
|
|
21
|
+
chunkId: batch[index].id,
|
|
22
|
+
provider: provider.id,
|
|
23
|
+
model: provider.model,
|
|
24
|
+
dimensions: provider.dimensions,
|
|
25
|
+
vector,
|
|
26
|
+
createdAt
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
return vectors;
|
|
31
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { EmbeddingConfig, EmbeddingProvider } from "./provider.js";
|
|
2
|
+
export declare const OLLAMA_EMBEDDING_PROVIDER = "ollama";
|
|
3
|
+
export declare const DEFAULT_OLLAMA_ENDPOINT = "http://127.0.0.1:11434";
|
|
4
|
+
export declare const DEFAULT_EMBEDDING_TIMEOUT_MS = 30000;
|
|
5
|
+
export declare const DEFAULT_EMBEDDING_BATCH_SIZE = 16;
|
|
6
|
+
export declare function createOllamaEmbeddingProvider(config: EmbeddingConfig): EmbeddingProvider;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { EmbeddingProviderError } from "./provider.js";
|
|
2
|
+
export const OLLAMA_EMBEDDING_PROVIDER = "ollama";
|
|
3
|
+
export const DEFAULT_OLLAMA_ENDPOINT = "http://127.0.0.1:11434";
|
|
4
|
+
export const DEFAULT_EMBEDDING_TIMEOUT_MS = 30_000;
|
|
5
|
+
export const DEFAULT_EMBEDDING_BATCH_SIZE = 16;
|
|
6
|
+
export function createOllamaEmbeddingProvider(config) {
|
|
7
|
+
const endpoint = validatedEndpoint(config.endpoint ?? DEFAULT_OLLAMA_ENDPOINT);
|
|
8
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_EMBEDDING_TIMEOUT_MS;
|
|
9
|
+
return {
|
|
10
|
+
id: OLLAMA_EMBEDDING_PROVIDER,
|
|
11
|
+
model: config.model,
|
|
12
|
+
dimensions: config.dimensions,
|
|
13
|
+
capability: "semantic-model",
|
|
14
|
+
locality: "local-service",
|
|
15
|
+
availability: () => ollamaAvailability(endpoint, config.model, timeoutMs),
|
|
16
|
+
embedDocuments: (inputs) => requestEmbeddings(endpoint, config, inputs, timeoutMs),
|
|
17
|
+
embedQuery: async (input) => (await requestEmbeddings(endpoint, config, [input], timeoutMs))[0]
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
async function ollamaAvailability(endpoint, model, timeoutMs) {
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetchWithTimeout(new URL("/api/tags", endpoint), { method: "GET" }, timeoutMs);
|
|
23
|
+
if (!response.ok) {
|
|
24
|
+
return { status: "unavailable", reason: `Ollama model listing returned HTTP ${response.status}.` };
|
|
25
|
+
}
|
|
26
|
+
const parsed = await readJson(response);
|
|
27
|
+
const models = isRecord(parsed) && Array.isArray(parsed.models) ? parsed.models ?? [] : [];
|
|
28
|
+
const available = models.some((item) => modelMatches(item.name, model) || modelMatches(item.model, model));
|
|
29
|
+
return available
|
|
30
|
+
? { status: "available" }
|
|
31
|
+
: { status: "model_missing", reason: `Ollama model '${model}' is not installed.` };
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
const providerError = normalizeFetchError(error, timeoutMs);
|
|
35
|
+
return { status: "unavailable", reason: providerError.message };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function requestEmbeddings(endpoint, config, inputs, timeoutMs) {
|
|
39
|
+
if (!inputs.length) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
let response;
|
|
43
|
+
try {
|
|
44
|
+
response = await fetchWithTimeout(new URL("/api/embed", endpoint), {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers: { "content-type": "application/json" },
|
|
47
|
+
body: JSON.stringify({
|
|
48
|
+
model: config.model,
|
|
49
|
+
input: inputs,
|
|
50
|
+
dimensions: config.dimensions,
|
|
51
|
+
truncate: true
|
|
52
|
+
})
|
|
53
|
+
}, timeoutMs);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
throw normalizeFetchError(error, timeoutMs);
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
const body = (await response.text()).trim().slice(0, 500);
|
|
60
|
+
const suffix = body ? `: ${body}` : "";
|
|
61
|
+
const code = response.status === 404 ? "model_missing" : "http_error";
|
|
62
|
+
throw new EmbeddingProviderError(code, OLLAMA_EMBEDDING_PROVIDER, `Ollama embedding request returned HTTP ${response.status}${suffix}`);
|
|
63
|
+
}
|
|
64
|
+
const parsed = await readJson(response);
|
|
65
|
+
const embeddings = isRecord(parsed) ? parsed.embeddings : undefined;
|
|
66
|
+
if (!Array.isArray(embeddings) || embeddings.length !== inputs.length) {
|
|
67
|
+
throw new EmbeddingProviderError("invalid_response", OLLAMA_EMBEDDING_PROVIDER, `Ollama returned ${Array.isArray(embeddings) ? embeddings.length : 0} embedding(s) for ${inputs.length} input(s).`);
|
|
68
|
+
}
|
|
69
|
+
return embeddings.map((value, index) => validatedVector(value, config.dimensions, index));
|
|
70
|
+
}
|
|
71
|
+
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
72
|
+
const controller = new AbortController();
|
|
73
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
74
|
+
try {
|
|
75
|
+
return await fetch(url, { ...init, signal: controller.signal });
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function readJson(response) {
|
|
82
|
+
try {
|
|
83
|
+
return await response.json();
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
throw new EmbeddingProviderError("invalid_response", OLLAMA_EMBEDDING_PROVIDER, "Ollama returned invalid JSON.", { cause: error });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function validatedVector(value, dimensions, index) {
|
|
90
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "number" && Number.isFinite(item))) {
|
|
91
|
+
throw new EmbeddingProviderError("invalid_response", OLLAMA_EMBEDDING_PROVIDER, `Ollama embedding ${index} is not a finite numeric vector.`);
|
|
92
|
+
}
|
|
93
|
+
if (value.length !== dimensions) {
|
|
94
|
+
throw new EmbeddingProviderError("dimension_mismatch", OLLAMA_EMBEDDING_PROVIDER, `Ollama embedding ${index} has ${value.length} dimensions; configured embedding.dimensions is ${dimensions}.`);
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function validatedEndpoint(value) {
|
|
99
|
+
let endpoint;
|
|
100
|
+
try {
|
|
101
|
+
endpoint = new URL(value);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
throw new EmbeddingProviderError("invalid_config", OLLAMA_EMBEDDING_PROVIDER, `Invalid Ollama endpoint: ${value}`, { cause: error });
|
|
105
|
+
}
|
|
106
|
+
if ((endpoint.protocol !== "http:" && endpoint.protocol !== "https:") || endpoint.username || endpoint.password) {
|
|
107
|
+
throw new EmbeddingProviderError("invalid_config", OLLAMA_EMBEDDING_PROVIDER, "Ollama endpoint must use http/https and must not contain credentials.");
|
|
108
|
+
}
|
|
109
|
+
return endpoint;
|
|
110
|
+
}
|
|
111
|
+
function normalizeFetchError(error, timeoutMs) {
|
|
112
|
+
if (error instanceof EmbeddingProviderError) {
|
|
113
|
+
return error;
|
|
114
|
+
}
|
|
115
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
116
|
+
return new EmbeddingProviderError("provider_timeout", OLLAMA_EMBEDDING_PROVIDER, `Ollama embedding request timed out after ${timeoutMs} ms.`, { cause: error });
|
|
117
|
+
}
|
|
118
|
+
return new EmbeddingProviderError("provider_unavailable", OLLAMA_EMBEDDING_PROVIDER, `Ollama is unavailable: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
119
|
+
}
|
|
120
|
+
function modelMatches(value, expected) {
|
|
121
|
+
if (typeof value !== "string") {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
return value === expected || stripLatest(value) === stripLatest(expected);
|
|
125
|
+
}
|
|
126
|
+
function stripLatest(value) {
|
|
127
|
+
return value.endsWith(":latest") ? value.slice(0, -":latest".length) : value;
|
|
128
|
+
}
|
|
129
|
+
function isRecord(value) {
|
|
130
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
131
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EmbeddingConfig, EmbeddingProvider } from "./provider.js";
|
|
2
|
+
export declare const SUPPORTED_EMBEDDING_PROVIDERS: readonly ["local-hash", "ollama"];
|
|
3
|
+
export type EmbeddingProviderFactory = (config: EmbeddingConfig) => EmbeddingProvider;
|
|
4
|
+
export declare function isSupportedEmbeddingProvider(provider: string): boolean;
|
|
5
|
+
export declare function supportsSynchronousEmbeddingProvider(provider: string): boolean;
|
|
6
|
+
export declare function createEmbeddingProvider(config: EmbeddingConfig): EmbeddingProvider;
|
|
7
|
+
export declare function embeddingCapability(provider: string): "lexical-hash" | "semantic-model" | "unknown";
|
|
8
|
+
export declare function registerEmbeddingProvider(id: string, capability: EmbeddingProvider["capability"], factory: EmbeddingProviderFactory): () => void;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { EmbeddingProviderError } from "./provider.js";
|
|
2
|
+
import { embedTextLocal, LOCAL_EMBEDDING_PROVIDER } from "./local-embedding.js";
|
|
3
|
+
import { createOllamaEmbeddingProvider, OLLAMA_EMBEDDING_PROVIDER } from "./ollama-provider.js";
|
|
4
|
+
export const SUPPORTED_EMBEDDING_PROVIDERS = [LOCAL_EMBEDDING_PROVIDER, OLLAMA_EMBEDDING_PROVIDER];
|
|
5
|
+
const registeredProviders = new Map();
|
|
6
|
+
export function isSupportedEmbeddingProvider(provider) {
|
|
7
|
+
return SUPPORTED_EMBEDDING_PROVIDERS.includes(provider)
|
|
8
|
+
|| registeredProviders.has(provider);
|
|
9
|
+
}
|
|
10
|
+
export function supportsSynchronousEmbeddingProvider(provider) {
|
|
11
|
+
return provider === LOCAL_EMBEDDING_PROVIDER;
|
|
12
|
+
}
|
|
13
|
+
export function createEmbeddingProvider(config) {
|
|
14
|
+
const registered = registeredProviders.get(config.provider);
|
|
15
|
+
if (registered) {
|
|
16
|
+
return validatedProvider(registered.factory(config), config);
|
|
17
|
+
}
|
|
18
|
+
switch (config.provider) {
|
|
19
|
+
case LOCAL_EMBEDDING_PROVIDER:
|
|
20
|
+
return validatedProvider({
|
|
21
|
+
id: LOCAL_EMBEDDING_PROVIDER,
|
|
22
|
+
model: config.model,
|
|
23
|
+
dimensions: config.dimensions,
|
|
24
|
+
capability: "lexical-hash",
|
|
25
|
+
locality: "in-process",
|
|
26
|
+
availability: async () => ({ status: "available" }),
|
|
27
|
+
embedDocuments: async (inputs) => inputs.map((input) => embedTextLocal(input, config.dimensions)),
|
|
28
|
+
embedQuery: async (input) => embedTextLocal(input, config.dimensions)
|
|
29
|
+
}, config);
|
|
30
|
+
case OLLAMA_EMBEDDING_PROVIDER:
|
|
31
|
+
return validatedProvider(createOllamaEmbeddingProvider(config), config);
|
|
32
|
+
default:
|
|
33
|
+
throw new EmbeddingProviderError("unsupported_provider", config.provider, `Embedding provider '${config.provider}' is not available in this build.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function validatedProvider(provider, config) {
|
|
37
|
+
if (provider.id !== config.provider || provider.model !== config.model || provider.dimensions !== config.dimensions) {
|
|
38
|
+
throw new EmbeddingProviderError("invalid_config", config.provider, `Embedding provider factory returned ${provider.id}/${provider.model}/${provider.dimensions}; expected ${config.provider}/${config.model}/${config.dimensions}.`);
|
|
39
|
+
}
|
|
40
|
+
return provider;
|
|
41
|
+
}
|
|
42
|
+
export function embeddingCapability(provider) {
|
|
43
|
+
if (provider === LOCAL_EMBEDDING_PROVIDER) {
|
|
44
|
+
return "lexical-hash";
|
|
45
|
+
}
|
|
46
|
+
if (provider === OLLAMA_EMBEDDING_PROVIDER) {
|
|
47
|
+
return "semantic-model";
|
|
48
|
+
}
|
|
49
|
+
return registeredProviders.get(provider)?.capability ?? "unknown";
|
|
50
|
+
}
|
|
51
|
+
export function registerEmbeddingProvider(id, capability, factory) {
|
|
52
|
+
const normalizedId = id.trim();
|
|
53
|
+
if (!normalizedId) {
|
|
54
|
+
throw new Error("Embedding provider id must not be empty.");
|
|
55
|
+
}
|
|
56
|
+
if (SUPPORTED_EMBEDDING_PROVIDERS.includes(normalizedId) || registeredProviders.has(normalizedId)) {
|
|
57
|
+
throw new Error(`Embedding provider '${normalizedId}' is already registered.`);
|
|
58
|
+
}
|
|
59
|
+
const registration = { capability, factory };
|
|
60
|
+
registeredProviders.set(normalizedId, registration);
|
|
61
|
+
return () => {
|
|
62
|
+
if (registeredProviders.get(normalizedId) === registration) {
|
|
63
|
+
registeredProviders.delete(normalizedId);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { MDGraphConfig } from "../types.js";
|
|
2
|
+
export type EmbeddingCapability = "lexical-hash" | "semantic-model";
|
|
3
|
+
export type EmbeddingRuntimeStatus = "available" | "unavailable" | "model_missing" | "unchecked" | "disabled";
|
|
4
|
+
export type EmbeddingProviderErrorCode = "unsupported_provider" | "invalid_config" | "provider_unavailable" | "provider_timeout" | "model_missing" | "http_error" | "invalid_response" | "dimension_mismatch" | "vectors_unavailable";
|
|
5
|
+
export interface EmbeddingProviderAvailability {
|
|
6
|
+
status: Extract<EmbeddingRuntimeStatus, "available" | "unavailable" | "model_missing">;
|
|
7
|
+
reason?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface EmbeddingProvider {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly model: string;
|
|
12
|
+
readonly dimensions: number;
|
|
13
|
+
readonly capability: EmbeddingCapability;
|
|
14
|
+
readonly locality: "in-process" | "local-service";
|
|
15
|
+
availability(): Promise<EmbeddingProviderAvailability>;
|
|
16
|
+
embedDocuments(inputs: string[]): Promise<number[][]>;
|
|
17
|
+
embedQuery(input: string): Promise<number[]>;
|
|
18
|
+
}
|
|
19
|
+
export interface EmbeddingDiagnostic {
|
|
20
|
+
code: EmbeddingProviderErrorCode;
|
|
21
|
+
provider: string;
|
|
22
|
+
message: string;
|
|
23
|
+
degraded: true;
|
|
24
|
+
}
|
|
25
|
+
export type EmbeddingConfig = MDGraphConfig["embedding"];
|
|
26
|
+
export declare class EmbeddingProviderError extends Error {
|
|
27
|
+
readonly code: EmbeddingProviderErrorCode;
|
|
28
|
+
readonly provider: string;
|
|
29
|
+
readonly name = "EmbeddingProviderError";
|
|
30
|
+
constructor(code: EmbeddingProviderErrorCode, provider: string, message: string, options?: {
|
|
31
|
+
cause?: unknown;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export declare function embeddingDiagnostic(error: unknown, provider: string): EmbeddingDiagnostic;
|
|
35
|
+
export declare function validateEmbeddingVector(provider: string, vector: number[], dimensions: number): void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export class EmbeddingProviderError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
provider;
|
|
4
|
+
name = "EmbeddingProviderError";
|
|
5
|
+
constructor(code, provider, message, options) {
|
|
6
|
+
super(message, options);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.provider = provider;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function embeddingDiagnostic(error, provider) {
|
|
12
|
+
if (error instanceof EmbeddingProviderError) {
|
|
13
|
+
return { code: error.code, provider: error.provider, message: error.message, degraded: true };
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
code: "provider_unavailable",
|
|
17
|
+
provider,
|
|
18
|
+
message: `Embedding provider '${provider}' failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
19
|
+
degraded: true
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function validateEmbeddingVector(provider, vector, dimensions) {
|
|
23
|
+
if (vector.length !== dimensions) {
|
|
24
|
+
throw new EmbeddingProviderError("dimension_mismatch", provider, `Embedding provider '${provider}' returned ${vector.length} dimensions; configured embedding.dimensions is ${dimensions}.`);
|
|
25
|
+
}
|
|
26
|
+
if (!vector.every((value) => Number.isFinite(value))) {
|
|
27
|
+
throw new EmbeddingProviderError("invalid_response", provider, `Embedding provider '${provider}' returned a non-finite vector.`);
|
|
28
|
+
}
|
|
29
|
+
}
|