agentic-qe 3.8.10 → 3.8.12
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.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +40 -0
- package/dist/cli/bundle.js +1345 -1003
- package/dist/cli/command-registry.js +5 -1
- package/dist/cli/commands/pipeline.d.ts +16 -0
- package/dist/cli/commands/pipeline.js +314 -0
- package/dist/cli/commands/ruvector-commands.js +17 -0
- package/dist/cli/commands/token-usage.js +24 -1
- package/dist/cli/handlers/heartbeat-handler.d.ts +26 -0
- package/dist/cli/handlers/heartbeat-handler.js +382 -0
- package/dist/cli/handlers/index.d.ts +2 -0
- package/dist/cli/handlers/index.js +2 -0
- package/dist/cli/handlers/routing-handler.d.ts +22 -0
- package/dist/cli/handlers/routing-handler.js +227 -0
- package/dist/cli/index.js +2 -0
- package/dist/coordination/deterministic-actions.d.ts +36 -0
- package/dist/coordination/deterministic-actions.js +257 -0
- package/dist/coordination/workflow-orchestrator.d.ts +18 -1
- package/dist/coordination/workflow-orchestrator.js +113 -3
- package/dist/coordination/workflow-types.d.ts +19 -1
- package/dist/coordination/workflow-types.js +3 -0
- package/dist/coordination/yaml-pipeline-loader.d.ts +1 -0
- package/dist/coordination/yaml-pipeline-loader.js +34 -0
- package/dist/domains/code-intelligence/coordinator-gnn.d.ts +21 -0
- package/dist/domains/code-intelligence/coordinator-gnn.js +102 -0
- package/dist/domains/contract-testing/coordinator.js +13 -0
- package/dist/domains/coverage-analysis/coordinator.js +5 -0
- package/dist/domains/defect-intelligence/coordinator.d.ts +1 -0
- package/dist/domains/defect-intelligence/coordinator.js +43 -0
- package/dist/domains/quality-assessment/coordinator.js +26 -0
- package/dist/domains/test-generation/coordinator.js +14 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +11 -0
- package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +44 -1
- package/dist/integrations/rl-suite/algorithms/eprop.d.ts +79 -0
- package/dist/integrations/rl-suite/algorithms/eprop.js +284 -0
- package/dist/integrations/rl-suite/algorithms/index.d.ts +2 -1
- package/dist/integrations/rl-suite/algorithms/index.js +2 -1
- package/dist/integrations/rl-suite/index.d.ts +2 -2
- package/dist/integrations/rl-suite/index.js +2 -2
- package/dist/integrations/rl-suite/interfaces.d.ts +3 -3
- package/dist/integrations/rl-suite/interfaces.js +1 -1
- package/dist/integrations/rl-suite/orchestrator.d.ts +2 -2
- package/dist/integrations/rl-suite/orchestrator.js +3 -2
- package/dist/integrations/rl-suite/reward-signals.d.ts +1 -1
- package/dist/integrations/rl-suite/reward-signals.js +1 -1
- package/dist/integrations/ruvector/coherence-gate-cohomology.d.ts +41 -0
- package/dist/integrations/ruvector/coherence-gate-cohomology.js +47 -0
- package/dist/integrations/ruvector/coherence-gate-core.d.ts +200 -0
- package/dist/integrations/ruvector/coherence-gate-core.js +294 -0
- package/dist/integrations/ruvector/coherence-gate-energy.d.ts +136 -0
- package/dist/integrations/ruvector/coherence-gate-energy.js +373 -0
- package/dist/integrations/ruvector/coherence-gate-vector.d.ts +38 -0
- package/dist/integrations/ruvector/coherence-gate-vector.js +76 -0
- package/dist/integrations/ruvector/coherence-gate.d.ts +10 -311
- package/dist/integrations/ruvector/coherence-gate.js +10 -652
- package/dist/integrations/ruvector/cold-tier-trainer.d.ts +103 -0
- package/dist/integrations/ruvector/cold-tier-trainer.js +377 -0
- package/dist/integrations/ruvector/cusum-detector.d.ts +70 -0
- package/dist/integrations/ruvector/cusum-detector.js +142 -0
- package/dist/integrations/ruvector/delta-tracker.d.ts +122 -0
- package/dist/integrations/ruvector/delta-tracker.js +311 -0
- package/dist/integrations/ruvector/domain-transfer.d.ts +79 -1
- package/dist/integrations/ruvector/domain-transfer.js +158 -2
- package/dist/integrations/ruvector/eprop-learner.d.ts +135 -0
- package/dist/integrations/ruvector/eprop-learner.js +351 -0
- package/dist/integrations/ruvector/feature-flags.d.ts +177 -0
- package/dist/integrations/ruvector/feature-flags.js +145 -0
- package/dist/integrations/ruvector/graphmae-encoder.d.ts +88 -0
- package/dist/integrations/ruvector/graphmae-encoder.js +360 -0
- package/dist/integrations/ruvector/hdc-fingerprint.d.ts +127 -0
- package/dist/integrations/ruvector/hdc-fingerprint.js +222 -0
- package/dist/integrations/ruvector/hopfield-memory.d.ts +97 -0
- package/dist/integrations/ruvector/hopfield-memory.js +238 -0
- package/dist/integrations/ruvector/index.d.ts +13 -2
- package/dist/integrations/ruvector/index.js +46 -2
- package/dist/integrations/ruvector/mincut-wrapper.d.ts +7 -0
- package/dist/integrations/ruvector/mincut-wrapper.js +54 -2
- package/dist/integrations/ruvector/reservoir-replay.d.ts +172 -0
- package/dist/integrations/ruvector/reservoir-replay.js +335 -0
- package/dist/integrations/ruvector/solver-adapter.d.ts +93 -0
- package/dist/integrations/ruvector/solver-adapter.js +299 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +33 -0
- package/dist/integrations/ruvector/sona-persistence.js +47 -0
- package/dist/integrations/ruvector/spectral-sparsifier.d.ts +154 -0
- package/dist/integrations/ruvector/spectral-sparsifier.js +389 -0
- package/dist/integrations/ruvector/temporal-causality.d.ts +63 -0
- package/dist/integrations/ruvector/temporal-causality.js +317 -0
- package/dist/learning/pattern-promotion.d.ts +63 -0
- package/dist/learning/pattern-promotion.js +235 -1
- package/dist/learning/pattern-store.d.ts +2 -0
- package/dist/learning/pattern-store.js +187 -1
- package/dist/learning/sqlite-persistence.d.ts +2 -0
- package/dist/learning/sqlite-persistence.js +4 -0
- package/dist/mcp/bundle.js +477 -380
- package/dist/mcp/handlers/heartbeat-handlers.d.ts +67 -0
- package/dist/mcp/handlers/heartbeat-handlers.js +180 -0
- package/dist/mcp/handlers/index.d.ts +2 -1
- package/dist/mcp/handlers/index.js +5 -1
- package/dist/mcp/handlers/task-handlers.d.ts +28 -0
- package/dist/mcp/handlers/task-handlers.js +39 -0
- package/dist/mcp/protocol-server.js +45 -1
- package/dist/mcp/server.js +41 -1
- package/dist/optimization/index.d.ts +2 -0
- package/dist/optimization/index.js +1 -0
- package/dist/optimization/session-cache.d.ts +80 -0
- package/dist/optimization/session-cache.js +227 -0
- package/dist/optimization/token-optimizer-service.d.ts +10 -0
- package/dist/optimization/token-optimizer-service.js +51 -0
- package/dist/routing/economic-routing.d.ts +126 -0
- package/dist/routing/economic-routing.js +290 -0
- package/dist/routing/index.d.ts +2 -0
- package/dist/routing/index.js +2 -0
- package/dist/routing/routing-feedback.d.ts +29 -0
- package/dist/routing/routing-feedback.js +75 -0
- package/dist/shared/utils/index.d.ts +1 -0
- package/dist/shared/utils/index.js +1 -0
- package/dist/shared/utils/xorshift128.d.ts +24 -0
- package/dist/shared/utils/xorshift128.js +50 -0
- package/package.json +1 -1
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coherence Gate - Energy Computation
|
|
3
|
+
*
|
|
4
|
+
* Two-tier compute ladder for coherence energy:
|
|
5
|
+
* - Reflex (<1ms): Simple heuristic checks (assertion count, coverage overlap)
|
|
6
|
+
* - Retrieval (~10ms): Full word-frequency coherence computation with
|
|
7
|
+
* contradiction detection and sheaf Laplacian deviation
|
|
8
|
+
*
|
|
9
|
+
* @module integrations/ruvector/coherence-gate-energy
|
|
10
|
+
* @see ADR-083-coherence-gated-agent-actions.md
|
|
11
|
+
*/
|
|
12
|
+
import { LoggerFactory } from '../../logging/index.js';
|
|
13
|
+
import { textToWordFeatureVector, cosineSimilarity } from './coherence-gate-vector.js';
|
|
14
|
+
import { getCohomologyEngine } from './coherence-gate-cohomology.js';
|
|
15
|
+
import { CusumDetector } from './cusum-detector.js';
|
|
16
|
+
import { isCusumDriftDetectionEnabled } from './feature-flags.js';
|
|
17
|
+
const logger = LoggerFactory.create('coherence-gate-energy');
|
|
18
|
+
/** Module-level CUSUM detector instance (lazy singleton) */
|
|
19
|
+
let cusumDetector = null;
|
|
20
|
+
/** Registered drift listeners */
|
|
21
|
+
const driftListeners = [];
|
|
22
|
+
/** Accumulated drift events for polling by EventBus consumers */
|
|
23
|
+
const recentDriftEvents = [];
|
|
24
|
+
const MAX_DRIFT_EVENT_BUFFER = 100;
|
|
25
|
+
/**
|
|
26
|
+
* Auto-create CUSUM detector if the feature flag is enabled.
|
|
27
|
+
* Returns null when the flag is off and no manual enable has occurred.
|
|
28
|
+
*/
|
|
29
|
+
function getCusumDetectorAuto() {
|
|
30
|
+
if (cusumDetector)
|
|
31
|
+
return cusumDetector;
|
|
32
|
+
if (!isCusumDriftDetectionEnabled())
|
|
33
|
+
return null;
|
|
34
|
+
cusumDetector = new CusumDetector();
|
|
35
|
+
logger.debug('CUSUM drift detector auto-created via feature flag');
|
|
36
|
+
return cusumDetector;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Get the module-level CUSUM detector.
|
|
40
|
+
* Auto-creates if the feature flag is enabled.
|
|
41
|
+
*/
|
|
42
|
+
export function getCusumDetector() {
|
|
43
|
+
return getCusumDetectorAuto();
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Enable CUSUM drift monitoring on energy computations.
|
|
47
|
+
* Once enabled, every energy computation feeds the
|
|
48
|
+
* CUSUM detector and may emit 'drift-detected' events.
|
|
49
|
+
*
|
|
50
|
+
* Note: With useCusumDriftDetection feature flag enabled, the detector
|
|
51
|
+
* is auto-created on first use. This function allows manual creation
|
|
52
|
+
* with custom config when the flag is off.
|
|
53
|
+
*/
|
|
54
|
+
export function enableCusumMonitoring(config) {
|
|
55
|
+
cusumDetector = new CusumDetector(config);
|
|
56
|
+
return cusumDetector;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Disable CUSUM drift monitoring and clear all listeners.
|
|
60
|
+
*/
|
|
61
|
+
export function disableCusumMonitoring() {
|
|
62
|
+
cusumDetector = null;
|
|
63
|
+
driftListeners.length = 0;
|
|
64
|
+
recentDriftEvents.length = 0;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Register a listener for 'drift-detected' events.
|
|
68
|
+
* Returns an unsubscribe function.
|
|
69
|
+
*/
|
|
70
|
+
export function onDriftDetected(listener) {
|
|
71
|
+
driftListeners.push(listener);
|
|
72
|
+
return () => {
|
|
73
|
+
const idx = driftListeners.indexOf(listener);
|
|
74
|
+
if (idx >= 0)
|
|
75
|
+
driftListeners.splice(idx, 1);
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Get and drain recent drift events (for EventBus polling integration).
|
|
80
|
+
* Returns all accumulated drift events and clears the buffer.
|
|
81
|
+
* Consumers (e.g. coordinators) can poll this in their tick loop and
|
|
82
|
+
* forward to EventBus.emit('cusum:drift-detected', event).
|
|
83
|
+
*/
|
|
84
|
+
export function drainDriftEvents() {
|
|
85
|
+
const events = [...recentDriftEvents];
|
|
86
|
+
recentDriftEvents.length = 0;
|
|
87
|
+
return events;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Feed a computed energy value to the CUSUM detector and emit
|
|
91
|
+
* 'drift-detected' events if drift is found.
|
|
92
|
+
*
|
|
93
|
+
* Called for all four gate types: retrieve, write, learn, act.
|
|
94
|
+
*/
|
|
95
|
+
function checkCusumDrift(gateType, energy) {
|
|
96
|
+
const detector = getCusumDetectorAuto();
|
|
97
|
+
if (!detector)
|
|
98
|
+
return;
|
|
99
|
+
const result = detector.update(gateType, energy);
|
|
100
|
+
if (result.driftDetected) {
|
|
101
|
+
const payload = {
|
|
102
|
+
gateType,
|
|
103
|
+
energy,
|
|
104
|
+
cusumResult: result,
|
|
105
|
+
timestamp: Date.now(),
|
|
106
|
+
};
|
|
107
|
+
logger.warn('CUSUM drift detected', {
|
|
108
|
+
gateType,
|
|
109
|
+
energy,
|
|
110
|
+
direction: result.direction,
|
|
111
|
+
cumulativeSum: result.cumulativeSum,
|
|
112
|
+
});
|
|
113
|
+
// Buffer for EventBus polling
|
|
114
|
+
recentDriftEvents.push(payload);
|
|
115
|
+
if (recentDriftEvents.length > MAX_DRIFT_EVENT_BUFFER) {
|
|
116
|
+
recentDriftEvents.shift();
|
|
117
|
+
}
|
|
118
|
+
for (const listener of driftListeners) {
|
|
119
|
+
try {
|
|
120
|
+
listener(payload);
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
logger.debug('Drift listener error', { error: String(err) });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Weights for energy component computation */
|
|
129
|
+
export const ENERGY_WEIGHTS = {
|
|
130
|
+
assertionCoverage: 0.4,
|
|
131
|
+
codeCoverage: 0.3,
|
|
132
|
+
confidencePenalty: 0.3,
|
|
133
|
+
contradictionWeight: 0.2,
|
|
134
|
+
laplacianWeight: 0.15,
|
|
135
|
+
};
|
|
136
|
+
/** Reflex tier latency cutoff in ms */
|
|
137
|
+
export const REFLEX_LATENCY_BUDGET_MS = 1;
|
|
138
|
+
// ============================================================================
|
|
139
|
+
// Component Energy Functions
|
|
140
|
+
// ============================================================================
|
|
141
|
+
/**
|
|
142
|
+
* Compute assertion coverage energy.
|
|
143
|
+
* High energy when assertions far exceed observed behavior (hallucination signal).
|
|
144
|
+
*/
|
|
145
|
+
export function computeAssertionCoverageEnergy(artifact) {
|
|
146
|
+
if (artifact.assertions.length === 0) {
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
const ratio = artifact.observedBehavior.length / artifact.assertions.length;
|
|
150
|
+
return Math.max(0, Math.min(1 - ratio, 1));
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Compute code coverage energy.
|
|
154
|
+
* Higher energy for lower coverage.
|
|
155
|
+
*/
|
|
156
|
+
export function computeCodeCoverageEnergy(artifact) {
|
|
157
|
+
return Math.max(0, Math.min(1 - artifact.coverage, 1));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Compute confidence penalty.
|
|
161
|
+
* Higher energy for lower confidence.
|
|
162
|
+
*/
|
|
163
|
+
export function computeConfidencePenalty(artifact) {
|
|
164
|
+
return Math.max(0, Math.min(1 - artifact.confidence, 1));
|
|
165
|
+
}
|
|
166
|
+
// ============================================================================
|
|
167
|
+
// Contradiction Detection
|
|
168
|
+
// ============================================================================
|
|
169
|
+
/**
|
|
170
|
+
* Detect contradictions between assertions and observed behavior.
|
|
171
|
+
*
|
|
172
|
+
* Simple heuristic: look for negation patterns and semantic opposites
|
|
173
|
+
* in the assertion/behavior pairing.
|
|
174
|
+
*/
|
|
175
|
+
export function detectContradictions(artifact) {
|
|
176
|
+
if (artifact.assertions.length === 0 || artifact.observedBehavior.length === 0) {
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
let contradictions = 0;
|
|
180
|
+
const negationPatterns = ['not', 'never', 'false', 'undefined', 'null', 'error', 'fail'];
|
|
181
|
+
for (const assertion of artifact.assertions) {
|
|
182
|
+
const assertionLower = assertion.toLowerCase();
|
|
183
|
+
for (const behavior of artifact.observedBehavior) {
|
|
184
|
+
const behaviorLower = behavior.toLowerCase();
|
|
185
|
+
// Check if assertion and behavior have opposing sentiment
|
|
186
|
+
for (const neg of negationPatterns) {
|
|
187
|
+
const assertionHasNeg = assertionLower.includes(neg);
|
|
188
|
+
const behaviorHasNeg = behaviorLower.includes(neg);
|
|
189
|
+
// One has negation, the other does not, and they share a common term
|
|
190
|
+
if (assertionHasNeg !== behaviorHasNeg) {
|
|
191
|
+
const assertionWords = new Set(assertionLower.split(/\s+/));
|
|
192
|
+
const behaviorWords = new Set(behaviorLower.split(/\s+/));
|
|
193
|
+
let shared = 0;
|
|
194
|
+
for (const word of assertionWords) {
|
|
195
|
+
if (behaviorWords.has(word) && word.length > 3) {
|
|
196
|
+
shared++;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (shared > 0) {
|
|
200
|
+
contradictions++;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return Math.min(contradictions / artifact.assertions.length, 1);
|
|
208
|
+
}
|
|
209
|
+
// ============================================================================
|
|
210
|
+
// Laplacian Deviation
|
|
211
|
+
// ============================================================================
|
|
212
|
+
/**
|
|
213
|
+
* Compute Laplacian deviation using the native CohomologyEngine.
|
|
214
|
+
* Builds a sheaf graph where each assertion is a node and related
|
|
215
|
+
* assertion pairs form edges with identity restriction maps.
|
|
216
|
+
*/
|
|
217
|
+
export function computeNativeLaplacianDeviation(engine, artifact, vectors) {
|
|
218
|
+
const dim = vectors[0]?.length ?? 64;
|
|
219
|
+
// Build sheaf graph: each assertion is a node
|
|
220
|
+
const nodes = vectors.map((vec, i) => ({
|
|
221
|
+
id: i,
|
|
222
|
+
label: artifact.assertions[i]?.slice(0, 50) ?? `assertion-${i}`,
|
|
223
|
+
section: vec,
|
|
224
|
+
weight: artifact.confidence,
|
|
225
|
+
}));
|
|
226
|
+
// Build edges: connect all pairs with identity restriction maps
|
|
227
|
+
const edges = [];
|
|
228
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
229
|
+
for (let j = i + 1; j < vectors.length; j++) {
|
|
230
|
+
// Identity restriction map (flat dim x dim matrix)
|
|
231
|
+
const identityMap = [];
|
|
232
|
+
for (let r = 0; r < dim; r++) {
|
|
233
|
+
for (let c = 0; c < dim; c++) {
|
|
234
|
+
identityMap.push(r === c ? 1.0 : 0.0);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
edges.push({
|
|
238
|
+
source: i,
|
|
239
|
+
target: j,
|
|
240
|
+
weight: 1.0,
|
|
241
|
+
restriction_map: identityMap,
|
|
242
|
+
source_dim: dim,
|
|
243
|
+
target_dim: dim,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const rawEnergy = engine.consistencyEnergy({ nodes, edges });
|
|
248
|
+
// Normalize: raw energy can vary widely; map to [0, 1]
|
|
249
|
+
// Use sigmoid-like scaling: energy / (energy + 1)
|
|
250
|
+
const normalizedEnergy = rawEnergy / (rawEnergy + 1);
|
|
251
|
+
return Math.max(0, Math.min(normalizedEnergy, 1));
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Fallback: compute pairwise word-frequency cosine consistency score.
|
|
255
|
+
*/
|
|
256
|
+
export function computeFallbackLaplacianDeviation(vectors) {
|
|
257
|
+
let totalSimilarity = 0;
|
|
258
|
+
let pairCount = 0;
|
|
259
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
260
|
+
for (let j = i + 1; j < vectors.length; j++) {
|
|
261
|
+
totalSimilarity += cosineSimilarity(vectors[i], vectors[j]);
|
|
262
|
+
pairCount++;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (pairCount === 0) {
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
// Average similarity -> deviation
|
|
269
|
+
// High similarity = low deviation, low similarity = high deviation
|
|
270
|
+
const avgSimilarity = totalSimilarity / pairCount;
|
|
271
|
+
return Math.max(0, Math.min(1 - avgSimilarity, 1));
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Compute coherence deviation using sheaf Laplacian energy.
|
|
275
|
+
*
|
|
276
|
+
* When `prime-radiant-advanced-wasm` CohomologyEngine is available,
|
|
277
|
+
* builds a sheaf graph from assertion vectors and computes real sheaf
|
|
278
|
+
* Laplacian consistency energy. Falls back to pairwise word-frequency
|
|
279
|
+
* cosine similarity when the WASM module is unavailable.
|
|
280
|
+
*
|
|
281
|
+
* Uses 64-dim word-level feature hashing with FNV-1a for bucket assignment
|
|
282
|
+
* and L2-normalized term-frequency vectors.
|
|
283
|
+
*/
|
|
284
|
+
export function computeLaplacianDeviation(artifact) {
|
|
285
|
+
if (artifact.assertions.length < 2) {
|
|
286
|
+
return 0;
|
|
287
|
+
}
|
|
288
|
+
// Build word-level feature vectors from assertions
|
|
289
|
+
const vectors = artifact.assertions.map(a => textToWordFeatureVector(a));
|
|
290
|
+
// Try native CohomologyEngine for real sheaf Laplacian
|
|
291
|
+
const engine = getCohomologyEngine();
|
|
292
|
+
if (engine) {
|
|
293
|
+
try {
|
|
294
|
+
return computeNativeLaplacianDeviation(engine, artifact, vectors);
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
logger.debug('CohomologyEngine.consistencyEnergy failed, using fallback', { error: String(err) });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
// Fallback: pairwise cosine similarity
|
|
301
|
+
return computeFallbackLaplacianDeviation(vectors);
|
|
302
|
+
}
|
|
303
|
+
// ============================================================================
|
|
304
|
+
// Tier Computation
|
|
305
|
+
// ============================================================================
|
|
306
|
+
/**
|
|
307
|
+
* Reflex-tier energy computation using simple heuristics.
|
|
308
|
+
* Must complete in <1ms.
|
|
309
|
+
*
|
|
310
|
+
* @param artifact - Test artifact to compute energy for
|
|
311
|
+
* @param gateType - Gate action type for CUSUM tracking (default: 'act')
|
|
312
|
+
*/
|
|
313
|
+
export function computeReflexEnergy(artifact, gateType = 'act') {
|
|
314
|
+
const assertionCoverage = computeAssertionCoverageEnergy(artifact);
|
|
315
|
+
const codeCoverage = computeCodeCoverageEnergy(artifact);
|
|
316
|
+
const confidencePenalty = computeConfidencePenalty(artifact);
|
|
317
|
+
const energy = Math.min(assertionCoverage * ENERGY_WEIGHTS.assertionCoverage +
|
|
318
|
+
codeCoverage * ENERGY_WEIGHTS.codeCoverage +
|
|
319
|
+
confidencePenalty * ENERGY_WEIGHTS.confidencePenalty, 1);
|
|
320
|
+
// R2: CUSUM drift check for reflex-tier gate actions
|
|
321
|
+
checkCusumDrift(gateType, energy);
|
|
322
|
+
return {
|
|
323
|
+
energy,
|
|
324
|
+
components: {
|
|
325
|
+
assertionCoverage,
|
|
326
|
+
codeCoverage,
|
|
327
|
+
confidencePenalty,
|
|
328
|
+
contradictionScore: 0,
|
|
329
|
+
laplacianDeviation: 0,
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Retrieval-tier energy computation using sheaf Laplacian.
|
|
335
|
+
* Includes contradiction detection and Laplacian deviation.
|
|
336
|
+
*
|
|
337
|
+
* @param artifact - Test artifact to compute energy for
|
|
338
|
+
* @param gateType - Gate action type for CUSUM tracking (default: 'retrieve')
|
|
339
|
+
*/
|
|
340
|
+
export function computeRetrievalEnergy(artifact, gateType = 'retrieve') {
|
|
341
|
+
const assertionCoverage = computeAssertionCoverageEnergy(artifact);
|
|
342
|
+
const codeCoverage = computeCodeCoverageEnergy(artifact);
|
|
343
|
+
const confidencePenalty = computeConfidencePenalty(artifact);
|
|
344
|
+
const contradictionScore = detectContradictions(artifact);
|
|
345
|
+
const laplacianDeviation = computeLaplacianDeviation(artifact);
|
|
346
|
+
// Weighted combination including retrieval-only components
|
|
347
|
+
const baseEnergy = assertionCoverage * ENERGY_WEIGHTS.assertionCoverage +
|
|
348
|
+
codeCoverage * ENERGY_WEIGHTS.codeCoverage +
|
|
349
|
+
confidencePenalty * ENERGY_WEIGHTS.confidencePenalty;
|
|
350
|
+
const retrievalEnergy = contradictionScore * ENERGY_WEIGHTS.contradictionWeight +
|
|
351
|
+
laplacianDeviation * ENERGY_WEIGHTS.laplacianWeight;
|
|
352
|
+
// Normalize: base has weight sum 1.0, retrieval adds up to 0.35
|
|
353
|
+
// Scale so total is still in [0, 1]
|
|
354
|
+
const totalWeight = ENERGY_WEIGHTS.assertionCoverage +
|
|
355
|
+
ENERGY_WEIGHTS.codeCoverage +
|
|
356
|
+
ENERGY_WEIGHTS.confidencePenalty +
|
|
357
|
+
ENERGY_WEIGHTS.contradictionWeight +
|
|
358
|
+
ENERGY_WEIGHTS.laplacianWeight;
|
|
359
|
+
const energy = Math.min((baseEnergy + retrievalEnergy) / totalWeight, 1);
|
|
360
|
+
// R2: CUSUM drift check for all four gate types
|
|
361
|
+
checkCusumDrift(gateType, energy);
|
|
362
|
+
return {
|
|
363
|
+
energy,
|
|
364
|
+
components: {
|
|
365
|
+
assertionCoverage,
|
|
366
|
+
codeCoverage,
|
|
367
|
+
confidencePenalty,
|
|
368
|
+
contradictionScore,
|
|
369
|
+
laplacianDeviation,
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
//# sourceMappingURL=coherence-gate-energy.js.map
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coherence Gate - Vector Math Utilities
|
|
3
|
+
*
|
|
4
|
+
* Pure math functions for word-level feature hashing and similarity.
|
|
5
|
+
* Uses FNV-1a hashing for bucket assignment and L2-normalized
|
|
6
|
+
* term-frequency vectors with cosine similarity.
|
|
7
|
+
*
|
|
8
|
+
* @module integrations/ruvector/coherence-gate-vector
|
|
9
|
+
* @see ADR-083-coherence-gated-agent-actions.md
|
|
10
|
+
*/
|
|
11
|
+
/** Feature vector dimensionality */
|
|
12
|
+
export declare const FEATURE_DIM = 64;
|
|
13
|
+
/**
|
|
14
|
+
* Hash a word to a bucket index 0-63 using FNV-1a.
|
|
15
|
+
*
|
|
16
|
+
* @param word - The word to hash
|
|
17
|
+
* @returns Bucket index in [0, FEATURE_DIM)
|
|
18
|
+
*/
|
|
19
|
+
export declare function hashWord(word: string): number;
|
|
20
|
+
/**
|
|
21
|
+
* Convert text to a 64-dim word-level feature vector using feature hashing.
|
|
22
|
+
*
|
|
23
|
+
* Tokenizes on whitespace and punctuation, hashes each word to one of 64
|
|
24
|
+
* buckets via FNV-1a, builds a term-frequency vector, and L2-normalizes it.
|
|
25
|
+
*
|
|
26
|
+
* @param text - The text to vectorize
|
|
27
|
+
* @returns L2-normalized 64-dim feature vector
|
|
28
|
+
*/
|
|
29
|
+
export declare function textToWordFeatureVector(text: string): number[];
|
|
30
|
+
/**
|
|
31
|
+
* Compute cosine similarity between two vectors.
|
|
32
|
+
*
|
|
33
|
+
* @param a - First vector
|
|
34
|
+
* @param b - Second vector
|
|
35
|
+
* @returns Cosine similarity in [0, 1] for non-negative vectors
|
|
36
|
+
*/
|
|
37
|
+
export declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
38
|
+
//# sourceMappingURL=coherence-gate-vector.d.ts.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coherence Gate - Vector Math Utilities
|
|
3
|
+
*
|
|
4
|
+
* Pure math functions for word-level feature hashing and similarity.
|
|
5
|
+
* Uses FNV-1a hashing for bucket assignment and L2-normalized
|
|
6
|
+
* term-frequency vectors with cosine similarity.
|
|
7
|
+
*
|
|
8
|
+
* @module integrations/ruvector/coherence-gate-vector
|
|
9
|
+
* @see ADR-083-coherence-gated-agent-actions.md
|
|
10
|
+
*/
|
|
11
|
+
/** Feature vector dimensionality */
|
|
12
|
+
export const FEATURE_DIM = 64;
|
|
13
|
+
/**
|
|
14
|
+
* Hash a word to a bucket index 0-63 using FNV-1a.
|
|
15
|
+
*
|
|
16
|
+
* @param word - The word to hash
|
|
17
|
+
* @returns Bucket index in [0, FEATURE_DIM)
|
|
18
|
+
*/
|
|
19
|
+
export function hashWord(word) {
|
|
20
|
+
let h = 0x811c9dc5; // FNV offset basis
|
|
21
|
+
for (let i = 0; i < word.length; i++) {
|
|
22
|
+
h ^= word.charCodeAt(i);
|
|
23
|
+
h = Math.imul(h, 0x01000193); // FNV prime
|
|
24
|
+
}
|
|
25
|
+
return ((h >>> 0) % FEATURE_DIM);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Convert text to a 64-dim word-level feature vector using feature hashing.
|
|
29
|
+
*
|
|
30
|
+
* Tokenizes on whitespace and punctuation, hashes each word to one of 64
|
|
31
|
+
* buckets via FNV-1a, builds a term-frequency vector, and L2-normalizes it.
|
|
32
|
+
*
|
|
33
|
+
* @param text - The text to vectorize
|
|
34
|
+
* @returns L2-normalized 64-dim feature vector
|
|
35
|
+
*/
|
|
36
|
+
export function textToWordFeatureVector(text) {
|
|
37
|
+
const vec = new Array(FEATURE_DIM).fill(0);
|
|
38
|
+
const words = text.toLowerCase().split(/[\s,;:.!?()[\]{}"']+/).filter(w => w.length > 0);
|
|
39
|
+
for (const word of words) {
|
|
40
|
+
const bucket = hashWord(word);
|
|
41
|
+
vec[bucket]++;
|
|
42
|
+
}
|
|
43
|
+
// L2-normalize
|
|
44
|
+
let norm = 0;
|
|
45
|
+
for (let i = 0; i < FEATURE_DIM; i++) {
|
|
46
|
+
norm += vec[i] * vec[i];
|
|
47
|
+
}
|
|
48
|
+
norm = Math.sqrt(norm);
|
|
49
|
+
if (norm > 1e-10) {
|
|
50
|
+
for (let i = 0; i < FEATURE_DIM; i++) {
|
|
51
|
+
vec[i] /= norm;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return vec;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Compute cosine similarity between two vectors.
|
|
58
|
+
*
|
|
59
|
+
* @param a - First vector
|
|
60
|
+
* @param b - Second vector
|
|
61
|
+
* @returns Cosine similarity in [0, 1] for non-negative vectors
|
|
62
|
+
*/
|
|
63
|
+
export function cosineSimilarity(a, b) {
|
|
64
|
+
let dot = 0;
|
|
65
|
+
let normA = 0;
|
|
66
|
+
let normB = 0;
|
|
67
|
+
const len = Math.min(a.length, b.length);
|
|
68
|
+
for (let i = 0; i < len; i++) {
|
|
69
|
+
dot += a[i] * b[i];
|
|
70
|
+
normA += a[i] * a[i];
|
|
71
|
+
normB += b[i] * b[i];
|
|
72
|
+
}
|
|
73
|
+
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
74
|
+
return denom > 1e-10 ? dot / denom : 0;
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=coherence-gate-vector.js.map
|