@daogee/mdgraph 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README-ZH.md +54 -2
  3. package/README.md +73 -21
  4. package/dist/bin/mdgraph.js +136 -19
  5. package/dist/config/limits.d.ts +2 -0
  6. package/dist/config/limits.js +3 -1
  7. package/dist/config/load-config.js +8 -2
  8. package/dist/db/repositories.d.ts +27 -0
  9. package/dist/db/repositories.js +310 -6
  10. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  11. package/dist/evaluation/context-packing-evaluation.js +134 -0
  12. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  13. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  14. package/dist/evaluation/historical-baseline.d.ts +70 -0
  15. package/dist/evaluation/historical-baseline.js +278 -0
  16. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  17. package/dist/evaluation/related-documents-evaluation.js +163 -0
  18. package/dist/evaluation/retrieval-eval.d.ts +14 -5
  19. package/dist/evaluation/retrieval-eval.js +44 -6
  20. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  21. package/dist/evaluation/structured-query-evaluation.js +156 -0
  22. package/dist/extraction/entity-extractor.js +42 -22
  23. package/dist/extraction/graph-builder.js +2 -18
  24. package/dist/index.d.ts +17 -4
  25. package/dist/index.js +9 -4
  26. package/dist/indexer.js +20 -2
  27. package/dist/mcp/server.d.ts +4 -0
  28. package/dist/mcp/server.js +16 -7
  29. package/dist/mcp/tools.d.ts +5 -1
  30. package/dist/mcp/tools.js +93 -9
  31. package/dist/parser/markdown-parser.js +2 -0
  32. package/dist/query/context-builder.d.ts +31 -2
  33. package/dist/query/context-builder.js +162 -12
  34. package/dist/query/search.d.ts +5 -1
  35. package/dist/query/search.js +77 -13
  36. package/dist/query/structured-query-executor.d.ts +28 -0
  37. package/dist/query/structured-query-executor.js +138 -0
  38. package/dist/query/structured-query.d.ts +50 -0
  39. package/dist/query/structured-query.js +390 -0
  40. package/dist/relationships/derive-related.d.ts +86 -0
  41. package/dist/relationships/derive-related.js +322 -0
  42. package/dist/reporting/report.js +2 -2
  43. package/dist/semantic/embed-chunks.d.ts +2 -0
  44. package/dist/semantic/embed-chunks.js +31 -0
  45. package/dist/semantic/ollama-provider.d.ts +6 -0
  46. package/dist/semantic/ollama-provider.js +131 -0
  47. package/dist/semantic/provider-registry.d.ts +8 -0
  48. package/dist/semantic/provider-registry.js +66 -0
  49. package/dist/semantic/provider.d.ts +35 -0
  50. package/dist/semantic/provider.js +29 -0
  51. package/dist/semantic/status.d.ts +6 -1
  52. package/dist/semantic/status.js +49 -3
  53. package/dist/types.d.ts +7 -2
  54. package/dist/types.js +2 -1
  55. package/dist/watcher/file-watcher.d.ts +4 -0
  56. package/dist/watcher/file-watcher.js +75 -10
  57. package/dist/watcher/watch-health.d.ts +34 -0
  58. package/dist/watcher/watch-health.js +75 -0
  59. package/docs/EN/Agent_Integration.md +1 -1
  60. package/docs/EN/Architecture.md +39 -16
  61. package/docs/EN/Evaluation_Questions.md +21 -5
  62. package/docs/EN/Operations.md +91 -0
  63. package/docs/EN/Output_Contracts.md +41 -7
  64. package/docs/EN/Public_Contracts.md +23 -16
  65. package/docs/EN/Public_Contracts_1.0.md +28 -18
  66. package/docs/EN/README.md +23 -0
  67. package/docs/EN/Release_Checklist.md +26 -13
  68. package/docs/EN/Retrieval_and_Context.md +112 -0
  69. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  70. package/docs/ZH/Agent_Integration.md +1 -1
  71. package/docs/ZH/Architecture.md +39 -19
  72. package/docs/ZH/Evaluation_Questions.md +22 -6
  73. package/docs/ZH/Operations.md +91 -0
  74. package/docs/ZH/Output_Contracts.md +41 -7
  75. package/docs/ZH/Public_Contracts.md +22 -15
  76. package/docs/ZH/Public_Contracts_1.0.md +27 -17
  77. package/docs/ZH/README.md +23 -0
  78. package/docs/ZH/Release_Checklist.md +26 -13
  79. package/docs/ZH/Retrieval_and_Context.md +112 -0
  80. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  81. package/package.json +44 -18
