All files system.adaptive.js

60.9% Statements 81/133
59.7% Branches 40/67
90% Functions 9/10
61.83% Lines 81/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        6x                       6x                                                                               6x                   16x 10x                                   5x     5x 1x     4x   4x 4x 4x 4x   4x 4x 4x   4x     4x 1x     3x       3x         3x       4x 4x             4x                         4x       4x       4x 4x 4x       4x             5x 2x 2x           3x                     3x     3x             21x   3x   1x   7x   9x   1x               4x 4x   4x 4x 4x 4x 4x                   19x 19x               2x     2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x             2x 2x       2x 2x   2x                                                                                                                                                                                                             2x   2x 1x 1x     1x 1x             1x 1x       6x  
/**
 * Adaptive System - CPU/メモリ使用率に応じた機能制御
 * 負荷が高い時は自動的に機能を制限し、余裕がある時は全機能を有効化
 */
 
/**
 * System modes:
 * 0: EMERGENCY - Minimal functionality to survive.
 * 1: MINIMAL - Basic features only.
 * 2: NORMAL - Standard operations.
 * 3: FULL - All features enabled.
 */
const MODES = {
    EMERGENCY: 0,
    MINIMAL: 1,
    NORMAL: 2,
    FULL: 3,
};
 
/**
 * ⚡ PERFORMANCE OPTIMIZATION: Hoisted feature configuration.
 * Moving this object literal outside of the `isEnabled` function prevents
 * redundant object allocation on every call (called many times per tick).
 */
const FEATURE_CONFIG = {
    [MODES.EMERGENCY]: {
        basicRoles: true,
        spawn: true,
        memoryCleanup: true,
    },
    [MODES.MINIMAL]: {
        basicRoles: true,
        spawn: true,
        memoryCleanup: true,
        defense: true,
        logging: true,
    },
    [MODES.NORMAL]: {
        basicRoles: true,
        spawn: true,
        memoryCleanup: true,
        defense: true,
        logging: true,
        gamification: true,
        emotions: true,
        memoryVisualizer: true,
    },
    [MODES.FULL]: {
        basicRoles: true,
        spawn: true,
        memoryCleanup: true,
        defense: true,
        logging: true,
        gamification: true,
        emotions: true,
        memoryVisualizer: true,
        visualEffects: true,
        autoEvolution: true,
        tutorial: true,
        socialInteractions: true,
        advancedRoles: true,
    },
};
 
