"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 session_memory_1 = require("../walls/01-context/sessions/session-memory");
const database_1 = require("../walls/06-memory/database/database");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
describe('session bridge (Unit 2.6)', () => {
    let mem;
    let originalHome;
    let tmpHome;
    beforeAll(() => {
        tmpHome = path.join(os.tmpdir(), 'fivo-cell-bridge-test-' + Date.now());
        fs.mkdirSync(tmpHome, { recursive: true });
        originalHome = process.env.USERPROFILE;
        process.env.USERPROFILE = tmpHome;
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        mem = new session_memory_1.SessionMemory();
    });
    afterAll(() => {
        process.env.USERPROFILE = originalHome;
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        try {
            fs.rmSync(tmpHome, { recursive: true, force: true });
        }
        catch { /* ignore */ }
    });
    beforeEach(() => {
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        mem = new session_memory_1.SessionMemory();
        try {
            const db = (0, database_1.getDb)();
            db.exec('DELETE FROM sessions; DELETE FROM session_approaches; DELETE FROM session_files; DELETE FROM session_questions;');
        }
        catch { /* ignore */ }
    });
    it('first session: getLastSessionForProject returns null', () => {
        const last = mem.getLastSessionForProject('bridge-test-project');
        expect(last).toBeNull();
    });
    it('bridge from claude-code → cursor: previous session is endable and retrievable', () => {
        const project = 'bridge-test-1';
        const s1 = mem.startSession('claude-code', project);
        mem.recordFileTouch({ sessionId: s1, project, filePath: 'src/foo.ts' });
        mem.recordApproach({ sessionId: s1, project, approach: 'better-sqlite3', status: 'succeeded' });
        mem.recordQuestion({ sessionId: s1, project, question: 'How to migrate?' });
        mem.endSession(s1, {
            filesTouched: ['src/foo.ts'],
            keyDecisions: ['use better-sqlite3'],
            contextSnapshot: 'Phase 2.5 done',
        });
        const last = mem.getLastSessionForProject(project);
        expect(last).not.toBeNull();
        expect(last?.toolName).toBe('claude-code');
        expect(last?.contextSnapshot).toBe('Phase 2.5 done');
        expect(last?.endTime).toBeDefined();
    });
    it('startSession returns new session id, and new session starts after old', async () => {
        const project = 'bridge-test-2';
        const s1 = mem.startSession('claude-code', project);
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: 's1 done' });
        await new Promise(r => setTimeout(r, 10));
        const s2 = mem.startSession('cursor', project);
        expect(s2).toBeGreaterThan(s1);
        const last = mem.getLastSessionForProject(project);
        expect(last?.id).toBe(s1);
    });
    it('SessionMemory preserves session_approaches across end/start (anti-repetition data)', () => {
        const project = 'bridge-test-3';
        const s1 = mem.startSession('claude-code', project);
        mem.recordApproach({ sessionId: s1, project, approach: 'chokidar', status: 'failed' });
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const recent = mem.getRecentApproaches(project, 5);
        expect(recent.length).toBeGreaterThan(0);
        const chokidar = recent.find(a => a.approach === 'chokidar');
        expect(chokidar?.status).toBe('failed');
    });
    it('SessionMemory preserves session_questions across sessions (open questions persist)', () => {
        const project = 'bridge-test-4';
        const s1 = mem.startSession('claude-code', project);
        const qId = mem.recordQuestion({ sessionId: s1, project, question: 'How to detect tool switch?', priority: 'high' });
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const s2 = mem.startSession('cursor', project);
        const open = mem.getOpenQuestions(project);
        expect(open.length).toBeGreaterThan(0);
        const found = open.find(q => q.id === qId);
        expect(found?.question).toContain('tool switch');
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
    });
    it('SessionMemory preserves session_files across sessions (hot files persist)', () => {
        const project = 'bridge-test-5';
        const s1 = mem.startSession('claude-code', project);
        mem.recordFileTouch({ sessionId: s1, project, filePath: 'src/foo.ts' });
        mem.recordFileTouch({ sessionId: s1, project, filePath: 'src/foo.ts' });
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const s2 = mem.startSession('cursor', project);
        const top = mem.getMostTouchedFiles(project, 5);
        const foo = top.find(f => f.filePath === 'src/foo.ts');
        expect(foo).toBeDefined();
        expect(foo?.touchCount).toBeGreaterThanOrEqual(2);
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
    });
    it('getRecentSessions returns sessions in time order', async () => {
        const project = 'bridge-test-6';
        const s1 = mem.startSession('claude-code', project);
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: 'first' });
        await new Promise(r => setTimeout(r, 10));
        const s2 = mem.startSession('cursor', project);
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: 'second' });
        const recent = mem.getRecentSessions(10).filter(s => s.project === project);
        expect(recent.length).toBeGreaterThanOrEqual(2);
        const last = recent[0];
        expect(last.id).toBe(s2);
    });
});
//# sourceMappingURL=session-bridge.test.js.map