monomind 2.7.4 → 2.7.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/package.json +1 -1
- package/packages/@monomind/cli/bin/cli.js +17 -1
- package/packages/@monomind/cli/dist/src/commands/doctor-project-checks.d.ts +3 -0
- package/packages/@monomind/cli/dist/src/commands/doctor-project-checks.js +81 -8
- package/packages/@monomind/cli/dist/src/commands/doctor.js +16 -2
- package/packages/@monomind/cli/dist/src/commands/memory-crud.js +15 -5
- package/packages/@monomind/cli/dist/src/commands/security-misc.js +7 -2
- package/packages/@monomind/cli/dist/src/init/helpers-generator.js +5 -0
- package/packages/@monomind/cli/dist/src/mcp-client.js +0 -2
- package/packages/@monomind/cli/dist/src/mcp-tools/agent-tools.js +1 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/embeddings-tools.d.ts +2 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/embeddings-tools.js +11 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/guidance-tools.js +17 -17
- package/packages/@monomind/cli/dist/src/mcp-tools/hive-mind-tools.d.ts +2 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/hive-mind-tools.js +14 -2
- package/packages/@monomind/cli/dist/src/mcp-tools/index.d.ts +0 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/index.js +0 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/monograph-tools.js +1 -2
- package/packages/@monomind/cli/dist/src/mcp-tools/neural-tools.js +1 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/swarm-tools.js +2 -2
- package/packages/@monomind/cli/dist/src/mcp-tools/transfer-tools.d.ts +2 -0
- package/packages/@monomind/cli/dist/src/mcp-tools/transfer-tools.js +11 -1
- package/packages/@monomind/cli/dist/src/ui/dashboard.html +44 -618
- package/packages/@monomind/cli/dist/src/ui/server.mjs +0 -275
- package/packages/@monomind/cli/dist/src/utils/cosine-similarity.d.ts +2 -2
- package/packages/@monomind/cli/dist/src/utils/cosine-similarity.js +2 -2
- package/packages/@monomind/cli/package.json +1 -1
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.d.ts +0 -15
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.js +0 -333
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.d.ts +0 -15
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.js +0 -188
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.d.ts +0 -14
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.js +0 -305
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.d.ts +0 -16
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.js +0 -279
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.d.ts +0 -15
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.js +0 -400
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.d.ts +0 -14
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.js +0 -312
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.d.ts +0 -430
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.js +0 -144
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.d.ts +0 -9
- package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.js +0 -25
- package/packages/@monomind/cli/dist/src/mcp-tools/daa-tools.d.ts +0 -13
- package/packages/@monomind/cli/dist/src/mcp-tools/daa-tools.js +0 -553
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Coherence Check Tool - pr_coherence_check
|
|
3
|
-
*
|
|
4
|
-
* Checks coherence of vectors using Sheaf Laplacian energy.
|
|
5
|
-
* Energy 0 = fully coherent, Energy 1 = contradictory
|
|
6
|
-
*
|
|
7
|
-
* Uses CohomologyEngine from prime-radiant-advanced-wasm
|
|
8
|
-
*/
|
|
9
|
-
import type { MCPTool } from './types.js';
|
|
10
|
-
/**
|
|
11
|
-
* pr_coherence_check MCP Tool Definition
|
|
12
|
-
*/
|
|
13
|
-
export declare const coherenceCheckTool: MCPTool;
|
|
14
|
-
export default coherenceCheckTool;
|
|
15
|
-
//# sourceMappingURL=coherence-check.d.ts.map
|
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Coherence Check Tool - pr_coherence_check
|
|
3
|
-
*
|
|
4
|
-
* Checks coherence of vectors using Sheaf Laplacian energy.
|
|
5
|
-
* Energy 0 = fully coherent, Energy 1 = contradictory
|
|
6
|
-
*
|
|
7
|
-
* Uses CohomologyEngine from prime-radiant-advanced-wasm
|
|
8
|
-
*/
|
|
9
|
-
import { cosineSimilarity } from '../../utils/cosine-similarity.js';
|
|
10
|
-
import { CoherenceInputSchema, successResult, errorResult, } from './types.js';
|
|
11
|
-
// Default logger for when context doesn't provide one
|
|
12
|
-
const defaultLogger = {
|
|
13
|
-
debug: (msg, meta) => console.debug(`[pr_coherence_check] ${msg}`, meta),
|
|
14
|
-
info: (msg, meta) => console.info(`[pr_coherence_check] ${msg}`, meta),
|
|
15
|
-
warn: (msg, meta) => console.warn(`[pr_coherence_check] ${msg}`, meta),
|
|
16
|
-
error: (msg, meta) => console.error(`[pr_coherence_check] ${msg}`, meta),
|
|
17
|
-
};
|
|
18
|
-
/**
|
|
19
|
-
* Compute Sheaf Laplacian energy for coherence detection
|
|
20
|
-
*
|
|
21
|
-
* The Sheaf Laplacian measures how well local data sections can be
|
|
22
|
-
* glued together into a global section. High energy indicates contradictions.
|
|
23
|
-
*
|
|
24
|
-
* For vectors v1, v2, ..., vn:
|
|
25
|
-
* 1. Construct a sheaf over the complete graph
|
|
26
|
-
* 2. Compute the Laplacian matrix L = D - A (where A captures similarities)
|
|
27
|
-
* 3. Energy = sum of disagreements across edges
|
|
28
|
-
*/
|
|
29
|
-
function computeSheafLaplacianEnergy(vectors) {
|
|
30
|
-
if (vectors.length < 2)
|
|
31
|
-
return 0;
|
|
32
|
-
const n = vectors.length;
|
|
33
|
-
let totalEnergy = 0;
|
|
34
|
-
let edgeCount = 0;
|
|
35
|
-
// Compute pairwise disagreement (1 - cosine_similarity)
|
|
36
|
-
for (let i = 0; i < n; i++) {
|
|
37
|
-
for (let j = i + 1; j < n; j++) {
|
|
38
|
-
const vi = vectors[i];
|
|
39
|
-
const vj = vectors[j];
|
|
40
|
-
const similarity = cosineSimilarity(vi, vj);
|
|
41
|
-
const disagreement = 1 - Math.max(0, similarity); // Clamp negative similarities
|
|
42
|
-
totalEnergy += disagreement;
|
|
43
|
-
edgeCount++;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// Normalize by number of edges
|
|
47
|
-
return edgeCount > 0 ? totalEnergy / edgeCount : 0;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Detect contradictions in the vector set
|
|
51
|
-
*/
|
|
52
|
-
function detectContradictions(vectors, threshold) {
|
|
53
|
-
const violations = [];
|
|
54
|
-
const n = vectors.length;
|
|
55
|
-
for (let i = 0; i < n; i++) {
|
|
56
|
-
for (let j = i + 1; j < n; j++) {
|
|
57
|
-
const vi = vectors[i];
|
|
58
|
-
const vj = vectors[j];
|
|
59
|
-
const similarity = cosineSimilarity(vi, vj);
|
|
60
|
-
// Negative similarity indicates potential contradiction
|
|
61
|
-
if (similarity < -0.3) {
|
|
62
|
-
violations.push(`Contradiction between vectors ${i} and ${j} (similarity: ${similarity.toFixed(3)})`);
|
|
63
|
-
}
|
|
64
|
-
// Low similarity with high threshold indicates inconsistency
|
|
65
|
-
else if (similarity < threshold && similarity > 0) {
|
|
66
|
-
violations.push(`Weak coherence between vectors ${i} and ${j} (similarity: ${similarity.toFixed(3)})`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
return violations;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Get interpretation of energy level
|
|
74
|
-
*/
|
|
75
|
-
function getInterpretation(energy) {
|
|
76
|
-
if (energy < 0.1)
|
|
77
|
-
return 'Fully coherent - vectors are highly consistent';
|
|
78
|
-
if (energy < 0.3)
|
|
79
|
-
return 'Minor inconsistencies - generally coherent with small variations';
|
|
80
|
-
if (energy < 0.5)
|
|
81
|
-
return 'Moderate inconsistencies - some conflicting information detected';
|
|
82
|
-
if (energy < 0.7)
|
|
83
|
-
return 'Significant contradictions - vectors contain conflicting content';
|
|
84
|
-
return 'Major contradictions detected - high disagreement between vectors';
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Handler for pr_coherence_check tool
|
|
88
|
-
*/
|
|
89
|
-
async function handler(input, context) {
|
|
90
|
-
const logger = context?.logger ?? defaultLogger;
|
|
91
|
-
const startTime = performance.now();
|
|
92
|
-
try {
|
|
93
|
-
// Validate input
|
|
94
|
-
const validationResult = CoherenceInputSchema.safeParse(input);
|
|
95
|
-
if (!validationResult.success) {
|
|
96
|
-
logger.error('Input validation failed', { error: validationResult.error.message });
|
|
97
|
-
return errorResult(`Invalid input: ${validationResult.error.message}`);
|
|
98
|
-
}
|
|
99
|
-
const { vectors, threshold } = validationResult.data;
|
|
100
|
-
logger.debug('Processing coherence check', { vectorCount: vectors.length, threshold });
|
|
101
|
-
// Convert to Float32Arrays
|
|
102
|
-
const float32Vectors = vectors.map(v => new Float32Array(v));
|
|
103
|
-
let energy;
|
|
104
|
-
let violations;
|
|
105
|
-
// Try to use WASM bridge if available
|
|
106
|
-
if (context?.bridge?.initialized) {
|
|
107
|
-
try {
|
|
108
|
-
logger.debug('Using WASM bridge for coherence check');
|
|
109
|
-
const result = await context.bridge.checkCoherence(float32Vectors);
|
|
110
|
-
energy = result.energy;
|
|
111
|
-
violations = result.violations;
|
|
112
|
-
}
|
|
113
|
-
catch (wasmError) {
|
|
114
|
-
logger.warn('WASM bridge failed, falling back to JS implementation', {
|
|
115
|
-
error: wasmError instanceof Error ? wasmError.message : String(wasmError),
|
|
116
|
-
});
|
|
117
|
-
energy = computeSheafLaplacianEnergy(float32Vectors);
|
|
118
|
-
violations = detectContradictions(float32Vectors, threshold);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
else {
|
|
122
|
-
// Pure JavaScript fallback implementation
|
|
123
|
-
logger.debug('Using JavaScript fallback for coherence check');
|
|
124
|
-
energy = computeSheafLaplacianEnergy(float32Vectors);
|
|
125
|
-
violations = detectContradictions(float32Vectors, threshold);
|
|
126
|
-
}
|
|
127
|
-
const isCoherent = energy < threshold;
|
|
128
|
-
const confidence = 1 - energy;
|
|
129
|
-
const output = {
|
|
130
|
-
energy,
|
|
131
|
-
isCoherent,
|
|
132
|
-
details: {
|
|
133
|
-
violations,
|
|
134
|
-
confidence,
|
|
135
|
-
interpretation: getInterpretation(energy),
|
|
136
|
-
vectorCount: vectors.length,
|
|
137
|
-
threshold,
|
|
138
|
-
},
|
|
139
|
-
};
|
|
140
|
-
const duration = performance.now() - startTime;
|
|
141
|
-
logger.info('Coherence check completed', {
|
|
142
|
-
energy: energy.toFixed(4),
|
|
143
|
-
isCoherent,
|
|
144
|
-
violations: violations.length,
|
|
145
|
-
durationMs: duration.toFixed(2),
|
|
146
|
-
});
|
|
147
|
-
return successResult(output);
|
|
148
|
-
}
|
|
149
|
-
catch (error) {
|
|
150
|
-
const duration = performance.now() - startTime;
|
|
151
|
-
logger.error('Coherence check failed', {
|
|
152
|
-
error: error instanceof Error ? error.message : String(error),
|
|
153
|
-
durationMs: duration.toFixed(2),
|
|
154
|
-
});
|
|
155
|
-
return errorResult(error instanceof Error ? error : new Error(String(error)));
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* pr_coherence_check MCP Tool Definition
|
|
160
|
-
*/
|
|
161
|
-
export const coherenceCheckTool = {
|
|
162
|
-
name: 'pr_coherence_check',
|
|
163
|
-
description: 'Check coherence of vectors using Sheaf Laplacian energy. Energy 0 = fully coherent, 1 = contradictory. Uses CohomologyEngine for mathematical validation of vector consistency.',
|
|
164
|
-
category: 'coherence',
|
|
165
|
-
version: '0.1.3',
|
|
166
|
-
tags: ['coherence', 'sheaf-laplacian', 'contradiction-detection', 'ai-interpretability'],
|
|
167
|
-
cacheable: true,
|
|
168
|
-
cacheTTL: 60000, // 1 minute cache
|
|
169
|
-
inputSchema: {
|
|
170
|
-
type: 'object',
|
|
171
|
-
properties: {
|
|
172
|
-
vectors: {
|
|
173
|
-
type: 'array',
|
|
174
|
-
items: { type: 'array', items: { type: 'number' } },
|
|
175
|
-
description: 'Array of embedding vectors to check for coherence',
|
|
176
|
-
},
|
|
177
|
-
threshold: {
|
|
178
|
-
type: 'number',
|
|
179
|
-
default: 0.3,
|
|
180
|
-
description: 'Energy threshold for coherence (0-1). Lower = stricter coherence requirement.',
|
|
181
|
-
},
|
|
182
|
-
},
|
|
183
|
-
required: ['vectors'],
|
|
184
|
-
},
|
|
185
|
-
handler,
|
|
186
|
-
};
|
|
187
|
-
export default coherenceCheckTool;
|
|
188
|
-
//# sourceMappingURL=coherence-check.js.map
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Consensus Verification Tool - pr_consensus_verify
|
|
3
|
-
*
|
|
4
|
-
* Verifies multi-agent consensus using cosine-similarity coherence analysis.
|
|
5
|
-
* Identifies divergent agents and measures agreement ratios.
|
|
6
|
-
* Connectivity stability uses a degree-ratio heuristic (not spectral decomposition).
|
|
7
|
-
*/
|
|
8
|
-
import type { MCPTool } from './types.js';
|
|
9
|
-
/**
|
|
10
|
-
* pr_consensus_verify MCP Tool Definition
|
|
11
|
-
*/
|
|
12
|
-
export declare const consensusVerifyTool: MCPTool;
|
|
13
|
-
export default consensusVerifyTool;
|
|
14
|
-
//# sourceMappingURL=consensus-verify.d.ts.map
|
|
@@ -1,305 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Consensus Verification Tool - pr_consensus_verify
|
|
3
|
-
*
|
|
4
|
-
* Verifies multi-agent consensus using cosine-similarity coherence analysis.
|
|
5
|
-
* Identifies divergent agents and measures agreement ratios.
|
|
6
|
-
* Connectivity stability uses a degree-ratio heuristic (not spectral decomposition).
|
|
7
|
-
*/
|
|
8
|
-
import { ConsensusInputSchema, successResult, errorResult, cosineSimilarity, } from './types.js';
|
|
9
|
-
// Default logger
|
|
10
|
-
const defaultLogger = {
|
|
11
|
-
debug: (msg, meta) => console.debug(`[pr_consensus_verify] ${msg}`, meta),
|
|
12
|
-
info: (msg, meta) => console.info(`[pr_consensus_verify] ${msg}`, meta),
|
|
13
|
-
warn: (msg, meta) => console.warn(`[pr_consensus_verify] ${msg}`, meta),
|
|
14
|
-
error: (msg, meta) => console.error(`[pr_consensus_verify] ${msg}`, meta),
|
|
15
|
-
};
|
|
16
|
-
// ============================================================================
|
|
17
|
-
// Consensus Analysis Functions
|
|
18
|
-
// ============================================================================
|
|
19
|
-
/**
|
|
20
|
-
* Compute pairwise similarity matrix
|
|
21
|
-
*/
|
|
22
|
-
function computeSimilarityMatrix(embeddings) {
|
|
23
|
-
const n = embeddings.length;
|
|
24
|
-
const matrix = [];
|
|
25
|
-
for (let i = 0; i < n; i++) {
|
|
26
|
-
const row = [];
|
|
27
|
-
const embi = embeddings[i];
|
|
28
|
-
for (let j = 0; j < n; j++) {
|
|
29
|
-
const embj = embeddings[j];
|
|
30
|
-
row.push(cosineSimilarity(embi, embj));
|
|
31
|
-
}
|
|
32
|
-
matrix.push(row);
|
|
33
|
-
}
|
|
34
|
-
return matrix;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Compute coherence energy using Sheaf Laplacian approach
|
|
38
|
-
*/
|
|
39
|
-
function computeCoherenceEnergy(embeddings) {
|
|
40
|
-
if (embeddings.length < 2)
|
|
41
|
-
return 0;
|
|
42
|
-
const n = embeddings.length;
|
|
43
|
-
let totalDisagreement = 0;
|
|
44
|
-
let edgeCount = 0;
|
|
45
|
-
for (let i = 0; i < n; i++) {
|
|
46
|
-
for (let j = i + 1; j < n; j++) {
|
|
47
|
-
const embi = embeddings[i];
|
|
48
|
-
const embj = embeddings[j];
|
|
49
|
-
const similarity = cosineSimilarity(embi, embj);
|
|
50
|
-
const disagreement = 1 - Math.max(0, similarity);
|
|
51
|
-
totalDisagreement += disagreement;
|
|
52
|
-
edgeCount++;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return edgeCount > 0 ? totalDisagreement / edgeCount : 0;
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Identify divergent agents whose embeddings differ significantly from the group
|
|
59
|
-
*/
|
|
60
|
-
function identifyDivergentAgents(agentStates, threshold) {
|
|
61
|
-
if (agentStates.length < 2)
|
|
62
|
-
return [];
|
|
63
|
-
const embeddings = agentStates.map(s => s.embedding);
|
|
64
|
-
const n = embeddings.length;
|
|
65
|
-
const divergentAgents = [];
|
|
66
|
-
// Compute centroid
|
|
67
|
-
const firstEmb = embeddings[0];
|
|
68
|
-
if (!firstEmb)
|
|
69
|
-
return [];
|
|
70
|
-
const dim = firstEmb.length;
|
|
71
|
-
const centroid = new Array(dim).fill(0);
|
|
72
|
-
for (const emb of embeddings) {
|
|
73
|
-
for (let d = 0; d < dim; d++) {
|
|
74
|
-
const val = emb[d];
|
|
75
|
-
if (val !== undefined) {
|
|
76
|
-
centroid[d] = (centroid[d] ?? 0) + val / n;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
// Find agents far from centroid
|
|
81
|
-
for (let i = 0; i < n; i++) {
|
|
82
|
-
const embi = embeddings[i];
|
|
83
|
-
const agentState = agentStates[i];
|
|
84
|
-
const similarity = cosineSimilarity(embi, centroid);
|
|
85
|
-
if (similarity < threshold) {
|
|
86
|
-
divergentAgents.push(agentState.agentId);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
return divergentAgents;
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Compute vote-based agreement ratio
|
|
93
|
-
*/
|
|
94
|
-
function computeVoteAgreement(agentStates) {
|
|
95
|
-
const votes = agentStates.filter(s => s.vote !== undefined).map(s => s.vote);
|
|
96
|
-
if (votes.length < 2)
|
|
97
|
-
return 1;
|
|
98
|
-
// Count vote frequencies
|
|
99
|
-
const voteCounts = new Map();
|
|
100
|
-
for (const vote of votes) {
|
|
101
|
-
voteCounts.set(vote, (voteCounts.get(vote) || 0) + 1);
|
|
102
|
-
}
|
|
103
|
-
// Agreement is based on majority
|
|
104
|
-
const values = Array.from(voteCounts.values());
|
|
105
|
-
const maxCount = values.length > 0 ? Math.max(...values) : 0;
|
|
106
|
-
return maxCount / votes.length;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Compute connectivity stability from similarity matrix.
|
|
110
|
-
* Uses the ratio of average to maximum degree as a connectivity proxy.
|
|
111
|
-
* A ratio near 1 means uniform connectivity; near 0 means a few nodes
|
|
112
|
-
* dominate connectivity while others are isolated.
|
|
113
|
-
* NOTE: This is NOT a true spectral gap (which requires eigendecomposition
|
|
114
|
-
* of the Laplacian). It is a lightweight degree-based heuristic.
|
|
115
|
-
*/
|
|
116
|
-
function computeConnectivityStability(similarityMatrix) {
|
|
117
|
-
const n = similarityMatrix.length;
|
|
118
|
-
if (n < 2)
|
|
119
|
-
return { stable: true, degreeRatio: 1 };
|
|
120
|
-
// Convert similarity to adjacency (threshold at 0.5)
|
|
121
|
-
const adjacency = [];
|
|
122
|
-
for (let i = 0; i < n; i++) {
|
|
123
|
-
const row = [];
|
|
124
|
-
const simRow = similarityMatrix[i];
|
|
125
|
-
for (let j = 0; j < n; j++) {
|
|
126
|
-
const simVal = simRow[j] ?? 0;
|
|
127
|
-
row.push(simVal > 0.5 ? simVal : 0);
|
|
128
|
-
}
|
|
129
|
-
adjacency.push(row);
|
|
130
|
-
}
|
|
131
|
-
// Compute degrees
|
|
132
|
-
const degrees = [];
|
|
133
|
-
for (let i = 0; i < n; i++) {
|
|
134
|
-
let degree = 0;
|
|
135
|
-
const adjRow = adjacency[i];
|
|
136
|
-
for (let j = 0; j < n; j++) {
|
|
137
|
-
degree += adjRow[j] ?? 0;
|
|
138
|
-
}
|
|
139
|
-
degrees.push(degree);
|
|
140
|
-
}
|
|
141
|
-
const avgDegree = degrees.reduce((a, b) => a + b, 0) / n;
|
|
142
|
-
const maxDegree = Math.max(...degrees);
|
|
143
|
-
const degreeRatio = maxDegree > 0 ? avgDegree / maxDegree : 0;
|
|
144
|
-
const stable = degreeRatio > 0.3;
|
|
145
|
-
return { stable, degreeRatio };
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Get interpretation of consensus results
|
|
149
|
-
*/
|
|
150
|
-
function getInterpretation(verified, coherenceScore, divergentAgents, connectivityStable) {
|
|
151
|
-
if (verified && divergentAgents.length === 0) {
|
|
152
|
-
return 'Strong consensus achieved - all agents are aligned';
|
|
153
|
-
}
|
|
154
|
-
if (verified && divergentAgents.length > 0) {
|
|
155
|
-
return `Consensus achieved with ${divergentAgents.length} minority agent(s)`;
|
|
156
|
-
}
|
|
157
|
-
if (!connectivityStable) {
|
|
158
|
-
return 'Consensus not achieved - agent network shows poor connectivity (uneven degree distribution)';
|
|
159
|
-
}
|
|
160
|
-
if (coherenceScore < 0.5) {
|
|
161
|
-
return 'Consensus not achieved - significant disagreement between agents';
|
|
162
|
-
}
|
|
163
|
-
return `Consensus not achieved - ${divergentAgents.length} divergent agent(s) detected`;
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Handler for pr_consensus_verify tool
|
|
167
|
-
*/
|
|
168
|
-
async function handler(input, context) {
|
|
169
|
-
const logger = context?.logger ?? defaultLogger;
|
|
170
|
-
const startTime = performance.now();
|
|
171
|
-
try {
|
|
172
|
-
// Validate input
|
|
173
|
-
const validationResult = ConsensusInputSchema.safeParse(input);
|
|
174
|
-
if (!validationResult.success) {
|
|
175
|
-
logger.error('Input validation failed', { error: validationResult.error.message });
|
|
176
|
-
return errorResult(`Invalid input: ${validationResult.error.message}`);
|
|
177
|
-
}
|
|
178
|
-
const { agentStates, threshold } = validationResult.data;
|
|
179
|
-
logger.debug('Processing consensus verification', {
|
|
180
|
-
agentCount: agentStates.length,
|
|
181
|
-
threshold,
|
|
182
|
-
});
|
|
183
|
-
if (agentStates.length === 0) {
|
|
184
|
-
return errorResult('No agent states provided');
|
|
185
|
-
}
|
|
186
|
-
// Validate embedding dimensions are consistent
|
|
187
|
-
const firstDim = agentStates[0].embedding.length;
|
|
188
|
-
for (let i = 1; i < agentStates.length; i++) {
|
|
189
|
-
if (agentStates[i].embedding.length !== firstDim) {
|
|
190
|
-
return errorResult(`Embedding dimension mismatch: agent ${agentStates[i].agentId} has ` +
|
|
191
|
-
`${agentStates[i].embedding.length} dimensions, expected ${firstDim}`);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
const embeddings = agentStates.map(s => s.embedding);
|
|
195
|
-
let coherenceEnergy;
|
|
196
|
-
let divergentAgents;
|
|
197
|
-
// Try to use WASM bridge if available
|
|
198
|
-
if (context?.bridge?.initialized) {
|
|
199
|
-
try {
|
|
200
|
-
logger.debug('Using WASM bridge for coherence check');
|
|
201
|
-
const float32Embeddings = embeddings.map(e => new Float32Array(e));
|
|
202
|
-
const result = await context.bridge.checkCoherence(float32Embeddings);
|
|
203
|
-
coherenceEnergy = result.energy;
|
|
204
|
-
// WASM doesn't return divergent agents, compute separately
|
|
205
|
-
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
206
|
-
}
|
|
207
|
-
catch (wasmError) {
|
|
208
|
-
logger.warn('WASM bridge failed, falling back to JS implementation', {
|
|
209
|
-
error: wasmError instanceof Error ? wasmError.message : String(wasmError),
|
|
210
|
-
});
|
|
211
|
-
coherenceEnergy = computeCoherenceEnergy(embeddings);
|
|
212
|
-
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
else {
|
|
216
|
-
// Pure JavaScript fallback
|
|
217
|
-
logger.debug('Using JavaScript fallback for consensus verification');
|
|
218
|
-
coherenceEnergy = computeCoherenceEnergy(embeddings);
|
|
219
|
-
divergentAgents = identifyDivergentAgents(agentStates, threshold);
|
|
220
|
-
}
|
|
221
|
-
// Compute additional metrics
|
|
222
|
-
const similarityMatrix = computeSimilarityMatrix(embeddings);
|
|
223
|
-
const { stable: connectivityStable, degreeRatio } = computeConnectivityStability(similarityMatrix);
|
|
224
|
-
const voteAgreement = computeVoteAgreement(agentStates);
|
|
225
|
-
// Coherence score is inverse of energy
|
|
226
|
-
const coherenceScore = 1 - coherenceEnergy;
|
|
227
|
-
// Agreement ratio combines embedding coherence and vote agreement
|
|
228
|
-
const agreementRatio = (coherenceScore + voteAgreement) / 2;
|
|
229
|
-
// Consensus is verified if agreement exceeds threshold and no major divergence
|
|
230
|
-
const verified = agreementRatio >= threshold &&
|
|
231
|
-
divergentAgents.length <= Math.floor(agentStates.length * 0.2); // Allow 20% minority
|
|
232
|
-
const output = {
|
|
233
|
-
verified,
|
|
234
|
-
coherenceScore,
|
|
235
|
-
divergentAgents,
|
|
236
|
-
details: {
|
|
237
|
-
agreementRatio,
|
|
238
|
-
coherenceEnergy,
|
|
239
|
-
connectivityStable,
|
|
240
|
-
degreeRatio,
|
|
241
|
-
interpretation: getInterpretation(verified, coherenceScore, divergentAgents, connectivityStable),
|
|
242
|
-
agentCount: agentStates.length,
|
|
243
|
-
},
|
|
244
|
-
};
|
|
245
|
-
const duration = performance.now() - startTime;
|
|
246
|
-
logger.info('Consensus verification completed', {
|
|
247
|
-
verified,
|
|
248
|
-
coherenceScore: coherenceScore.toFixed(4),
|
|
249
|
-
divergentAgents: divergentAgents.length,
|
|
250
|
-
durationMs: duration.toFixed(2),
|
|
251
|
-
});
|
|
252
|
-
return successResult(output);
|
|
253
|
-
}
|
|
254
|
-
catch (error) {
|
|
255
|
-
const duration = performance.now() - startTime;
|
|
256
|
-
logger.error('Consensus verification failed', {
|
|
257
|
-
error: error instanceof Error ? error.message : String(error),
|
|
258
|
-
durationMs: duration.toFixed(2),
|
|
259
|
-
});
|
|
260
|
-
return errorResult(error instanceof Error ? error : new Error(String(error)));
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* pr_consensus_verify MCP Tool Definition
|
|
265
|
-
*/
|
|
266
|
-
export const consensusVerifyTool = {
|
|
267
|
-
name: 'pr_consensus_verify',
|
|
268
|
-
description: 'Verify multi-agent consensus using cosine-similarity coherence analysis. Identifies divergent agents, measures agreement ratios, and checks connectivity stability via degree-ratio heuristic.',
|
|
269
|
-
category: 'consensus',
|
|
270
|
-
version: '0.1.3',
|
|
271
|
-
tags: ['consensus', 'multi-agent', 'coherence', 'swarm', 'ai-interpretability'],
|
|
272
|
-
cacheable: false, // Agent states change frequently
|
|
273
|
-
inputSchema: {
|
|
274
|
-
type: 'object',
|
|
275
|
-
properties: {
|
|
276
|
-
agentStates: {
|
|
277
|
-
type: 'array',
|
|
278
|
-
items: {
|
|
279
|
-
type: 'object',
|
|
280
|
-
properties: {
|
|
281
|
-
agentId: { type: 'string', description: 'Unique agent identifier' },
|
|
282
|
-
embedding: {
|
|
283
|
-
type: 'array',
|
|
284
|
-
items: { type: 'number' },
|
|
285
|
-
description: 'Agent state embedding vector',
|
|
286
|
-
},
|
|
287
|
-
vote: { type: 'string', description: 'Agent vote or decision' },
|
|
288
|
-
metadata: { type: 'object', description: 'Additional agent metadata' },
|
|
289
|
-
},
|
|
290
|
-
required: ['agentId', 'embedding'],
|
|
291
|
-
},
|
|
292
|
-
description: 'Array of agent states to verify consensus',
|
|
293
|
-
},
|
|
294
|
-
threshold: {
|
|
295
|
-
type: 'number',
|
|
296
|
-
default: 0.8,
|
|
297
|
-
description: 'Required agreement threshold (0-1)',
|
|
298
|
-
},
|
|
299
|
-
},
|
|
300
|
-
required: ['agentStates'],
|
|
301
|
-
},
|
|
302
|
-
handler,
|
|
303
|
-
};
|
|
304
|
-
export default consensusVerifyTool;
|
|
305
|
-
//# sourceMappingURL=consensus-verify.js.map
|
|
@@ -1,16 +0,0 @@
|
|
|
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
|
-
* Uses cosine similarity on vectors to compute coherence energy.
|
|
7
|
-
* When no pre-computed embeddings are supplied, falls back to a deterministic
|
|
8
|
-
* hash-based vector (structural proxy, not semantic similarity).
|
|
9
|
-
*/
|
|
10
|
-
import type { MCPTool } from './types.js';
|
|
11
|
-
/**
|
|
12
|
-
* pr_memory_gate MCP Tool Definition
|
|
13
|
-
*/
|
|
14
|
-
export declare const memoryGateTool: MCPTool;
|
|
15
|
-
export default memoryGateTool;
|
|
16
|
-
//# sourceMappingURL=memory-gate.d.ts.map
|