agentic-qe 3.7.21 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +4 -1
  2. package/.claude/helpers/statusline-v3.cjs +3 -1
  3. package/.claude/skills/skills-manifest.json +1 -1
  4. package/CHANGELOG.md +45 -0
  5. package/README.md +2 -14
  6. package/assets/helpers/statusline-v3.cjs +3 -1
  7. package/dist/cli/brain-commands.js +6 -10
  8. package/dist/cli/bundle.js +7441 -4327
  9. package/dist/cli/commands/audit.d.ts +43 -0
  10. package/dist/cli/commands/audit.js +125 -0
  11. package/dist/cli/commands/hooks.js +29 -6
  12. package/dist/cli/commands/init.js +1 -73
  13. package/dist/cli/commands/learning.js +270 -13
  14. package/dist/cli/commands/ruvector-commands.d.ts +15 -0
  15. package/dist/cli/commands/ruvector-commands.js +271 -0
  16. package/dist/cli/handlers/init-handler.d.ts +0 -1
  17. package/dist/cli/handlers/init-handler.js +0 -6
  18. package/dist/cli/index.js +4 -2
  19. package/dist/context/sources/defect-source.js +2 -2
  20. package/dist/context/sources/memory-source.js +2 -2
  21. package/dist/context/sources/requirements-source.js +2 -2
  22. package/dist/coordination/behavior-tree/decorators.d.ts +108 -0
  23. package/dist/coordination/behavior-tree/decorators.js +251 -0
  24. package/dist/coordination/behavior-tree/index.d.ts +12 -0
  25. package/dist/coordination/behavior-tree/index.js +15 -0
  26. package/dist/coordination/behavior-tree/nodes.d.ts +165 -0
  27. package/dist/coordination/behavior-tree/nodes.js +338 -0
  28. package/dist/coordination/behavior-tree/qe-trees.d.ts +105 -0
  29. package/dist/coordination/behavior-tree/qe-trees.js +181 -0
  30. package/dist/coordination/coherence-action-gate.d.ts +284 -0
  31. package/dist/coordination/coherence-action-gate.js +512 -0
  32. package/dist/coordination/index.d.ts +4 -0
  33. package/dist/coordination/index.js +8 -0
  34. package/dist/coordination/reasoning-qec.d.ts +315 -0
  35. package/dist/coordination/reasoning-qec.js +585 -0
  36. package/dist/coordination/task-executor.d.ts +16 -0
  37. package/dist/coordination/task-executor.js +99 -0
  38. package/dist/coordination/workflow-orchestrator.d.ts +29 -0
  39. package/dist/coordination/workflow-orchestrator.js +42 -0
  40. package/dist/domains/visual-accessibility/cnn-visual-regression.d.ts +135 -0
  41. package/dist/domains/visual-accessibility/cnn-visual-regression.js +327 -0
  42. package/dist/domains/visual-accessibility/index.d.ts +1 -0
  43. package/dist/domains/visual-accessibility/index.js +4 -0
  44. package/dist/governance/coherence-validator.d.ts +112 -0
  45. package/dist/governance/coherence-validator.js +180 -0
  46. package/dist/governance/index.d.ts +1 -0
  47. package/dist/governance/index.js +2 -0
  48. package/dist/governance/witness-chain.d.ts +311 -0
  49. package/dist/governance/witness-chain.js +509 -0
  50. package/dist/init/index.d.ts +0 -2
  51. package/dist/init/index.js +0 -1
  52. package/dist/init/init-wizard-steps.d.ts +10 -0
  53. package/dist/init/init-wizard-steps.js +87 -1
  54. package/dist/init/init-wizard.d.ts +1 -9
  55. package/dist/init/init-wizard.js +3 -69
  56. package/dist/init/orchestrator.js +0 -1
  57. package/dist/init/phases/01-detection.js +0 -27
  58. package/dist/init/phases/07-hooks.js +6 -4
  59. package/dist/init/phases/phase-interface.d.ts +0 -1
  60. package/dist/init/settings-merge.js +1 -1
  61. package/dist/integrations/browser/qe-dashboard/clustering.d.ts +48 -0
  62. package/dist/integrations/browser/qe-dashboard/clustering.js +183 -0
  63. package/dist/integrations/browser/qe-dashboard/index.d.ts +12 -0
  64. package/dist/integrations/browser/qe-dashboard/index.js +15 -0
  65. package/dist/integrations/browser/qe-dashboard/pattern-explorer.d.ts +165 -0
  66. package/dist/integrations/browser/qe-dashboard/pattern-explorer.js +260 -0
  67. package/dist/integrations/browser/qe-dashboard/wasm-vector-store.d.ts +144 -0
  68. package/dist/integrations/browser/qe-dashboard/wasm-vector-store.js +277 -0
  69. package/dist/integrations/ruvector/cognitive-container-codec.d.ts +51 -0
  70. package/dist/integrations/ruvector/cognitive-container-codec.js +180 -0
  71. package/dist/integrations/ruvector/cognitive-container.d.ts +125 -0
  72. package/dist/integrations/ruvector/cognitive-container.js +306 -0
  73. package/dist/integrations/ruvector/coherence-gate.d.ts +309 -0
  74. package/dist/integrations/ruvector/coherence-gate.js +631 -0
  75. package/dist/integrations/ruvector/compressed-hnsw-integration.d.ts +176 -0
  76. package/dist/integrations/ruvector/compressed-hnsw-integration.js +301 -0
  77. package/dist/integrations/ruvector/dither-adapter.d.ts +122 -0
  78. package/dist/integrations/ruvector/dither-adapter.js +295 -0
  79. package/dist/integrations/ruvector/domain-transfer.d.ts +129 -0
  80. package/dist/integrations/ruvector/domain-transfer.js +220 -0
  81. package/dist/integrations/ruvector/feature-flags.d.ts +214 -2
  82. package/dist/integrations/ruvector/feature-flags.js +167 -2
  83. package/dist/integrations/ruvector/filter-adapter.d.ts +71 -0
  84. package/dist/integrations/ruvector/filter-adapter.js +285 -0
  85. package/dist/integrations/ruvector/gnn-wrapper.d.ts +20 -0
  86. package/dist/integrations/ruvector/gnn-wrapper.js +40 -0
  87. package/dist/integrations/ruvector/hnsw-health-monitor.d.ts +237 -0
  88. package/dist/integrations/ruvector/hnsw-health-monitor.js +394 -0
  89. package/dist/integrations/ruvector/index.d.ts +8 -2
  90. package/dist/integrations/ruvector/index.js +18 -2
  91. package/dist/integrations/ruvector/interfaces.d.ts +40 -0
  92. package/dist/integrations/ruvector/sona-persistence.d.ts +54 -0
  93. package/dist/integrations/ruvector/sona-persistence.js +162 -0
  94. package/dist/integrations/ruvector/sona-three-loop.d.ts +392 -0
  95. package/dist/integrations/ruvector/sona-three-loop.js +814 -0
  96. package/dist/integrations/ruvector/sona-wrapper.d.ts +97 -0
  97. package/dist/integrations/ruvector/sona-wrapper.js +147 -3
  98. package/dist/integrations/ruvector/spectral-math.d.ts +101 -0
  99. package/dist/integrations/ruvector/spectral-math.js +254 -0
  100. package/dist/integrations/ruvector/temporal-compression.d.ts +163 -0
  101. package/dist/integrations/ruvector/temporal-compression.js +318 -0
  102. package/dist/integrations/ruvector/thompson-sampler.d.ts +61 -0
  103. package/dist/integrations/ruvector/thompson-sampler.js +118 -0
  104. package/dist/integrations/ruvector/transfer-coherence-stub.d.ts +80 -0
  105. package/dist/integrations/ruvector/transfer-coherence-stub.js +63 -0
  106. package/dist/integrations/ruvector/transfer-verification.d.ts +119 -0
  107. package/dist/integrations/ruvector/transfer-verification.js +115 -0
  108. package/dist/kernel/hnsw-adapter.d.ts +52 -1
  109. package/dist/kernel/hnsw-adapter.js +139 -4
  110. package/dist/kernel/hnsw-index-provider.d.ts +5 -0
  111. package/dist/kernel/native-hnsw-backend.d.ts +110 -0
  112. package/dist/kernel/native-hnsw-backend.js +408 -0
  113. package/dist/kernel/unified-memory.js +5 -6
  114. package/dist/learning/aqe-learning-engine.d.ts +2 -0
  115. package/dist/learning/aqe-learning-engine.js +65 -0
  116. package/dist/learning/experience-capture-middleware.js +20 -0
  117. package/dist/learning/experience-capture.d.ts +10 -0
  118. package/dist/learning/experience-capture.js +34 -0
  119. package/dist/learning/index.d.ts +2 -2
  120. package/dist/learning/index.js +4 -4
  121. package/dist/learning/metrics-tracker.d.ts +11 -0
  122. package/dist/learning/metrics-tracker.js +29 -13
  123. package/dist/learning/pattern-lifecycle.d.ts +30 -1
  124. package/dist/learning/pattern-lifecycle.js +92 -20
  125. package/dist/learning/pattern-store.d.ts +8 -0
  126. package/dist/learning/pattern-store.js +8 -2
  127. package/dist/learning/qe-unified-memory.js +1 -28
  128. package/dist/learning/regret-tracker.d.ts +201 -0
  129. package/dist/learning/regret-tracker.js +361 -0
  130. package/dist/mcp/bundle.js +5915 -474
  131. package/dist/routing/index.d.ts +4 -2
  132. package/dist/routing/index.js +3 -1
  133. package/dist/routing/neural-tiny-dancer-router.d.ts +268 -0
  134. package/dist/routing/neural-tiny-dancer-router.js +514 -0
  135. package/dist/routing/queen-integration.js +5 -5
  136. package/dist/routing/routing-config.d.ts +6 -0
  137. package/dist/routing/routing-config.js +1 -0
  138. package/dist/routing/simple-neural-router.d.ts +76 -0
  139. package/dist/routing/simple-neural-router.js +202 -0
  140. package/dist/routing/tiny-dancer-router.d.ts +20 -1
  141. package/dist/routing/tiny-dancer-router.js +21 -2
  142. package/dist/test-scheduling/dag-attention-scheduler.d.ts +81 -0
  143. package/dist/test-scheduling/dag-attention-scheduler.js +358 -0
  144. package/dist/test-scheduling/dag-attention-types.d.ts +81 -0
  145. package/dist/test-scheduling/dag-attention-types.js +10 -0
  146. package/dist/test-scheduling/index.d.ts +1 -0
  147. package/dist/test-scheduling/index.js +4 -0
  148. package/dist/test-scheduling/pipeline.d.ts +8 -0
  149. package/dist/test-scheduling/pipeline.js +28 -0
  150. package/package.json +6 -2
  151. package/dist/cli/commands/migrate.d.ts +0 -9
  152. package/dist/cli/commands/migrate.js +0 -566
  153. package/dist/init/init-wizard-migration.d.ts +0 -52
  154. package/dist/init/init-wizard-migration.js +0 -345
  155. package/dist/init/migration/config-migrator.d.ts +0 -31
  156. package/dist/init/migration/config-migrator.js +0 -149
  157. package/dist/init/migration/data-migrator.d.ts +0 -72
  158. package/dist/init/migration/data-migrator.js +0 -232
  159. package/dist/init/migration/detector.d.ts +0 -44
  160. package/dist/init/migration/detector.js +0 -105
  161. package/dist/init/migration/index.d.ts +0 -8
  162. package/dist/init/migration/index.js +0 -8
  163. package/dist/learning/v2-to-v3-migration.d.ts +0 -86
  164. package/dist/learning/v2-to-v3-migration.js +0 -529
