import { nexusEventBus } from './event-bus.js';
export class CompactionSentinel {
    budgetTokens;
    checkIntervalMs;
    timer;
    currentTokens = 0;
    storeRate = 0;
    startTime;
    lastStoreCount = 0;
    currentStoreCount = 0;
    unsubscribeStore;
    constructor(options = {}) {
        this.budgetTokens = options.budgetTokens ?? 100000;
        this.checkIntervalMs = options.checkIntervalMs ?? 30_000;
        this.startTime = Date.now();
    }
    start() {
        if (this.timer)
            return;
        this.startTime = Date.now();
        this.unsubscribeStore = nexusEventBus.on('memory.store', () => {
            this.currentStoreCount++;
        });
        this.timer = setInterval(() => {
            this.checkTriggers();
        }, this.checkIntervalMs);
        this.timer.unref();
    }
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = undefined;
        }
        this.unsubscribeStore?.();
        this.unsubscribeStore = undefined;
        this.currentStoreCount = 0;
        this.lastStoreCount = 0;
    }
    updateTokens(tokens) {
        this.currentTokens = tokens;
    }
    checkTriggers() {
        const sessionAgeMinutes = (Date.now() - this.startTime) / 60000;
        this.storeRate = this.currentStoreCount - this.lastStoreCount;
        this.lastStoreCount = this.currentStoreCount;
        const isNearBudget = this.currentTokens > this.budgetTokens * 0.9;
        const isRapidStoring = this.storeRate > 10;
        let reason = '';
        if (isNearBudget) {
            reason = 'Token count nearing context budget';
        }
        else if (isRapidStoring) {
            reason = 'Rapid memory burst detected';
        }
        if (reason) {
            nexusEventBus.emit('memory.pre-compaction', {
                tokensRemaining: this.budgetTokens - this.currentTokens,
                reason,
                sessionAgeMinutes,
            });
        }
    }
}
