@daogee/mdgraph 1.1.0 → 1.2.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README-ZH.md +12 -2
  3. package/README.md +12 -2
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +3 -1
  6. package/agent-pack/prompts/wiki-authoring.md +12 -0
  7. package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
  8. package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
  9. package/dist/analysis/status-freshness.d.ts +8 -1
  10. package/dist/analysis/status-freshness.js +19 -6
  11. package/dist/bin/mdgraph.js +124 -6
  12. package/dist/db/connection.js +17 -1
  13. package/dist/db/repositories.d.ts +28 -4
  14. package/dist/db/repositories.js +148 -5
  15. package/dist/db/sqlite-adapter.js +8 -2
  16. package/dist/evaluation/retrieval-eval.d.ts +11 -0
  17. package/dist/evaluation/retrieval-eval.js +35 -1
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +3 -0
  20. package/dist/indexer.js +64 -6
  21. package/dist/mcp/server.js +5 -4
  22. package/dist/mcp/tools.js +23 -9
  23. package/dist/query/context-builder.d.ts +1 -0
  24. package/dist/query/context-builder.js +30 -1
  25. package/dist/query/knowledge-card.d.ts +90 -0
  26. package/dist/query/knowledge-card.js +676 -0
  27. package/dist/query/search.js +8 -3
  28. package/dist/semantic/ollama-provider.js +6 -1
  29. package/dist/utils/path-safety.d.ts +3 -0
  30. package/dist/utils/path-safety.js +27 -0
  31. package/dist/watcher/file-watcher.js +85 -16
  32. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  33. package/dist/wiki/wiki-dependencies.js +45 -0
  34. package/dist/wiki/wiki-domains.d.ts +13 -0
  35. package/dist/wiki/wiki-domains.js +55 -0
  36. package/dist/wiki/wiki-evidence.d.ts +27 -0
  37. package/dist/wiki/wiki-evidence.js +112 -0
  38. package/dist/wiki/wiki-plan.d.ts +121 -0
  39. package/dist/wiki/wiki-plan.js +616 -0
  40. package/dist/wiki/wiki-status.d.ts +67 -0
  41. package/dist/wiki/wiki-status.js +451 -0
  42. package/docs/EN/Agent_Integration.md +14 -4
  43. package/docs/EN/Architecture.md +13 -0
  44. package/docs/EN/Evaluation_Questions.md +14 -0
  45. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  46. package/docs/EN/Operations.md +20 -0
  47. package/docs/EN/Output_Contracts.md +42 -3
  48. package/docs/EN/Public_Contracts.md +3 -1
  49. package/docs/EN/Public_Contracts_1.0.md +4 -0
  50. package/docs/EN/README.md +1 -0
  51. package/docs/EN/Release_Checklist.md +1 -0
  52. package/docs/EN/Retrieval_and_Context.md +6 -0
  53. package/docs/ZH/Agent_Integration.md +14 -4
  54. package/docs/ZH/Architecture.md +13 -2
  55. package/docs/ZH/Evaluation_Questions.md +14 -0
  56. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  57. package/docs/ZH/Operations.md +20 -0
  58. package/docs/ZH/Output_Contracts.md +42 -3
  59. package/docs/ZH/Public_Contracts.md +3 -1
  60. package/docs/ZH/Public_Contracts_1.0.md +4 -0
  61. package/docs/ZH/README.md +1 -0
  62. package/docs/ZH/Release_Checklist.md +1 -0
  63. package/docs/ZH/Retrieval_and_Context.md +6 -0
  64. package/package.json +7 -2
