"use strict";
/**
 * Cross-Memory Continue (Phase 5) — full resume flow test
 *
 * Tests the chain: last-session lookup → summary → new session creation →
 * event linking → cross-tool context block, end to end.
 */
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 os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'cell-continue-test-'));
const originalHome = process.env.USERPROFILE;
process.env.USERPROFILE = tempHome;
process.env.HOME = tempHome;
process.env.FIVO_CELL_HOME = tempHome;
const database_1 = require("../walls/06-memory/database/database");
const session_memory_1 = require("../walls/01-context/sessions/session-memory");
const event_capture_1 = require("../walls/01-context/sessions/event-capture");
const replay_1 = require("../walls/01-context/sessions/replay");
describe('Cross-Memory Continue (Phase 5) — resume flow', () => {
    beforeEach(() => {
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        (0, database_1.initializeDatabase)();
        const db = (0, database_1.getDb)();
        const tables = ['live_events', 'sessions', 'session_approaches', 'session_files',
            'session_questions', 'decisions', 'model_interactions', 'model_profiles',
            'bugs', 'watch_deltas'];
        for (const t of tables) {
            try {
                db.exec(`DELETE FROM ${t}`);
            }
            catch { /* table may not exist */ }
        }
    });
    afterAll(() => {
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        process.env.USERPROFILE = originalHome;
        process.env.HOME = originalHome;
        try {
            fs.rmSync(tempHome, { recursive: true, force: true });
        }
        catch { /* ignore */ }
    });
    it('detects no previous session on a fresh project', () => {
        const mem = new session_memory_1.SessionMemory();
        const last = mem.getLastSessionForProject('brand-new-project');
        expect(last).toBeNull();
    });
    it('finds the most recent ended session for a project', async () => {
        const mem = new session_memory_1.SessionMemory();
        const s1 = mem.startSession('claude-code', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: s1, toolName: 'claude-code' });
        mem.endSession(s1, { filesTouched: ['a.ts'], contextSnapshot: 'editing a.ts' });
        (0, event_capture_1.recordSessionEnd)({ project: 'p1', sessionId: s1, toolName: 'claude-code' });
        // Wait 2ms to ensure distinct end_time
        await new Promise(r => setTimeout(r, 5));
        const s2 = mem.startSession('cursor', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: s2, toolName: 'cursor' });
        mem.endSession(s2, { filesTouched: ['b.ts'], contextSnapshot: 'editing b.ts' });
        (0, event_capture_1.recordSessionEnd)({ project: 'p1', sessionId: s2, toolName: 'cursor' });
        const last = mem.getLastSessionForProject('p1');
        expect(last).not.toBeNull();
        expect(last.id).toBe(s2);
        expect(last.toolName).toBe('cursor');
        expect(last.filesTouched).toContain('b.ts');
    });
    it('does not find active (unended) sessions', () => {
        const mem = new session_memory_1.SessionMemory();
        const s1 = mem.startSession('claude-code', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: s1, toolName: 'claude-code' });
        const last = mem.getLastSessionForProject('p1');
        expect(last).toBeNull();
    });
    it('summarizes a real session for context preview', () => {
        const mem = new session_memory_1.SessionMemory();
        const sessionId = mem.startSession('claude-code', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId, toolName: 'claude-code' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', sessionId, filePath: 'src/api.ts' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', sessionId, filePath: 'src/auth.ts' });
        (0, event_capture_1.recordTerminalCommand)({ project: 'p1', sessionId, command: 'npm test', cwd: '/p1' });
        mem.endSession(sessionId, {
            filesTouched: ['src/api.ts', 'src/auth.ts'],
            keyDecisions: ['Use JWT for auth'],
            contextSnapshot: 'building auth flow',
        });
        (0, event_capture_1.recordSessionEnd)({ project: 'p1', sessionId, toolName: 'claude-code' });
        const summary = (0, replay_1.summarizeSession)('p1', sessionId);
        expect(summary).not.toBeNull();
        expect(summary.sessionId).toBe(sessionId);
        expect(summary.totalEvents).toBeGreaterThanOrEqual(5);
        expect(summary.uniqueFiles).toEqual(expect.arrayContaining(['src/api.ts', 'src/auth.ts']));
        expect(summary.uniqueCommands).toContain('npm test');
        expect(summary.contextSnapshot).toContain('auth');
        const text = (0, replay_1.renderSessionSummary)(summary);
        expect(text).toContain('Session #' + sessionId);
        expect(text).toContain('claude-code');
        expect(text).toContain('building auth flow');
    });
    it('links recent unlinked events to a new session', () => {
        const mem = new session_memory_1.SessionMemory();
        (0, event_capture_1.recordFileSave)({ project: 'p1', filePath: 'a.ts' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', filePath: 'b.ts' });
        (0, event_capture_1.recordTerminalCommand)({ project: 'p1', command: 'ls', cwd: '/p1' });
        const newId = mem.startSession('cursor', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: newId, toolName: 'cursor' });
        const linked = (0, event_capture_1.linkSessionToRecentEvents)('p1', newId, false);
        expect(linked).toBe(3);
        const timeline = (0, event_capture_1.getTimeline)({ project: 'p1', sessionId: newId });
        const files = timeline.filter(e => e.filePath).map(e => e.filePath);
        expect(files).toEqual(expect.arrayContaining(['a.ts', 'b.ts']));
    });
    it('full resume flow: find last → summarize → start new → link', () => {
        const mem = new session_memory_1.SessionMemory();
        const oldId = mem.startSession('claude-code', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: oldId, toolName: 'claude-code' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', sessionId: oldId, filePath: 'old.ts' });
        mem.endSession(oldId, {
            filesTouched: ['old.ts'],
            keyDecisions: ['chose SQLite'],
            contextSnapshot: 'designing schema',
        });
        (0, event_capture_1.recordSessionEnd)({ project: 'p1', sessionId: oldId, toolName: 'claude-code' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', filePath: 'new1.ts' });
        (0, event_capture_1.recordFileSave)({ project: 'p1', filePath: 'new2.ts' });
        const last = mem.getLastSessionForProject('p1');
        expect(last).not.toBeNull();
        const summary = (0, replay_1.summarizeSession)('p1', last.id);
        expect(summary).not.toBeNull();
        expect(summary.contextSnapshot).toContain('designing schema');
        const newId = mem.startSession('cursor', 'p1');
        (0, event_capture_1.recordSessionStart)({ project: 'p1', sessionId: newId, toolName: 'cursor' });
        const linked = (0, event_capture_1.linkSessionToRecentEvents)('p1', newId, false);
        expect(linked).toBe(2);
        const newSummary = (0, replay_1.summarizeSession)('p1', newId);
        expect(newSummary).not.toBeNull();
        expect(newSummary.uniqueFiles).toEqual(expect.arrayContaining(['new1.ts', 'new2.ts']));
    });
});
//# sourceMappingURL=cross-memory-continue.test.js.map