@@ -6,16 +6,15 @@
6
6
  *
7
7
  * This is a facade module. Implementation details are extracted to:
8
8
  * - init-wizard-hooks.ts (hook configuration, MCP, CLAUDE.md generation)
9
- * - init-wizard-migration.ts (V2 detection, migration, config conversion)
10
- * - init-wizard-steps.ts (persistence, learning, workers, skills, agents, config)
9
+ * - init-wizard-steps.ts (persistence, learning, workers, skills, agents, config, version)
11
10
  */
12
11
  import { createDefaultConfig } from './types.js';
13
12
  import { createProjectAnalyzer } from './project-analyzer.js';
14
13
  import { createSelfConfigurator } from './self-configurator.js';
15
- import { detectV2Installation, runV2Migration, writeVersionToDb, } from './init-wizard-migration.js';
14
+ // Import from extracted modules
16
15
  import { configureHooks, configureMCP, generateCLAUDEmd, } from './init-wizard-hooks.js';
17
16
  import { toErrorMessage } from '../shared/error-utils.js';
18
- import { initializePersistenceDatabase, checkCodeIntelligenceIndex, runCodeIntelligenceScan, getKGEntryCount, initializeLearningSystem, startWorkers, installSkills, installAgents, installN8n, saveConfig, } from './init-wizard-steps.js';
17
+ import { initializePersistenceDatabase, checkCodeIntelligenceIndex, runCodeIntelligenceScan, getKGEntryCount, initializeLearningSystem, startWorkers, installSkills, installAgents, installN8n, saveConfig, writeVersionToDb, } from './init-wizard-steps.js';
19
18
  // ============================================================================
