@daogee/mdgraph 1.0.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 (106) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README-ZH.md +66 -4
  3. package/README.md +84 -22
  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 +260 -25
  12. package/dist/config/limits.d.ts +2 -0
  13. package/dist/config/limits.js +3 -1
  14. package/dist/config/load-config.js +8 -2
  15. package/dist/db/connection.js +17 -1
  16. package/dist/db/repositories.d.ts +55 -4
  17. package/dist/db/repositories.js +458 -11
  18. package/dist/db/sqlite-adapter.js +8 -2
  19. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  20. package/dist/evaluation/context-packing-evaluation.js +134 -0
  21. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  22. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  23. package/dist/evaluation/historical-baseline.d.ts +70 -0
  24. package/dist/evaluation/historical-baseline.js +278 -0
  25. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  26. package/dist/evaluation/related-documents-evaluation.js +163 -0
  27. package/dist/evaluation/retrieval-eval.d.ts +25 -5
  28. package/dist/evaluation/retrieval-eval.js +79 -7
  29. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  30. package/dist/evaluation/structured-query-evaluation.js +156 -0
  31. package/dist/extraction/entity-extractor.js +42 -22
  32. package/dist/extraction/graph-builder.js +2 -18
  33. package/dist/index.d.ts +24 -4
  34. package/dist/index.js +12 -4
  35. package/dist/indexer.js +80 -4
  36. package/dist/mcp/server.d.ts +4 -0
  37. package/dist/mcp/server.js +21 -11
  38. package/dist/mcp/tools.d.ts +5 -1
  39. package/dist/mcp/tools.js +116 -18
  40. package/dist/parser/markdown-parser.js +2 -0
  41. package/dist/query/context-builder.d.ts +32 -2
  42. package/dist/query/context-builder.js +191 -12
  43. package/dist/query/knowledge-card.d.ts +90 -0
  44. package/dist/query/knowledge-card.js +676 -0
  45. package/dist/query/search.d.ts +5 -1
  46. package/dist/query/search.js +85 -16
  47. package/dist/query/structured-query-executor.d.ts +28 -0
  48. package/dist/query/structured-query-executor.js +138 -0
  49. package/dist/query/structured-query.d.ts +50 -0
  50. package/dist/query/structured-query.js +390 -0
  51. package/dist/relationships/derive-related.d.ts +86 -0
  52. package/dist/relationships/derive-related.js +322 -0
  53. package/dist/reporting/report.js +2 -2
  54. package/dist/semantic/embed-chunks.d.ts +2 -0
  55. package/dist/semantic/embed-chunks.js +31 -0
  56. package/dist/semantic/ollama-provider.d.ts +6 -0
  57. package/dist/semantic/ollama-provider.js +136 -0
  58. package/dist/semantic/provider-registry.d.ts +8 -0
  59. package/dist/semantic/provider-registry.js +66 -0
  60. package/dist/semantic/provider.d.ts +35 -0
  61. package/dist/semantic/provider.js +29 -0
  62. package/dist/semantic/status.d.ts +6 -1
  63. package/dist/semantic/status.js +49 -3
  64. package/dist/types.d.ts +7 -2
  65. package/dist/types.js +2 -1
  66. package/dist/utils/path-safety.d.ts +3 -0
  67. package/dist/utils/path-safety.js +27 -0
  68. package/dist/watcher/file-watcher.d.ts +4 -0
  69. package/dist/watcher/file-watcher.js +151 -17
  70. package/dist/watcher/watch-health.d.ts +34 -0
  71. package/dist/watcher/watch-health.js +75 -0
  72. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  73. package/dist/wiki/wiki-dependencies.js +45 -0
  74. package/dist/wiki/wiki-domains.d.ts +13 -0
  75. package/dist/wiki/wiki-domains.js +55 -0
  76. package/dist/wiki/wiki-evidence.d.ts +27 -0
  77. package/dist/wiki/wiki-evidence.js +112 -0
  78. package/dist/wiki/wiki-plan.d.ts +121 -0
  79. package/dist/wiki/wiki-plan.js +616 -0
  80. package/dist/wiki/wiki-status.d.ts +67 -0
  81. package/dist/wiki/wiki-status.js +451 -0
  82. package/docs/EN/Agent_Integration.md +15 -5
  83. package/docs/EN/Architecture.md +52 -16
  84. package/docs/EN/Evaluation_Questions.md +35 -5
  85. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  86. package/docs/EN/Operations.md +111 -0
  87. package/docs/EN/Output_Contracts.md +83 -10
  88. package/docs/EN/Public_Contracts.md +25 -16
  89. package/docs/EN/Public_Contracts_1.0.md +32 -18
  90. package/docs/EN/README.md +24 -0
  91. package/docs/EN/Release_Checklist.md +27 -13
  92. package/docs/EN/Retrieval_and_Context.md +118 -0
  93. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  94. package/docs/ZH/Agent_Integration.md +15 -5
  95. package/docs/ZH/Architecture.md +52 -21
  96. package/docs/ZH/Evaluation_Questions.md +36 -6
  97. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  98. package/docs/ZH/Operations.md +111 -0
  99. package/docs/ZH/Output_Contracts.md +83 -10
  100. package/docs/ZH/Public_Contracts.md +24 -15
  101. package/docs/ZH/Public_Contracts_1.0.md +31 -17
  102. package/docs/ZH/README.md +24 -0
  103. package/docs/ZH/Release_Checklist.md +27 -13
  104. package/docs/ZH/Retrieval_and_Context.md +118 -0
  105. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  106. package/package.json +50 -19
