"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const MEMORY_DIR = path.join(os.homedir(), '.fivo', 'cell', 'memory');
describe('AIMemory', () => {
    let aim;
    beforeEach(async () => {
        aim = await Promise.resolve().then(() => __importStar(require('../../walls/03-knowledge/decisions/ai-memory')));
        aim.clearAllMemory();
    });
    test('initializeMemory creates memory directory', () => {
        aim.initializeMemory();
        expect(fs.existsSync(MEMORY_DIR)).toBe(true);
    });
    test('persistOutcome and queryOutcomes', () => {
        aim.persistOutcome({ patternId: 'p1', description: 'test', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: Date.now() });
        aim.persistOutcome({ patternId: 'p2', description: 'test2', action: 'reject', workflowSessionId: 's1', workflowSuccess: false, timestamp: Date.now() });
        const all = aim.queryOutcomes();
        expect(all.length).toBe(2);
        const filtered = aim.queryOutcomes(100, 'p1');
        expect(filtered.length).toBe(1);
        expect(filtered[0].action).toBe('accept');
    });
    test('getOutcomeCounts returns correct stats', () => {
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: 1 });
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: 2 });
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'reject', workflowSessionId: 's1', workflowSuccess: false, timestamp: 3 });
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'retry', workflowSessionId: 's1', workflowSuccess: false, timestamp: 4 });
        const counts = aim.getOutcomeCounts();
        expect(counts.total).toBe(4);
        expect(counts.accepts).toBe(2);
        expect(counts.rejects).toBe(1);
        expect(counts.retries).toBe(1);
    });
    test('persistFailure and getPersistedFailures', () => {
        aim.persistFailure({ patternId: 'p_bad', category: 'test', description: 'bad pattern', from: 'x', to: 'y', language: 'ts', acceptCount: 1, rejectCount: 9, totalSignals: 10, lastTimestamp: Date.now() });
        const failures = aim.getPersistedFailures();
        expect(failures.length).toBe(1);
        expect(failures[0].patternId).toBe('p_bad');
        expect(failures[0].rejectCount).toBe(9);
        const found = aim.getPersistedFailure('p_bad');
        expect(found).toBeDefined();
        expect(found.rejectCount).toBe(9);
    });
    test('persistWorkflowSession and getPersistedWorkflows', () => {
        aim.persistWorkflowSession({ sessionId: 's1', patternIds: ['p1', 'p2'], actions: ['edit_diff', 'accept'], startedAt: 100, completedAt: 200, success: true });
        const workflows = aim.getPersistedWorkflows();
        expect(workflows.length).toBe(1);
        expect(workflows[0].sessionId).toBe('s1');
        expect(workflows[0].success).toBe(true);
        const found = aim.getPersistedWorkflow('s1');
        expect(found).toBeDefined();
        expect(found.patternIds.length).toBe(2);
    });
    test('persistTimeSaved and getPersistedTimeSaved', () => {
        aim.persistTimeSaved({ patternId: 'p1', category: 'test', description: '', language: 'ts', estimatedSeconds: 45, timestamp: Date.now() });
        aim.persistTimeSaved({ patternId: 'p2', category: 'test', description: '', language: 'ts', estimatedSeconds: 120, timestamp: Date.now() });
        const records = aim.getPersistedTimeSaved();
        expect(records.length).toBe(2);
        expect(records.reduce((s, r) => s + r.estimatedSeconds, 0)).toBe(165);
    });
    test('getMemoryStats returns all counts', () => {
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: 1 });
        aim.persistFailure({ patternId: 'p_bad', category: 'test', description: '', from: 'x', to: 'y', language: 'ts', acceptCount: 0, rejectCount: 3, totalSignals: 3, lastTimestamp: 1 });
        aim.persistWorkflowSession({ sessionId: 's1', patternIds: ['p1'], actions: ['accept'], startedAt: 1, completedAt: 2, success: true });
        aim.persistTimeSaved({ patternId: 'p1', category: 'test', description: '', language: 'ts', estimatedSeconds: 45, timestamp: 1 });
        const stats = aim.getMemoryStats();
        expect(stats.outcomeCount).toBe(1);
        expect(stats.failureCount).toBe(1);
        expect(stats.workflowCount).toBe(1);
        expect(stats.timeSavedCount).toBe(1);
        expect(stats.totalTimeSavedSeconds).toBe(45);
    });
    test('clearAllMemory resets everything', () => {
        aim.persistOutcome({ patternId: 'p1', description: '', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: 1 });
        aim.persistFailure({ patternId: 'p_bad', category: 'test', description: '', from: 'x', to: 'y', language: 'ts', acceptCount: 0, rejectCount: 3, totalSignals: 3, lastTimestamp: 1 });
        expect(aim.getMemoryStats().outcomeCount).toBe(1);
        expect(aim.getMemoryStats().failureCount).toBe(1);
        aim.clearAllMemory();
        expect(aim.getMemoryStats().outcomeCount).toBe(0);
        expect(aim.getMemoryStats().failureCount).toBe(0);
    });
    test('persisted data survives re-init', () => {
        aim.persistOutcome({ patternId: 'p_survive', description: 'survive test', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: Date.now() });
        aim.initializeMemory();
        const outcomes = aim.queryOutcomes();
        expect(outcomes.some((o) => o.patternId === 'p_survive')).toBe(true);
    });
    test('indexMemoryForSearch and searchMemory work', () => {
        aim.persistOutcome({ patternId: 'p_search', description: 'search test pattern', action: 'accept', workflowSessionId: 's1', workflowSuccess: true, timestamp: 1 });
        aim.indexMemoryForSearch();
        const results = aim.searchMemory('search test', 5);
        expect(results.length).toBeGreaterThanOrEqual(1);
        expect(results[0].id).toContain('p_search');
    });
    test('ContextWindow manages entries', () => {
        aim.ctxWindow.clear();
        aim.addWindowEntry('user', 'hello');
        aim.addWindowEntry('assistant', 'hi there');
        expect(aim.getWindow()).toHaveLength(2);
    });
    test('estimateQueryCost returns number', () => {
        const cost = aim.estimateQueryCost('hello world', 'gpt-4o');
        expect(typeof cost).toBe('number');
        expect(cost).toBeGreaterThan(0);
    });
});
//# sourceMappingURL=ai-memory.test.js.map