@daogee/mdgraph 1.1.0 → 1.2.1
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 +42 -0
- package/README-ZH.md +13 -3
- package/README.md +13 -3
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +5 -1
- package/agent-pack/prompts/wiki-authoring.md +12 -0
- package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
- package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
- package/dist/analysis/status-freshness.d.ts +8 -1
- package/dist/analysis/status-freshness.js +19 -6
- package/dist/bin/mdgraph.js +125 -6
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +30 -5
- package/dist/db/repositories.js +171 -8
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/retrieval-eval.d.ts +11 -0
- package/dist/evaluation/retrieval-eval.js +35 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.js +3 -0
- package/dist/indexer.js +64 -6
- package/dist/mcp/server.js +5 -4
- package/dist/mcp/tools.js +26 -11
- package/dist/query/context-builder.d.ts +2 -0
- package/dist/query/context-builder.js +154 -24
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.js +30 -8
- package/dist/scanner/file-scanner.js +7 -7
- package/dist/semantic/ollama-provider.js +6 -1
- package/dist/utils/fts.d.ts +1 -0
- package/dist/utils/fts.js +68 -13
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.js +121 -17
- package/dist/wiki/wiki-dependencies.d.ts +20 -0
- package/dist/wiki/wiki-dependencies.js +45 -0
- package/dist/wiki/wiki-domains.d.ts +13 -0
- package/dist/wiki/wiki-domains.js +55 -0
- package/dist/wiki/wiki-evidence.d.ts +27 -0
- package/dist/wiki/wiki-evidence.js +112 -0
- package/dist/wiki/wiki-plan.d.ts +121 -0
- package/dist/wiki/wiki-plan.js +616 -0
- package/dist/wiki/wiki-status.d.ts +67 -0
- package/dist/wiki/wiki-status.js +451 -0
- package/docs/EN/Agent_Integration.md +16 -4
- package/docs/EN/Architecture.md +14 -2
- package/docs/EN/Evaluation_Questions.md +21 -1
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +22 -0
- package/docs/EN/Output_Contracts.md +44 -3
- package/docs/EN/Public_Contracts.md +4 -2
- package/docs/EN/Public_Contracts_1.0.md +4 -0
- package/docs/EN/README.md +1 -0
- package/docs/EN/Release_Checklist.md +3 -2
- package/docs/EN/Retrieval_and_Context.md +20 -5
- package/docs/ZH/Agent_Integration.md +16 -4
- package/docs/ZH/Architecture.md +14 -4
- package/docs/ZH/Evaluation_Questions.md +21 -1
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +22 -0
- package/docs/ZH/Output_Contracts.md +44 -3
- package/docs/ZH/Public_Contracts.md +4 -2
- package/docs/ZH/Public_Contracts_1.0.md +4 -0
- package/docs/ZH/README.md +1 -0
- package/docs/ZH/Release_Checklist.md +3 -2
- package/docs/ZH/Retrieval_and_Context.md +20 -5
- package/package.json +8 -3
package/dist/db/repositories.js
CHANGED
|
@@ -2,6 +2,12 @@ import { readSchemaMetadata } from "./connection.js";
|
|
|
2
2
|
import { decodeFloat32Vector, encodeFloat32Vector } from "../semantic/vector-codec.js";
|
|
3
3
|
import { ftsIndexContent } from "../utils/fts.js";
|
|
4
4
|
import { normalizePath, slugifyHeading } from "../utils/text.js";
|
|
5
|
+
export class IndexGenerationConflict extends Error {
|
|
6
|
+
constructor() {
|
|
7
|
+
super("The index changed while this scan was running.");
|
|
8
|
+
this.name = "IndexGenerationConflict";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
5
11
|
export class GraphRepository {
|
|
6
12
|
db;
|
|
7
13
|
constructor(db) {
|
|
@@ -10,21 +16,41 @@ export class GraphRepository {
|
|
|
10
16
|
close() {
|
|
11
17
|
this.db.close();
|
|
12
18
|
}
|
|
13
|
-
|
|
19
|
+
indexWriteState() {
|
|
20
|
+
const rows = this.db.prepare("SELECT key, value FROM schema_metadata WHERE key IN ('index_extraction_fingerprint', 'index_generation')").all();
|
|
21
|
+
const values = new Map(rows.map((row) => [row.key, row.value]));
|
|
22
|
+
const generation = Number(values.get("index_generation") ?? "0");
|
|
23
|
+
return {
|
|
24
|
+
extractionFingerprint: values.get("index_extraction_fingerprint"),
|
|
25
|
+
generation: Number.isSafeInteger(generation) && generation >= 0 ? generation : 0
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
replaceAll(records, state) {
|
|
14
29
|
const write = this.db.transaction(() => {
|
|
30
|
+
this.assertExpectedGeneration(state?.expectedGeneration);
|
|
15
31
|
this.db.exec("DELETE FROM chunks_fts; DELETE FROM chunk_vectors; DELETE FROM edges; DELETE FROM chunks; DELETE FROM source_refs; DELETE FROM entities; DELETE FROM sections; DELETE FROM documents;");
|
|
16
32
|
this.insertRecords(records, "strict");
|
|
33
|
+
this.writeIndexState(state);
|
|
17
34
|
});
|
|
18
35
|
write();
|
|
19
36
|
this.compactStorage({ vacuum: true });
|
|
20
37
|
}
|
|
21
|
-
replaceDocuments(records, changedDocumentIds, deletedDocumentIds) {
|
|
38
|
+
replaceDocuments(records, changedDocumentIds, deletedDocumentIds, canonical, state) {
|
|
22
39
|
const write = this.db.transaction(() => {
|
|
40
|
+
this.assertExpectedGeneration(state?.expectedGeneration);
|
|
23
41
|
for (const documentId of [...changedDocumentIds, ...deletedDocumentIds]) {
|
|
24
42
|
this.deleteDocumentDerivedRecords(documentId);
|
|
25
43
|
}
|
|
26
44
|
this.insertRecords(records, "incremental");
|
|
27
|
-
|
|
45
|
+
if (canonical) {
|
|
46
|
+
// Entity and deterministic edge resolution depends on every document, not
|
|
47
|
+
// only on the changed subset. Reconcile it from the complete candidate graph.
|
|
48
|
+
this.reconcileSharedGraphRecords(canonical);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
this.pruneUnreferencedEntitiesAndSources();
|
|
52
|
+
}
|
|
53
|
+
this.writeIndexState(state);
|
|
28
54
|
});
|
|
29
55
|
write();
|
|
30
56
|
this.compactStorage({ vacuum: false });
|
|
@@ -80,7 +106,43 @@ export class GraphRepository {
|
|
|
80
106
|
const rows = this.db.prepare("SELECT id, path, hash FROM documents").all();
|
|
81
107
|
return new Map(rows.map((row) => [stringValue(row.path), { id: stringValue(row.id), hash: stringValue(row.hash) }]));
|
|
82
108
|
}
|
|
83
|
-
|
|
109
|
+
reusableVectors(chunks, profile) {
|
|
110
|
+
if (!chunks.length)
|
|
111
|
+
return [];
|
|
112
|
+
const candidateContent = new Map(chunks.map((chunk) => [chunk.id, chunk.content]));
|
|
113
|
+
const rows = this.db.prepare(`
|
|
114
|
+
SELECT c.id AS chunk_id, c.content, v.provider, v.model, v.dimensions, v.vector_blob, v.created_at
|
|
115
|
+
FROM chunks c JOIN chunk_vectors v ON v.chunk_id = c.id
|
|
116
|
+
WHERE v.provider = ? AND v.model = ? AND v.dimensions = ?
|
|
117
|
+
`).all(profile.provider, profile.model, profile.dimensions);
|
|
118
|
+
const reusable = [];
|
|
119
|
+
for (const row of rows) {
|
|
120
|
+
const chunkId = stringValue(row.chunk_id);
|
|
121
|
+
if (candidateContent.get(chunkId) !== stringValue(row.content))
|
|
122
|
+
continue;
|
|
123
|
+
try {
|
|
124
|
+
const vector = decodeFloat32Vector(row.vector_blob);
|
|
125
|
+
if (vector.length !== profile.dimensions || !vector.every(Number.isFinite))
|
|
126
|
+
continue;
|
|
127
|
+
reusable.push({ chunkId, provider: stringValue(row.provider), model: stringValue(row.model), dimensions: numberValue(row.dimensions), vector, createdAt: stringValue(row.created_at) });
|
|
128
|
+
}
|
|
129
|
+
catch { /* stale or malformed vectors are regenerated */ }
|
|
130
|
+
}
|
|
131
|
+
return reusable;
|
|
132
|
+
}
|
|
133
|
+
preservedDerivedEdges(records) {
|
|
134
|
+
const candidateHashes = new Map(records.documents.map((document) => [document.id, document.hash]));
|
|
135
|
+
const rows = this.db.prepare(`
|
|
136
|
+
SELECT e.*
|
|
137
|
+
FROM edges e
|
|
138
|
+
JOIN documents from_document ON from_document.id = e.from_id
|
|
139
|
+
JOIN documents to_document ON to_document.id = e.to_id
|
|
140
|
+
WHERE e.provenance = 'embedding_similarity'
|
|
141
|
+
`).all();
|
|
142
|
+
return rows.map(rowToEdge).filter((edge) => (candidateHashes.get(edge.fromId) === this.documentHash(edge.fromId)
|
|
143
|
+
&& candidateHashes.get(edge.toId) === this.documentHash(edge.toId)));
|
|
144
|
+
}
|
|
145
|
+
searchChunks(ftsQuery, limit, documentId) {
|
|
84
146
|
const rows = this.db.prepare(`
|
|
85
147
|
SELECT
|
|
86
148
|
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
@@ -96,9 +158,10 @@ export class GraphRepository {
|
|
|
96
158
|
JOIN documents d ON d.id = c.document_id
|
|
97
159
|
LEFT JOIN sections s ON s.id = c.section_id
|
|
98
160
|
WHERE chunks_fts MATCH ?
|
|
99
|
-
|
|
161
|
+
${documentId ? "AND d.id = ?" : ""}
|
|
162
|
+
ORDER BY rank ASC, c.id ASC
|
|
100
163
|
LIMIT ?
|
|
101
|
-
`).all(ftsQuery, limit);
|
|
164
|
+
`).all(...(documentId ? [ftsQuery, documentId, limit] : [ftsQuery, limit]));
|
|
102
165
|
return rows.map((row) => ({
|
|
103
166
|
document: rowToDocument(row, "d_"),
|
|
104
167
|
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
@@ -106,6 +169,25 @@ export class GraphRepository {
|
|
|
106
169
|
rank: numberValue(row.rank)
|
|
107
170
|
}));
|
|
108
171
|
}
|
|
172
|
+
contextChunksForDocument(documentId) {
|
|
173
|
+
const rows = this.db.prepare(`
|
|
174
|
+
SELECT
|
|
175
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
176
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
177
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
178
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
179
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
180
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
181
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
182
|
+
0 AS rank
|
|
183
|
+
FROM chunks c
|
|
184
|
+
JOIN documents d ON d.id = c.document_id
|
|
185
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
186
|
+
WHERE d.id = ?
|
|
187
|
+
ORDER BY s.start_line ASC, c.id ASC
|
|
188
|
+
`).all(documentId);
|
|
189
|
+
return rows.map(rowToChunkSearchRow);
|
|
190
|
+
}
|
|
109
191
|
findEntitiesByNormalizedNames(names) {
|
|
110
192
|
if (!names.length) {
|
|
111
193
|
return [];
|
|
@@ -169,7 +251,7 @@ export class GraphRepository {
|
|
|
169
251
|
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
170
252
|
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
171
253
|
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
172
|
-
e.weight AS rank
|
|
254
|
+
e.weight AS rank, e.to_id AS entity_id
|
|
173
255
|
FROM edges e
|
|
174
256
|
LEFT JOIN sections s ON s.id = e.from_id
|
|
175
257
|
JOIN documents d ON d.id = COALESCE(s.document_id, e.from_id)
|
|
@@ -183,7 +265,8 @@ export class GraphRepository {
|
|
|
183
265
|
document: rowToDocument(row, "d_"),
|
|
184
266
|
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
185
267
|
chunk: definitionChunk(row, sectionChunk, documentChunk),
|
|
186
|
-
rank: numberValue(row.rank)
|
|
268
|
+
rank: numberValue(row.rank),
|
|
269
|
+
entityId: stringValue(row.entity_id)
|
|
187
270
|
})));
|
|
188
271
|
}
|
|
189
272
|
searchSemanticChunks(queryVector, provider, model, limit) {
|
|
@@ -712,6 +795,86 @@ export class GraphRepository {
|
|
|
712
795
|
insertVector.run(vectorToParams(vector));
|
|
713
796
|
}
|
|
714
797
|
}
|
|
798
|
+
reconcileSharedGraphRecords(records) {
|
|
799
|
+
const insertEntity = this.db.prepare(`
|
|
800
|
+
INSERT INTO entities (id, name, normalized_name, kind, namespace, created_at, metadata_json)
|
|
801
|
+
VALUES (@id, @name, @normalizedName, @kind, @namespace, @createdAt, @metadataJson)
|
|
802
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
803
|
+
name = excluded.name, normalized_name = excluded.normalized_name, kind = excluded.kind,
|
|
804
|
+
namespace = excluded.namespace, metadata_json = excluded.metadata_json
|
|
805
|
+
WHERE entities.name <> excluded.name OR entities.normalized_name <> excluded.normalized_name
|
|
806
|
+
OR entities.kind <> excluded.kind OR entities.namespace IS NOT excluded.namespace
|
|
807
|
+
OR entities.metadata_json IS NOT excluded.metadata_json
|
|
808
|
+
`);
|
|
809
|
+
const insertSourceRef = this.db.prepare(`
|
|
810
|
+
INSERT INTO source_refs (id, path, normalized_path, created_at, metadata_json)
|
|
811
|
+
VALUES (@id, @path, @normalizedPath, @createdAt, @metadataJson)
|
|
812
|
+
ON CONFLICT(id) DO UPDATE SET path = excluded.path, normalized_path = excluded.normalized_path,
|
|
813
|
+
metadata_json = excluded.metadata_json
|
|
814
|
+
WHERE source_refs.path <> excluded.path OR source_refs.normalized_path <> excluded.normalized_path
|
|
815
|
+
OR source_refs.metadata_json IS NOT excluded.metadata_json
|
|
816
|
+
`);
|
|
817
|
+
const insertEdge = this.db.prepare(`
|
|
818
|
+
INSERT INTO edges (id, from_id, to_id, kind, weight, confidence, provenance, metadata_json, created_at)
|
|
819
|
+
VALUES (@id, @fromId, @toId, @kind, @weight, @confidence, @provenance, @metadataJson, @createdAt)
|
|
820
|
+
ON CONFLICT(id) DO UPDATE SET from_id = excluded.from_id, to_id = excluded.to_id, kind = excluded.kind,
|
|
821
|
+
weight = excluded.weight, confidence = excluded.confidence, provenance = excluded.provenance,
|
|
822
|
+
metadata_json = excluded.metadata_json
|
|
823
|
+
WHERE edges.from_id <> excluded.from_id OR edges.to_id <> excluded.to_id OR edges.kind <> excluded.kind
|
|
824
|
+
OR edges.weight <> excluded.weight OR edges.confidence <> excluded.confidence
|
|
825
|
+
OR edges.provenance <> excluded.provenance OR edges.metadata_json IS NOT excluded.metadata_json
|
|
826
|
+
`);
|
|
827
|
+
const candidateEntities = new Set(records.entities.map((entity) => entity.id));
|
|
828
|
+
const candidateSources = new Set(records.sourceRefs.map((sourceRef) => sourceRef.id));
|
|
829
|
+
const candidateEdges = new Set(records.edges.map((edge) => edge.id));
|
|
830
|
+
const staleEdges = this.db.prepare("SELECT id FROM edges WHERE provenance <> 'embedding_similarity'").all();
|
|
831
|
+
const deleteEdge = this.db.prepare("DELETE FROM edges WHERE id = ?");
|
|
832
|
+
for (const edge of staleEdges)
|
|
833
|
+
if (!candidateEdges.has(edge.id))
|
|
834
|
+
deleteEdge.run(edge.id);
|
|
835
|
+
for (const entity of records.entities) {
|
|
836
|
+
const { metadata, ...fields } = entity;
|
|
837
|
+
insertEntity.run({ ...fields, namespace: entity.namespace ?? null, metadataJson: toJson(metadata) });
|
|
838
|
+
}
|
|
839
|
+
for (const sourceRef of records.sourceRefs) {
|
|
840
|
+
const { metadata, ...fields } = sourceRef;
|
|
841
|
+
insertSourceRef.run({ ...fields, metadataJson: toJson(metadata) });
|
|
842
|
+
}
|
|
843
|
+
for (const edge of records.edges) {
|
|
844
|
+
const { metadata, ...fields } = edge;
|
|
845
|
+
insertEdge.run({ ...fields, metadataJson: toJson(metadata) });
|
|
846
|
+
}
|
|
847
|
+
const deleteUnusedEntity = this.db.prepare("DELETE FROM entities WHERE id = ? AND id NOT IN (SELECT from_id FROM edges UNION SELECT to_id FROM edges)");
|
|
848
|
+
for (const row of this.db.prepare("SELECT id FROM entities").all()) {
|
|
849
|
+
if (!candidateEntities.has(row.id))
|
|
850
|
+
deleteUnusedEntity.run(row.id);
|
|
851
|
+
}
|
|
852
|
+
const deleteUnusedSource = this.db.prepare("DELETE FROM source_refs WHERE id = ? AND id NOT IN (SELECT from_id FROM edges UNION SELECT to_id FROM edges)");
|
|
853
|
+
for (const row of this.db.prepare("SELECT id FROM source_refs").all()) {
|
|
854
|
+
if (!candidateSources.has(row.id))
|
|
855
|
+
deleteUnusedSource.run(row.id);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
assertExpectedGeneration(expectedGeneration) {
|
|
859
|
+
if (expectedGeneration === undefined)
|
|
860
|
+
return;
|
|
861
|
+
if (this.indexWriteState().generation !== expectedGeneration) {
|
|
862
|
+
throw new IndexGenerationConflict();
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
writeIndexState(state) {
|
|
866
|
+
if (!state)
|
|
867
|
+
return;
|
|
868
|
+
const nextGeneration = (state.expectedGeneration ?? this.indexWriteState().generation) + 1;
|
|
869
|
+
const upsert = this.db.prepare("INSERT OR REPLACE INTO schema_metadata (key, value) VALUES (?, ?)");
|
|
870
|
+
if (state.extractionFingerprint !== undefined)
|
|
871
|
+
upsert.run("index_extraction_fingerprint", state.extractionFingerprint);
|
|
872
|
+
upsert.run("index_generation", String(nextGeneration));
|
|
873
|
+
}
|
|
874
|
+
documentHash(id) {
|
|
875
|
+
const row = this.db.prepare("SELECT hash FROM documents WHERE id = ?").get(id);
|
|
876
|
+
return row?.hash;
|
|
877
|
+
}
|
|
715
878
|
prepareInsertVector() {
|
|
716
879
|
return this.db.prepare(`
|
|
717
880
|
INSERT INTO chunk_vectors (chunk_id, provider, model, dimensions, vector_blob, created_at)
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
class NodeSqliteAdapter {
|
|
3
|
+
closed = false;
|
|
4
|
+
legacyEmptyGet;
|
|
3
5
|
db;
|
|
4
6
|
constructor(dbPath) {
|
|
5
7
|
const require = createRequire(import.meta.url);
|
|
6
8
|
const { DatabaseSync } = require("node:sqlite");
|
|
7
9
|
this.db = new DatabaseSync(dbPath);
|
|
10
|
+
// Early node:sqlite returns a null-filled object instead of undefined for an
|
|
11
|
+
// empty get(). Probe the behavior rather than tying compatibility to versions.
|
|
12
|
+
this.legacyEmptyGet = this.db.prepare("SELECT 1 AS value WHERE 0").get() !== undefined;
|
|
8
13
|
}
|
|
9
14
|
prepare(sql) {
|
|
10
15
|
const statement = this.db.prepare(sql);
|
|
@@ -16,7 +21,7 @@ class NodeSqliteAdapter {
|
|
|
16
21
|
lastInsertRowid: result?.lastInsertRowid ?? 0
|
|
17
22
|
};
|
|
18
23
|
},
|
|
19
|
-
get: (...params) => statement.get(...params),
|
|
24
|
+
get: (...params) => this.legacyEmptyGet ? statement.all(...params)[0] : statement.get(...params),
|
|
20
25
|
all: (...params) => statement.all(...params)
|
|
21
26
|
};
|
|
22
27
|
}
|
|
@@ -50,8 +55,9 @@ class NodeSqliteAdapter {
|
|
|
50
55
|
};
|
|
51
56
|
}
|
|
52
57
|
close() {
|
|
53
|
-
if (this.
|
|
58
|
+
if (!this.closed) {
|
|
54
59
|
this.db.close();
|
|
60
|
+
this.closed = true;
|
|
55
61
|
}
|
|
56
62
|
}
|
|
57
63
|
}
|
|
@@ -28,9 +28,16 @@ export interface EvaluationMetrics {
|
|
|
28
28
|
topKDocumentRecall: number;
|
|
29
29
|
expectedSectionRecall: number;
|
|
30
30
|
contextPrecision: number;
|
|
31
|
+
/** Compatibility metric: entity existence across the index. */
|
|
31
32
|
entityRecall: number;
|
|
33
|
+
/** Compatibility metric: source-reference existence across the index. */
|
|
32
34
|
sourceRefRecall: number;
|
|
35
|
+
/** Compatibility metric: edge kinds across the index and trace. */
|
|
33
36
|
edgeKindCoverage: number;
|
|
37
|
+
retrievedEntityRecall: number;
|
|
38
|
+
retrievedSourceRefRecall: number;
|
|
39
|
+
retrievedEdgeKindCoverage: number;
|
|
40
|
+
contextIrrelevantRatio: number;
|
|
34
41
|
traceSuccess: boolean | null;
|
|
35
42
|
latencyMs: number;
|
|
36
43
|
returnedChars: number;
|
|
@@ -50,6 +57,7 @@ export interface EvaluationCaseResult {
|
|
|
50
57
|
id: string;
|
|
51
58
|
query: string;
|
|
52
59
|
passed: boolean;
|
|
60
|
+
retrievalEvidencePassed: boolean;
|
|
53
61
|
expected: Omit<EvaluationCase, "id" | "query" | "trace">;
|
|
54
62
|
observed: {
|
|
55
63
|
searchDocuments: string[];
|
|
@@ -62,6 +70,9 @@ export interface EvaluationCaseResult {
|
|
|
62
70
|
resolvedEntities: string[];
|
|
63
71
|
resolvedSourceRefs: string[];
|
|
64
72
|
edgeKinds: EdgeKind[];
|
|
73
|
+
retrievedEntities: string[];
|
|
74
|
+
retrievedSourceRefs: string[];
|
|
75
|
+
retrievedEdgeKinds: EdgeKind[];
|
|
65
76
|
trace?: TraceResult;
|
|
66
77
|
ranking: {
|
|
67
78
|
queryMode: SearchQueryMode;
|
|
@@ -266,6 +266,7 @@ function evaluationCaseResult(repository, evaluationCase, queryMode, searchExpla
|
|
|
266
266
|
const resolvedEntities = resolveExpected(repository, evaluationCase.expectedEntities, "entity");
|
|
267
267
|
const resolvedSourceRefs = resolveExpected(repository, evaluationCase.expectedSourceRefs, "source_ref");
|
|
268
268
|
const edgeKinds = observedEdgeKinds(repository, trace);
|
|
269
|
+
const returnedEvidence = retrievalEvidence(repository, searchResults, context, trace);
|
|
269
270
|
const metrics = calculateMetrics({
|
|
270
271
|
evaluationCase,
|
|
271
272
|
searchResults,
|
|
@@ -274,12 +275,17 @@ function evaluationCaseResult(repository, evaluationCase, queryMode, searchExpla
|
|
|
274
275
|
latencyMs,
|
|
275
276
|
resolvedEntities,
|
|
276
277
|
resolvedSourceRefs,
|
|
277
|
-
edgeKinds
|
|
278
|
+
edgeKinds,
|
|
279
|
+
returnedEvidence
|
|
278
280
|
});
|
|
279
281
|
return {
|
|
280
282
|
id: evaluationCase.id,
|
|
281
283
|
query: evaluationCase.query,
|
|
282
284
|
passed: casePassed(metrics),
|
|
285
|
+
retrievalEvidencePassed: casePassed(metrics)
|
|
286
|
+
&& metrics.retrievedEntityRecall === 1
|
|
287
|
+
&& metrics.retrievedSourceRefRecall === 1
|
|
288
|
+
&& metrics.retrievedEdgeKindCoverage === 1,
|
|
283
289
|
expected: {
|
|
284
290
|
expectedDocuments: evaluationCase.expectedDocuments,
|
|
285
291
|
expectedSections: evaluationCase.expectedSections,
|
|
@@ -294,6 +300,7 @@ function evaluationCaseResult(repository, evaluationCase, queryMode, searchExpla
|
|
|
294
300
|
resolvedEntities,
|
|
295
301
|
resolvedSourceRefs,
|
|
296
302
|
edgeKinds,
|
|
303
|
+
...returnedEvidence,
|
|
297
304
|
trace,
|
|
298
305
|
ranking: {
|
|
299
306
|
queryMode,
|
|
@@ -308,6 +315,29 @@ function evaluationCaseResult(repository, evaluationCase, queryMode, searchExpla
|
|
|
308
315
|
metrics
|
|
309
316
|
};
|
|
310
317
|
}
|
|
318
|
+
function retrievalEvidence(repository, search, context, trace) {
|
|
319
|
+
const entities = search.flatMap((result) => result.matchedEntities.map((entity) => entity.name));
|
|
320
|
+
entities.push(...context.items.flatMap((item) => item.matchedEntities.map((name) => name.replace(/ \([^()]*\)$/u, ""))));
|
|
321
|
+
const sourceRefs = context.items.flatMap((item) => item.sourceRefs?.map((ref) => ref.path) ?? []);
|
|
322
|
+
const edgeKinds = context.items.flatMap((item) => [
|
|
323
|
+
...(item.edgePath?.map((step) => step.edgeKind) ?? []),
|
|
324
|
+
...(item.sourceRefs?.map((ref) => ref.edgeKind) ?? [])
|
|
325
|
+
]);
|
|
326
|
+
// The returned search reason identifies a DEFINES traversal; no global graph facts are added.
|
|
327
|
+
if (search.some((result) => result.reason.includes("definition matched an explicit query entity")))
|
|
328
|
+
edgeKinds.push("DEFINES");
|
|
329
|
+
for (const step of trace?.steps ?? []) {
|
|
330
|
+
edgeKinds.push(step.edgeKind);
|
|
331
|
+
for (const id of [step.fromId, step.toId]) {
|
|
332
|
+
const node = repository.getNode(id);
|
|
333
|
+
if (node?.kind === "entity")
|
|
334
|
+
entities.push(node.label);
|
|
335
|
+
if (node?.kind === "source_ref")
|
|
336
|
+
sourceRefs.push(node.label);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return { retrievedEntities: unique(entities), retrievedSourceRefs: unique(sourceRefs), retrievedEdgeKinds: unique(edgeKinds) };
|
|
340
|
+
}
|
|
311
341
|
function calculateMetrics(input) {
|
|
312
342
|
const expectedDocumentSet = new Set(input.evaluationCase.expectedDocuments);
|
|
313
343
|
const returnedDocuments = unique(input.searchResults.map((result) => result.document.path));
|
|
@@ -323,6 +353,10 @@ function calculateMetrics(input) {
|
|
|
323
353
|
entityRecall: expectedCovered(input.evaluationCase.expectedEntities, input.resolvedEntities),
|
|
324
354
|
sourceRefRecall: expectedCovered(input.evaluationCase.expectedSourceRefs, input.resolvedSourceRefs),
|
|
325
355
|
edgeKindCoverage: expectedCovered(input.evaluationCase.expectedEdges, input.edgeKinds),
|
|
356
|
+
retrievedEntityRecall: expectedCovered(input.evaluationCase.expectedEntities, input.returnedEvidence.retrievedEntities),
|
|
357
|
+
retrievedSourceRefRecall: expectedCovered(input.evaluationCase.expectedSourceRefs, input.returnedEvidence.retrievedSourceRefs),
|
|
358
|
+
retrievedEdgeKindCoverage: expectedCovered(input.evaluationCase.expectedEdges, input.returnedEvidence.retrievedEdgeKinds),
|
|
359
|
+
contextIrrelevantRatio: input.context.items.length ? 1 - contextMatches.length / input.context.items.length : 0,
|
|
326
360
|
traceSuccess,
|
|
327
361
|
latencyMs: roundMetric(input.latencyMs),
|
|
328
362
|
returnedChars: input.context.usedChars,
|
package/dist/index.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
|
18
18
|
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
19
|
export { CONTEXT_PACKING_STRATEGIES, CONTEXT_PACKING_STRATEGY, DEFAULT_MMR_LAMBDA, buildContext, buildContextAsync } from "./query/context-builder.js";
|
|
20
20
|
export type { ContextBuildOptions, ContextDebug, ContextPackingInfo, ContextPackingSelection, ContextPackingSimilarity, ContextPackingStrategy, ContextResult } from "./query/context-builder.js";
|
|
21
|
+
export { DEFAULT_KNOWLEDGE_CARD_LIMITS, buildKnowledgeCard, createKnowledgeCardBuilder, formatKnowledgeCard } from "./query/knowledge-card.js";
|
|
22
|
+
export type { CardAssociation, CardNextRead, CardEvidence, CardReference, CardSourceReference, KnowledgeCard, KnowledgeCardBuilder, KnowledgeCardNodeKind, KnowledgeCardOptions } from "./query/knowledge-card.js";
|
|
21
23
|
export { explainSearchGraph, explainSearchGraphAsync, searchGraph, searchGraphAsync } from "./query/search.js";
|
|
22
24
|
export { traceNodes } from "./query/trace.js";
|
|
23
25
|
export { executeStructuredQuery, StructuredQueryExecutionError } from "./query/structured-query-executor.js";
|
|
@@ -38,4 +40,9 @@ export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-code
|
|
|
38
40
|
export { watchProject } from "./watcher/file-watcher.js";
|
|
39
41
|
export type { WatchHandle, WatchProjectOptions } from "./watcher/file-watcher.js";
|
|
40
42
|
export type { WatchFailureCode, WatchFailurePhase, WatchHealthError, WatchHealthSnapshot, WatchHealthState } from "./watcher/watch-health.js";
|
|
43
|
+
export { WIKI_PAGE_BRIEF_FORMAT, WIKI_PAGE_BRIEF_FORMAT_VERSION, WIKI_PLAN_FORMAT, WIKI_PLAN_FORMAT_VERSION, WikiPlanError, buildWikiPageBrief, buildWikiPlan, calculateWikiPageEvidenceHash, formatWikiPageBrief, formatWikiPlan, readWikiPlan, safeProjectRelativePath, safeWikiPagePath, sourceRefFingerprint, stableWikiPlan, validateWikiPlan, writeWikiPlan, wikiSourceHash } from "./wiki/wiki-plan.js";
|
|
44
|
+
export type { WikiBriefSourceDocument, WikiBriefOptions, WikiPageBrief, WikiPlan, WikiPlanOptions, WikiPlanSuggestions, WikiPlanGap, WikiDependencySnapshot, WikiPlanPage, WikiStrictFreshness } from "./wiki/wiki-plan.js";
|
|
45
|
+
export { WIKI_STATUS_FORMAT, WIKI_STATUS_FORMAT_VERSION, WIKI_VERIFICATION_FORMAT, WIKI_VERIFICATION_FORMAT_VERSION, buildWikiStatus, formatWikiStatus, formatWikiVerification, verifyWiki } from "./wiki/wiki-status.js";
|
|
46
|
+
export type { WikiDependencyAssessment, WikiDependencyChange } from "./wiki/wiki-dependencies.js";
|
|
47
|
+
export type { WikiPageState, WikiPageStatus, WikiPlanStatus, WikiStatus, WikiStatusOptions, WikiVerification, WikiVerificationIssue } from "./wiki/wiki-status.js";
|
|
41
48
|
export * from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -17,6 +17,7 @@ export { MCPServer, startStdioMcpServer } from "./mcp/server.js";
|
|
|
17
17
|
export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
18
18
|
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
19
|
export { CONTEXT_PACKING_STRATEGIES, CONTEXT_PACKING_STRATEGY, DEFAULT_MMR_LAMBDA, buildContext, buildContextAsync } from "./query/context-builder.js";
|
|
20
|
+
export { DEFAULT_KNOWLEDGE_CARD_LIMITS, buildKnowledgeCard, createKnowledgeCardBuilder, formatKnowledgeCard } from "./query/knowledge-card.js";
|
|
20
21
|
export { explainSearchGraph, explainSearchGraphAsync, searchGraph, searchGraphAsync } from "./query/search.js";
|
|
21
22
|
export { traceNodes } from "./query/trace.js";
|
|
22
23
|
export { executeStructuredQuery, StructuredQueryExecutionError } from "./query/structured-query-executor.js";
|
|
@@ -30,4 +31,6 @@ export { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector }
|
|
|
30
31
|
export { semanticStatusReport, semanticStatusReportAsync } from "./semantic/status.js";
|
|
31
32
|
export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-codec.js";
|
|
32
33
|
export { watchProject } from "./watcher/file-watcher.js";
|
|
34
|
+
export { WIKI_PAGE_BRIEF_FORMAT, WIKI_PAGE_BRIEF_FORMAT_VERSION, WIKI_PLAN_FORMAT, WIKI_PLAN_FORMAT_VERSION, WikiPlanError, buildWikiPageBrief, buildWikiPlan, calculateWikiPageEvidenceHash, formatWikiPageBrief, formatWikiPlan, readWikiPlan, safeProjectRelativePath, safeWikiPagePath, sourceRefFingerprint, stableWikiPlan, validateWikiPlan, writeWikiPlan, wikiSourceHash } from "./wiki/wiki-plan.js";
|
|
35
|
+
export { WIKI_STATUS_FORMAT, WIKI_STATUS_FORMAT_VERSION, WIKI_VERIFICATION_FORMAT, WIKI_VERIFICATION_FORMAT_VERSION, buildWikiStatus, formatWikiStatus, formatWikiVerification, verifyWiki } from "./wiki/wiki-status.js";
|
|
33
36
|
export * from "./types.js";
|
package/dist/indexer.js
CHANGED
|
@@ -1,13 +1,37 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { loadConfig } from "./config/load-config.js";
|
|
2
3
|
import { openDatabase } from "./db/connection.js";
|
|
3
|
-
import { GraphRepository } from "./db/repositories.js";
|
|
4
|
+
import { GraphRepository, IndexGenerationConflict } from "./db/repositories.js";
|
|
4
5
|
import { buildGraphRecords } from "./extraction/graph-builder.js";
|
|
5
6
|
import { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
6
7
|
import { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
7
8
|
import { embedChunks } from "./semantic/embed-chunks.js";
|
|
8
9
|
import { relativePathInsideRoot } from "./utils/path-safety.js";
|
|
9
10
|
export async function indexProject(projectRoot, options = {}) {
|
|
11
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
12
|
+
try {
|
|
13
|
+
return await indexProjectAttempt(projectRoot, options);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (!(error instanceof IndexGenerationConflict) || attempt === 1)
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
throw new Error("Unreachable index retry state.");
|
|
21
|
+
}
|
|
22
|
+
async function indexProjectAttempt(projectRoot, options) {
|
|
10
23
|
const config = effectiveConfig(loadConfig(projectRoot), options);
|
|
24
|
+
const fingerprint = extractionFingerprint(config);
|
|
25
|
+
// Capture generation before asynchronous scan/parse/embed work. The write CAS
|
|
26
|
+
// below rejects this candidate if another index finishes while it is prepared.
|
|
27
|
+
const preflightDb = openDatabase(projectRoot);
|
|
28
|
+
let expectedGeneration;
|
|
29
|
+
try {
|
|
30
|
+
expectedGeneration = new GraphRepository(preflightDb).indexWriteState().generation;
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
preflightDb.close();
|
|
34
|
+
}
|
|
11
35
|
const files = await scanMarkdownFiles(projectRoot, config);
|
|
12
36
|
const { parsed, skippedFiles } = parseScannedFiles(projectRoot, files);
|
|
13
37
|
const records = buildGraphRecords(parsed, config);
|
|
@@ -15,10 +39,19 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
15
39
|
try {
|
|
16
40
|
const repository = new GraphRepository(db);
|
|
17
41
|
const existingCounts = repository.counts();
|
|
42
|
+
const writeState = repository.indexWriteState();
|
|
18
43
|
const requiresCompleteEmbedding = config.embedding.enabled && !hasMatchingVectorCoverage(repository, config, existingCounts);
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
44
|
+
const vectorProfileChanged = existingCounts.vectors > 0 && requiresCompleteEmbedding;
|
|
45
|
+
const requiresRebuild = options.full || existingCounts.documents === 0 || requiresCompleteEmbedding || writeState.extractionFingerprint !== fingerprint;
|
|
46
|
+
// A parser failure is a non-destructive condition: retain that document's last
|
|
47
|
+
// known graph until it can be parsed again, rather than turning a transient edit
|
|
48
|
+
// into a deletion during a requested rebuild.
|
|
49
|
+
if (requiresRebuild && skippedFiles.length === 0) {
|
|
50
|
+
records.vectors = await vectorsForChunks(repository, records.chunks, config);
|
|
51
|
+
if (!options.full && !vectorProfileChanged) {
|
|
52
|
+
records.edges.push(...repository.preservedDerivedEdges(records));
|
|
53
|
+
}
|
|
54
|
+
repository.replaceAll(records, { expectedGeneration, extractionFingerprint: fingerprint });
|
|
22
55
|
return {
|
|
23
56
|
files: files.length,
|
|
24
57
|
changed: parsed.length,
|
|
@@ -42,8 +75,13 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
42
75
|
.map((document) => existing.get(document.relativePath)?.id)
|
|
43
76
|
.filter((existingId) => typeof existingId === "string" && !changedIds.has(existingId));
|
|
44
77
|
const changedRecords = filterRecordsForDocuments(records, changedIds);
|
|
45
|
-
changedRecords.vectors = await
|
|
46
|
-
repository.replaceDocuments(changedRecords, [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds]
|
|
78
|
+
changedRecords.vectors = await vectorsForChunks(repository, changedRecords.chunks, config);
|
|
79
|
+
repository.replaceDocuments(changedRecords, [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds], skippedFiles.length === 0 ? records : undefined, {
|
|
80
|
+
expectedGeneration,
|
|
81
|
+
// Do not mark a partial, parser-skipped candidate as a completed
|
|
82
|
+
// extraction-config rebuild. The next successful scan must retry it.
|
|
83
|
+
extractionFingerprint: requiresRebuild ? writeState.extractionFingerprint : fingerprint
|
|
84
|
+
});
|
|
47
85
|
}
|
|
48
86
|
return {
|
|
49
87
|
files: files.length,
|
|
@@ -60,6 +98,26 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
60
98
|
db.close();
|
|
61
99
|
}
|
|
62
100
|
}
|
|
101
|
+
async function vectorsForChunks(repository, chunks, config) {
|
|
102
|
+
if (!config.embedding.enabled)
|
|
103
|
+
return [];
|
|
104
|
+
const profile = { provider: config.embedding.provider, model: config.embedding.model, dimensions: config.embedding.dimensions };
|
|
105
|
+
const reusable = repository.reusableVectors(chunks, profile);
|
|
106
|
+
const present = new Set(reusable.map((vector) => vector.chunkId));
|
|
107
|
+
const embedded = await embedChunks(chunks.filter((chunk) => !present.has(chunk.id)), config);
|
|
108
|
+
return [...reusable, ...embedded];
|
|
109
|
+
}
|
|
110
|
+
function extractionFingerprint(config) {
|
|
111
|
+
const extraction = {
|
|
112
|
+
docs: config.docs,
|
|
113
|
+
index: config.index,
|
|
114
|
+
entities: {
|
|
115
|
+
enabledKinds: [...config.entities.enabledKinds].sort(),
|
|
116
|
+
stopEntities: [...config.entities.stopEntities].sort()
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
return createHash("sha256").update(JSON.stringify(extraction)).digest("hex");
|
|
120
|
+
}
|
|
63
121
|
function hasMatchingVectorCoverage(repository, config, counts) {
|
|
64
122
|
if (counts.vectors !== counts.chunks) {
|
|
65
123
|
return false;
|
package/dist/mcp/server.js
CHANGED
|
@@ -6,7 +6,7 @@ import { errorMessage, initializeErrorMessage, internalToolErrorMessage, mcpDebu
|
|
|
6
6
|
import { SERVER_INSTRUCTIONS, SERVER_INSTRUCTIONS_UNINDEXED } from "./server-instructions.js";
|
|
7
7
|
import { McpInputError, ToolHandler, hasIndex, tools } from "./tools.js";
|
|
8
8
|
import { packageVersion } from "../version.js";
|
|
9
|
-
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
9
|
+
import { assertProjectFilesInsideRoot, isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
10
10
|
import { watchProject } from "../watcher/file-watcher.js";
|
|
11
11
|
export const PROTOCOL_VERSION = "2024-11-05";
|
|
12
12
|
export class MCPServer {
|
|
@@ -23,8 +23,8 @@ export class MCPServer {
|
|
|
23
23
|
watchRoot;
|
|
24
24
|
constructor(transport, options = {}) {
|
|
25
25
|
this.transport = transport;
|
|
26
|
-
this.boundProjectRoot = validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd()));
|
|
27
|
-
this.projectRoot =
|
|
26
|
+
this.boundProjectRoot = fs.realpathSync(validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd())));
|
|
27
|
+
this.projectRoot = validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd()));
|
|
28
28
|
this.toolHandler = this.createToolHandler(this.projectRoot);
|
|
29
29
|
this.watchEnabled = options.watch ?? true;
|
|
30
30
|
this.watchSemantic = options.semantic;
|
|
@@ -98,7 +98,8 @@ export class MCPServer {
|
|
|
98
98
|
let projectRoot;
|
|
99
99
|
try {
|
|
100
100
|
projectRoot = validatedProjectRoot(projectRootFromInitialize(request.params) ?? this.projectRoot);
|
|
101
|
-
|
|
101
|
+
assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
|
|
102
|
+
if (!isPathInsideOrEqual(this.boundProjectRoot, fs.realpathSync(projectRoot))) {
|
|
102
103
|
throw new Error(`Initialize root must stay inside served project root: ${this.boundProjectRoot}`);
|
|
103
104
|
}
|
|
104
105
|
}
|