Configuration Runtime Issues.md - johnpeterman72/CursorRIPER.sigma GitHub Wiki
Configuration and Runtime Issues
Framework Configuration Problems
Configuration File Validation Errors
Problem: Framework fails to start due to invalid configuration
Symptoms:
Error: Invalid configuration schema
Configuration validation failed at path: database.type
Missing required configuration: server.port
Solutions:
Validate configuration structure
// Use framework's built-in validator
const { validateConfig } = require('@cursoriper/core');
try {
const config = require('./framework.config.js');
const validation = validateConfig(config);
if (!validation.valid) {
console.log('Configuration errors:');
validation.errors.forEach(error => {
console.log(`- ${error.path}: ${error.message}`);
});
}
} catch (error) {
console.log('Configuration file syntax error:', error.message);
}
Fix common configuration errors
// framework.config.js - Correct structure
module.exports = {
// Required: Server configuration
server: {
port: process.env.PORT || 3000,
host: process.env.HOST || 'localhost',
cors: {
enabled: true,
origins: ['http://localhost:3000']
}
},
// Required: Database configuration
database: {
type: 'sqlite', // sqlite, postgresql, mysql
database: './data/framework.sqlite',
synchronize: process.env.NODE_ENV === 'development',
logging: process.env.NODE_ENV === 'development'
},
// Optional: Authentication
auth: {
jwt: {
secret: process.env.JWT_SECRET || 'your-secret-key',
expiresIn: '24h'
},
session: {
secret: process.env.SESSION_SECRET || 'your-session-secret',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
},
// Optional: Modules
modules: {
bmad: {
enabled: true,
config: {
// BMAD-specific configuration
}
}
}
};
Environment-Specific Configuration
Problem: Different behavior between development and production
Symptoms:
Works in development but fails in production
Environment variables not being read correctly
Database connection fails in production
Solutions:
Create environment-specific configs
// config/development.js
module.exports = {
database: {
type: 'sqlite',
database: './data/dev.sqlite',
synchronize: true,
logging: true
},
server: {
port: 3000,
debug: true
}
};
// config/production.js
module.exports = {
database: {
type: 'postgresql',
url: process.env.DATABASE_URL,
synchronize: false,
logging: false,
ssl: { rejectUnauthorized: false }
},
server: {
port: process.env.PORT || 8080,
debug: false
}
};
// framework.config.js
const env = process.env.NODE_ENV || 'development';
const baseConfig = require('./config/base');
const envConfig = require(`./config/${env}`);
module.exports = {
...baseConfig,
...envConfig
};
Environment variable validation
// config/env-validator.js
const requiredEnvVars = {
development: ['JWT_SECRET'],
production: ['JWT_SECRET', 'DATABASE_URL', 'SESSION_SECRET']
};
function validateEnvironment() {
const env = process.env.NODE_ENV || 'development';
const required = requiredEnvVars[env] || [];
const missing = required.filter(varName => !process.env[varName]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
module.exports = { validateEnvironment };
Runtime Performance Issues
Memory Leaks and High Memory Usage
Problem: Framework consuming excessive memory over time
Symptoms:
Memory usage steadily increasing
Application becomes sluggish over time
"Out of memory" errors
Process killed by system
Diagnosis:
// Add memory monitoring
const { performance, PerformanceObserver } = require('perf_hooks');
// Monitor memory usage
setInterval(() => {
const usage = process.memoryUsage();
console.log('Memory Usage:', {
rss: `${Math.round(usage.rss / 1024 / 1024)} MB`,
heapTotal: `${Math.round(usage.heapTotal / 1024 / 1024)} MB`,
heapUsed: `${Math.round(usage.heapUsed / 1024 / 1024)} MB`,
external: `${Math.round(usage.external / 1024 / 1024)} MB`
});
}, 10000); // Every 10 seconds
// Monitor garbage collection
const obs = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
if (entry.entryType === 'gc') {
console.log(`GC: ${entry.kind} - Duration: ${entry.duration}ms`);
}
});
});
obs.observe({ entryTypes: ['gc'] });
Solutions:
Check for event listener leaks
// Monitor event listeners
process.on('warning', (warning) => {
if (warning.name === 'MaxListenersExceededWarning') {
console.warn('Possible EventEmitter memory leak detected:', warning);
console.warn('Stack trace:', warning.stack);
}
});
// Properly remove event listeners
class ComponentManager {
constructor() {
this.listeners = new Map();
}
addListener(emitter, event, handler) {
emitter.on(event, handler);
// Track for cleanup
if (!this.listeners.has(emitter)) {
this.listeners.set(emitter, []);
}
this.listeners.get(emitter).push({ event, handler });
}
cleanup() {
// Remove all tracked listeners
for (const [emitter, listeners] of this.listeners) {
listeners.forEach(({ event, handler }) => {
emitter.removeListener(event, handler);
});
}
this.listeners.clear();
}
}
Database connection pooling
// Configure connection pooling properly
module.exports = {
database: {
type: 'postgresql',
url: process.env.DATABASE_URL,
poolSize: 10,
extra: {
connectionLimit: 10,
acquireTimeout: 60000,
timeout: 60000,
reconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
}
}
};
High CPU Usage
Problem: Framework consuming excessive CPU resources
Symptoms:
CPU usage consistently high (>80%)
Application response times slow
System becomes unresponsive
Diagnosis:
// CPU profiling
const v8Profiler = require('v8-profiler-next');
// Start CPU profiling
function startProfiling(duration = 30000) {
console.log('Starting CPU profiling...');
v8Profiler.startProfiling('cpu-profile');
setTimeout(() => {
const profile = v8Profiler.stopProfiling('cpu-profile');
profile.export((error, result) => {
if (error) {
console.error('Profiling error:', error);
return;
}
// Save profile
require('fs').writeFileSync('./cpu-profile.cpuprofile', result);
console.log('CPU profile saved to cpu-profile.cpuprofile');
// Clean up
profile.delete();
});
}, duration);
}
// Monitor event loop lag
const { monitorEventLoopDelay } = require('perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
setInterval(() => {
console.log('Event Loop Delay:', {
min: histogram.min,
max: histogram.max,
mean: histogram.mean,
stddev: histogram.stddev
});
histogram.reset();
}, 5000);
Solutions:
Optimize async operations
// Avoid blocking operations
const { Worker, isMainThread, parentPort } = require('worker_threads');
// Use worker threads for CPU-intensive tasks
async function processDataInWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(`
const { parentPort } = require('worker_threads');
// CPU-intensive processing
function processData(data) {
// Your heavy computation here
return processedData;
}
parentPort.on('message', (data) => {
try {
const result = processData(data);
parentPort.postMessage({ success: true, result });
} catch (error) {
parentPort.postMessage({ success: false, error: error.message });
}
});
`, { eval: true });
worker.postMessage(data);
worker.on('message', ({ success, result, error }) => {
worker.terminate();
if (success) {
resolve(result);
} else {
reject(new Error(error));
}
});
});
}
Implement rate limiting
// Add rate limiting to prevent resource exhaustion
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
standardHeaders: true,
legacyHeaders: false
});
// Apply to all requests
app.use(limiter);
// Stricter limits for specific endpoints
const strictLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5
});
app.use('/api/heavy-operation', strictLimiter);
Module Loading and Plugin Issues
Plugin Loading Failures
Problem: Custom plugins or modules fail to load
Symptoms:
Error: Plugin 'my-plugin' not found
Module loading failed for bmad
Plugin initialization error
Solutions:
Check plugin structure
// plugins/my-plugin/index.js - Correct structure
module.exports = {
name: 'my-plugin',
version: '1.0.0',
// Required: Plugin initialization
async initialize(framework) {
console.log('Initializing my-plugin...');
// Register services
framework.services.register('my-service', new MyService());
// Register routes
framework.router.use('/api/my-plugin', require('./routes'));
// Subscribe to events
framework.events.on('app.ready', this.onAppReady.bind(this));
},
// Optional: Plugin cleanup
async destroy(framework) {
console.log('Destroying my-plugin...');
// Cleanup resources
},
// Required: Plugin metadata
dependencies: ['@cursoriper/core'],
framework_version: '^1.0.0'
};
Validate plugin installation
# Check plugin directory structure
ls -la plugins/my-plugin/
# Should contain: index.js, package.json
# Verify plugin package.json
cat plugins/my-plugin/package.json
# Test plugin loading
node -e "
const plugin = require('./plugins/my-plugin');
console.log('Plugin loaded:', plugin.name, plugin.version);
"
Module Dependency Conflicts
Problem: Version conflicts between framework modules
Symptoms:
Dependency version mismatch
Module resolution conflicts
TypeError: Cannot read property of undefined
Solutions:
Check dependency tree
# Analyze dependency conflicts
npm ls --depth=2
npm audit
# Check for duplicate dependencies
npm ls --duplicated
# Resolution with npm
npm install --legacy-peer-deps
# Or use yarn for better resolution
yarn install --ignore-engines
Use peer dependency resolution
// package.json - Force specific versions
{
"overrides": {
"@cursoriper/bmad": {
"@cursoriper/core": "^1.0.0"
}
},
"resolutions": {
"@cursoriper/core": "^1.0.0"
}
}
Database and Storage Issues
Database Connection Pool Exhaustion
Problem: Database connections not being released properly
Symptoms:
Error: Connection pool exhausted
Too many database connections
Database timeout errors
Solutions:
Proper connection management
// Use framework's database service
class DatabaseService {
constructor(framework) {
this.db = framework.getDatabase();
}
async executeQuery(query, params) {
let connection;
try {
connection = await this.db.getConnection();
const result = await connection.query(query, params);
return result;
} catch (error) {
console.error('Database query error:', error);
throw error;
} finally {
// Always release connection
if (connection) {
await connection.release();
}
}
}
// Use transactions properly
async executeTransaction(operations) {
const transaction = await this.db.transaction();
try {
for (const operation of operations) {
await operation(transaction);
}
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
Configure connection pooling
// framework.config.js
module.exports = {
database: {
type: 'postgresql',
url: process.env.DATABASE_URL,
pool: {
min: 2,
max: 10,
acquireTimeoutMillis: 30000,
createTimeoutMillis: 30000,
destroyTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 200
}
}
};
File System Permission Issues
Problem: Framework cannot read/write files
Symptoms:
EACCES: permission denied
ENOENT: no such file or directory
Cannot create directory
Solutions:
Fix permissions
# Check current permissions
ls -la data/
ls -la logs/
# Fix directory permissions
chmod 755 data/ logs/
chmod 644 data/*.sqlite
# Change ownership (if needed)
chown -R $USER:$USER data/ logs/
# Create missing directories
mkdir -p data logs temp
Implement proper file handling
const fs = require('fs').promises;
const path = require('path');
class FileManager {
constructor(basePath) {
this.basePath = basePath;
}
async ensureDirectory(dirPath) {
const fullPath = path.join(this.basePath, dirPath);
try {
await fs.access(fullPath);
} catch (error) {
if (error.code === 'ENOENT') {
await fs.mkdir(fullPath, { recursive: true });
} else {
throw error;
}
}
}
async writeFile(filePath, data) {
const fullPath = path.join(this.basePath, filePath);
const dirPath = path.dirname(fullPath);
// Ensure directory exists
await this.ensureDirectory(dirPath);
// Write file
await fs.writeFile(fullPath, data, 'utf8');
}
async readFile(filePath) {
const fullPath = path.join(this.basePath, filePath);
try {
return await fs.readFile(fullPath, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`File not found: ${filePath}`);
}
throw error;
}
}
}
Quick Fixes and Workarounds
Restart Services Safely
#!/bin/bash
# Safe framework restart script
echo "Starting safe framework restart..."
# Graceful shutdown
echo "Sending SIGTERM to framework processes..."
pkill -TERM -f "node.*framework"
# Wait for graceful shutdown
sleep 5
# Force kill if still running
echo "Checking for remaining processes..."
if pgrep -f "node.*framework" > /dev/null; then
echo "Force killing remaining processes..."
pkill -KILL -f "node.*framework"
fi
# Clear temporary files
echo "Cleaning temporary files..."
rm -rf temp/* cache/*
# Restart framework
echo "Starting framework..."
npm start
echo "Framework restart complete"
Clear All Caches
#!/bin/bash
# Clear all framework caches
echo "Clearing framework caches..."
# Application cache
rm -rf cache/* temp/*
# Node.js cache
npm cache clean --force
# Framework-specific cache
rm -rf .framework-cache/
# Database query cache (if using Redis)
if command -v redis-cli &> /dev/null; then
redis-cli FLUSHDB
fi
echo "All caches cleared"
Emergency Mode
// config/emergency.js - Minimal configuration for emergency startup
module.exports = {
server: {
port: process.env.PORT || 3000,
debug: true
},
database: {
type: 'sqlite',
database: ':memory:', // In-memory database
synchronize: true
},
modules: {
// Disable all non-essential modules
},
logging: {
level: 'debug',
console: true
}
};
// Start in emergency mode
// NODE_ENV=emergency npm start
Last Updated: June 28, 2025
Framework Version: CursorRIPER.sigma v1.0+