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.
Files changed (54) hide show
  1. package/.claude/scheduled_tasks.lock +1 -1
  2. package/package.json +1 -1
  3. package/packages/@monomind/cli/dist/src/mcp-client.js +7 -0
  4. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.d.ts +15 -0
  5. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/causal-infer.js +347 -0
  6. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.d.ts +15 -0
  7. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/coherence-check.js +206 -0
  8. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.d.ts +15 -0
  9. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/consensus-verify.js +303 -0
  10. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.d.ts +15 -0
  11. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/memory-gate.js +266 -0
  12. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.d.ts +15 -0
  13. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/quantum-topology.js +406 -0
  14. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.d.ts +15 -0
  15. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/spectral-analyze.js +293 -0
  16. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.d.ts +277 -0
  17. package/packages/@monomind/cli/dist/src/mcp-tools/coherence/types.js +159 -0
  18. package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.d.ts +9 -0
  19. package/packages/@monomind/cli/dist/src/mcp-tools/coherence-tools.js +25 -0
  20. package/packages/@monomind/cli/dist/src/mcp-tools/quality/chaos-resilience/chaos-inject.d.ts +163 -0
  21. package/packages/@monomind/cli/dist/src/mcp-tools/quality/chaos-resilience/chaos-inject.js +414 -0
  22. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/analyze-coverage.d.ts +128 -0
  23. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/analyze-coverage.js +375 -0
  24. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.d.ts +161 -0
  25. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/prioritize-gaps.js +423 -0
  26. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/track-trends.d.ts +165 -0
  27. package/packages/@monomind/cli/dist/src/mcp-tools/quality/coverage-analysis/track-trends.js +395 -0
  28. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/analyze-root-cause.d.ts +165 -0
  29. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/analyze-root-cause.js +508 -0
  30. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/find-similar-defects.d.ts +147 -0
  31. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/find-similar-defects.js +391 -0
  32. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/predict-defects.d.ts +147 -0
  33. package/packages/@monomind/cli/dist/src/mcp-tools/quality/defect-intelligence/predict-defects.js +422 -0
  34. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/assess-readiness.d.ts +185 -0
  35. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/assess-readiness.js +437 -0
  36. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/calculate-risk.d.ts +166 -0
  37. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/calculate-risk.js +410 -0
  38. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/evaluate-quality-gate.d.ts +201 -0
  39. package/packages/@monomind/cli/dist/src/mcp-tools/quality/quality-assessment/evaluate-quality-gate.js +363 -0
  40. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/audit-compliance.d.ts +166 -0
  41. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/audit-compliance.js +394 -0
  42. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/detect-secrets.d.ts +129 -0
  43. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/detect-secrets.js +383 -0
  44. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/security-scan.d.ts +171 -0
  45. package/packages/@monomind/cli/dist/src/mcp-tools/quality/security-compliance/security-scan.js +476 -0
  46. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/generate-tests.d.ts +147 -0
  47. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/generate-tests.js +400 -0
  48. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/suggest-tests.d.ts +145 -0
  49. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/suggest-tests.js +328 -0
  50. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/tdd-cycle.d.ts +126 -0
  51. package/packages/@monomind/cli/dist/src/mcp-tools/quality/test-generation/tdd-cycle.js +348 -0
  52. package/packages/@monomind/cli/dist/src/mcp-tools/quality-tools.d.ts +9 -0
  53. package/packages/@monomind/cli/dist/src/mcp-tools/quality-tools.js +308 -0
  54. package/packages/@monomind/cli/package.json +1 -1
@@ -1 +1 @@
1
- {"sessionId":"ed60b548-7aa2-4e96-bcec-4eaf8aa33732","pid":74650,"procStart":"Mon Jun 1 16:07:08 2026","acquiredAt":1780344677932}
1
+ {"sessionId":"db24c21a-e929-4aba-911b-4cdb7fc5c3d5","pid":2346,"procStart":"Wed Jun 24 16:31:36 2026","acquiredAt":1782380072591}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monomind",
3
- "version": "1.15.3",
3
+ "version": "1.15.5",
4
4
  "description": "Monomind - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -43,6 +43,9 @@ import { monographTools } from './mcp-tools/monograph-tools.js';
