vineguard-core
v2.0.6
Published
Core orchestration engine for VineGuard
Downloads
16
Maintainers
Readme
VineGuard Core - Orchestration Engine 🍇
Core orchestration engine for VineGuard AI testing system
VineGuard Core v2.0.1 provides the foundational orchestration engine that powers both the VineGuard CLI and MCP server. It handles task coordination, file monitoring, queue management, and provides a unified interface for all VineGuard operations.
🎯 What is VineGuard Core?
VineGuard Core is the central orchestration engine that:
- ✅ Task Orchestration: Coordinates complex testing workflows across multiple tools
- ✅ File Monitoring: Watches project files for changes and triggers appropriate actions
- ✅ Queue Management: Handles concurrent operations with priority-based task queuing
- ✅ Event System: Provides event-driven architecture for loosely coupled components
- ✅ Configuration Management: Centralized configuration handling across all VineGuard packages
🚀 Installation
# Install as dependency
npm install vineguard-core
# Or install with other VineGuard packages
npm install vineguard # CLI package includes core
npm install vineguard-mcp # MCP package includes core📋 Core Features
Orchestration Engine
The core orchestration system manages complex testing workflows:
import { OrchestrationEngine } from 'vineguard-core';
const engine = new OrchestrationEngine({
projectRoot: process.cwd(),
concurrency: 4,
enableFileWatcher: true
});
// Start orchestration
await engine.initialize();
// Execute a workflow
const result = await engine.executeWorkflow('test-generation', {
target: './src/components',
framework: 'jest'
});File Monitoring
Automatic file watching and change detection:
import { FileWatcher } from 'vineguard-core';
const watcher = new FileWatcher({
paths: ['src/**/*.{js,ts,tsx}'],
ignore: ['node_modules', 'dist']
});
watcher.on('change', (file) => {
console.log(`File changed: ${file}`);
// Trigger test regeneration
});
watcher.on('add', (file) => {
console.log(`File added: ${file}`);
// Analyze new file
});Task Queue Management
Priority-based task queuing with concurrency control:
import { TaskQueue } from 'vineguard-core';
const queue = new TaskQueue({
concurrency: 3,
defaultPriority: 5
});
// Add high-priority task
await queue.add('security-scan', {
target: './src/auth'
}, { priority: 10 });
// Add normal task
await queue.add('test-generation', {
component: './src/Button.tsx'
});
// Process queue
await queue.start();Event System
Event-driven architecture for component communication:
import { EventBus } from 'vineguard-core';
const events = new EventBus();
// Subscribe to events
events.on('test:generated', (data) => {
console.log(`Tests generated for ${data.component}`);
});
events.on('scan:complete', (results) => {
console.log(`Scan found ${results.issues.length} issues`);
});
// Emit events
events.emit('test:requested', {
component: './src/Button.tsx',
framework: 'jest'
});Configuration Management
Centralized configuration with validation:
import { ConfigManager } from 'vineguard-core';
const config = new ConfigManager({
configFile: 'vineguard.config.js',
schema: {
frameworks: ['jest', 'playwright'],
analysis: {
depth: 'deep',
includeTests: true
}
}
});
// Get configuration
const testFrameworks = config.get('frameworks');
const analysisDepth = config.get('analysis.depth');
// Watch for configuration changes
config.on('change', (newConfig) => {
console.log('Configuration updated');
});🛠️ API Reference
OrchestrationEngine
Main orchestration class that coordinates all VineGuard operations.
class OrchestrationEngine {
constructor(options: OrchestrationOptions)
// Initialize the engine
async initialize(): Promise<void>
// Execute a workflow
async executeWorkflow(
workflowName: string,
params: any
): Promise<WorkflowResult>
// Register a new workflow
registerWorkflow(
name: string,
workflow: WorkflowDefinition
): void
// Get engine status
getStatus(): EngineStatus
// Shutdown the engine
async shutdown(): Promise<void>
}FileWatcher
File system monitoring with glob pattern support.
class FileWatcher extends EventEmitter {
constructor(options: WatcherOptions)
// Start watching
start(): void
// Stop watching
stop(): void
// Add watch patterns
addPaths(patterns: string[]): void
// Remove watch patterns
removePaths(patterns: string[]): void
}TaskQueue
Priority-based task queue with concurrency control.
class TaskQueue extends EventEmitter {
constructor(options: QueueOptions)
// Add task to queue
async add(
name: string,
data: any,
options?: TaskOptions
): Promise<string>
// Start processing queue
async start(): Promise<void>
// Pause queue processing
pause(): void
// Resume queue processing
resume(): void
// Get queue statistics
getStats(): QueueStats
}EventBus
Event system for component communication.
class EventBus extends EventEmitter {
// Emit event with data
emit(event: string, data?: any): boolean
// Subscribe to event
on(event: string, listener: Function): this
// Subscribe once to event
once(event: string, listener: Function): this
// Unsubscribe from event
off(event: string, listener: Function): this
// Get event listener count
listenerCount(event: string): number
}ConfigManager
Configuration management with validation and watching.
class ConfigManager extends EventEmitter {
constructor(options: ConfigOptions)
// Get configuration value
get(path: string): any
// Set configuration value
set(path: string, value: any): void
// Load configuration from file
async load(): Promise<void>
// Save configuration to file
async save(): Promise<void>
// Validate configuration
validate(): ValidationResult
}⚙️ Configuration
Engine Configuration
Configure the orchestration engine:
// vineguard.config.js
export default {
core: {
// Orchestration settings
orchestration: {
concurrency: 4,
defaultTimeout: 30000,
enableFileWatcher: true,
watchPatterns: ['src/**/*.{js,ts,tsx}']
},
// Queue settings
queue: {
maxConcurrency: 3,
defaultPriority: 5,
retryAttempts: 3
},
// File watcher settings
watcher: {
ignorePatterns: [
'node_modules/**',
'dist/**',
'*.log'
],
debounceMs: 100
},
// Event system settings
events: {
maxListeners: 20,
enableLogging: true
}
}
};Environment Variables
# Core settings
export VINEGUARD_CORE_CONCURRENCY="4"
export VINEGUARD_CORE_TIMEOUT="30000"
export VINEGUARD_ENABLE_FILE_WATCHER="true"
# Queue settings
export VINEGUARD_QUEUE_CONCURRENCY="3"
export VINEGUARD_QUEUE_RETRY_ATTEMPTS="3"
# Debug settings
export VINEGUARD_CORE_DEBUG="true"
export VINEGUARD_CORE_LOG_LEVEL="info"🔄 Workflow System
Built-in Workflows
VineGuard Core includes several built-in workflows:
project-analysis: Comprehensive project structure and dependency analysistest-generation: Intelligent test creation based on code analysissecurity-scan: Security vulnerability detection and reportingbug-detection: Code quality and potential bug identificationfix-generation: Automated fix suggestions with regression tests
🐘 PHP Framework Support
VineGuard Core includes comprehensive support for PHP frameworks (Laravel and Phalcon):
Supported Frameworks
Laravel (v8.x - v11.x)
- Eloquent models with relationships
- Route detection (web.php, api.php)
- Sanctum/Passport authentication
- Exception handlers
- Middleware detection
Phalcon (v4.x - v5.x)
- Phalcon ORM models
- Micro and MVC routing
- Security component detection
- Event-based error handling
PHP Framework Detection
import { PhpFrameworkDetector } from 'vineguard-core';
const detector = new PhpFrameworkDetector();
const info = await detector.detectFramework('./my-laravel-app');
console.log(info.framework); // 'laravel'
console.log(info.version); // '^10.0'
console.log(info.detectedBy); // ['composer.json', 'artisan file exists', ...]PHP Code Parsing
import {
parseLaravelRoutes,
extractEloquentModelProperties,
extractEloquentRelationships
} from 'vineguard-core';
// Parse Laravel routes
const routes = parseLaravelRoutes(routeFileContent);
console.log(routes);
// [{ method: 'GET', path: '/users', controller: 'UserController', action: 'index' }]
// Extract Eloquent model properties
const properties = extractEloquentModelProperties(modelContent);
console.log(properties.fillable); // ['name', 'email', 'password']
console.log(properties.casts); // { email_verified_at: 'datetime', is_active: 'boolean' }
// Extract relationships
const relationships = extractEloquentRelationships(modelContent);
console.log(relationships);
// [{ name: 'posts', type: 'hasMany', relatedModel: 'Post' }]PHP Detection in Project Scanner
VineGuard automatically detects PHP frameworks during project scanning:
import { ProjectScanner } from 'vineguard-core';
const scanner = new ProjectScanner();
const result = await scanner.scan('./my-php-project');
console.log(result.framework); // 'laravel'
console.log(result.phpRoutes); // Array of detected routes
console.log(result.authProviders); // ['sanctum']
console.log(result.dataModels); // Eloquent/Phalcon models
console.log(result.errorHandlers); // Exception handlersCustom Workflows
Create custom workflows:
import { OrchestrationEngine, WorkflowDefinition } from 'vineguard-core';
const customWorkflow: WorkflowDefinition = {
name: 'custom-analysis',
description: 'Custom code analysis workflow',
steps: [
{
name: 'scan-files',
tool: 'vineyard-scanner',
params: { depth: 'deep' }
},
{
name: 'analyze-patterns',
tool: 'vine-inspector',
params: { includeMetrics: true }
},
{
name: 'generate-report',
tool: 'harvest-planner',
params: { format: 'detailed' }
}
]
};
const engine = new OrchestrationEngine();
engine.registerWorkflow('custom-analysis', customWorkflow);🧪 Testing
Running Tests
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run in watch mode
npm run test:watch
# Run specific test file
npm test -- file-watcher.test.tsTesting Utilities
VineGuard Core provides testing utilities:
import { TestHelper } from 'vineguard-core/testing';
describe('Custom Workflow', () => {
let engine: OrchestrationEngine;
let helper: TestHelper;
beforeEach(async () => {
helper = new TestHelper();
engine = helper.createEngine({
projectRoot: helper.createTempProject()
});
});
it('should execute workflow', async () => {
const result = await engine.executeWorkflow('test-generation', {
target: './test-component.tsx'
});
expect(result.success).toBe(true);
expect(result.generatedTests).toBeDefined();
});
});🔍 Debugging
Debug Logging
Enable debug logging:
# Enable all core debug logs
DEBUG=vineguard:core:* npm test
# Enable specific component logs
DEBUG=vineguard:core:orchestration npm test
DEBUG=vineguard:core:queue npm test
DEBUG=vineguard:core:watcher npm testPerformance Monitoring
Monitor engine performance:
import { OrchestrationEngine } from 'vineguard-core';
const engine = new OrchestrationEngine({
enableMetrics: true
});
// Get performance metrics
const metrics = engine.getMetrics();
console.log(`Tasks processed: ${metrics.tasksProcessed}`);
console.log(`Average execution time: ${metrics.avgExecutionTime}ms`);
console.log(`Memory usage: ${metrics.memoryUsage}MB`);🔗 Integration Examples
CLI Integration
How VineGuard CLI uses the core:
import { OrchestrationEngine } from 'vineguard-core';
class VineGuardCLI {
private engine: OrchestrationEngine;
async initialize() {
this.engine = new OrchestrationEngine({
projectRoot: process.cwd(),
enableFileWatcher: false // CLI doesn't need file watching
});
await this.engine.initialize();
}
async analyze(path: string) {
return await this.engine.executeWorkflow('project-analysis', {
target: path
});
}
}MCP Integration
How VineGuard MCP uses the core:
import { OrchestrationEngine } from 'vineguard-core';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
class VineGuardMCP {
private engine: OrchestrationEngine;
private server: Server;
async initialize() {
this.engine = new OrchestrationEngine({
projectRoot: process.env.VINEGUARD_PROJECT_ROOT || '.',
enableFileWatcher: true // MCP benefits from file watching
});
await this.engine.initialize();
this.setupMCPTools();
}
private setupMCPTools() {
this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'scan_project',
description: 'Comprehensive project analysis',
inputSchema: { /* ... */ }
}
]
}));
}
}🤝 Contributing
We welcome contributions to VineGuard Core! Please see our Contributing Guide for details.
Development Setup
# Clone the repository
git clone https://github.com/idvd20/vineguard.git
cd vineguard/packages/core
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test📄 License
MIT License - see LICENSE file for details.
🔗 Related Packages
- VineGuard CLI: Command-line interface
- VineGuard MCP: IDE integration server
- VineGuard Utils: Shared utilities
- VineGuard Types: TypeScript definitions
🔗 Links
- Main Project: VineGuard Monorepo
- Core Package: vineguard-core
- Issues: Report Issues
- Documentation: Full Docs
