// PRE-INITIALIZATION SCRIPT
// Runs BEFORE any agent system starts
// Organizes directories, validates structure, sets up logging
import { promises as fs } from 'fs';
import path from 'path';
export class SystemPreInitializer {
constructor() {
this.rootPath = 'C:/';
this.mcpPath = 'C:/MCP';
this.qanapConfigPath = 'C:/MCP/qnap-config.json';
// Define the standard directory structure
this.directoryStructure = {
'C:/MCP': {
purpose: 'Main MCP Server and Agent Hub',
subdirs: [
'src/agents/core', // Core reusable agents
'src/agents/specialized', // Specialized agents
'src/tools', // Tools and integrations
'src/integrations', // External service integrations
'logs/agent-actions', // Agent action logs
'logs/system', // System logs
'logs/rollback', // Rollback points
'backups/daily', // Daily backups
'backups/manual', // Manual backups
'inventory', // Agent/tool inventory
'workflows' // Workflow definitions
]
},
'C:/AI Projects': {
purpose: 'AI Project Workspace',
subdirs: [
'agents',
'scripts',
'workflows',
'prompts',
'config',
'data',
'docs'
]
},
'C:/AgentSystem': {
purpose: 'Agent System Runtime',
subdirs: [
'assets',
'database',
'logs',
'templates',
'workflows'
]
},
'C:/tools': {
purpose: 'Utility Tools and Scripts',
subdirs: [
'n8n-workflows',
'scripts',
'config'
]
}
};
this.initLog = [];
}
// MAIN INITIALIZATION METHOD
async initialize() {
console.log('🚀 SYSTEM PRE-INITIALIZATION STARTING...\n');
try {
// Step 1: Validate and create directory structure
await this.validateDirectoryStructure();
// Step 2: Initialize logging system
await this.initializeLoggingSystem();
// Step 3: Check QNAP/NAS connection
await this.validateQNAPConnection();
// Step 4: Create inventory directory
await this.setupInventorySystem();
// Step 5: Save initialization log
await this.saveInitLog();
console.log('\n✅ SYSTEM PRE-INITIALIZATION COMPLETE!');
console.log('🎯 System is ready for agent operations.\n');
return {
success: true,
timestamp: new Date().toISOString(),
log: this.initLog
};
} catch (error) {
console.error('\n❌ PRE-INITIALIZATION FAILED:', error);
await this.saveInitLog();
throw error;
}
}
// Validate and create directory structure
async validateDirectoryStructure() {
console.log('📁 Validating directory structure...\n');
for (const [basePath, config] of Object.entries(this.directoryStructure)) {
this.log(`Checking: ${basePath} - ${config.purpose}`);
// Ensure base directory exists
await this.ensureDirectory(basePath);
// Create subdirectories
for (const subdir of config.subdirs) {
const fullPath = path.join(basePath, subdir);
await this.ensureDirectory(fullPath);
}
}
console.log('✅ Directory structure validated\n');
}
// Initialize logging system
async initializeLoggingSystem() {
console.log('📝 Initializing logging system...\n');
const logConfig = {
version: '1.0.0',
initialized: new Date().toISOString(),
logging: {
agentActions: 'C:/MCP/logs/agent-actions',
systemLogs: 'C:/MCP/logs/system',
rollbackPoints: 'C:/MCP/logs/rollback'
},
retention: {
agentActions: '30 days',
systemLogs: '90 days',
rollbackPoints: '7 days'
},
rollback: {
enabled: true,
maxRollbackPoints: 100,
autoSnapshot: true
}
};
// Save logging config
const configPath = path.join(this.mcpPath, 'logging-config.json');
await fs.writeFile(configPath, JSON.stringify(logConfig, null, 2));
this.log('Logging system configured');
console.log('✅ Logging system initialized\n');
}
// Validate QNAP/NAS connection
async validateQNAPConnection() {
console.log('🖥️ Validating QNAP/NAS connection...\n');
try {
// Check if QNAP config exists
const configExists = await this.fileExists(this.qanapConfigPath);
if (!configExists) {
// Create default QNAP config
const defaultConfig = {
enabled: false,
host: 'YOUR_QNAP_IP',
containerName: 'n8n',
paths: {
n8nData: '/share/Container/n8n',
workflows: '/share/Container/n8n/workflows',
credentials: '/share/Container/n8n/credentials'
},
connection: {
type: 'ssh',
port: 22,
username: 'admin'
},
notes: 'Configure this file with your QNAP details to enable N8N integration'
};
await fs.writeFile(
this.qanapConfigPath,
JSON.stringify(defaultConfig, null, 2)
);
console.log('⚠️ QNAP config created - needs manual configuration');
console.log(` Edit: ${this.qanapConfigPath}\n`);
this.log('QNAP config template created - awaiting manual setup');
} else {
const config = JSON.parse(await fs.readFile(this.qanapConfigPath, 'utf-8'));
if (config.enabled) {
console.log(`✅ QNAP configured: ${config.host}`);
console.log(` N8N Container: ${config.containerName}\n`);
this.log(`QNAP connected: ${config.host}`);
} else {
console.log('⚠️ QNAP config exists but is disabled\n');
this.log('QNAP config disabled');
}
}
} catch (error) {
console.log('⚠️ QNAP validation skipped:', error.message, '\n');
this.log(`QNAP validation error: ${error.message}`);
}
}
// Setup inventory system
async setupInventorySystem() {
console.log('📦 Setting up inventory system...\n');
const inventoryPath = path.join(this.mcpPath, 'inventory');
await this.ensureDirectory(inventoryPath);
// Create inventory index file
const inventoryIndex = {
version: '1.0.0',
created: new Date().toISOString(),
inventoryFiles: {
agents: 'agent-inventory.json',
tools: 'tool-inventory.json',
workflows: 'workflow-inventory.json',
combined: 'master-inventory.json'
},
scanPaths: [
'C:/MCP/src/agents',
'C:/AI Projects/agents',
'C:/AI Projects/scripts',
'C:/tools',
'C:/AgentSystem'
]
};
const indexPath = path.join(inventoryPath, 'inventory-index.json');
await fs.writeFile(indexPath, JSON.stringify(inventoryIndex, null, 2));
this.log('Inventory system configured');
console.log('✅ Inventory system ready\n');
}
// Save initialization log
async saveInitLog() {
const logPath = path.join(this.mcpPath, 'logs/system', 'pre-init.log');
const logContent = {
timestamp: new Date().toISOString(),
status: 'completed',
steps: this.initLog
};
await fs.writeFile(logPath, JSON.stringify(logContent, null, 2));
console.log(`📄 Initialization log saved: ${logPath}`);
}
// Helper: Ensure directory exists
async ensureDirectory(dirPath) {
try {
await fs.mkdir(dirPath, { recursive: true });
this.log(`Created/Verified: ${dirPath}`);
return true;
} catch (error) {
if (error.code !== 'EEXIST') {
this.log(`Failed to create: ${dirPath} - ${error.message}`);
throw error;
}
return false;
}
}
// Helper: Check if file exists
async fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
// Helper: Log message
log(message) {
const timestamp = new Date().toISOString();
this.initLog.push({ timestamp, message });
console.log(` ✓ ${message}`);
}
}
// Export singleton
export const preInitializer = new SystemPreInitializer();