43
43
  import { coverageRouterTools } from './monovector/coverage-tools.js';
44
44
  // A2A Agent Card protocol (source: https://a2a-protocol.org)
45
45
  import { a2aTools } from './mcp-tools/a2a-tools.js';
46
+ // Quality (agentic-qe) and Coherence (prime-radiant) core tools
47
+ import { qualityTools } from './mcp-tools/quality-tools.js';
48
+ import { coherenceTools } from './mcp-tools/coherence-tools.js';
46
49
  /**
47
50
  * MCP Tool Registry
48
51
  * Maps tool names to their handler functions
@@ -100,6 +103,10 @@ registerTools([
100
103
  ...coverageRouterTools,
101
104
  // A2A Agent Card protocol (source: https://a2a-protocol.org)
102
105
  ...a2aTools,
106
+ // Quality tools (migrated from agentic-qe plugin)
107
+ ...qualityTools,
108
+ // Coherence tools (migrated from prime-radiant plugin)
109
+ ...coherenceTools,
103
110
  ]);
104
111
  /**
105
112
  * MCP Client Error
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Causal Inference Tool - pr_causal_infer
3
+ *
4
+ * Performs causal inference using do-calculus.
5
+ * Estimates causal effects, identifies confounders, and finds backdoor paths.
6
+ *
7
+ * Uses CausalEngine from prime-radiant-advanced-wasm
8
+ */
9
+ import type { MCPTool } from './types.js';
10
+ /**
11
+ * pr_causal_infer MCP Tool Definition
12
+ */
13
+ export declare const causalInferTool: MCPTool;
14
+ export default causalInferTool;
15
+ //# sourceMappingURL=causal-infer.d.ts.map
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Causal Inference Tool - pr_causal_infer
3
+ *
4
+ * Performs causal inference using do-calculus.
5
+ * Estimates causal effects, identifies confounders, and finds backdoor paths.
6
+ *
7
+ * Uses CausalEngine from prime-radiant-advanced-wasm
8
+ */
9
+ import { CausalInputSchema, successResult, errorResult, } from './types.js';
10
+ // Default logger
11
+ const defaultLogger = {
12
+ debug: (msg, meta) => console.debug(`[pr_causal_infer] ${msg}`, meta),
13
+ info: (msg, meta) => console.info(`[pr_causal_infer] ${msg}`, meta),
14
+ warn: (msg, meta) => console.warn(`[pr_causal_infer] ${msg}`, meta),
15
+ error: (msg, meta) => console.error(`[pr_causal_infer] ${msg}`, meta),
16
+ };
17
+ function buildGraphStructure(graph) {
18
+ const nodes = new Map();
19
+ // Initialize nodes
20
+ for (const nodeId of graph.nodes) {
21
+ nodes.set(nodeId, {
22
+ id: nodeId,
23
+ parents: new Set(),
24
+ children: new Set(),
25
+ });
26
+ }
27
+ // Add edges
28
+ for (const [from, to] of graph.edges) {
29
+ const fromNode = nodes.get(from);
30
+ const toNode = nodes.get(to);
31
+ if (fromNode && toNode) {
32
+ fromNode.children.add(to);
33
+ toNode.parents.add(from);
34
+ }
35
+ }
36
+ return nodes;
37
+ }
38
+ /**
39
+ * Find all ancestors of a node (including the node itself)
40
+ */
41
+ function findAncestors(nodeId, graph) {
42
+ const ancestors = new Set();
43
+ const queue = [nodeId];
44
+ while (queue.length > 0) {
45
+ const current = queue.shift();
46
+ if (ancestors.has(current))
47
+ continue;
48
+ ancestors.add(current);
49
+ const node = graph.get(current);
50
+ if (node) {
51
+ for (const parent of node.parents) {
52
+ queue.push(parent);
53
+ }
54
+ }
55
+ }
56
+ return ancestors;
57
+ }
58
+ /**
59
+ * Find all descendants of a node (including the node itself)
60
+ */
61
+ function findDescendants(nodeId, graph) {
62
+ const descendants = new Set();
63
+ const queue = [nodeId];
64
+ while (queue.length > 0) {
65
+ const current = queue.shift();
66
+ if (descendants.has(current))
67
+ continue;
68
+ descendants.add(current);
69
+ const node = graph.get(current);
70
+ if (node) {
71
+ for (const child of node.children) {
72
+ queue.push(child);
73
+ }
74
+ }
75
+ }
76
+ return descendants;
77
+ }
78
+ /**
79
+ * Identify confounders (common causes of treatment and outcome)
80
+ */
81
+ function identifyConfounders(treatment, outcome, graph) {
82
+ const treatmentAncestors = findAncestors(treatment, graph);
83
+ const outcomeAncestors = findAncestors(outcome, graph);
84
+ // Confounders are ancestors of both treatment and outcome
85
+ // that are not the treatment itself
86
+ const confounders = [];
87
+ for (const ancestor of treatmentAncestors) {
88
+ if (ancestor !== treatment && ancestor !== outcome && outcomeAncestors.has(ancestor)) {
89
+ confounders.push(ancestor);
90
+ }
91
+ }
92
+ return confounders;
93
+ }
94
+ /**
95
+ * Find backdoor paths from treatment to outcome
96
+ * A backdoor path is a path that goes into the treatment node
97
+ */
98
+ function findBackdoorPaths(treatment, outcome, graph, maxPaths = 10) {
99
+ const backdoorPaths = [];
100
+ const treatmentNode = graph.get(treatment);
101
+ if (!treatmentNode)
102
+ return [];
103
+ // Start from each parent of treatment (backdoor)
104
+ for (const parent of treatmentNode.parents) {
105
+ const paths = findAllPaths(parent, outcome, graph, new Set([treatment]), maxPaths - backdoorPaths.length);
106
+ for (const path of paths) {
107
+ backdoorPaths.push([treatment, ...path]);
108
+ if (backdoorPaths.length >= maxPaths)
109
+ break;
110
+ }
111
+ if (backdoorPaths.length >= maxPaths)
112
+ break;
113
+ }
114
+ return backdoorPaths;
115
+ }
116
+ /**
117
+ * Find all paths from source to target (BFS with path tracking)
118
+ */
119
+ function findAllPaths(source, target, graph, exclude, maxPaths) {
120
+ const paths = [];
121
+ const queue = [{ node: source, path: [source] }];
122
+ while (queue.length > 0 && paths.length < maxPaths) {
123
+ const { node, path } = queue.shift();
124
+ if (node === target) {
125
+ paths.push(path);
126
+ continue;
127
+ }
128
+ const currentNode = graph.get(node);
129
+ if (!currentNode)
130
+ continue;
131
+ // Consider both parents and children for undirected path finding
132
+ const neighbors = new Set([...currentNode.parents, ...currentNode.children]);
133
+ for (const neighbor of neighbors) {
134
+ if (!path.includes(neighbor) && !exclude.has(neighbor)) {
135
+ queue.push({
136
+ node: neighbor,
137
+ path: [...path, neighbor],
138
+ });
139
+ }
140
+ }
141
+ }
142
+ return paths;
143
+ }
144
+ /**
145
+ * Check if intervention is valid (treatment must exist and have outgoing edges)
146
+ */
147
+ function validateIntervention(treatment, outcome, graph) {
148
+ const treatmentNode = graph.get(treatment);
149
+ const outcomeNode = graph.get(outcome);
150
+ if (!treatmentNode || !outcomeNode) {
151
+ return false;
152
+ }
153
+ // Check if there's any path from treatment to outcome
154
+ const descendants = findDescendants(treatment, graph);
155
+ return descendants.has(outcome);
156
+ }
157
+ /**
158
+ * Estimate causal effect using backdoor adjustment
159
+ * This is a simplified estimation - real estimation requires data
160
+ */
161
+ function estimateCausalEffect(treatment, outcome, confounders, backdoorPaths, graph) {
162
+ // Effect estimation heuristic based on graph structure
163
+ // In practice, this requires observational data
164
+ // Base effect: based on direct path existence
165
+ const treatmentNode = graph.get(treatment);
166
+ let baseEffect = treatmentNode?.children.has(outcome) ? 0.5 : 0.3;
167
+ // Adjust for confounders (more confounders = less identifiable effect)
168
+ const confounderPenalty = Math.min(confounders.length * 0.1, 0.3);
169
+ // Adjust for backdoor paths (more unblocked paths = less reliable)
170
+ const pathPenalty = Math.min(backdoorPaths.length * 0.05, 0.2);
171
+ const effect = Math.max(0, baseEffect - confounderPenalty - pathPenalty);
172
+ // Confidence decreases with confounders and backdoor paths
173
+ const confidence = Math.max(0.1, 1 - confounderPenalty - pathPenalty);
174
+ return { effect, confidence };
175
+ }
176
+ /**
177
+ * Get interpretation of causal analysis results
178
+ */
179
+ function getInterpretation(interventionValid, confounders, backdoorPaths, confidence) {
180
+ if (!interventionValid) {
181
+ return 'Intervention is not valid - no causal path exists from treatment to outcome';
182
+ }
183
+ if (confounders.length === 0 && backdoorPaths.length === 0) {
184
+ return 'Clean causal identification - no confounding detected';
185
+ }
186
+ if (confidence > 0.8) {
187
+ return 'Strong causal identification - confounders can be adjusted for';
188
+ }
189
+ if (confidence > 0.5) {
190
+ return `Moderate causal identification - ${confounders.length} confounder(s) require adjustment`;
191
+ }
192
+ return `Weak causal identification - multiple confounders (${confounders.length}) and backdoor paths (${backdoorPaths.length}) detected`;
193
+ }
194
+ /**
195
+ * Handler for pr_causal_infer tool
196
+ */
197
+ async function handler(input, context) {
198
+ const logger = context?.logger ?? defaultLogger;
199
+ const startTime = performance.now();
200
+ try {
201
+ // Validate input
202
+ const validationResult = CausalInputSchema.safeParse(input);
203
+ if (!validationResult.success) {
204
+ logger.error('Input validation failed', { error: validationResult.error.message });
205
+ return errorResult(`Invalid input: ${validationResult.error.message}`);
206
+ }
207
+ const { graph, intervention, outcome } = validationResult.data;
208
+ logger.debug('Processing causal inference', {
209
+ nodes: graph.nodes.length,
210
+ edges: graph.edges.length,
211
+ intervention,
212
+ outcome,
213
+ });
214
+ // Validate nodes exist
215
+ if (!graph.nodes.includes(intervention)) {
216
+ return errorResult(`Intervention variable "${intervention}" not found in graph nodes`);
217
+ }
218
+ if (!graph.nodes.includes(outcome)) {
219
+ return errorResult(`Outcome variable "${outcome}" not found in graph nodes`);
220
+ }
221
+ const maxBackdoorPaths = context?.config?.causal?.maxBackdoorPaths ?? 10;
222
+ // Note: confidenceThreshold can be used for filtering in future enhancements
223
+ void (context?.config?.causal?.confidenceThreshold ?? 0.8);
224
+ let effect;
225
+ let confidence;
226
+ let confounders;
227
+ let backdoorPaths;
228
+ let interventionValid;
229
+ // Try to use WASM bridge if available
230
+ if (context?.bridge?.initialized) {
231
+ try {
232
+ logger.debug('Using WASM bridge for causal inference');
233
+ const result = await context.bridge.inferCausal(graph, intervention, outcome);
234
+ effect = result.effect;
235
+ confidence = result.confidence;
236
+ confounders = result.confounders;
237
+ backdoorPaths = result.backdoorPaths;
238
+ interventionValid = result.interventionValid;
239
+ }
240
+ catch (wasmError) {
241
+ logger.warn('WASM bridge failed, falling back to JS implementation', {
242
+ error: wasmError instanceof Error ? wasmError.message : String(wasmError),
243
+ });
244
+ // Use JavaScript implementation
245
+ const graphStructure = buildGraphStructure(graph);
246
+ interventionValid = validateIntervention(intervention, outcome, graphStructure);
247
+ confounders = identifyConfounders(intervention, outcome, graphStructure);
248
+ backdoorPaths = findBackdoorPaths(intervention, outcome, graphStructure, maxBackdoorPaths);
249
+ const estimation = estimateCausalEffect(intervention, outcome, confounders, backdoorPaths, graphStructure);
250
+ effect = estimation.effect;
251
+ confidence = estimation.confidence;
252
+ }
253
+ }
254
+ else {
255
+ // Pure JavaScript fallback
256
+ logger.debug('Using JavaScript fallback for causal inference');
257
+ const graphStructure = buildGraphStructure(graph);
258
+ interventionValid = validateIntervention(intervention, outcome, graphStructure);
259
+ confounders = identifyConfounders(intervention, outcome, graphStructure);
260
+ backdoorPaths = findBackdoorPaths(intervention, outcome, graphStructure, maxBackdoorPaths);
261
+ const estimation = estimateCausalEffect(intervention, outcome, confounders, backdoorPaths, graphStructure);
262
+ effect = estimation.effect;
263
+ confidence = estimation.confidence;
264
+ }
265
+ const output = {
266
+ effect,
267
+ confidence,
268
+ backdoorPaths: backdoorPaths.map(p => p.join(' -> ')),
269
+ details: {
270
+ confounders,
271
+ interventionValid,
272
+ interpretation: getInterpretation(interventionValid, confounders, backdoorPaths, confidence),
273
+ nodeCount: graph.nodes.length,
274
+ edgeCount: graph.edges.length,
275
+ },
276
+ };
277
+ const duration = performance.now() - startTime;
278
+ logger.info('Causal inference completed', {
279
+ effect: effect.toFixed(4),
280
+ confidence: confidence.toFixed(4),
281
+ confounders: confounders.length,
282
+ backdoorPaths: backdoorPaths.length,
283
+ interventionValid,
284
+ durationMs: duration.toFixed(2),
285
+ });
286
+ return successResult(output);
287
+ }
288
+ catch (error) {
289
+ const duration = performance.now() - startTime;
290
+ logger.error('Causal inference failed', {
291
+ error: error instanceof Error ? error.message : String(error),
292
+ durationMs: duration.toFixed(2),
293
+ });
294
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
295
+ }
296
+ }
297
+ /**
298
+ * pr_causal_infer MCP Tool Definition
299
+ */
300
+ export const causalInferTool = {
301
+ name: 'pr_causal_infer',
302
+ description: 'Perform causal inference using do-calculus. Estimates causal effects, identifies confounders, and finds backdoor paths. Uses CausalEngine for mathematical causal analysis.',
303
+ category: 'causal',
304
+ version: '0.1.3',
305
+ tags: ['causal', 'do-calculus', 'confounders', 'backdoor-paths', 'ai-interpretability'],
306
+ cacheable: true,
307
+ cacheTTL: 60000,
308
+ inputSchema: {
309
+ type: 'object',
310
+ properties: {
311
+ graph: {
312
+ type: 'object',
313
+ properties: {
314
+ nodes: {
315
+ type: 'array',
316
+ items: { type: 'string' },
317
+ description: 'List of variable names',
318
+ },
319
+ edges: {
320
+ type: 'array',
321
+ items: {
322
+ type: 'array',
323
+ items: { type: 'string' },
324
+ minItems: 2,
325
+ maxItems: 2,
326
+ },
327
+ description: 'Directed edges as [from, to] pairs',
328
+ },
329
+ },
330
+ required: ['nodes', 'edges'],
331
+ description: 'Causal graph with nodes and directed edges',
332
+ },
333
+ intervention: {
334
+ type: 'string',
335
+ description: 'Treatment/intervention variable',
336
+ },
337
+ outcome: {
338
+ type: 'string',
339
+ description: 'Outcome variable to measure effect on',
340
+ },
341
+ },
342
+ required: ['graph', 'intervention', 'outcome'],
343
+ },
344
+ handler,
345
+ };
346
+ export default causalInferTool;
347
+ //# sourceMappingURL=causal-infer.js.map
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,206 @@
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 { CoherenceInputSchema, successResult, errorResult, } from './types.js';
10
+ // Default logger for when context doesn't provide one
11
+ const defaultLogger = {
12
+ debug: (msg, meta) => console.debug(`[pr_coherence_check] ${msg}`, meta),
13
+ info: (msg, meta) => console.info(`[pr_coherence_check] ${msg}`, meta),
14
+ warn: (msg, meta) => console.warn(`[pr_coherence_check] ${msg}`, meta),
15
+ error: (msg, meta) => console.error(`[pr_coherence_check] ${msg}`, meta),
16
+ };
17
+ /**
18
+ * Compute Sheaf Laplacian energy for coherence detection
19
+ *
20
+ * The Sheaf Laplacian measures how well local data sections can be
21
+ * glued together into a global section. High energy indicates contradictions.
22
+ *
23
+ * For vectors v1, v2, ..., vn:
24
+ * 1. Construct a sheaf over the complete graph
25
+ * 2. Compute the Laplacian matrix L = D - A (where A captures similarities)
26
+ * 3. Energy = sum of disagreements across edges
27
+ */
28
+ function computeSheafLaplacianEnergy(vectors) {
29
+ if (vectors.length < 2)
30
+ return 0;
31
+ const n = vectors.length;
32
+ let totalEnergy = 0;
33
+ let edgeCount = 0;
34
+ // Compute pairwise disagreement (1 - cosine_similarity)
35
+ for (let i = 0; i < n; i++) {
36
+ for (let j = i + 1; j < n; j++) {
37
+ const vi = vectors[i];
38
+ const vj = vectors[j];
39
+ const similarity = cosineSimilarity(vi, vj);
40
+ const disagreement = 1 - Math.max(0, similarity); // Clamp negative similarities
41
+ totalEnergy += disagreement;
42
+ edgeCount++;
43
+ }
44
+ }
45
+ // Normalize by number of edges
46
+ return edgeCount > 0 ? totalEnergy / edgeCount : 0;
47
+ }
48
+ /**
49
+ * Detect contradictions in the vector set
50
+ */
51
+ function detectContradictions(vectors, threshold) {
52
+ const violations = [];
53
+ const n = vectors.length;
54
+ for (let i = 0; i < n; i++) {
55
+ for (let j = i + 1; j < n; j++) {
56
+ const vi = vectors[i];
57
+ const vj = vectors[j];
58
+ const similarity = cosineSimilarity(vi, vj);
59
+ // Negative similarity indicates potential contradiction
60
+ if (similarity < -0.3) {
61
+ violations.push(`Contradiction between vectors ${i} and ${j} (similarity: ${similarity.toFixed(3)})`);
62
+ }
63
+ // Low similarity with high threshold indicates inconsistency
64
+ else if (similarity < threshold && similarity > 0) {
65
+ violations.push(`Weak coherence between vectors ${i} and ${j} (similarity: ${similarity.toFixed(3)})`);
66
+ }
67
+ }
68
+ }
69
+ return violations;
70
+ }
71
+ /**
72
+ * Calculate cosine similarity
73
+ */
74
+ function cosineSimilarity(a, b) {
75
+ if (a.length !== b.length)
76
+ return 0;
77
+ let dotProduct = 0;
78
+ let normA = 0;
79
+ let normB = 0;
80
+ for (let i = 0; i < a.length; i++) {
81
+ const ai = a[i];
82
+ const bi = b[i];
83
+ dotProduct += ai * bi;
84
+ normA += ai * ai;
85
+ normB += bi * bi;
86
+ }
87
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
88
+ return denominator > 0 ? dotProduct / denominator : 0;
89
+ }
90
+ /**
91
+ * Get interpretation of energy level
92
+ */
93
+ function getInterpretation(energy) {
94
+ if (energy < 0.1)
95
+ return 'Fully coherent - vectors are highly consistent';
96
+ if (energy < 0.3)
97
+ return 'Minor inconsistencies - generally coherent with small variations';
98
+ if (energy < 0.5)
99
+ return 'Moderate inconsistencies - some conflicting information detected';
100
+ if (energy < 0.7)
101
+ return 'Significant contradictions - vectors contain conflicting content';
102
+ return 'Major contradictions detected - high disagreement between vectors';
103
+ }
104
+ /**
105
+ * Handler for pr_coherence_check tool
106
+ */
107
+ async function handler(input, context) {
108
+ const logger = context?.logger ?? defaultLogger;
109
+ const startTime = performance.now();
110
+ try {
111
+ // Validate input
112
+ const validationResult = CoherenceInputSchema.safeParse(input);
113
+ if (!validationResult.success) {
114
+ logger.error('Input validation failed', { error: validationResult.error.message });
115
+ return errorResult(`Invalid input: ${validationResult.error.message}`);
116
+ }
117
+ const { vectors, threshold } = validationResult.data;
118
+ logger.debug('Processing coherence check', { vectorCount: vectors.length, threshold });
119
+ // Convert to Float32Arrays
120
+ const float32Vectors = vectors.map(v => new Float32Array(v));
121
+ let energy;
122
+ let violations;
123
+ // Try to use WASM bridge if available
124
+ if (context?.bridge?.initialized) {
125
+ try {
126
+ logger.debug('Using WASM bridge for coherence check');
127
+ const result = await context.bridge.checkCoherence(float32Vectors);
128
+ energy = result.energy;
129
+ violations = result.violations;
130
+ }
131
+ catch (wasmError) {
132
+ logger.warn('WASM bridge failed, falling back to JS implementation', {
133
+ error: wasmError instanceof Error ? wasmError.message : String(wasmError),
134
+ });
135
+ energy = computeSheafLaplacianEnergy(float32Vectors);
136
+ violations = detectContradictions(float32Vectors, threshold);
137
+ }
138
+ }
139
+ else {
140
+ // Pure JavaScript fallback implementation
141
+ logger.debug('Using JavaScript fallback for coherence check');
142
+ energy = computeSheafLaplacianEnergy(float32Vectors);
143
+ violations = detectContradictions(float32Vectors, threshold);
144
+ }
145
+ const isCoherent = energy < threshold;
146
+ const confidence = 1 - energy;
147
+ const output = {
148
+ energy,
149
+ isCoherent,
150
+ details: {
151
+ violations,
152
+ confidence,
153
+ interpretation: getInterpretation(energy),
154
+ vectorCount: vectors.length,
155
+ threshold,
156
+ },
157
+ };
158
+ const duration = performance.now() - startTime;
159
+ logger.info('Coherence check completed', {
160
+ energy: energy.toFixed(4),
161
+ isCoherent,
162
+ violations: violations.length,
163
+ durationMs: duration.toFixed(2),
164
+ });
165
+ return successResult(output);
166
+ }
167
+ catch (error) {
168
+ const duration = performance.now() - startTime;
169
+ logger.error('Coherence check failed', {
170
+ error: error instanceof Error ? error.message : String(error),
171
+ durationMs: duration.toFixed(2),
172
+ });
173
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
174
+ }
175
+ }
176
+ /**
177
+ * pr_coherence_check MCP Tool Definition
178
+ */
179
+ export const coherenceCheckTool = {
180
+ name: 'pr_coherence_check',
181
+ description: 'Check coherence of vectors using Sheaf Laplacian energy. Energy 0 = fully coherent, 1 = contradictory. Uses CohomologyEngine for mathematical validation of vector consistency.',
182
+ category: 'coherence',
183
+ version: '0.1.3',
184
+ tags: ['coherence', 'sheaf-laplacian', 'contradiction-detection', 'ai-interpretability'],
185
+ cacheable: true,
186
+ cacheTTL: 60000, // 1 minute cache
187
+ inputSchema: {
188
+ type: 'object',
189
+ properties: {
190
+ vectors: {
191
+ type: 'array',
192
+ items: { type: 'array', items: { type: 'number' } },
193
+ description: 'Array of embedding vectors to check for coherence',
194
+ },
195
+ threshold: {
196
+ type: 'number',
197
+ default: 0.3,
198
+ description: 'Energy threshold for coherence (0-1). Lower = stricter coherence requirement.',
199
+ },
200
+ },
201
+ required: ['vectors'],
202
+ },
203
+ handler,
204
+ };
205
+ export default coherenceCheckTool;
206
+ //# sourceMappingURL=coherence-check.js.map
@@ -0,0 +1,15 @@
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 type { MCPTool } from './types.js';
10
+ /**
11
+ * pr_consensus_verify MCP Tool Definition
12
+ */
13
+ export declare const consensusVerifyTool: MCPTool;
14
+ export default consensusVerifyTool;
15
+ //# sourceMappingURL=consensus-verify.d.ts.map