monomind 1.15.3 → 1.15.5
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/scheduled_tasks.lock +1 -1
- package/package.json +1 -1
- package/packages/@monomind/cli/dist/src/mcp-client.js +7 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.js +347 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.js +206 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.js +303 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.js +266 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.js +406 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.d.ts +15 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.js +293 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.d.ts +277 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.js +159 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.d.ts +9 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.js +25 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/chaos-resilience/chaos-inject.d.ts +163 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/chaos-resilience/chaos-inject.js +414 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/analyze-coverage.d.ts +128 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/analyze-coverage.js +375 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.d.ts +161 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.js +423 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/track-trends.d.ts +165 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/track-trends.js +395 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/analyze-root-cause.d.ts +165 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/analyze-root-cause.js +508 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/find-similar-defects.d.ts +147 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/find-similar-defects.js +391 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/predict-defects.d.ts +147 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/predict-defects.js +422 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/assess-readiness.d.ts +185 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/assess-readiness.js +437 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/calculate-risk.d.ts +166 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/calculate-risk.js +410 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/evaluate-quality-gate.d.ts +201 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/evaluate-quality-gate.js +363 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/audit-compliance.d.ts +166 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/audit-compliance.js +394 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/detect-secrets.d.ts +129 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/detect-secrets.js +383 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/security-scan.d.ts +171 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/security-scan.js +476 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/generate-tests.d.ts +147 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/generate-tests.js +400 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/suggest-tests.d.ts +145 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/suggest-tests.js +328 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/tdd-cycle.d.ts +126 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/tdd-cycle.js +348 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality-tools.d.ts +9 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/quality-tools.js +308 -0
- package/packages/@monomind/cli/package.json +1 -1
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consensus Verification Tool - pr_consensus_verify
|
|
3
|
+
*
|
|
4
|
+
* Verifies multi-agent consensus mathematically using coherence analysis.
|
|
5
|
+
* Identifies divergent agents and measures agreement ratios.
|
|
6
|
+
*
|
|
7
|
+
* Uses CohomologyEngine for multi-agent consensus validation
|
|
8
|
+
*/
|
|
9
|
+
import { ConsensusInputSchema, successResult, errorResult, cosineSimilarity, } from './types.js';
|
|
10
|
+
// Default logger
|
|
11
|
+
const defaultLogger = {
|
|
12
|
+
debug: (msg, meta) => console.debug(`[pr_consensus_verify] ${msg}`, meta),
|
|
13
|
+
info: (msg, meta) => console.info(`[pr_consensus_verify] ${msg}`, meta),
|
|
14
|
+
warn: (msg, meta) => console.warn(`[pr_consensus_verify] ${msg}`, meta),
|
|
15
|
+
error: (msg, meta) => console.error(`[pr_consensus_verify] ${msg}`, meta),
|
|
16
|
+
};
|
|
17
|
+
// ============================================================================
|
|
18
|
+
// Consensus Analysis Functions
|
|
19
|
+
// ============================================================================
|
|
20
|
+
/**
|
|
21
|
+
* Compute pairwise similarity matrix
|
|
22
|
+
*/
|
|
23
|
+
function computeSimilarityMatrix(embeddings) {
|
|
24
|
+
const n = embeddings.length;
|
|
25
|
+
const matrix = [];
|
|
26
|
+
for (let i = 0; i < n; i++) {
|
|
27
|
+
const row = [];
|
|
28
|
+
const embi = embeddings[i];
|
|
29
|
+
for (let j = 0; j < n; j++) {
|
|
30
|
+
const embj = embeddings[j];
|
|
31
|
+
row.push(cosineSimilarity(embi, embj));
|
|
32
|
+
}
|
|
33
|
+
matrix.push(row);
|
|
34
|
+
}
|
|
35
|
+
return matrix;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Compute coherence energy using Sheaf Laplacian approach
|
|
39
|
+
*/
|
|
40
|
+
function computeCoherenceEnergy(embeddings) {
|
|
41
|
+
if (embeddings.length < 2)
|
|
42
|
+
return 0;
|
|
43
|
+
const n = embeddings.length;
|
|
44
|
+
let totalDisagreement = 0;
|
|
45
|
+
let edgeCount = 0;
|
|
46
|
+
for (let i = 0; i < n; i++) {
|
|
47
|
+
for (let j = i + 1; j < n; j++) {
|
|
48
|
+
const embi = embeddings[i];
|
|
49
|
+
const embj = embeddings[j];
|
|
50
|
+
const similarity = cosineSimilarity(embi, embj);
|
|
51
|
+
const disagreement = 1 - Math.max(0, similarity);
|
|
52
|
+
totalDisagreement += disagreement;
|
|
53
|
+
edgeCount++;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return edgeCount > 0 ? totalDisagreement / edgeCount : 0;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Identify divergent agents whose embeddings differ significantly from the group
|
|
60
|
+
*/
|
|
61
|
+
function identifyDivergentAgents(agentStates, threshold) {
|
|
62
|
+
if (agentStates.length < 2)
|
|
63
|
+
return [];
|
|
64
|
+
const embeddings = agentStates.map(s => s.embedding);
|
|
65
|
+
const n = embeddings.length;
|
|
66
|
+
const divergentAgents = [];
|
|
67
|
+
// Compute centroid
|
|
68
|
+
const firstEmb = embeddings[0];
|
|
69
|
+
if (!firstEmb)
|
|
70
|
+
return [];
|
|
71
|
+
const dim = firstEmb.length;
|
|
72
|
+
const centroid = new Array(dim).fill(0);
|
|
73
|
+
for (const emb of embeddings) {
|
|
74
|
+
for (let d = 0; d < dim; d++) {
|
|
75
|
+
const val = emb[d];
|
|
76
|
+
if (val !== undefined) {
|
|
77
|
+
centroid[d] = (centroid[d] ?? 0) + val / n;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// Find agents far from centroid
|
|
82
|
+
for (let i = 0; i < n; i++) {
|
|
83
|
+
const embi = embeddings[i];
|
|
84
|
+
const agentState = agentStates[i];
|
|
85
|
+
const similarity = cosineSimilarity(embi, centroid);
|
|
86
|
+
if (similarity < threshold) {
|
|
87
|
+
divergentAgents.push(agentState.agentId);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return divergentAgents;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Compute vote-based agreement ratio
|
|
94
|
+
*/
|
|
95
|
+
function computeVoteAgreement(agentStates) {
|
|
96
|
+
const votes = agentStates.filter(s => s.vote !== undefined).map(s => s.vote);
|
|
97
|
+
if (votes.length < 2)
|
|
98
|
+
return 1;
|
|
99
|
+
// Count vote frequencies
|
|
100
|
+
const voteCounts = new Map();
|
|
101
|
+
for (const vote of votes) {
|
|
102
|
+
voteCounts.set(vote, (voteCounts.get(vote) || 0) + 1);
|
|
103
|
+
}
|
|
104
|
+
// Agreement is based on majority
|
|
105
|
+
const values = Array.from(voteCounts.values());
|
|
106
|
+
const maxCount = values.length > 0 ? Math.max(...values) : 0;
|
|
107
|
+
return maxCount / votes.length;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Compute spectral stability from similarity matrix
|
|
111
|
+
*/
|
|
112
|
+
function computeSpectralStability(similarityMatrix) {
|
|
113
|
+
const n = similarityMatrix.length;
|
|
114
|
+
if (n < 2)
|
|
115
|
+
return { stable: true, spectralGap: 1 };
|
|
116
|
+
// Convert similarity to adjacency (threshold at 0.5)
|
|
117
|
+
const adjacency = [];
|
|
118
|
+
for (let i = 0; i < n; i++) {
|
|
119
|
+
const row = [];
|
|
120
|
+
const simRow = similarityMatrix[i];
|
|
121
|
+
for (let j = 0; j < n; j++) {
|
|
122
|
+
const simVal = simRow[j] ?? 0;
|
|
123
|
+
row.push(simVal > 0.5 ? simVal : 0);
|
|
124
|
+
}
|
|
125
|
+
adjacency.push(row);
|
|
126
|
+
}
|
|
127
|
+
// Compute degree matrix and Laplacian
|
|
128
|
+
const degrees = [];
|
|
129
|
+
for (let i = 0; i < n; i++) {
|
|
130
|
+
let degree = 0;
|
|
131
|
+
const adjRow = adjacency[i];
|
|
132
|
+
for (let j = 0; j < n; j++) {
|
|
133
|
+
degree += adjRow[j] ?? 0;
|
|
134
|
+
}
|
|
135
|
+
degrees.push(degree);
|
|
136
|
+
}
|
|
137
|
+
// Estimate spectral gap using power iteration on Laplacian
|
|
138
|
+
// Simplified: use average degree connectivity as proxy
|
|
139
|
+
const avgDegree = degrees.reduce((a, b) => a + b, 0) / n;
|
|
140
|
+
const maxDegree = Math.max(...degrees);
|
|
141
|
+
const spectralGap = maxDegree > 0 ? avgDegree / maxDegree : 0;
|
|
142
|
+
const stable = spectralGap > 0.3;
|
|
143
|
+
return { stable, spectralGap };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Get interpretation of consensus results
|
|
147
|
+
*/
|
|
148
|
+
function getInterpretation(verified, coherenceScore, divergentAgents, spectralStability) {
|
|
149
|
+
if (verified && divergentAgents.length === 0) {
|
|
150
|
+
return 'Strong consensus achieved - all agents are aligned';
|
|
151
|
+
}
|
|
152
|
+
if (verified && divergentAgents.length > 0) {
|
|
153
|
+
return `Consensus achieved with ${divergentAgents.length} minority agent(s)`;
|
|
154
|
+
}
|
|
155
|
+
if (!spectralStability) {
|
|
156
|
+
return 'Consensus not achieved - agent network shows instability patterns';
|
|
157
|
+
}
|
|
158
|
+
if (coherenceScore < 0.5) {
|
|
159
|
+
return 'Consensus not achieved - significant disagreement between agents';
|
|
160
|
+
}
|
|
161
|
+
return `Consensus not achieved - ${divergentAgents.length} divergent agent(s) detected`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Handler for pr_consensus_verify tool
|
|
165
|
+
*/
|
|
166
|
+
async function handler(input, context) {
|
|
167
|
+
const logger = context?.logger ?? defaultLogger;
|
|
168
|
+
const startTime = performance.now();
|
|
169
|
+
try {
|
|
170
|
+
// Validate input
|
|
171
|
+
const validationResult = ConsensusInputSchema.safeParse(input);
|
|
172
|
+
if (!validationResult.success) {
|
|
173
|
+
logger.error('Input validation failed', { error: validationResult.error.message });
|
|
174
|
+
return errorResult(`Invalid input: ${validationResult.error.message}`);
|
|
175
|
+
}
|
|
176
|
+
const { agentStates, threshold } = validationResult.data;
|
|
177
|
+
logger.debug('Processing consensus verification', {
|
|
178
|
+
agentCount: agentStates.length,
|
|
179
|
+
threshold,
|
|
180
|
+
});
|
|
181
|
+
if (agentStates.length === 0) {
|
|
182
|
+
return errorResult('No agent states provided');
|
|
183
|
+
}
|
|
184
|
+
// Validate embedding dimensions are consistent
|
|
185
|
+
const firstDim = agentStates[0].embedding.length;
|
|
186
|
+
for (let i = 1; i < agentStates.length; i++) {
|
|
187
|
+
if (agentStates[i].embedding.length !== firstDim) {
|
|
188
|
+
return errorResult(`Embedding dimension mismatch: agent ${agentStates[i].agentId} has ` +
|
|
189
|
+
`${agentStates[i].embedding.length} dimensions, expected ${firstDim}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const embeddings = agentStates.map(s => s.embedding);
|
|
193
|
+
let coherenceEnergy;
|
|
194
|
+
let divergentAgents;
|
|
195
|
+
// Try to use WASM bridge if available
|
|
196
|
+
if (context?.bridge?.initialized) {
|
|
197
|
+
try {
|
|
198
|
+
logger.debug('Using WASM bridge for coherence check');
|
|
199
|
+
const float32Embeddings = embeddings.map(e => new Float32Array(e));
|
|
200
|
+
const result = await context.bridge.checkCoherence(float32Embeddings);
|
|
201
|
+
coherenceEnergy = result.energy;
|
|
202
|
+
// WASM doesn't return divergent agents, compute separately
|
|
203
|
+
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
204
|
+
}
|
|
205
|
+
catch (wasmError) {
|
|
206
|
+
logger.warn('WASM bridge failed, falling back to JS implementation', {
|
|
207
|
+
error: wasmError instanceof Error ? wasmError.message : String(wasmError),
|
|
208
|
+
});
|
|
209
|
+
coherenceEnergy = computeCoherenceEnergy(embeddings);
|
|
210
|
+
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
// Pure JavaScript fallback
|
|
215
|
+
logger.debug('Using JavaScript fallback for consensus verification');
|
|
216
|
+
coherenceEnergy = computeCoherenceEnergy(embeddings);
|
|
217
|
+
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
218
|
+
}
|
|
219
|
+
// Compute additional metrics
|
|
220
|
+
const similarityMatrix = computeSimilarityMatrix(embeddings);
|
|
221
|
+
const { stable: spectralStability, spectralGap } = computeSpectralStability(similarityMatrix);
|
|
222
|
+
const voteAgreement = computeVoteAgreement(agentStates);
|
|
223
|
+
// Coherence score is inverse of energy
|
|
224
|
+
const coherenceScore = 1 - coherenceEnergy;
|
|
225
|
+
// Agreement ratio combines embedding coherence and vote agreement
|
|
226
|
+
const agreementRatio = (coherenceScore + voteAgreement) / 2;
|
|
227
|
+
// Consensus is verified if agreement exceeds threshold and no major divergence
|
|
228
|
+
const verified = agreementRatio >= threshold &&
|
|
229
|
+
divergentAgents.length <= Math.floor(agentStates.length * 0.2); // Allow 20% minority
|
|
230
|
+
const output = {
|
|
231
|
+
verified,
|
|
232
|
+
coherenceScore,
|
|
233
|
+
divergentAgents,
|
|
234
|
+
details: {
|
|
235
|
+
agreementRatio,
|
|
236
|
+
coherenceEnergy,
|
|
237
|
+
spectralStability,
|
|
238
|
+
spectralGap,
|
|
239
|
+
interpretation: getInterpretation(verified, coherenceScore, divergentAgents, spectralStability),
|
|
240
|
+
agentCount: agentStates.length,
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
const duration = performance.now() - startTime;
|
|
244
|
+
logger.info('Consensus verification completed', {
|
|
245
|
+
verified,
|
|
246
|
+
coherenceScore: coherenceScore.toFixed(4),
|
|
247
|
+
divergentAgents: divergentAgents.length,
|
|
248
|
+
durationMs: duration.toFixed(2),
|
|
249
|
+
});
|
|
250
|
+
return successResult(output);
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
const duration = performance.now() - startTime;
|
|
254
|
+
logger.error('Consensus verification failed', {
|
|
255
|
+
error: error instanceof Error ? error.message : String(error),
|
|
256
|
+
durationMs: duration.toFixed(2),
|
|
257
|
+
});
|
|
258
|
+
return errorResult(error instanceof Error ? error : new Error(String(error)));
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* pr_consensus_verify MCP Tool Definition
|
|
263
|
+
*/
|
|
264
|
+
export const consensusVerifyTool = {
|
|
265
|
+
name: 'pr_consensus_verify',
|
|
266
|
+
description: 'Verify multi-agent consensus mathematically using coherence analysis. Identifies divergent agents and measures agreement ratios. Uses CohomologyEngine for consensus validation.',
|
|
267
|
+
category: 'consensus',
|
|
268
|
+
version: '0.1.3',
|
|
269
|
+
tags: ['consensus', 'multi-agent', 'coherence', 'swarm', 'ai-interpretability'],
|
|
270
|
+
cacheable: false, // Agent states change frequently
|
|
271
|
+
inputSchema: {
|
|
272
|
+
type: 'object',
|
|
273
|
+
properties: {
|
|
274
|
+
agentStates: {
|
|
275
|
+
type: 'array',
|
|
276
|
+
items: {
|
|
277
|
+
type: 'object',
|
|
278
|
+
properties: {
|
|
279
|
+
agentId: { type: 'string', description: 'Unique agent identifier' },
|
|
280
|
+
embedding: {
|
|
281
|
+
type: 'array',
|
|
282
|
+
items: { type: 'number' },
|
|
283
|
+
description: 'Agent state embedding vector',
|
|
284
|
+
},
|
|
285
|
+
vote: { type: 'string', description: 'Agent vote or decision' },
|
|
286
|
+
metadata: { type: 'object', description: 'Additional agent metadata' },
|
|
287
|
+
},
|
|
288
|
+
required: ['agentId', 'embedding'],
|
|
289
|
+
},
|
|
290
|
+
description: 'Array of agent states to verify consensus',
|
|
291
|
+
},
|
|
292
|
+
threshold: {
|
|
293
|
+
type: 'number',
|
|
294
|
+
default: 0.8,
|
|
295
|
+
description: 'Required agreement threshold (0-1)',
|
|
296
|
+
},
|
|
297
|
+
},
|
|
298
|
+
required: ['agentStates'],
|
|
299
|
+
},
|
|
300
|
+
handler,
|
|
301
|
+
};
|
|
302
|
+
export default consensusVerifyTool;
|
|
303
|
+
//# sourceMappingURL=consensus-verify.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Gate Tool - pr_memory_gate
|
|
3
|
+
*
|
|
4
|
+
* Pre-storage coherence gate for memory entries.
|
|
5
|
+
* Validates that new entries are coherent with existing context before storage.
|
|
6
|
+
*
|
|
7
|
+
* Uses CohomologyEngine Sheaf Laplacian for coherence validation
|
|
8
|
+
*/
|
|
9
|
+
import type { MCPTool } from './types.js';
|
|
10
|
+
/**
|
|
11
|
+
* pr_memory_gate MCP Tool Definition
|
|
12
|
+
*/
|
|
13
|
+
export declare const memoryGateTool: MCPTool;
|
|
14
|
+
export default memoryGateTool;
|
|
15
|
+
//# sourceMappingURL=memory-gate.d.ts.map
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Gate Tool - pr_memory_gate
|
|
3
|
+
*
|
|
4
|
+
* Pre-storage coherence gate for memory entries.
|
|
5
|
+
* Validates that new entries are coherent with existing context before storage.
|
|
6
|
+
*
|
|
7
|
+
* Uses CohomologyEngine Sheaf Laplacian for coherence validation
|
|
8
|
+
*/
|
|
9
|
+
import { MemoryGateInputSchema, successResult, errorResult, cosineSimilarity, } from './types.js';
|
|
10
|
+
// Default logger
|
|
11
|
+
const defaultLogger = {
|
|
12
|
+
debug: (msg, meta) => console.debug(`[pr_memory_gate] ${msg}`, meta),
|
|
13
|
+
info: (msg, meta) => console.info(`[pr_memory_gate] ${msg}`, meta),
|
|
14
|
+
warn: (msg, meta) => console.warn(`[pr_memory_gate] ${msg}`, meta),
|
|
15
|
+
error: (msg, meta) => console.error(`[pr_memory_gate] ${msg}`, meta),
|
|
16
|
+
};
|
|
17
|
+
// ============================================================================
|
|
18
|
+
// Memory Gate Functions
|
|
19
|
+
// ============================================================================
|
|
20
|
+
/**
|
|
21
|
+
* Generate embedding from value (simplified - in production use actual embedding model)
|
|
22
|
+
*/
|
|
23
|
+
function generateEmbedding(value) {
|
|
24
|
+
// Convert value to string representation
|
|
25
|
+
const str = typeof value === 'string' ? value : JSON.stringify(value);
|
|
26
|
+
// Simple hash-based embedding (for demo purposes)
|
|
27
|
+
// In production, use actual embedding model
|
|
28
|
+
const embedding = new Array(64).fill(0);
|
|
29
|
+
for (let i = 0; i < str.length; i++) {
|
|
30
|
+
const charCode = str.charCodeAt(i);
|
|
31
|
+
const idx = i % embedding.length;
|
|
32
|
+
embedding[idx] += charCode * (i + 1) * 0.001;
|
|
33
|
+
}
|
|
34
|
+
// Normalize
|
|
35
|
+
let norm = 0;
|
|
36
|
+
for (let i = 0; i < embedding.length; i++) {
|
|
37
|
+
norm += embedding[i] * embedding[i];
|
|
38
|
+
}
|
|
39
|
+
norm = Math.sqrt(norm);
|
|
40
|
+
if (norm > 0) {
|
|
41
|
+
for (let i = 0; i < embedding.length; i++) {
|
|
42
|
+
embedding[i] /= norm;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return embedding;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Compute coherence energy using Sheaf Laplacian
|
|
49
|
+
*/
|
|
50
|
+
function computeCoherenceEnergy(newEmbedding, existingEmbeddings) {
|
|
51
|
+
if (existingEmbeddings.length === 0)
|
|
52
|
+
return 0;
|
|
53
|
+
let totalDisagreement = 0;
|
|
54
|
+
for (const existing of existingEmbeddings) {
|
|
55
|
+
const similarity = cosineSimilarity(newEmbedding, existing);
|
|
56
|
+
const disagreement = 1 - Math.max(0, similarity);
|
|
57
|
+
totalDisagreement += disagreement;
|
|
58
|
+
}
|
|
59
|
+
return totalDisagreement / existingEmbeddings.length;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Detect specific violations
|
|
63
|
+
*/
|
|
64
|
+
function detectViolations(newEmbedding, existingEmbeddings, warnThreshold) {
|
|
65
|
+
const violations = [];
|
|
66
|
+
for (let i = 0; i < existingEmbeddings.length; i++) {
|
|
67
|
+
const similarity = cosineSimilarity(newEmbedding, existingEmbeddings[i]);
|
|
68
|
+
if (similarity < -0.3) {
|
|
69
|
+
violations.push(`Strong contradiction with context entry ${i} (similarity: ${similarity.toFixed(3)})`);
|
|
70
|
+
}
|
|
71
|
+
else if (similarity < warnThreshold) {
|
|
72
|
+
violations.push(`Weak coherence with context entry ${i} (similarity: ${similarity.toFixed(3)})`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return violations;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Determine action based on coherence energy
|
|
79
|
+
*/
|
|
80
|
+
function determineAction(energy, thresholds) {
|
|
81
|
+
if (energy >= thresholds.reject) {
|
|
82
|
+
return 'reject';
|
|
83
|
+
}
|
|
84
|
+
if (energy >= thresholds.warn) {
|
|
85
|
+
return 'warn';
|
|
86
|
+
}
|
|
87
|
+
return 'allow';
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Get interpretation of memory gate result
|
|
91
|
+
*/
|
|
92
|
+
function getInterpretation(action, energy, violations) {
|
|
93
|
+
switch (action) {
|
|
94
|
+
case 'allow':
|
|
95
|
+
return 'Entry is coherent with existing context - storage allowed';
|
|
96
|
+
case 'warn':
|
|
97
|
+
return `Entry has minor inconsistencies (energy: ${energy.toFixed(3)}) - storage allowed with warning`;
|
|
98
|
+
case 'reject':
|
|
99
|
+
return `Entry contradicts existing context (energy: ${energy.toFixed(3)}) - storage blocked. ${violations.length} violation(s) detected.`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Handler for pr_memory_gate tool
|
|
104
|
+
*/
|
|
105
|
+
async function handler(input, context) {
|
|
106
|
+
const logger = context?.logger ?? defaultLogger;
|
|
107
|
+
const startTime = performance.now();
|
|
108
|
+
try {
|
|
109
|
+
// Validate input
|
|
110
|
+
const validationResult = MemoryGateInputSchema.safeParse(input);
|
|
111
|
+
if (!validationResult.success) {
|
|
112
|
+
logger.error('Input validation failed', { error: validationResult.error.message });
|
|
113
|
+
return errorResult(`Invalid input: ${validationResult.error.message}`);
|
|
114
|
+
}
|
|
115
|
+
const { key, value, existingVectors, thresholds } = validationResult.data;
|
|
116
|
+
// Get thresholds from config or input
|
|
117
|
+
const warnThreshold = thresholds?.warn ?? context?.config?.coherence?.warnThreshold ?? 0.3;
|
|
118
|
+
const rejectThreshold = thresholds?.reject ?? context?.config?.coherence?.rejectThreshold ?? 0.7;
|
|
119
|
+
logger.debug('Processing memory gate check', {
|
|
120
|
+
key,
|
|
121
|
+
hasExistingContext: !!existingVectors?.length,
|
|
122
|
+
contextSize: existingVectors?.length ?? 0,
|
|
123
|
+
warnThreshold,
|
|
124
|
+
rejectThreshold,
|
|
125
|
+
});
|
|
126
|
+
// Generate embedding for the new value
|
|
127
|
+
const newEmbedding = generateEmbedding(value);
|
|
128
|
+
// If no existing context, always allow
|
|
129
|
+
if (!existingVectors || existingVectors.length === 0) {
|
|
130
|
+
const output = {
|
|
131
|
+
allowed: true,
|
|
132
|
+
coherenceEnergy: 0,
|
|
133
|
+
details: {
|
|
134
|
+
action: 'allow',
|
|
135
|
+
violations: [],
|
|
136
|
+
confidence: 1,
|
|
137
|
+
interpretation: 'No existing context - entry allowed',
|
|
138
|
+
contextSize: 0,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
const duration = performance.now() - startTime;
|
|
142
|
+
logger.info('Memory gate check completed (no context)', {
|
|
143
|
+
key,
|
|
144
|
+
allowed: true,
|
|
145
|
+
durationMs: duration.toFixed(2),
|
|
146
|
+
});
|
|
147
|
+
return successResult(output);
|
|
148
|
+
}
|
|
149
|
+
// Validate embedding dimensions match
|
|
150
|
+
const firstDim = existingVectors[0].length;
|
|
151
|
+
for (let i = 1; i < existingVectors.length; i++) {
|
|
152
|
+
if (existingVectors[i].length !== firstDim) {
|
|
153
|
+
return errorResult(`Context embedding dimension mismatch: entry ${i} has ${existingVectors[i].length} dimensions, expected ${firstDim}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
let coherenceEnergy;
|
|
157
|
+
let violations;
|
|
158
|
+
// Try to use WASM bridge if available
|
|
159
|
+
if (context?.bridge?.initialized) {
|
|
160
|
+
try {
|
|
161
|
+
logger.debug('Using WASM bridge for coherence check');
|
|
162
|
+
const allEmbeddings = [
|
|
163
|
+
new Float32Array(newEmbedding),
|
|
164
|
+
...existingVectors.map(v => new Float32Array(v)),
|
|
165
|
+
];
|
|
166
|
+
const result = await context.bridge.checkCoherence(allEmbeddings);
|
|
167
|
+
coherenceEnergy = result.energy;
|
|
168
|
+
violations = result.violations;
|
|
169
|
+
}
|
|
170
|
+
catch (wasmError) {
|
|
171
|
+
logger.warn('WASM bridge failed, falling back to JS implementation', {
|
|
172
|
+
error: wasmError instanceof Error ? wasmError.message : String(wasmError),
|
|
173
|
+
});
|
|
174
|
+
coherenceEnergy = computeCoherenceEnergy(newEmbedding, existingVectors);
|
|
175
|
+
violations = detectViolations(newEmbedding, existingVectors, warnThreshold);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
// Pure JavaScript fallback
|
|
180
|
+
logger.debug('Using JavaScript fallback for memory gate');
|
|
181
|
+
coherenceEnergy = computeCoherenceEnergy(newEmbedding, existingVectors);
|
|
182
|
+
violations = detectViolations(newEmbedding, existingVectors, warnThreshold);
|
|
183
|
+
}
|
|
184
|
+
const action = determineAction(coherenceEnergy, { warn: warnThreshold, reject: rejectThreshold });
|
|
185
|
+
const allowed = action !== 'reject';
|
|
186
|
+
const confidence = 1 - coherenceEnergy;
|
|
187
|
+
const output = {
|
|
188
|
+
allowed,
|
|
189
|
+
coherenceEnergy,
|
|
190
|
+
reason: !allowed ? `Coherence energy ${coherenceEnergy.toFixed(3)} exceeds reject threshold ${rejectThreshold}` : undefined,
|
|
191
|
+
details: {
|
|
192
|
+
action,
|
|
193
|
+
violations,
|
|
194
|
+
confidence,
|
|
195
|
+
interpretation: getInterpretation(action, coherenceEnergy, violations),
|
|
196
|
+
contextSize: existingVectors.length,
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
const duration = performance.now() - startTime;
|
|
200
|
+
logger.info('Memory gate check completed', {
|
|
201
|
+
key,
|
|
202
|
+
allowed,
|
|
203
|
+
action,
|
|
204
|
+
coherenceEnergy: coherenceEnergy.toFixed(4),
|
|
205
|
+
violations: violations.length,
|
|
206
|
+
durationMs: duration.toFixed(2),
|
|
207
|
+
});
|
|
208
|
+
return successResult(output);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
const duration = performance.now() - startTime;
|
|
212
|
+
logger.error('Memory gate check failed', {
|
|
213
|
+
error: error instanceof Error ? error.message : String(error),
|
|
214
|
+
durationMs: duration.toFixed(2),
|
|
215
|
+
});
|
|
216
|
+
return errorResult(error instanceof Error ? error : new Error(String(error)));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* pr_memory_gate MCP Tool Definition
|
|
221
|
+
*/
|
|
222
|
+
export const memoryGateTool = {
|
|
223
|
+
name: 'pr_memory_gate',
|
|
224
|
+
description: 'Pre-storage coherence gate for memory entries. Validates new entries against existing context using Sheaf Laplacian energy. Blocks contradictory entries to maintain memory coherence.',
|
|
225
|
+
category: 'memory',
|
|
226
|
+
version: '0.1.3',
|
|
227
|
+
tags: ['memory', 'coherence', 'gate', 'validation', 'ai-interpretability'],
|
|
228
|
+
cacheable: false, // Context changes frequently
|
|
229
|
+
inputSchema: {
|
|
230
|
+
type: 'object',
|
|
231
|
+
properties: {
|
|
232
|
+
key: {
|
|
233
|
+
type: 'string',
|
|
234
|
+
description: 'Memory entry key',
|
|
235
|
+
},
|
|
236
|
+
value: {
|
|
237
|
+
description: 'Value to be stored (any JSON-serializable type)',
|
|
238
|
+
},
|
|
239
|
+
existingVectors: {
|
|
240
|
+
type: 'array',
|
|
241
|
+
items: { type: 'array', items: { type: 'number' } },
|
|
242
|
+
description: 'Existing context embeddings to check against',
|
|
243
|
+
},
|
|
244
|
+
thresholds: {
|
|
245
|
+
type: 'object',
|
|
246
|
+
properties: {
|
|
247
|
+
warn: {
|
|
248
|
+
type: 'number',
|
|
249
|
+
default: 0.3,
|
|
250
|
+
description: 'Energy threshold for warnings (0-1)',
|
|
251
|
+
},
|
|
252
|
+
reject: {
|
|
253
|
+
type: 'number',
|
|
254
|
+
default: 0.7,
|
|
255
|
+
description: 'Energy threshold for rejection (0-1)',
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
description: 'Custom coherence thresholds',
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
required: ['key', 'value'],
|
|
262
|
+
},
|
|
263
|
+
handler,
|
|
264
|
+
};
|
|
265
|
+
export default memoryGateTool;
|
|
266
|
+
//# sourceMappingURL=memory-gate.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quantum Topology Tool - pr_quantum_topology
|
|
3
|
+
*
|
|
4
|
+
* Computes quantum topology features including Betti numbers and persistence diagrams.
|
|
5
|
+
* Analyzes topological features of point clouds and simplicial complexes.
|
|
6
|
+
*
|
|
7
|
+
* Uses QuantumEngine from prime-radiant-advanced-wasm
|
|
8
|
+
*/
|
|
9
|
+
import type { MCPTool } from './types.js';
|
|
10
|
+
/**
|
|
11
|
+
* pr_quantum_topology MCP Tool Definition
|
|
12
|
+
*/
|
|
13
|
+
export declare const quantumTopologyTool: MCPTool;
|
|
14
|
+
export default quantumTopologyTool;
|
|
15
|
+
//# sourceMappingURL=quantum-topology.d.ts.map
|