agentic-qe 3.6.9 → 3.6.11

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 (117) hide show
  1. package/.claude/skills/.validation/schemas/skill-eval.schema.json +11 -1
  2. package/.claude/skills/pr-review/SKILL.md +2 -2
  3. package/.claude/skills/qcsd-production-swarm/SKILL.md +2781 -0
  4. package/.claude/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +246 -0
  5. package/.claude/skills/qcsd-production-swarm/schemas/output.json +505 -0
  6. package/.claude/skills/qcsd-production-swarm/scripts/validate-config.json +25 -0
  7. package/.claude/skills/skills-manifest.json +5 -5
  8. package/package.json +1 -1
  9. package/scripts/benchmark-hnsw-loading.ts +480 -0
  10. package/scripts/benchmark-kg-assisted.ts +725 -0
  11. package/scripts/collect-production-telemetry.sh +291 -0
  12. package/scripts/detect-skill-conflicts.ts +347 -0
  13. package/scripts/eval-driven-workflow.ts +704 -0
  14. package/scripts/run-skill-eval.ts +210 -10
  15. package/scripts/score-skill-quality.ts +511 -0
  16. package/v3/CHANGELOG.md +44 -0
  17. package/v3/assets/skills/pr-review/SKILL.md +2 -2
  18. package/v3/dist/cli/bundle.js +1526 -700
  19. package/v3/dist/cli/commands/code.d.ts.map +1 -1
  20. package/v3/dist/cli/commands/code.js +9 -85
  21. package/v3/dist/cli/commands/code.js.map +1 -1
  22. package/v3/dist/cli/commands/coverage.d.ts.map +1 -1
  23. package/v3/dist/cli/commands/coverage.js +3 -28
  24. package/v3/dist/cli/commands/coverage.js.map +1 -1
  25. package/v3/dist/cli/commands/hooks.d.ts.map +1 -1
  26. package/v3/dist/cli/commands/hooks.js +143 -2
  27. package/v3/dist/cli/commands/hooks.js.map +1 -1
  28. package/v3/dist/cli/commands/security.d.ts.map +1 -1
  29. package/v3/dist/cli/commands/security.js +3 -29
  30. package/v3/dist/cli/commands/security.js.map +1 -1
  31. package/v3/dist/cli/commands/test.d.ts.map +1 -1
  32. package/v3/dist/cli/commands/test.js +11 -58
  33. package/v3/dist/cli/commands/test.js.map +1 -1
  34. package/v3/dist/cli/utils/file-discovery.d.ts +27 -0
  35. package/v3/dist/cli/utils/file-discovery.d.ts.map +1 -0
  36. package/v3/dist/cli/utils/file-discovery.js +105 -0
  37. package/v3/dist/cli/utils/file-discovery.js.map +1 -0
  38. package/v3/dist/coordination/task-executor.d.ts.map +1 -1
  39. package/v3/dist/coordination/task-executor.js +304 -44
  40. package/v3/dist/coordination/task-executor.js.map +1 -1
  41. package/v3/dist/domains/code-intelligence/coordinator.d.ts.map +1 -1
  42. package/v3/dist/domains/code-intelligence/coordinator.js +8 -1
  43. package/v3/dist/domains/code-intelligence/coordinator.js.map +1 -1
  44. package/v3/dist/domains/code-intelligence/services/metric-collector/index.d.ts.map +1 -1
  45. package/v3/dist/domains/code-intelligence/services/metric-collector/index.js +10 -0
  46. package/v3/dist/domains/code-intelligence/services/metric-collector/index.js.map +1 -1
  47. package/v3/dist/domains/code-intelligence/services/metric-collector/interfaces.d.ts +7 -1
  48. package/v3/dist/domains/code-intelligence/services/metric-collector/interfaces.d.ts.map +1 -1
  49. package/v3/dist/domains/code-intelligence/services/metric-collector/interfaces.js +10 -1
  50. package/v3/dist/domains/code-intelligence/services/metric-collector/interfaces.js.map +1 -1
  51. package/v3/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +34 -10
  52. package/v3/dist/domains/code-intelligence/services/metric-collector/loc-counter.js.map +1 -1
  53. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts +9 -0
  54. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts.map +1 -1
  55. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js +38 -3
  56. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js.map +1 -1
  57. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.d.ts.map +1 -1
  58. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.js +58 -6
  59. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.js.map +1 -1
  60. package/v3/dist/domains/test-generation/generators/mocha-generator.d.ts.map +1 -1
  61. package/v3/dist/domains/test-generation/generators/mocha-generator.js +79 -7
  62. package/v3/dist/domains/test-generation/generators/mocha-generator.js.map +1 -1
  63. package/v3/dist/domains/test-generation/generators/pytest-generator.d.ts +4 -0
  64. package/v3/dist/domains/test-generation/generators/pytest-generator.d.ts.map +1 -1
  65. package/v3/dist/domains/test-generation/generators/pytest-generator.js +77 -10
  66. package/v3/dist/domains/test-generation/generators/pytest-generator.js.map +1 -1
  67. package/v3/dist/domains/test-generation/interfaces/test-generator.interface.d.ts +21 -0
  68. package/v3/dist/domains/test-generation/interfaces/test-generator.interface.d.ts.map +1 -1
  69. package/v3/dist/domains/test-generation/interfaces.d.ts +21 -0
  70. package/v3/dist/domains/test-generation/interfaces.d.ts.map +1 -1
  71. package/v3/dist/domains/test-generation/services/test-generator.d.ts +22 -0
  72. package/v3/dist/domains/test-generation/services/test-generator.d.ts.map +1 -1
  73. package/v3/dist/domains/test-generation/services/test-generator.js +163 -3
  74. package/v3/dist/domains/test-generation/services/test-generator.js.map +1 -1
  75. package/v3/dist/init/init-wizard-hooks.d.ts +8 -1
  76. package/v3/dist/init/init-wizard-hooks.d.ts.map +1 -1
  77. package/v3/dist/init/init-wizard-hooks.js +47 -39
  78. package/v3/dist/init/init-wizard-hooks.js.map +1 -1
  79. package/v3/dist/init/phases/07-hooks.d.ts +11 -1
  80. package/v3/dist/init/phases/07-hooks.d.ts.map +1 -1
  81. package/v3/dist/init/phases/07-hooks.js +46 -50
  82. package/v3/dist/init/phases/07-hooks.js.map +1 -1
  83. package/v3/dist/init/settings-merge.d.ts +35 -0
  84. package/v3/dist/init/settings-merge.d.ts.map +1 -0
  85. package/v3/dist/init/settings-merge.js +140 -0
  86. package/v3/dist/init/settings-merge.js.map +1 -0
  87. package/v3/dist/integrations/agentic-flow/model-router/router.js +1 -1
  88. package/v3/dist/integrations/agentic-flow/model-router/router.js.map +1 -1
  89. package/v3/dist/integrations/agentic-flow/model-router/score-calculator.d.ts.map +1 -1
  90. package/v3/dist/integrations/agentic-flow/model-router/score-calculator.js +18 -3
  91. package/v3/dist/integrations/agentic-flow/model-router/score-calculator.js.map +1 -1
  92. package/v3/dist/integrations/agentic-flow/model-router/signal-collector.d.ts +3 -3
  93. package/v3/dist/integrations/agentic-flow/model-router/signal-collector.d.ts.map +1 -1
  94. package/v3/dist/integrations/agentic-flow/model-router/signal-collector.js +18 -0
  95. package/v3/dist/integrations/agentic-flow/model-router/signal-collector.js.map +1 -1
  96. package/v3/dist/kernel/unified-memory-hnsw.d.ts +29 -0
  97. package/v3/dist/kernel/unified-memory-hnsw.d.ts.map +1 -1
  98. package/v3/dist/kernel/unified-memory-hnsw.js +136 -0
  99. package/v3/dist/kernel/unified-memory-hnsw.js.map +1 -1
  100. package/v3/dist/kernel/unified-memory.d.ts +2 -2
  101. package/v3/dist/kernel/unified-memory.d.ts.map +1 -1
  102. package/v3/dist/kernel/unified-memory.js +7 -9
  103. package/v3/dist/kernel/unified-memory.js.map +1 -1
  104. package/v3/dist/learning/qe-hooks.d.ts.map +1 -1
  105. package/v3/dist/learning/qe-hooks.js +34 -3
  106. package/v3/dist/learning/qe-hooks.js.map +1 -1
  107. package/v3/dist/mcp/bundle.js +1403 -425
  108. package/v3/dist/mcp/handlers/domain-handler-configs.d.ts.map +1 -1
  109. package/v3/dist/mcp/handlers/domain-handler-configs.js +40 -31
  110. package/v3/dist/mcp/handlers/domain-handler-configs.js.map +1 -1
  111. package/v3/dist/mcp/handlers/task-handlers.d.ts.map +1 -1
  112. package/v3/dist/mcp/handlers/task-handlers.js +68 -5
  113. package/v3/dist/mcp/handlers/task-handlers.js.map +1 -1
  114. package/v3/dist/mcp/protocol-server.d.ts.map +1 -1
  115. package/v3/dist/mcp/protocol-server.js +16 -2
  116. package/v3/dist/mcp/protocol-server.js.map +1 -1
  117. package/v3/package.json +1 -1
@@ -4597,13 +4597,78 @@ var init_sql_safety = __esm({
4597
4597
  }
4598
4598
  });
4599
4599
 
4600
+ // native-require:@ruvector/gnn
4601
+ var gnn_exports = {};
4602
+ __export(gnn_exports, {
4603
+ DotProductAttention: () => DotProductAttention2,
4604
+ FlashAttention: () => FlashAttention2,
4605
+ HyperbolicAttention: () => HyperbolicAttention2,
4606
+ LinearAttention: () => LinearAttention2,
4607
+ MoEAttention: () => MoEAttention2,
4608
+ MultiHeadAttention: () => MultiHeadAttention2,
4609
+ RuvectorLayer: () => RuvectorLayer2,
4610
+ SonaEngine: () => SonaEngine2,
4611
+ TensorCompress: () => TensorCompress2,
4612
+ default: () => gnn_default,
4613
+ differentiableSearch: () => differentiableSearch2,
4614
+ getCompressionLevel: () => getCompressionLevel2,
4615
+ hierarchicalForward: () => hierarchicalForward2,
4616
+ init: () => init2,
4617
+ pipeline: () => pipeline2
4618
+ });
4619
+ import { createRequire as createRequire2 } from "module";
4620
+ var __require3, __mod2, gnn_default, RuvectorLayer2, TensorCompress2, differentiableSearch2, hierarchicalForward2, getCompressionLevel2, init2, FlashAttention2, DotProductAttention2, MultiHeadAttention2, HyperbolicAttention2, LinearAttention2, MoEAttention2, SonaEngine2, pipeline2;
4621
+ var init_gnn = __esm({
4622
+ "native-require:@ruvector/gnn"() {
4623
+ __require3 = createRequire2(import.meta.url);
4624
+ __mod2 = __require3("@ruvector/gnn");
4625
+ gnn_default = __mod2;
4626
+ ({
4627
+ RuvectorLayer: RuvectorLayer2,
4628
+ TensorCompress: TensorCompress2,
4629
+ differentiableSearch: differentiableSearch2,
4630
+ hierarchicalForward: hierarchicalForward2,
4631
+ getCompressionLevel: getCompressionLevel2,
4632
+ init: init2,
4633
+ FlashAttention: FlashAttention2,
4634
+ DotProductAttention: DotProductAttention2,
4635
+ MultiHeadAttention: MultiHeadAttention2,
4636
+ HyperbolicAttention: HyperbolicAttention2,
4637
+ LinearAttention: LinearAttention2,
4638
+ MoEAttention: MoEAttention2,
4639
+ SonaEngine: SonaEngine2,
4640
+ pipeline: pipeline2
4641
+ } = __mod2 || {});
4642
+ }
4643
+ });
4644
+
4600
4645
  // src/kernel/unified-memory-hnsw.ts
