@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
package/dist/query/search.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { GraphEntity, MDGraphConfig, SearchQueryMode, SearchResult } from "../types.js";
|
|
2
2
|
import { GraphRepository } from "../db/repositories.js";
|
|
3
|
+
import { type EmbeddingDiagnostic } from "../semantic/provider.js";
|
|
3
4
|
type SearchChannel = "definition" | "fts" | "semantic";
|
|
4
5
|
export interface SearchOptions {
|
|
5
6
|
semantic?: boolean;
|
|
@@ -17,8 +18,9 @@ export interface SearchExplanation {
|
|
|
17
18
|
fusion: "rrf";
|
|
18
19
|
fusionK: number;
|
|
19
20
|
channels: SearchChannel[];
|
|
20
|
-
optionalReranker:
|
|
21
|
+
optionalReranker: string;
|
|
21
22
|
};
|
|
23
|
+
semanticDiagnostic?: EmbeddingDiagnostic;
|
|
22
24
|
matchedEntities: Array<{
|
|
23
25
|
name: string;
|
|
24
26
|
kind: GraphEntity["kind"];
|
|
@@ -27,6 +29,8 @@ export interface SearchExplanation {
|
|
|
27
29
|
results: SearchResult[];
|
|
28
30
|
}
|
|
29
31
|
export declare function searchGraph(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): SearchResult[];
|
|
32
|
+
export declare function searchGraphAsync(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): Promise<SearchResult[]>;
|
|
30
33
|
export declare function explainSearchGraph(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): SearchExplanation;
|
|
34
|
+
export declare function explainSearchGraphAsync(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): Promise<SearchExplanation>;
|
|
31
35
|
export declare function extractQueryEntityCandidates(query: string): string[];
|
|
32
36
|
export {};
|
package/dist/query/search.js
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
|
|
2
|
+
import { createEmbeddingProvider, supportsSynchronousEmbeddingProvider } from "../semantic/provider-registry.js";
|
|
3
|
+
import { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector } from "../semantic/provider.js";
|
|
2
4
|
import { ftsQueryFor } from "../utils/fts.js";
|
|
3
5
|
import { normalizeEntityName } from "../utils/text.js";
|
|
4
6
|
const RRF_K = 60;
|
|
5
7
|
const RRF_SCORE_WEIGHT = 1_000;
|
|
6
8
|
export function searchGraph(repository, config, query, limit = config.search.defaultLimit, options = {}) {
|
|
9
|
+
const mode = resolveSearchMode(config, options);
|
|
10
|
+
const semanticRows = mode.semanticActive
|
|
11
|
+
? repository.searchSemanticChunks(embedTextLocal(query, config.embedding.dimensions), config.embedding.provider, config.embedding.model, limit * 2)
|
|
12
|
+
: [];
|
|
13
|
+
return rankSearchResults(repository, config, query, limit, semanticRows, mode.semanticActive ? config.embedding.provider : undefined);
|
|
14
|
+
}
|
|
15
|
+
export async function searchGraphAsync(repository, config, query, limit = config.search.defaultLimit, options = {}) {
|
|
16
|
+
return (await executeSearchGraphAsync(repository, config, query, limit, options)).results;
|
|
17
|
+
}
|
|
18
|
+
function rankSearchResults(repository, config, query, limit, semanticRows, semanticProvider) {
|
|
7
19
|
const entityCandidates = extractQueryEntityCandidates(query);
|
|
8
20
|
const matchedEntities = repository.findEntitiesByNormalizedNames(entityCandidates.map(normalizeEntityName));
|
|
9
21
|
const entityDocumentFrequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
|
|
10
22
|
const definitionRows = repository.findEntityDefinitions(matchedEntities.map((entity) => entity.id));
|
|
11
23
|
const ftsQuery = ftsQueryFor(query);
|
|
12
24
|
const ftsRows = ftsQuery ? repository.searchChunks(ftsQuery, limit * 2) : [];
|
|
13
|
-
const mode = resolveSearchMode(config, options);
|
|
14
|
-
const semanticRows = mode.semanticActive
|
|
15
|
-
? repository.searchSemanticChunks(embedTextLocal(query, config.embedding.dimensions), config.embedding.provider, config.embedding.model, limit * 2)
|
|
16
|
-
: [];
|
|
17
25
|
const results = [];
|
|
18
26
|
for (const [index, row] of definitionRows.entries()) {
|
|
19
27
|
const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
|
|
@@ -56,7 +64,7 @@ export function searchGraph(repository, config, query, limit = config.search.def
|
|
|
56
64
|
document: row.document,
|
|
57
65
|
section: row.section,
|
|
58
66
|
score: adjustScore(80 + row.similarity * 50, row.document, penalty),
|
|
59
|
-
reason: highFrequencyReason(
|
|
67
|
+
reason: highFrequencyReason(`${semanticProvider === "local-hash" ? "local" : semanticProvider ?? "configured"} semantic vector match (${row.similarity.toFixed(3)})`, matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold),
|
|
60
68
|
content: row.chunk.content,
|
|
61
69
|
matchedEntities: matched,
|
|
62
70
|
semantic: {
|
|
@@ -73,27 +81,39 @@ export function searchGraph(repository, config, query, limit = config.search.def
|
|
|
73
81
|
.slice(0, limit);
|
|
74
82
|
}
|
|
75
83
|
export function explainSearchGraph(repository, config, query, limit = config.search.defaultLimit, options = {}) {
|
|
84
|
+
const mode = resolveSearchMode(config, options);
|
|
85
|
+
const results = searchGraph(repository, config, query, limit, options);
|
|
86
|
+
return buildSearchExplanation(repository, config, query, limit, results, {
|
|
87
|
+
queryMode: mode.queryMode,
|
|
88
|
+
semanticRequested: mode.semanticRequested,
|
|
89
|
+
semanticProvider: mode.semanticActive ? config.embedding.provider : undefined
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
export async function explainSearchGraphAsync(repository, config, query, limit = config.search.defaultLimit, options = {}) {
|
|
93
|
+
const execution = await executeSearchGraphAsync(repository, config, query, limit, options);
|
|
94
|
+
return buildSearchExplanation(repository, config, query, limit, execution.results, execution);
|
|
95
|
+
}
|
|
96
|
+
function buildSearchExplanation(repository, config, query, limit, results, execution) {
|
|
76
97
|
const entityCandidates = extractQueryEntityCandidates(query);
|
|
77
98
|
const matchedEntities = repository.findEntitiesByNormalizedNames(entityCandidates.map(normalizeEntityName));
|
|
78
99
|
const frequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
|
|
79
|
-
const mode = resolveSearchMode(config, options);
|
|
80
|
-
const results = searchGraph(repository, config, query, limit, options);
|
|
81
100
|
const channels = channelsForResults(results);
|
|
82
|
-
const semanticActive =
|
|
101
|
+
const semanticActive = channels.includes("semantic");
|
|
83
102
|
return {
|
|
84
103
|
query,
|
|
85
104
|
limit,
|
|
86
|
-
queryMode:
|
|
105
|
+
queryMode: execution.queryMode,
|
|
87
106
|
entityCandidates,
|
|
88
107
|
ftsQuery: ftsQueryFor(query),
|
|
89
|
-
semanticEnabled:
|
|
108
|
+
semanticEnabled: execution.semanticRequested,
|
|
90
109
|
semanticActive,
|
|
91
110
|
ranking: {
|
|
92
111
|
fusion: "rrf",
|
|
93
112
|
fusionK: RRF_K,
|
|
94
113
|
channels,
|
|
95
|
-
optionalReranker: semanticActive ?
|
|
114
|
+
optionalReranker: semanticActive ? execution.semanticProvider ?? config.embedding.provider : "none"
|
|
96
115
|
},
|
|
116
|
+
semanticDiagnostic: execution.semanticDiagnostic,
|
|
97
117
|
matchedEntities: matchedEntities.map((entity) => ({
|
|
98
118
|
name: entity.name,
|
|
99
119
|
kind: entity.kind,
|
|
@@ -102,6 +122,44 @@ export function explainSearchGraph(repository, config, query, limit = config.sea
|
|
|
102
122
|
results
|
|
103
123
|
};
|
|
104
124
|
}
|
|
125
|
+
async function executeSearchGraphAsync(repository, config, query, limit, options) {
|
|
126
|
+
const request = resolveSearchRequest(config, options);
|
|
127
|
+
if (!request.semanticRequested) {
|
|
128
|
+
return {
|
|
129
|
+
results: rankSearchResults(repository, config, query, limit, [], undefined),
|
|
130
|
+
queryMode: request.queryMode,
|
|
131
|
+
semanticRequested: false
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
let providerId = config.embedding.provider;
|
|
135
|
+
try {
|
|
136
|
+
const vectorCount = repository.semanticVectorCount(config.embedding.provider, config.embedding.model, config.embedding.dimensions);
|
|
137
|
+
const chunkCount = repository.counts().chunks;
|
|
138
|
+
if (vectorCount !== chunkCount || chunkCount === 0) {
|
|
139
|
+
throw new EmbeddingProviderError("vectors_unavailable", config.embedding.provider, `Semantic vectors for ${config.embedding.provider}/${config.embedding.model}/${config.embedding.dimensions} cover ${vectorCount}/${chunkCount} chunks; run \`mdgraph index --full --semantic\`.`);
|
|
140
|
+
}
|
|
141
|
+
const provider = createEmbeddingProvider(config.embedding);
|
|
142
|
+
providerId = provider.id;
|
|
143
|
+
const queryVector = await provider.embedQuery(query);
|
|
144
|
+
validateEmbeddingVector(provider.id, queryVector, provider.dimensions);
|
|
145
|
+
const semanticRows = repository.searchSemanticChunks(queryVector, provider.id, provider.model, limit * 2);
|
|
146
|
+
return {
|
|
147
|
+
results: rankSearchResults(repository, config, query, limit, semanticRows, provider.id),
|
|
148
|
+
queryMode: request.queryMode,
|
|
149
|
+
semanticRequested: true,
|
|
150
|
+
semanticProvider: provider.id
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return {
|
|
155
|
+
results: rankSearchResults(repository, config, query, limit, [], undefined),
|
|
156
|
+
queryMode: request.queryMode,
|
|
157
|
+
semanticRequested: true,
|
|
158
|
+
semanticProvider: providerId,
|
|
159
|
+
semanticDiagnostic: embeddingDiagnostic(error, providerId)
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
105
163
|
export function extractQueryEntityCandidates(query) {
|
|
106
164
|
const candidates = query.match(/`([^`]+)`|\b[A-Z][A-Za-z0-9_.]+\b|\b[A-Z][A-Z0-9_]{2,}\b|\/[A-Za-z0-9_./:{}-]+/g) ?? [];
|
|
107
165
|
return candidates.map((candidate) => candidate.replace(/^`|`$/g, "").trim()).filter(Boolean);
|
|
@@ -158,10 +216,16 @@ function statusBoost(status) {
|
|
|
158
216
|
return 0;
|
|
159
217
|
}
|
|
160
218
|
function resolveSearchMode(config, options) {
|
|
219
|
+
const { queryMode, semanticRequested } = resolveSearchRequest(config, options);
|
|
220
|
+
const semanticActive = semanticRequested
|
|
221
|
+
&& supportsSynchronousEmbeddingProvider(config.embedding.provider)
|
|
222
|
+
&& supportsLocalEmbedding({ ...config, embedding: { ...config.embedding, enabled: true } });
|
|
223
|
+
return { queryMode, semanticRequested, semanticActive };
|
|
224
|
+
}
|
|
225
|
+
function resolveSearchRequest(config, options) {
|
|
161
226
|
const queryMode = options.queryMode ?? (options.semantic ? "semantic" : "auto");
|
|
162
227
|
const semanticRequested = queryMode === "semantic" || (queryMode === "auto" && (options.semantic ?? config.embedding.enabled));
|
|
163
|
-
|
|
164
|
-
return { queryMode, semanticRequested, semanticActive };
|
|
228
|
+
return { queryMode, semanticRequested };
|
|
165
229
|
}
|
|
166
230
|
function applyReciprocalRankFusion(results) {
|
|
167
231
|
const fusionByKey = new Map();
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { GraphRepository } from "../db/repositories.js";
|
|
2
|
+
import type { GraphDocument } from "../types.js";
|
|
3
|
+
import { type StructuredQueryAST } from "./structured-query.js";
|
|
4
|
+
export type StructuredQueryExecutionStage = "document" | "metadata" | "graph" | "doctor";
|
|
5
|
+
export interface StructuredQueryItem {
|
|
6
|
+
document: GraphDocument;
|
|
7
|
+
reason: string;
|
|
8
|
+
predicateFields: string[];
|
|
9
|
+
provenance: StructuredQueryExecutionStage[];
|
|
10
|
+
}
|
|
11
|
+
export interface StructuredQueryResult {
|
|
12
|
+
query: string;
|
|
13
|
+
ast: StructuredQueryAST;
|
|
14
|
+
execution: {
|
|
15
|
+
strategy: "parameterized-sql" | "parameterized-hybrid-doctor";
|
|
16
|
+
stages: StructuredQueryExecutionStage[];
|
|
17
|
+
parameterCount: number;
|
|
18
|
+
doctorHealthEvaluated: boolean;
|
|
19
|
+
};
|
|
20
|
+
total: number;
|
|
21
|
+
returned: number;
|
|
22
|
+
truncated: boolean;
|
|
23
|
+
items: StructuredQueryItem[];
|
|
24
|
+
}
|
|
25
|
+
export declare class StructuredQueryExecutionError extends Error {
|
|
26
|
+
readonly name = "StructuredQueryExecutionError";
|
|
27
|
+
}
|
|
28
|
+
export declare function executeStructuredQuery(repository: GraphRepository, projectRoot: string, query: string, ast?: StructuredQueryAST): Promise<StructuredQueryResult>;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { runDoctor } from "../analysis/doctor.js";
|
|
2
|
+
import { formatStructuredQueryExpression, parseStructuredQuery, structuredQueryPredicates, structuredQueryUsesHealth, validateStructuredQuery } from "./structured-query.js";
|
|
3
|
+
export class StructuredQueryExecutionError extends Error {
|
|
4
|
+
name = "StructuredQueryExecutionError";
|
|
5
|
+
}
|
|
6
|
+
export async function executeStructuredQuery(repository, projectRoot, query, ast = parseStructuredQuery(query)) {
|
|
7
|
+
validateStructuredQuery(ast);
|
|
8
|
+
const predicates = structuredQueryPredicates(ast.expression);
|
|
9
|
+
const predicateFields = [...new Set(predicates.map((predicate) => predicate.field))];
|
|
10
|
+
const stages = stagesForPredicates(predicates);
|
|
11
|
+
const reason = `matched structured query: ${formatStructuredQueryExpression(ast.expression)}`;
|
|
12
|
+
if (!structuredQueryUsesHealth(ast.expression)) {
|
|
13
|
+
const rows = repository.queryStructuredDocuments(ast);
|
|
14
|
+
const items = rows.documents.map((document) => ({ document, reason, predicateFields, provenance: stages }));
|
|
15
|
+
return {
|
|
16
|
+
query,
|
|
17
|
+
ast,
|
|
18
|
+
execution: {
|
|
19
|
+
strategy: "parameterized-sql",
|
|
20
|
+
stages,
|
|
21
|
+
parameterCount: rows.parameterCount,
|
|
22
|
+
doctorHealthEvaluated: false
|
|
23
|
+
},
|
|
24
|
+
total: rows.total,
|
|
25
|
+
returned: items.length,
|
|
26
|
+
truncated: rows.truncated,
|
|
27
|
+
items
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const doctor = await runDoctor(projectRoot, { applySchema: false });
|
|
31
|
+
if (doctor.staleIndex.stale) {
|
|
32
|
+
throw new StructuredQueryExecutionError("Health predicates require a fresh index; run `mdgraph index` before retrying the structured query.");
|
|
33
|
+
}
|
|
34
|
+
const predicateMatches = new Map();
|
|
35
|
+
let parameterCount = 0;
|
|
36
|
+
for (const predicate of uniquePredicates(predicates.filter((predicate) => predicate.field !== "health"))) {
|
|
37
|
+
const matched = repository.documentIdsMatchingStructuredPredicate(predicate);
|
|
38
|
+
predicateMatches.set(predicateKey(predicate), matched.documentIds);
|
|
39
|
+
parameterCount += matched.parameterCount;
|
|
40
|
+
}
|
|
41
|
+
const health = healthDocumentPaths(doctor);
|
|
42
|
+
const matchedDocuments = repository.allDocuments()
|
|
43
|
+
.filter((document) => evaluateExpression(ast.expression, document, predicateMatches, health))
|
|
44
|
+
.sort(documentComparator(ast.orderBy));
|
|
45
|
+
const documents = matchedDocuments.slice(0, ast.limit);
|
|
46
|
+
const items = documents.map((document) => ({ document, reason, predicateFields, provenance: stages }));
|
|
47
|
+
return {
|
|
48
|
+
query,
|
|
49
|
+
ast,
|
|
50
|
+
execution: {
|
|
51
|
+
strategy: "parameterized-hybrid-doctor",
|
|
52
|
+
stages,
|
|
53
|
+
parameterCount,
|
|
54
|
+
doctorHealthEvaluated: true
|
|
55
|
+
},
|
|
56
|
+
total: matchedDocuments.length,
|
|
57
|
+
returned: items.length,
|
|
58
|
+
truncated: matchedDocuments.length > ast.limit,
|
|
59
|
+
items
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function evaluateExpression(expression, document, predicateMatches, health) {
|
|
63
|
+
if (expression.kind === "predicate") {
|
|
64
|
+
if (expression.field === "health") {
|
|
65
|
+
const matches = health.get(expression.value)?.has(document.path) ?? false;
|
|
66
|
+
return expression.operator === "!=" ? !matches : matches;
|
|
67
|
+
}
|
|
68
|
+
return predicateMatches.get(predicateKey(expression))?.has(document.id) ?? false;
|
|
69
|
+
}
|
|
70
|
+
if (expression.kind === "not") {
|
|
71
|
+
return !evaluateExpression(expression.expression, document, predicateMatches, health);
|
|
72
|
+
}
|
|
73
|
+
if (expression.kind === "and") {
|
|
74
|
+
return evaluateExpression(expression.left, document, predicateMatches, health)
|
|
75
|
+
&& evaluateExpression(expression.right, document, predicateMatches, health);
|
|
76
|
+
}
|
|
77
|
+
return evaluateExpression(expression.left, document, predicateMatches, health)
|
|
78
|
+
|| evaluateExpression(expression.right, document, predicateMatches, health);
|
|
79
|
+
}
|
|
80
|
+
function healthDocumentPaths(report) {
|
|
81
|
+
return new Map([
|
|
82
|
+
["dead_link", new Set(report.deadLinks.map((issue) => issue.documentPath))],
|
|
83
|
+
["orphan", new Set(report.orphanDocs.map((document) => document.path))],
|
|
84
|
+
["stale_source_ref", new Set(report.staleSourceRefs.flatMap((issue) => issue.documentPaths))],
|
|
85
|
+
["missing_definition", new Set(report.missingDefinitions.map((issue) => issue.document.path))],
|
|
86
|
+
["weakly_linked", new Set(report.weaklyLinkedDocs.map((issue) => issue.document.path))],
|
|
87
|
+
["possible_contradiction", new Set(report.possibleContradictions.flatMap((issue) => issue.documents.map((document) => document.path)))],
|
|
88
|
+
["content_risk", new Set(report.contentRisks.map((issue) => issue.documentPath))]
|
|
89
|
+
]);
|
|
90
|
+
}
|
|
91
|
+
function documentComparator(orderBy) {
|
|
92
|
+
const sorts = orderBy.length ? orderBy : [{ field: "path", direction: "asc" }];
|
|
93
|
+
return (left, right) => {
|
|
94
|
+
for (const sort of sorts) {
|
|
95
|
+
const comparison = documentSortValue(left, sort.field).localeCompare(documentSortValue(right, sort.field));
|
|
96
|
+
if (comparison !== 0) {
|
|
97
|
+
return sort.direction === "desc" ? -comparison : comparison;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return left.path.localeCompare(right.path);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function documentSortValue(document, field) {
|
|
104
|
+
switch (field) {
|
|
105
|
+
case "path": return document.path;
|
|
106
|
+
case "title": return document.title;
|
|
107
|
+
case "type": return document.type;
|
|
108
|
+
case "status": return document.status;
|
|
109
|
+
case "trust": return document.trustTier;
|
|
110
|
+
case "updated": return document.updatedAt ?? "";
|
|
111
|
+
case "indexed": return document.indexedAt;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function stagesForPredicates(predicates) {
|
|
115
|
+
const stages = new Set();
|
|
116
|
+
for (const predicate of predicates) {
|
|
117
|
+
if (predicate.field === "tag") {
|
|
118
|
+
stages.add("metadata");
|
|
119
|
+
}
|
|
120
|
+
else if (predicate.field === "edge" || predicate.field.startsWith("edge.")) {
|
|
121
|
+
stages.add("graph");
|
|
122
|
+
}
|
|
123
|
+
else if (predicate.field === "health") {
|
|
124
|
+
stages.add("doctor");
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
stages.add("document");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const order = ["document", "metadata", "graph", "doctor"];
|
|
131
|
+
return order.filter((stage) => stages.has(stage));
|
|
132
|
+
}
|
|
133
|
+
function uniquePredicates(predicates) {
|
|
134
|
+
return [...new Map(predicates.map((predicate) => [predicateKey(predicate), predicate])).values()];
|
|
135
|
+
}
|
|
136
|
+
function predicateKey(predicate) {
|
|
137
|
+
return `${predicate.field}\u0000${predicate.operator}\u0000${predicate.value}`;
|
|
138
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type EdgeKind } from "../types.js";
|
|
2
|
+
export declare const STRUCTURED_QUERY_DEFAULT_LIMIT = 50;
|
|
3
|
+
export declare const STRUCTURED_QUERY_MAX_LIMIT = 500;
|
|
4
|
+
export declare const STRUCTURED_QUERY_HEALTH_VALUES: readonly ["dead_link", "orphan", "stale_source_ref", "missing_definition", "weakly_linked", "possible_contradiction", "content_risk"];
|
|
5
|
+
export type StructuredQueryHealth = typeof STRUCTURED_QUERY_HEALTH_VALUES[number];
|
|
6
|
+
export type StructuredQueryOperator = "=" | "!=" | "~" | "!~" | "<" | "<=" | ">" | ">=";
|
|
7
|
+
export type StructuredQuerySortDirection = "asc" | "desc";
|
|
8
|
+
export type StructuredQueryField = "type" | "status" | "trust" | "path" | "title" | "updated" | "indexed" | "tag" | "edge" | `edge.${EdgeKind}` | "health";
|
|
9
|
+
export interface StructuredQueryPredicate {
|
|
10
|
+
kind: "predicate";
|
|
11
|
+
field: StructuredQueryField;
|
|
12
|
+
operator: StructuredQueryOperator;
|
|
13
|
+
value: string;
|
|
14
|
+
}
|
|
15
|
+
export interface StructuredQueryLogicalExpression {
|
|
16
|
+
kind: "and" | "or";
|
|
17
|
+
left: StructuredQueryExpression;
|
|
18
|
+
right: StructuredQueryExpression;
|
|
19
|
+
}
|
|
20
|
+
export interface StructuredQueryNotExpression {
|
|
21
|
+
kind: "not";
|
|
22
|
+
expression: StructuredQueryExpression;
|
|
23
|
+
}
|
|
24
|
+
export type StructuredQueryExpression = StructuredQueryPredicate | StructuredQueryLogicalExpression | StructuredQueryNotExpression;
|
|
25
|
+
export interface StructuredQuerySort {
|
|
26
|
+
field: Extract<StructuredQueryField, "path" | "title" | "type" | "status" | "trust" | "updated" | "indexed">;
|
|
27
|
+
direction: StructuredQuerySortDirection;
|
|
28
|
+
}
|
|
29
|
+
export interface StructuredQueryAST {
|
|
30
|
+
expression: StructuredQueryExpression;
|
|
31
|
+
orderBy: StructuredQuerySort[];
|
|
32
|
+
limit: number;
|
|
33
|
+
}
|
|
34
|
+
export type StructuredQueryTokenKind = "word" | "string" | "operator" | "left_paren" | "right_paren" | "comma";
|
|
35
|
+
export interface StructuredQueryToken {
|
|
36
|
+
kind: StructuredQueryTokenKind;
|
|
37
|
+
value: string;
|
|
38
|
+
offset: number;
|
|
39
|
+
}
|
|
40
|
+
export declare class StructuredQuerySyntaxError extends Error {
|
|
41
|
+
readonly offset: number;
|
|
42
|
+
readonly name = "StructuredQuerySyntaxError";
|
|
43
|
+
constructor(message: string, offset: number);
|
|
44
|
+
}
|
|
45
|
+
export declare function tokenizeStructuredQuery(input: string): StructuredQueryToken[];
|
|
46
|
+
export declare function parseStructuredQuery(input: string): StructuredQueryAST;
|
|
47
|
+
export declare function validateStructuredQuery(ast: StructuredQueryAST): void;
|
|
48
|
+
export declare function structuredQueryUsesHealth(expression: StructuredQueryExpression): boolean;
|
|
49
|
+
export declare function structuredQueryPredicates(expression: StructuredQueryExpression): StructuredQueryPredicate[];
|
|
50
|
+
export declare function formatStructuredQueryExpression(expression: StructuredQueryExpression): string;
|