chahuadev
Update README
857cdcf
/**
* executor.js - Execution Strategy Manager (Level 5)
* สำหรับ Chahuadev Framework
*
* ใช้: system-detector.js (Level 4), validation_gateway.js (Level 4)
* จัดการ: Strategy selection, execution flow, error handling
*/
const SystemDetector = require('./system-detector');
const ErrorHandler = require('./error-handler');
const ContextManager = require('./context-manager');
class Executor {
constructor() {
this.systemDetector = new SystemDetector();
this.errorHandler = new ErrorHandler();
this.contextManager = new ContextManager();
this.executionHistory = [];
this.maxHistorySize = 100;
console.log(' Executor initialized - ready for strategy execution');
}
/**
* Main execution method
*/
async execute(request) {
const executionId = this.generateExecutionId();
const startTime = Date.now();
try {
console.log(` Starting execution [${executionId}]`);
// Phase 1: Use request as-is (validation done by ValidationGateway)
const validationResult = {
success: true,
sessionId: 'exec_' + Date.now(),
userId: request.userId || 'system',
permissions: request.permissions || 'admin',
level: 'admin'
};
// Phase 2: Context Preparation
const executionContext = this.prepareExecutionContext(request, executionId, validationResult);
// Phase 3: System Detection
const detectionResult = await this.systemDetector.detect(
executionContext.projectPath,
executionContext
);
// Phase 4: Strategy Execution
const executionResult = await this.executeWithStrategy(
detectionResult.strategy,
executionContext
);
// Phase 5: Result Processing
const finalResult = this.processExecutionResult(
executionResult,
detectionResult,
executionContext,
startTime
);
this.recordExecution(finalResult);
console.log(` Execution completed [${executionId}] in ${finalResult.totalDuration}ms`);
return finalResult;
} catch (error) {
console.log(` Execution failed [${executionId}]: ${error.message}`);
const errorResult = this.handleExecutionError(error, request, executionId, startTime);
this.recordExecution(errorResult);
return errorResult;
}
}
/**
* เตรียม execution context
*/
prepareExecutionContext(request, executionId, validationResult) {
// จัดการ command และ args
let fullCommand;
if (request.args && Array.isArray(request.args) && request.args.length > 0) {
// ถ้ามี args แยกมา ให้รวมกับ command
fullCommand = `${request.command} ${request.args.join(' ')}`;
} else {
// ถ้าไม่มี args ใช้ command ตรงๆ
fullCommand = request.command;
}
const context = this.contextManager.createContext({
executionId: executionId,
command: fullCommand,
originalCommand: request.command, // เก็บ command เดิมไว้
args: request.args || [], // เก็บ args แยกไว้
projectPath: request.projectPath || process.cwd(),
options: request.options || {},
sessionId: validationResult.sessionId,
userId: validationResult.userId,
permissions: validationResult.permissions,
timestamp: Date.now(),
platform: process.platform,
nodeVersion: process.version,
isSecure: validationResult.success,
validationLevel: validationResult.level
});
console.log(` Execution context prepared: ${context.executionId}`);
return context;
}
/**
* รัน command ด้วย strategy
*/
async executeWithStrategy(strategy, executionContext) {
console.log(` Executing with strategy: ${strategy.name}`);
const strategyStatus = await strategy.getStatus();
if (strategyStatus.status !== 'READY') {
throw new Error(`Strategy not ready: ${strategy.name}`);
}
const result = await strategy.execute(executionContext);
console.log(` Strategy execution completed: ${strategy.name}`);
return result;
}
/**
* ประมวลผลผลลัพธ์
*/
processExecutionResult(executionResult, detectionResult, executionContext, startTime) {
return {
success: executionResult.success,
executionId: executionContext.executionId,
command: executionContext.command,
projectPath: executionContext.projectPath,
strategy: detectionResult.type,
confidence: detectionResult.confidence,
output: executionResult.output,
exitCode: executionResult.exitCode,
error: executionResult.error,
totalDuration: Date.now() - startTime,
strategyDuration: executionResult.duration,
sessionId: executionContext.sessionId,
userId: executionContext.userId,
timestamp: startTime,
platform: executionContext.platform
};
}
/**
* จัดการ error
*/
handleExecutionError(error, request, executionId, startTime) {
this.errorHandler.logError('EXECUTION_FAILED', error, {
executionId: executionId,
request: request
});
return {
success: false,
executionId: executionId,
error: error.message,
command: request.command,
projectPath: request.projectPath,
totalDuration: Date.now() - startTime,
timestamp: startTime,
errorType: error.constructor.name
};
}
/**
* บันทึก execution history
*/
recordExecution(result) {
this.executionHistory.unshift(result);
if (this.executionHistory.length > this.maxHistorySize) {
this.executionHistory = this.executionHistory.slice(0, this.maxHistorySize);
}
console.log(` Execution recorded: ${result.executionId}`);
}
/**
* รัน command แบบง่าย
*/
async run(command, projectPath = process.cwd(), options = {}) {
return this.execute({
command: command,
projectPath: projectPath,
options: options
});
}
/**
* รายงานสถานะ
*/
async getStatus() {
const systemStatus = await this.systemDetector.getStatus();
return {
executor: 'ExecutionManager',
status: 'READY',
components: {
systemDetector: systemStatus
},
executionHistory: {
total: this.executionHistory.length,
successful: this.executionHistory.filter(r => r.success).length,
failed: this.executionHistory.filter(r => !r.success).length
},
timestamp: Date.now()
};
}
/**
* สร้าง execution ID
*/
generateExecutionId() {
return `exec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
}
/**
* ดู execution history
*/
getHistory(limit = 10) {
return this.executionHistory.slice(0, limit);
}
/**
* ล้าง history
*/
clearHistory() {
this.executionHistory = [];
console.log(' Execution history cleared');
}
}
module.exports = Executor;