Spaces:
Paused
Paused
File size: 20,640 Bytes
529090e f1a6f7e 529090e f1a6f7e af443cc 529090e f1a6f7e af443cc 529090e f1a6f7e 529090e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 | // HansPedder Agent Controller
// Autonomous testing and improvement agent that runs continuously
// until explicitly stopped
import { eventBus } from '../../mcp/EventBus.js';
import { logger } from '../../utils/logger.js';
import { selfHealing } from '../SelfHealingAdapter.js';
import { errorKnowledgeBase } from '../ErrorKnowledgeBase.js';
interface TestResult {
name: string;
passed: boolean;
duration: number;
error?: string;
timestamp: Date;
}
interface HealthMetrics {
dataflowOk: boolean;
apiLatency: number;
wsConnections: number;
lastIngestion: Date | null;
vectorStoreResponsive: boolean;
mcpConnected: boolean;
}
export class HansPedderAgentController {
private isRunning = false;
private testInterval: NodeJS.Timeout | null = null;
private nudgeInterval: NodeJS.Timeout | null = null;
private testResults: TestResult[] = [];
private healthMetrics: HealthMetrics = {
dataflowOk: false,
apiLatency: 0,
wsConnections: 0,
lastIngestion: null,
vectorStoreResponsive: false,
mcpConnected: false,
};
// Track what areas have been nudged
private nudgedAreas: Set<string> = new Set();
private readonly IMPROVEMENT_AREAS = [
'error-handling',
'loading-states',
'empty-states',
'data-freshness',
'connection-recovery',
'cache-optimization',
'api-retry-logic',
'user-feedback',
'accessibility',
'performance-monitoring',
];
start() {
if (this.isRunning) {
logger.warn('HansPedder already running');
return;
}
this.isRunning = true;
logger.info('π€ HansPedder Agent Controller started');
logger.info(' Mode: Continuous testing + 30min improvement nudges');
logger.info(' Priority: Robustness β Usability β Value Creation');
// Run tests every 2 minutes
this.testInterval = setInterval(() => this.runTestSuite(), 2 * 60 * 1000);
// Nudge new areas every 30 minutes
this.nudgeInterval = setInterval(() => this.nudgeImprovement(), 30 * 60 * 1000);
// Initial run
this.runTestSuite();
// Listen for events
this.setupEventListeners();
}
stop() {
if (this.testInterval) clearInterval(this.testInterval);
if (this.nudgeInterval) clearInterval(this.nudgeInterval);
this.isRunning = false;
logger.info('π HansPedder Agent Controller stopped');
this.reportFinalStatus();
}
private setupEventListeners() {
// Track ingestion events
eventBus.on('ingestion:emails', () => {
this.healthMetrics.lastIngestion = new Date();
this.healthMetrics.dataflowOk = true;
});
eventBus.on('ingestion:news', () => {
this.healthMetrics.lastIngestion = new Date();
this.healthMetrics.dataflowOk = true;
});
eventBus.on('threat:detected', () => {
this.healthMetrics.lastIngestion = new Date();
this.healthMetrics.dataflowOk = true;
});
// Also track threat feed broadcasts (from OpenPhish etc.)
eventBus.on('threats:broadcast', () => {
this.healthMetrics.lastIngestion = new Date();
this.healthMetrics.dataflowOk = true;
});
eventBus.on('system:heartbeat', (data: any) => {
this.healthMetrics.mcpConnected = true;
});
// Track WebSocket connections
eventBus.on('ws:connected', () => {
this.healthMetrics.wsConnections++;
});
eventBus.on('ws:disconnected', () => {
this.healthMetrics.wsConnections = Math.max(0, this.healthMetrics.wsConnections - 1);
});
}
private async runTestSuite() {
logger.info('π§ͺ Running HansPedder test suite...');
const startTime = Date.now();
const tests = [
this.testDataflow,
this.testVectorStore,
this.testMCPConnection,
this.testAPIEndpoints,
this.testEventBus,
this.testSchedulerRunning,
];
let passed = 0;
let failed = 0;
for (const test of tests) {
try {
const result = await test.call(this);
this.testResults.push(result);
if (result.passed) passed++;
else failed++;
} catch (error) {
failed++;
this.testResults.push({
name: test.name,
passed: false,
duration: 0,
error: (error as Error).message,
timestamp: new Date(),
});
}
}
const duration = Date.now() - startTime;
logger.info(`β
Tests complete: ${passed}/${passed + failed} passed (${duration}ms)`);
// Emit results for UI consumption
eventBus.emit('hanspedder:test-results', {
passed,
failed,
total: passed + failed,
duration,
timestamp: new Date().toISOString(),
health: this.healthMetrics,
});
// Auto-fix if issues detected
if (failed > 0) {
await this.attemptAutoFix();
}
}
private async testDataflow(): Promise<TestResult> {
const start = Date.now();
const name = 'dataflow';
try {
// Check if we've had any ingestion in the last 20 minutes
const lastIngestion = this.healthMetrics.lastIngestion;
const twentyMinutesAgo = new Date(Date.now() - 20 * 60 * 1000);
const passed = lastIngestion !== null && lastIngestion > twentyMinutesAgo;
return {
name,
passed,
duration: Date.now() - start,
error: passed ? undefined : 'No recent data ingestion detected',
timestamp: new Date(),
};
} catch (error) {
return {
name,
passed: false,
duration: Date.now() - start,
error: (error as Error).message,
timestamp: new Date(),
};
}
}
private async testVectorStore(): Promise<TestResult> {
const start = Date.now();
const name = 'vectorStore';
try {
// Import dynamically to avoid circular deps
const { getNeo4jVectorStore } =
await import('../../platform/vector/Neo4jVectorStoreAdapter.js');
const store = getNeo4jVectorStore();
// Try a simple search
const results = await store.search({
text: 'test',
namespace: 'system',
limit: 1,
});
this.healthMetrics.vectorStoreResponsive = true;
return {
name,
passed: true,
duration: Date.now() - start,
timestamp: new Date(),
};
} catch (error) {
this.healthMetrics.vectorStoreResponsive = false;
return {
name,
passed: false,
duration: Date.now() - start,
error: (error as Error).message,
timestamp: new Date(),
};
}
}
private async testMCPConnection(): Promise<TestResult> {
const start = Date.now();
const name = 'mcpConnection';
try {
// Check if MCP tools endpoint responds (indicates server is ready)
// Default to 7860 which is the standard port for WidgeTDC backend (both local and HuggingFace)
const port = process.env.PORT || 7860;
const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;
const response = await fetch(`${baseUrl}/api/mcp/tools`, {
method: 'GET',
signal: AbortSignal.timeout(3000),
});
const passed = response.ok;
if (passed) {
this.healthMetrics.mcpConnected = true;
}
return {
name,
passed,
duration: Date.now() - start,
error: passed ? undefined : `MCP endpoint returned ${response.status}`,
timestamp: new Date(),
};
} catch (error) {
return {
name,
passed: false,
duration: Date.now() - start,
error: (error as Error).message,
timestamp: new Date(),
};
}
}
private async testAPIEndpoints(): Promise<TestResult> {
const start = Date.now();
const name = 'apiEndpoints';
try {
// Test key API endpoints - default to 7860 which is standard for WidgeTDC
const port = process.env.PORT || 7860;
const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;
const endpoints = [
{ url: `${baseUrl}/health`, method: 'GET' },
{ url: `${baseUrl}/api/mcp/route`, method: 'POST', body: JSON.stringify({ tool: 'ping' }) },
];
for (const endpoint of endpoints) {
const response = await fetch(endpoint.url, {
method: endpoint.method,
headers: { 'Content-Type': 'application/json' },
body: endpoint.body,
signal: AbortSignal.timeout(5000),
});
// MCP route returns 400 for invalid tool, but that means server is up
if (!response.ok && !(endpoint.url.includes('/mcp/route') && response.status === 400)) {
throw new Error(`${endpoint.url} returned ${response.status}`);
}
}
return {
name,
passed: true,
duration: Date.now() - start,
timestamp: new Date(),
};
} catch (error) {
return {
name,
passed: false,
duration: Date.now() - start,
error: (error as Error).message,
timestamp: new Date(),
};
}
}
private async testEventBus(): Promise<TestResult> {
const start = Date.now();
const name = 'eventBus';
return new Promise(resolve => {
let received = false;
const handler = () => {
received = true;
};
// Use a known event type for testing
eventBus.on('system:heartbeat', handler);
eventBus.emit('system:heartbeat', { test: true });
// Give it 100ms
setTimeout(() => {
eventBus.off('system:heartbeat', handler);
resolve({
name,
passed: received,
duration: Date.now() - start,
error: received ? undefined : 'Event not received',
timestamp: new Date(),
});
}, 100);
});
}
private async testSchedulerRunning(): Promise<TestResult> {
const start = Date.now();
const name = 'schedulerRunning';
try {
const { dataScheduler } = await import('../ingestion/DataScheduler.js');
// Check if scheduler has tasks
const passed = (dataScheduler as any).isRunning === true;
return {
name,
passed,
duration: Date.now() - start,
error: passed ? undefined : 'DataScheduler not running',
timestamp: new Date(),
};
} catch (error) {
return {
name,
passed: false,
duration: Date.now() - start,
error: (error as Error).message,
timestamp: new Date(),
};
}
}
private async attemptAutoFix() {
logger.info('π§ Attempting auto-fix for failed tests...');
const recentFailures = this.testResults.filter(r => !r.passed).slice(-10);
for (const failure of recentFailures) {
let fixSuccess = false;
let fixAction = '';
switch (failure.name) {
case 'schedulerRunning':
logger.info(' β Restarting DataScheduler...');
fixAction = 'Restart DataScheduler service';
try {
const { dataScheduler } = await import('../ingestion/DataScheduler.js');
dataScheduler.start();
logger.info(' β DataScheduler restarted');
fixSuccess = true;
} catch (e) {
logger.error(' β Failed to restart scheduler:', e);
}
break;
case 'dataflow':
logger.info(' β Triggering manual data refresh...');
fixAction = 'Trigger system force-refresh event';
eventBus.emit('system:force-refresh', {});
logger.info(' β Refresh triggered');
fixSuccess = true;
break;
case 'apiEndpoints':
logger.info(' β API endpoints unreachable - checking backend status...');
fixAction = 'Health check on correct backend port';
try {
const backendPort = process.env.PORT || '7860';
const testUrl = `http://localhost:${backendPort}/health`;
const response = await fetch(testUrl, { signal: AbortSignal.timeout(3000) });
if (response.ok) {
logger.info(` β Backend healthy on port ${backendPort} - frontend may be down`);
fixSuccess = true;
}
} catch (e) {
logger.warn(' β Backend health check failed - service may need restart');
eventBus.emit('system:backend-unhealthy', { error: failure.error });
}
break;
case 'vectorStore':
logger.info(' β Vector store connection issue - attempting reconnect...');
fixAction = 'Reconnect vector store via health ping';
try {
const { getNeo4jVectorStore } =
await import('../../platform/vector/Neo4jVectorStoreAdapter.js');
const store = getNeo4jVectorStore();
await store.search({ text: 'health_check', namespace: 'system', limit: 1 });
logger.info(' β Vector store reconnected');
fixSuccess = true;
} catch (e) {
logger.warn(' β Vector store reconnection failed:', (e as Error).message);
}
break;
case 'mcpConnection':
logger.info(' β MCP connection lost - will auto-reconnect on next heartbeat');
fixAction = 'Reset MCP status and request reconnect';
this.healthMetrics.mcpConnected = false;
eventBus.emit('mcp:reconnect-requested', {});
fixSuccess = true; // Action taken, success depends on reconnect
break;
case 'eventBus':
logger.info(' β Event bus test failed - checking event system...');
fixAction = 'Emit health check event to verify bus';
eventBus.emit('system:health-check', { source: 'auto-fix' });
logger.info(' β Health check event emitted');
fixSuccess = true;
break;
default:
logger.debug(` β No auto-fix available for: ${failure.name}`);
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// REPORT FIX ATTEMPT TO DATABASE - All fixes get reported
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if (fixAction) {
try {
// Ingest the error pattern to ErrorKnowledgeBase for learning
const patternAdded = errorKnowledgeBase.ingest({
source: 'internal-logs',
category: this.mapTestNameToCategory(failure.name),
signature: failure.error || `${failure.name} test failure`,
description: `HansPedder auto-fix: ${fixAction}`,
severity: fixSuccess ? 'low' : 'medium',
solutions: [
{
description: fixAction,
confidence: fixSuccess ? 0.8 : 0.3,
source: 'hanspedder-agent',
verified: fixSuccess,
successCount: fixSuccess ? 1 : 0,
failureCount: fixSuccess ? 0 : 1,
lastUsed: new Date(),
},
],
tags: ['hanspedder', 'auto-fix', failure.name],
});
// Log the report
logger.info(
` π Reported to database: ${fixAction} (${fixSuccess ? 'SUCCESS' : 'FAILED'})${patternAdded ? ' [NEW PATTERN]' : ' [UPDATED]'}`
);
// Emit event for dashboard consumption
eventBus.emit('hanspedder:fix-reported', {
testName: failure.name,
error: failure.error,
fixAction,
fixSuccess,
patternAdded,
timestamp: new Date().toISOString(),
});
// If Neo4j is available, persist immediately for important patterns
if (!fixSuccess) {
const patterns = errorKnowledgeBase.findMatches(failure.error || failure.name, 1);
if (patterns.length > 0) {
await errorKnowledgeBase.persistToNeo4j(patterns[0]);
logger.debug(` β Persisted failure pattern to Neo4j`);
}
}
} catch (reportError) {
logger.warn(` β Failed to report fix to database:`, (reportError as Error).message);
}
}
}
}
/**
* Map test names to ErrorKnowledgeBase categories
*/
private mapTestNameToCategory(
testName: string
): 'network' | 'database' | 'runtime' | 'api' | 'configuration' {
const mapping: Record<string, 'network' | 'database' | 'runtime' | 'api' | 'configuration'> = {
dataflow: 'runtime',
vectorStore: 'database',
mcpConnection: 'network',
apiEndpoints: 'api',
eventBus: 'runtime',
schedulerRunning: 'configuration',
};
return mapping[testName] || 'runtime';
}
private nudgeImprovement() {
// Find an area we haven't nudged yet
const unNudged = this.IMPROVEMENT_AREAS.filter(a => !this.nudgedAreas.has(a));
if (unNudged.length === 0) {
// Reset and start over
this.nudgedAreas.clear();
logger.info('π All improvement areas covered - resetting cycle');
return;
}
const area = unNudged[0];
this.nudgedAreas.add(area);
logger.info(`π‘ Improvement Nudge: ${area}`);
logger.info(` Suggested action: Review and enhance ${area} across all widgets`);
// Emit for UI/dashboard
eventBus.emit('hanspedder:nudge', {
area,
timestamp: new Date().toISOString(),
remaining: unNudged.length - 1,
suggestions: this.getSuggestionsForArea(area),
});
}
private getSuggestionsForArea(area: string): string[] {
const suggestions: Record<string, string[]> = {
'error-handling': [
'Add try-catch blocks to all async operations',
'Show user-friendly error messages',
'Implement error boundaries in React components',
],
'loading-states': [
'Add skeleton loaders to widgets',
'Show progress indicators for long operations',
'Disable buttons during submissions',
],
'empty-states': [
'Add helpful messages when no data available',
'Suggest actions users can take',
'Show example data or tutorials',
],
'data-freshness': [
'Display "last updated" timestamps',
'Add manual refresh buttons',
'Implement auto-refresh with intervals',
],
'connection-recovery': [
'Auto-reconnect WebSocket on disconnect',
'Queue actions during offline mode',
'Show connection status indicator',
],
'cache-optimization': [
'Implement request deduplication',
'Add local storage caching',
'Use stale-while-revalidate pattern',
],
'api-retry-logic': [
'Add exponential backoff for retries',
'Implement circuit breaker pattern',
'Handle rate limiting gracefully',
],
'user-feedback': [
'Add toast notifications for actions',
'Show success/failure confirmations',
'Implement undo functionality',
],
accessibility: [
'Add ARIA labels to interactive elements',
'Ensure keyboard navigation works',
'Check color contrast ratios',
],
'performance-monitoring': [
'Track widget render times',
'Monitor API response times',
'Log slow operations for analysis',
],
};
return suggestions[area] || ['Review and improve this area'];
}
private reportFinalStatus() {
const totalTests = this.testResults.length;
const passedTests = this.testResults.filter(r => r.passed).length;
const passRate = totalTests > 0 ? ((passedTests / totalTests) * 100).toFixed(1) : 0;
logger.info('π HansPedder Final Report:');
logger.info(` Total tests run: ${totalTests}`);
logger.info(` Pass rate: ${passRate}%`);
logger.info(` Areas nudged: ${this.nudgedAreas.size}/${this.IMPROVEMENT_AREAS.length}`);
logger.info(` Health: ${JSON.stringify(this.healthMetrics, null, 2)}`);
}
// Public method to get current status
getStatus() {
return {
isRunning: this.isRunning,
health: this.healthMetrics,
recentTests: this.testResults.slice(-20),
nudgedAreas: Array.from(this.nudgedAreas),
nextNudgeIn: this.nudgeInterval ? '~30 minutes' : 'stopped',
};
}
}
// Singleton instance
export const hansPedderAgent = new HansPedderAgentController();
|