@@ -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
- replaceAll(records) {
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
- this.pruneUnreferencedEntitiesAndSources();
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,6 +106,42 @@ 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
  }
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
+ }
83
145
  searchChunks(ftsQuery, limit) {
84
146
  const rows = this.db.prepare(`
85
147
  SELECT
@@ -169,7 +231,7 @@ export class GraphRepository {
169
231
  d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
170
232
  s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
171
233
  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
234
+ e.weight AS rank, e.to_id AS entity_id
173
235
  FROM edges e
174
236
  LEFT JOIN sections s ON s.id = e.from_id
175
237
  JOIN documents d ON d.id = COALESCE(s.document_id, e.from_id)
@@ -183,7 +245,8 @@ export class GraphRepository {
183
245
  document: rowToDocument(row, "d_"),
184
246
  section: row.s_id ? rowToSection(row, "s_") : undefined,
185
247
  chunk: definitionChunk(row, sectionChunk, documentChunk),
186
- rank: numberValue(row.rank)
248
+ rank: numberValue(row.rank),
249
+ entityId: stringValue(row.entity_id)
187
250
  })));
188
251
  }
189
252
  searchSemanticChunks(queryVector, provider, model, limit) {
@@ -712,6 +775,86 @@ export class GraphRepository {
712
775
  insertVector.run(vectorToParams(vector));
713
776
  }
714
777
  }
778
+ reconcileSharedGraphRecords(records) {
779
+ const insertEntity = this.db.prepare(`
780
+ INSERT INTO entities (id, name, normalized_name, kind, namespace, created_at, metadata_json)
781
+ VALUES (@id, @name, @normalizedName, @kind, @namespace, @createdAt, @metadataJson)
782
+ ON CONFLICT(id) DO UPDATE SET
783
+ name = excluded.name, normalized_name = excluded.normalized_name, kind = excluded.kind,
784
+ namespace = excluded.namespace, metadata_json = excluded.metadata_json
785
+ WHERE entities.name <> excluded.name OR entities.normalized_name <> excluded.normalized_name
786
+ OR entities.kind <> excluded.kind OR entities.namespace IS NOT excluded.namespace
787
+ OR entities.metadata_json IS NOT excluded.metadata_json
788
+ `);
789
+ const insertSourceRef = this.db.prepare(`
790
+ INSERT INTO source_refs (id, path, normalized_path, created_at, metadata_json)
791
+ VALUES (@id, @path, @normalizedPath, @createdAt, @metadataJson)
792
+ ON CONFLICT(id) DO UPDATE SET path = excluded.path, normalized_path = excluded.normalized_path,
793
+ metadata_json = excluded.metadata_json
794
+ WHERE source_refs.path <> excluded.path OR source_refs.normalized_path <> excluded.normalized_path
795
+ OR source_refs.metadata_json IS NOT excluded.metadata_json
796
+ `);
797
+ const insertEdge = this.db.prepare(`
798
+ INSERT INTO edges (id, from_id, to_id, kind, weight, confidence, provenance, metadata_json, created_at)
799
+ VALUES (@id, @fromId, @toId, @kind, @weight, @confidence, @provenance, @metadataJson, @createdAt)
800
+ ON CONFLICT(id) DO UPDATE SET from_id = excluded.from_id, to_id = excluded.to_id, kind = excluded.kind,
801
+ weight = excluded.weight, confidence = excluded.confidence, provenance = excluded.provenance,
802
+ metadata_json = excluded.metadata_json
803
+ WHERE edges.from_id <> excluded.from_id OR edges.to_id <> excluded.to_id OR edges.kind <> excluded.kind
804
+ OR edges.weight <> excluded.weight OR edges.confidence <> excluded.confidence
805
+ OR edges.provenance <> excluded.provenance OR edges.metadata_json IS NOT excluded.metadata_json
806
+ `);
807
+ const candidateEntities = new Set(records.entities.map((entity) => entity.id));
808
+ const candidateSources = new Set(records.sourceRefs.map((sourceRef) => sourceRef.id));
809
+ const candidateEdges = new Set(records.edges.map((edge) => edge.id));
810
+ const staleEdges = this.db.prepare("SELECT id FROM edges WHERE provenance <> 'embedding_similarity'").all();
811
+ const deleteEdge = this.db.prepare("DELETE FROM edges WHERE id = ?");
812
+ for (const edge of staleEdges)
813
+ if (!candidateEdges.has(edge.id))
814
+ deleteEdge.run(edge.id);
815
+ for (const entity of records.entities) {
816
+ const { metadata, ...fields } = entity;
817
+ insertEntity.run({ ...fields, namespace: entity.namespace ?? null, metadataJson: toJson(metadata) });
818
+ }
819
+ for (const sourceRef of records.sourceRefs) {
820
+ const { metadata, ...fields } = sourceRef;
821
+ insertSourceRef.run({ ...fields, metadataJson: toJson(metadata) });
822
+ }
823
+ for (const edge of records.edges) {
824
+ const { metadata, ...fields } = edge;
825
+ insertEdge.run({ ...fields, metadataJson: toJson(metadata) });
826
+ }
827
+ 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)");
828
+ for (const row of this.db.prepare("SELECT id FROM entities").all()) {
829
+ if (!candidateEntities.has(row.id))
830
+ deleteUnusedEntity.run(row.id);
831
+ }
832
+ 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)");
833
+ for (const row of this.db.prepare("SELECT id FROM source_refs").all()) {
834
+ if (!candidateSources.has(row.id))
835
+ deleteUnusedSource.run(row.id);
836
+ }
837
+ }
838
+ assertExpectedGeneration(expectedGeneration) {
839
+ if (expectedGeneration === undefined)
840
+ return;
841
+ if (this.indexWriteState().generation !== expectedGeneration) {
842
+ throw new IndexGenerationConflict();
843
+ }
844
+ }
845
+ writeIndexState(state) {
846
+ if (!state)
847
+ return;
848
+ const nextGeneration = (state.expectedGeneration ?? this.indexWriteState().generation) + 1;
849
+ const upsert = this.db.prepare("INSERT OR REPLACE INTO schema_metadata (key, value) VALUES (?, ?)");
850
+ if (state.extractionFingerprint !== undefined)
851
+ upsert.run("index_extraction_fingerprint", state.extractionFingerprint);
852
+ upsert.run("index_generation", String(nextGeneration));
853
+ }
854
+ documentHash(id) {
855
+ const row = this.db.prepare("SELECT hash FROM documents WHERE id = ?").get(id);
856
+ return row?.hash;
857
+ }
715
858
  prepareInsertVector() {
716
859
  return this.db.prepare(`
717
860
  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.db.isOpen) {
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
- if (options.full || existingCounts.documents === 0 || requiresCompleteEmbedding) {
20
- records.vectors = await embedChunks(records.chunks, config);
21
- repository.replaceAll(records);
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 embedChunks(changedRecords.chunks, config);
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;
@@ -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 = this.boundProjectRoot;
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
- if (!isPathInsideOrEqual(this.boundProjectRoot, projectRoot)) {
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
  }
package/dist/mcp/tools.js CHANGED
@@ -6,9 +6,10 @@ import { databasePath, loadConfig } from "../config/load-config.js";
6
6
  import { openExistingDatabase } from "../db/connection.js";
7
7
  import { GraphRepository } from "../db/repositories.js";
8
8
  import { CONTEXT_PACKING_STRATEGIES, buildContext, buildContextAsync } from "../query/context-builder.js";
9
+ import { buildKnowledgeCard, formatKnowledgeCard } from "../query/knowledge-card.js";
9
10
  import { explainSearchGraphAsync, searchGraph } from "../query/search.js";
10
11
  import { traceNodes } from "../query/trace.js";
11
- import { isPathInsideOrEqual } from "../utils/path-safety.js";
12
+ import { assertProjectFilesInsideRoot, isPathInsideOrEqual } from "../utils/path-safety.js";
12
13
  export class McpInputError extends Error {
13
14
  name = "McpInputError";
14
15
  }
@@ -97,9 +98,10 @@ export class ToolHandler {
97
98
  boundProjectRoot;
98
99
  constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot, watchHealthProvider) {
99
100
  this.watchHealthProvider = watchHealthProvider;
100
- this.boundProjectRoot = validatedProjectRoot(path.resolve(boundProjectRoot));
101
+ this.boundProjectRoot = fs.realpathSync(validatedProjectRoot(path.resolve(boundProjectRoot)));
101
102
  this.defaultProjectRoot = validatedProjectRoot(path.resolve(defaultProjectRoot));
102
- if (!isPathInsideOrEqual(this.boundProjectRoot, this.defaultProjectRoot)) {
103
+ assertProjectFilesInsideRoot(this.boundProjectRoot, this.defaultProjectRoot);
104
+ if (!isPathInsideOrEqual(this.boundProjectRoot, fs.realpathSync(this.defaultProjectRoot))) {
103
105
  throw new McpInputError(`Default project root must stay inside served root: ${this.boundProjectRoot}`);
104
106
  }
105
107
  }
@@ -167,7 +169,9 @@ export class ToolHandler {
167
169
  if (resolution.status === "ambiguous") {
168
170
  return withFreshnessNotice(textResult(formatAmbiguousNodeQuery(resolution), { projectRoot, query, error: resolution.error, candidates: resolution.candidates, node: null }), freshness);
169
171
  }
170
- return withFreshnessNotice(textResult(formatNode(resolution.node, repository), { projectRoot, node: resolution.node }), freshness);
172
+ const card = buildKnowledgeCard(repository, resolution.node);
173
+ const node = card ? { ...resolution.node, card } : resolution.node;
174
+ return withFreshnessNotice(textResult(formatNode(resolution.node, repository, card), { projectRoot, node }), freshness);
171
175
  });
172
176
  case "mdgraph_trace":
173
177
  return this.withRepository(projectRoot, (repository) => {
@@ -232,6 +236,7 @@ export class ToolHandler {
232
236
  });
233
237
  }
234
238
  withRepository(projectRoot, fn) {
239
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
235
240
  const repository = new GraphRepository(openExistingDatabase(projectRoot));
236
241
  try {
237
242
  return fn(repository);
@@ -241,6 +246,7 @@ export class ToolHandler {
241
246
  }
242
247
  }
243
248
  async withRepositoryAsync(projectRoot, fn) {
249
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
244
250
  const repository = new GraphRepository(openExistingDatabase(projectRoot));
245
251
  try {
246
252
  return await fn(repository);
@@ -444,7 +450,8 @@ function formatContext(context) {
444
450
  const entities = item.matchedEntities.length ? `\nMatched entities: ${item.matchedEntities.join(", ")}` : "";
445
451
  const sourceRefs = item.sourceRefs?.length ? `\nSource refs: ${item.sourceRefs.map((sourceRef) => `${sourceRef.path} (${sourceRef.edgeKind}/${sourceRef.provenance}, confidence ${sourceRef.confidence})`).join(", ")}` : "";
446
452
  const riskNotes = item.riskNotes?.length ? `\nRisk notes: ${item.riskNotes.join("; ")}` : "";
447
- return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}\n${heading}\n${item.content}`;
453
+ const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
454
+ return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}${cardSummary}\n${heading}\n${item.content}`;
448
455
  });
449
456
  const hints = [
450
457
  context.mode ? `Mode: ${context.mode.name} (searchLimit ${context.mode.searchLimit}, maxDepth ${context.mode.maxDepth}; ${context.mode.reason})` : "",
@@ -453,7 +460,7 @@ function formatContext(context) {
453
460
  ].filter(Boolean);
454
461
  return [header, ...hints, ...items].join("\n\n");
455
462
  }
456
- function formatNode(node, repository) {
463
+ function formatNode(node, repository, card) {
457
464
  const edges = repository.edgesForNode(node.id).slice(0, 12);
458
465
  const related = edges.map((edge) => {
459
466
  const otherId = edge.fromId === node.id ? edge.toId : edge.fromId;
@@ -463,8 +470,9 @@ function formatNode(node, repository) {
463
470
  return [
464
471
  `${node.kind}: ${node.label}`,
465
472
  JSON.stringify(node.data, null, 2),
466
- related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none"
467
- ].join("\n\n");
473
+ related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none",
474
+ card ? formatKnowledgeCard(card) : ""
475
+ ].filter(Boolean).join("\n\n");
468
476
  }
469
477
  function formatAmbiguousNodeQuery(resolution) {
470
478
  const candidates = resolution.candidates
@@ -509,7 +517,13 @@ function validatedProjectRoot(projectRoot) {
509
517
  }
510
518
  function validatedBoundProjectRoot(projectRoot, boundProjectRoot) {
511
519
  const resolved = validatedProjectRoot(projectRoot);
512
- if (!isPathInsideOrEqual(boundProjectRoot, resolved)) {
520
+ try {
521
+ assertProjectFilesInsideRoot(boundProjectRoot, resolved);
522
+ }
523
+ catch (error) {
524
+ throw new McpInputError(error instanceof Error ? error.message : String(error));
525
+ }
526
+ if (!isPathInsideOrEqual(boundProjectRoot, fs.realpathSync(resolved))) {
513
527
  throw new McpInputError(`projectPath must stay inside served project root: ${boundProjectRoot}`);
514
528
  }
515
529
  return resolved;
@@ -23,6 +23,7 @@ export interface ContextItem {
23
23
  edgePath?: ContextEdgePathStep[];
24
24
  sourceRefs?: ContextSourceRef[];
25
25
  riskNotes?: string[];
26
+ cardSummary?: string;
26
27
  content: string;
27
28
  }
28
29
  export interface ContextEdgePathStep {