const adaptiveSystem = {
    /**
     * システムモード
     */
    MODE: MODES,
 
    /**
     * 初期化
     */
    init: function () {
        if (!Memory.adaptive) {
            Memory.adaptive = {
                currentMode: this.MODE.NORMAL,
                lastCheck: 0,
                modeHistory: [],
                stats: {
                    emergencyCount: 0,
                    minimalCount: 0,
                    normalCount: 0,
                    fullCount: 0,
                },
            };
        }
    },
 
    /**
     * 現在のシステム状態を評価
     */
    evaluate: function () {
        this.init();
 
        // 10ティックごとにチェック
        if (Game.time - Memory.adaptive.lastCheck < 10) {
            return Memory.adaptive.currentMode;
        }
 
        Memory.adaptive.lastCheck = Game.time;
 
        const cpuUsed = Game.cpu.getUsed();
        const cpuLimit = Game.cpu.limit;
        const cpuBucket = Game.cpu.bucket;
        const cpuUsagePercent = (cpuUsed / cpuLimit) * 100;
 
        const memorySize = RawMemory.get().length;
        const memoryLimit = 2048 * 1024; // 2MB in bytes
        const memoryUsagePercent = (memorySize / memoryLimit) * 100;
 
        let newMode = this.MODE.FULL;
 
        // EMERGENCY: CPU bucket < 1000 または メモリ > 95%
        if (cpuBucket < 1000 || memoryUsagePercent > 95) {
            newMode = this.MODE.EMERGENCY;
        }
        // MINIMAL: CPU bucket < 3000 または メモリ > 85% または CPU使用率 > 80%
        else Iif (cpuBucket < 3000 || memoryUsagePercent > 85 || cpuUsagePercent > 80) {
            newMode = this.MODE.MINIMAL;
        }
        // NORMAL: CPU bucket < 7000 または メモリ > 70% または CPU使用率 > 60%
        else Iif (cpuBucket < 7000 || memoryUsagePercent > 70 || cpuUsagePercent > 60) {
            newMode = this.MODE.NORMAL;
        }
        // FULL: 余裕あり
        else {
            newMode = this.MODE.FULL;
        }
 
        // モード変更時にログ出力
        Eif (newMode !== Memory.adaptive.currentMode) {
            this.logModeChange(Memory.adaptive.currentMode, newMode, {
                cpuUsagePercent: cpuUsagePercent,
                cpuBucket: cpuBucket,
                memoryUsagePercent: memoryUsagePercent,
            });
 
            // モード履歴に追加
            Memory.adaptive.modeHistory.push({
                time: Game.time,
                from: Memory.adaptive.currentMode,
                to: newMode,
                reason: this.getModeChangeReason(
                    newMode,
                    cpuUsagePercent,
                    cpuBucket,
                    memoryUsagePercent
                ),
            });
 
            // 履歴は最新20件まで
            Iif (Memory.adaptive.modeHistory.length > 20) {
                Memory.adaptive.modeHistory.shift();
            }
 
            Memory.adaptive.currentMode = newMode;
        }
 
        // 統計更新
        const modeName = this.getModeName(newMode);
        Eif (modeName) {
            Memory.adaptive.stats[modeName + 'Count'] =
                (Memory.adaptive.stats?.[modeName + 'Count'] ?? 0) + 1;
        }
 
        return newMode;
    },
 
    /**
     * モード変更理由を取得
     */
    getModeChangeReason: function (mode, cpuUsage, cpuBucket, memoryUsage) {
        if (mode === this.MODE.EMERGENCY) {
            Eif (cpuBucket < 1000) {
                return 'CPU bucket critical';
            }
            if (memoryUsage > 95) {
                return 'Memory critical';
            }
        }
        Iif (mode === this.MODE.MINIMAL) {
            if (cpuBucket < 3000) {
                return 'CPU bucket low';
            }
            if (memoryUsage > 85) {
                return 'Memory high';
            }
            if (cpuUsage > 80) {
                return 'CPU usage high';
            }
        }
        Iif (mode === this.MODE.NORMAL) {
            return 'Moderate load';
        }
        return 'System healthy';
    },
 
    /**
     * モード名取得
     */
    getModeName: function (mode) {
        switch (mode) {
            case this.MODE.EMERGENCY:
                return 'emergency';
            case this.MODE.MINIMAL:
                return 'minimal';
            case this.MODE.NORMAL:
                return 'normal';
            case this.MODE.FULL:
                return 'full';
            default:
                return null;
        }
    },
 
    /**
     * モード変更ログ
     */
    logModeChange: function (oldMode, newMode, stats) {
        const oldName = this.getModeName(oldMode);
        const newName = this.getModeName(newMode);
 
        console.log('\n🔄 === ADAPTIVE SYSTEM MODE CHANGE === 🔄');
        console.log('From: ' + oldName.toUpperCase() + ' → To: ' + newName.toUpperCase());
        console.log('CPU Usage: ' + stats.cpuUsagePercent.toFixed(1) + '%');
        console.log('CPU Bucket: ' + stats.cpuBucket + '/10000');
        console.log('Memory Usage: ' + stats.memoryUsagePercent.toFixed(1) + '%');
    },
 
    /**
     * 機能が有効かチェック
     * ⚡ PERFORMANCE OPTIMIZATION: Removed redundant `this.init()` call.
     * `init()` is already called at the start of the loop in `main.js` via `evaluate()`.
     * Estimated impact: Reduces CPU overhead in a high-frequency function.
     */
    isEnabled: function (feature) {
        const mode = Memory.adaptive.currentMode;
        return FEATURE_CONFIG?.[mode]?.[feature] === true;
    },
 
    /**
     * 緊急クリーンアップ実行
     * ⚡ SECURITY: Enhanced DoS mitigation by clearing more memory-intensive structures.
     */
    emergencyCleanup: function () {
        console.log('🚨 Emergency cleanup triggered!');
 
        // Delete heavy root structures
        delete Memory.evolution;
        delete Memory.backups;
        delete Memory.timeMachine;
        delete Memory.leaderboard;
        delete Memory.cache;
        delete Memory.memorySnapshots;
 
        // Clean up per-creep memory (non-essential features)
        Eif (Memory.creeps) {
            for (const name in Memory.creeps) {
                Eif (Object.prototype.hasOwnProperty.call(Memory.creeps, name)) {
                    const creepMemory = Memory.creeps[name];
                    Eif (creepMemory) {
                        delete creepMemory.diary;
                        delete creepMemory.emotions;
                        delete creepMemory.trailPositions;
                    }
                }
            }
        }
 
        // Truncate gamification achievements to save space
        Eif (Memory.gamification && Array.isArray(Memory.gamification.achievements)) {
            Memory.gamification.achievements = Memory.gamification.achievements.slice(-5);
        }
 
        // Delete any other suspected heavy structures
        delete Memory.emotions; // Root-level emotions (if any)
        delete Memory.diary; // Root-level diary
 
        console.log('✅ Emergency cleanup completed');
    },
 
    /**
     * ダッシュボード表示
     */
    showDashboard: function () {
        this.init();
        const mode = Memory.adaptive.currentMode;
        const modeName = this.getModeName(mode).toUpperCase();
 
        const cpuUsed = Game.cpu.getUsed();
        const cpuLimit = Game.cpu.limit;
        const cpuBucket = Game.cpu.bucket;
        const memorySize = RawMemory.get().length;
        const memoryLimit = 2048 * 1024;
 
        console.log('\n⚡ === ADAPTIVE SYSTEM DASHBOARD === ⚡');
        console.log('Current Mode: ' + modeName);
        console.log('');
        console.log(
            'CPU Used: ' +
                cpuUsed.toFixed(2) +
                '/' +
                cpuLimit +
                ' (' +
                ((cpuUsed / cpuLimit) * 100).toFixed(1) +
                '%)'
        );
        console.log('CPU Bucket: ' + cpuBucket + '/10000 (' + (cpuBucket / 100).toFixed(1) + '%)');
        console.log(
            'Memory: ' +
                (memorySize / 1024).toFixed(1) +
                ' KB / 2048 KB (' +
                ((memorySize / memoryLimit) * 100).toFixed(1) +
                '%)'
        );
        console.log('');
 
        // 有効機能リスト
        console.log('Enabled Features:');
        const allFeatures = [
            'basicRoles',
            'spawn',
            'defense',
            'logging',
            'gamification',
            'emotions',
            'memoryVisualizer',
            'visualEffects',
            'autoEvolution',
            'tutorial',
            'socialInteractions',
            'advancedRoles',
        ];
 
        let enabledCount = 0;
        for (let i = 0; i < allFeatures.length; i++) {
            if (this.isEnabled(allFeatures[i])) {
                enabledCount++;
            }
        }
        console.log('  ' + enabledCount + '/' + allFeatures.length + ' features active');
 
        // 統計
        console.log('');
        console.log('Mode Statistics:');
        const stats = Memory.adaptive.stats;
        const total =
            stats.emergencyCount + stats.minimalCount + stats.normalCount + stats.fullCount;
        if (total > 0) {
            console.log('  Emergency: ' + ((stats.emergencyCount / total) * 100).toFixed(1) + '%');
            console.log('  Minimal: ' + ((stats.minimalCount / total) * 100).toFixed(1) + '%');
            console.log('  Normal: ' + ((stats.normalCount / total) * 100).toFixed(1) + '%');
            console.log('  Full: ' + ((stats.fullCount / total) * 100).toFixed(1) + '%');
        }
 
        // 最近のモード変更履歴
        if (Memory.adaptive.modeHistory.length > 0) {
            console.log('');
            console.log('Recent Mode Changes:');
            const recentHistory = Memory.adaptive.modeHistory.slice(-5);
            for (let i = 0; i < recentHistory.length; i++) {
                const h = recentHistory[i];
                console.log(
                    '  [' +
                        h.time +
                        '] ' +
                        this.getModeName(h.from) +
                        ' → ' +
                        this.getModeName(h.to) +
                        ' (' +
                        h.reason +
                        ')'
                );
            }
        }
    },
 
    /**
     * 強制モード変更
     */
    setMode: function (mode) {
        this.init();
 
        if (mode < this.MODE.EMERGENCY || mode > this.MODE.FULL) {
            console.log('❌ Invalid mode. Use 0-3.');
            return;
        }
 
        Memory.adaptive.currentMode = mode;
        console.log('✅ Mode set to: ' + this.getModeName(mode).toUpperCase());
    },
 
    /**
     * リセット
     */
    reset: function () {
        delete Memory.adaptive;
        console.log('🔄 Adaptive system reset!');
    },
};
 
module.exports = adaptiveSystem;