@@ -1,6 +1,7 @@
1
1
  import type { SqliteDatabase } from "./sqlite-adapter.js";
2
2
  import { type SchemaMetadata } from "./connection.js";
3
- import type { EdgeKind, GraphChunk, GraphDocument, GraphEdge, GraphEntity, GraphRecordSet, GraphSection, SourceRef } from "../types.js";
3
+ import type { ChunkVector, EdgeKind, GraphChunk, GraphDocument, GraphEdge, GraphEntity, GraphRecordSet, GraphSection, SourceRef } from "../types.js";
4
+ import type { StructuredQueryAST, StructuredQueryPredicate } from "../query/structured-query.js";
4
5
  export interface StatusCounts {
5
6
  documents: number;
6
7
  sections: number;
@@ -10,6 +11,13 @@ export interface StatusCounts {
10
11
  chunks: number;
11
12
  vectors: number;
12
13
  }
14
+ export interface IndexWriteState {
15
+ expectedGeneration?: number;
16
+ extractionFingerprint?: string;
17
+ }
18
+ export declare class IndexGenerationConflict extends Error {
19
+ constructor();
20
+ }
13
21
  export interface StorageObjectStat {
14
22
  name: string;
15
23
  type: string;
@@ -77,6 +85,9 @@ export interface ChunkSearchRow {
77
85
  chunk: GraphChunk;
78
86
  rank: number;
79
87
  }
88
+ export interface EntityDefinitionSearchRow extends ChunkSearchRow {
89
+ entityId: string;
90
+ }
80
91
  export interface NodeRecord {
81
92
  id: string;
82
93
  label: string;
@@ -107,6 +118,13 @@ export type NodeResolution = {
107
118
  export interface SemanticSearchRow extends ChunkSearchRow {
108
119
  similarity: number;
109
120
  }
121
+ export interface SemanticRelationshipChunk extends ChunkSearchRow {
122
+ vector: number[];
123
+ }
124
+ export interface SemanticRelationshipCorpus {
125
+ chunks: SemanticRelationshipChunk[];
126
+ invalidVectors: number;
127
+ }
110
128
  export interface DocumentLinkStats {
111
129
  document: GraphDocument;
112
130
  nonContainmentEdges: number;
@@ -116,12 +134,26 @@ export interface DefinitionCollision {
116
134
  entity: GraphEntity;
117
135
  documents: GraphDocument[];
118
136
  }
137
+ export interface StructuredDocumentQueryRows {
138
+ documents: GraphDocument[];
139
+ total: number;
140
+ truncated: boolean;
141
+ parameterCount: number;
142
+ }
143
+ export interface StructuredPredicateDocumentIds {
144
+ documentIds: Set<string>;
145
+ parameterCount: number;
146
+ }
119
147
  export declare class GraphRepository {
120
148
  private readonly db;
121
149
  constructor(db: SqliteDatabase);
122
150
  close(): void;
123
- replaceAll(records: GraphRecordSet): void;
124
- replaceDocuments(records: GraphRecordSet, changedDocumentIds: string[], deletedDocumentIds: string[]): void;
151
+ indexWriteState(): {
152
+ extractionFingerprint?: string;
153
+ generation: number;
154
+ };
155
+ replaceAll(records: GraphRecordSet, state?: IndexWriteState): void;
156
+ replaceDocuments(records: GraphRecordSet, changedDocumentIds: string[], deletedDocumentIds: string[], canonical?: GraphRecordSet, state?: IndexWriteState): void;
125
157
  counts(): StatusCounts;
126
158
  latestIndexedAt(): string | undefined;
127
159
  schemaMetadata(): SchemaMetadata;
@@ -131,11 +163,24 @@ export declare class GraphRepository {
131
163
  id: string;
132
164
  hash: string;
133
165
  }>;
166
+ reusableVectors(chunks: GraphChunk[], profile: {
167
+ provider: string;
168
+ model: string;
169
+ dimensions: number;
170
+ }): ChunkVector[];
171
+ preservedDerivedEdges(records: GraphRecordSet): GraphEdge[];
134
172
  searchChunks(ftsQuery: string, limit: number): ChunkSearchRow[];
135
173
  findEntitiesByNormalizedNames(names: string[]): GraphEntity[];
136
174
  entityDocumentFrequencies(entityIds: string[]): Map<string, number>;
137
- findEntityDefinitions(entityIds: string[]): ChunkSearchRow[];
175
+ findEntityDefinitions(entityIds: string[]): EntityDefinitionSearchRow[];
138
176
  searchSemanticChunks(queryVector: number[], provider: string, model: string, limit: number): SemanticSearchRow[];
177
+ semanticVectorCount(provider: string, model: string, dimensions: number): number;
178
+ chunkVectors(chunkIds: string[], provider: string, model: string, dimensions: number): Map<string, number[]>;
179
+ semanticRelationshipCorpus(provider: string, model: string, dimensions: number): SemanticRelationshipCorpus;
180
+ replaceEmbeddingSimilarityEdges(edges: GraphEdge[]): {
181
+ removed: number;
182
+ inserted: number;
183
+ };
139
184
  contextChunkForNode(id: string): ChunkSearchRow | undefined;
140
185
  resolveNode(query: string): NodeRecord | undefined;
141
186
  resolveNodeDetailed(query: string): NodeResolution;
@@ -145,6 +190,8 @@ export declare class GraphRepository {
145
190
  private resolveSectionByHeading;
146
191
  edgesFromNode(id: string): GraphEdge[];
147
192
  allDocuments(): GraphDocument[];
193
+ queryStructuredDocuments(ast: StructuredQueryAST): StructuredDocumentQueryRows;
194
+ documentIdsMatchingStructuredPredicate(predicate: StructuredQueryPredicate): StructuredPredicateDocumentIds;
148
195
  allSections(): GraphSection[];
149
196
  allEntities(): GraphEntity[];
150
197
  allSourceRefs(): SourceRef[];
@@ -152,6 +199,10 @@ export declare class GraphRepository {
152
199
  documentLinkStats(): DocumentLinkStats[];
153
200
  definitionCollisions(): DefinitionCollision[];
154
201
  private insertRecords;
202
+ private reconcileSharedGraphRecords;
203
+ private assertExpectedGeneration;
204
+ private writeIndexState;
205
+ private documentHash;
155
206
  private prepareInsertVector;
156
207
  private deleteDocumentDerivedRecords;
157
208
  private pruneUnreferencedEntitiesAndSources;
@@ -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) {
@@ -215,6 +278,109 @@ export class GraphRepository {
215
278
  .sort((a, b) => b.similarity - a.similarity)
216
279
  .slice(0, limit);
217
280
  }
281
+ semanticVectorCount(provider, model, dimensions) {
282
+ const row = this.db.prepare(`
283
+ SELECT count(*) AS count
284
+ FROM chunk_vectors
285
+ WHERE provider = ? AND model = ? AND dimensions = ?
286
+ `).get(provider, model, dimensions);
287
+ return row.count;
288
+ }
289
+ chunkVectors(chunkIds, provider, model, dimensions) {
290
+ const uniqueChunkIds = [...new Set(chunkIds.filter(Boolean))];
291
+ if (!uniqueChunkIds.length) {
292
+ return new Map();
293
+ }
294
+ const placeholders = uniqueChunkIds.map(() => "?").join(", ");
295
+ const rows = this.db.prepare(`
296
+ SELECT chunk_id, vector_blob
297
+ FROM chunk_vectors
298
+ WHERE provider = ? AND model = ? AND dimensions = ? AND chunk_id IN (${placeholders})
299
+ `).all(provider, model, dimensions, ...uniqueChunkIds);
300
+ const vectors = new Map();
301
+ for (const row of rows) {
302
+ try {
303
+ const vector = decodeFloat32Vector(row.vector_blob);
304
+ if (vector.length === dimensions) {
305
+ vectors.set(row.chunk_id, vector);
306
+ }
307
+ }
308
+ catch {
309
+ // A malformed optional vector is unavailable to MMR; lexical similarity remains usable.
310
+ }
311
+ }
312
+ return vectors;
313
+ }
314
+ semanticRelationshipCorpus(provider, model, dimensions) {
315
+ const rows = this.db.prepare(`
316
+ SELECT
317
+ 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,
318
+ d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
319
+ d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
320
+ s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
321
+ s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
322
+ c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
323
+ c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
324
+ v.vector_blob AS vector_blob
325
+ FROM chunk_vectors v
326
+ JOIN chunks c ON c.id = v.chunk_id
327
+ JOIN documents d ON d.id = c.document_id
328
+ LEFT JOIN sections s ON s.id = c.section_id
329
+ WHERE v.provider = ? AND v.model = ? AND v.dimensions = ?
330
+ ORDER BY d.path ASC, s.start_line ASC, c.id ASC
331
+ `).all(provider, model, dimensions);
332
+ const chunks = [];
333
+ let invalidVectors = 0;
334
+ for (const row of rows) {
335
+ try {
336
+ const vector = decodeFloat32Vector(row.vector_blob);
337
+ if (vector.length !== dimensions || !vector.every(Number.isFinite) || !vector.some((value) => value !== 0)) {
338
+ invalidVectors += 1;
339
+ continue;
340
+ }
341
+ chunks.push({
342
+ document: rowToDocument(row, "d_"),
343
+ section: row.s_id ? rowToSection(row, "s_") : undefined,
344
+ chunk: rowToChunk(row, "c_"),
345
+ rank: 0,
346
+ vector
347
+ });
348
+ }
349
+ catch {
350
+ invalidVectors += 1;
351
+ }
352
+ }
353
+ return { chunks, invalidVectors };
354
+ }
355
+ replaceEmbeddingSimilarityEdges(edges) {
356
+ for (const edge of edges) {
357
+ if (edge.kind !== "RELATED_TO" || edge.provenance !== "embedding_similarity") {
358
+ throw new Error("Derived relationship replacement accepts only RELATED_TO/embedding_similarity edges.");
359
+ }
360
+ }
361
+ const replace = this.db.transaction(() => {
362
+ const removed = this.db.prepare("DELETE FROM edges WHERE kind = 'RELATED_TO' AND provenance = 'embedding_similarity'").run().changes;
363
+ const insert = this.db.prepare(`
364
+ INSERT INTO edges (id, from_id, to_id, kind, weight, confidence, provenance, metadata_json, created_at)
365
+ VALUES (@id, @fromId, @toId, @kind, @weight, @confidence, @provenance, @metadataJson, @createdAt)
366
+ `);
367
+ for (const edge of edges) {
368
+ insert.run({
369
+ id: edge.id,
370
+ fromId: edge.fromId,
371
+ toId: edge.toId,
372
+ kind: edge.kind,
373
+ weight: edge.weight,
374
+ confidence: edge.confidence,
375
+ provenance: edge.provenance,
376
+ metadataJson: toJson(edge.metadata),
377
+ createdAt: edge.createdAt
378
+ });
379
+ }
380
+ return { removed: Number(removed), inserted: edges.length };
381
+ });
382
+ return replace();
383
+ }
218
384
  contextChunkForNode(id) {
219
385
  const chunkRow = this.db.prepare(`
220
386
  SELECT
@@ -416,6 +582,36 @@ export class GraphRepository {
416
582
  const rows = this.db.prepare("SELECT * FROM documents ORDER BY path").all();
417
583
  return rows.map((row) => rowToDocument(row));
418
584
  }
585
+ queryStructuredDocuments(ast) {
586
+ const compiled = compileStructuredExpression(ast.expression);
587
+ const orderBy = structuredOrderBy(ast.orderBy);
588
+ const rows = this.db.prepare(`
589
+ SELECT d.*, COUNT(*) OVER() AS structured_total
590
+ FROM documents d
591
+ WHERE ${compiled.sql}
592
+ ORDER BY ${orderBy}
593
+ LIMIT ?
594
+ `).all(...compiled.parameters, ast.limit + 1);
595
+ return {
596
+ documents: rows.slice(0, ast.limit).map((row) => rowToDocument(row)),
597
+ total: rows.length ? numberValue(rows[0].structured_total) : 0,
598
+ truncated: rows.length > ast.limit,
599
+ parameterCount: compiled.parameters.length + 1
600
+ };
601
+ }
602
+ documentIdsMatchingStructuredPredicate(predicate) {
603
+ const compiled = compileStructuredPredicate(predicate);
604
+ const rows = this.db.prepare(`
605
+ SELECT d.id
606
+ FROM documents d
607
+ WHERE ${compiled.sql}
608
+ ORDER BY d.path
609
+ `).all(...compiled.parameters);
610
+ return {
611
+ documentIds: new Set(rows.map((row) => row.id)),
612
+ parameterCount: compiled.parameters.length
613
+ };
614
+ }
419
615
  allSections() {
420
616
  const rows = this.db.prepare("SELECT * FROM sections ORDER BY document_id, start_line, id").all();
421
617
  return rows.map((row) => rowToSection(row));
@@ -436,7 +632,7 @@ export class GraphRepository {
436
632
  const documents = this.allDocuments();
437
633
  const statement = this.db.prepare(`
438
634
  SELECT
439
- SUM(CASE WHEN e.kind <> 'CONTAINS' THEN 1 ELSE 0 END) AS non_containment_edges,
635
+ SUM(CASE WHEN e.kind <> 'CONTAINS' AND e.provenance <> 'embedding_similarity' THEN 1 ELSE 0 END) AS non_containment_edges,
440
636
  SUM(CASE WHEN e.kind = 'DEFINES' THEN 1 ELSE 0 END) AS definition_edges
441
637
  FROM documents d
442
638
  LEFT JOIN sections s ON s.document_id = d.id
@@ -579,6 +775,86 @@ export class GraphRepository {
579
775
  insertVector.run(vectorToParams(vector));
580
776
  }
581
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
+ }
582
858
  prepareInsertVector() {
583
859
  return this.db.prepare(`
584
860
  INSERT INTO chunk_vectors (chunk_id, provider, model, dimensions, vector_blob, created_at)
@@ -620,6 +896,169 @@ export class GraphRepository {
620
896
  }
621
897
  }
622
898
  }
899
+ function compileStructuredExpression(expression) {
900
+ if (expression.kind === "predicate") {
901
+ return compileStructuredPredicate(expression);
902
+ }
903
+ if (expression.kind === "not") {
904
+ const compiled = compileStructuredExpression(expression.expression);
905
+ return { sql: `NOT (${compiled.sql})`, parameters: compiled.parameters };
906
+ }
907
+ const left = compileStructuredExpression(expression.left);
908
+ const right = compileStructuredExpression(expression.right);
909
+ return {
910
+ sql: `(${left.sql}) ${expression.kind.toUpperCase()} (${right.sql})`,
911
+ parameters: [...left.parameters, ...right.parameters]
912
+ };
913
+ }
914
+ function compileStructuredPredicate(predicate) {
915
+ switch (predicate.field) {
916
+ case "type":
917
+ return scalarPredicate("d.type", predicate);
918
+ case "status":
919
+ return scalarPredicate("d.status", predicate);
920
+ case "trust":
921
+ return scalarPredicate("d.trust_tier", predicate);
922
+ case "path":
923
+ return scalarPredicate("d.path", predicate);
924
+ case "title":
925
+ return scalarPredicate("d.title", predicate);
926
+ case "updated":
927
+ return datePredicate("d.updated_at", predicate);
928
+ case "indexed":
929
+ return datePredicate("d.indexed_at", predicate);
930
+ case "tag":
931
+ return tagPredicate(predicate);
932
+ case "edge":
933
+ return edgeKindPredicate(predicate);
934
+ case "health":
935
+ throw new Error("Doctor-derived health predicates require hybrid structured-query execution.");
936
+ default:
937
+ if (predicate.field.startsWith("edge.")) {
938
+ return edgeTargetPredicate(predicate.field.slice("edge.".length), predicate);
939
+ }
940
+ throw new Error(`Unsupported structured query field: ${String(predicate.field)}`);
941
+ }
942
+ }
943
+ function scalarPredicate(column, predicate) {
944
+ const valueExpression = `COALESCE(${column}, '')`;
945
+ switch (predicate.operator) {
946
+ case "=":
947
+ return { sql: `LOWER(${valueExpression}) = LOWER(?)`, parameters: [predicate.value] };
948
+ case "!=":
949
+ return { sql: `LOWER(${valueExpression}) != LOWER(?)`, parameters: [predicate.value] };
950
+ case "~":
951
+ return { sql: `INSTR(LOWER(${valueExpression}), LOWER(?)) > 0`, parameters: [predicate.value] };
952
+ case "!~":
953
+ return { sql: `INSTR(LOWER(${valueExpression}), LOWER(?)) = 0`, parameters: [predicate.value] };
954
+ default:
955
+ throw new Error(`Unsupported scalar operator: ${predicate.operator}`);
956
+ }
957
+ }
958
+ function datePredicate(column, predicate) {
959
+ const valueExpression = `COALESCE(${column}, '')`;
960
+ const dayOnly = /^\d{4}-\d{2}-\d{2}$/u.test(predicate.value);
961
+ if (dayOnly && (predicate.operator === "=" || predicate.operator === "!=")) {
962
+ return {
963
+ sql: `SUBSTR(${valueExpression}, 1, 10) ${predicate.operator} ?`,
964
+ parameters: [predicate.value]
965
+ };
966
+ }
967
+ const normalized = dayOnly ? `${predicate.value}T00:00:00.000Z` : new Date(predicate.value).toISOString();
968
+ const nextDay = dayOnly ? new Date(Date.parse(normalized) + 86_400_000).toISOString() : undefined;
969
+ if (dayOnly && predicate.operator === "<=") {
970
+ return { sql: `${valueExpression} < ?`, parameters: [nextDay] };
971
+ }
972
+ if (dayOnly && predicate.operator === ">") {
973
+ return { sql: `${valueExpression} >= ?`, parameters: [nextDay] };
974
+ }
975
+ return { sql: `${valueExpression} ${predicate.operator} ?`, parameters: [normalized] };
976
+ }
977
+ function tagPredicate(predicate) {
978
+ const positiveOperator = predicate.operator === "!=" ? "=" : predicate.operator === "!~" ? "~" : predicate.operator;
979
+ const match = positiveOperator === "="
980
+ ? "LOWER(CAST(tag.value AS TEXT)) = LOWER(?)"
981
+ : "INSTR(LOWER(CAST(tag.value AS TEXT)), LOWER(?)) > 0";
982
+ const exists = `EXISTS (
983
+ SELECT 1
984
+ FROM json_each(COALESCE(d.metadata_json, '{}'), '$.tags') tag
985
+ WHERE ${match}
986
+ )`;
987
+ return {
988
+ sql: predicate.operator === "!=" || predicate.operator === "!~" ? `NOT (${exists})` : exists,
989
+ parameters: [predicate.value]
990
+ };
991
+ }
992
+ function edgeKindPredicate(predicate) {
993
+ const exists = `EXISTS (
994
+ SELECT 1 FROM edges edge
995
+ WHERE (${structuredEdgeSourceSql()}) AND edge.kind = ?
996
+ )`;
997
+ return {
998
+ sql: predicate.operator === "!=" ? `NOT (${exists})` : exists,
999
+ parameters: [predicate.value.toUpperCase()]
1000
+ };
1001
+ }
1002
+ function edgeTargetPredicate(kind, predicate) {
1003
+ const negative = predicate.operator === "!=" || predicate.operator === "!~";
1004
+ const contains = predicate.operator === "~" || predicate.operator === "!~";
1005
+ const targetExpressions = [
1006
+ "target_document.id",
1007
+ "target_document.path",
1008
+ "target_document.title",
1009
+ "target_section.id",
1010
+ "target_section.heading",
1011
+ "target_section.anchor",
1012
+ "target_entity.id",
1013
+ "target_entity.name",
1014
+ "target_source.id",
1015
+ "target_source.path",
1016
+ "edge.to_id"
1017
+ ];
1018
+ const targetMatch = targetExpressions
1019
+ .map((expression) => contains
1020
+ ? `INSTR(LOWER(COALESCE(${expression}, '')), LOWER(?)) > 0`
1021
+ : `LOWER(COALESCE(${expression}, '')) = LOWER(?)`)
1022
+ .join(" OR ");
1023
+ const exists = `EXISTS (
1024
+ SELECT 1
1025
+ FROM edges edge
1026
+ LEFT JOIN documents target_document ON target_document.id = edge.to_id
1027
+ LEFT JOIN sections target_section ON target_section.id = edge.to_id
1028
+ LEFT JOIN entities target_entity ON target_entity.id = edge.to_id
1029
+ LEFT JOIN source_refs target_source ON target_source.id = edge.to_id
1030
+ WHERE (${structuredEdgeSourceSql()})
1031
+ AND edge.kind = ?
1032
+ AND (${targetMatch})
1033
+ )`;
1034
+ return {
1035
+ sql: negative ? `NOT (${exists})` : exists,
1036
+ parameters: [kind.toUpperCase(), ...targetExpressions.map(() => predicate.value)]
1037
+ };
1038
+ }
1039
+ function structuredEdgeSourceSql() {
1040
+ return [
1041
+ "edge.from_id = d.id",
1042
+ "edge.from_id IN (SELECT section.id FROM sections section WHERE section.document_id = d.id)",
1043
+ "edge.from_id IN (SELECT chunk.id FROM chunks chunk WHERE chunk.document_id = d.id)"
1044
+ ].join(" OR ");
1045
+ }
1046
+ function structuredOrderBy(orderBy) {
1047
+ const columns = {
1048
+ path: "d.path",
1049
+ title: "d.title",
1050
+ type: "d.type",
1051
+ status: "d.status",
1052
+ trust: "d.trust_tier",
1053
+ updated: "d.updated_at",
1054
+ indexed: "d.indexed_at"
1055
+ };
1056
+ const clauses = orderBy.map((sort) => `${columns[sort.field]} ${sort.direction.toUpperCase()}`);
1057
+ if (!orderBy.some((sort) => sort.field === "path")) {
1058
+ clauses.push("d.path ASC");
1059
+ }
1060
+ return clauses.length ? clauses.join(", ") : "d.path ASC";
1061
+ }
623
1062
  function definitionChunk(row, sectionChunk, documentChunk) {
624
1063
  const sectionChunkRow = row.s_id ? sectionChunk.get(row.s_id) : undefined;
625
1064
  const chunkRow = sectionChunkRow ?? documentChunk.get(row.d_id);
@@ -905,12 +1344,20 @@ function vectorToParams(vector) {
905
1344
  };
906
1345
  }
907
1346
  function cosine(left, right) {
908
- const length = Math.min(left.length, right.length);
909
- let score = 0;
910
- for (let index = 0; index < length; index += 1) {
911
- score += left[index] * right[index];
1347
+ if (left.length !== right.length) {
1348
+ return 0;
1349
+ }
1350
+ let dot = 0;
1351
+ let leftMagnitude = 0;
1352
+ let rightMagnitude = 0;
1353
+ for (let index = 0; index < left.length; index += 1) {
1354
+ dot += left[index] * right[index];
1355
+ leftMagnitude += left[index] * left[index];
1356
+ rightMagnitude += right[index] * right[index];
912
1357
  }
913
- return score;
1358
+ return leftMagnitude > 0 && rightMagnitude > 0
1359
+ ? dot / Math.sqrt(leftMagnitude * rightMagnitude)
1360
+ : 0;
914
1361
  }
915
1362
  function fromJson(value) {
916
1363
  if (typeof value !== "string" || !value) {