@@ -1,6 +1,7 @@
1
1
  import type { SqliteDatabase } from "./sqlite-adapter.js";
2
2
  import { type SchemaMetadata } from "./connection.js";
3
3
  import type { 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;
@@ -107,6 +108,13 @@ export type NodeResolution = {
107
108
  export interface SemanticSearchRow extends ChunkSearchRow {
108
109
  similarity: number;
109
110
  }
111
+ export interface SemanticRelationshipChunk extends ChunkSearchRow {
112
+ vector: number[];
113
+ }
114
+ export interface SemanticRelationshipCorpus {
115
+ chunks: SemanticRelationshipChunk[];
116
+ invalidVectors: number;
117
+ }
110
118
  export interface DocumentLinkStats {
111
119
  document: GraphDocument;
112
120
  nonContainmentEdges: number;
@@ -116,6 +124,16 @@ export interface DefinitionCollision {
116
124
  entity: GraphEntity;
117
125
  documents: GraphDocument[];
118
126
  }
127
+ export interface StructuredDocumentQueryRows {
128
+ documents: GraphDocument[];
129
+ total: number;
130
+ truncated: boolean;
131
+ parameterCount: number;
132
+ }
133
+ export interface StructuredPredicateDocumentIds {
134
+ documentIds: Set<string>;
135
+ parameterCount: number;
136
+ }
119
137
  export declare class GraphRepository {
120
138
  private readonly db;
121
139
  constructor(db: SqliteDatabase);
@@ -136,6 +154,13 @@ export declare class GraphRepository {
136
154
  entityDocumentFrequencies(entityIds: string[]): Map<string, number>;
137
155
  findEntityDefinitions(entityIds: string[]): ChunkSearchRow[];
138
156
  searchSemanticChunks(queryVector: number[], provider: string, model: string, limit: number): SemanticSearchRow[];
157
+ semanticVectorCount(provider: string, model: string, dimensions: number): number;
158
+ chunkVectors(chunkIds: string[], provider: string, model: string, dimensions: number): Map<string, number[]>;
159
+ semanticRelationshipCorpus(provider: string, model: string, dimensions: number): SemanticRelationshipCorpus;
160
+ replaceEmbeddingSimilarityEdges(edges: GraphEdge[]): {
161
+ removed: number;
162
+ inserted: number;
163
+ };
139
164
  contextChunkForNode(id: string): ChunkSearchRow | undefined;
140
165
  resolveNode(query: string): NodeRecord | undefined;
141
166
  resolveNodeDetailed(query: string): NodeResolution;
@@ -145,6 +170,8 @@ export declare class GraphRepository {
145
170
  private resolveSectionByHeading;
146
171
  edgesFromNode(id: string): GraphEdge[];
147
172
  allDocuments(): GraphDocument[];
173
+ queryStructuredDocuments(ast: StructuredQueryAST): StructuredDocumentQueryRows;
174
+ documentIdsMatchingStructuredPredicate(predicate: StructuredQueryPredicate): StructuredPredicateDocumentIds;
148
175
  allSections(): GraphSection[];
149
176
  allEntities(): GraphEntity[];
150
177
  allSourceRefs(): SourceRef[];
@@ -215,6 +215,109 @@ export class GraphRepository {
215
215
  .sort((a, b) => b.similarity - a.similarity)
216
216
  .slice(0, limit);
217
217
  }
218
+ semanticVectorCount(provider, model, dimensions) {
219
+ const row = this.db.prepare(`
220
+ SELECT count(*) AS count
221
+ FROM chunk_vectors
222
+ WHERE provider = ? AND model = ? AND dimensions = ?
223
+ `).get(provider, model, dimensions);
224
+ return row.count;
225
+ }
226
+ chunkVectors(chunkIds, provider, model, dimensions) {
227
+ const uniqueChunkIds = [...new Set(chunkIds.filter(Boolean))];
228
+ if (!uniqueChunkIds.length) {
229
+ return new Map();
230
+ }
231
+ const placeholders = uniqueChunkIds.map(() => "?").join(", ");
232
+ const rows = this.db.prepare(`
233
+ SELECT chunk_id, vector_blob
234
+ FROM chunk_vectors
235
+ WHERE provider = ? AND model = ? AND dimensions = ? AND chunk_id IN (${placeholders})
236
+ `).all(provider, model, dimensions, ...uniqueChunkIds);
237
+ const vectors = new Map();
238
+ for (const row of rows) {
239
+ try {
240
+ const vector = decodeFloat32Vector(row.vector_blob);
241
+ if (vector.length === dimensions) {
242
+ vectors.set(row.chunk_id, vector);
243
+ }
244
+ }
245
+ catch {
246
+ // A malformed optional vector is unavailable to MMR; lexical similarity remains usable.
247
+ }
248
+ }
249
+ return vectors;
250
+ }
251
+ semanticRelationshipCorpus(provider, model, dimensions) {
252
+ const rows = this.db.prepare(`
253
+ SELECT
254
+ 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,
255
+ d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
256
+ d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
257
+ s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
258
+ s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
259
+ c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
260
+ c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
261
+ v.vector_blob AS vector_blob
262
+ FROM chunk_vectors v
263
+ JOIN chunks c ON c.id = v.chunk_id
264
+ JOIN documents d ON d.id = c.document_id
265
+ LEFT JOIN sections s ON s.id = c.section_id
266
+ WHERE v.provider = ? AND v.model = ? AND v.dimensions = ?
267
+ ORDER BY d.path ASC, s.start_line ASC, c.id ASC
268
+ `).all(provider, model, dimensions);
269
+ const chunks = [];
270
+ let invalidVectors = 0;
271
+ for (const row of rows) {
272
+ try {
273
+ const vector = decodeFloat32Vector(row.vector_blob);
274
+ if (vector.length !== dimensions || !vector.every(Number.isFinite) || !vector.some((value) => value !== 0)) {
275
+ invalidVectors += 1;
276
+ continue;
277
+ }
278
+ chunks.push({
279
+ document: rowToDocument(row, "d_"),
280
+ section: row.s_id ? rowToSection(row, "s_") : undefined,
281
+ chunk: rowToChunk(row, "c_"),
282
+ rank: 0,
283
+ vector
284
+ });
285
+ }
286
+ catch {
287
+ invalidVectors += 1;
288
+ }
289
+ }
290
+ return { chunks, invalidVectors };
291
+ }
292
+ replaceEmbeddingSimilarityEdges(edges) {
293
+ for (const edge of edges) {
294
+ if (edge.kind !== "RELATED_TO" || edge.provenance !== "embedding_similarity") {
295
+ throw new Error("Derived relationship replacement accepts only RELATED_TO/embedding_similarity edges.");
296
+ }
297
+ }
298
+ const replace = this.db.transaction(() => {
299
+ const removed = this.db.prepare("DELETE FROM edges WHERE kind = 'RELATED_TO' AND provenance = 'embedding_similarity'").run().changes;
300
+ const insert = this.db.prepare(`
301
+ INSERT INTO edges (id, from_id, to_id, kind, weight, confidence, provenance, metadata_json, created_at)
302
+ VALUES (@id, @fromId, @toId, @kind, @weight, @confidence, @provenance, @metadataJson, @createdAt)
303
+ `);
304
+ for (const edge of edges) {
305
+ insert.run({
306
+ id: edge.id,
307
+ fromId: edge.fromId,
308
+ toId: edge.toId,
309
+ kind: edge.kind,
310
+ weight: edge.weight,
311
+ confidence: edge.confidence,
312
+ provenance: edge.provenance,
313
+ metadataJson: toJson(edge.metadata),
314
+ createdAt: edge.createdAt
315
+ });
316
+ }
317
+ return { removed: Number(removed), inserted: edges.length };
318
+ });
319
+ return replace();
320
+ }
218
321
  contextChunkForNode(id) {
219
322
  const chunkRow = this.db.prepare(`
220
323
  SELECT
@@ -416,6 +519,36 @@ export class GraphRepository {
416
519
  const rows = this.db.prepare("SELECT * FROM documents ORDER BY path").all();
417
520
  return rows.map((row) => rowToDocument(row));
418
521
  }
522
+ queryStructuredDocuments(ast) {
523
+ const compiled = compileStructuredExpression(ast.expression);
524
+ const orderBy = structuredOrderBy(ast.orderBy);
525
+ const rows = this.db.prepare(`
526
+ SELECT d.*, COUNT(*) OVER() AS structured_total
527
+ FROM documents d
528
+ WHERE ${compiled.sql}
529
+ ORDER BY ${orderBy}
530
+ LIMIT ?
531
+ `).all(...compiled.parameters, ast.limit + 1);
532
+ return {
533
+ documents: rows.slice(0, ast.limit).map((row) => rowToDocument(row)),
534
+ total: rows.length ? numberValue(rows[0].structured_total) : 0,
535
+ truncated: rows.length > ast.limit,
536
+ parameterCount: compiled.parameters.length + 1
537
+ };
538
+ }
539
+ documentIdsMatchingStructuredPredicate(predicate) {
540
+ const compiled = compileStructuredPredicate(predicate);
541
+ const rows = this.db.prepare(`
542
+ SELECT d.id
543
+ FROM documents d
544
+ WHERE ${compiled.sql}
545
+ ORDER BY d.path
546
+ `).all(...compiled.parameters);
547
+ return {
548
+ documentIds: new Set(rows.map((row) => row.id)),
549
+ parameterCount: compiled.parameters.length
550
+ };
551
+ }
419
552
  allSections() {
420
553
  const rows = this.db.prepare("SELECT * FROM sections ORDER BY document_id, start_line, id").all();
421
554
  return rows.map((row) => rowToSection(row));
@@ -436,7 +569,7 @@ export class GraphRepository {
436
569
  const documents = this.allDocuments();
437
570
  const statement = this.db.prepare(`
438
571
  SELECT
439
- SUM(CASE WHEN e.kind <> 'CONTAINS' THEN 1 ELSE 0 END) AS non_containment_edges,
572
+ SUM(CASE WHEN e.kind <> 'CONTAINS' AND e.provenance <> 'embedding_similarity' THEN 1 ELSE 0 END) AS non_containment_edges,
440
573
  SUM(CASE WHEN e.kind = 'DEFINES' THEN 1 ELSE 0 END) AS definition_edges
441
574
  FROM documents d
442
575
  LEFT JOIN sections s ON s.document_id = d.id
@@ -620,6 +753,169 @@ export class GraphRepository {
620
753
  }
621
754
  }
622
755
  }
756
+ function compileStructuredExpression(expression) {
757
+ if (expression.kind === "predicate") {
758
+ return compileStructuredPredicate(expression);
759
+ }
760
+ if (expression.kind === "not") {
761
+ const compiled = compileStructuredExpression(expression.expression);
762
+ return { sql: `NOT (${compiled.sql})`, parameters: compiled.parameters };
763
+ }
764
+ const left = compileStructuredExpression(expression.left);
765
+ const right = compileStructuredExpression(expression.right);
766
+ return {
767
+ sql: `(${left.sql}) ${expression.kind.toUpperCase()} (${right.sql})`,
768
+ parameters: [...left.parameters, ...right.parameters]
769
+ };
770
+ }
771
+ function compileStructuredPredicate(predicate) {
772
+ switch (predicate.field) {
773
+ case "type":
774
+ return scalarPredicate("d.type", predicate);
775
+ case "status":
776
+ return scalarPredicate("d.status", predicate);
777
+ case "trust":
778
+ return scalarPredicate("d.trust_tier", predicate);
779
+ case "path":
780
+ return scalarPredicate("d.path", predicate);
781
+ case "title":
782
+ return scalarPredicate("d.title", predicate);
783
+ case "updated":
784
+ return datePredicate("d.updated_at", predicate);
785
+ case "indexed":
786
+ return datePredicate("d.indexed_at", predicate);
787
+ case "tag":
788
+ return tagPredicate(predicate);
789
+ case "edge":
790
+ return edgeKindPredicate(predicate);
791
+ case "health":
792
+ throw new Error("Doctor-derived health predicates require hybrid structured-query execution.");
793
+ default:
794
+ if (predicate.field.startsWith("edge.")) {
795
+ return edgeTargetPredicate(predicate.field.slice("edge.".length), predicate);
796
+ }
797
+ throw new Error(`Unsupported structured query field: ${String(predicate.field)}`);
798
+ }
799
+ }
800
+ function scalarPredicate(column, predicate) {
801
+ const valueExpression = `COALESCE(${column}, '')`;
802
+ switch (predicate.operator) {
803
+ case "=":
804
+ return { sql: `LOWER(${valueExpression}) = LOWER(?)`, parameters: [predicate.value] };
805
+ case "!=":
806
+ return { sql: `LOWER(${valueExpression}) != LOWER(?)`, parameters: [predicate.value] };
807
+ case "~":
808
+ return { sql: `INSTR(LOWER(${valueExpression}), LOWER(?)) > 0`, parameters: [predicate.value] };
809
+ case "!~":
810
+ return { sql: `INSTR(LOWER(${valueExpression}), LOWER(?)) = 0`, parameters: [predicate.value] };
811
+ default:
812
+ throw new Error(`Unsupported scalar operator: ${predicate.operator}`);
813
+ }
814
+ }
815
+ function datePredicate(column, predicate) {
816
+ const valueExpression = `COALESCE(${column}, '')`;
817
+ const dayOnly = /^\d{4}-\d{2}-\d{2}$/u.test(predicate.value);
818
+ if (dayOnly && (predicate.operator === "=" || predicate.operator === "!=")) {
819
+ return {
820
+ sql: `SUBSTR(${valueExpression}, 1, 10) ${predicate.operator} ?`,
821
+ parameters: [predicate.value]
822
+ };
823
+ }
824
+ const normalized = dayOnly ? `${predicate.value}T00:00:00.000Z` : new Date(predicate.value).toISOString();
825
+ const nextDay = dayOnly ? new Date(Date.parse(normalized) + 86_400_000).toISOString() : undefined;
826
+ if (dayOnly && predicate.operator === "<=") {
827
+ return { sql: `${valueExpression} < ?`, parameters: [nextDay] };
828
+ }
829
+ if (dayOnly && predicate.operator === ">") {
830
+ return { sql: `${valueExpression} >= ?`, parameters: [nextDay] };
831
+ }
832
+ return { sql: `${valueExpression} ${predicate.operator} ?`, parameters: [normalized] };
833
+ }
834
+ function tagPredicate(predicate) {
835
+ const positiveOperator = predicate.operator === "!=" ? "=" : predicate.operator === "!~" ? "~" : predicate.operator;
836
+ const match = positiveOperator === "="
837
+ ? "LOWER(CAST(tag.value AS TEXT)) = LOWER(?)"
838
+ : "INSTR(LOWER(CAST(tag.value AS TEXT)), LOWER(?)) > 0";
839
+ const exists = `EXISTS (
840
+ SELECT 1
841
+ FROM json_each(COALESCE(d.metadata_json, '{}'), '$.tags') tag
842
+ WHERE ${match}
843
+ )`;
844
+ return {
845
+ sql: predicate.operator === "!=" || predicate.operator === "!~" ? `NOT (${exists})` : exists,
846
+ parameters: [predicate.value]
847
+ };
848
+ }
849
+ function edgeKindPredicate(predicate) {
850
+ const exists = `EXISTS (
851
+ SELECT 1 FROM edges edge
852
+ WHERE (${structuredEdgeSourceSql()}) AND edge.kind = ?
853
+ )`;
854
+ return {
855
+ sql: predicate.operator === "!=" ? `NOT (${exists})` : exists,
856
+ parameters: [predicate.value.toUpperCase()]
857
+ };
858
+ }
859
+ function edgeTargetPredicate(kind, predicate) {
860
+ const negative = predicate.operator === "!=" || predicate.operator === "!~";
861
+ const contains = predicate.operator === "~" || predicate.operator === "!~";
862
+ const targetExpressions = [
863
+ "target_document.id",
864
+ "target_document.path",
865
+ "target_document.title",
866
+ "target_section.id",
867
+ "target_section.heading",
868
+ "target_section.anchor",
869
+ "target_entity.id",
870
+ "target_entity.name",
871
+ "target_source.id",
872
+ "target_source.path",
873
+ "edge.to_id"
874
+ ];
875
+ const targetMatch = targetExpressions
876
+ .map((expression) => contains
877
+ ? `INSTR(LOWER(COALESCE(${expression}, '')), LOWER(?)) > 0`
878
+ : `LOWER(COALESCE(${expression}, '')) = LOWER(?)`)
879
+ .join(" OR ");
880
+ const exists = `EXISTS (
881
+ SELECT 1
882
+ FROM edges edge
883
+ LEFT JOIN documents target_document ON target_document.id = edge.to_id
884
+ LEFT JOIN sections target_section ON target_section.id = edge.to_id
885
+ LEFT JOIN entities target_entity ON target_entity.id = edge.to_id
886
+ LEFT JOIN source_refs target_source ON target_source.id = edge.to_id
887
+ WHERE (${structuredEdgeSourceSql()})
888
+ AND edge.kind = ?
889
+ AND (${targetMatch})
890
+ )`;
891
+ return {
892
+ sql: negative ? `NOT (${exists})` : exists,
893
+ parameters: [kind.toUpperCase(), ...targetExpressions.map(() => predicate.value)]
894
+ };
895
+ }
896
+ function structuredEdgeSourceSql() {
897
+ return [
898
+ "edge.from_id = d.id",
899
+ "edge.from_id IN (SELECT section.id FROM sections section WHERE section.document_id = d.id)",
900
+ "edge.from_id IN (SELECT chunk.id FROM chunks chunk WHERE chunk.document_id = d.id)"
901
+ ].join(" OR ");
902
+ }
903
+ function structuredOrderBy(orderBy) {
904
+ const columns = {
905
+ path: "d.path",
906
+ title: "d.title",
907
+ type: "d.type",
908
+ status: "d.status",
909
+ trust: "d.trust_tier",
910
+ updated: "d.updated_at",
911
+ indexed: "d.indexed_at"
912
+ };
913
+ const clauses = orderBy.map((sort) => `${columns[sort.field]} ${sort.direction.toUpperCase()}`);
914
+ if (!orderBy.some((sort) => sort.field === "path")) {
915
+ clauses.push("d.path ASC");
916
+ }
917
+ return clauses.length ? clauses.join(", ") : "d.path ASC";
918
+ }
623
919
  function definitionChunk(row, sectionChunk, documentChunk) {
624
920
  const sectionChunkRow = row.s_id ? sectionChunk.get(row.s_id) : undefined;
625
921
  const chunkRow = sectionChunkRow ?? documentChunk.get(row.d_id);
@@ -905,12 +1201,20 @@ function vectorToParams(vector) {
905
1201
  };
906
1202
  }
907
1203
  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];
1204
+ if (left.length !== right.length) {
1205
+ return 0;
1206
+ }
1207
+ let dot = 0;
1208
+ let leftMagnitude = 0;
1209
+ let rightMagnitude = 0;
1210
+ for (let index = 0; index < left.length; index += 1) {
1211
+ dot += left[index] * right[index];
1212
+ leftMagnitude += left[index] * left[index];
1213
+ rightMagnitude += right[index] * right[index];
912
1214
  }
913
- return score;
1215
+ return leftMagnitude > 0 && rightMagnitude > 0
1216
+ ? dot / Math.sqrt(leftMagnitude * rightMagnitude)
1217
+ : 0;
914
1218
  }
915
1219
  function fromJson(value) {
916
1220
  if (typeof value !== "string" || !value) {
@@ -0,0 +1,29 @@
1
+ import { type ContextDebug, type ContextPackingStrategy } from "../query/context-builder.js";
2
+ export declare const CONTEXT_PACKING_EVALUATION_VERSION = 1;
3
+ export declare const CONTEXT_PACKING_GATES: {
4
+ readonly minimumRedundancyReduction: 0.2;
5
+ readonly maximumDocumentRecallDrop: 0.02;
6
+ };
7
+ export interface ContextPackingMeasurement {
8
+ packingStrategy: ContextPackingStrategy;
9
+ itemCount: number;
10
+ uniqueDocuments: number;
11
+ expectedDocumentRecall: number;
12
+ averagePairwiseJaccard: number;
13
+ maximumPairwiseJaccard: number;
14
+ nearDuplicatePairs: number;
15
+ budgetFit: boolean;
16
+ packingSimilarity?: ContextDebug["packingSimilarity"];
17
+ redundancySkippedItems: number;
18
+ }
19
+ export interface ContextPackingEvaluationReport {
20
+ evaluationVersion: typeof CONTEXT_PACKING_EVALUATION_VERSION;
21
+ baseline: ContextPackingMeasurement;
22
+ mmr: ContextPackingMeasurement;
23
+ redundancyReduction: number;
24
+ documentRecallDrop: number;
25
+ gates: typeof CONTEXT_PACKING_GATES;
26
+ passed: boolean;
27
+ elapsedMs: number;
28
+ }
29
+ export declare function runContextPackingEvaluation(): Promise<ContextPackingEvaluationReport>;
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+ import { DEFAULT_CONFIG } from "../config/load-config.js";
6
+ import { openDatabase } from "../db/connection.js";
7
+ import { GraphRepository } from "../db/repositories.js";
8
+ import { indexProject } from "../indexer.js";
9
+ import { buildContext } from "../query/context-builder.js";
10
+ export const CONTEXT_PACKING_EVALUATION_VERSION = 1;
11
+ export const CONTEXT_PACKING_GATES = {
12
+ minimumRedundancyReduction: 0.2,
13
+ maximumDocumentRecallDrop: 0.02
14
+ };
15
+ const EXPECTED_DOCUMENTS = [
16
+ "docs/recovery-details.md",
17
+ "docs/recovery-limits.md",
18
+ "docs/recovery-operations.md"
19
+ ];
20
+ export async function runContextPackingEvaluation() {
21
+ const started = performance.now();
22
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mdgraph-context-packing-"));
23
+ try {
24
+ writeFixture(root);
25
+ await indexProject(root, { full: true });
26
+ const repository = new GraphRepository(openDatabase(root));
27
+ try {
28
+ const config = {
29
+ ...DEFAULT_CONFIG,
30
+ search: { ...DEFAULT_CONFIG.search, defaultLimit: 12, maxContextChars: 50_000 }
31
+ };
32
+ const baseline = measure(repository, config, "mmr-style-document-round-robin");
33
+ const mmr = measure(repository, config, "mmr");
34
+ const redundancyReduction = baseline.averagePairwiseJaccard
35
+ ? round((baseline.averagePairwiseJaccard - mmr.averagePairwiseJaccard) / baseline.averagePairwiseJaccard)
36
+ : 0;
37
+ const documentRecallDrop = round(Math.max(0, baseline.expectedDocumentRecall - mmr.expectedDocumentRecall));
38
+ const passed = redundancyReduction >= CONTEXT_PACKING_GATES.minimumRedundancyReduction
39
+ && documentRecallDrop <= CONTEXT_PACKING_GATES.maximumDocumentRecallDrop
40
+ && mmr.budgetFit;
41
+ return {
42
+ evaluationVersion: CONTEXT_PACKING_EVALUATION_VERSION,
43
+ baseline,
44
+ mmr,
45
+ redundancyReduction,
46
+ documentRecallDrop,
47
+ gates: CONTEXT_PACKING_GATES,
48
+ passed,
49
+ elapsedMs: Number((performance.now() - started).toFixed(2))
50
+ };
51
+ }
52
+ finally {
53
+ repository.close();
54
+ }
55
+ }
56
+ finally {
57
+ fs.rmSync(root, { recursive: true, force: true });
58
+ }
59
+ }
60
+ function measure(repository, config, packingStrategy) {
61
+ const context = buildContext(repository, config, "SessionRecoveryPolicy", {
62
+ debug: true,
63
+ searchLimit: 12,
64
+ maxChars: 50_000,
65
+ packingStrategy
66
+ });
67
+ const pairwise = pairwiseJaccard(context.items.map((item) => item.content));
68
+ const observedDocuments = new Set(context.items.map((item) => item.path));
69
+ return {
70
+ packingStrategy,
71
+ itemCount: context.items.length,
72
+ uniqueDocuments: observedDocuments.size,
73
+ expectedDocumentRecall: ratio(EXPECTED_DOCUMENTS.filter((document) => observedDocuments.has(document)).length, EXPECTED_DOCUMENTS.length),
74
+ averagePairwiseJaccard: average(pairwise),
75
+ maximumPairwiseJaccard: pairwise.length ? round(Math.max(...pairwise)) : 0,
76
+ nearDuplicatePairs: pairwise.filter((value) => value >= 0.8).length,
77
+ budgetFit: context.usedChars <= context.maxChars,
78
+ packingSimilarity: context.debug?.packingSimilarity,
79
+ redundancySkippedItems: context.debug?.redundancySkippedItems ?? 0
80
+ };
81
+ }
82
+ function writeFixture(root) {
83
+ writeMarkdown(root, "docs/recovery-details.md", "Recovery Details", [
84
+ "## First Attempt",
85
+ "",
86
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics.",
87
+ "",
88
+ "## Second Attempt",
89
+ "",
90
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics.",
91
+ "",
92
+ "## Third Attempt",
93
+ "",
94
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics."
95
+ ].join("\n"));
96
+ writeMarkdown(root, "docs/recovery-limits.md", "Recovery Limits", "`SessionRecoveryPolicy` caps retries before returning a terminal authentication response.");
97
+ writeMarkdown(root, "docs/recovery-operations.md", "Recovery Operations", "`SessionRecoveryPolicy` routes exhausted attempts to operational diagnostics and an incident runbook.");
98
+ }
99
+ function writeMarkdown(root, relativePath, title, content) {
100
+ const target = path.join(root, relativePath);
101
+ fs.mkdirSync(path.dirname(target), { recursive: true });
102
+ fs.writeFileSync(target, `# ${title}\n\n${content}\n`, "utf8");
103
+ }
104
+ function pairwiseJaccard(contents) {
105
+ const tokenSets = contents.map(tokensForSimilarity);
106
+ const similarities = [];
107
+ for (let left = 0; left < tokenSets.length; left += 1) {
108
+ for (let right = left + 1; right < tokenSets.length; right += 1) {
109
+ similarities.push(jaccard(tokenSets[left], tokenSets[right]));
110
+ }
111
+ }
112
+ return similarities;
113
+ }
114
+ function tokensForSimilarity(content) {
115
+ return new Set(content.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []);
116
+ }
117
+ function jaccard(left, right) {
118
+ let intersection = 0;
119
+ for (const token of left) {
120
+ if (right.has(token)) {
121
+ intersection += 1;
122
+ }
123
+ }
124
+ return ratio(intersection, new Set([...left, ...right]).size);
125
+ }
126
+ function average(values) {
127
+ return values.length ? round(values.reduce((sum, value) => sum + value, 0) / values.length) : 0;
128
+ }
129
+ function ratio(numerator, denominator) {
130
+ return denominator ? round(numerator / denominator) : 0;
131
+ }
132
+ function round(value) {
133
+ return Number(value.toFixed(4));
134
+ }
@@ -0,0 +1,38 @@
1
+ import type { EntityKind } from "../types.js";
2
+ export declare const ENTITY_EXTRACTION_EVALUATION_VERSION = 1;
3
+ export declare const ENTITY_EXTRACTION_GATES: {
4
+ readonly minimumPrecision: 0.9;
5
+ readonly minimumRecall: 0.8;
6
+ readonly minimumCjkRecall: 0.8;
7
+ };
8
+ export interface EntityExtractionExpectedEntity {
9
+ name: string;
10
+ kind: EntityKind;
11
+ language: "latin" | "cjk";
12
+ }
13
+ export interface EntityExtractionEvaluationReport {
14
+ evaluationVersion: typeof ENTITY_EXTRACTION_EVALUATION_VERSION;
15
+ expected: EntityExtractionExpectedEntity[];
16
+ extracted: Array<{
17
+ name: string;
18
+ kind: EntityKind;
19
+ }>;
20
+ truePositives: Array<{
21
+ name: string;
22
+ kind: EntityKind;
23
+ }>;
24
+ falsePositives: Array<{
25
+ name: string;
26
+ kind: EntityKind;
27
+ }>;
28
+ falseNegatives: EntityExtractionExpectedEntity[];
29
+ expectedNoise: string[];
30
+ leakedNoise: string[];
31
+ precision: number;
32
+ recall: number;
33
+ cjkRecall: number;
34
+ elapsedMs: number;
35
+ }
36
+ export declare const ENTITY_EXTRACTION_EXPECTED: EntityExtractionExpectedEntity[];
37
+ export declare const ENTITY_EXTRACTION_NOISE: readonly ["/auth/session.ts", "Design", "Do", "Fall", "GET", "Include", "Note", "Prefer", "Reason", "Should", "Start", "The", "Use", "When"];
38
+ export declare function runEntityExtractionEvaluation(): EntityExtractionEvaluationReport;