20
19
  // Wizard Step Definitions
21
20
  // ============================================================================
@@ -105,13 +104,6 @@ export class InitOrchestrator {
105
104
  async initialize() {
106
105
  const startTime = Date.now();
107
106
  try {
108
- // Step 0: Check for existing v2 installation
109
- const v2Detection = await detectV2Installation(this.projectRoot);
110
- if (v2Detection.detected) {
111
- const earlyResult = this.handleV2Detection(v2Detection, startTime);
112
- if (earlyResult)
113
- return earlyResult;
114
- }
115
107
  // Step 1: Analyze project
116
108
  const analysis = await this.runStep('Project Analysis', async () => {
117
109
  return await this.analyzer.analyze();
@@ -251,64 +243,6 @@ export class InitOrchestrator {
251
243
  getWizardSteps() {
252
244
  return WIZARD_STEPS;
253
245
  }
254
- /**
255
- * Handle V2 detection - returns early result if migration not auto, null otherwise.
256
- */
257
- handleV2Detection(v2Detection, startTime) {
258
- console.log('\n' + '='.repeat(60));
259
- console.log(' EXISTING V2 INSTALLATION DETECTED');
260
- console.log('='.repeat(60) + '\n');
261
- console.log('Found v2 installation at:');
262
- if (v2Detection.hasMemoryDb) {
263
- console.log(` - Memory DB: .agentic-qe/memory.db`);
264
- }
265
- if (v2Detection.hasConfig) {
266
- console.log(` - Config: .agentic-qe/config/`);
267
- }
268
- if (v2Detection.hasAgents) {
269
- console.log(` - Agents: .claude/agents/`);
270
- }
271
- console.log('');
272
- if (this.options.autoMigrate) {
273
- console.log('Auto-migrate mode enabled. Running migration...\n');
274
- // Fire and forget - the caller will await initialize() which runs migration inline
275
- runV2Migration(this.projectRoot, v2Detection).catch((e) => { console.warn('[InitWizard] V2 migration failed:', e instanceof Error ? e.message : e); });
276
- return null;
277
- }
278
- // Warn and suggest migration
279
- console.log('RECOMMENDED: Run migration before init:\n');
280
- console.log(' npx aqe migrate status # Check what needs migration');
281
- console.log(' npx aqe migrate run --dry-run # Preview changes');
282
- console.log(' npx aqe migrate run # Execute migration\n');
283
- console.log('Or continue with:');
284
- console.log(' aqe init --auto-migrate # Auto-migrate during init\n');
285
- console.log('='.repeat(60) + '\n');
286
- return {
287
- success: false,
288
- config: createDefaultConfig('unknown', this.projectRoot),
289
- steps: [{
290
- step: 'V2 Detection',
291
- status: 'error',
292
- message: 'Existing v2 installation detected. Run migration first.',
293
- durationMs: Date.now() - startTime,
294
- }],
295
- summary: {
296
- projectAnalyzed: false,
297
- configGenerated: false,
298
- codeIntelligenceIndexed: 0,
299
- patternsLoaded: 0,
300
- skillsInstalled: 0,
301
- agentsInstalled: 0,
302
- hooksConfigured: false,
303
- mcpConfigured: false,
304
- claudeMdGenerated: false,
305
- workersStarted: 0,
306
- },
307
- totalDurationMs: Date.now() - startTime,
308
- timestamp: new Date(),
309
- v2Detected: true,
310
- };
311
- }
312
246
  /**
313
247
  * Run a single initialization step with timing and status tracking
314
248
  */
@@ -32,7 +32,6 @@ export class ModularInitOrchestrator {
32
32
  upgrade: options.upgrade,
33
33
  skipPatterns: options.skipPatterns,
34
34
  minimal: options.minimal,
35
- autoMigrate: options.autoMigrate,
36
35
  withN8n: options.withN8n,
37
36
  withOpenCode: options.withOpenCode,
38
37
  withKiro: options.withKiro,
@@ -27,33 +27,6 @@ export class DetectionPhase extends BasePhase {
27
27
  const freshInstall = !v2Detected && !v3Detected;
28
28
  // Store v2 detection in context for other phases
29
29
  context.v2Detection = v2Detection;
30
- if (v2Detected && !context.options.autoMigrate) {
31
- context.services.log('');
32
- context.services.log('═'.repeat(60));
33
- context.services.log('⚠️ EXISTING V2 INSTALLATION DETECTED');
34
- context.services.log('═'.repeat(60));
35
- context.services.log('');
36
- context.services.log('Found v2 installation at:');
37
- if (v2Detection.hasMemoryDb) {
38
- context.services.log(' • Memory DB: .agentic-qe/memory.db');
39
- }
40
- if (v2Detection.hasConfig) {
41
- context.services.log(' • Config: .agentic-qe/config/');
42
- }
43
- if (v2Detection.hasAgents) {
44
- context.services.log(' • Agents: .claude/agents/');
45
- }
46
- context.services.log('');
47
- context.services.log('📋 RECOMMENDED: Run with --auto-migrate:');
48
- context.services.log(' aqe init --auto-migrate');
49
- context.services.log('');
50
- return {
51
- v2Detected: true,
52
- v3Detected,
53
- freshInstall: false,
54
- v2Detection,
55
- };
56
- }
57
30
  return {
58
31
  v2Detected,
59
32
  v3Detected,
@@ -289,13 +289,14 @@ const { execFileSync } = require('child_process');
289
289
 
290
290
  function q(bin, args, d) { try { return execFileSync(bin, args, { encoding: 'utf-8', timeout: 3000, stdio: ['pipe', 'pipe', 'pipe'] }).trim(); } catch { return d || ''; } }
291
291
 
292
- const dir = process.cwd();
292
+ const dir = path.resolve(__dirname, '..', '..');
293
293
  const dbPath = path.join(dir, '.agentic-qe', 'memory.db');
294
294
  let patterns = 0;
295
295
  try {
296
296
  if (fs.existsSync(dbPath)) {
297
297
  const Database = require('better-sqlite3');
298
298
  const db = new Database(dbPath, { readonly: true, fileMustExist: true });
299
+ db.pragma('busy_timeout = 5000');
299
300
  patterns = db.prepare('SELECT COUNT(*) AS c FROM qe_patterns').get()?.c || 0;
300
301
  db.close();
301
302
  }
@@ -325,7 +326,8 @@ const { execFileSync } = require('child_process');
325
326
  const fs = require('fs');
326
327
  const path = require('path');
327
328
 
328
- const AQE_DIR = path.join(process.cwd(), '.agentic-qe');
329
+ const PROJECT_ROOT = path.resolve(__dirname, '..', '..');
330
+ const AQE_DIR = path.join(PROJECT_ROOT, '.agentic-qe');
329
331
  const RVF_PATH = path.join(AQE_DIR, 'aqe.rvf');
330
332
  const DB_PATH = path.join(AQE_DIR, 'memory.db');
331
333
  const MAX_AGE_HOURS = 24;
@@ -496,7 +498,7 @@ if (process.argv.includes('--json')) process.stdout.write(JSON.stringify(result)
496
498
  hooks: [
497
499
  {
498
500
  type: 'command',
499
- command: 'node .claude/helpers/brain-checkpoint.cjs verify --json',
501
+ command: 'node "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.claude/helpers/brain-checkpoint.cjs" verify --json',
500
502
  timeout: 5000,
501
503
  continueOnError: true,
502
504
  },
@@ -518,7 +520,7 @@ if (process.argv.includes('--json')) process.stdout.write(JSON.stringify(result)
518
520
  hooks: [
519
521
  {
520
522
  type: 'command',
521
- command: 'node .claude/helpers/brain-checkpoint.cjs export --json',
523
+ command: 'node "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.claude/helpers/brain-checkpoint.cjs" export --json',
522
524
  timeout: 60000,
523
525
  continueOnError: true,
524
526
  },
@@ -73,7 +73,6 @@ export interface InitOptions {
73
73
  /** Minimal configuration (no skills, patterns, workers) */
74
74
  minimal?: boolean;
75
75
  /** Automatically migrate from v2 if detected */
76
- autoMigrate?: boolean;
77
76
  /** Install n8n workflow testing platform */
78
77
  withN8n?: boolean;
79
78
  /** N8n API configuration */
@@ -97,7 +97,7 @@ export function generateV3SettingsSections(config) {
97
97
  },
98
98
  statusLine: {
99
99
  type: 'command',
100
- command: 'node .claude/helpers/statusline-v3.cjs 2>/dev/null || echo "▊ Agentic QE v3"',
100
+ command: 'node "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "▊ Agentic QE v3"',
101
101
  refreshMs: 5000,
102
102
  enabled: true,
103
103
  },
@@ -0,0 +1,48 @@
1
+ /**
2
+ * K-Means Clustering and Embedding Utilities (Task 4.6)
3
+ *
4
+ * Provides K-Means clustering with K-Means++ initialization and
5
+ * deterministic pseudo-embedding generation for patterns without
6
+ * pre-computed vectors.
7
+ *
8
+ * @module integrations/browser/qe-dashboard/clustering
9
+ */
10
+ /**
11
+ * Dimension for auto-generated embeddings.
12
+ * Kept small (32) for efficiency in browser contexts.
13
+ */
14
+ export declare const EMBEDDING_DIM = 32;
15
+ /** Minimal pattern shape needed for embedding generation */
16
+ export interface EmbeddablePattern {
17
+ domain: string;
18
+ description: string;
19
+ tags?: string[];
20
+ }
21
+ /**
22
+ * Generate a deterministic pseudo-embedding from a pattern's text content.
23
+ *
24
+ * Uses a simple hash-based approach to produce a stable vector from the
25
+ * pattern's description and domain. This is a fallback when no real
26
+ * embedding model is available.
27
+ *
28
+ * @param pattern - The pattern to embed
29
+ * @returns Float32Array embedding of length EMBEDDING_DIM
30
+ */
31
+ export declare function generateEmbedding(pattern: EmbeddablePattern): Float32Array;
32
+ /**
33
+ * Generate a query embedding from a text string
34
+ */
35
+ export declare function generateQueryEmbedding(query: string): Float32Array;
36
+ /**
37
+ * K-Means clustering for Float32Array vectors.
38
+ *
39
+ * Uses K-Means++ initialization for better centroid placement,
40
+ * then iterates until convergence or maxIter is reached.
41
+ *
42
+ * @param vectors - Array of vectors to cluster
43
+ * @param k - Number of clusters
44
+ * @param maxIter - Maximum iterations (default: 50)
45
+ * @returns Array of cluster assignments (index per vector)
46
+ */
47
+ export declare function kMeansClustering(vectors: Float32Array[], k: number, maxIter?: number): number[];
48
+ //# sourceMappingURL=clustering.d.ts.map
@@ -0,0 +1,183 @@
1
+ /**
2
+ * K-Means Clustering and Embedding Utilities (Task 4.6)
3
+ *
4
+ * Provides K-Means clustering with K-Means++ initialization and
5
+ * deterministic pseudo-embedding generation for patterns without
6
+ * pre-computed vectors.
7
+ *
8
+ * @module integrations/browser/qe-dashboard/clustering
9
+ */
10
+ import { cosineSimilarity } from './wasm-vector-store.js';
11
+ // ============================================================================
12
+ // Embedding Generation
13
+ // ============================================================================
14
+ /**
15
+ * Dimension for auto-generated embeddings.
16
+ * Kept small (32) for efficiency in browser contexts.
17
+ */
18
+ export const EMBEDDING_DIM = 32;
19
+ /**
20
+ * Generate a deterministic pseudo-embedding from a pattern's text content.
21
+ *
22
+ * Uses a simple hash-based approach to produce a stable vector from the
23
+ * pattern's description and domain. This is a fallback when no real
24
+ * embedding model is available.
25
+ *
26
+ * @param pattern - The pattern to embed
27
+ * @returns Float32Array embedding of length EMBEDDING_DIM
28
+ */
29
+ export function generateEmbedding(pattern) {
30
+ const text = `${pattern.domain} ${pattern.description} ${(pattern.tags || []).join(' ')}`;
31
+ const embedding = new Float32Array(EMBEDDING_DIM);
32
+ // Simple deterministic hash-based embedding
33
+ for (let i = 0; i < text.length; i++) {
34
+ const charCode = text.charCodeAt(i);
35
+ const idx = i % EMBEDDING_DIM;
36
+ // Mix character codes using a simple multiplicative hash
37
+ embedding[idx] += Math.sin(charCode * (i + 1) * 0.1) * 0.5;
38
+ }
39
+ // Normalize to unit length
40
+ let norm = 0;
41
+ for (let i = 0; i < embedding.length; i++) {
42
+ norm += embedding[i] * embedding[i];
43
+ }
44
+ norm = Math.sqrt(norm);
45
+ if (norm > 0) {
46
+ for (let i = 0; i < embedding.length; i++) {
47
+ embedding[i] /= norm;
48
+ }
49
+ }
50
+ return embedding;
51
+ }
52
+ /**
53
+ * Generate a query embedding from a text string
54
+ */
55
+ export function generateQueryEmbedding(query) {
56
+ return generateEmbedding({
57
+ domain: '',
58
+ description: query,
59
+ });
60
+ }
61
+ // ============================================================================
62
+ // K-Means Clustering
63
+ // ============================================================================
64
+ /**
65
+ * K-Means clustering for Float32Array vectors.
66
+ *
67
+ * Uses K-Means++ initialization for better centroid placement,
68
+ * then iterates until convergence or maxIter is reached.
69
+ *
70
+ * @param vectors - Array of vectors to cluster
71
+ * @param k - Number of clusters
72
+ * @param maxIter - Maximum iterations (default: 50)
73
+ * @returns Array of cluster assignments (index per vector)
74
+ */
75
+ export function kMeansClustering(vectors, k, maxIter = 50) {
76
+ if (vectors.length === 0 || k <= 0) {
77
+ return [];
78
+ }
79
+ const n = vectors.length;
80
+ const clampedK = Math.min(k, n);
81
+ const dim = vectors[0].length;
82
+ // K-Means++ initialization
83
+ const centroids = initializeCentroids(vectors, clampedK);
84
+ const assignments = new Array(n).fill(0);
85
+ for (let iter = 0; iter < maxIter; iter++) {
86
+ let changed = false;
87
+ // Assignment step: assign each vector to the nearest centroid
88
+ for (let i = 0; i < n; i++) {
89
+ let bestCluster = 0;
90
+ let bestSim = -Infinity;
91
+ for (let c = 0; c < clampedK; c++) {
92
+ const sim = cosineSimilarity(vectors[i], centroids[c]);
93
+ if (sim > bestSim) {
94
+ bestSim = sim;
95
+ bestCluster = c;
96
+ }
97
+ }
98
+ if (assignments[i] !== bestCluster) {
99
+ assignments[i] = bestCluster;
100
+ changed = true;
101
+ }
102
+ }
103
+ // Convergence check
104
+ if (!changed) {
105
+ break;
106
+ }
107
+ // Update step: recompute centroids
108
+ for (let c = 0; c < clampedK; c++) {
109
+ const newCentroid = new Float32Array(dim);
110
+ let count = 0;
111
+ for (let i = 0; i < n; i++) {
112
+ if (assignments[i] === c) {
113
+ for (let d = 0; d < dim; d++) {
114
+ newCentroid[d] += vectors[i][d];
115
+ }
116
+ count++;
117
+ }
118
+ }
119
+ if (count > 0) {
120
+ for (let d = 0; d < dim; d++) {
121
+ newCentroid[d] /= count;
122
+ }
123
+ // Normalize centroid
124
+ let norm = 0;
125
+ for (let d = 0; d < dim; d++) {
126
+ norm += newCentroid[d] * newCentroid[d];
127
+ }
128
+ norm = Math.sqrt(norm);
129
+ if (norm > 0) {
130
+ for (let d = 0; d < dim; d++) {
131
+ newCentroid[d] /= norm;
132
+ }
133
+ }
134
+ centroids[c] = newCentroid;
135
+ }
136
+ }
137
+ }
138
+ return assignments;
139
+ }
140
+ /**
141
+ * K-Means++ initialization: select initial centroids with probability
142
+ * proportional to squared distance from nearest existing centroid.
143
+ */
144
+ function initializeCentroids(vectors, k) {
145
+ const n = vectors.length;
146
+ const centroids = [];
147
+ // Pick first centroid (deterministic: use first vector)
148
+ centroids.push(new Float32Array(vectors[0]));
149
+ for (let c = 1; c < k; c++) {
150
+ // Compute distances to nearest centroid
151
+ const distances = new Float64Array(n);
152
+ let totalDist = 0;
153
+ for (let i = 0; i < n; i++) {
154
+ let minDist = Infinity;
155
+ for (const centroid of centroids) {
156
+ const sim = cosineSimilarity(vectors[i], centroid);
157
+ const dist = 1 - sim;
158
+ if (dist < minDist) {
159
+ minDist = dist;
160
+ }
161
+ }
162
+ distances[i] = minDist * minDist; // Squared distance
163
+ totalDist += distances[i];
164
+ }
165
+ if (totalDist === 0) {
166
+ // All points identical to existing centroids; pick sequentially
167
+ centroids.push(new Float32Array(vectors[c % n]));
168
+ continue;
169
+ }
170
+ // Deterministic selection: pick the point with maximum distance
171
+ let maxIdx = 0;
172
+ let maxDist = -1;
173
+ for (let i = 0; i < n; i++) {
174
+ if (distances[i] > maxDist) {
175
+ maxDist = distances[i];
176
+ maxIdx = i;
177
+ }
178
+ }
179
+ centroids.push(new Float32Array(vectors[maxIdx]));
180
+ }
181
+ return centroids;
182
+ }
183
+ //# sourceMappingURL=clustering.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * QE Dashboard - Browser-based intelligence dashboard (Task 4.6)
3
+ *
4
+ * Provides WASM-accelerated vector storage and pattern exploration
5
+ * for visualizing QE intelligence data in the browser.
6
+ *
7
+ * @module integrations/browser/qe-dashboard
8
+ */
9
+ export { WasmVectorStore, cosineSimilarity, type SearchResult, type StoreStats, } from './wasm-vector-store.js';
10
+ export { kMeansClustering, generateEmbedding, generateQueryEmbedding, EMBEDDING_DIM, type EmbeddablePattern, } from './clustering.js';
11
+ export { PatternExplorer, type Pattern, type PatternCluster, type DomainStats, type DashboardData, } from './pattern-explorer.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * QE Dashboard - Browser-based intelligence dashboard (Task 4.6)
3
+ *
4
+ * Provides WASM-accelerated vector storage and pattern exploration
5
+ * for visualizing QE intelligence data in the browser.
6
+ *
7
+ * @module integrations/browser/qe-dashboard
8
+ */
9
+ // Vector Store
10
+ export { WasmVectorStore, cosineSimilarity, } from './wasm-vector-store.js';
11
+ // Clustering
12
+ export { kMeansClustering, generateEmbedding, generateQueryEmbedding, EMBEDDING_DIM, } from './clustering.js';
13
+ // Pattern Explorer
14
+ export { PatternExplorer, } from './pattern-explorer.js';
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Pattern Explorer for QE Dashboard (Task 4.6)
3
+ *
4
+ * Provides pattern exploration, similarity clustering, and visualization
5
+ * data preparation for the browser-based QE intelligence dashboard.
6
+ *
7
+ * Features:
8
+ * - Load and index patterns into the vector store
9
+ * - Similarity search across patterns
10
+ * - K-Means clustering for visualization
11
+ * - Domain distribution analysis
12
+ * - Health dashboard data aggregation
13
+ *
14
+ * No browser-specific APIs: works in Node.js for testing.
15
+ *
16
+ * @module integrations/browser/qe-dashboard/pattern-explorer
17
+ */
18
+ import { WasmVectorStore } from './wasm-vector-store.js';
19
+ export { kMeansClustering } from './clustering.js';
20
+ /** A QE pattern for exploration */
21
+ export interface Pattern {
22
+ /** Unique pattern identifier */
23
+ id: string;
24
+ /** Domain the pattern belongs to */
25
+ domain: string;
26
+ /** Human-readable description */
27
+ description: string;
28
+ /** Confidence score (0..1) */
29
+ confidence: number;
30
+ /** Embedding vector (optional - will be auto-generated if missing) */
31
+ embedding?: Float32Array;
32
+ /** Tags for filtering */
33
+ tags?: string[];
34
+ /** Timestamp of pattern creation */
35
+ createdAt?: number;
36
+ /** Whether the pattern was successful */
37
+ success?: boolean;
38
+ /** Additional metadata */
39
+ metadata?: Record<string, unknown>;
40
+ }
41
+ /** A cluster of similar patterns */
42
+ export interface PatternCluster {
43
+ /** Cluster index */
44
+ id: number;
45
+ /** Centroid vector of the cluster */
46
+ centroid: Float32Array;
47
+ /** Patterns assigned to this cluster */
48
+ patterns: Pattern[];
49
+ /** Dominant domain in this cluster */
50
+ dominantDomain: string;
51
+ /** Average confidence within the cluster */
52
+ avgConfidence: number;
53
+ /** Intra-cluster cohesion (average similarity to centroid) */
54
+ cohesion: number;
55
+ }
56
+ /** Statistics about a domain */
57
+ export interface DomainStats {
58
+ /** Domain name */
59
+ domain: string;
60
+ /** Number of patterns in this domain */
61
+ patternCount: number;
62
+ /** Average confidence across patterns */
63
+ avgConfidence: number;
64
+ /** Success rate (fraction of successful patterns) */
65
+ successRate: number;
66
+ /** Most recent pattern timestamp */
67
+ latestTimestamp: number;
68
+ /** Top tags in this domain */
69
+ topTags: Array<{
70
+ tag: string;
71
+ count: number;
72
+ }>;
73
+ }
74
+ /** Aggregated dashboard data */
75
+ export interface DashboardData {
76
+ /** Total number of loaded patterns */
77
+ totalPatterns: number;
78
+ /** Number of distinct domains */
79
+ domainCount: number;
80
+ /** Overall average confidence */
81
+ avgConfidence: number;
82
+ /** Overall success rate */
83
+ successRate: number;
84
+ /** Per-domain statistics */
85
+ domainStats: DomainStats[];
86
+ /** Confidence distribution histogram (10 bins) */
87
+ confidenceHistogram: number[];
88
+ /** Recent pattern activity (last 30 days if timestamps present) */
89
+ recentActivity: number;
90
+ /** Vector store statistics */
91
+ storeStats: {
92
+ totalVectors: number;
93
+ dimensions: number;
94
+ wasmActive: boolean;
95
+ memoryBytes: number;
96
+ };
97
+ }
98
+ /**
99
+ * Pattern exploration and visualization data preparation.
100
+ *
101
+ * Loads QE patterns into a vector store, provides similarity search,
102
+ * clustering, domain distribution, and aggregated dashboard data.
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * const explorer = new PatternExplorer();
107
+ * await explorer.initialize();
108
+ *
109
+ * explorer.loadPatterns(patterns);
110
+ *
111
+ * // Find similar patterns
112
+ * const similar = explorer.searchSimilar('authentication testing', 5);
113
+ *
114
+ * // Cluster for visualization
115
+ * const clusters = explorer.clusterPatterns(4);
116
+ *
117
+ * // Dashboard data
118
+ * const dashboard = explorer.getHealthDashboardData();
119
+ * ```
120
+ */
121
+ export declare class PatternExplorer {
122
+ private store;
123
+ private patterns;
124
+ private embeddings;
125
+ constructor(store?: WasmVectorStore);
126
+ /** Initialize the explorer (loads WASM backend if available) */
127
+ initialize(): Promise<void>;
128
+ /**
129
+ * Load patterns into the explorer
130
+ *
131
+ * Each pattern is embedded (using provided embedding or auto-generated)
132
+ * and indexed in the vector store for similarity search.
133
+ */
134
+ loadPatterns(patterns: Pattern[]): void;
135
+ /**
136
+ * Search for patterns similar to a text query
137
+ *
138
+ * @param query - Natural language query string
139
+ * @param k - Number of results to return
140
+ * @returns Array of matched patterns ordered by similarity
141
+ */
142
+ searchSimilar(query: string, k: number): Pattern[];
143
+ /**
144
+ * Cluster patterns into groups using K-Means
145
+ *
146
+ * @param numClusters - Number of clusters to create
147
+ * @returns Array of PatternCluster with centroid, members, and statistics
148
+ */
149
+ clusterPatterns(numClusters: number): PatternCluster[];
150
+ /** Get distribution statistics per domain */
151
+ getDomainDistribution(): DomainStats[];
152
+ /** Get aggregated health dashboard data */
153
+ getHealthDashboardData(): DashboardData;
154
+ /** Get a pattern by id */
155
+ getPattern(id: string): Pattern | undefined;
156
+ /** Get total number of loaded patterns */
157
+ get patternCount(): number;
158
+ /** Clear all patterns and reset the explorer */
159
+ clear(): void;
160
+ private buildClusters;
161
+ private computeNormalizedCentroid;
162
+ private findDominantDomain;
163
+ private computeDomainStats;
164
+ }
165
+ //# sourceMappingURL=pattern-explorer.d.ts.map