"use strict";
// vibe-engine.ts — Core Vibe Learning Engine v3 Supreme
// Analyzes sessions, detects signals, generates rules, builds identity
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 });
exports.analyzeSession = analyzeSession;
exports.buildVibeSummary = buildVibeSummary;
exports.getVibeSummaryFromVibeEngine_forTests = buildVibeSummary;
exports.getVibeData = getVibeData;
exports.getVibeSummary = getVibeSummary;
exports.getVibeMarkdown = getVibeMarkdown;
exports.resetVibe = resetVibe;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
const vibe_signals_1 = require("./vibe-signals");
const vibe_confidence_1 = require("./vibe-confidence");
const vibe_intelligence_1 = require("./vibe-intelligence");
function getVibeDir(projectDir) {
    return path.join(projectDir, '.cell', 'vibe');
}
function ensureVibeDir(projectDir) {
    const dir = getVibeDir(projectDir);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    return dir;
}
function analyzeSession(project, projectDir, totalSessions) {
    const existing = loadSignals(projectDir);
    const db = (0, database_1.getDb)();
    const sessions = db.prepare('SELECT id, tool_name, files_touched, key_decisions, start_time FROM sessions WHERE project = ? ORDER BY id DESC LIMIT 20').all(project);
    const events = db.prepare('SELECT type, topic, summary, details_json, importance FROM memory_events WHERE project = ? ORDER BY id DESC LIMIT 500').all(project);
    const decisions = db.prepare('SELECT decision, approach, worked FROM decision_log WHERE project = ? ORDER BY id DESC LIMIT 100').all(project);
    let teachData = {};
    try {
        const t = db.prepare("SELECT section, raw_text FROM developer_profile ORDER BY updated_at DESC").all();
        t.forEach((x) => { teachData[x.section] = x.raw_text; });
    }
    catch { }
    let styleData = {};
    try {
        const s = db.prepare('SELECT pattern_key, pattern_value FROM style_profiles ORDER BY detection_count DESC').all();
        s.forEach((x) => { styleData[x.pattern_key] = x.pattern_value; });
    }
    catch { }
    let sessionTextRaw = '';
    try {
        const apps = db.prepare('SELECT approach, status, reason FROM session_approaches ORDER BY id DESC LIMIT 50').all();
        for (const a of apps)
            sessionTextRaw += (a.approach || '') + ' ' + (a.reason || '') + ' ' + (a.status || '') + '\n';
        const qs = db.prepare('SELECT question, priority FROM session_questions ORDER BY id DESC LIMIT 50').all();
        for (const q of qs)
            sessionTextRaw += (q.question || '') + ' ' + (q.priority || '') + '\n';
    }
    catch { }
    let deepAnalysisData = { totalApproaches: 0, accepted: 0, rejected: 0, tried: 0, approachTexts: '' };
    try {
        const apps = db.prepare('SELECT approach, status, reason FROM session_approaches ORDER BY id DESC LIMIT 100').all();
        deepAnalysisData.totalApproaches = apps.length;
        for (const a of apps) {
            deepAnalysisData.approachTexts += (a.approach || '') + ' ' + (a.reason || '') + ' ';
            if (a.status === 'accepted' || a.status === 'worked')
                deepAnalysisData.accepted++;
            else if (a.status === 'rejected' || a.status === 'failed')
                deepAnalysisData.rejected++;
            else if (a.status === 'tried')
                deepAnalysisData.tried++;
        }
    }
    catch { }
    const signals = detectAllSignals(existing, sessions, events, decisions, teachData, styleData, sessionTextRaw, deepAnalysisData, totalSessions);
    const rules = generateVibeRules(signals);
    const correlated = (0, vibe_intelligence_1.generateCorrelatedInsights)(signals);
    const traits = (0, vibe_intelligence_1.generateTraitInsights)(signals);
    const allInsights = (0, vibe_intelligence_1.rankInsights)([...correlated, ...traits]);
    const identitySummary = (0, vibe_intelligence_1.generateIdentitySummary)(signals, allInsights);
    const aiGuide = (0, vibe_intelligence_1.generateAiGuide)(signals);
    const vibeData = { sessionsAnalyzed: totalSessions, lastUpdated: new Date().toISOString(), signals, rules, insights: allInsights, identitySummary, aiGuide };
    writeSignalsJson(projectDir, vibeData);
    writeVibeMarkdown(projectDir, vibeData);
    writeVibeSummary(projectDir, vibeData);
    return vibeData;
}
// ─── All signal detection + rule generation + file I/O from existing code ───
// (preserved from previous version — same detectAllSignals, generateVibeRules, etc.)
function loadSignals(projectDir) {
    try {
        const p = path.join(getVibeDir(projectDir), 'signals.json');
        if (!fs.existsSync(p))
            return [];
        const d = JSON.parse(fs.readFileSync(p, 'utf-8'));
        return d.signals || [];
    }
    catch {
        return [];
    }
}
function detectAllSignals(existingSignals, sessions, events, decisions, teachData, styleData, sessionTextRaw, deepAnalysisData, totalSessions) {
    const signalMap = new Map();
    existingSignals.forEach(s => signalMap.set(s.id, s));
    const now = new Date().toISOString();
    const allText = [...sessions.map((s) => (s.files_touched || '') + (s.key_decisions || '')), ...events.map((e) => (e.summary || '') + (e.topic || '') + (e.details_json || '')), ...decisions.map((d) => (d.decision || '') + (d.approach || '')), ...Object.values(teachData), ...Object.values(styleData), sessionTextRaw].join(' ').toLowerCase();
    for (const sig of vibe_signals_1.VIBE_SIGNALS) {
        let detected = false;
        switch (sig.id) {
            case 'language_hindi':
                detected = /[अ-ह]|hinglish|hindi|kar\b|de\b|bata\b|hai\b/.test(allText);
                break;
            case 'language_english':
                detected = !/[अ-ह]/.test(allText) && allText.length > 500;
                break;
            case 'language_mix_ratio':
                const hc = (allText.match(/[अ-ह]|hinglish|hindi|kar\b|de\b|bata\b|hai\b/g) || []).length;
                const ec = (allText.match(/[a-z]{3,}/g) || []).length;
                detected = hc > 0 && ec > 0 && (hc / Math.max(ec, 1)) > 0.3;
                break;
            case 'structure_bullets':
                detected = (allText.match(/^[-•*]\s|\d+[.)]\s/gm) || []).length > sessions.length * 2;
                break;
            case 'structure_paragraphs':
                detected = allText.length / Math.max(sessions.length, 1) > 500;
                break;
            case 'tone_direct':
                detected = /\b(kar|de|bata|fix|add|remove|create|delete|ship|launch)\b/.test(allText);
                break;
            case 'tone_formal':
                detected = (allText.match(/\b(please|could you|would you|may i|kindly)\b/g) || []).length > 5;
                break;
            case 'verbosity_low':
                detected = allText.length / Math.max(sessions.length, 1) < 300;
                break;
            case 'verbosity_high':
                detected = allText.length / Math.max(sessions.length, 1) > 1500;
                break;
            case 'communication_cadence':
                detected = sessions.length >= 3 && (allText.length / Math.max(sessions.length, 1)) < 400;
                break;
            case 'changes_minimal':
                detected = /minimal|small change|patch|fix only|don't refactor|no rewrite/.test(allText);
                break;
            case 'changes_thorough':
                detected = /rewrite|refactor entirely|full change|restructure/.test(allText);
                break;
            case 'change_size_from_diffs':
                detected = /under 50 lines|small diff|minimal change|single file|one file|small patch/.test(allText);
                break;
            case 'abstraction_low':
                detected = /keep flat|no abstraction|simple code|don't abstract|no util/.test(allText);
                break;
            case 'abstraction_high':
                detected = /base class|abstract|interface|generic|util|helper/.test(allText);
                break;
            case 'abstraction_threshold':
                detected = /duplication|dry after|third time|3rd occurrence|DRY/.test(allText) && allText.includes('abstraction');
                break;
            case 'testing_after':
                detected = /code first|test later|write tests? after/.test(allText);
                break;
            case 'testing_first':
                detected = /tdd|test first|write test|test-driven/.test(allText);
                break;
            case 'test_priority':
                detected = /integration test|e2e|unit test|coverage|jest|vitest/.test(allText);
                break;
            case 'typescript_strict':
                detected = /strict.*true|no any|explicit type|type safety/.test(allText);
                break;
            case 'typescript_loose':
                detected = /any type|as cast|ts-ignore|skip check/.test(allText);
                break;
            case 'functional_style':
                detected = /map|filter|reduce|immutable|pure function|const|arrow/.test(allText);
                break;
            case 'oop_style':
                detected = /class |extends|implements|private|public|protected/.test(allText);
                break;
            case 'naming_philosophy':
                detected = /short name|descriptive|domain language|single word|clear name/.test(allText);
                break;
            case 'audit_first':
                detected = /audit|analyze|scan|review|understand first|check first/.test(allText);
                break;
            case 'code_first':
                detected = /just build|start coding|implement now|bana de|seedha code/.test(allText);
                break;
            case 'workflow_sequence':
                detected = allText.includes('audit') && allText.includes('plan') && (allText.includes('code') || allText.includes('implement'));
                break;
            case 'plan_phased':
                detected = /phase|step by step|roadmap|plan first|milestone|iteration/.test(allText);
                break;
            case 'plan_single_shot':
                detected = /everything at once|all together|ek sath|pura ek bar/.test(allText);
                break;
            case 'task_list_mode':
                detected = /list banao|list bana|sab khatam|get them all done|task list|checklist/.test(allText);
                break;
            case 'focus_mode':
                detected = /sirf ye|just that one|ek hi kaam|single focus|only this/.test(allText);
                break;
            case 'overnight_mode':
                detected = /raat bhar|subah tak|overnight|subah report|crack on|going to bed|sleep/.test(allText);
                break;
            case 'ship_fast':
                detected = /good enough|launch kar|ship it|mvp|80%|working hai|release now/.test(allText);
                break;
            case 'session_time_pattern':
                const hrs = sessions.map((s) => s.start_time ? new Date(s.start_time).getHours() : -1).filter((h) => h >= 0);
                const nc = hrs.filter((h) => h >= 20 || h <= 4).length;
                const mc = hrs.filter((h) => h >= 5 && h <= 11).length;
                detected = sessions.length >= 3 && (nc > mc * 2 || mc > nc * 2);
                break;
            case 'deadline_behavior':
                detected = /deadline|urgent|asap|time is tight|rush|fast/.test(allText) && /ship|launch|release|deploy/.test(allText);
                break;
            case 'completion_discipline':
                detected = deepAnalysisData.totalApproaches > 0 && (deepAnalysisData.accepted + deepAnalysisData.rejected) > deepAnalysisData.tried;
                break;
            case 'roi_first':
                detected = /revenue|paisa|monetize|customer pays|profit|business value|making money/.test(allText);
                break;
            case 'ux_first':
                detected = /user experience|ux|design|flow|usability|user friendly|ui/.test(allText);
                break;
            case 'tech_first':
                detected = /architecture|performance|scale|clean code|best practice|properly/.test(allText);
                break;
            case 'decision_argument_type':
                const ar = (allText.match(/revenue|paisa|profit|money|business/g) || []).length;
                const au = (allText.match(/user experience|ux|design|flow|usability/g) || []).length;
                const at = (allText.match(/performance|scale|architecture|clean/g) || []).length;
                detected = Math.max(ar, au, at) > 3;
                break;
            case 'speed_over_quality':
                detected = /deadline|urgent|asap|quick fix|fast|time pressure/.test(allText);
                break;
            case 'quality_over_speed':
                detected = /properly|production ready|thoroughly|well tested|solid|resilient/.test(allText);
                break;
            case 'stick_to_known':
                detected = /same setup|known stack|familiar|tried and tested|proven/.test(allText);
                break;
            case 'explore_new':
                detected = /new framework|try new|experiment|latest|bleeding edge|cutting edge/.test(allText);
                break;
            case 'monetization_thinking':
                detected = /monetize|pricing|revenue|paid|subscription|tier|freemium/.test(allText);
                break;
            case 'growth_strategy':
                detected = /community|viral|organic|ads|marketing|github stars|growth/.test(allText);
                break;
            case 'user_focus':
                detected = /power user|enterprise|casual|developer|end user/.test(allText);
                break;
            case 'trust_high':
                detected = /accepted|good output|works perfectly|no changes needed/.test(allText);
                break;
            case 'trust_low':
                detected = /verify|test karo|check|make sure|confirm|validate|double check/.test(allText);
                break;
            case 'acceptance_pattern':
                detected = deepAnalysisData.totalApproaches >= 5 && (deepAnalysisData.accepted / deepAnalysisData.totalApproaches > 0.7 || deepAnalysisData.rejected / deepAnalysisData.totalApproaches > 0.5);
                break;
            case 'iterative_prompter':
                detected = /edit|refine|modify|improve|tweak|update the|change that|redo/.test(allText);
                break;
            case 'prompt_iteration_count':
                detected = deepAnalysisData.totalApproaches >= 5 && deepAnalysisData.tried > deepAnalysisData.accepted;
                break;
            case 'one_shot_user':
                detected = sessions.length > 0 && allText.length / sessions.length < 200;
                break;
            case 'verify_always':
                detected = (allText.match(/\b(verify|test karo|check|make sure|confirm|validate)\b/g) || []).length > 5;
                break;
            case 'edit_accepted_code':
                detected = /modify output|tweak|adjust the code|change .* implementation/.test(allText);
                break;
            case 'output_modification_pattern':
                detected = /modify|adjust|tweak|change that|update the|fix the|rework/.test(allText) && deepAnalysisData.accepted > 0;
                break;
            case 'model_switcher':
                detected = /claude|gpt|gemini|sonar|copilot|codex|windsurf|cursor/.test(allText);
                break;
            case 'feedback_specificity':
                detected = deepAnalysisData.approachTexts.length > 500 && (deepAnalysisData.approachTexts.match(/\b(because|due to|since|as the|should|instead of)\b/g) || []).length > 3;
                break;
            case 'prompt_complexity':
                detected = allText.split(/[.!?]\s/).length / Math.max(sessions.length, 1) > 8;
                break;
            case 'exploration_bias':
                try {
                    const d2 = (0, database_1.getDb)();
                    const pc = d2.prepare('SELECT COUNT(*) as c FROM projects').get()?.c || 1;
                    const cc = events.filter((e) => e.type === 'verification' && /complete|done|finished|launched/.test(e.summary || '')).length;
                    detected = pc > cc * 2;
                }
                catch {
                    detected = false;
                }
                break;
            case 'completion_focused':
                try {
                    const d2 = (0, database_1.getDb)();
                    const pc = d2.prepare('SELECT COUNT(*) as c FROM projects').get()?.c || 1;
                    const dc = events.filter((e) => e.type === 'verification' && /complete|done|finished|launched/.test(e.summary || '')).length;
                    detected = dc > 0 && pc <= dc + 2;
                }
                catch {
                    detected = false;
                }
                break;
            case 'completion_rate':
                detected = deepAnalysisData.totalApproaches > 10 && deepAnalysisData.tried < deepAnalysisData.accepted + deepAnalysisData.rejected;
                break;
            case 'scope_creep':
                detected = /also add|and also|while we're at|might as well|ek aur|1 more thing/.test(allText);
                break;
            case 'scope_disciplined':
                detected = /sticking to|on task|focused|only this|nothing else|bas itna/.test(allText);
                break;
            case 'solo_developer':
                detected = sessions.length > 0 && allText.length > 0 && !/team|pair|collaborate|review my pr/.test(allText);
                break;
            case 'team_player':
                detected = /team|pair programming|collaborate|review|standup|sprint|pr review/.test(allText);
                break;
            case 'refactor_trigger':
                detected = /bug|fix|broken|error/.test(allText) && /refactor|rewrite|restructure/.test(allText);
                break;
            case 'commit_small':
                detected = /small commit|atomic|single change|one thing|single file/.test(allText);
                break;
            case 'commit_large':
                detected = /big commit|squash|merge everything|all changes/.test(allText);
                break;
            case 'docs_writer':
                detected = /readme|documentation|docs|comment|wiki|guide|explanation/.test(allText);
                break;
            case 'docs_skipper':
                detected = !/readme|documentation|docs|comment|wiki/.test(allText) && allText.length > 1000;
                break;
            case 'documentation_style':
                detected = /README|documentation|docs|comment|JSDoc|wiki/.test(allText);
                break;
            case 'review_style':
                detected = /nitpick|minor|approve|LGTM|ship it|looks good/.test(allText);
                break;
            case 'error_response_pattern':
                detected = /fix immediately|fix now|quick fix|hotfix|patch/.test(allText) || /log and|note and|track and|later/.test(allText);
                break;
            case 'dependency_attitude':
                detected = /no dependency|zero dep|add dep|new package|npm install|new library/.test(allText);
                break;
            case 'stack_loyalty':
                detected = /same stack|consistent|tried and tested|proven|familiar/.test(allText) || /new framework|try something new|different/.test(allText);
                break;
            case 'learning_approach':
                detected = /deep dive|source code|understand|learn|tutorial|guide|docs/.test(allText);
                break;
            case 'ui_preference_dark':
                detected = /dark mode|dark theme|dark ui|dark background|never light/.test(allText);
                break;
            case 'ui_preference_minimal':
                detected = /minimalist|minimal|simple|clean|no clutter|single column|fewer/.test(allText);
                break;
            case 'design_philosophy':
                detected = /function over form|ugly.*fast|fast.*ugly|form over function|pretty|beautiful/.test(allText);
                break;
            case 'frustration_signal':
                detected = /[!]{2,}|are yaar|yaar|damn|pagal|gussa|frustrat|what the|bc\b/i.test(allText);
                break;
            case 'correction_style':
                detected = /galat hai|ye galat|nahi chahiye|dont do|stop that|mat kar|never do/i.test(allText);
                break;
            case 'satisfaction_signal':
                detected = /sahi hai|perfect|bas yahi|exactly|correct|spot on|finally|thats it|acha hai/i.test(allText);
                break;
            case 'urgency_detection':
                detected = /jaldi kar|jaldi se|fast|abhi karo|time nahi|asap|rush|urgent|hurry|jaldi/i.test(allText);
                break;
            case 'patience_level':
                detected = deepAnalysisData.tried > deepAnalysisData.rejected && deepAnalysisData.tried > 2;
                break;
            case 'appreciation_style':
                detected = /thanks|thank you|good job|great|nice work|awesome|accha|badhiya/i.test(allText);
                break;
            case 'thinking_aloud':
                detected = /soch raha|let me think|hmm|wait|actually|i think|mujhe lagta|lagna/i.test(allText);
                break;
            case 'example_request_style':
                detected = /example de|dikha|dikhao|samjha|samjhao|show me|example|give me example/i.test(allText);
                break;
            case 'comparison_style':
                detected = /vs\.?|compared|better way|faster way|alternative|which one|difference between/i.test(allText);
                break;
            case 'certainty_language':
                detected = /pakka|definitely|100%|absolutely|sure|for sure|shayad|maybe|ho sakta|might be|probably|not sure/i.test(allText);
                break;
            case 'ownership_language':
                const oc = (allText.match(/maine\b|main\s+ne|mera\b/i) || []).length;
                const wc = (allText.match(/hum\b|we\b|hamara\b/i) || []).length;
                detected = oc > 3 || wc > 3;
                break;
            case 'pattern_recognition_skill':
                detected = /pichli baar|last time|remember|jaise pahle|similar|same pattern|kabhi kiya/i.test(allText);
                break;
            case 'architecture_question_depth':
                const wc2 = (allText.match(/kyun\b|why\b|reason|what if|what about/i) || []).length;
                const hc2 = (allText.match(/kaise\b|how\b|karo|banao|create/i) || []).length;
                detected = wc2 > 2 || hc2 > 5;
                break;
            case 'refactoring_motivation':
                detected = (/refactor|rewrite|restructure/i.test(allText) && (/clean|performance|bug|fix|slow|ugly/i.test(allText)));
                break;
            case 'tech_curiosity':
                detected = /try karte|try karo|explore|naya|latest|new tech|what about|check out|dekhte/i.test(allText);
                break;
            case 'simplicity_bias':
                detected = /simple\b|easy\b|seedha\b|straightforward\b|minimal\b|no complexity|keep it simple/i.test(allText);
                break;
            case 'context_switch_frequency':
                detected = deepAnalysisData.totalApproaches > 5 && deepAnalysisData.totalApproaches < 15;
                break;
            case 'deep_work_detection':
                detected = sessions.length === 1 && deepAnalysisData.totalApproaches >= 3 && allText.length > 500;
                break;
            case 'break_pattern':
                detected = sessions.length >= 2;
                break;
            case 'task_chaining':
                detected = /ab ye|next\b|after this|fir\b|then\b|now this|ab ise|uske baad/i.test(allText);
                break;
            default: detected = false;
        }
        const existing = signalMap.get(sig.id);
        const count = detected ? (existing?.count || 0) + 1 : (existing?.count || 0);
        const vibe = (0, vibe_confidence_1.evolveVibe)(existing?.vibe || 0, detected, count, totalSessions, sig.multiplier);
        signalMap.set(sig.id, { id: sig.id, group: sig.group, category: sig.category, count, vibe, firstSeen: existing?.firstSeen || (detected ? now : ''), lastSeen: detected ? now : existing?.lastSeen || '' });
    }
    return [...signalMap.values()].sort((a, b) => b.vibe - a.vibe);
}
function generateVibeRules(signals) {
    const tmpl = {
        language_hindi: (s) => `Hinglish preferred — Hindi explanations, English code, mixed casually. Vibe: ${s.vibe}`, language_english: (s) => `English only communication. Code and explanations both in English. Vibe: ${s.vibe}`, structure_bullets: (s) => `Bullet points over paragraphs. Max 3 lines per bullet. Vibe: ${s.vibe}`, structure_paragraphs: (s) => `Detailed paragraphs preferred. Vibe: ${s.vibe}`, tone_direct: (s) => `Seedha bolo, no sugar-coating. Direct imperatives over polite requests. Vibe: ${s.vibe}`, tone_formal: (s) => `Formal, polite communication preferred. Vibe: ${s.vibe}`, verbosity_low: (s) => `Short answers only. Explain only when explicitly asked. Vibe: ${s.vibe}`, verbosity_high: (s) => `Detailed, thorough explanations expected with every answer. Vibe: ${s.vibe}`,
        changes_minimal: (s) => `Changes must be minimal — diff under 50 lines. Never propose full rewrites. Vibe: ${s.vibe}`, changes_thorough: (s) => `Full rewrites accepted. Large-scope changes preferred over patches. Vibe: ${s.vibe}`, abstraction_low: (s) => `Keep code flat. No abstraction until 3rd duplication. Vibe: ${s.vibe}`, abstraction_high: (s) => `Well-abstracted code. Use interfaces, base classes, utils. Vibe: ${s.vibe}`, testing_after: (s) => `Code first, tests after. Integration tests over unit tests. Vibe: ${s.vibe}`, testing_first: (s) => `TDD approach. Write tests before implementation. Vibe: ${s.vibe}`, typescript_strict: (s) => `TypeScript strict mode always. any only with documented reason. Vibe: ${s.vibe}`,
        ship_fast: (s) => `Ship at 80%. Polish is infinite, shipping is finite. Good enough beats perfect. Vibe: ${s.vibe}`, audit_first: (s) => `Always audit before code: scan → understand → plan → implement. Vibe: ${s.vibe}`, roi_first: (s) => `Revenue-first decision making. Ask "kya paisa dega?" before any feature. Vibe: ${s.vibe}`, trust_low: (s) => `Verify everything. Never accept first AI output without testing. Vibe: ${s.vibe}`, trust_high: (s) => `High trust in AI output. Accepts suggestions readily. Vibe: ${s.vibe}`, iterative_prompter: (s) => `Iterative refiner. Edits prompts 3-5 times until exact result. Vibe: ${s.vibe}`, exploration_bias: (s) => `Starts many projects. Exploration over completion. Vibe: ${s.vibe}`, completion_focused: (s) => `Finishes projects before starting new ones. Completion-driven. Vibe: ${s.vibe}`, commit_small: (s) => `Small atomic commits. Present tense. Each commit does exactly one thing. Vibe: ${s.vibe}`, solo_developer: (s) => `Solo developer. Works independently. Full ownership. Vibe: ${s.vibe}`, team_player: (s) => `Team player. Collaborates, reviews PRs, pairs frequently. Vibe: ${s.vibe}`, overnight_mode: (s) => `Autonomous overnight mode active. Vibe: ${s.vibe}`, focus_mode: (s) => `Single focus mode — one task at a time, strict scope. Vibe: ${s.vibe}`, task_list_mode: (s) => `Task list mode — create checklist, work through systematically. Vibe: ${s.vibe}`, scope_creep: (s) => `Scope creep tendency — expands features during implementation. Vibe: ${s.vibe}`, docs_writer: (s) => `Documentation writer. READMEs, comments, wikis well-maintained. Vibe: ${s.vibe}`, verify_always: (s) => `Always verifies. Runs tests after every change. Vibe: ${s.vibe}`,
        language_mix_ratio: (s) => `Mixed language communication — Hinglish pattern. Vibe: ${s.vibe}`, change_size_from_diffs: (s) => `Small, focused code changes — single files, minimal diffs. Vibe: ${s.vibe}`, test_priority: (s) => `Testing-aware developer — actively tracks coverage. Vibe: ${s.vibe}`, workflow_sequence: (s) => `Structured workflow: audit → plan → implement. Vibe: ${s.vibe}`, deadline_behavior: (s) => `Deadline-driven — shifts to speed mode under time pressure. Vibe: ${s.vibe}`, completion_discipline: (s) => `Completes what is started — high session resolution rate. Vibe: ${s.vibe}`, decision_argument_type: (s) => `Uses multiple argument types — balanced thinking. Vibe: ${s.vibe}`, monetization_thinking: (s) => `Business-aware — thinks about monetization in technical decisions. Vibe: ${s.vibe}`, acceptance_pattern: (s) => `Distinct AI acceptance pattern. Vibe: ${s.vibe}`, prompt_iteration_count: (s) => `Iterative prompter — refines through multiple edits. Vibe: ${s.vibe}`, output_modification_pattern: (s) => `Always enhances AI output. Vibe: ${s.vibe}`, feedback_specificity: (s) => `Detailed feedback giver — specific, actionable rejection reasons. Vibe: ${s.vibe}`, completion_rate: (s) => `High task completion rate. Vibe: ${s.vibe}`, refactor_trigger: (s) => `Bug-driven refactorer — changes structure when bugs force it. Vibe: ${s.vibe}`, documentation_style: (s) => `Documentation-conscious. Vibe: ${s.vibe}`, error_response_pattern: (s) => `Immediate error responder — fixes bugs quickly. Vibe: ${s.vibe}`, ui_preference_dark: (s) => `Dark mode devotee. Vibe: ${s.vibe}`, ui_preference_minimal: (s) => `Minimalist aesthetic. Vibe: ${s.vibe}`, design_philosophy: (s) => `Function-first designer. Vibe: ${s.vibe}`,
        frustration_signal: (s) => `Shows frustration directly — uses strong language when things go wrong. Vibe: ${s.vibe}`, correction_style: (s) => `Direct corrector — gives blunt, undiplomatic feedback. Vibe: ${s.vibe}`, satisfaction_signal: (s) => `Expresses satisfaction — gives clear positive signals. Vibe: ${s.vibe}`, urgency_detection: (s) => `Urgency-aware — frequently operates under time pressure. Vibe: ${s.vibe}`, patience_level: (s) => `Patient iterater — refines through edits rather than immediately rejecting. Vibe: ${s.vibe}`, appreciation_style: (s) => `Expresses appreciation — acknowledges good work. Vibe: ${s.vibe}`, thinking_aloud: (s) => `Visible thinker — shares thought process openly. Vibe: ${s.vibe}`, example_request_style: (s) => `Example-driven learner — prefers concrete examples. Vibe: ${s.vibe}`, comparison_style: (s) => `Comparison-driven — evaluates by comparing alternatives. Vibe: ${s.vibe}`, certainty_language: (s) => `Uses certainty markers — expresses confidence through language. Vibe: ${s.vibe}`, ownership_language: (s) => `Distinct ownership voice. Vibe: ${s.vibe}`, pattern_recognition_skill: (s) => `Pattern-aware — references past experiences. Vibe: ${s.vibe}`, architecture_question_depth: (s) => `Deep questioner — asks why, not just how. Vibe: ${s.vibe}`, refactoring_motivation: (s) => `Purposeful refactorer — specific motivation behind changes. Vibe: ${s.vibe}`, tech_curiosity: (s) => `Tech-curious — explores new technologies. Vibe: ${s.vibe}`, simplicity_bias: (s) => `Simplicity-first — values simple solutions. Vibe: ${s.vibe}`, context_switch_frequency: (s) => `Moderate context switcher. Vibe: ${s.vibe}`, deep_work_detection: (s) => `Deep worker — capable of long focused sessions. Vibe: ${s.vibe}`, task_chaining: (s) => `Sequential planner — chains tasks together. Vibe: ${s.vibe}`,
    };
    const rules = [];
    for (const s of signals) {
        if (!(0, vibe_confidence_1.shouldWriteToFile)(s.vibe))
            continue;
        const t = tmpl[s.id];
        if (t)
            rules.push({ text: t(s), category: s.category, vibe: s.vibe, count: s.count, level: (0, vibe_confidence_1.getVibeLevel)(s.vibe) });
    }
    return rules.sort((a, b) => b.vibe - a.vibe);
}
function buildVibeSummary(signals, rules) {
    const sigMap = new Map(signals.map(s => [s.id, s]));
    const g = (id) => sigMap.get(id)?.vibe ?? 0;
    const comm = {};
    if (g('language_hindi') >= 65)
        comm.language = 'hinglish';
    else if (g('language_english') >= 65)
        comm.language = 'english';
    if (g('structure_bullets') >= 65)
        comm.structure = 'bullets';
    if (g('tone_direct') >= 65)
        comm.tone = 'direct';
    if (g('verbosity_low') >= 65)
        comm.verbosity = 'low';
    const coding = {};
    if (g('changes_minimal') >= 65)
        coding.changeSize = 'minimal';
    if (g('abstraction_low') >= 65)
        coding.abstraction = 'low';
    if (g('testing_after') >= 65)
        coding.testing = 'after-code';
    if (g('typescript_strict') >= 65)
        coding.typescript = 'strict';
    let decisionDriver = 'balanced';
    if (g('roi_first') >= 65)
        decisionDriver = 'roi';
    else if (g('ux_first') >= 65)
        decisionDriver = 'ux';
    else if (g('tech_first') >= 65)
        decisionDriver = 'tech';
    let uiPreference = 'unknown';
    if (g('ui_preference_dark') >= 65)
        uiPreference = 'dark';
    let shipStyle = 'balanced';
    if (g('ship_fast') >= 65)
        shipStyle = 'fast';
    let aiTrust = 'balanced';
    if (g('trust_low') >= 65 || g('verify_always') >= 65)
        aiTrust = 'verify_always';
    else if (g('trust_high') >= 65)
        aiTrust = 'high';
    const strengths = [];
    if (g('audit_first') >= 65)
        strengths.push('Systematic auditor');
    if (g('ship_fast') >= 65)
        strengths.push('Fast shipper');
    if (g('tone_direct') >= 65)
        strengths.push('Direct communicator');
    if (g('commit_small') >= 65)
        strengths.push('Clean git hygiene');
    if (g('completion_focused') >= 65)
        strengths.push('Completion driven');
    if (g('simplicity_bias') >= 65)
        strengths.push('Simplicity advocate');
    if (g('deep_work_detection') >= 65)
        strengths.push('Deep focus capability');
    const risks = (0, vibe_confidence_1.detectRisks)(signals);
    if (g('exploration_bias') >= 65)
        risks.push('Exploration bias — starts more than finishes');
    if (g('scope_creep') >= 65)
        risks.push('Scope creep — features expand during work');
    if (g('frustration_signal') >= 65)
        risks.push('Frustration under pressure — communication may intensify');
    const avoid = [];
    if (g('changes_minimal') >= 65)
        avoid.push('Large rewrites');
    if (g('abstraction_low') >= 65)
        avoid.push('Over-abstraction');
    if (g('tone_direct') >= 65)
        avoid.push('Corporate/formal language');
    if (g('language_hindi') >= 65)
        avoid.push('Pure English responses');
    if (g('simplicity_bias') >= 65)
        avoid.push('Over-engineering');
    let bestWorkflow = 'Standard workflow';
    if (g('audit_first') >= 65 && g('ship_fast') >= 65)
        bestWorkflow = 'Audit → phased plan → incremental delivery → ship at 80%';
    else if (g('audit_first') >= 65)
        bestWorkflow = 'Audit → plan → thorough implementation';
    else if (g('ship_fast') >= 65)
        bestWorkflow = 'Build fast → test → ship';
    let riskProfile = 'medium';
    if (g('ship_fast') >= 65 && g('speed_over_quality') >= 60)
        riskProfile = 'high';
    else if (g('quality_over_speed') >= 65)
        riskProfile = 'low';
    const catAvgs = [];
    for (const cat of (0, vibe_signals_1.getAllCategories)()) {
        const cs = signals.filter(s => s.category === cat);
        const a = (0, vibe_confidence_1.categoryVibeAverage)(cs);
        if (a > 0)
            catAvgs.push({ cat, avg: a });
    }
    const topCats = catAvgs.sort((a, b) => b.avg - a.avg).slice(0, 5).map(c => c.cat);
    const sp = [];
    if (decisionDriver === 'roi')
        sp.push('ROI-driven');
    if (decisionDriver === 'ux')
        sp.push('UX-focused');
    if (shipStyle === 'fast')
        sp.push('ships fast');
    if (comm.language === 'hinglish')
        sp.push('Hinglish communicator');
    if (aiTrust === 'verify_always')
        sp.push('verification-obsessed');
    const summary = sp.length > 0 ? sp.join(', ') + '.' : 'Style still learning.';
    return { summary, strengths: strengths.length > 0 ? strengths : ['Still discovering strengths'], risks: risks.length > 0 ? risks : ['No risks detected yet'], bestWorkflow, avoid: avoid.length > 0 ? avoid : ['Nothing specific yet'], communication: comm, coding, decisionDriver, riskProfile, uiPreference, shipStyle, aiTrust, totalRules: rules.length, averageVibe: Math.round(signals.reduce((acc, s) => acc + s.vibe, 0) / Math.max(signals.length, 1)), topCategories: topCats };
}
function writeSignalsJson(projectDir, data) { ensureVibeDir(projectDir); fs.writeFileSync(path.join(getVibeDir(projectDir), 'signals.json'), JSON.stringify(data, null, 2), 'utf-8'); }
function writeVibeMarkdown(projectDir, data) {
    ensureVibeDir(projectDir);
    const lines = ['# Cell Vibe — Your Developer Personality\n', `*Learned from ${data.sessionsAnalyzed} sessions. Last updated: ${data.lastUpdated}*\n`];
    if (data.identitySummary) {
        lines.push(`## 🔮 Identity`);
        lines.push('');
        lines.push(data.identitySummary);
        lines.push('');
    }
    const byCat = new Map();
    for (const r of data.rules) {
        const e = byCat.get(r.category) || [];
        e.push(r);
        byCat.set(r.category, e);
    }
    for (const [cat, rules] of byCat) {
        lines.push(`## ${cat}\n`);
        for (const r of rules.sort((a, b) => b.vibe - a.vibe))
            lines.push(`- ${r.text}`);
        lines.push('');
    }
    if (data.insights && data.insights.length > 0) {
        lines.push('## 🧬 Deep Insights');
        lines.push('');
        for (const i of data.insights.slice(0, 5))
            lines.push(`- ${i.text} (${i.confidence}/100)`);
        lines.push('');
    }
    if (data.aiGuide) {
        lines.push('## 🤖 AI Guide — How To Work With This Developer');
        lines.push('');
        lines.push(data.aiGuide);
        lines.push('');
    }
    fs.writeFileSync(path.join(getVibeDir(projectDir), 'vibe.md'), lines.join('\n'), 'utf-8');
}
function writeVibeSummary(projectDir, data) { ensureVibeDir(projectDir); const s = buildVibeSummary(data.signals, data.rules); if (data.identitySummary)
    s.summary = data.identitySummary; fs.writeFileSync(path.join(getVibeDir(projectDir), 'vibe-summary.json'), JSON.stringify(s, null, 2), 'utf-8'); }
function getVibeData(projectDir) { try {
    const p = path.join(getVibeDir(projectDir), 'signals.json');
    if (!fs.existsSync(p))
        return null;
    return JSON.parse(fs.readFileSync(p, 'utf-8'));
}
catch {
    return null;
} }
function getVibeSummary(projectDir) { try {
    const p = path.join(getVibeDir(projectDir), 'vibe-summary.json');
    if (!fs.existsSync(p))
        return null;
    return JSON.parse(fs.readFileSync(p, 'utf-8'));
}
catch {
    return null;
} }
function getVibeMarkdown(projectDir) { try {
    const p = path.join(getVibeDir(projectDir), 'vibe.md');
    if (!fs.existsSync(p))
        return '# Vibe\n\nNo vibe data yet.';
    return fs.readFileSync(p, 'utf-8');
}
catch {
    return '# Vibe\n\nCould not read.';
} }
function resetVibe(projectDir) { const d = getVibeDir(projectDir); if (fs.existsSync(d))
    for (const f of fs.readdirSync(d))
        fs.unlinkSync(path.join(d, f)); }
//# sourceMappingURL=vibe-engine.js.map