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
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Deterministic Dithering Adapter for Cross-Platform Reproducibility
3
+ *
4
+ * Provides golden-ratio quasi-random dithering for embedding quantization.
5
+ * Ensures identical quantization results across x86, ARM, and WASM platforms
6
+ * by using only deterministic integer and float arithmetic.
7
+ *
8
+ * The golden ratio sequence produces a low-discrepancy quasi-random sequence
9
+ * that distributes quantization error more evenly than truncation alone,
10
+ * improving reconstruction quality at low bit depths.
11
+ *
12
+ * @module integrations/ruvector/dither-adapter
13
+ */
14
+ // ============================================================================
15
+ // Constants
16
+ // ============================================================================
17
+ /** Golden ratio: phi = (1 + sqrt(5)) / 2 */
18
+ const PHI = (1 + Math.sqrt(5)) / 2; // 1.618033988749895
19
+ /** Inverse golden ratio: 1/phi = phi - 1 */
20
+ const PHI_INV = 1 / PHI; // 0.6180339887498949
21
+ // ============================================================================
22
+ // Native binding status
23
+ // No native package exists for dithering — the TypeScript implementation
24
+ // below IS the production implementation (pure math, no native benefit).
25
+ // ============================================================================
26
+ /**
27
+ * Check if a native dither module is available.
28
+ * Always returns false — the TypeScript implementation is production-ready.
29
+ */
30
+ export function isNativeDitherAvailable() {
31
+ return false;
32
+ }
33
+ // ============================================================================
34
+ // Core Dither Sequence Generation
35
+ // ============================================================================
36
+ /**
37
+ * Create a deterministic quasi-random dither sequence using the golden ratio.
38
+ *
39
+ * The sequence d_n = frac((seed + (n+1) * phi)) produces values uniformly
40
+ * distributed in [0, 1) with low discrepancy (no clumping). This is a
41
+ * Weyl sequence / additive recurrence, which is deterministic and
42
+ * platform-independent since it uses only standard IEEE 754 arithmetic.
43
+ *
44
+ * @param length - Number of dither values to generate
45
+ * @param seed - Starting offset for the sequence (default: 0)
46
+ * @returns Float32Array of dither values in [0, 1)
47
+ */
48
+ export function createDitherSequence(length, seed = 0) {
49
+ if (length < 0 || !Number.isFinite(length)) {
50
+ throw new Error(`Invalid dither sequence length: ${length}`);
51
+ }
52
+ if (!Number.isFinite(seed)) {
53
+ throw new Error(`Invalid dither seed: ${seed}`);
54
+ }
55
+ const sequence = new Float32Array(length);
56
+ // Map the integer seed into a fractional offset using the inverse golden ratio.
57
+ // This ensures different integer seeds produce genuinely different sequences,
58
+ // since a raw integer seed would be discarded by the modulo-1 operation.
59
+ const base = (seed * PHI_INV % 1 + 1) % 1;
60
+ for (let i = 0; i < length; i++) {
61
+ // Quasi-random sequence using golden ratio additive recurrence
62
+ // The double modulo ensures the result is always in [0, 1)
63
+ sequence[i] = ((base + (i + 1) * PHI) % 1 + 1) % 1;
64
+ }
65
+ return sequence;
66
+ }
67
+ // ============================================================================
68
+ // Quantization with Dithering
69
+ // ============================================================================
70
+ /**
71
+ * Apply deterministic dithered quantization to a float vector.
72
+ *
73
+ * The algorithm:
74
+ * 1. Compute the range [min, max] of the input vector.
75
+ * 2. Compute step_size = range / (2^bitDepth - 1).
76
+ * 3. Generate a golden-ratio dither sequence of the same length.
77
+ * 4. For each element: quantized[i] = clamp(round((value[i] - min) / stepSize + (dither[i] - 0.5)), 0, maxLevel)
78
+ * 5. Dequantize: dequantized[i] = quantized[i] * stepSize + min
79
+ *
80
+ * The dither offset (dither[i] - 0.5) centers the dither noise around zero,
81
+ * which reduces systematic bias compared to truncation-only quantization.
82
+ *
83
+ * @param vector - Input float vector to quantize
84
+ * @param bitDepth - Number of bits for quantization (1-32)
85
+ * @param seed - Seed for dither sequence reproducibility (default: 0)
86
+ * @returns DitheredResult with quantized and reconstructed values
87
+ */
88
+ export function applyDither(vector, bitDepth, seed = 0) {
89
+ if (!(vector instanceof Float32Array)) {
90
+ throw new Error('Input vector must be a Float32Array');
91
+ }
92
+ if (vector.length === 0) {
93
+ return {
94
+ quantized: new Int32Array(0),
95
+ dequantized: new Float32Array(0),
96
+ bitDepth,
97
+ seed,
98
+ stepSize: 0,
99
+ minValue: 0,
100
+ maxValue: 0,
101
+ };
102
+ }
103
+ if (bitDepth < 1 || bitDepth > 32 || !Number.isInteger(bitDepth)) {
104
+ throw new Error(`Invalid bit depth: ${bitDepth}. Must be an integer in [1, 32].`);
105
+ }
106
+ // Compute value range
107
+ let minValue = vector[0];
108
+ let maxValue = vector[0];
109
+ for (let i = 1; i < vector.length; i++) {
110
+ if (vector[i] < minValue)
111
+ minValue = vector[i];
112
+ if (vector[i] > maxValue)
113
+ maxValue = vector[i];
114
+ }
115
+ // Number of quantization levels
116
+ const maxLevel = (1 << bitDepth) - 1; // 2^bitDepth - 1
117
+ // Handle constant vector (all values the same)
118
+ const range = maxValue - minValue;
119
+ const stepSize = range === 0 ? 1 : range / maxLevel;
120
+ // Generate dither sequence
121
+ const dither = createDitherSequence(vector.length, seed);
122
+ // Quantize with dithering
123
+ const quantized = new Int32Array(vector.length);
124
+ const dequantized = new Float32Array(vector.length);
125
+ for (let i = 0; i < vector.length; i++) {
126
+ if (range === 0) {
127
+ // Constant vector: all quantize to middle level
128
+ quantized[i] = Math.round(maxLevel / 2);
129
+ }
130
+ else {
131
+ // Normalize to [0, maxLevel], add centered dither, round, and clamp
132
+ const normalized = (vector[i] - minValue) / stepSize;
133
+ const dithered = normalized + (dither[i] - 0.5);
134
+ quantized[i] = Math.max(0, Math.min(maxLevel, Math.round(dithered)));
135
+ }
136
+ // Dequantize
137
+ dequantized[i] = quantized[i] * stepSize + minValue;
138
+ }
139
+ return {
140
+ quantized,
141
+ dequantized,
142
+ bitDepth,
143
+ seed,
144
+ stepSize,
145
+ minValue,
146
+ maxValue,
147
+ };
148
+ }
149
+ // ============================================================================
150
+ // Naive Quantization (for comparison)
151
+ // ============================================================================
152
+ /**
153
+ * Apply naive (non-dithered) quantization for comparison purposes.
154
+ *
155
+ * Uses simple rounding without dither noise. This tends to produce
156
+ * systematic quantization artifacts, especially at low bit depths.
157
+ *
158
+ * @param vector - Input float vector to quantize
159
+ * @param bitDepth - Number of bits for quantization (1-32)
160
+ * @returns DitheredResult with quantized and reconstructed values (seed = -1 to indicate no dither)
161
+ */
162
+ export function applyNaiveQuantization(vector, bitDepth) {
163
+ if (!(vector instanceof Float32Array)) {
164
+ throw new Error('Input vector must be a Float32Array');
165
+ }
166
+ if (vector.length === 0) {
167
+ return {
168
+ quantized: new Int32Array(0),
169
+ dequantized: new Float32Array(0),
170
+ bitDepth,
171
+ seed: -1,
172
+ stepSize: 0,
173
+ minValue: 0,
174
+ maxValue: 0,
175
+ };
176
+ }
177
+ if (bitDepth < 1 || bitDepth > 32 || !Number.isInteger(bitDepth)) {
178
+ throw new Error(`Invalid bit depth: ${bitDepth}. Must be an integer in [1, 32].`);
179
+ }
180
+ let minValue = vector[0];
181
+ let maxValue = vector[0];
182
+ for (let i = 1; i < vector.length; i++) {
183
+ if (vector[i] < minValue)
184
+ minValue = vector[i];
185
+ if (vector[i] > maxValue)
186
+ maxValue = vector[i];
187
+ }
188
+ const maxLevel = (1 << bitDepth) - 1;
189
+ const range = maxValue - minValue;
190
+ const stepSize = range === 0 ? 1 : range / maxLevel;
191
+ const quantized = new Int32Array(vector.length);
192
+ const dequantized = new Float32Array(vector.length);
193
+ for (let i = 0; i < vector.length; i++) {
194
+ if (range === 0) {
195
+ quantized[i] = Math.round(maxLevel / 2);
196
+ }
197
+ else {
198
+ const normalized = (vector[i] - minValue) / stepSize;
199
+ quantized[i] = Math.max(0, Math.min(maxLevel, Math.round(normalized)));
200
+ }
201
+ dequantized[i] = quantized[i] * stepSize + minValue;
202
+ }
203
+ return {
204
+ quantized,
205
+ dequantized,
206
+ bitDepth,
207
+ seed: -1,
208
+ stepSize,
209
+ minValue,
210
+ maxValue,
211
+ };
212
+ }
213
+ // ============================================================================
214
+ // Determinism Verification
215
+ // ============================================================================
216
+ /**
217
+ * Verify that dithered quantization is deterministic for the given input.
218
+ *
219
+ * Runs the quantization twice with the same parameters and compares results.
220
+ * This guards against any non-determinism from floating point ordering,
221
+ * platform differences, or hidden state.
222
+ *
223
+ * @param vector - Input float vector to test
224
+ * @param bitDepth - Number of bits for quantization
225
+ * @returns true if both runs produce identical quantized values
226
+ */
227
+ export function verifyDeterminism(vector, bitDepth) {
228
+ const seed = 42; // Fixed seed for verification
229
+ const result1 = applyDither(vector, bitDepth, seed);
230
+ const result2 = applyDither(vector, bitDepth, seed);
231
+ // Compare quantized arrays element by element
232
+ if (result1.quantized.length !== result2.quantized.length) {
233
+ return false;
234
+ }
235
+ for (let i = 0; i < result1.quantized.length; i++) {
236
+ if (result1.quantized[i] !== result2.quantized[i]) {
237
+ return false;
238
+ }
239
+ }
240
+ return true;
241
+ }
242
+ // ============================================================================
243
+ // Reconstruction Error Metrics
244
+ // ============================================================================
245
+ /**
246
+ * Compute mean squared error between original and reconstructed vectors.
247
+ *
248
+ * @param original - Original float vector
249
+ * @param reconstructed - Reconstructed (dequantized) float vector
250
+ * @returns Mean squared error
251
+ */
252
+ export function computeMSE(original, reconstructed) {
253
+ if (original.length !== reconstructed.length) {
254
+ throw new Error('Vectors must have the same length');
255
+ }
256
+ if (original.length === 0)
257
+ return 0;
258
+ let sumSqError = 0;
259
+ for (let i = 0; i < original.length; i++) {
260
+ const diff = original[i] - reconstructed[i];
261
+ sumSqError += diff * diff;
262
+ }
263
+ return sumSqError / original.length;
264
+ }
265
+ /**
266
+ * Compute signal-to-noise ratio (SNR) in decibels.
267
+ *
268
+ * SNR = 10 * log10(signal_power / noise_power)
269
+ *
270
+ * Higher SNR means better reconstruction quality.
271
+ *
272
+ * @param original - Original float vector
273
+ * @param reconstructed - Reconstructed (dequantized) float vector
274
+ * @returns SNR in dB, or Infinity if reconstruction is perfect
275
+ */
276
+ export function computeSNR(original, reconstructed) {
277
+ if (original.length !== reconstructed.length) {
278
+ throw new Error('Vectors must have the same length');
279
+ }
280
+ if (original.length === 0)
281
+ return Infinity;
282
+ let signalPower = 0;
283
+ let noisePower = 0;
284
+ for (let i = 0; i < original.length; i++) {
285
+ signalPower += original[i] * original[i];
286
+ const diff = original[i] - reconstructed[i];
287
+ noisePower += diff * diff;
288
+ }
289
+ if (noisePower === 0)
290
+ return Infinity;
291
+ if (signalPower === 0)
292
+ return 0;
293
+ return 10 * Math.log10(signalPower / noisePower);
294
+ }
295
+ //# sourceMappingURL=dither-adapter.js.map
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Cross-Domain Transfer Learning Engine (Task 2.3, ADR-084)
3
+ *
4
+ * Enables knowledge transfer between QE domains using Thompson Sampling
5
+ * with Beta priors, sqrt-dampening, transfer verification gates, domain
6
+ * pair affinity scoring, and coherence gate integration.
7
+ *
8
+ * @module integrations/ruvector/domain-transfer
9
+ */
10
+ import type { ITransferCoherenceGate, CoherenceValidation } from './transfer-coherence-stub.js';
11
+ import { type DomainPerformanceSnapshot, type VerificationResult, type TransferVerificationConfig } from './transfer-verification.js';
12
+ import { ThompsonSampler } from './thompson-sampler.js';
13
+ export { ThompsonSampler } from './thompson-sampler.js';
14
+ /** Candidate for a cross-domain transfer */
15
+ export interface TransferCandidate {
16
+ sourceDomain: string;
17
+ targetDomain: string;
18
+ /** Thompson-sampled probability of success */
19
+ sampledProbability: number;
20
+ affinityScore: number;
21
+ /** Whether this candidate was selected for exploration (vs exploitation) */
22
+ isExploration: boolean;
23
+ /** Domain pair key (e.g., "test-generation->coverage-analysis") */
24
+ pairKey: string;
25
+ }
26
+ /** Result of executing a transfer */
27
+ export interface TransferResult {
28
+ transferId: string;
29
+ candidate: TransferCandidate;
30
+ success: boolean;
31
+ /** Dampening factor applied (sqrt-dampening) */
32
+ dampeningFactor: number;
33
+ verification: VerificationResult;
34
+ coherenceResult: CoherenceValidation;
35
+ sourcePerformanceBefore: DomainPerformanceSnapshot;
36
+ sourcePerformanceAfter: DomainPerformanceSnapshot;
37
+ targetPerformanceBefore: DomainPerformanceSnapshot;
38
+ targetPerformanceAfter: DomainPerformanceSnapshot;
39
+ timestamp: number;
40
+ }
41
+ /** Record of a past transfer for history tracking */
42
+ export interface TransferRecord {
43
+ transferId: string;
44
+ sourceDomain: string;
45
+ targetDomain: string;
46
+ success: boolean;
47
+ sampledProbability: number;
48
+ dampeningFactor: number;
49
+ sourceDelta: number;
50
+ targetDelta: number;
51
+ timestamp: number;
52
+ }
53
+ /** Configuration for the domain transfer engine */
54
+ export interface DomainTransferConfig {
55
+ /** Minimum Thompson sample probability to attempt a transfer */
56
+ minTransferProbability: number;
57
+ /** Number of initial explorations before Thompson kicks in */
58
+ explorationWarmup: number;
59
+ verification: Partial<TransferVerificationConfig>;
60
+ /** Maximum transfer records to retain in history */
61
+ maxHistorySize: number;
62
+ }
63
+ /** Default domain transfer configuration */
64
+ export declare const DEFAULT_DOMAIN_TRANSFER_CONFIG: DomainTransferConfig;
65
+ /**
66
+ * Cross-domain transfer learning engine. Moves learned patterns between QE
67
+ * domains using Thompson Sampling, sqrt-dampening, and a double verification gate.
68
+ */
69
+ export declare class DomainTransferEngine {
70
+ private readonly config;
71
+ private readonly sampler;
72
+ private readonly verifier;
73
+ private readonly coherenceGate;
74
+ private readonly transferHistory;
75
+ private readonly affinityScores;
76
+ private performanceProvider;
77
+ private transferExecutor;
78
+ private nativeModule;
79
+ constructor(config?: Partial<DomainTransferConfig>);
80
+ /**
81
+ * Evaluate whether a transfer between two domains should be attempted.
82
+ * Uses Thompson Sampling to balance exploration and exploitation.
83
+ */
84
+ evaluateTransfer(sourceDomain: string, targetDomain: string): TransferCandidate;
85
+ /**
86
+ * Execute a cross-domain transfer through the full pipeline:
87
+ * coherence gate -> snapshot before -> sqrt-dampen & execute ->
88
+ * snapshot after -> verify -> update sampler & affinity.
89
+ */
90
+ executeTransfer(candidate: TransferCandidate): TransferResult;
91
+ /** Get the affinity score for a domain pair (0-1, default 0.5). */
92
+ getAffinityScore(source: string, target: string): number;
93
+ /** Get the full transfer history. */
94
+ getTransferHistory(): TransferRecord[];
95
+ /** Get the Thompson Sampler's mean success probability for a domain pair. */
96
+ getExpectedSuccessRate(source: string, target: string): number;
97
+ /** Get the total number of observations for a domain pair. */
98
+ getObservationCount(source: string, target: string): number;
99
+ /** Inject a performance provider for testing or custom integration. */
100
+ setPerformanceProvider(provider: (domain: string) => DomainPerformanceSnapshot): void;
101
+ /** Inject a transfer executor for testing or custom integration. */
102
+ setTransferExecutor(executor: (source: string, target: string, dampening: number) => boolean): void;
103
+ /** Get the Thompson Sampler (for testing). */
104
+ getSampler(): ThompsonSampler;
105
+ /** Get the coherence gate (for testing). */
106
+ getCoherenceGate(): ITransferCoherenceGate;
107
+ private isEnabled;
108
+ private makePairKey;
109
+ /**
110
+ * Sqrt-dampening: sqrt(observations / (observations + warmup)).
111
+ * New pairs -> ~0 (conservative), proven pairs -> ~1 (full strength).
112
+ */
113
+ private computeSqrtDampening;
114
+ private doTransfer;
115
+ private getPerformanceSnapshot;
116
+ /** EMA update (alpha=0.2) for affinity score */
117
+ private updateAffinityScore;
118
+ private addToHistory;
119
+ private createBlockedResult;
120
+ private createRejectedCandidate;
121
+ /**
122
+ * Check for native domain transfer module.
123
+ * No native package exists — Thompson Sampling works well in TypeScript.
124
+ */
125
+ private tryLoadNativeModule;
126
+ }
127
+ /** Create a DomainTransferEngine with the given configuration. */
128
+ export declare function createDomainTransferEngine(config?: Partial<DomainTransferConfig>): DomainTransferEngine;
129
+ //# sourceMappingURL=domain-transfer.d.ts.map
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Cross-Domain Transfer Learning Engine (Task 2.3, ADR-084)
3
+ *
4
+ * Enables knowledge transfer between QE domains using Thompson Sampling
5
+ * with Beta priors, sqrt-dampening, transfer verification gates, domain
6
+ * pair affinity scoring, and coherence gate integration.
7
+ *
8
+ * @module integrations/ruvector/domain-transfer
9
+ */
10
+ import { LoggerFactory } from '../../logging/index.js';
11
+ import { createTransferCoherenceGate } from './transfer-coherence-stub.js';
12
+ import { createTransferVerifier, } from './transfer-verification.js';
13
+ import { getRuVectorFeatureFlags } from './feature-flags.js';
14
+ import { ThompsonSampler } from './thompson-sampler.js';
15
+ export { ThompsonSampler } from './thompson-sampler.js';
16
+ const logger = LoggerFactory.create('domain-transfer');
17
+ /** Default domain transfer configuration */
18
+ export const DEFAULT_DOMAIN_TRANSFER_CONFIG = {
19
+ minTransferProbability: 0.3,
20
+ explorationWarmup: 5,
21
+ verification: {},
22
+ maxHistorySize: 1000,
23
+ };
24
+ // ============================================================================
25
+ // Domain Transfer Engine
26
+ // ============================================================================
27
+ /**
28
+ * Cross-domain transfer learning engine. Moves learned patterns between QE
29
+ * domains using Thompson Sampling, sqrt-dampening, and a double verification gate.
30
+ */
31
+ export class DomainTransferEngine {
32
+ config;
33
+ sampler;
34
+ verifier;
35
+ coherenceGate;
36
+ transferHistory = [];
37
+ affinityScores = new Map();
38
+ performanceProvider = null;
39
+ transferExecutor = null;
40
+ nativeModule = null;
41
+ constructor(config = {}) {
42
+ this.config = { ...DEFAULT_DOMAIN_TRANSFER_CONFIG, ...config };
43
+ this.sampler = new ThompsonSampler();
44
+ this.verifier = createTransferVerifier(this.config.verification);
45
+ this.coherenceGate = createTransferCoherenceGate();
46
+ this.tryLoadNativeModule();
47
+ }
48
+ /**
49
+ * Evaluate whether a transfer between two domains should be attempted.
50
+ * Uses Thompson Sampling to balance exploration and exploitation.
51
+ */
52
+ evaluateTransfer(sourceDomain, targetDomain) {
53
+ if (!this.isEnabled()) {
54
+ return this.createRejectedCandidate(sourceDomain, targetDomain);
55
+ }
56
+ const pairKey = this.makePairKey(sourceDomain, targetDomain);
57
+ const sampledProbability = this.sampler.sample(pairKey);
58
+ const observationCount = this.sampler.getObservationCount(pairKey);
59
+ const isExploration = observationCount < this.config.explorationWarmup;
60
+ const affinityScore = this.getAffinityScore(sourceDomain, targetDomain);
61
+ return { sourceDomain, targetDomain, sampledProbability, affinityScore, isExploration, pairKey };
62
+ }
63
+ /**
64
+ * Execute a cross-domain transfer through the full pipeline:
65
+ * coherence gate -> snapshot before -> sqrt-dampen & execute ->
66
+ * snapshot after -> verify -> update sampler & affinity.
67
+ */
68
+ executeTransfer(candidate) {
69
+ const transferId = `transfer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
70
+ // Step 1: Coherence gate
71
+ const coherenceResult = this.coherenceGate.validateTransfer({ domain: candidate.sourceDomain }, candidate.targetDomain);
72
+ if (!coherenceResult.approved) {
73
+ logger.info('Transfer blocked by coherence gate', {
74
+ transferId, source: candidate.sourceDomain,
75
+ target: candidate.targetDomain, reason: coherenceResult.rejectionReason,
76
+ });
77
+ return this.createBlockedResult(transferId, candidate, coherenceResult);
78
+ }
79
+ // Step 2-4: Snapshot, execute, snapshot
80
+ const sourcePerformanceBefore = this.getPerformanceSnapshot(candidate.sourceDomain);
81
+ const targetPerformanceBefore = this.getPerformanceSnapshot(candidate.targetDomain);
82
+ const dampeningFactor = this.computeSqrtDampening(candidate);
83
+ const transferSuccess = this.doTransfer(candidate.sourceDomain, candidate.targetDomain, dampeningFactor);
84
+ const sourcePerformanceAfter = this.getPerformanceSnapshot(candidate.sourceDomain);
85
+ const targetPerformanceAfter = this.getPerformanceSnapshot(candidate.targetDomain);
86
+ // Step 5: Verify
87
+ const verification = this.verifier.verifyTransfer({
88
+ transferId, sourceDomain: candidate.sourceDomain, targetDomain: candidate.targetDomain,
89
+ sourcePerformanceBefore, sourcePerformanceAfter,
90
+ targetPerformanceBefore, targetPerformanceAfter,
91
+ });
92
+ const success = transferSuccess && verification.passed;
93
+ // Step 6: Update Thompson Sampling and affinity
94
+ this.sampler.update(candidate.pairKey, success);
95
+ this.updateAffinityScore(candidate.pairKey, success);
96
+ this.addToHistory({
97
+ transferId, sourceDomain: candidate.sourceDomain, targetDomain: candidate.targetDomain,
98
+ success, sampledProbability: candidate.sampledProbability, dampeningFactor,
99
+ sourceDelta: verification.sourceDelta, targetDelta: verification.targetDelta,
100
+ timestamp: Date.now(),
101
+ });
102
+ logger.info('Transfer completed', {
103
+ transferId, source: candidate.sourceDomain, target: candidate.targetDomain,
104
+ success, dampeningFactor: dampeningFactor.toFixed(4),
105
+ sourceDelta: verification.sourceDelta.toFixed(4),
106
+ targetDelta: verification.targetDelta.toFixed(4),
107
+ });
108
+ return {
109
+ transferId, candidate, success, dampeningFactor, verification, coherenceResult,
110
+ sourcePerformanceBefore, sourcePerformanceAfter,
111
+ targetPerformanceBefore, targetPerformanceAfter,
112
+ timestamp: Date.now(),
113
+ };
114
+ }
115
+ /** Get the affinity score for a domain pair (0-1, default 0.5). */
116
+ getAffinityScore(source, target) {
117
+ return this.affinityScores.get(this.makePairKey(source, target)) ?? 0.5;
118
+ }
119
+ /** Get the full transfer history. */
120
+ getTransferHistory() {
121
+ return [...this.transferHistory];
122
+ }
123
+ /** Get the Thompson Sampler's mean success probability for a domain pair. */
124
+ getExpectedSuccessRate(source, target) {
125
+ return this.sampler.getMean(this.makePairKey(source, target));
126
+ }
127
+ /** Get the total number of observations for a domain pair. */
128
+ getObservationCount(source, target) {
129
+ return this.sampler.getObservationCount(this.makePairKey(source, target));
130
+ }
131
+ /** Inject a performance provider for testing or custom integration. */
132
+ setPerformanceProvider(provider) {
133
+ this.performanceProvider = provider;
134
+ }
135
+ /** Inject a transfer executor for testing or custom integration. */
136
+ setTransferExecutor(executor) {
137
+ this.transferExecutor = executor;
138
+ }
139
+ /** Get the Thompson Sampler (for testing). */
140
+ getSampler() { return this.sampler; }
141
+ /** Get the coherence gate (for testing). */
142
+ getCoherenceGate() { return this.coherenceGate; }
143
+ // --- Private Helpers ---
144
+ isEnabled() {
145
+ return getRuVectorFeatureFlags().useCrossDomainTransfer === true;
146
+ }
147
+ makePairKey(source, target) {
148
+ return `${source}->${target}`;
149
+ }
150
+ /**
151
+ * Sqrt-dampening: sqrt(observations / (observations + warmup)).
152
+ * New pairs -> ~0 (conservative), proven pairs -> ~1 (full strength).
153
+ */
154
+ computeSqrtDampening(candidate) {
155
+ const obs = this.sampler.getObservationCount(candidate.pairKey);
156
+ return Math.sqrt(obs / (obs + this.config.explorationWarmup));
157
+ }
158
+ doTransfer(source, target, dampening) {
159
+ if (this.transferExecutor)
160
+ return this.transferExecutor(source, target, dampening);
161
+ return true;
162
+ }
163
+ getPerformanceSnapshot(domain) {
164
+ if (this.performanceProvider)
165
+ return this.performanceProvider(domain);
166
+ return { domain, successRate: 0.5, avgConfidence: 0.5, patternCount: 0, timestamp: Date.now() };
167
+ }
168
+ /** EMA update (alpha=0.2) for affinity score */
169
+ updateAffinityScore(pairKey, success) {
170
+ const current = this.affinityScores.get(pairKey) ?? 0.5;
171
+ this.affinityScores.set(pairKey, 0.2 * (success ? 1 : 0) + 0.8 * current);
172
+ }
173
+ addToHistory(record) {
174
+ this.transferHistory.push(record);
175
+ while (this.transferHistory.length > this.config.maxHistorySize) {
176
+ this.transferHistory.shift();
177
+ }
178
+ }
179
+ createBlockedResult(transferId, candidate, coherenceResult) {
180
+ const empty = {
181
+ domain: '', successRate: 0, avgConfidence: 0, patternCount: 0, timestamp: Date.now(),
182
+ };
183
+ return {
184
+ transferId, candidate, success: false, dampeningFactor: 0,
185
+ verification: {
186
+ passed: false, sourceStable: false, targetImproved: false,
187
+ sourceDelta: 0, targetDelta: 0, sourceConfidenceDelta: 0, targetConfidenceDelta: 0,
188
+ failureReason: `Coherence gate rejected: ${coherenceResult.rejectionReason ?? 'unknown'}`,
189
+ },
190
+ coherenceResult,
191
+ sourcePerformanceBefore: { ...empty, domain: candidate.sourceDomain },
192
+ sourcePerformanceAfter: { ...empty, domain: candidate.sourceDomain },
193
+ targetPerformanceBefore: { ...empty, domain: candidate.targetDomain },
194
+ targetPerformanceAfter: { ...empty, domain: candidate.targetDomain },
195
+ timestamp: Date.now(),
196
+ };
197
+ }
198
+ createRejectedCandidate(sourceDomain, targetDomain) {
199
+ return {
200
+ sourceDomain, targetDomain, sampledProbability: 0,
201
+ affinityScore: 0, isExploration: false,
202
+ pairKey: this.makePairKey(sourceDomain, targetDomain),
203
+ };
204
+ }
205
+ /**
206
+ * Check for native domain transfer module.
207
+ * No native package exists — Thompson Sampling works well in TypeScript.
208
+ */
209
+ tryLoadNativeModule() {
210
+ this.nativeModule = null;
211
+ }
212
+ }
213
+ // ============================================================================
214
+ // Factory
215
+ // ============================================================================
216
+ /** Create a DomainTransferEngine with the given configuration. */
217
+ export function createDomainTransferEngine(config) {
218
+ return new DomainTransferEngine(config);
219
+ }
220
+ //# sourceMappingURL=domain-transfer.js.map