"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDb = getDb;
exports.closeDb = closeDb;
exports.initializeDatabase = initializeDatabase;
exports.backupDatabase = backupDatabase;
exports.getDatabaseStats = getDatabaseStats;
exports.migrateJsonToSqlite = migrateJsonToSqlite;
exports.optimizeDatabase = optimizeDatabase;
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
function getDbPath() {
    return path.join(os.homedir(), '.fivo', 'cell', 'cell.db');
}
let _db = null;
let _dbPath = null;
let _initializedPaths = new Set();
let _initializing = false;
function getDb() {
    const p = getDbPath();
    if (_db && _dbPath === p) {
        if (!_initializing && !_initializedPaths.has(p)) {
            _initializing = true;
            try {
                initializeDatabase();
                _initializedPaths.add(p);
            }
            finally {
                _initializing = false;
            }
        }
        return _db;
    }
    if (_db) {
        try {
            _db.close();
        }
        catch { /* ignore */ }
        _db = null;
    }
    const dir = path.dirname(p);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    _db = new better_sqlite3_1.default(p);
    _db.pragma('journal_mode = WAL');
    _db.pragma('foreign_keys = ON');
    _dbPath = p;
    if (!_initializing) {
        _initializing = true;
        try {
            initializeDatabase();
            _initializedPaths.add(p);
        }
        finally {
            _initializing = false;
        }
    }
    return _db;
}
function closeDb() {
    if (_db) {
        try {
            _db.pragma('wal_checkpoint(TRUNCATE)');
        }
        catch { /* ignore */ }
        try {
            _db.close();
        }
        catch { /* ignore */ }
        _db = null;
    }
}
function initializeDatabase() {
    const db = getDb();
    db.exec(`
    CREATE TABLE IF NOT EXISTS patterns (
      id TEXT PRIMARY KEY,
      category TEXT NOT NULL,
      subcategory TEXT,
      rule TEXT NOT NULL,
      confidence REAL DEFAULT 0.5,
      source TEXT,
      project TEXT,
      language TEXT,
      file_path TEXT,
      line_number INTEGER,
      created_at TEXT DEFAULT (datetime('now')),
      updated_at TEXT DEFAULT (datetime('now')),
      decay_rate REAL DEFAULT 0.01,
      reuse_count INTEGER DEFAULT 0,
      success_count INTEGER DEFAULT 0,
      failure_count INTEGER DEFAULT 0,
      tags TEXT,
      metadata TEXT
    );

    CREATE TABLE IF NOT EXISTS scans (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      scanned_at TEXT DEFAULT (datetime('now')),
      file_count INTEGER,
      line_count INTEGER,
      stack TEXT,
      patterns TEXT,
      hubs TEXT,
      issues TEXT
    );

    CREATE TABLE IF NOT EXISTS behavior_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      event_type TEXT NOT NULL,
      project TEXT,
      file_path TEXT,
      description TEXT,
      severity TEXT DEFAULT 'low',
      evidence TEXT,
      created_at TEXT DEFAULT (datetime('now')),
      resolved_at TEXT,
      pattern_id TEXT,
      recurrence_count INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS journey_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      event_type TEXT NOT NULL,
      project TEXT,
      description TEXT,
      metadata TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS skills (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      language TEXT NOT NULL,
      level TEXT NOT NULL DEFAULT 'new',
      confidence REAL DEFAULT 0.5,
      file_count INTEGER DEFAULT 0,
      line_count INTEGER DEFAULT 0,
      first_seen TEXT,
      last_active TEXT,
      milestones TEXT
    );

    CREATE TABLE IF NOT EXISTS goals (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      description TEXT,
      category TEXT DEFAULT 'skill',
      target_date TEXT,
      progress REAL DEFAULT 0,
      status TEXT DEFAULT 'active',
      evidence TEXT,
      created_at TEXT DEFAULT (datetime('now')),
      updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS collaborators (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      email TEXT,
      project TEXT,
      commit_count INTEGER DEFAULT 0,
      first_commit TEXT,
      last_commit TEXT,
      skills TEXT,
      collaboration_score REAL DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS silos (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      members TEXT,
      knowledge_area TEXT,
      risk_level TEXT DEFAULT 'low',
      bus_factor INTEGER DEFAULT 1,
      detected_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS signals (
      id TEXT PRIMARY KEY,
      signal_type TEXT NOT NULL,
      file_path TEXT,
      diff TEXT,
      pattern_ids TEXT,
      project TEXT,
      session_id TEXT,
      weight REAL DEFAULT 1.0,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS outcomes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      outcome_type TEXT NOT NULL,
      pattern_id TEXT,
      project TEXT,
      description TEXT,
      metrics TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS user_profile (
      id INTEGER PRIMARY KEY DEFAULT 1,
      name TEXT,
      products TEXT,
      stack TEXT,
      work_style TEXT,
      preferences TEXT,
      updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS community_signals (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      pattern_hash TEXT,
      category TEXT,
      language TEXT,
      frequency INTEGER DEFAULT 1,
      trend TEXT DEFAULT 'stable',
      percentile REAL,
      region TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS projects (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      path TEXT,
      status TEXT DEFAULT 'active',
      last_commit TEXT,
      commit_count INTEGER DEFAULT 0,
      file_count INTEGER DEFAULT 0,
      line_count INTEGER DEFAULT 0,
      tech_stack TEXT,
      health_score REAL DEFAULT 0,
      updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS insights (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      insight_type TEXT NOT NULL,
      level TEXT,
      confidence REAL,
      evidence TEXT,
      content TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS config (
      key TEXT PRIMARY KEY,
      value TEXT,
      updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS sessions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      tool_name TEXT,
      project TEXT,
      start_time TEXT DEFAULT (datetime('now')),
      end_time TEXT,
      files_touched TEXT,
      key_decisions TEXT,
      context_snapshot TEXT
    );

    CREATE TABLE IF NOT EXISTS session_approaches (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      session_id INTEGER,
      project TEXT,
      approach TEXT NOT NULL,
      status TEXT,
      reason TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );
    CREATE INDEX IF NOT EXISTS idx_session_approaches_project ON session_approaches(project);
    CREATE INDEX IF NOT EXISTS idx_session_approaches_session ON session_approaches(session_id);

    CREATE TABLE IF NOT EXISTS session_files (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      session_id INTEGER,
      project TEXT,
      file_path TEXT NOT NULL,
      touch_count INTEGER DEFAULT 1,
      first_touched TEXT DEFAULT (datetime('now')),
      last_touched TEXT DEFAULT (datetime('now'))
    );
    CREATE INDEX IF NOT EXISTS idx_session_files_project ON session_files(project);
    CREATE INDEX IF NOT EXISTS idx_session_files_session ON session_files(session_id);
    CREATE INDEX IF NOT EXISTS idx_session_files_path ON session_files(file_path);

    CREATE TABLE IF NOT EXISTS session_questions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      session_id INTEGER,
      project TEXT,
      question TEXT NOT NULL,
      priority TEXT,
      resolved INTEGER DEFAULT 0,
      answer TEXT,
      created_at TEXT DEFAULT (datetime('now')),
      resolved_at TEXT
    );
    CREATE INDEX IF NOT EXISTS idx_session_questions_project ON session_questions(project);
    CREATE INDEX IF NOT EXISTS idx_session_questions_open ON session_questions(resolved, project);

    CREATE TABLE IF NOT EXISTS decisions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      technology TEXT,
      reason TEXT,
      outcome TEXT,
      was_right INTEGER,
      project TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS model_profiles (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      model_name TEXT NOT NULL,
      task_type TEXT,
      acceptance_rate REAL,
      rejection_rate REAL,
      avg_time_ms INTEGER,
      best_use_cases TEXT,
      worst_use_cases TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS model_interactions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      model_name TEXT NOT NULL,
      task_type TEXT NOT NULL,
      suggestion TEXT,
      accepted INTEGER DEFAULT 0,
      rejection_reason TEXT,
      time_to_accept_ms INTEGER,
      project TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS prompt_history (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      model_name TEXT NOT NULL,
      task_type TEXT NOT NULL,
      prompt_pattern TEXT NOT NULL,
      success_rate REAL DEFAULT 0,
      use_count INTEGER DEFAULT 0,
      avg_iterations REAL DEFAULT 0,
      project TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    -- Phase 3.1: File-level Knowledge Graph (deps + complexity)
    CREATE TABLE IF NOT EXISTS knowledge_graph_files (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      file_path TEXT NOT NULL,
      complexity INTEGER DEFAULT 0,
      import_count INTEGER DEFAULT 0,
      imported_by_count INTEGER DEFAULT 0,
      is_entry_point INTEGER DEFAULT 0,
      risk_score REAL DEFAULT 0,
      built_at TEXT DEFAULT (datetime('now')),
      UNIQUE(project, file_path)
    );

    CREATE TABLE IF NOT EXISTS knowledge_graph_deps (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      from_file TEXT NOT NULL,
      to_file TEXT NOT NULL,
      built_at TEXT DEFAULT (datetime('now')),
      UNIQUE(project, from_file, to_file)
    );

    -- Phase 3.2: Pattern-level Knowledge Graph
    CREATE TABLE IF NOT EXISTS graph_entities (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      entity_name TEXT NOT NULL,
      entity_type TEXT NOT NULL,
      pattern_id TEXT,
      weight REAL DEFAULT 1.0,
      metadata TEXT,
      built_at TEXT DEFAULT (datetime('now')),
      UNIQUE(entity_name, entity_type)
    );

    CREATE TABLE IF NOT EXISTS graph_relationships (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      from_pattern TEXT NOT NULL,
      to_pattern TEXT NOT NULL,
      rel_type TEXT NOT NULL,
      strength REAL DEFAULT 1.0,
      evidence TEXT,
      built_at TEXT DEFAULT (datetime('now')),
      UNIQUE(from_pattern, to_pattern, rel_type)
    );

    -- Phase 3.3: Tech proficiency tracking
    CREATE TABLE IF NOT EXISTS tech_proficiency (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      technology TEXT NOT NULL,
      category TEXT,
      signals_count INTEGER DEFAULT 0,
      proficiency_score REAL DEFAULT 0,
      last_seen TEXT DEFAULT (datetime('now')),
      trend TEXT DEFAULT 'stable',
      UNIQUE(project, technology)
    );

    -- Phase 3.4/3.5: Unified predictive insights + blast radius
    CREATE TABLE IF NOT EXISTS predictive_insights (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      insight_type TEXT NOT NULL,
      target TEXT NOT NULL,
      score REAL DEFAULT 0,
      evidence TEXT,
      recommendation TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    -- Phase 5: Community shared patterns + insights
    CREATE TABLE IF NOT EXISTS community_patterns (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      pattern_id TEXT NOT NULL UNIQUE,
      anonymous_id TEXT NOT NULL,
      category TEXT NOT NULL,
      language TEXT,
      framework TEXT,
      rule TEXT NOT NULL,
      success_rate REAL DEFAULT 0,
      usage_count INTEGER DEFAULT 0,
      votes INTEGER DEFAULT 0,
      privacy_safe INTEGER DEFAULT 1,
      shared_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS community_insights (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      insight_type TEXT NOT NULL,
      title TEXT NOT NULL,
      description TEXT,
      category TEXT,
      language TEXT,
      severity TEXT DEFAULT 'info',
      evidence TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS community_benchmarks (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      metric TEXT NOT NULL,
      value REAL NOT NULL,
      user_value REAL,
      delta REAL,
      category TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    -- Phase 6: Usage Intelligence
    CREATE TABLE IF NOT EXISTS decision_outcomes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      technology TEXT NOT NULL,
      reason TEXT,
      outcome TEXT,
      was_right INTEGER DEFAULT 0,
      confidence INTEGER DEFAULT 50,
      context TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS repeat_mistake_alerts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      error_type TEXT NOT NULL,
      file_pattern TEXT,
      occurrence_count INTEGER DEFAULT 1,
      last_seen TEXT DEFAULT (datetime('now')),
      dismissed INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS productivity_signals (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      signal_type TEXT NOT NULL,
      duration_minutes INTEGER,
      files_touched INTEGER,
      context_switches INTEGER,
      flow_state INTEGER DEFAULT 0,
      friction_score INTEGER DEFAULT 0,
      created_at TEXT DEFAULT (datetime('now'))
    );

    -- Phase 7: Live watcher state + events
    CREATE TABLE IF NOT EXISTS live_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      event_type TEXT NOT NULL,
      file_path TEXT,
      metadata TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS watcher_state (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL UNIQUE,
      dir_path TEXT NOT NULL,
      active INTEGER DEFAULT 1,
      last_event_at TEXT,
      event_count INTEGER DEFAULT 0,
      started_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS refresh_log (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      trigger_type TEXT NOT NULL,
      success INTEGER DEFAULT 0,
      duration_ms INTEGER,
      details TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS branch_snapshots (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      branch TEXT NOT NULL,
      goal TEXT,
      files_touched TEXT,
      pending_tasks TEXT,
      recent_errors TEXT,
      recent_decisions TEXT,
      last_session_id INTEGER,
      last_active_at TEXT DEFAULT (datetime('now')),
      created_at TEXT DEFAULT (datetime('now')),
      updated_at TEXT DEFAULT (datetime('now')),
      UNIQUE(project, branch)
    );

    CREATE TABLE IF NOT EXISTS stack_history (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      stack_json TEXT NOT NULL,
      file_count INTEGER,
      line_count INTEGER,
      scanned_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS memory_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      branch TEXT,
      type TEXT NOT NULL,
      topic TEXT,
      summary TEXT NOT NULL,
      details_json TEXT,
      files_json TEXT,
      importance INTEGER DEFAULT 3,
      tool TEXT,
      model TEXT,
      tags_json TEXT,
      created_at TEXT DEFAULT (datetime('now')),
      occurrence_count INTEGER DEFAULT 1,
      last_seen_at TEXT DEFAULT (datetime('now')),
      synced INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS memory_archive_refs (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      category TEXT NOT NULL,
      chunk_path TEXT NOT NULL,
      record_count INTEGER DEFAULT 0,
      compressed_size INTEGER DEFAULT 0,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS handoff_entries (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      branch TEXT,
      title TEXT NOT NULL,
      summary TEXT NOT NULL,
      why TEXT,
      files_changed_json TEXT,
      related_files_json TEXT,
      impact TEXT,
      verification TEXT,
      tool TEXT,
      model TEXT,
      status TEXT DEFAULT 'done',
      next_steps TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS memory_summaries (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      summary_type TEXT NOT NULL,
      period TEXT,
      content TEXT NOT NULL,
      event_count INTEGER DEFAULT 0,
      created_at TEXT DEFAULT (datetime('now')),
      date TEXT,
      total_events INTEGER DEFAULT 0,
      avg_importance REAL DEFAULT 0,
      top_topics TEXT,
      key_decisions TEXT,
      errors TEXT,
      by_type TEXT,
      ai_prompt TEXT
    );

    CREATE TABLE IF NOT EXISTS style_profiles (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      profile_type TEXT NOT NULL,
      profile_json TEXT NOT NULL,
      updated_at TEXT DEFAULT (datetime('now')),
      UNIQUE(project, profile_type)
    );

    CREATE TABLE IF NOT EXISTS memory_patterns (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      pattern TEXT NOT NULL,
      category TEXT NOT NULL,
      importance INTEGER DEFAULT 5,
      confidence REAL DEFAULT 0.5,
      source TEXT,
      files_json TEXT,
      last_seen TEXT DEFAULT (datetime('now')),
      occurrence_count INTEGER DEFAULT 1,
      created_at TEXT DEFAULT (datetime('now')),
      language TEXT,
      framework TEXT,
      success_rate REAL DEFAULT 0.5,
      shared_at TEXT DEFAULT (datetime('now'))
    );
  `);
    // Migrate memory_patterns: add columns if missing
    const mpCols = db.prepare("PRAGMA table_info(memory_patterns)").all();
    const mpColNames = mpCols.map(c => c.name);
    if (!mpColNames.includes('language'))
        db.exec("ALTER TABLE memory_patterns ADD COLUMN language TEXT");
    if (!mpColNames.includes('framework'))
        db.exec("ALTER TABLE memory_patterns ADD COLUMN framework TEXT");
    if (!mpColNames.includes('success_rate'))
        db.exec("ALTER TABLE memory_patterns ADD COLUMN success_rate REAL DEFAULT 0.5");
    if (!mpColNames.includes('shared_at'))
        db.exec("ALTER TABLE memory_patterns ADD COLUMN shared_at TEXT DEFAULT (datetime('now'))");
    // Migrate memory_summaries: add columns if missing
    const msCols = db.prepare("PRAGMA table_info(memory_summaries)").all();
    const msColNames = msCols.map(c => c.name);
    if (!msColNames.includes('date'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN date TEXT");
    if (!msColNames.includes('total_events'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN total_events INTEGER DEFAULT 0");
    if (!msColNames.includes('avg_importance'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN avg_importance REAL DEFAULT 0");
    if (!msColNames.includes('top_topics'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN top_topics TEXT");
    if (!msColNames.includes('key_decisions'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN key_decisions TEXT");
    if (!msColNames.includes('errors'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN errors TEXT");
    if (!msColNames.includes('by_type'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN by_type TEXT");
    if (!msColNames.includes('ai_prompt'))
        db.exec("ALTER TABLE memory_summaries ADD COLUMN ai_prompt TEXT");
    db.exec(`
    CREATE INDEX IF NOT EXISTS idx_patterns_category ON patterns(category);
    CREATE INDEX IF NOT EXISTS idx_patterns_project ON patterns(project);
    CREATE INDEX IF NOT EXISTS idx_patterns_language ON patterns(language);
    CREATE INDEX IF NOT EXISTS idx_patterns_confidence ON patterns(confidence DESC);
    CREATE INDEX IF NOT EXISTS idx_signals_type ON signals(signal_type);
    CREATE INDEX IF NOT EXISTS idx_signals_project ON signals(project);
    CREATE INDEX IF NOT EXISTS idx_signals_session ON signals(session_id);
    CREATE INDEX IF NOT EXISTS idx_behavior_type ON behavior_events(event_type);
    CREATE INDEX IF NOT EXISTS idx_behavior_project ON behavior_events(project);
    CREATE INDEX IF NOT EXISTS idx_journey_project ON journey_events(project);
    CREATE INDEX IF NOT EXISTS idx_sessions_tool ON sessions(tool_name);
    CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project);
    CREATE INDEX IF NOT EXISTS idx_outcomes_pattern ON outcomes(pattern_id);
    CREATE INDEX IF NOT EXISTS idx_outcomes_project ON outcomes(project);
    CREATE INDEX IF NOT EXISTS idx_scans_project ON scans(project);
    CREATE INDEX IF NOT EXISTS idx_skills_language ON skills(language);
    CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status);
    CREATE INDEX IF NOT EXISTS idx_collaborators_project ON collaborators(project);
    CREATE INDEX IF NOT EXISTS idx_silos_risk ON silos(risk_level);
    CREATE INDEX IF NOT EXISTS idx_community_hash ON community_signals(pattern_hash);
    CREATE INDEX IF NOT EXISTS idx_community_trend ON community_signals(trend);
    CREATE INDEX IF NOT EXISTS idx_projects_status ON projects(status);
    CREATE INDEX IF NOT EXISTS idx_decisions_project ON decisions(project);
    CREATE INDEX IF NOT EXISTS idx_model_name ON model_profiles(model_name);
    CREATE INDEX IF NOT EXISTS idx_model_interactions_name ON model_interactions(model_name);
    CREATE INDEX IF NOT EXISTS idx_model_interactions_task ON model_interactions(task_type);
    CREATE INDEX IF NOT EXISTS idx_prompt_history_name ON prompt_history(model_name);
    CREATE INDEX IF NOT EXISTS idx_branch_snapshots_project ON branch_snapshots(project);
    CREATE INDEX IF NOT EXISTS idx_branch_snapshots_branch ON branch_snapshots(branch);
    CREATE INDEX IF NOT EXISTS idx_stack_history_project ON stack_history(project);
    CREATE INDEX IF NOT EXISTS idx_stack_history_scanned ON stack_history(scanned_at);
    CREATE INDEX IF NOT EXISTS idx_prompt_history_task ON prompt_history(task_type);
    CREATE INDEX IF NOT EXISTS idx_kg_files_project ON knowledge_graph_files(project);
    CREATE INDEX IF NOT EXISTS idx_kg_files_complexity ON knowledge_graph_files(complexity DESC);
    CREATE INDEX IF NOT EXISTS idx_kg_deps_project ON knowledge_graph_deps(project);
    CREATE INDEX IF NOT EXISTS idx_kg_deps_from ON knowledge_graph_deps(from_file);
    CREATE INDEX IF NOT EXISTS idx_graph_entities_type ON graph_entities(entity_type);
    CREATE INDEX IF NOT EXISTS idx_graph_relationships_from ON graph_relationships(from_pattern);
    CREATE INDEX IF NOT EXISTS idx_graph_relationships_type ON graph_relationships(rel_type);
    CREATE INDEX IF NOT EXISTS idx_tech_proficiency_project ON tech_proficiency(project);
    CREATE INDEX IF NOT EXISTS idx_tech_proficiency_score ON tech_proficiency(proficiency_score DESC);
    CREATE INDEX IF NOT EXISTS idx_predictive_insights_project ON predictive_insights(project);
    CREATE INDEX IF NOT EXISTS idx_predictive_insights_type ON predictive_insights(insight_type);
    CREATE INDEX IF NOT EXISTS idx_predictive_insights_score ON predictive_insights(score DESC);
    CREATE INDEX IF NOT EXISTS idx_community_patterns_category ON community_patterns(category);
    CREATE INDEX IF NOT EXISTS idx_community_patterns_language ON community_patterns(language);
    CREATE INDEX IF NOT EXISTS idx_community_patterns_votes ON community_patterns(votes DESC);
    CREATE INDEX IF NOT EXISTS idx_community_insights_type ON community_insights(insight_type);
    CREATE INDEX IF NOT EXISTS idx_community_insights_severity ON community_insights(severity);
    CREATE INDEX IF NOT EXISTS idx_community_benchmarks_metric ON community_benchmarks(metric);
    CREATE INDEX IF NOT EXISTS idx_decision_outcomes_project ON decision_outcomes(project);
    CREATE INDEX IF NOT EXISTS idx_decision_outcomes_tech ON decision_outcomes(technology);
    CREATE INDEX IF NOT EXISTS idx_repeat_mistake_project ON repeat_mistake_alerts(project);
    CREATE INDEX IF NOT EXISTS idx_repeat_mistake_type ON repeat_mistake_alerts(error_type);
    CREATE INDEX IF NOT EXISTS idx_productivity_project ON productivity_signals(project);
    CREATE INDEX IF NOT EXISTS idx_productivity_type ON productivity_signals(signal_type);
    CREATE INDEX IF NOT EXISTS idx_live_events_project ON live_events(project);
    CREATE INDEX IF NOT EXISTS idx_live_events_type ON live_events(event_type);
    CREATE INDEX IF NOT EXISTS idx_live_events_time ON live_events(created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_watcher_state_active ON watcher_state(active);
    CREATE INDEX IF NOT EXISTS idx_refresh_log_project ON refresh_log(project);

    CREATE INDEX IF NOT EXISTS idx_memory_events_project ON memory_events(project);
    CREATE INDEX IF NOT EXISTS idx_memory_events_type ON memory_events(type);
    CREATE INDEX IF NOT EXISTS idx_memory_events_topic ON memory_events(topic);
    CREATE INDEX IF NOT EXISTS idx_memory_events_branch ON memory_events(branch);
    CREATE INDEX IF NOT EXISTS idx_memory_events_importance ON memory_events(importance DESC);
    CREATE INDEX IF NOT EXISTS idx_memory_events_time ON memory_events(created_at DESC);

    -- Phase 11: Composite indexes for common query patterns
    CREATE INDEX IF NOT EXISTS idx_memory_events_project_type_time ON memory_events(project, type, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_memory_events_project_imp_time ON memory_events(project, importance DESC, created_at DESC);
    CREATE INDEX IF NOT EXISTS idx_memory_events_project_summary_time ON memory_events(project, summary, created_at);
    CREATE INDEX IF NOT EXISTS idx_memory_events_synced ON memory_events(synced);

    CREATE INDEX IF NOT EXISTS idx_memory_archive_project ON memory_archive_refs(project);
    CREATE INDEX IF NOT EXISTS idx_memory_archive_category ON memory_archive_refs(category);

    CREATE INDEX IF NOT EXISTS idx_handoff_project ON handoff_entries(project);
    CREATE INDEX IF NOT EXISTS idx_handoff_status ON handoff_entries(status);
    CREATE INDEX IF NOT EXISTS idx_handoff_time ON handoff_entries(created_at DESC);

    CREATE INDEX IF NOT EXISTS idx_memory_summaries_project ON memory_summaries(project);
    CREATE INDEX IF NOT EXISTS idx_memory_summaries_type ON memory_summaries(summary_type);

    CREATE INDEX IF NOT EXISTS idx_style_profiles_project ON style_profiles(project);

    CREATE INDEX IF NOT EXISTS idx_memory_patterns_project ON memory_patterns(project);
    CREATE INDEX IF NOT EXISTS idx_memory_patterns_category ON memory_patterns(category);
    CREATE INDEX IF NOT EXISTS idx_memory_patterns_importance ON memory_patterns(importance DESC);

    -- Phase 13: Missing architecture tables
    CREATE TABLE IF NOT EXISTS verification_runs (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      build_id TEXT,
      branch TEXT,
      status TEXT NOT NULL,
      tests_total INTEGER DEFAULT 0,
      tests_passed INTEGER DEFAULT 0,
      tests_failed INTEGER DEFAULT 0,
      tests_skipped INTEGER DEFAULT 0,
      duration_ms INTEGER DEFAULT 0,
      coverage REAL,
      ci_platform TEXT,
      commit_hash TEXT,
      commit_message TEXT,
      author TEXT,
      log_snippet TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );
    CREATE INDEX IF NOT EXISTS idx_verification_project ON verification_runs(project);
    CREATE INDEX IF NOT EXISTS idx_verification_status ON verification_runs(status);
    CREATE INDEX IF NOT EXISTS idx_verification_time ON verification_runs(created_at DESC);

    CREATE TABLE IF NOT EXISTS publish_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      version TEXT NOT NULL,
      environment TEXT NOT NULL,
      status TEXT NOT NULL,
      duration_ms INTEGER DEFAULT 0,
      commit_hash TEXT,
      author TEXT,
      notes TEXT,
      created_at TEXT DEFAULT (datetime('now'))
    );
    CREATE INDEX IF NOT EXISTS idx_publish_project ON publish_events(project);
    CREATE INDEX IF NOT EXISTS idx_publish_status ON publish_events(status);

    CREATE TABLE IF NOT EXISTS memory_topics (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      topic TEXT NOT NULL,
      event_count INTEGER DEFAULT 1,
      first_seen TEXT DEFAULT (datetime('now')),
      last_seen TEXT DEFAULT (datetime('now')),
      avg_importance REAL DEFAULT 0,
      files_json TEXT,
      UNIQUE(project, topic)
    );
    CREATE INDEX IF NOT EXISTS idx_memory_topics_project ON memory_topics(project);

    -- Migration tracking
    CREATE TABLE IF NOT EXISTS _migrations (
      version INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      applied_at TEXT DEFAULT (datetime('now'))
    );
  `);
    // Phase 13: FTS5 full-text search (standalone, optional)
    try {
        const hasFts = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='memory_events_fts'").get();
        if (!hasFts) {
            db.exec(`
        CREATE VIRTUAL TABLE memory_events_fts USING fts5(
          summary, topic, details_json, tags_json, files_json
        )
      `);
        }
    }
    catch { /* FTS not available */ }
    // Phase 9: Cloud Sync
    // Migrate memory_events: add columns if missing
    const meCols = db.prepare("PRAGMA table_info(memory_events)").all();
    const meColNames = meCols.map(c => c.name);
    if (!meColNames.includes('synced'))
        db.exec("ALTER TABLE memory_events ADD COLUMN synced INTEGER DEFAULT 0");
    if (!meColNames.includes('occurrence_count'))
        db.exec("ALTER TABLE memory_events ADD COLUMN occurrence_count INTEGER DEFAULT 1");
    if (!meColNames.includes('last_seen_at'))
        db.exec("ALTER TABLE memory_events ADD COLUMN last_seen_at TEXT");
    // Migrate branch_snapshots: add open_risks column
    const bsCols = db.prepare("PRAGMA table_info(branch_snapshots)").all();
    const bsColNames = bsCols.map(c => c.name);
    if (!bsColNames.includes('open_risks'))
        db.exec("ALTER TABLE branch_snapshots ADD COLUMN open_risks TEXT");
}
function backupDatabase() {
    const db = getDb();
    const dbPath = getDbPath();
    const dbDir = path.dirname(dbPath);
    const now = new Date().toISOString().replace(/[:.]/g, '-');
    const backupDir = path.join(dbDir, 'backups');
    if (!fs.existsSync(backupDir))
        fs.mkdirSync(backupDir, { recursive: true });
    const backupPath = path.join(backupDir, `cell-${now}.db`);
    db.backup(backupPath);
    return backupPath;
}
function getDatabaseStats() {
    const db = getDb();
    const tables = db
        .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
        .all();
    const stats = {};
    for (const { name } of tables) {
        try {
            const row = db.prepare(`SELECT COUNT(*) as count FROM "${name}"`).get();
            stats[name] = { rows: row.count };
        }
        catch {
            stats[name] = { rows: 0 };
        }
    }
    stats['db_path'] = getDbPath();
    stats['db_size_bytes'] = fs.statSync(getDbPath()).size;
    return stats;
}
function migrateJsonToSqlite() {
    const db = getDb();
    const stats = {
        patterns: 0, scans: 0, behaviorEvents: 0, journeyEvents: 0,
        skills: 0, collaborators: 0, silos: 0, communitySignals: 0,
        projects: 0, insights: 0, configEntries: 0, userProfiles: 0, failures: 0, total: 0,
    };
    const jsonFiles = {};
    const jsonDir = path.dirname(getDbPath());
    for (const f of fs.readdirSync(jsonDir)) {
        if (f.endsWith('.json') && !f.startsWith('.')) {
            const fp = path.join(jsonDir, f);
            try {
                const parsed = JSON.parse(fs.readFileSync(fp, 'utf-8'));
                jsonFiles[f] = parsed;
            }
            catch { /* skip */ }
        }
    }
    const insertStmt = (sql, params) => {
        try {
            db.prepare(sql).run(...params);
        }
        catch { /* skip duplicates */ }
    };
    // 1. cell.json → patterns
    if (jsonFiles['cell.json'] && jsonFiles['cell.json'].patterns) {
        const cell = jsonFiles['cell.json'];
        const patterns = cell.patterns;
        for (const p of patterns) {
            const patternId = String(p.patternId || p.id || randomUUID());
            const rule = String(p.description || p.rule || '');
            insertStmt(`INSERT OR REPLACE INTO patterns (id, category, subcategory, rule, confidence, source, project, language, file_path, line_number, reuse_count, success_count, failure_count, tags, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [patternId, String(p.category || ''), String(p.subcategory || p.from || ''), rule, Number(p.confidence || p.signals || 0.5), String(p.scope || p.source || 'scan'), '', '', '', 0, Number(p.survivedDays || 0), Number(p.signals || 0), 0, JSON.stringify(p.conditions || []), JSON.stringify(p)]);
            stats.patterns++;
        }
    }
    // 2. onboarding.json → scans
    if (jsonFiles['onboarding.json']) {
        const o = jsonFiles['onboarding.json'];
        insertStmt('INSERT OR IGNORE INTO scans (project, scanned_at, file_count, line_count, stack, patterns, hubs, issues) VALUES (?, datetime(\'now\'), ?, ?, ?, ?, ?, ?)', [o.project || 'global', o.filesScanned || 0, o.totalLines || 0, JSON.stringify(o.stack || {}), JSON.stringify(o.patterns || {}), JSON.stringify(o.hubs || {}), JSON.stringify(o.issues || {})]);
        stats.scans++;
    }
    // 3. intelligence.json → behavior_events
    if (jsonFiles['intelligence.json']) {
        const intel = jsonFiles['intelligence.json'];
        const sources = [
            { key: 'mistakes', type: 'repeat_mistake' },
            { key: 'blindSpots', type: 'blind_spot' },
            { key: 'bugHistory', type: 'bug_fix' },
            { key: 'decisions', type: 'decision' },
        ];
        for (const src of sources) {
            const arr = intel[src.key];
            if (!arr)
                continue;
            for (const item of arr) {
                insertStmt('INSERT OR IGNORE INTO behavior_events (event_type, project, file_path, description, severity, evidence, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', [src.type, item.project || '', item.file || item.filePath || '', item.description || item.detail || item.name || '', item.severity || 'medium', JSON.stringify(item), item.date || item.created_at || new Date().toISOString()]);
                stats.behaviorEvents++;
            }
        }
    }
    // 4. journey.json → journey_events + skills
    if (jsonFiles['journey.json']) {
        const j = jsonFiles['journey.json'];
        if (Array.isArray(j.timeline)) {
            for (const event of j.timeline) {
                insertStmt('INSERT OR IGNORE INTO journey_events (event_type, project, description, metadata, created_at) VALUES (?, ?, ?, ?, ?)', [event.type || 'milestone', event.project || '', event.detail || event.description || '', JSON.stringify(event), event.date || new Date().toISOString()]);
                stats.journeyEvents++;
            }
        }
        const skillsObj = j.skills;
        if (skillsObj) {
            for (const [lang, skill] of Object.entries(skillsObj)) {
                insertStmt('INSERT OR IGNORE INTO skills (language, level, confidence, file_count, line_count, first_seen, last_active, milestones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [lang, skill.level || 'learning', skill.confidence || 0.5, skill.fileCount || 0, skill.lineCount || 0, skill.firstSeen || '', skill.lastActive || '', JSON.stringify(skill.milestones || [])]);
                stats.skills++;
            }
        }
    }
    // 5. insights.json → insights
    if (jsonFiles['insights.json']) {
        const ins = jsonFiles['insights.json'];
        if (ins.level) {
            insertStmt('INSERT OR IGNORE INTO insights (insight_type, level, confidence, evidence, content) VALUES (?, ?, ?, ?, ?)', ['level_assessment', ins.level, ins.confidence || 0.75, JSON.stringify(ins), JSON.stringify(ins)]);
            stats.insights++;
        }
        if (Array.isArray(ins.strengths)) {
            for (const s of ins.strengths) {
                insertStmt('INSERT OR IGNORE INTO insights (insight_type, confidence, evidence, content) VALUES (?, ?, ?, ?)', ['strength', 0.8, JSON.stringify(s), typeof s === 'string' ? s : JSON.stringify(s)]);
                stats.insights++;
            }
        }
        if (Array.isArray(ins.trends)) {
            for (const t of ins.trends) {
                insertStmt('INSERT OR IGNORE INTO insights (insight_type, confidence, evidence, content) VALUES (?, ?, ?, ?)', ['trend', 0.7, JSON.stringify(t), JSON.stringify(t)]);
                stats.insights++;
            }
        }
    }
    // 6. team-intel.json → collaborators
    if (jsonFiles['team-intel.json']) {
        const ti = jsonFiles['team-intel.json'];
        if (Array.isArray(ti.collaborators)) {
            for (const c of ti.collaborators) {
                insertStmt('INSERT OR IGNORE INTO collaborators (name, email, project, commit_count, first_commit, last_commit, skills, collaboration_score) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [c.name || '', c.email || '', Array.isArray(c.projects) ? c.projects[0] : c.project || '', c.commits || c.commitCount || 0, c.firstCommit || '', c.lastCommit || '', JSON.stringify(c.skills || {}), c.collaborationScore || 0]);
                stats.collaborators++;
            }
        }
        if (ti.silos || (ti.summary && ti.summary.silos)) {
            const silosArr = (ti.silos || ti.summary.silos);
            if (silosArr) {
                for (const s of silosArr) {
                    insertStmt('INSERT OR IGNORE INTO silos (name, members, knowledge_area, risk_level, bus_factor) VALUES (?, ?, ?, ?, ?)', [s.name || '', JSON.stringify(s.members || []), s.knowledge_area || s.area || '', s.risk_level || s.busFactor || 'low', s.bus_factor || s.busFactor || 1]);
                    stats.silos++;
                }
            }
        }
    }
    // 7. user-profile.json → user_profile
    if (jsonFiles['user-profile.json']) {
        const up = jsonFiles['user-profile.json'];
        insertStmt('INSERT OR REPLACE INTO user_profile (id, name, products, stack, work_style, preferences) VALUES (1, ?, ?, ?, ?, ?)', [up.name || '', JSON.stringify(up.products || []), JSON.stringify(up.goToStack || up.stack || {}), JSON.stringify(up.work_style || {}), JSON.stringify(up.preferences || {})]);
        stats.userProfiles++;
    }
    // 8. project_dna.json → projects
    if (jsonFiles['project_dna.json']?.projects) {
        const projs = jsonFiles['project_dna.json'].projects;
        for (const [name, p] of Object.entries(projs)) {
            insertStmt('INSERT OR IGNORE INTO projects (name, path, status, tech_stack, file_count, line_count, health_score) VALUES (?, ?, ?, ?, ?, ?, ?)', [name, p.projectPath || '', 'active', JSON.stringify(p.language || {}), p.fileCount || 0, p.totalLines || p.lineCount || 0, 0.5]);
            stats.projects++;
        }
    }
    // 9. community-report.json + community-intelligence.json → community_signals
    for (const fname of ['community-report.json', 'community-intelligence.json']) {
        const data = jsonFiles[fname];
        if (!data)
            continue;
        const trends = data.trends || data.comparisons;
        if (Array.isArray(trends)) {
            for (const t of trends) {
                insertStmt('INSERT OR IGNORE INTO community_signals (pattern_hash, category, language, frequency, trend, percentile, region) VALUES (?, ?, ?, ?, ?, ?, ?)', [t.technology || t.name || '', t.category || '', t.language || t.technology || '', t.users || t.frequency || 1, t.trend || t.adoption || 'stable', t.percentile || t.userScore || 50, 'global']);
                stats.communitySignals++;
            }
        }
    }
    // 10. knowledge-graph.json → graph_entities + graph_relationships
    if (jsonFiles['knowledge-graph.json']) {
        const kg = jsonFiles['knowledge-graph.json'];
        if (Array.isArray(kg.nodes)) {
            for (const n of kg.nodes) {
                try {
                    db.prepare('INSERT OR IGNORE INTO graph_entities (entity_name, entity_type, pattern_id) VALUES (?, ?, ?)').run(n.id || n.name || '', n.type || 'unknown', n.id || null);
                }
                catch { /* skip */ }
            }
        }
        if (Array.isArray(kg.edges)) {
            for (const e of kg.edges) {
                try {
                    db.prepare('INSERT OR IGNORE INTO graph_relationships (from_pattern, to_pattern, rel_type, strength, evidence) VALUES (?, ?, ?, ?, ?)').run(e.from || e.source || '', e.to || e.target || '', e.type || 'related', e.weight || e.strength || 1, JSON.stringify(e));
                }
                catch { /* skip */ }
            }
        }
    }
    // 11. cell-meta.json → config
    if (jsonFiles['cell-meta.json']) {
        for (const [k, v] of Object.entries(jsonFiles['cell-meta.json'])) {
            insertStmt('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', [k, String(v)]);
            stats.configEntries++;
        }
    }
    // 12. privacy-mode.json → config
    if (jsonFiles['privacy-mode.json']) {
        for (const [k, v] of Object.entries(jsonFiles['privacy-mode.json'])) {
            insertStmt('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', ['privacy_' + k, String(v)]);
            stats.configEntries++;
        }
    }
    // 13. org-intelligence.json → silos (if not already from team-intel)
    if (jsonFiles['org-intelligence.json']) {
        const org = jsonFiles['org-intelligence.json'];
        if (Array.isArray(org.silos) && stats.silos === 0) {
            for (const s of org.silos) {
                insertStmt('INSERT OR IGNORE INTO silos (name, members, knowledge_area, risk_level, bus_factor) VALUES (?, ?, ?, ?, ?)', [s.name || '', JSON.stringify(s.members || []), s.knowledge_area || '', s.risk_level || 'low', s.bus_factor || 1]);
                stats.silos++;
            }
        }
    }
    stats.total = stats.patterns + stats.scans + stats.behaviorEvents + stats.journeyEvents
        + stats.skills + stats.collaborators + stats.silos + stats.communitySignals
        + stats.projects + stats.insights + stats.configEntries + stats.userProfiles;
    return stats;
}
function randomUUID() {
    const hex = '0123456789abcdef';
    let uuid = '';
    for (let i = 0; i < 36; i++) {
        if (i === 8 || i === 13 || i === 18 || i === 23)
            uuid += '-';
        else if (i === 14)
            uuid += '4';
        else
            uuid += hex[Math.floor(Math.random() * 16)];
    }
    return uuid;
}
function optimizeDatabase() {
    const db = getDb();
    db.exec('VACUUM');
    db.exec('ANALYZE');
    db.exec('PRAGMA integrity_check');
    return getDatabaseStats();
}
//# sourceMappingURL=database.js.map