/**
 * AgentMemory - Persistent per-agent-type memory storage.
 *
 * Stores key-value memories scoped by agent type and scope level.
 * Memories persist on the virtual filesystem.
 */
export class AgentMemory {
    memories = new Map();
    maxEntries;
    constructor(options) {
        this.maxEntries = options?.maxEntries ?? 10000;
    }
    entryKey(agentType, scope, key) {
        return `${scope}:${agentType}:${key}`;
    }
    write(agentType, scope, key, value) {
        const entryId = this.entryKey(agentType, scope, key);
        const existing = this.memories.get(entryId);
        const now = Date.now();
        const entry = {
            key,
            value,
            scope,
            agentType,
            createdAt: existing?.createdAt ?? now,
            updatedAt: now,
        };
        // Evict oldest entries if at capacity (skip if this is an update)
        if (!existing && this.memories.size >= this.maxEntries) {
            const oldest = this.memories.keys().next().value;
            if (oldest !== undefined)
                this.memories.delete(oldest);
        }
        this.memories.set(entryId, entry);
        return entry;
    }
    read(agentType, scope, key) {
        return this.memories.get(this.entryKey(agentType, scope, key));
    }
    list(agentType, scope) {
        const entries = [];
        for (const entry of this.memories.values()) {
            if (entry.agentType !== agentType)
                continue;
            if (scope && entry.scope !== scope)
                continue;
            entries.push(entry);
        }
        return entries;
    }
    delete(agentType, scope, key) {
        return this.memories.delete(this.entryKey(agentType, scope, key));
    }
    listAllAgentTypes() {
        const types = new Set();
        for (const entry of this.memories.values()) {
            types.add(entry.agentType);
        }
        return Array.from(types);
    }
    toJSON() {
        return Array.from(this.memories.values());
    }
    loadFromJSON(entries) {
        this.memories.clear();
        for (const entry of entries) {
            const entryId = this.entryKey(entry.agentType, entry.scope, entry.key);
            this.memories.set(entryId, entry);
        }
    }
}