4601
- var BinaryHeap, InMemoryHNSWIndex;
4646
+ function computeNorm(v62) {
4647
+ let sum = 0;
4648
+ for (let i58 = 0; i58 < v62.length; i58++) sum += v62[i58] * v62[i58];
4649
+ return Math.sqrt(sum);
4650
+ }
4651
+ function fastCosine(a37, b68, normA, normB) {
4652
+ const denom = normA * normB;
4653
+ if (denom === 0) return 0;
4654
+ let dot = 0;
4655
+ for (let i58 = 0; i58 < a37.length; i58++) dot += a37[i58] * b68[i58];
4656
+ return dot / denom;
4657
+ }
4658
+ var ruvectorDifferentiableSearch, ruvectorInit, BinaryHeap, InMemoryHNSWIndex, RuvectorFlatIndex;
4602
4659
  var init_unified_memory_hnsw = __esm({
4603
4660
  "src/kernel/unified-memory-hnsw.ts"() {
4604
4661
  "use strict";
4605
4662
  init_vector_math();
4606
4663
  init_constants();
4664
+ ruvectorDifferentiableSearch = null;
4665
+ ruvectorInit = null;
4666
+ try {
4667
+ const gnn = (init_gnn(), __toCommonJS(gnn_exports));
4668
+ ruvectorDifferentiableSearch = gnn.differentiableSearch;
4669
+ ruvectorInit = gnn.init;
4670
+ } catch {
4671
+ }
4607
4672
  BinaryHeap = class {
4608
4673
  data = [];
4609
4674
  compareFn;
@@ -4936,6 +5001,94 @@ var init_unified_memory_hnsw = __esm({
4936
5001
  this.currentMaxLevel = -1;
4937
5002
  }
4938
5003
  };
5004
+ RuvectorFlatIndex = class {
5005
+ ids = [];
5006
+ vectors = [];
5007
+ /** Pre-computed L2 norms for each vector (enables dot-product-only cosine). */
5008
+ norms = [];
5009
+ idToIndex = /* @__PURE__ */ new Map();
5010
+ initialized = false;
5011
+ constructor() {
5012
+ if (ruvectorInit && !this.initialized) {
5013
+ try {
5014
+ ruvectorInit();
5015
+ this.initialized = true;
5016
+ } catch {
5017
+ this.initialized = ruvectorDifferentiableSearch !== null;
5018
+ }
5019
+ }
5020
+ }
5021
+ add(id, embedding) {
5022
+ const f322 = new Float32Array(embedding);
5023
+ const norm = computeNorm(f322);
5024
+ if (this.idToIndex.has(id)) {
5025
+ const idx2 = this.idToIndex.get(id);
5026
+ this.vectors[idx2] = f322;
5027
+ this.norms[idx2] = norm;
5028
+ return;
5029
+ }
5030
+ const idx = this.ids.length;
5031
+ this.ids.push(id);
5032
+ this.vectors.push(f322);
5033
+ this.norms.push(norm);
5034
+ this.idToIndex.set(id, idx);
5035
+ }
5036
+ search(query, k68) {
5037
+ if (this.ids.length === 0) return [];
5038
+ const actualK = Math.min(k68, this.ids.length);
5039
+ if (ruvectorDifferentiableSearch && this.vectors.length > 0) {
5040
+ const queryF322 = new Float32Array(query);
5041
+ const queryNorm2 = computeNorm(queryF322);
5042
+ const result = ruvectorDifferentiableSearch(
5043
+ queryF322,
5044
+ this.vectors,
5045
+ actualK,
5046
+ 1
5047
+ );
5048
+ return result.indices.map((idx) => ({
5049
+ id: this.ids[idx],
5050
+ score: fastCosine(queryF322, this.vectors[idx], queryNorm2, this.norms[idx])
5051
+ }));
5052
+ }
5053
+ const queryF32 = new Float32Array(query);
5054
+ const queryNorm = computeNorm(queryF32);
5055
+ const scored = [];
5056
+ for (let i58 = 0; i58 < this.ids.length; i58++) {
5057
+ scored.push({
5058
+ id: this.ids[i58],
5059
+ score: fastCosine(queryF32, this.vectors[i58], queryNorm, this.norms[i58])
5060
+ });
5061
+ }
5062
+ scored.sort((a37, b68) => b68.score - a37.score);
5063
+ return scored.slice(0, actualK);
5064
+ }
5065
+ remove(id) {
5066
+ const idx = this.idToIndex.get(id);
5067
+ if (idx === void 0) return false;
5068
+ const lastIdx = this.ids.length - 1;
5069
+ if (idx !== lastIdx) {
5070
+ const lastId = this.ids[lastIdx];
5071
+ this.ids[idx] = lastId;
5072
+ this.vectors[idx] = this.vectors[lastIdx];
5073
+ this.norms[idx] = this.norms[lastIdx];
5074
+ this.idToIndex.set(lastId, idx);
5075
+ }
5076
+ this.ids.pop();
5077
+ this.vectors.pop();
5078
+ this.norms.pop();
5079
+ this.idToIndex.delete(id);
5080
+ return true;
5081
+ }
5082
+ clear() {
5083
+ this.ids = [];
5084
+ this.vectors = [];
5085
+ this.norms = [];
5086
+ this.idToIndex.clear();
5087
+ }
5088
+ size() {
5089
+ return this.ids.length;
5090
+ }
5091
+ };
4939
5092
  }
4940
5093
  });
4941
5094
 
@@ -6490,6 +6643,7 @@ __export(unified_memory_exports, {
6490
6643
  BinaryHeap: () => BinaryHeap,
6491
6644
  DEFAULT_UNIFIED_MEMORY_CONFIG: () => DEFAULT_UNIFIED_MEMORY_CONFIG,
6492
6645
  InMemoryHNSWIndex: () => InMemoryHNSWIndex,
6646
+ RuvectorFlatIndex: () => RuvectorFlatIndex,
6493
6647
  UnifiedMemoryManager: () => UnifiedMemoryManager,
6494
6648
  clearProjectRootCache: () => clearProjectRootCache,
6495
6649
  findProjectRoot: () => findProjectRoot,
@@ -6620,7 +6774,7 @@ var init_unified_memory = __esm({
6620
6774
  vectorsLoaded = false;
6621
6775
  initPromise = null;
6622
6776
  preparedStatements = /* @__PURE__ */ new Map();
6623
- vectorIndex = new InMemoryHNSWIndex();
6777
+ vectorIndex = new RuvectorFlatIndex();
6624
6778
  // CRDT store for distributed state synchronization
6625
6779
  crdtStore = null;
6626
6780
  constructor(config) {
@@ -6788,7 +6942,7 @@ var init_unified_memory = __esm({
6788
6942
  this.vectorIndex.add(row2.id, embedding);
6789
6943
  }
6790
6944
  this.vectorsLoaded = true;
6791
- console.log(`[UnifiedMemory] Loaded ${rows.length} vectors into HNSW index`);
6945
+ console.log(`[UnifiedMemory] Loaded ${rows.length} vectors into vector index (ruvector flat)`);
6792
6946
  }
6793
6947
  // ============================================================================
6794
6948
  // KV Store Operations (v2 compatible)
@@ -7092,9 +7246,8 @@ var init_unified_memory = __esm({
7092
7246
  return buffer;
7093
7247
  }
7094
7248
  bufferToFloatArray(buffer, dimensions) {
7095
- const arr = [];
7096
- for (let i58 = 0; i58 < dimensions; i58++) arr.push(buffer.readFloatLE(i58 * 4));
7097
- return arr;
7249
+ const f322 = new Float32Array(buffer.buffer, buffer.byteOffset, dimensions);
7250
+ return Array.from(f322);
7098
7251
  }
7099
7252
  };
7100
7253
  exitHandlersRegistered = false;
@@ -7105,45 +7258,45 @@ var init_unified_memory = __esm({
7105
7258
  // native-require:@xenova/transformers
7106
7259
  var transformers_exports = {};
7107
7260
  __export(transformers_exports, {
7108
- DotProductAttention: () => DotProductAttention2,
7109
- FlashAttention: () => FlashAttention2,
7110
- HyperbolicAttention: () => HyperbolicAttention2,
7111
- LinearAttention: () => LinearAttention2,
7112
- MoEAttention: () => MoEAttention2,
7113
- MultiHeadAttention: () => MultiHeadAttention2,
7114
- RuvectorLayer: () => RuvectorLayer2,
7115
- SonaEngine: () => SonaEngine2,
7116
- TensorCompress: () => TensorCompress2,
7261
+ DotProductAttention: () => DotProductAttention3,
7262
+ FlashAttention: () => FlashAttention3,
7263
+ HyperbolicAttention: () => HyperbolicAttention3,
7264
+ LinearAttention: () => LinearAttention3,
7265
+ MoEAttention: () => MoEAttention3,
7266
+ MultiHeadAttention: () => MultiHeadAttention3,
7267
+ RuvectorLayer: () => RuvectorLayer3,
7268
+ SonaEngine: () => SonaEngine3,
7269
+ TensorCompress: () => TensorCompress3,
7117
7270
  default: () => transformers_default,
7118
- differentiableSearch: () => differentiableSearch2,
7119
- getCompressionLevel: () => getCompressionLevel2,
7120
- hierarchicalForward: () => hierarchicalForward2,
7121
- init: () => init2,
7122
- pipeline: () => pipeline2
7271
+ differentiableSearch: () => differentiableSearch3,
7272
+ getCompressionLevel: () => getCompressionLevel3,
7273
+ hierarchicalForward: () => hierarchicalForward3,
7274
+ init: () => init3,
7275
+ pipeline: () => pipeline3
7123
7276
  });
7124
- import { createRequire as createRequire2 } from "module";
7125
- var __require3, __mod2, transformers_default, RuvectorLayer2, TensorCompress2, differentiableSearch2, hierarchicalForward2, getCompressionLevel2, init2, FlashAttention2, DotProductAttention2, MultiHeadAttention2, HyperbolicAttention2, LinearAttention2, MoEAttention2, SonaEngine2, pipeline2;
7277
+ import { createRequire as createRequire3 } from "module";
7278
+ var __require4, __mod3, transformers_default, RuvectorLayer3, TensorCompress3, differentiableSearch3, hierarchicalForward3, getCompressionLevel3, init3, FlashAttention3, DotProductAttention3, MultiHeadAttention3, HyperbolicAttention3, LinearAttention3, MoEAttention3, SonaEngine3, pipeline3;
7126
7279
  var init_transformers = __esm({
7127
7280
  "native-require:@xenova/transformers"() {
7128
- __require3 = createRequire2(import.meta.url);
7129
- __mod2 = __require3("@xenova/transformers");
7130
- transformers_default = __mod2;
7281
+ __require4 = createRequire3(import.meta.url);
7282
+ __mod3 = __require4("@xenova/transformers");
7283
+ transformers_default = __mod3;
7131
7284
  ({
7132
- RuvectorLayer: RuvectorLayer2,
7133
- TensorCompress: TensorCompress2,
7134
- differentiableSearch: differentiableSearch2,
7135
- hierarchicalForward: hierarchicalForward2,
7136
- getCompressionLevel: getCompressionLevel2,
7137
- init: init2,
7138
- FlashAttention: FlashAttention2,
7139
- DotProductAttention: DotProductAttention2,
7140
- MultiHeadAttention: MultiHeadAttention2,
7141
- HyperbolicAttention: HyperbolicAttention2,
7142
- LinearAttention: LinearAttention2,
7143
- MoEAttention: MoEAttention2,
7144
- SonaEngine: SonaEngine2,
7145
- pipeline: pipeline2
7146
- } = __mod2 || {});
7285
+ RuvectorLayer: RuvectorLayer3,
7286
+ TensorCompress: TensorCompress3,
7287
+ differentiableSearch: differentiableSearch3,
7288
+ hierarchicalForward: hierarchicalForward3,
7289
+ getCompressionLevel: getCompressionLevel3,
7290
+ init: init3,
7291
+ FlashAttention: FlashAttention3,
7292
+ DotProductAttention: DotProductAttention3,
7293
+ MultiHeadAttention: MultiHeadAttention3,
7294
+ HyperbolicAttention: HyperbolicAttention3,
7295
+ LinearAttention: LinearAttention3,
7296
+ MoEAttention: MoEAttention3,
7297
+ SonaEngine: SonaEngine3,
7298
+ pipeline: pipeline3
7299
+ } = __mod3 || {});
7147
7300
  }
7148
7301
  });
7149
7302
 
@@ -7171,10 +7324,10 @@ async function initializeModel(config = {}) {
7171
7324
  initPromise = (async () => {
7172
7325
  try {
7173
7326
  const transformers = await Promise.resolve().then(() => (init_transformers(), transformers_exports));
7174
- pipeline3 = transformers.pipeline;
7327
+ pipeline4 = transformers.pipeline;
7175
7328
  console.log(`[RealEmbeddings] Loading model: ${fullConfig.modelName}`);
7176
7329
  const startTime = performance.now();
7177
- embeddingModel = await pipeline3("feature-extraction", fullConfig.modelName, {
7330
+ embeddingModel = await pipeline4("feature-extraction", fullConfig.modelName, {
7178
7331
  quantized: fullConfig.quantized
7179
7332
  });
7180
7333
  const loadTime = performance.now() - startTime;
@@ -7292,20 +7445,20 @@ function getEmbeddingDimension() {
7292
7445
  return 384;
7293
7446
  }
7294
7447
  function resetInitialization() {
7295
- pipeline3 = null;
7448
+ pipeline4 = null;
7296
7449
  embeddingModel = null;
7297
7450
  initPromise = null;
7298
7451
  initializationFailed = false;
7299
7452
  failureReason = "";
7300
7453
  embeddingCache.clear();
7301
7454
  }
7302
- var pipeline3, embeddingModel, initPromise, initializationFailed, failureReason, DEFAULT_EMBEDDING_CONFIG, embeddingCache, CACHE_TTL_MS;
7455
+ var pipeline4, embeddingModel, initPromise, initializationFailed, failureReason, DEFAULT_EMBEDDING_CONFIG, embeddingCache, CACHE_TTL_MS;
7303
7456
  var init_real_embeddings = __esm({
7304
7457
  "src/learning/real-embeddings.ts"() {
7305
7458
  "use strict";
7306
7459
  init_vector_math();
7307
7460
  init_error_utils();
7308
- pipeline3 = null;
7461
+ pipeline4 = null;
7309
7462
  embeddingModel = null;
7310
7463
  initPromise = null;
7311
7464
  initializationFailed = false;
@@ -7526,6 +7679,105 @@ var init_unified_persistence = __esm({
7526
7679
  }
7527
7680
  });
7528
7681
 
7682
+ // src/learning/qe-patterns.ts
7683
+ function detectQEDomain(taskDescription) {
7684
+ for (const [domain, pattern] of Object.entries(QE_DOMAINS)) {
7685
+ if (pattern.test(taskDescription)) {
7686
+ return domain;
7687
+ }
7688
+ }
7689
+ return null;
7690
+ }
7691
+ function detectQEDomains(taskDescription) {
7692
+ const detected = [];
7693
+ for (const [domain, pattern] of Object.entries(QE_DOMAINS)) {
7694
+ if (pattern.test(taskDescription)) {
7695
+ detected.push(domain);
7696
+ }
7697
+ }
7698
+ return detected;
7699
+ }
7700
+ function mapQEDomainToAQE(qeDomain) {
7701
+ return qeDomain;
7702
+ }
7703
+ function calculateQualityScore(pattern) {
7704
+ const usageScore = Math.min(pattern.usageCount / 100, 1);
7705
+ return pattern.confidence * 0.3 + usageScore * 0.2 + pattern.successRate * 0.5;
7706
+ }
7707
+ function shouldPromotePattern(pattern, coherenceEnergy, coherenceThreshold = 0.4) {
7708
+ const meetsUsageCriteria = pattern.tier === "short-term" && pattern.successfulUses >= 3;
7709
+ const meetsQualityCriteria = pattern.successRate >= 0.7 && pattern.confidence >= 0.6;
7710
+ const meetsCoherenceCriteria = coherenceEnergy === void 0 || coherenceEnergy < coherenceThreshold;
7711
+ let blockReason;
7712
+ if (!meetsUsageCriteria) {
7713
+ blockReason = "insufficient_usage";
7714
+ } else if (!meetsQualityCriteria) {
7715
+ blockReason = "low_quality";
7716
+ } else if (!meetsCoherenceCriteria) {
7717
+ blockReason = "coherence_violation";
7718
+ }
7719
+ return {
7720
+ meetsUsageCriteria,
7721
+ meetsQualityCriteria,
7722
+ meetsCoherenceCriteria,
7723
+ blockReason
7724
+ };
7725
+ }
7726
+ function validateQEPattern(pattern) {
7727
+ const errors = [];
7728
+ if (!pattern.id) errors.push("Pattern ID is required");
7729
+ if (!pattern.patternType) errors.push("Pattern type is required");
7730
+ if (!pattern.qeDomain) errors.push("QE domain is required");
7731
+ if (!pattern.name) errors.push("Pattern name is required");
7732
+ if (!pattern.template?.content) errors.push("Template content is required");
7733
+ if (pattern.confidence !== void 0 && (pattern.confidence < 0 || pattern.confidence > 1)) {
7734
+ errors.push("Confidence must be between 0 and 1");
7735
+ }
7736
+ if (pattern.successRate !== void 0 && (pattern.successRate < 0 || pattern.successRate > 1)) {
7737
+ errors.push("Success rate must be between 0 and 1");
7738
+ }
7739
+ if (pattern.template?.variables) {
7740
+ const variableNames = /* @__PURE__ */ new Set();
7741
+ for (const variable of pattern.template.variables) {
7742
+ if (variableNames.has(variable.name)) {
7743
+ errors.push(`Duplicate variable name: ${variable.name}`);
7744
+ }
7745
+ variableNames.add(variable.name);
7746
+ if (!pattern.template.content.includes(`{{${variable.name}}}`)) {
7747
+ errors.push(
7748
+ `Variable ${variable.name} not referenced in template`
7749
+ );
7750
+ }
7751
+ }
7752
+ }
7753
+ return { valid: errors.length === 0, errors };
7754
+ }
7755
+ var QE_DOMAINS, QE_DOMAIN_LIST;
7756
+ var init_qe_patterns = __esm({
7757
+ "src/learning/qe-patterns.ts"() {
7758
+ "use strict";
7759
+ QE_DOMAINS = {
7760
+ // Core Testing Domains
7761
+ "test-generation": /test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,
7762
+ "test-execution": /run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,
7763
+ "coverage-analysis": /coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,
7764
+ // Quality Domains
7765
+ "quality-assessment": /quality|gate|deploy|readiness|metric|threshold|sla|score/i,
7766
+ "defect-intelligence": /defect|bug|predict|root.?cause|regression|failure|incident/i,
7767
+ "requirements-validation": /requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,
7768
+ // Analysis Domains
7769
+ "code-intelligence": /semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,
7770
+ "security-compliance": /vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,
7771
+ "contract-testing": /contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,
7772
+ // Specialized Testing Domains
7773
+ "visual-accessibility": /screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,
7774
+ "chaos-resilience": /chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,
7775
+ "learning-optimization": /learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i
7776
+ };
7777
+ QE_DOMAIN_LIST = Object.keys(QE_DOMAINS);
7778
+ }
7779
+ });
7780
+
7529
7781
  // src/coordination/consensus/model-provider.ts
7530
7782
  function buildVerificationPrompt(finding, options = {}) {
7531
7783
  const {
@@ -9354,45 +9606,45 @@ Format your response with: verdict (confirmed/rejected/uncertain), confidence (0
9354
9606
  // native-require:@ruvector/sona
9355
9607
  var sona_exports = {};
9356
9608
  __export(sona_exports, {
9357
- DotProductAttention: () => DotProductAttention3,
9358
- FlashAttention: () => FlashAttention3,
9359
- HyperbolicAttention: () => HyperbolicAttention3,
9360
- LinearAttention: () => LinearAttention3,
9361
- MoEAttention: () => MoEAttention3,
9362
- MultiHeadAttention: () => MultiHeadAttention3,
9363
- RuvectorLayer: () => RuvectorLayer3,
9364
- SonaEngine: () => SonaEngine3,
9365
- TensorCompress: () => TensorCompress3,
9609
+ DotProductAttention: () => DotProductAttention4,
9610
+ FlashAttention: () => FlashAttention4,
9611
+ HyperbolicAttention: () => HyperbolicAttention4,
9612
+ LinearAttention: () => LinearAttention4,
9613
+ MoEAttention: () => MoEAttention4,
9614
+ MultiHeadAttention: () => MultiHeadAttention4,
9615
+ RuvectorLayer: () => RuvectorLayer4,
9616
+ SonaEngine: () => SonaEngine4,
9617
+ TensorCompress: () => TensorCompress4,
9366
9618
  default: () => sona_default,
9367
- differentiableSearch: () => differentiableSearch3,
9368
- getCompressionLevel: () => getCompressionLevel3,
9369
- hierarchicalForward: () => hierarchicalForward3,
9370
- init: () => init3,
9371
- pipeline: () => pipeline4
9619
+ differentiableSearch: () => differentiableSearch4,
9620
+ getCompressionLevel: () => getCompressionLevel4,
9621
+ hierarchicalForward: () => hierarchicalForward4,
9622
+ init: () => init4,
9623
+ pipeline: () => pipeline5
9372
9624
  });
9373
- import { createRequire as createRequire3 } from "module";
9374
- var __require4, __mod3, sona_default, RuvectorLayer3, TensorCompress3, differentiableSearch3, hierarchicalForward3, getCompressionLevel3, init3, FlashAttention3, DotProductAttention3, MultiHeadAttention3, HyperbolicAttention3, LinearAttention3, MoEAttention3, SonaEngine3, pipeline4;
9625
+ import { createRequire as createRequire4 } from "module";
9626
+ var __require5, __mod4, sona_default, RuvectorLayer4, TensorCompress4, differentiableSearch4, hierarchicalForward4, getCompressionLevel4, init4, FlashAttention4, DotProductAttention4, MultiHeadAttention4, HyperbolicAttention4, LinearAttention4, MoEAttention4, SonaEngine4, pipeline5;
9375
9627
  var init_sona = __esm({
9376
9628
  "native-require:@ruvector/sona"() {
9377
- __require4 = createRequire3(import.meta.url);
9378
- __mod3 = __require4("@ruvector/sona");
9379
- sona_default = __mod3;
9629
+ __require5 = createRequire4(import.meta.url);
9630
+ __mod4 = __require5("@ruvector/sona");
9631
+ sona_default = __mod4;
9380
9632
  ({
9381
- RuvectorLayer: RuvectorLayer3,
9382
- TensorCompress: TensorCompress3,
9383
- differentiableSearch: differentiableSearch3,
9384
- hierarchicalForward: hierarchicalForward3,
9385
- getCompressionLevel: getCompressionLevel3,
9386
- init: init3,
9387
- FlashAttention: FlashAttention3,
9388
- DotProductAttention: DotProductAttention3,
9389
- MultiHeadAttention: MultiHeadAttention3,
9390
- HyperbolicAttention: HyperbolicAttention3,
9391
- LinearAttention: LinearAttention3,
9392
- MoEAttention: MoEAttention3,
9393
- SonaEngine: SonaEngine3,
9394
- pipeline: pipeline4
9395
- } = __mod3 || {});
9633
+ RuvectorLayer: RuvectorLayer4,
9634
+ TensorCompress: TensorCompress4,
9635
+ differentiableSearch: differentiableSearch4,
9636
+ hierarchicalForward: hierarchicalForward4,
9637
+ getCompressionLevel: getCompressionLevel4,
9638
+ init: init4,
9639
+ FlashAttention: FlashAttention4,
9640
+ DotProductAttention: DotProductAttention4,
9641
+ MultiHeadAttention: MultiHeadAttention4,
9642
+ HyperbolicAttention: HyperbolicAttention4,
9643
+ LinearAttention: LinearAttention4,
9644
+ MoEAttention: MoEAttention4,
9645
+ SonaEngine: SonaEngine4,
9646
+ pipeline: pipeline5
9647
+ } = __mod4 || {});
9396
9648
  }
9397
9649
  });
9398
9650
 
@@ -9534,7 +9786,7 @@ var init_sona_wrapper = __esm({
9534
9786
  qualityThreshold: this.config.qualityThreshold,
9535
9787
  enableSimd: this.config.enableSimd
9536
9788
  };
9537
- this.engine = SonaEngine3.withConfig(jsConfig);
9789
+ this.engine = SonaEngine4.withConfig(jsConfig);
9538
9790
  this.registry = new QESONAPatternRegistry(this.config.maxPatterns ?? 1e4);
9539
9791
  }
9540
9792
  /**
@@ -9963,45 +10215,45 @@ var init_sona_wrapper = __esm({
9963
10215
  // native-require:@ruvector/attention
9964
10216
  var attention_exports = {};
9965
10217
  __export(attention_exports, {
9966
- DotProductAttention: () => DotProductAttention4,
9967
- FlashAttention: () => FlashAttention4,
9968
- HyperbolicAttention: () => HyperbolicAttention4,
9969
- LinearAttention: () => LinearAttention4,
9970
- MoEAttention: () => MoEAttention4,
9971
- MultiHeadAttention: () => MultiHeadAttention4,
9972
- RuvectorLayer: () => RuvectorLayer4,
9973
- SonaEngine: () => SonaEngine4,
9974
- TensorCompress: () => TensorCompress4,
10218
+ DotProductAttention: () => DotProductAttention5,
10219
+ FlashAttention: () => FlashAttention5,
10220
+ HyperbolicAttention: () => HyperbolicAttention5,
10221
+ LinearAttention: () => LinearAttention5,
10222
+ MoEAttention: () => MoEAttention5,
10223
+ MultiHeadAttention: () => MultiHeadAttention5,
10224
+ RuvectorLayer: () => RuvectorLayer5,
10225
+ SonaEngine: () => SonaEngine5,
10226
+ TensorCompress: () => TensorCompress5,
9975
10227
  default: () => attention_default,
9976
- differentiableSearch: () => differentiableSearch4,
9977
- getCompressionLevel: () => getCompressionLevel4,
9978
- hierarchicalForward: () => hierarchicalForward4,
9979
- init: () => init4,
9980
- pipeline: () => pipeline5
10228
+ differentiableSearch: () => differentiableSearch5,
10229
+ getCompressionLevel: () => getCompressionLevel5,
10230
+ hierarchicalForward: () => hierarchicalForward5,
10231
+ init: () => init5,
10232
+ pipeline: () => pipeline6
9981
10233
  });
9982
- import { createRequire as createRequire4 } from "module";
9983
- var __require5, __mod4, attention_default, RuvectorLayer4, TensorCompress4, differentiableSearch4, hierarchicalForward4, getCompressionLevel4, init4, FlashAttention4, DotProductAttention4, MultiHeadAttention4, HyperbolicAttention4, LinearAttention4, MoEAttention4, SonaEngine4, pipeline5;
10234
+ import { createRequire as createRequire5 } from "module";
10235
+ var __require6, __mod5, attention_default, RuvectorLayer5, TensorCompress5, differentiableSearch5, hierarchicalForward5, getCompressionLevel5, init5, FlashAttention5, DotProductAttention5, MultiHeadAttention5, HyperbolicAttention5, LinearAttention5, MoEAttention5, SonaEngine5, pipeline6;
9984
10236
  var init_attention = __esm({
9985
10237
  "native-require:@ruvector/attention"() {
9986
- __require5 = createRequire4(import.meta.url);
9987
- __mod4 = __require5("@ruvector/attention");
9988
- attention_default = __mod4;
10238
+ __require6 = createRequire5(import.meta.url);
10239
+ __mod5 = __require6("@ruvector/attention");
10240
+ attention_default = __mod5;
9989
10241
  ({
9990
- RuvectorLayer: RuvectorLayer4,
9991
- TensorCompress: TensorCompress4,
9992
- differentiableSearch: differentiableSearch4,
9993
- hierarchicalForward: hierarchicalForward4,
9994
- getCompressionLevel: getCompressionLevel4,
9995
- init: init4,
9996
- FlashAttention: FlashAttention4,
9997
- DotProductAttention: DotProductAttention4,
9998
- MultiHeadAttention: MultiHeadAttention4,
9999
- HyperbolicAttention: HyperbolicAttention4,
10000
- LinearAttention: LinearAttention4,
10001
- MoEAttention: MoEAttention4,
10002
- SonaEngine: SonaEngine4,
10003
- pipeline: pipeline5
10004
- } = __mod4 || {});
10242
+ RuvectorLayer: RuvectorLayer5,
10243
+ TensorCompress: TensorCompress5,
10244
+ differentiableSearch: differentiableSearch5,
10245
+ hierarchicalForward: hierarchicalForward5,
10246
+ getCompressionLevel: getCompressionLevel5,
10247
+ init: init5,
10248
+ FlashAttention: FlashAttention5,
10249
+ DotProductAttention: DotProductAttention5,
10250
+ MultiHeadAttention: MultiHeadAttention5,
10251
+ HyperbolicAttention: HyperbolicAttention5,
10252
+ LinearAttention: LinearAttention5,
10253
+ MoEAttention: MoEAttention5,
10254
+ SonaEngine: SonaEngine5,
10255
+ pipeline: pipeline6
10256
+ } = __mod5 || {});
10005
10257
  }
10006
10258
  });
10007
10259
 
@@ -10159,23 +10411,23 @@ var init_attention_wrapper = __esm({
10159
10411
  static create(config) {
10160
10412
  switch (config.strategy) {
10161
10413
  case "flash":
10162
- return new FlashAttention4(config.dim, config.blockSize);
10414
+ return new FlashAttention5(config.dim, config.blockSize);
10163
10415
  case "dot-product":
10164
- return new DotProductAttention4(config.dim);
10416
+ return new DotProductAttention5(config.dim);
10165
10417
  case "multi-head":
10166
- return new MultiHeadAttention4(config.dim, config.numHeads ?? 8);
10418
+ return new MultiHeadAttention5(config.dim, config.numHeads ?? 8);
10167
10419
  case "hyperbolic":
10168
- return new HyperbolicAttention4(config.dim, config.curvature);
10420
+ return new HyperbolicAttention5(config.dim, config.curvature);
10169
10421
  case "linear":
10170
- return new LinearAttention4(config.dim, config.features);
10422
+ return new LinearAttention5(config.dim, config.features);
10171
10423
  case "moe":
10172
- return MoEAttention4.simple(
10424
+ return MoEAttention5.simple(
10173
10425
  config.dim,
10174
10426
  config.moeConfig?.numExperts ?? 8,
10175
10427
  config.moeConfig?.topK ?? 2
10176
10428
  );
10177
10429
  default:
10178
- return new FlashAttention4(config.dim, config.blockSize);
10430
+ return new FlashAttention5(config.dim, config.blockSize);
10179
10431
  }
10180
10432
  }
10181
10433
  };
@@ -10232,20 +10484,20 @@ var init_attention_wrapper = __esm({
10232
10484
  const keys = this.splitMatrix(K58, seqLen, dim);
10233
10485
  const values = this.splitMatrix(V45, seqLen, dim);
10234
10486
  let output;
10235
- if (this.attention instanceof FlashAttention4) {
10487
+ if (this.attention instanceof FlashAttention5) {
10236
10488
  output = this.attention.compute(query, keys, values);
10237
- } else if (this.attention instanceof DotProductAttention4) {
10489
+ } else if (this.attention instanceof DotProductAttention5) {
10238
10490
  output = this.attention.compute(query, keys, values);
10239
- } else if (this.attention instanceof MultiHeadAttention4) {
10491
+ } else if (this.attention instanceof MultiHeadAttention5) {
10240
10492
  output = this.attention.compute(query, keys, values);
10241
- } else if (this.attention instanceof HyperbolicAttention4) {
10493
+ } else if (this.attention instanceof HyperbolicAttention5) {
10242
10494
  output = this.attention.compute(query, keys, values);
10243
- } else if (this.attention instanceof LinearAttention4) {
10495
+ } else if (this.attention instanceof LinearAttention5) {
10244
10496
  output = this.attention.compute(query, keys, values);
10245
- } else if (this.attention instanceof MoEAttention4) {
10497
+ } else if (this.attention instanceof MoEAttention5) {
10246
10498
  output = this.attention.compute(query, keys, values);
10247
10499
  } else {
10248
- const fallback = new FlashAttention4(this.config.dim);
10500
+ const fallback = new FlashAttention5(this.config.dim);
10249
10501
  output = fallback.compute(query, keys, values);
10250
10502
  }
10251
10503
  const endTime = performance.now();
@@ -10490,65 +10742,20 @@ var init_attention_wrapper = __esm({
10490
10742
  }
10491
10743
  });
10492
10744
 
10493
- // native-require:@ruvector/gnn
10494
- var gnn_exports = {};
10495
- __export(gnn_exports, {
10496
- DotProductAttention: () => DotProductAttention5,
10497
- FlashAttention: () => FlashAttention5,
10498
- HyperbolicAttention: () => HyperbolicAttention5,
10499
- LinearAttention: () => LinearAttention5,
10500
- MoEAttention: () => MoEAttention5,
10501
- MultiHeadAttention: () => MultiHeadAttention5,
10502
- RuvectorLayer: () => RuvectorLayer5,
10503
- SonaEngine: () => SonaEngine5,
10504
- TensorCompress: () => TensorCompress5,
10505
- default: () => gnn_default,
10506
- differentiableSearch: () => differentiableSearch5,
10507
- getCompressionLevel: () => getCompressionLevel5,
10508
- hierarchicalForward: () => hierarchicalForward5,
10509
- init: () => init5,
10510
- pipeline: () => pipeline6
10511
- });
10512
- import { createRequire as createRequire5 } from "module";
10513
- var __require6, __mod5, gnn_default, RuvectorLayer5, TensorCompress5, differentiableSearch5, hierarchicalForward5, getCompressionLevel5, init5, FlashAttention5, DotProductAttention5, MultiHeadAttention5, HyperbolicAttention5, LinearAttention5, MoEAttention5, SonaEngine5, pipeline6;
10514
- var init_gnn = __esm({
10515
- "native-require:@ruvector/gnn"() {
10516
- __require6 = createRequire5(import.meta.url);
10517
- __mod5 = __require6("@ruvector/gnn");
10518
- gnn_default = __mod5;
10519
- ({
10520
- RuvectorLayer: RuvectorLayer5,
10521
- TensorCompress: TensorCompress5,
10522
- differentiableSearch: differentiableSearch5,
10523
- hierarchicalForward: hierarchicalForward5,
10524
- getCompressionLevel: getCompressionLevel5,
10525
- init: init5,
10526
- FlashAttention: FlashAttention5,
10527
- DotProductAttention: DotProductAttention5,
10528
- MultiHeadAttention: MultiHeadAttention5,
10529
- HyperbolicAttention: HyperbolicAttention5,
10530
- LinearAttention: LinearAttention5,
10531
- MoEAttention: MoEAttention5,
10532
- SonaEngine: SonaEngine5,
10533
- pipeline: pipeline6
10534
- } = __mod5 || {});
10535
- }
10536
- });
10537
-
10538
10745
  // src/integrations/ruvector/gnn-wrapper.ts
10539
10746
  var gnn_wrapper_exports = {};
10540
10747
  __export(gnn_wrapper_exports, {
10541
10748
  GNNLayerFactory: () => GNNLayerFactory,
10542
10749
  QEGNNEmbeddingIndex: () => QEGNNEmbeddingIndex,
10543
10750
  QEGNNIndexFactory: () => QEGNNIndexFactory,
10544
- RuvectorLayer: () => RuvectorLayer5,
10545
- TensorCompress: () => TensorCompress5,
10751
+ RuvectorLayer: () => RuvectorLayer2,
10752
+ TensorCompress: () => TensorCompress2,
10546
10753
  TensorCompressionFactory: () => TensorCompressionFactory,
10547
10754
  batchDifferentiableSearch: () => batchDifferentiableSearch,
10548
- differentiableSearch: () => differentiableSearch5,
10549
- getCompressionLevel: () => getCompressionLevel5,
10550
- hierarchicalForward: () => hierarchicalForward5,
10551
- init: () => init5,
10755
+ differentiableSearch: () => differentiableSearch2,
10756
+ getCompressionLevel: () => getCompressionLevel2,
10757
+ hierarchicalForward: () => hierarchicalForward2,
10758
+ init: () => init2,
10552
10759
  initGNN: () => initGNN,
10553
10760
  toFloat32Array: () => toFloat32Array2,
10554
10761
  toIEmbedding: () => toIEmbedding,
@@ -10556,7 +10763,7 @@ __export(gnn_wrapper_exports, {
10556
10763
  });
10557
10764
  function initGNN() {
10558
10765
  if (!gnnInitialized) {
10559
- const result = init5();
10766
+ const result = init2();
10560
10767
  gnnInitialized = true;
10561
10768
  return result;
10562
10769
  }
@@ -10597,7 +10804,7 @@ function batchDifferentiableSearch(queries, candidateEmbeddings, k68, temperatur
10597
10804
  );
10598
10805
  for (const query of queries) {
10599
10806
  const queryFloat32 = query instanceof Float32Array ? query : new Float32Array(query);
10600
- const result = differentiableSearch5(
10807
+ const result = differentiableSearch2(
10601
10808
  queryFloat32,
10602
10809
  candidatesFloat32,
10603
10810
  k68,
@@ -10635,7 +10842,7 @@ var init_gnn_wrapper = __esm({
10635
10842
  this.indexes = /* @__PURE__ */ new Map();
10636
10843
  this.nextId = /* @__PURE__ */ new Map();
10637
10844
  this.gnnLayers = /* @__PURE__ */ new Map();
10638
- this.compressor = new TensorCompress5();
10845
+ this.compressor = new TensorCompress2();
10639
10846
  initGNN();
10640
10847
  }
10641
10848
  /**
@@ -10696,7 +10903,7 @@ var init_gnn_wrapper = __esm({
10696
10903
  }
10697
10904
  const queryFloat32 = new Float32Array(query.vector);
10698
10905
  const candidateFloat32s = candidates.map((c70) => new Float32Array(c70.vector));
10699
- const result = differentiableSearch5(
10906
+ const result = differentiableSearch2(
10700
10907
  queryFloat32,
10701
10908
  candidateFloat32s,
10702
10909
  Math.min(k68, candidates.length),
@@ -10719,7 +10926,7 @@ var init_gnn_wrapper = __esm({
10719
10926
  const candidateVectors = candidates.map(
10720
10927
  (c70) => new Float32Array(c70.embedding.vector)
10721
10928
  );
10722
- const result = differentiableSearch5(
10929
+ const result = differentiableSearch2(
10723
10930
  queryVector,
10724
10931
  candidateVectors,
10725
10932
  Math.min(k68, candidates.length),
@@ -10740,7 +10947,7 @@ var init_gnn_wrapper = __esm({
10740
10947
  if (!this.gnnLayers.has(layerKey)) {
10741
10948
  const layers = [];
10742
10949
  for (const config of layerConfigs) {
10743
- const layer2 = new RuvectorLayer5(
10950
+ const layer2 = new RuvectorLayer2(
10744
10951
  config.inputDim,
10745
10952
  config.hiddenDim,
10746
10953
  config.heads,
@@ -10756,7 +10963,7 @@ var init_gnn_wrapper = __esm({
10756
10963
  const layerEmbeddingsFloat32 = layerEmbeddings.map(
10757
10964
  (layer2) => layer2.map((emb) => new Float32Array(emb))
10758
10965
  );
10759
- return Array.from(hierarchicalForward5(
10966
+ return Array.from(hierarchicalForward2(
10760
10967
  queryFloat32,
10761
10968
  layerEmbeddingsFloat32,
10762
10969
  [gnnLayerJson]
@@ -10771,7 +10978,7 @@ var init_gnn_wrapper = __esm({
10771
10978
  * - Cold data (low access): product quantization
10772
10979
  */
10773
10980
  compressEmbedding(embedding, accessFreq) {
10774
- const rawLevel = getCompressionLevel5(accessFreq);
10981
+ const rawLevel = getCompressionLevel2(accessFreq);
10775
10982
  const levelMap = {
10776
10983
  "none": "none",
10777
10984
  "half": "half",
@@ -10817,7 +11024,7 @@ var init_gnn_wrapper = __esm({
10817
11024
  * Get compression level for access frequency
10818
11025
  */
10819
11026
  getCompressionLevelForFrequency(accessFreq) {
10820
- return getCompressionLevel5(accessFreq);
11027
+ return getCompressionLevel2(accessFreq);
10821
11028
  }
10822
11029
  /**
10823
11030
  * Get index statistics
@@ -10961,7 +11168,7 @@ var init_gnn_wrapper = __esm({
10961
11168
  static getLayer(config) {
10962
11169
  const key = `${config.inputDim}-${config.hiddenDim}-${config.heads}-${config.dropout}`;
10963
11170
  if (!this.layers.has(key)) {
10964
- const layer = new RuvectorLayer5(
11171
+ const layer = new RuvectorLayer2(
10965
11172
  config.inputDim,
10966
11173
  config.hiddenDim,
10967
11174
  config.heads,
@@ -10975,7 +11182,7 @@ var init_gnn_wrapper = __esm({
10975
11182
  * Create layer from JSON
10976
11183
  */
10977
11184
  static layerFromJson(json) {
10978
- return RuvectorLayer5.fromJson(json);
11185
+ return RuvectorLayer2.fromJson(json);
10979
11186
  }
10980
11187
  /**
10981
11188
  * Clear cached layers
@@ -10985,7 +11192,7 @@ var init_gnn_wrapper = __esm({
10985
11192
  }
10986
11193
  };
10987
11194
  TensorCompressionFactory = class {
10988
- static compressor = new TensorCompress5();
11195
+ static compressor = new TensorCompress2();
10989
11196
  /**
10990
11197
  * Compress tensor with specific level
10991
11198
  */
@@ -11011,7 +11218,7 @@ var init_gnn_wrapper = __esm({
11011
11218
  * Get compression level for frequency
11012
11219
  */
11013
11220
  static getLevel(accessFreq) {
11014
- return getCompressionLevel5(accessFreq);
11221
+ return getCompressionLevel2(accessFreq);
11015
11222
  }
11016
11223
  };
11017
11224
  }
@@ -11028,14 +11235,14 @@ __export(wrappers_exports, {
11028
11235
  QE_FLASH_ATTENTION_CONFIG: () => QE_FLASH_ATTENTION_CONFIG,
11029
11236
  QE_PERFORMANCE_TARGETS: () => QE_PERFORMANCE_TARGETS,
11030
11237
  QE_SONA_CONFIG: () => QE_SONA_CONFIG,
11031
- RuvectorDotProductAttention: () => DotProductAttention4,
11032
- RuvectorFlashAttention: () => FlashAttention4,
11033
- RuvectorHyperbolicAttention: () => HyperbolicAttention4,
11034
- RuvectorLayer: () => RuvectorLayer5,
11035
- RuvectorLinearAttention: () => LinearAttention4,
11036
- RuvectorMoEAttention: () => MoEAttention4,
11037
- RuvectorMultiHeadAttention: () => MultiHeadAttention4,
11038
- TensorCompress: () => TensorCompress5,
11238
+ RuvectorDotProductAttention: () => DotProductAttention5,
11239
+ RuvectorFlashAttention: () => FlashAttention5,
11240
+ RuvectorHyperbolicAttention: () => HyperbolicAttention5,
11241
+ RuvectorLayer: () => RuvectorLayer2,
11242
+ RuvectorLinearAttention: () => LinearAttention5,
11243
+ RuvectorMoEAttention: () => MoEAttention5,
11244
+ RuvectorMultiHeadAttention: () => MultiHeadAttention5,
11245
+ TensorCompress: () => TensorCompress2,
11039
11246
  TensorCompressionFactory: () => TensorCompressionFactory,
11040
11247
  batchComputeAttention: () => batchComputeAttention,
11041
11248
  batchDifferentiableSearch: () => batchDifferentiableSearch,
@@ -11043,14 +11250,14 @@ __export(wrappers_exports, {
11043
11250
  createDomainQESONA: () => createDomainQESONA,
11044
11251
  createQEFlashAttention: () => createQEFlashAttention,
11045
11252
  createQESONA: () => createQESONA,
11046
- differentiableSearch: () => differentiableSearch5,
11047
- getCompressionLevel: () => getCompressionLevel5,
11253
+ differentiableSearch: () => differentiableSearch2,
11254
+ getCompressionLevel: () => getCompressionLevel2,
11048
11255
  getOptimalBlockConfig: () => getOptimalBlockConfig,
11049
11256
  getQEFlashAttentionConfig: () => getQEFlashAttentionConfig,
11050
11257
  getRuvectorPackageVersions: () => getRuvectorPackageVersions,
11051
11258
  getWorkloadTypes: () => getWorkloadTypes,
11052
- hierarchicalForward: () => hierarchicalForward5,
11053
- init: () => init5,
11259
+ hierarchicalForward: () => hierarchicalForward2,
11260
+ init: () => init2,
11054
11261
  initAllRuvectorPackages: () => initAllRuvectorPackages,
11055
11262
  initGNN: () => initGNN,
11056
11263
  toFloat32Array: () => toFloat32Array,
@@ -11254,7 +11461,7 @@ var init_hnsw_index = __esm({
11254
11461
  if (!this.initialized) {
11255
11462
  await this.initialize();
11256
11463
  }
11257
- this.validateVector(vector);
11464
+ vector = this.validateVector(vector);
11258
11465
  if (this.keyToLabel.has(key)) {
11259
11466
  await this.delete(key);
11260
11467
  }
@@ -11283,7 +11490,7 @@ var init_hnsw_index = __esm({
11283
11490
  if (!this.initialized) {
11284
11491
  await this.initialize();
11285
11492
  }
11286
- this.validateVector(query);
11493
+ query = this.validateVector(query);
11287
11494
  const startTime = performance.now();
11288
11495
  const results = this.stats.vectorCount > 0 ? this.searchRuvector(query, k68) : [];
11289
11496
  const endTime = performance.now();
@@ -11408,17 +11615,46 @@ var init_hnsw_index = __esm({
11408
11615
  // ============================================================================
11409
11616
  // Private Helper Methods
11410
11617
  // ============================================================================
11618
+ /**
11619
+ * Validate and auto-resize vectors to match HNSW configured dimensions.
11620
+ * Fix #279: Prevents Rust WASM panic when RealEmbeddings (768-dim) are
11621
+ * passed to a 128-dim HNSW index.
11622
+ */
11411
11623
  validateVector(vector) {
11412
11624
  if (vector.length !== this.config.dimensions) {
11413
- throw new Error(
11414
- `Vector dimension mismatch: expected ${this.config.dimensions}, got ${vector.length}`
11415
- );
11625
+ return this.resizeVector(vector, this.config.dimensions);
11416
11626
  }
11417
11627
  for (let i58 = 0; i58 < vector.length; i58++) {
11418
11628
  if (!Number.isFinite(vector[i58])) {
11419
11629
  throw new Error(`Invalid vector value at index ${i58}: ${vector[i58]}`);
11420
11630
  }
11421
11631
  }
11632
+ return vector;
11633
+ }
11634
+ /**
11635
+ * Resize vector to target dimensions using averaging (shrink) or zero-padding (grow).
11636
+ */
11637
+ resizeVector(vector, targetDim) {
11638
+ if (vector.length === targetDim) return vector;
11639
+ if (vector.length > targetDim) {
11640
+ const result2 = new Array(targetDim).fill(0);
11641
+ const ratio = vector.length / targetDim;
11642
+ for (let i58 = 0; i58 < targetDim; i58++) {
11643
+ const start = Math.floor(i58 * ratio);
11644
+ const end = Math.floor((i58 + 1) * ratio);
11645
+ let sum = 0;
11646
+ for (let j52 = start; j52 < end; j52++) {
11647
+ sum += vector[j52];
11648
+ }
11649
+ result2[i58] = sum / (end - start);
11650
+ }
11651
+ return result2;
11652
+ }
11653
+ const result = new Array(targetDim).fill(0);
11654
+ for (let i58 = 0; i58 < vector.length; i58++) {
11655
+ result[i58] = vector[i58];
11656
+ }
11657
+ return result;
11422
11658
  }
11423
11659
  buildKey(key) {
11424
11660
  return `${this.config.namespace}:${key}`;
@@ -14209,105 +14445,6 @@ var init_dream = __esm({
14209
14445
  }
14210
14446
  });
14211
14447
 
14212
- // src/learning/qe-patterns.ts
14213
- function detectQEDomain(taskDescription) {
14214
- for (const [domain, pattern] of Object.entries(QE_DOMAINS)) {
14215
- if (pattern.test(taskDescription)) {
14216
- return domain;
14217
- }
14218
- }
14219
- return null;
14220
- }
14221
- function detectQEDomains(taskDescription) {
14222
- const detected = [];
14223
- for (const [domain, pattern] of Object.entries(QE_DOMAINS)) {
14224
- if (pattern.test(taskDescription)) {
14225
- detected.push(domain);
14226
- }
14227
- }
14228
- return detected;
14229
- }
14230
- function mapQEDomainToAQE(qeDomain) {
14231
- return qeDomain;
14232
- }
14233
- function calculateQualityScore(pattern) {
14234
- const usageScore = Math.min(pattern.usageCount / 100, 1);
14235
- return pattern.confidence * 0.3 + usageScore * 0.2 + pattern.successRate * 0.5;
14236
- }
14237
- function shouldPromotePattern(pattern, coherenceEnergy, coherenceThreshold = 0.4) {
14238
- const meetsUsageCriteria = pattern.tier === "short-term" && pattern.successfulUses >= 3;
14239
- const meetsQualityCriteria = pattern.successRate >= 0.7 && pattern.confidence >= 0.6;
14240
- const meetsCoherenceCriteria = coherenceEnergy === void 0 || coherenceEnergy < coherenceThreshold;
14241
- let blockReason;
14242
- if (!meetsUsageCriteria) {
14243
- blockReason = "insufficient_usage";
14244
- } else if (!meetsQualityCriteria) {
14245
- blockReason = "low_quality";
14246
- } else if (!meetsCoherenceCriteria) {
14247
- blockReason = "coherence_violation";
14248
- }
14249
- return {
14250
- meetsUsageCriteria,
14251
- meetsQualityCriteria,
14252
- meetsCoherenceCriteria,
14253
- blockReason
14254
- };
14255
- }
14256
- function validateQEPattern(pattern) {
14257
- const errors = [];
14258
- if (!pattern.id) errors.push("Pattern ID is required");
14259
- if (!pattern.patternType) errors.push("Pattern type is required");
14260
- if (!pattern.qeDomain) errors.push("QE domain is required");
14261
- if (!pattern.name) errors.push("Pattern name is required");
14262
- if (!pattern.template?.content) errors.push("Template content is required");
14263
- if (pattern.confidence !== void 0 && (pattern.confidence < 0 || pattern.confidence > 1)) {
14264
- errors.push("Confidence must be between 0 and 1");
14265
- }
14266
- if (pattern.successRate !== void 0 && (pattern.successRate < 0 || pattern.successRate > 1)) {
14267
- errors.push("Success rate must be between 0 and 1");
14268
- }
14269
- if (pattern.template?.variables) {
14270
- const variableNames = /* @__PURE__ */ new Set();
14271
- for (const variable of pattern.template.variables) {
14272
- if (variableNames.has(variable.name)) {
14273
- errors.push(`Duplicate variable name: ${variable.name}`);
14274
- }
14275
- variableNames.add(variable.name);
14276
- if (!pattern.template.content.includes(`{{${variable.name}}}`)) {
14277
- errors.push(
14278
- `Variable ${variable.name} not referenced in template`
14279
- );
14280
- }
14281
- }
14282
- }
14283
- return { valid: errors.length === 0, errors };
14284
- }
14285
- var QE_DOMAINS, QE_DOMAIN_LIST;
14286
- var init_qe_patterns = __esm({
14287
- "src/learning/qe-patterns.ts"() {
14288
- "use strict";
14289
- QE_DOMAINS = {
14290
- // Core Testing Domains
14291
- "test-generation": /test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,
14292
- "test-execution": /run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,
14293
- "coverage-analysis": /coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,
14294
- // Quality Domains
14295
- "quality-assessment": /quality|gate|deploy|readiness|metric|threshold|sla|score/i,
14296
- "defect-intelligence": /defect|bug|predict|root.?cause|regression|failure|incident/i,
14297
- "requirements-validation": /requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,
14298
- // Analysis Domains
14299
- "code-intelligence": /semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,
14300
- "security-compliance": /vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,
14301
- "contract-testing": /contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,
14302
- // Specialized Testing Domains
14303
- "visual-accessibility": /screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,
14304
- "chaos-resilience": /chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,
14305
- "learning-optimization": /learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i
14306
- };
14307
- QE_DOMAIN_LIST = Object.keys(QE_DOMAINS);
14308
- }
14309
- });
14310
-
14311
14448
  // src/integrations/agentic-flow/agent-booster/types.ts
14312
14449
  var ALL_TRANSFORM_TYPES, TRANSFORM_METADATA, DEFAULT_AGENT_BOOSTER_CONFIG, AgentBoosterError, TransformError, WasmUnavailableError, TransformTimeoutError, FileTooLargeError;
14313
14450
  var init_types4 = __esm({
@@ -17688,7 +17825,13 @@ var init_signal_collector = __esm({
17688
17825
  "test generation",
17689
17826
  "error handling",
17690
17827
  "validation logic",
17691
- "api integration"
17828
+ "api integration",
17829
+ "code index",
17830
+ "coverage analysis",
17831
+ "quality assessment",
17832
+ "defect prediction",
17833
+ "predict defect",
17834
+ "analyze coverage"
17692
17835
  ],
17693
17836
  // Tier 3 - High complexity
17694
17837
  complex: [
@@ -17699,7 +17842,14 @@ var init_signal_collector = __esm({
17699
17842
  "migration",
17700
17843
  "cross-domain",
17701
17844
  "workflow",
17702
- "system design"
17845
+ "system design",
17846
+ "analyze security",
17847
+ "security scan",
17848
+ "security analysis",
17849
+ "vulnerability scan",
17850
+ "chaos test",
17851
+ "resilience test",
17852
+ "contract validation"
17703
17853
  ],
17704
17854
  // Tier 4 - Critical/expert
17705
17855
  critical: [
@@ -17710,7 +17860,12 @@ var init_signal_collector = __esm({
17710
17860
  "system-wide",
17711
17861
  "vulnerability",
17712
17862
  "cryptography",
17713
- "performance critical"
17863
+ "performance critical",
17864
+ "hardcoded secret",
17865
+ "cve",
17866
+ "owasp",
17867
+ "penetration test",
17868
+ "exploit"
17714
17869
  ]
17715
17870
  };
17716
17871
  SCOPE_PATTERNS = {
@@ -18007,11 +18162,15 @@ var init_score_calculator = __esm({
18007
18162
  * Calculate overall complexity score (0-100)
18008
18163
  */
18009
18164
  calculateOverallComplexity(codeComplexity, reasoningComplexity, scopeComplexity, signals) {
18010
- if (signals.isMechanicalTransform) {
18165
+ if (signals.isMechanicalTransform && !signals.hasSecurityScope && !signals.hasArchitectureScope && !signals.requiresMultiStepReasoning && !signals.requiresCrossDomainCoordination && codeComplexity === 0 && reasoningComplexity === 0 && scopeComplexity === 0) {
18011
18166
  return 5;
18012
18167
  }
18013
18168
  const weighted = codeComplexity * 0.3 + reasoningComplexity * 0.4 + scopeComplexity * 0.3;
18014
- return Math.min(Math.round(weighted), 100);
18169
+ let minScore = 0;
18170
+ if (signals.hasSecurityScope) minScore = Math.max(minScore, 50);
18171
+ if (signals.hasArchitectureScope) minScore = Math.max(minScore, 55);
18172
+ if (signals.requiresCrossDomainCoordination) minScore = Math.max(minScore, 35);
18173
+ return Math.min(Math.max(Math.round(weighted), minScore), 100);
18015
18174
  }
18016
18175
  /**
18017
18176
  * Calculate confidence in complexity assessment (0-1)
@@ -18814,7 +18973,7 @@ var init_router = __esm({
18814
18973
  agentBoosterStats: {
18815
18974
  eligible: agentBoosterEligible,
18816
18975
  used: agentBoosterUsed,
18817
- fallbackToLLM: agentBoosterEligible - agentBoosterUsed,
18976
+ fallbackToLLM: Math.max(0, agentBoosterEligible - agentBoosterUsed),
18818
18977
  successRate: agentBoosterUsed > 0 ? agentBoosterSuccess / agentBoosterUsed : 0
18819
18978
  },
18820
18979
  budgetStats: {
@@ -38624,7 +38783,7 @@ var JestVitestGenerator = class extends BaseTestGenerator {
38624
38783
  * Generate complete test file from analysis
38625
38784
  */
38626
38785
  generateTests(context) {
38627
- const { moduleName, importPath, testType, patterns, analysis } = context;
38786
+ const { moduleName, importPath, testType, patterns, analysis, dependencies } = context;
38628
38787
  if (!analysis || analysis.functions.length === 0 && analysis.classes.length === 0) {
38629
38788
  return this.generateStubTests(context);
38630
38789
  }
@@ -38634,8 +38793,23 @@ var JestVitestGenerator = class extends BaseTestGenerator {
38634
38793
  const mockImport = this.framework === "vitest" ? ", vi" : "";
38635
38794
  let testCode = `${patternComment}import { describe, it, expect, beforeEach${mockImport} } from '${this.framework}';
38636
38795
  ${importStatement}
38637
-
38638
38796
  `;
38797
+ if (dependencies && dependencies.imports.length > 0) {
38798
+ const mockFn = this.framework === "vitest" ? "vi.fn()" : "jest.fn()";
38799
+ testCode += `
38800
+ // Auto-generated mocks from Knowledge Graph dependency analysis
38801
+ `;
38802
+ for (const dep of dependencies.imports.slice(0, 10)) {
38803
+ const depName = dep.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g, "_") || dep;
38804
+ testCode += `${this.framework === "vitest" ? "vi" : "jest"}.mock('${dep}', () => ({ default: ${mockFn} }));
38805
+ `;
38806
+ }
38807
+ testCode += `
38808
+ `;
38809
+ } else {
38810
+ testCode += `
38811
+ `;
38812
+ }
38639
38813
  for (const fn of analysis.functions) {
38640
38814
  testCode += this.generateFunctionTests(fn, testType);
38641
38815
  }
@@ -38755,22 +38929,80 @@ ${importStatement}
38755
38929
  * Generate stub tests when no AST analysis is available
38756
38930
  */
38757
38931
  generateStubTests(context) {
38758
- const { moduleName, importPath, testType, patterns } = context;
38932
+ const { moduleName, importPath, testType, patterns, dependencies, similarCode } = context;
38759
38933
  const patternComment = this.generatePatternComment(patterns);
38760
38934
  const basicOpsTest = this.generateBasicOpsTest(moduleName, patterns);
38761
38935
  const edgeCaseTest = this.generateEdgeCaseTest(moduleName, patterns);
38762
38936
  const errorHandlingTest = this.generateErrorHandlingTest(moduleName, patterns);
38937
+ let mockDeclarations = "";
38938
+ if (dependencies && dependencies.imports.length > 0) {
38939
+ const mockFn = this.framework === "vitest" ? "vi.fn()" : "jest.fn()";
38940
+ mockDeclarations += `
38941
+ // Auto-generated mocks from Knowledge Graph dependency analysis
38942
+ `;
38943
+ for (const dep of dependencies.imports.slice(0, 10)) {
38944
+ mockDeclarations += `${this.mockUtil}.mock('${dep}', () => ({ default: ${mockFn} }));
38945
+ `;
38946
+ }
38947
+ }
38948
+ let similarityComment = "";
38949
+ if (similarCode && similarCode.snippets.length > 0) {
38950
+ similarityComment += ` // KG: Similar modules found - consider testing shared patterns:
38951
+ `;
38952
+ for (const s70 of similarCode.snippets.slice(0, 3)) {
38953
+ similarityComment += ` // - ${s70.file} (${(s70.score * 100).toFixed(0)}% similar)
38954
+ `;
38955
+ }
38956
+ similarityComment += `
38957
+ `;
38958
+ }
38959
+ let depTest = "";
38960
+ if (dependencies && dependencies.imports.length > 0) {
38961
+ depTest += `
38962
+ it('should interact with dependencies correctly', () => {
38963
+ `;
38964
+ depTest += ` // KG-informed: module depends on ${dependencies.imports.length} imports
38965
+ `;
38966
+ depTest += ` const instance = typeof ${moduleName} === 'function'
38967
+ `;
38968
+ depTest += ` ? new ${moduleName}()
38969
+ `;
38970
+ depTest += ` : ${moduleName};
38971
+ `;
38972
+ depTest += ` expect(instance).toBeDefined();
38973
+ `;
38974
+ depTest += ` });
38975
+ `;
38976
+ }
38977
+ let callerTest = "";
38978
+ if (dependencies && dependencies.importedBy.length > 0) {
38979
+ callerTest += `
38980
+ it('should expose stable API for ${dependencies.importedBy.length} consumers', () => {
38981
+ `;
38982
+ callerTest += ` // KG-informed: used by ${dependencies.importedBy.slice(0, 3).join(", ")}
38983
+ `;
38984
+ callerTest += ` const publicKeys = Object.keys(typeof ${moduleName} === 'function'
38985
+ `;
38986
+ callerTest += ` ? ${moduleName}.prototype || {}
38987
+ `;
38988
+ callerTest += ` : ${moduleName});
38989
+ `;
38990
+ callerTest += ` expect(publicKeys.length).toBeGreaterThan(0);
38991
+ `;
38992
+ callerTest += ` });
38993
+ `;
38994
+ }
38763
38995
  return `${patternComment}import { ${moduleName} } from '${importPath}';
38764
-
38996
+ ${mockDeclarations}
38765
38997
  describe('${moduleName}', () => {
38766
- describe('${testType} tests', () => {
38998
+ ${similarityComment} describe('${testType} tests', () => {
38767
38999
  it('should be defined', () => {
38768
39000
  expect(${moduleName}).toBeDefined();
38769
39001
  });
38770
39002
 
38771
39003
  ${basicOpsTest}
38772
39004
  ${edgeCaseTest}
38773
- ${errorHandlingTest}
39005
+ ${errorHandlingTest}${depTest}${callerTest}
38774
39006
  });
38775
39007
  });
38776
39008
  `;
@@ -38978,18 +39210,51 @@ var MochaGenerator = class extends BaseTestGenerator {
38978
39210
  * Generate complete test file from analysis
38979
39211
  */
38980
39212
  generateTests(context) {
38981
- const { moduleName, importPath, testType, patterns, analysis } = context;
39213
+ const { moduleName, importPath, testType, patterns, analysis, dependencies } = context;
38982
39214
  if (!analysis || analysis.functions.length === 0 && analysis.classes.length === 0) {
38983
39215
  return this.generateStubTests(context);
38984
39216
  }
38985
39217
  const patternComment = this.generatePatternComment(patterns);
38986
39218
  const exports = this.extractExports(analysis.functions, analysis.classes);
38987
39219
  const importStatement = this.generateImportStatement(exports, importPath, moduleName);
39220
+ let sinonImport = "";
39221
+ let stubSetup = "";
39222
+ if (dependencies && dependencies.imports.length > 0) {
39223
+ sinonImport = `import sinon from 'sinon';
39224
+ `;
39225
+ const depsToMock = dependencies.imports.slice(0, 5);
39226
+ stubSetup += ` // Auto-generated stubs from Knowledge Graph dependency analysis
39227
+ `;
39228
+ stubSetup += ` let stubs;
39229
+
39230
+ `;
39231
+ stubSetup += ` beforeEach(function() {
39232
+ `;
39233
+ stubSetup += ` stubs = {
39234
+ `;
39235
+ for (const dep of depsToMock) {
39236
+ const depName = dep.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g, "_") || dep;
39237
+ stubSetup += ` ${depName}: sinon.stub(),
39238
+ `;
39239
+ }
39240
+ stubSetup += ` };
39241
+ `;
39242
+ stubSetup += ` });
39243
+
39244
+ `;
39245
+ stubSetup += ` afterEach(function() {
39246
+ `;
39247
+ stubSetup += ` sinon.restore();
39248
+ `;
39249
+ stubSetup += ` });
39250
+
39251
+ `;
39252
+ }
38988
39253
  let code = `${patternComment}import { expect } from 'chai';
38989
- ${importStatement}
39254
+ ${sinonImport}${importStatement}
38990
39255
 
38991
39256
  describe('${moduleName} - ${testType} tests', function() {
38992
- `;
39257
+ ${stubSetup}`;
38993
39258
  for (const fn of analysis.functions) {
38994
39259
  code += this.generateFunctionTests(fn, testType);
38995
39260
  }
@@ -39079,18 +39344,100 @@ describe('${moduleName} - ${testType} tests', function() {
39079
39344
  * Generate stub tests when no AST analysis is available
39080
39345
  */
39081
39346
  generateStubTests(context) {
39082
- const { moduleName, importPath, testType, patterns } = context;
39347
+ const { moduleName, importPath, testType, patterns, dependencies, similarCode } = context;
39083
39348
  const patternComment = this.generatePatternComment(patterns);
39084
39349
  const isAsync = patterns.some(
39085
39350
  (p74) => p74.name.toLowerCase().includes("async") || p74.name.toLowerCase().includes("promise")
39086
39351
  );
39087
39352
  const asyncSetup = isAsync ? "async " : "";
39353
+ let sinonImport = "";
39354
+ let stubSetup = "";
39355
+ let stubTeardown = "";
39356
+ if (dependencies && dependencies.imports.length > 0) {
39357
+ sinonImport = `import sinon from 'sinon';
39358
+ `;
39359
+ const depsToMock = dependencies.imports.slice(0, 5);
39360
+ stubSetup += `
39361
+ // Auto-generated stubs from Knowledge Graph dependency analysis
39362
+ `;
39363
+ stubSetup += ` let stubs;
39364
+
39365
+ `;
39366
+ stubSetup += ` beforeEach(function() {
39367
+ `;
39368
+ stubSetup += ` stubs = {
39369
+ `;
39370
+ for (const dep of depsToMock) {
39371
+ const depName = dep.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g, "_") || dep;
39372
+ stubSetup += ` ${depName}: sinon.stub(),
39373
+ `;
39374
+ }
39375
+ stubSetup += ` };
39376
+ `;
39377
+ stubSetup += ` });
39378
+
39379
+ `;
39380
+ stubTeardown += ` afterEach(function() {
39381
+ `;
39382
+ stubTeardown += ` sinon.restore();
39383
+ `;
39384
+ stubTeardown += ` });
39385
+
39386
+ `;
39387
+ }
39388
+ let similarityComment = "";
39389
+ if (similarCode && similarCode.snippets.length > 0) {
39390
+ similarityComment += ` // KG: Similar modules found - consider testing shared patterns:
39391
+ `;
39392
+ for (const s70 of similarCode.snippets.slice(0, 3)) {
39393
+ similarityComment += ` // - ${s70.file} (${(s70.score * 100).toFixed(0)}% similar)
39394
+ `;
39395
+ }
39396
+ similarityComment += `
39397
+ `;
39398
+ }
39399
+ let depTest = "";
39400
+ if (dependencies && dependencies.imports.length > 0) {
39401
+ depTest += `
39402
+ it('should interact with dependencies correctly', function() {
39403
+ `;
39404
+ depTest += ` // KG-informed: module depends on ${dependencies.imports.length} imports
39405
+ `;
39406
+ depTest += ` const instance = typeof ${moduleName} === 'function'
39407
+ `;
39408
+ depTest += ` ? new ${moduleName}()
39409
+ `;
39410
+ depTest += ` : ${moduleName};
39411
+ `;
39412
+ depTest += ` expect(instance).to.exist;
39413
+ `;
39414
+ depTest += ` });
39415
+ `;
39416
+ }
39417
+ let callerTest = "";
39418
+ if (dependencies && dependencies.importedBy.length > 0) {
39419
+ callerTest += `
39420
+ it('should expose stable API for ${dependencies.importedBy.length} consumers', function() {
39421
+ `;
39422
+ callerTest += ` // KG-informed: used by ${dependencies.importedBy.slice(0, 3).join(", ")}
39423
+ `;
39424
+ callerTest += ` const publicKeys = Object.keys(typeof ${moduleName} === 'function'
39425
+ `;
39426
+ callerTest += ` ? ${moduleName}.prototype || {}
39427
+ `;
39428
+ callerTest += ` : ${moduleName});
39429
+ `;
39430
+ callerTest += ` expect(publicKeys.length).to.be.greaterThan(0);
39431
+ `;
39432
+ callerTest += ` });
39433
+ `;
39434
+ }
39088
39435
  return `${patternComment}import { expect } from 'chai';
39089
- import { ${moduleName} } from '${importPath}';
39436
+ ${sinonImport}import { ${moduleName} } from '${importPath}';
39090
39437
 
39091
39438
  describe('${moduleName}', function() {
39092
39439
  describe('${testType} tests', function() {
39093
- it('should be defined', function() {
39440
+ ${stubSetup}${stubTeardown}${similarityComment} it('should be defined', function() {
39094
39441
  expect(${moduleName}).to.not.be.undefined;
39095
39442
  });
39096
39443
 
@@ -39124,7 +39471,7 @@ describe('${moduleName}', function() {
39124
39471
  : ${moduleName};
39125
39472
  return instance;
39126
39473
  }).to.not.throw();
39127
- });
39474
+ });${depTest}${callerTest}
39128
39475
  });
39129
39476
  });
39130
39477
  `;
@@ -39172,7 +39519,7 @@ var PytestGenerator = class extends BaseTestGenerator {
39172
39519
  * Generate complete test file from analysis
39173
39520
  */
39174
39521
  generateTests(context) {
39175
- const { moduleName, importPath, testType, patterns, analysis } = context;
39522
+ const { moduleName, importPath, testType, patterns, analysis, dependencies } = context;
39176
39523
  if (!analysis || analysis.functions.length === 0 && analysis.classes.length === 0) {
39177
39524
  return this.generateStubTests(context);
39178
39525
  }
@@ -39180,8 +39527,18 @@ var PytestGenerator = class extends BaseTestGenerator {
39180
39527
  const exports = this.extractExports(analysis.functions, analysis.classes);
39181
39528
  const pythonImport = importPath.replace(/\//g, ".").replace(/\.(ts|js)$/, "");
39182
39529
  const importStatement = exports.length > 0 ? `from ${pythonImport} import ${exports.join(", ")}` : `import ${pythonImport} as ${moduleName}`;
39530
+ let mockImport = "";
39531
+ if (dependencies && dependencies.imports.length > 0) {
39532
+ mockImport = `from unittest.mock import patch, MagicMock
39533
+ `;
39534
+ }
39535
+ const depsToMock = dependencies?.imports.slice(0, 5) || [];
39536
+ const patchDecorators = depsToMock.map((dep) => {
39537
+ const depModule = dep.replace(/\//g, ".").replace(/\.py$/, "");
39538
+ return `@patch('${depModule}')`;
39539
+ });
39183
39540
  let code = `${patternComment}import pytest
39184
- ${importStatement}
39541
+ ${mockImport}${importStatement}
39185
39542
 
39186
39543
 
39187
39544
  class Test${this.pascalCase(moduleName)}:
@@ -39189,7 +39546,7 @@ class Test${this.pascalCase(moduleName)}:
39189
39546
 
39190
39547
  `;
39191
39548
  for (const fn of analysis.functions) {
39192
- code += this.generateFunctionTests(fn, testType);
39549
+ code += this.generateFunctionTestsWithPatches(fn, testType, patchDecorators);
39193
39550
  }
39194
39551
  for (const cls of analysis.classes) {
39195
39552
  code += this.generateClassTests(cls, testType);
@@ -39200,8 +39557,18 @@ class Test${this.pascalCase(moduleName)}:
39200
39557
  * Generate tests for a standalone function
39201
39558
  */
39202
39559
  generateFunctionTests(fn, _testType) {
39560
+ return this.generateFunctionTestsWithPatches(fn, _testType, []);
39561
+ }
39562
+ /**
39563
+ * Generate tests for a function with @patch decorators from KG dependencies
39564
+ */
39565
+ generateFunctionTestsWithPatches(fn, _testType, patchDecorators) {
39203
39566
  const validParams = fn.parameters.map((p74) => this.generatePythonTestValue(p74)).join(", ");
39204
- let code = ` def test_${fn.name}_valid_input(self):
39567
+ const mockParams = patchDecorators.map((_56, i58) => `mock_dep_${i58}`).reverse().join(", ");
39568
+ const allParams = mockParams ? `self, ${mockParams}` : "self";
39569
+ const patchPrefix = patchDecorators.map((d74) => ` ${d74}
39570
+ `).join("");
39571
+ let code = `${patchPrefix} def test_${fn.name}_valid_input(${allParams}):
39205
39572
  `;
39206
39573
  code += ` """Test ${fn.name} with valid input"""
39207
39574
  `;
@@ -39212,7 +39579,7 @@ class Test${this.pascalCase(moduleName)}:
39212
39579
  `;
39213
39580
  for (const param of fn.parameters) {
39214
39581
  if (!param.optional && param.type?.includes("str")) {
39215
- code += ` def test_${fn.name}_empty_${param.name}(self):
39582
+ code += `${patchPrefix} def test_${fn.name}_empty_${param.name}(${allParams}):
39216
39583
  `;
39217
39584
  code += ` """Test ${fn.name} with empty ${param.name}"""
39218
39585
  `;
@@ -39267,21 +39634,84 @@ class Test${cls.name}:
39267
39634
  * Generate stub tests when no AST analysis is available
39268
39635
  */
39269
39636
  generateStubTests(context) {
39270
- const { moduleName, importPath, testType, patterns } = context;
39637
+ const { moduleName, importPath, testType, patterns, dependencies, similarCode } = context;
39271
39638
  const patternComment = this.generatePythonPatternComment(patterns);
39272
39639
  const isAsync = patterns.some(
39273
39640
  (p74) => p74.name.toLowerCase().includes("async") || p74.name.toLowerCase().includes("promise")
39274
39641
  );
39275
39642
  const asyncDecorator = isAsync ? "@pytest.mark.asyncio\n " : "";
39276
39643
  const asyncDef = isAsync ? "async def" : "def";
39644
+ let mockImports = "";
39645
+ let mockPatches = "";
39646
+ if (dependencies && dependencies.imports.length > 0) {
39647
+ mockImports = `from unittest.mock import patch, MagicMock
39648
+ `;
39649
+ const depsToMock = dependencies.imports.slice(0, 5);
39650
+ for (const dep of depsToMock) {
39651
+ const depModule = dep.replace(/\//g, ".").replace(/\.py$/, "");
39652
+ mockPatches += ` @patch('${depModule}')
39653
+ `;
39654
+ }
39655
+ }
39656
+ let similarityComment = "";
39657
+ if (similarCode && similarCode.snippets.length > 0) {
39658
+ similarityComment = ` # KG: Similar modules found - consider testing shared patterns:
39659
+ `;
39660
+ for (const s70 of similarCode.snippets.slice(0, 3)) {
39661
+ similarityComment += ` # - ${s70.file} (${(s70.score * 100).toFixed(0)}% similar)
39662
+ `;
39663
+ }
39664
+ similarityComment += `
39665
+ `;
39666
+ }
39667
+ let depTests = "";
39668
+ if (dependencies && dependencies.imports.length > 0) {
39669
+ depTests += `
39670
+ def test_dependencies_importable(self):
39671
+ `;
39672
+ depTests += ` """Verify all dependencies are importable (KG-informed)."""
39673
+ `;
39674
+ for (const dep of dependencies.imports.slice(0, 5)) {
39675
+ const depModule = dep.replace(/\//g, ".").replace(/\.py$/, "");
39676
+ depTests += ` import importlib
39677
+ `;
39678
+ depTests += ` mod = importlib.import_module('${depModule}')
39679
+ `;
39680
+ depTests += ` assert mod is not None
39681
+ `;
39682
+ }
39683
+ depTests += `
39684
+ def test_dependency_interactions(self):
39685
+ `;
39686
+ depTests += ` """Test module interactions with its dependencies (KG-informed)."""
39687
+ `;
39688
+ depTests += ` # Module should handle dependency failures gracefully
39689
+ `;
39690
+ depTests += ` assert ${moduleName} is not None
39691
+ `;
39692
+ depTests += ` assert hasattr(${moduleName}, '__name__') or hasattr(${moduleName}, '__class__')
39693
+ `;
39694
+ }
39695
+ let callerTests = "";
39696
+ if (dependencies && dependencies.importedBy.length > 0) {
39697
+ callerTests += `
39698
+ def test_public_api_surface(self):
39699
+ `;
39700
+ callerTests += ` """Verify public API used by ${dependencies.importedBy.length} consumers (KG-informed)."""
39701
+ `;
39702
+ callerTests += ` public_attrs = [a for a in dir(${moduleName}) if not a.startswith('_')]
39703
+ `;
39704
+ callerTests += ` assert len(public_attrs) > 0, "Module should expose public API"
39705
+ `;
39706
+ }
39277
39707
  return `${patternComment}import pytest
39278
- from ${importPath} import ${moduleName}
39708
+ ${mockImports}from ${importPath} import ${moduleName}
39279
39709
 
39280
39710
 
39281
39711
  class Test${this.pascalCase(moduleName)}:
39282
39712
  """${testType} tests for ${moduleName}"""
39283
39713
 
39284
- def test_is_defined(self):
39714
+ ${similarityComment} def test_is_defined(self):
39285
39715
  """Verify the module is properly exported and defined."""
39286
39716
  assert ${moduleName} is not None
39287
39717
 
@@ -39315,7 +39745,7 @@ class Test${this.pascalCase(moduleName)}:
39315
39745
  except TypeError:
39316
39746
  # Expected if constructor requires arguments
39317
39747
  pass
39318
- `;
39748
+ ${depTests}${callerTests}`;
39319
39749
  }
39320
39750
  /**
39321
39751
  * Generate coverage-focused tests for specific lines
@@ -40333,10 +40763,46 @@ var TestGeneratorService = class {
40333
40763
  * Enhance generated test code using LLM
40334
40764
  * Adds edge cases, improves assertions, and adds documentation
40335
40765
  */
40336
- async enhanceTestWithLLM(testCode, sourceCode, analysis) {
40766
+ async enhanceTestWithLLM(testCode, sourceCode, analysis, context) {
40337
40767
  if (!this.llmRouter) return testCode;
40338
40768
  try {
40339
- const prompt = this.buildTestEnhancementPrompt(testCode, sourceCode, analysis);
40769
+ let prompt = this.buildTestEnhancementPrompt(testCode, sourceCode, analysis);
40770
+ if (context?.dependencies) {
40771
+ prompt += `
40772
+ ## Dependency Context (from Knowledge Graph):
40773
+ `;
40774
+ if (context.dependencies.imports.length > 0) {
40775
+ prompt += `- Imports: ${context.dependencies.imports.join(", ")}
40776
+ `;
40777
+ prompt += ` \u2192 Generate mock declarations for these dependencies
40778
+ `;
40779
+ }
40780
+ if (context.dependencies.importedBy.length > 0) {
40781
+ prompt += `- Imported by: ${context.dependencies.importedBy.join(", ")}
40782
+ `;
40783
+ prompt += ` \u2192 Focus tests on the public API surface these consumers use
40784
+ `;
40785
+ }
40786
+ if (context.dependencies.callers.length > 0) {
40787
+ prompt += `- Called by: ${context.dependencies.callers.join(", ")}
40788
+ `;
40789
+ }
40790
+ if (context.dependencies.callees.length > 0) {
40791
+ prompt += `- Calls: ${context.dependencies.callees.join(", ")}
40792
+ `;
40793
+ }
40794
+ }
40795
+ if (context?.similarCode && context.similarCode.snippets.length > 0) {
40796
+ prompt += `
40797
+ ## Similar Code Patterns (from Knowledge Graph):
40798
+ `;
40799
+ for (const s70 of context.similarCode.snippets.slice(0, 3)) {
40800
+ prompt += `- ${s70.file} (similarity: ${(s70.score * 100).toFixed(0)}%): ${s70.snippet}
40801
+ `;
40802
+ }
40803
+ prompt += ` \u2192 Use similar patterns as templates for assertions
40804
+ `;
40805
+ }
40340
40806
  const modelId = this.getModelForTier(this.config.llmModelTier);
40341
40807
  const response = await this.llmRouter.chat({
40342
40808
  messages: [
@@ -40576,6 +41042,15 @@ ${sourceCode}
40576
41042
  codeAnalysis = this.analyzeSourceCode(sourceContent, sourceFile);
40577
41043
  } catch {
40578
41044
  }
41045
+ let dependencies;
41046
+ let similarCode;
41047
+ if (this.memory && sourceContent) {
41048
+ const hasKGVectors = await this.hasKGVectors();
41049
+ if (hasKGVectors) {
41050
+ dependencies = await this.queryKGDependencies(sourceFile, sourceContent);
41051
+ similarCode = await this.queryKGSimilarCode(sourceContent);
41052
+ }
41053
+ }
40579
41054
  const generator = this.generatorFactory.create(framework);
40580
41055
  const moduleName = this.extractModuleName(sourceFile);
40581
41056
  const importPath = this.getImportPath(sourceFile);
@@ -40584,11 +41059,13 @@ ${sourceCode}
40584
41059
  importPath,
40585
41060
  testType,
40586
41061
  patterns: applicablePatterns,
40587
- analysis: codeAnalysis ?? void 0
41062
+ analysis: codeAnalysis ?? void 0,
41063
+ dependencies,
41064
+ similarCode
40588
41065
  };
40589
41066
  let testCode = generator.generateTests(context);
40590
41067
  if (this.isLLMEnhancementAvailable() && sourceContent) {
40591
- testCode = await this.enhanceTestWithLLM(testCode, sourceContent, codeAnalysis);
41068
+ testCode = await this.enhanceTestWithLLM(testCode, sourceContent, codeAnalysis, context);
40592
41069
  }
40593
41070
  const test = {
40594
41071
  id: v4_default(),
@@ -40783,6 +41260,107 @@ ${sourceCode}
40783
41260
  return complexity;
40784
41261
  }
40785
41262
  // ============================================================================
41263
+ // Private Helper Methods - Knowledge Graph Queries
41264
+ // ============================================================================
41265
+ /**
41266
+ * Check if KG vectors exist by probing a vector search.
41267
+ * Returns true if vectorSearch returns any results (indicating indexed code exists).
41268
+ */
41269
+ async hasKGVectors() {
41270
+ try {
41271
+ const probe = new Array(768).fill(0);
41272
+ probe[0] = 1;
41273
+ const results = await this.memory.vectorSearch(probe, 1);
41274
+ return results.length > 0;
41275
+ } catch {
41276
+ return false;
41277
+ }
41278
+ }
41279
+ /**
41280
+ * Query KG for dependency information about a file.
41281
+ * Extracts imports from source and cross-references with KG vector index
41282
+ * to find which indexed modules this file depends on and which depend on it.
41283
+ */
41284
+ async queryKGDependencies(filePath, sourceContent) {
41285
+ try {
41286
+ const imports = [];
41287
+ const importedBy = [];
41288
+ const callees = [];
41289
+ const callers = [];
41290
+ const tsImports = sourceContent.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);
41291
+ const pyImports = sourceContent.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);
41292
+ for (const match of tsImports) {
41293
+ imports.push(match[1]);
41294
+ }
41295
+ for (const match of pyImports) {
41296
+ imports.push(match[1] || match[2]);
41297
+ }
41298
+ const normalizedPath = filePath.replace(/\\/g, "/");
41299
+ const baseName = normalizedPath.split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/, "") || "";
41300
+ const nodeKeys = await this.memory.search(`code-intelligence:kg:node:*${baseName}*`, 50);
41301
+ for (const key of nodeKeys) {
41302
+ if (!key.includes(baseName)) continue;
41303
+ const parts = key.split(":");
41304
+ const nodeType = parts[parts.length - 2];
41305
+ const nodeName = parts[parts.length - 1];
41306
+ if (nodeType === "function") {
41307
+ callees.push(nodeName);
41308
+ }
41309
+ }
41310
+ if (imports.length === 0 && importedBy.length === 0 && callees.length === 0 && callers.length === 0) {
41311
+ return void 0;
41312
+ }
41313
+ return { imports, importedBy, callees, callers };
41314
+ } catch {
41315
+ return void 0;
41316
+ }
41317
+ }
41318
+ /**
41319
+ * Query KG for semantically similar code snippets.
41320
+ * Uses vector search against the persisted vectors table.
41321
+ * KG nodes are stored as vectors with IDs like code-intelligence:kg:node:*
41322
+ */
41323
+ async queryKGSimilarCode(sourceContent) {
41324
+ try {
41325
+ const embedding = this.generatePseudoEmbedding(sourceContent);
41326
+ const results = await this.memory.vectorSearch(embedding, 5);
41327
+ if (results.length === 0) return void 0;
41328
+ const snippets = [];
41329
+ for (const result of results) {
41330
+ if (result.score < 0.1) continue;
41331
+ const metadata = result.metadata;
41332
+ const file = metadata?.file || result.key;
41333
+ const snippet = metadata?.name || metadata?.type || result.key.split(":").pop() || "";
41334
+ snippets.push({ file, snippet, score: result.score });
41335
+ }
41336
+ return snippets.length > 0 ? { snippets } : void 0;
41337
+ } catch {
41338
+ return void 0;
41339
+ }
41340
+ }
41341
+ /**
41342
+ * Generate a simple pseudo-embedding for vector search.
41343
+ * Uses token-based feature extraction similar to semantic-analyzer.
41344
+ */
41345
+ generatePseudoEmbedding(code) {
41346
+ const dimension = 768;
41347
+ const embedding = new Array(dimension).fill(0);
41348
+ const tokens = code.split(/[^a-zA-Z0-9_$]+/).filter((t50) => t50.length > 1);
41349
+ for (let i58 = 0; i58 < tokens.length; i58++) {
41350
+ const token = tokens[i58];
41351
+ for (let j52 = 0; j52 < token.length && j52 < embedding.length; j52++) {
41352
+ embedding[(i58 + j52) % dimension] += token.charCodeAt(j52) / 1e3;
41353
+ }
41354
+ }
41355
+ const magnitude2 = Math.sqrt(embedding.reduce((sum, v62) => sum + v62 * v62, 0));
41356
+ if (magnitude2 > 0) {
41357
+ for (let i58 = 0; i58 < dimension; i58++) {
41358
+ embedding[i58] /= magnitude2;
41359
+ }
41360
+ }
41361
+ return embedding;
41362
+ }
41363
+ // ============================================================================
40786
41364
  // Private Helper Methods - Utility Functions
40787
41365
  // ============================================================================
40788
41366
  async findApplicablePatterns(sourceFile, requestedPatterns) {
@@ -42703,6 +43281,7 @@ var TypeScriptASTParser = class {
42703
43281
  // src/learning/qe-hooks.ts
42704
43282
  init_error_utils();
42705
43283
  init_logging();
43284
+ init_qe_patterns();
42706
43285
  var logger6 = LoggerFactory.create("qe-hooks");
42707
43286
  var QE_HOOK_EVENTS = {
42708
43287
  // Test lifecycle
@@ -85572,7 +86151,35 @@ import { join as join10, extname as extname3 } from "path";
85572
86151
  // src/domains/code-intelligence/services/metric-collector/interfaces.ts
85573
86152
  var DEFAULT_METRIC_CONFIG = {
85574
86153
  timeout: 6e4,
85575
- excludeDirs: ["node_modules", "dist", "coverage", "build", ".git", "vendor", "target"],
86154
+ excludeDirs: [
86155
+ // JS/TS ecosystem
86156
+ "node_modules",
86157
+ "dist",
86158
+ "build",
86159
+ "coverage",
86160
+ ".nyc_output",
86161
+ ".next",
86162
+ ".nuxt",
86163
+ ".output",
86164
+ // Python ecosystem
86165
+ "__pycache__",
86166
+ ".venv",
86167
+ "venv",
86168
+ ".tox",
86169
+ ".mypy_cache",
86170
+ ".pytest_cache",
86171
+ ".eggs",
86172
+ "*.egg-info",
86173
+ // Rust / Java / Go
86174
+ "target",
86175
+ ".gradle",
86176
+ "vendor",
86177
+ ".bundle",
86178
+ // General
86179
+ ".git",
86180
+ ".svn",
86181
+ ".hg"
86182
+ ],
85576
86183
  testPatterns: ["**/*.test.ts", "**/*.spec.ts", "**/*.test.js", "**/*.spec.js"],
85577
86184
  enableCache: true,
85578
86185
  cacheTTL: 3e5
@@ -85580,7 +86187,7 @@ var DEFAULT_METRIC_CONFIG = {
85580
86187
 
85581
86188
  // src/domains/code-intelligence/services/metric-collector/loc-counter.ts
85582
86189
  import { execSync as execSync3, spawnSync as spawnSync2 } from "child_process";
85583
- import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5 } from "fs";
86190
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
85584
86191
  import { join as join8, extname } from "path";
85585
86192
  init_safe_json();
85586
86193
  async function countLOC(projectPath, config = {}) {
@@ -85724,22 +86331,35 @@ function getLanguageForExtension(ext) {
85724
86331
  function manualLOCCount(projectPath, config) {
85725
86332
  const byLanguage = {};
85726
86333
  let total = 0;
85727
- function walkDirectory2(dirPath) {
85728
- if (!existsSync6(dirPath)) {
86334
+ const excludeSet = new Set(config.excludeDirs);
86335
+ const MAX_FILE_SIZE = 2 * 1024 * 1024;
86336
+ function walkDirectory2(dirPath, depth) {
86337
+ if (!existsSync6(dirPath) || depth > 20) {
86338
+ return;
86339
+ }
86340
+ let entries;
86341
+ try {
86342
+ entries = readdirSync(dirPath, { withFileTypes: true });
86343
+ } catch {
85729
86344
  return;
85730
86345
  }
85731
- const entries = readdirSync(dirPath, { withFileTypes: true });
85732
86346
  for (const entry of entries) {
85733
86347
  const fullPath = join8(dirPath, entry.name);
85734
86348
  if (entry.isDirectory()) {
85735
- if (config.excludeDirs.includes(entry.name)) {
86349
+ if (excludeSet.has(entry.name) || entry.name.startsWith(".")) {
85736
86350
  continue;
85737
86351
  }
85738
- walkDirectory2(fullPath);
86352
+ walkDirectory2(fullPath, depth + 1);
85739
86353
  } else if (entry.isFile()) {
85740
86354
  const ext = extname(entry.name);
85741
86355
  const language = getLanguageForExtension(ext);
85742
86356
  if (language) {
86357
+ try {
86358
+ const stat6 = statSync2(fullPath);
86359
+ if (stat6.size > MAX_FILE_SIZE) continue;
86360
+ } catch {
86361
+ continue;
86362
+ }
85743
86363
  const lines = countFileLines(fullPath);
85744
86364
  byLanguage[language] = (byLanguage[language] || 0) + lines;
85745
86365
  total += lines;
@@ -85747,11 +86367,11 @@ function manualLOCCount(projectPath, config) {
85747
86367
  }
85748
86368
  }
85749
86369
  }
85750
- walkDirectory2(projectPath);
86370
+ walkDirectory2(projectPath, 0);
85751
86371
  return {
85752
86372
  total,
85753
86373
  byLanguage,
85754
- source: "fallback",
86374
+ source: "node-native",
85755
86375
  excludedDirs: config.excludeDirs
85756
86376
  };
85757
86377
  }
@@ -86382,12 +87002,19 @@ var MetricCollectorService = class {
86382
87002
  const toolsUsed = [];
86383
87003
  if (loc.source !== "fallback") toolsUsed.push(loc.source);
86384
87004
  if (tests.source !== "fallback") toolsUsed.push(tests.source);
87005
+ const locAccuracy = loc.source === "fallback" ? "approximate" : "accurate";
87006
+ const testAccuracy = tests.source === "fallback" ? "approximate" : "accurate";
86385
87007
  const metrics = {
86386
87008
  loc,
86387
87009
  tests,
86388
87010
  patterns,
86389
87011
  collectedAt: /* @__PURE__ */ new Date(),
86390
- toolsUsed
87012
+ toolsUsed,
87013
+ accuracy: {
87014
+ loc: locAccuracy,
87015
+ tests: testAccuracy,
87016
+ overall: locAccuracy === "accurate" && testAccuracy === "accurate" ? "accurate" : "approximate"
87017
+ }
86391
87018
  };
86392
87019
  if (this.config.enableCache) {
86393
87020
  this.setInCache(cacheKey, metrics);
@@ -88617,9 +89244,15 @@ var CodeIntelligenceCoordinator = class extends BaseDomainCoordinator {
88617
89244
  try {
88618
89245
  console.log(`[CodeIntelligence] Collecting real metrics for ${projectPath}`);
88619
89246
  const metrics = await this.metricCollector.collectAll(projectPath);
89247
+ const toolsLabel = metrics.toolsUsed.length > 0 ? metrics.toolsUsed.join(", ") : metrics.loc.source === "node-native" ? "node-native" : "fallback";
88620
89248
  console.log(
88621
- `[CodeIntelligence] Real metrics collected: ${metrics.loc.total} LOC, ${metrics.tests.total} tests, tools: ${metrics.toolsUsed.join(", ") || "fallback"}`
89249
+ `[CodeIntelligence] Real metrics collected: ${metrics.loc.total} LOC, ${metrics.tests.total} tests, tools: ${toolsLabel}`
88622
89250
  );
89251
+ if (metrics.loc.source === "node-native") {
89252
+ console.log(
89253
+ `[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)`
89254
+ );
89255
+ }
88623
89256
  await this.storeProjectMetricsInMemory(projectPath, metrics);
88624
89257
  if (this.config.publishEvents) {
88625
89258
  const event = createEvent(
@@ -132322,13 +132955,58 @@ function parseLcovInfo(content) {
132322
132955
  async function discoverSourceFiles(targetPath, options = {}) {
132323
132956
  const files = [];
132324
132957
  const { includeTests = true, languages } = options;
132325
- let extensions = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
132958
+ let extensions = [
132959
+ ".ts",
132960
+ ".tsx",
132961
+ ".js",
132962
+ ".jsx",
132963
+ ".mjs",
132964
+ ".cjs",
132965
+ // JavaScript/TypeScript
132966
+ ".py",
132967
+ ".pyw",
132968
+ // Python
132969
+ ".go",
132970
+ // Go
132971
+ ".rs",
132972
+ // Rust
132973
+ ".java",
132974
+ ".kt",
132975
+ ".kts",
132976
+ // Java/Kotlin
132977
+ ".rb",
132978
+ // Ruby
132979
+ ".cs",
132980
+ // C#
132981
+ ".php",
132982
+ // PHP
132983
+ ".swift",
132984
+ // Swift
132985
+ ".c",
132986
+ ".h",
132987
+ ".cpp",
132988
+ ".hpp",
132989
+ ".cc",
132990
+ // C/C++
132991
+ ".scala"
132992
+ // Scala
132993
+ ];
132326
132994
  if (languages && languages.length > 0) {
132327
132995
  extensions = [];
132328
132996
  for (const lang of languages) {
132329
132997
  if (lang === "typescript") extensions.push(".ts", ".tsx");
132330
132998
  if (lang === "javascript") extensions.push(".js", ".jsx", ".mjs", ".cjs");
132331
- if (lang === "python") extensions.push(".py");
132999
+ if (lang === "python") extensions.push(".py", ".pyw");
133000
+ if (lang === "go") extensions.push(".go");
133001
+ if (lang === "rust") extensions.push(".rs");
133002
+ if (lang === "java") extensions.push(".java");
133003
+ if (lang === "kotlin") extensions.push(".kt", ".kts");
133004
+ if (lang === "ruby") extensions.push(".rb");
133005
+ if (lang === "csharp" || lang === "c#") extensions.push(".cs");
133006
+ if (lang === "php") extensions.push(".php");
133007
+ if (lang === "swift") extensions.push(".swift");
133008
+ if (lang === "c" || lang === "cpp" || lang === "c++") extensions.push(".c", ".h", ".cpp", ".hpp", ".cc");
133009
+ if (lang === "scala") extensions.push(".scala");
132332
133010
  }
132333
133011
  }
132334
133012
  async function walkDir(dir) {
@@ -132337,7 +133015,23 @@ async function discoverSourceFiles(targetPath, options = {}) {
132337
133015
  for (const entry of entries) {
132338
133016
  const fullPath = path16.join(dir, entry.name);
132339
133017
  if (entry.isDirectory()) {
132340
- if (["node_modules", ".git", "dist", "build", "coverage", ".nyc_output"].includes(entry.name)) {
133018
+ if ([
133019
+ "node_modules",
133020
+ ".git",
133021
+ "dist",
133022
+ "build",
133023
+ "coverage",
133024
+ ".nyc_output",
133025
+ "__pycache__",
133026
+ ".venv",
133027
+ "venv",
133028
+ ".tox",
133029
+ ".mypy_cache",
133030
+ "target",
133031
+ ".gradle",
133032
+ "vendor",
133033
+ ".bundle"
133034
+ ].includes(entry.name)) {
132341
133035
  continue;
132342
133036
  }
132343
133037
  await walkDir(fullPath);
@@ -132503,7 +133197,24 @@ var DomainTaskExecutor = class {
132503
133197
  } else if (payload.filePath) {
132504
133198
  sourceFiles = [payload.filePath];
132505
133199
  } else if (payload.sourceCode) {
132506
- const tempPath = `/tmp/aqe-temp-${v4_default()}.ts`;
133200
+ const langExtMap = {
133201
+ python: ".py",
133202
+ typescript: ".ts",
133203
+ javascript: ".js",
133204
+ go: ".go",
133205
+ rust: ".rs",
133206
+ java: ".java",
133207
+ ruby: ".rb",
133208
+ kotlin: ".kt",
133209
+ csharp: ".cs",
133210
+ php: ".php",
133211
+ swift: ".swift",
133212
+ cpp: ".cpp",
133213
+ c: ".c",
133214
+ scala: ".scala"
133215
+ };
133216
+ const ext = langExtMap[payload.language?.toLowerCase() || "typescript"] || ".ts";
133217
+ const tempPath = `/tmp/aqe-temp-${v4_default()}${ext}`;
132507
133218
  await fs15.writeFile(tempPath, payload.sourceCode, "utf-8");
132508
133219
  sourceFiles = [tempPath];
132509
133220
  }
@@ -132619,12 +133330,96 @@ var DomainTaskExecutor = class {
132619
133330
  sast: payload.sast !== false,
132620
133331
  dast: payload.dast || false
132621
133332
  },
132622
- warning: `No TypeScript/JavaScript files found in ${targetPath}`
133333
+ warning: `No source files found in ${targetPath}`
132623
133334
  });
132624
133335
  }
132625
- const filePathObjects = filesToScan.map((filePath) => FilePath.create(filePath));
133336
+ const jstsFiles = filesToScan.filter((f74) => /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f74));
133337
+ const otherFiles = filesToScan.filter((f74) => !/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f74));
133338
+ const crossLangVulns = [];
133339
+ for (const filePath of otherFiles) {
133340
+ try {
133341
+ const content = await fs15.readFile(filePath, "utf-8");
133342
+ const lines = content.split("\n");
133343
+ const relPath = filePath.startsWith(targetPath) ? filePath.slice(targetPath.length).replace(/^\//, "") : filePath;
133344
+ const secretPatterns = [
133345
+ { regex: /(?:secret|password|api_key|apikey|token|jwt_secret|private_key)\s*[=:]\s*['"][^'"]{8,}['"]/gi, title: "Hardcoded secret", severity: "critical" },
133346
+ { regex: /(?:AWS_SECRET|GITHUB_TOKEN|SLACK_TOKEN)\s*[=:]\s*['"][^'"]+['"]/gi, title: "Hardcoded cloud credential", severity: "critical" }
133347
+ ];
133348
+ for (const pattern of secretPatterns) {
133349
+ for (let i58 = 0; i58 < lines.length; i58++) {
133350
+ if (pattern.regex.test(lines[i58])) {
133351
+ crossLangVulns.push({
133352
+ title: pattern.title,
133353
+ severity: pattern.severity,
133354
+ location: { file: relPath, line: i58 + 1 },
133355
+ description: `Potential hardcoded secret found at line ${i58 + 1}`,
133356
+ category: "sensitive-data"
133357
+ });
133358
+ }
133359
+ pattern.regex.lastIndex = 0;
133360
+ }
133361
+ }
133362
+ const sqlPatterns = /(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;
133363
+ for (let i58 = 0; i58 < lines.length; i58++) {
133364
+ if (sqlPatterns.test(lines[i58])) {
133365
+ crossLangVulns.push({
133366
+ title: "Potential SQL injection",
133367
+ severity: "high",
133368
+ location: { file: relPath, line: i58 + 1 },
133369
+ description: "String interpolation in SQL query \u2014 use parameterized queries",
133370
+ category: "injection"
133371
+ });
133372
+ }
133373
+ sqlPatterns.lastIndex = 0;
133374
+ }
133375
+ if (/allow_origins\s*=\s*\[?\s*['"]?\*['"]?\s*\]?/i.test(content)) {
133376
+ crossLangVulns.push({
133377
+ title: "CORS wildcard origin",
133378
+ severity: "high",
133379
+ location: { file: relPath, line: lines.findIndex((l75) => /allow_origins/i.test(l75)) + 1 },
133380
+ description: "CORS configured with wildcard (*) origin \u2014 restrict to specific domains",
133381
+ category: "security-misconfiguration"
133382
+ });
133383
+ }
133384
+ if (/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(content)) {
133385
+ crossLangVulns.push({
133386
+ title: "Debug mode enabled",
133387
+ severity: "medium",
133388
+ location: { file: relPath, line: lines.findIndex((l75) => /DEBUG\s*[=:]\s*(?:True|true|1)/i.test(l75)) + 1 },
133389
+ description: "Debug mode should be disabled in production",
133390
+ category: "security-misconfiguration"
133391
+ });
133392
+ }
133393
+ if (/\b(?:eval|exec)\s*\(/i.test(content)) {
133394
+ crossLangVulns.push({
133395
+ title: "Dangerous eval/exec usage",
133396
+ severity: "high",
133397
+ location: { file: relPath, line: lines.findIndex((l75) => /\b(?:eval|exec)\s*\(/.test(l75)) + 1 },
133398
+ description: "eval/exec can lead to code injection \u2014 avoid using with user input",
133399
+ category: "injection"
133400
+ });
133401
+ }
133402
+ } catch {
133403
+ }
133404
+ }
133405
+ const depManifests = ["requirements.txt", "pyproject.toml", "Gemfile", "go.mod", "Cargo.toml"];
133406
+ for (const manifest of depManifests) {
133407
+ const manifestPath = path16.join(targetPath, manifest);
133408
+ try {
133409
+ await fs15.access(manifestPath);
133410
+ crossLangVulns.push({
133411
+ title: "Dependency audit recommended",
133412
+ severity: "informational",
133413
+ location: { file: manifest, line: 1 },
133414
+ description: `Found ${manifest} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,
133415
+ category: "dependencies"
133416
+ });
133417
+ } catch {
133418
+ }
133419
+ }
133420
+ const filePathObjects = jstsFiles.map((filePath) => FilePath.create(filePath));
132626
133421
  let sastResult = null;
132627
- if (payload.sast !== false) {
133422
+ if (payload.sast !== false && filePathObjects.length > 0) {
132628
133423
  const result = await scanner.scanFiles(filePathObjects);
132629
133424
  if (result.success) {
132630
133425
  sastResult = result.value;
@@ -132641,16 +133436,24 @@ var DomainTaskExecutor = class {
132641
133436
  dastResult = result.value;
132642
133437
  }
132643
133438
  }
133439
+ const crossLangSeverityCounts = {
133440
+ critical: crossLangVulns.filter((v62) => v62.severity === "critical").length,
133441
+ high: crossLangVulns.filter((v62) => v62.severity === "high").length,
133442
+ medium: crossLangVulns.filter((v62) => v62.severity === "medium").length,
133443
+ low: crossLangVulns.filter((v62) => v62.severity === "low").length,
133444
+ informational: crossLangVulns.filter((v62) => v62.severity === "informational").length
133445
+ };
132644
133446
  const summary = {
132645
- critical: (sastResult?.summary?.critical || 0) + (dastResult?.summary?.critical || 0),
132646
- high: (sastResult?.summary?.high || 0) + (dastResult?.summary?.high || 0),
132647
- medium: (sastResult?.summary?.medium || 0) + (dastResult?.summary?.medium || 0),
132648
- low: (sastResult?.summary?.low || 0) + (dastResult?.summary?.low || 0),
132649
- informational: (sastResult?.summary?.informational || 0) + (dastResult?.summary?.informational || 0)
133447
+ critical: (sastResult?.summary?.critical || 0) + (dastResult?.summary?.critical || 0) + crossLangSeverityCounts.critical,
133448
+ high: (sastResult?.summary?.high || 0) + (dastResult?.summary?.high || 0) + crossLangSeverityCounts.high,
133449
+ medium: (sastResult?.summary?.medium || 0) + (dastResult?.summary?.medium || 0) + crossLangSeverityCounts.medium,
133450
+ low: (sastResult?.summary?.low || 0) + (dastResult?.summary?.low || 0) + crossLangSeverityCounts.low,
133451
+ informational: (sastResult?.summary?.informational || 0) + (dastResult?.summary?.informational || 0) + crossLangSeverityCounts.informational
132650
133452
  };
132651
133453
  const allVulns = [
132652
133454
  ...sastResult?.vulnerabilities || [],
132653
- ...dastResult?.vulnerabilities || []
133455
+ ...dastResult?.vulnerabilities || [],
133456
+ ...crossLangVulns
132654
133457
  ];
132655
133458
  const topVulnerabilities = allVulns.sort((a37, b68) => {
132656
133459
  const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, informational: 4 };
@@ -132677,7 +133480,12 @@ var DomainTaskExecutor = class {
132677
133480
  dast: payload.dast || false
132678
133481
  },
132679
133482
  filesScanned: filesToScan.length,
132680
- coverage: sastResult?.coverage
133483
+ jstsFilesScanned: jstsFiles.length,
133484
+ otherFilesScanned: otherFiles.length,
133485
+ coverage: sastResult?.coverage,
133486
+ ...otherFiles.length > 0 && jstsFiles.length === 0 ? {
133487
+ note: "Non-JS/TS files were scanned with cross-language pattern matching. For deeper analysis, use language-specific security tools."
133488
+ } : {}
132681
133489
  });
132682
133490
  } catch (error) {
132683
133491
  return err(toError(error));
@@ -132700,9 +133508,9 @@ var DomainTaskExecutor = class {
132700
133508
  edgesCreated: 0,
132701
133509
  target: targetPath,
132702
133510
  incremental: payload.incremental || false,
132703
- languages: payload.languages || ["typescript", "javascript"],
133511
+ languages: payload.languages || [],
132704
133512
  duration: Date.now() - startTime,
132705
- warning: `No source files found in ${targetPath}`
133513
+ warning: `No source files found in ${targetPath}. Searched for: TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, C/C++, and more.`
132706
133514
  });
132707
133515
  }
132708
133516
  const result = await kg.index({
@@ -132716,11 +133524,35 @@ var DomainTaskExecutor = class {
132716
133524
  }
132717
133525
  const indexResult = result.value;
132718
133526
  const detectedLanguages = /* @__PURE__ */ new Set();
133527
+ const extToLang = {
133528
+ ts: "typescript",
133529
+ tsx: "typescript",
133530
+ js: "javascript",
133531
+ jsx: "javascript",
133532
+ mjs: "javascript",
133533
+ cjs: "javascript",
133534
+ py: "python",
133535
+ pyw: "python",
133536
+ go: "go",
133537
+ rs: "rust",
133538
+ java: "java",
133539
+ kt: "kotlin",
133540
+ kts: "kotlin",
133541
+ rb: "ruby",
133542
+ cs: "csharp",
133543
+ php: "php",
133544
+ swift: "swift",
133545
+ c: "c",
133546
+ h: "c",
133547
+ cpp: "cpp",
133548
+ hpp: "cpp",
133549
+ cc: "cpp",
133550
+ scala: "scala"
133551
+ };
132719
133552
  for (const file of filesToIndex) {
132720
133553
  const ext = path16.extname(file).slice(1);
132721
- if (["ts", "tsx"].includes(ext)) detectedLanguages.add("typescript");
132722
- if (["js", "jsx", "mjs", "cjs"].includes(ext)) detectedLanguages.add("javascript");
132723
- if (ext === "py") detectedLanguages.add("python");
133554
+ const lang = extToLang[ext];
133555
+ if (lang) detectedLanguages.add(lang);
132724
133556
  }
132725
133557
  return ok({
132726
133558
  filesIndexed: indexResult.filesIndexed,
@@ -132818,25 +133650,103 @@ var DomainTaskExecutor = class {
132818
133650
  });
132819
133651
  this.taskHandlers.set("predict-defects", async (task) => {
132820
133652
  const payload = task.payload;
132821
- return ok({
132822
- predictedDefects: [
132823
- {
132824
- file: `${payload.target}/complex-module.ts`,
132825
- probability: 0.78,
132826
- reason: "High cyclomatic complexity combined with low test coverage"
132827
- },
132828
- {
132829
- file: `${payload.target}/legacy-handler.ts`,
132830
- probability: 0.65,
132831
- reason: "Frequent changes in recent commits with error-prone patterns"
133653
+ try {
133654
+ const targetPath = payload.target || process.cwd();
133655
+ const minConfidence = payload.minConfidence || 0.5;
133656
+ const sourceFiles = await discoverSourceFiles(targetPath, { includeTests: false });
133657
+ if (sourceFiles.length === 0) {
133658
+ return ok({
133659
+ predictedDefects: [],
133660
+ riskScore: 0,
133661
+ recommendations: [
133662
+ `No source files found in ${targetPath}. Ensure the path contains source code files.`
133663
+ ],
133664
+ warning: `No source files found in ${targetPath}`,
133665
+ filesAnalyzed: 0
133666
+ });
133667
+ }
133668
+ const predictedDefects = [];
133669
+ for (const filePath of sourceFiles) {
133670
+ try {
133671
+ const content = await fs15.readFile(filePath, "utf-8");
133672
+ const lines = content.split("\n");
133673
+ const lineCount = lines.length;
133674
+ let probability = 0;
133675
+ const reasons = [];
133676
+ if (lineCount > 500) {
133677
+ probability += 0.25;
133678
+ reasons.push(`Large file (${lineCount} lines)`);
133679
+ } else if (lineCount > 300) {
133680
+ probability += 0.15;
133681
+ reasons.push(`Medium-large file (${lineCount} lines)`);
133682
+ }
133683
+ const branchKeywords = content.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g) || [];
133684
+ const branchDensity = branchKeywords.length / Math.max(lineCount, 1);
133685
+ if (branchDensity > 0.15) {
133686
+ probability += 0.25;
133687
+ reasons.push(`High branch density (${branchKeywords.length} branches in ${lineCount} lines)`);
133688
+ } else if (branchDensity > 0.08) {
133689
+ probability += 0.1;
133690
+ reasons.push("Moderate branch complexity");
133691
+ }
133692
+ const maxIndent = Math.max(...lines.map((l75) => {
133693
+ const match = l75.match(/^(\s*)/);
133694
+ return match ? match[1].length : 0;
133695
+ }));
133696
+ if (maxIndent > 20) {
133697
+ probability += 0.15;
133698
+ reasons.push("Deep nesting detected");
133699
+ }
133700
+ const debtComments = (content.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi) || []).length;
133701
+ if (debtComments > 3) {
133702
+ probability += 0.15;
133703
+ reasons.push(`${debtComments} technical debt markers`);
133704
+ }
133705
+ const functionStarts = (content.match(/\b(function|def|func|async)\b/g) || []).length;
133706
+ if (functionStarts > 0 && lineCount / functionStarts > 80) {
133707
+ probability += 0.1;
133708
+ reasons.push("Potentially long functions");
133709
+ }
133710
+ probability = Math.min(probability, 0.95);
133711
+ if (probability >= minConfidence) {
133712
+ const relativePath = filePath.startsWith(targetPath) ? filePath.slice(targetPath.length).replace(/^\//, "") : filePath;
133713
+ predictedDefects.push({
133714
+ file: relativePath,
133715
+ probability: Math.round(probability * 100) / 100,
133716
+ reason: reasons.join("; ")
133717
+ });
133718
+ }
133719
+ } catch {
132832
133720
  }
132833
- ],
132834
- riskScore: 42,
132835
- recommendations: [
132836
- "Add integration tests for complex-module.ts",
132837
- "Refactor legacy-handler.ts to reduce complexity"
132838
- ]
132839
- });
133721
+ }
133722
+ predictedDefects.sort((a37, b68) => b68.probability - a37.probability);
133723
+ const avgProb = predictedDefects.length > 0 ? predictedDefects.reduce((sum, d74) => sum + d74.probability, 0) / predictedDefects.length : 0;
133724
+ const riskScore = Math.round(avgProb * 100);
133725
+ const recommendations = [];
133726
+ if (predictedDefects.length > 0) {
133727
+ recommendations.push(`${predictedDefects.length} files flagged for potential defects out of ${sourceFiles.length} analyzed`);
133728
+ const topFile = predictedDefects[0];
133729
+ recommendations.push(`Highest risk: ${topFile.file} (${Math.round(topFile.probability * 100)}%) \u2014 ${topFile.reason}`);
133730
+ }
133731
+ if (predictedDefects.some((d74) => d74.reason.includes("Large file"))) {
133732
+ recommendations.push("Consider splitting large files to reduce complexity");
133733
+ }
133734
+ if (predictedDefects.some((d74) => d74.reason.includes("technical debt"))) {
133735
+ recommendations.push("Address TODO/FIXME comments to reduce technical debt");
133736
+ }
133737
+ if (predictedDefects.length === 0) {
133738
+ recommendations.push("No files exceeded the defect probability threshold \u2014 code looks healthy");
133739
+ }
133740
+ return ok({
133741
+ predictedDefects: predictedDefects.slice(0, 20),
133742
+ // Top 20
133743
+ riskScore,
133744
+ recommendations,
133745
+ filesAnalyzed: sourceFiles.length
133746
+ });
133747
+ } catch (error) {
133748
+ return err(toError(error));
133749
+ }
132840
133750
  });
132841
133751
  this.taskHandlers.set("validate-requirements", async (task) => {
132842
133752
  const payload = task.payload;
@@ -137056,50 +137966,54 @@ var coverageAnalyzeConfig = {
137056
137966
  const learning = generateV2LearningFeedback("coverage-analyzer");
137057
137967
  const detailedGaps = gaps.map((gap, i58) => {
137058
137968
  const g67 = gap;
137969
+ if (!g67?.file) return null;
137059
137970
  return {
137060
137971
  id: `gap-${Date.now()}-${i58}`,
137061
- file: g67?.file || `src/module${i58}.ts`,
137062
- line: g67?.lines?.[0] || 10 + i58 * 5,
137063
- uncoveredLines: g67?.lines || [10 + i58 * 5, 20 + i58 * 5],
137064
- type: g67?.type || "uncovered-line",
137065
- severity: g67?.severity || (i58 < 2 ? "high" : "medium"),
137066
- reason: g67?.reason || "Missing test case",
137067
- priority: g67?.priority || (i58 < 2 ? "high" : "medium"),
137068
- suggestion: g67?.suggestedTest || `Add test for line ${10 + i58 * 5}`,
137069
- suggestedTest: g67?.suggestedTest || `Add test for line ${10 + i58 * 5}`,
137070
- riskScore: g67?.riskScore || 0.8 - i58 * 0.1,
137071
- confidence: g67?.confidence || 0.85
137972
+ file: g67.file,
137973
+ line: g67.lines?.[0] || 0,
137974
+ uncoveredLines: g67.lines || [],
137975
+ type: g67.type || "uncovered-line",
137976
+ severity: g67.severity || "medium",
137977
+ reason: g67.reason || "Missing test case",
137978
+ priority: g67.priority || "medium",
137979
+ suggestion: g67.suggestedTest || "Add test coverage",
137980
+ suggestedTest: g67.suggestedTest || "Add test coverage",
137981
+ riskScore: g67.riskScore || 0.5,
137982
+ confidence: g67.confidence || 0.7
137072
137983
  };
137073
- });
137074
- return {
137075
- // V2-compatible fields
137076
- coverageByFile: Array.from({ length: totalFiles }, (_56, i58) => {
137077
- const variation = (i58 % 3 - 1) * 5;
137078
- return {
137079
- file: `src/module${i58}.ts`,
137080
- lineCoverage: Math.max(0, Math.min(100, lineCoverage + variation)),
137081
- branchCoverage: Math.max(0, Math.min(100, branchCoverage + variation - 2)),
137082
- functionCoverage: Math.max(0, Math.min(100, functionCoverage + variation + 2))
137083
- };
137084
- }),
137984
+ }).filter((g67) => g67 !== null);
137985
+ const coverageByFileData = data.coverageByFile;
137986
+ const realCoverageByFile = coverageByFileData ? coverageByFileData.map((f74) => ({
137987
+ file: f74.file,
137988
+ lineCoverage: f74.lineCoverage || 0,
137989
+ branchCoverage: f74.branchCoverage || 0,
137990
+ functionCoverage: f74.functionCoverage || 0
137991
+ })) : [];
137992
+ return {
137993
+ // V2-compatible fields — only real data, no synthetic file paths
137994
+ coverageByFile: realCoverageByFile,
137085
137995
  gapAnalysis: {
137086
137996
  totalGaps: detailedGaps.length,
137087
137997
  highPriority: detailedGaps.filter((g67) => g67.priority === "high").length,
137088
137998
  gaps: detailedGaps
137089
137999
  },
137090
138000
  trends: {
137091
- lineCoverageTrend: "stable",
137092
- branchCoverageTrend: "improving",
137093
- weeklyChange: 2.5
138001
+ lineCoverageTrend: totalFiles > 0 ? "stable" : "no-data",
138002
+ branchCoverageTrend: totalFiles > 0 ? "stable" : "no-data",
138003
+ weeklyChange: 0
137094
138004
  },
137095
- aiInsights: {
137096
- recommendations: [
137097
- "Focus on uncovered branches in authentication module",
137098
- "Add edge case tests for error handling paths",
137099
- "Consider property-based testing for utility functions"
138005
+ aiInsights: totalFiles > 0 ? {
138006
+ recommendations: data.recommendations || [
138007
+ "Run tests with coverage enabled to get accurate metrics"
137100
138008
  ],
137101
138009
  riskAssessment: lineCoverage < 70 ? "high" : lineCoverage < 85 ? "medium" : "low",
137102
138010
  confidence: 0.88
138011
+ } : {
138012
+ recommendations: [
138013
+ "No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"
138014
+ ],
138015
+ riskAssessment: "unknown",
138016
+ confidence: 0
137103
138017
  },
137104
138018
  learning,
137105
138019
  // V3 fields
@@ -152819,14 +153733,22 @@ async function handleTaskOrchestrate(params) {
152819
153733
  }
152820
153734
  const { queen, workflowOrchestrator } = getFleetState();
152821
153735
  try {
153736
+ const inferredDomain = params.context?.project || inferDomainFromDescription(params.task);
153737
+ const inferredIsCritical = params.priority === "critical" || /\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(params.task);
152822
153738
  const router = await getTaskRouter();
152823
153739
  const routingResult = await router.routeTask({
152824
153740
  task: params.task,
152825
153741
  codeContext: params.codeContext,
152826
153742
  filePaths: params.filePaths,
152827
153743
  manualTier: params.manualTier,
152828
- isCritical: params.priority === "critical",
152829
- domain: params.context?.project
153744
+ isCritical: inferredIsCritical,
153745
+ agentType: `qe-${inferredDomain}`,
153746
+ domain: inferredDomain,
153747
+ metadata: {
153748
+ inferredDomain,
153749
+ hasCodeContext: !!params.codeContext,
153750
+ fileCount: params.filePaths?.length
153751
+ }
152830
153752
  });
152831
153753
  const reasoningBankService = await getReasoningBankService();
152832
153754
  const experienceGuidance = await reasoningBankService.getExperienceGuidance(
@@ -152964,14 +153886,22 @@ async function handleTaskOrchestrate(params) {
152964
153886
  async function handleModelRoute(params) {
152965
153887
  try {
152966
153888
  const router = await getTaskRouter();
153889
+ const inferredDomain = params.domain || inferDomainFromDescription(params.task);
153890
+ const inferredIsCritical = params.isCritical ?? /\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(params.task);
152967
153891
  const result = await router.routeTask({
152968
153892
  task: params.task,
152969
153893
  codeContext: params.codeContext,
152970
153894
  filePaths: params.filePaths,
152971
153895
  manualTier: params.manualTier,
152972
- isCritical: params.isCritical,
152973
- agentType: params.agentType,
152974
- domain: params.domain
153896
+ isCritical: inferredIsCritical,
153897
+ agentType: params.agentType || `qe-${inferredDomain}`,
153898
+ domain: inferredDomain,
153899
+ // Pass metadata to help the complexity analyzer
153900
+ metadata: {
153901
+ inferredDomain,
153902
+ hasCodeContext: !!params.codeContext,
153903
+ fileCount: params.filePaths?.length
153904
+ }
152975
153905
  });
152976
153906
  return {
152977
153907
  success: true,
@@ -153034,6 +153964,43 @@ async function handleRoutingMetrics(params) {
153034
153964
  };
153035
153965
  }
153036
153966
  }
153967
+ function inferDomainFromDescription(description) {
153968
+ const lower = description.toLowerCase();
153969
+ if (/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(lower)) {
153970
+ return "security-compliance";
153971
+ }
153972
+ if (/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(lower)) {
153973
+ return "chaos-resilience";
153974
+ }
153975
+ if (/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(lower)) {
153976
+ return "defect-intelligence";
153977
+ }
153978
+ if (/\b(coverage|uncovered|gap.?analy)\b/.test(lower)) {
153979
+ return "coverage-analysis";
153980
+ }
153981
+ if (/\b(quality|code.?review|maintain|tech.?debt)\b/.test(lower)) {
153982
+ return "quality-assessment";
153983
+ }
153984
+ if (/\b(contract|api.?compat|breaking.?change|pact)\b/.test(lower)) {
153985
+ return "contract-testing";
153986
+ }
153987
+ if (/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(lower)) {
153988
+ return "code-intelligence";
153989
+ }
153990
+ if (/\b(accessib|a11y|wcag|screen.?read)\b/.test(lower)) {
153991
+ return "visual-accessibility";
153992
+ }
153993
+ if (/\b(requirement|bdd|acceptance|user.?stor)\b/.test(lower)) {
153994
+ return "requirements-validation";
153995
+ }
153996
+ if (/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(lower)) {
153997
+ return "test-generation";
153998
+ }
153999
+ if (/\b(run.*test|execut.*test)\b/.test(lower)) {
154000
+ return "test-execution";
154001
+ }
154002
+ return "test-generation";
154003
+ }
153037
154004
  function inferTaskType(description) {
153038
154005
  const lower = description.toLowerCase();
153039
154006
  if (/run\s+(?:\w+\s+)*tests?/.test(lower) || /execute\s+(?:\w+\s+)*tests?/.test(lower) || lower.includes("run tests") || lower.includes("execute tests")) {
@@ -154793,7 +155760,18 @@ var MCPProtocolServer = class {
154793
155760
  async start() {
154794
155761
  await initializeConnectionPool();
154795
155762
  this.transport.onRequest(async (request) => {
154796
- return this.handleRequest(request);
155763
+ try {
155764
+ return await this.handleRequest(request);
155765
+ } catch (err4) {
155766
+ const message = err4 instanceof Error ? err4.message : String(err4);
155767
+ console.error(`[MCP] Unhandled error in request handler: ${message}`);
155768
+ return {
155769
+ content: [{
155770
+ type: "text",
155771
+ text: JSON.stringify({ success: false, error: `Internal error: ${message}` })
155772
+ }]
155773
+ };
155774
+ }
154797
155775
  });
154798
155776
  this.transport.onNotification(async (notification) => {
154799
155777
  await this.handleNotification(notification);