#!/usr/bin/env node
import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import H from'sql.js';import {v4}from'uuid';import*as I from'path';import*as y from'fs';import {fileURLToPath}from'url';var J=5,$={score:50,timesMatched:0,timesResolved:0,timesRecurred:0},b=null,O=class{db=null;dbPath;incidentCounter=0;initialized=false;constructor(e){this.dbPath=e||this.getDefaultDbPath();}getDefaultDbPath(){let e=process.env.SENTINEL_DATA_DIR||process.env.PARADIGM_DATA_DIR||I.join(process.cwd(),".paradigm","sentinel");return I.join(e,"sentinel.db")}createSchema(){this.db&&(this.db.run(`
      -- Metadata table for schema versioning
      CREATE TABLE IF NOT EXISTS metadata (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL
      );

      -- Incidents table
      CREATE TABLE IF NOT EXISTS incidents (
        id TEXT PRIMARY KEY,
        timestamp TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'open',
        error_message TEXT NOT NULL,
        error_stack TEXT,
        error_code TEXT,
        error_type TEXT,
        symbols TEXT NOT NULL,
        flow_position TEXT,
        environment TEXT NOT NULL,
        service TEXT,
        version TEXT,
        user_id TEXT,
        request_id TEXT,
        group_id TEXT,
        notes TEXT DEFAULT '[]',
        related_incidents TEXT DEFAULT '[]',
        resolved_at TEXT,
        resolved_by TEXT,
        resolution TEXT,
        created_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      );

      -- Patterns table
      CREATE TABLE IF NOT EXISTS patterns (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        description TEXT,
        pattern TEXT NOT NULL,
        resolution TEXT NOT NULL,
        confidence TEXT NOT NULL,
        source TEXT NOT NULL DEFAULT 'manual',
        private INTEGER NOT NULL DEFAULT 0,
        tags TEXT DEFAULT '[]',
        created_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      );

      -- Incident groups
      CREATE TABLE IF NOT EXISTS groups (
        id TEXT PRIMARY KEY,
        name TEXT,
        common_symbols TEXT,
        common_error_patterns TEXT,
        suggested_pattern_id TEXT,
        first_seen TEXT NOT NULL,
        last_seen TEXT NOT NULL,
        created_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      );

      -- Group members
      CREATE TABLE IF NOT EXISTS group_members (
        group_id TEXT NOT NULL,
        incident_id TEXT NOT NULL,
        added_at TEXT NOT NULL,
        PRIMARY KEY (group_id, incident_id)
      );

      -- Resolutions history
      CREATE TABLE IF NOT EXISTS resolutions (
        id TEXT PRIMARY KEY,
        incident_id TEXT NOT NULL,
        pattern_id TEXT,
        commit_hash TEXT,
        pr_url TEXT,
        notes TEXT,
        resolved_at TEXT NOT NULL,
        recurred INTEGER DEFAULT 0
      );

      -- Practice events (habits system)
      CREATE TABLE IF NOT EXISTS practice_events (
        id TEXT PRIMARY KEY,
        timestamp TEXT NOT NULL,
        habit_id TEXT NOT NULL,
        habit_category TEXT NOT NULL,
        result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
        engineer TEXT NOT NULL,
        session_id TEXT NOT NULL,
        lore_entry_id TEXT,
        task_description TEXT,
        symbols_touched TEXT DEFAULT '[]',
        files_modified TEXT DEFAULT '[]',
        related_incident_id TEXT,
        notes TEXT
      );

      -- Structured logs table
      CREATE TABLE IF NOT EXISTS logs (
        id TEXT PRIMARY KEY,
        timestamp TEXT NOT NULL,
        level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
        symbol TEXT NOT NULL,
        symbol_type TEXT NOT NULL DEFAULT 'raw',
        message TEXT NOT NULL,
        data_json TEXT,
        service TEXT NOT NULL,
        session_id TEXT,
        correlation_id TEXT,
        duration_ms REAL,
        environment TEXT
      );

      -- Service registry
      CREATE TABLE IF NOT EXISTS services (
        name TEXT PRIMARY KEY,
        version TEXT,
        pid INTEGER,
        started_at TEXT NOT NULL,
        last_seen_at TEXT NOT NULL,
        environment TEXT,
        metadata_json TEXT
      );

      -- Live app state snapshots (latest-wins per service+session)
      CREATE TABLE IF NOT EXISTS app_state (
        service TEXT NOT NULL,
        session_id TEXT NOT NULL,
        timestamp TEXT NOT NULL,
        state_json TEXT NOT NULL,
        active_flows_json TEXT,
        active_gates_json TEXT,
        PRIMARY KEY (service, session_id)
      );

      -- Metrics table
      CREATE TABLE IF NOT EXISTS metrics (
        id TEXT PRIMARY KEY,
        timestamp TEXT NOT NULL,
        name TEXT NOT NULL,
        type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
        value REAL NOT NULL,
        tags_json TEXT DEFAULT '{}',
        service TEXT NOT NULL,
        environment TEXT
      );

      -- Traces table
      CREATE TABLE IF NOT EXISTS traces (
        trace_id TEXT NOT NULL,
        span_id TEXT PRIMARY KEY,
        parent_span_id TEXT,
        service TEXT NOT NULL,
        symbol TEXT NOT NULL,
        operation TEXT NOT NULL,
        start_time TEXT NOT NULL,
        end_time TEXT,
        duration_ms REAL,
        status TEXT NOT NULL DEFAULT 'ok',
        tags_json TEXT DEFAULT '{}',
        log_ids_json TEXT DEFAULT '[]'
      );

      -- Indexes
      CREATE INDEX IF NOT EXISTS idx_incidents_timestamp ON incidents(timestamp);
      CREATE INDEX IF NOT EXISTS idx_incidents_status ON incidents(status);
      CREATE INDEX IF NOT EXISTS idx_incidents_environment ON incidents(environment);
      CREATE INDEX IF NOT EXISTS idx_patterns_source ON patterns(source);
      CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
      CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
      CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
      CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
      CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
      CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
      CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
      CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
      CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
      CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
      CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
      CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
      CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
      CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
      CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
      CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
    `),this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', ?)",[String(J)]));}save(){if(!this.db)return;let e=this.db.export(),t=Buffer.from(e);y.writeFileSync(this.dbPath,t);}recordIncident(e){this.db||this.initializeSync(),this.incidentCounter++;let s=`INC-${String(this.incidentCounter).padStart(3,"0")}`,n=new Date().toISOString();return this.db.run(`INSERT INTO incidents (
        id, timestamp, status, error_message, error_stack, error_code, error_type,
        symbols, flow_position, environment, service, version, user_id, request_id,
        group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
        created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s,e.timestamp||n,e.status||"open",e.error.message,e.error.stack||null,e.error.code||null,e.error.type||null,JSON.stringify(e.symbols),e.flowPosition?JSON.stringify(e.flowPosition):null,e.environment,e.service||null,e.version||null,e.userId||null,e.requestId||null,e.groupId||null,"[]","[]",e.resolvedAt||null,e.resolvedBy||null,e.resolution?JSON.stringify(e.resolution):null,n,n]),this.save(),s}initializeSync(){if(!(this.initialized&&this.db)&&!this.db&&b){let e=I.dirname(this.dbPath);if(y.existsSync(e)||y.mkdirSync(e,{recursive:true}),y.existsSync(this.dbPath)){let t=y.readFileSync(this.dbPath);this.db=new b.Database(t);}else this.db=new b.Database,this.createSchema();try{let t=this.db.exec("SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents");t.length>0&&t[0].values.length>0&&t[0].values[0][0]&&(this.incidentCounter=t[0].values[0][0]);}catch{this.incidentCounter=0;}this.migrateSchema(),this.initialized=true,this.save();}}migrateSchema(){if(!this.db)return;let e=1;try{let t=this.db.exec("SELECT value FROM metadata WHERE key = 'schema_version'");t.length>0&&t[0].values.length>0&&(e=parseInt(t[0].values[0][0],10)||1);}catch{}if(e<2){try{this.db.run(`
          CREATE TABLE IF NOT EXISTS practice_events (
            id TEXT PRIMARY KEY,
            timestamp TEXT NOT NULL,
            habit_id TEXT NOT NULL,
            habit_category TEXT NOT NULL,
            result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
            engineer TEXT NOT NULL,
            session_id TEXT NOT NULL,
            lore_entry_id TEXT,
            task_description TEXT,
            symbols_touched TEXT DEFAULT '[]',
            files_modified TEXT DEFAULT '[]',
            related_incident_id TEXT,
            notes TEXT
          );

          CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
          CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
          CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
          CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
        `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '2')"),e=2;}if(e<3){try{this.db.run(`
          CREATE TABLE IF NOT EXISTS logs (
            id TEXT PRIMARY KEY,
            timestamp TEXT NOT NULL,
            level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
            symbol TEXT NOT NULL,
            symbol_type TEXT NOT NULL DEFAULT 'raw',
            message TEXT NOT NULL,
            data_json TEXT,
            service TEXT NOT NULL,
            session_id TEXT,
            correlation_id TEXT,
            duration_ms REAL,
            environment TEXT
          );

          CREATE TABLE IF NOT EXISTS services (
            name TEXT PRIMARY KEY,
            version TEXT,
            pid INTEGER,
            started_at TEXT NOT NULL,
            last_seen_at TEXT NOT NULL,
            environment TEXT,
            metadata_json TEXT
          );

          CREATE TABLE IF NOT EXISTS app_state (
            service TEXT NOT NULL,
            session_id TEXT NOT NULL,
            timestamp TEXT NOT NULL,
            state_json TEXT NOT NULL,
            active_flows_json TEXT,
            active_gates_json TEXT,
            PRIMARY KEY (service, session_id)
          );

          CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
          CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
          CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
          CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
          CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
          CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
        `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '3')"),e=3;}if(e<4){try{this.db.run(`
          CREATE TABLE IF NOT EXISTS metrics (
            id TEXT PRIMARY KEY,
            timestamp TEXT NOT NULL,
            name TEXT NOT NULL,
            type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
            value REAL NOT NULL,
            tags_json TEXT DEFAULT '{}',
            service TEXT NOT NULL,
            environment TEXT
          );

          CREATE TABLE IF NOT EXISTS traces (
            trace_id TEXT NOT NULL,
            span_id TEXT PRIMARY KEY,
            parent_span_id TEXT,
            service TEXT NOT NULL,
            symbol TEXT NOT NULL,
            operation TEXT NOT NULL,
            start_time TEXT NOT NULL,
            end_time TEXT,
            duration_ms REAL,
            status TEXT NOT NULL DEFAULT 'ok',
            tags_json TEXT DEFAULT '{}',
            log_ids_json TEXT DEFAULT '[]'
          );

          CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
          CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
          CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
          CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
          CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
          CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
        `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '4')"),e=4;}if(e<5){try{this.db.run(`
          CREATE TABLE IF NOT EXISTS schemas (
            id TEXT PRIMARY KEY,
            version TEXT NOT NULL,
            name TEXT NOT NULL,
            description TEXT,
            scope_json TEXT NOT NULL,
            event_types_json TEXT NOT NULL,
            causality_json TEXT,
            visualization_json TEXT,
            tags_json TEXT DEFAULT '[]',
            registered_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
          );

          CREATE TABLE IF NOT EXISTS events (
            id TEXT PRIMARY KEY,
            schema_id TEXT NOT NULL,
            event_type TEXT NOT NULL,
            category TEXT NOT NULL,
            timestamp TEXT NOT NULL,
            scope_value TEXT,
            scope_ordinal INTEGER,
            session_id TEXT,
            service TEXT NOT NULL,
            data_json TEXT,
            severity TEXT DEFAULT 'info',
            parent_event_id TEXT,
            depth INTEGER DEFAULT 0
          );

          CREATE INDEX IF NOT EXISTS idx_events_schema ON events(schema_id);
          CREATE INDEX IF NOT EXISTS idx_events_type ON events(event_type);
          CREATE INDEX IF NOT EXISTS idx_events_scope ON events(schema_id, scope_value);
          CREATE INDEX IF NOT EXISTS idx_events_scope_ord ON events(schema_id, scope_ordinal);
          CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
          CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
          CREATE INDEX IF NOT EXISTS idx_events_service ON events(service);
        `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '5')");}}async ensureReady(){b||(b=await H()),this.initializeSync();}getIncident(e){this.initializeSync();let t=this.db.exec("SELECT * FROM incidents WHERE id = ?",[e]);return t.length===0||t[0].values.length===0?null:this.rowToIncident(t[0].columns,t[0].values[0])}getRecentIncidents(e={}){this.initializeSync();let{limit:t=50,offset:s=0}=e,n=[],i=[];e.status&&e.status!=="all"&&(n.push("status = ?"),i.push(e.status)),e.environment&&(n.push("environment = ?"),i.push(e.environment)),e.symbol&&(n.push("symbols LIKE ?"),i.push(`%${e.symbol}%`)),e.search&&(n.push("(error_message LIKE ? OR notes LIKE ?)"),i.push(`%${e.search}%`,`%${e.search}%`)),e.dateFrom&&(n.push("timestamp >= ?"),i.push(e.dateFrom)),e.dateTo&&(n.push("timestamp <= ?"),i.push(e.dateTo)),e.groupId&&(n.push("group_id = ?"),i.push(e.groupId));let r=n.length>0?`WHERE ${n.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM incidents ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...i,t,s]);return a.length===0?[]:a[0].values.map(o=>this.rowToIncident(a[0].columns,o))}updateIncident(e,t){this.initializeSync();let s=new Date().toISOString(),n=["updated_at = ?"],i=[s];t.status!==void 0&&(n.push("status = ?"),i.push(t.status)),t.error!==void 0&&(n.push("error_message = ?"),i.push(t.error.message),t.error.stack!==void 0&&(n.push("error_stack = ?"),i.push(t.error.stack||null))),t.symbols!==void 0&&(n.push("symbols = ?"),i.push(JSON.stringify(t.symbols))),t.flowPosition!==void 0&&(n.push("flow_position = ?"),i.push(t.flowPosition?JSON.stringify(t.flowPosition):null)),t.groupId!==void 0&&(n.push("group_id = ?"),i.push(t.groupId||null)),t.resolvedAt!==void 0&&(n.push("resolved_at = ?"),i.push(t.resolvedAt||null)),t.resolvedBy!==void 0&&(n.push("resolved_by = ?"),i.push(t.resolvedBy||null)),t.resolution!==void 0&&(n.push("resolution = ?"),i.push(t.resolution?JSON.stringify(t.resolution):null)),i.push(e),this.db.run(`UPDATE incidents SET ${n.join(", ")} WHERE id = ?`,i),this.save();}resolveIncident(e,t){this.updateIncident(e,{status:"resolved",resolvedAt:new Date().toISOString()}),t?.notes&&this.addIncidentNote(e,{author:"system",content:t.notes,timestamp:new Date().toISOString()});}addIncidentNote(e,t){this.initializeSync();let s=this.getIncident(e);if(!s)return;let n={id:v4(),...t},i=[...s.notes,n];this.db.run("UPDATE incidents SET notes = ?, updated_at = ? WHERE id = ?",[JSON.stringify(i),new Date().toISOString(),e]),this.save();}linkIncidents(e,t){this.initializeSync();let s=this.getIncident(e);if(!s)return;if(!s.relatedIncidents.includes(t)){let i=[...s.relatedIncidents,t];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(i),new Date().toISOString(),e]);}let n=this.getIncident(t);if(n&&!n.relatedIncidents.includes(e)){let i=[...n.relatedIncidents,e];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(i),new Date().toISOString(),t]);}this.save();}getIncidentCount(e={}){this.initializeSync();let t=[],s=[];e.status&&e.status!=="all"&&(t.push("status = ?"),s.push(e.status)),e.environment&&(t.push("environment = ?"),s.push(e.environment)),e.dateFrom&&(t.push("timestamp >= ?"),s.push(e.dateFrom)),e.dateTo&&(t.push("timestamp <= ?"),s.push(e.dateTo));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT COUNT(*) as count FROM incidents ${n}`,s);return i.length===0||i[0].values.length===0?0:i[0].values[0][0]}addPattern(e){this.initializeSync();let t=new Date().toISOString(),s={...$,...e.confidence};return this.db.run(`INSERT INTO patterns (
        id, name, description, pattern, resolution, confidence,
        source, private, tags, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.id,e.name,e.description||null,JSON.stringify(e.pattern),JSON.stringify(e.resolution),JSON.stringify(s),e.source,e.private?1:0,JSON.stringify(e.tags||[]),t,t]),this.save(),e.id}getPattern(e){this.initializeSync();let t=this.db.exec("SELECT * FROM patterns WHERE id = ?",[e]);return t.length===0||t[0].values.length===0?null:this.rowToPattern(t[0].columns,t[0].values[0])}getAllPatterns(e={}){this.initializeSync();let t=[],s=[];if(e.source&&(t.push("source = ?"),s.push(e.source)),e.minConfidence!==void 0&&(t.push("json_extract(confidence, '$.score') >= ?"),s.push(e.minConfidence)),e.includePrivate||t.push("private = 0"),e.tags&&e.tags.length>0){let r=e.tags.map(()=>"tags LIKE ?");t.push(`(${r.join(" OR ")})`),s.push(...e.tags.map(a=>`%"${a}"%`));}let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT * FROM patterns ${n} ORDER BY json_extract(confidence, '$.score') DESC`,s);return i.length===0?[]:i[0].values.map(r=>this.rowToPattern(i[0].columns,r))}updatePattern(e,t){this.initializeSync();let s=new Date().toISOString(),n=["updated_at = ?"],i=[s];t.name!==void 0&&(n.push("name = ?"),i.push(t.name)),t.description!==void 0&&(n.push("description = ?"),i.push(t.description||null)),t.pattern!==void 0&&(n.push("pattern = ?"),i.push(JSON.stringify(t.pattern))),t.resolution!==void 0&&(n.push("resolution = ?"),i.push(JSON.stringify(t.resolution))),t.confidence!==void 0&&(n.push("confidence = ?"),i.push(JSON.stringify(t.confidence))),t.source!==void 0&&(n.push("source = ?"),i.push(t.source)),t.private!==void 0&&(n.push("private = ?"),i.push(t.private?1:0)),t.tags!==void 0&&(n.push("tags = ?"),i.push(JSON.stringify(t.tags))),i.push(e),this.db.run(`UPDATE patterns SET ${n.join(", ")} WHERE id = ?`,i),this.save();}deletePattern(e){this.initializeSync(),this.db.run("DELETE FROM patterns WHERE id = ?",[e]),this.save();}updatePatternConfidence(e,t){let s=this.getPattern(e);if(!s)return;let n=new Date().toISOString(),i={...s.confidence};switch(t){case "matched":i.timesMatched++,i.lastMatched=n;break;case "resolved":i.timesResolved++,i.lastResolved=n,i.score=Math.min(100,i.score+2);break;case "recurred":i.timesRecurred++,i.score=Math.max(10,i.score-5);break}this.updatePattern(e,{confidence:i});}createGroup(e){this.initializeSync();let t=`GRP-${v4().substring(0,8)}`,s=new Date().toISOString();this.db.run(`INSERT INTO groups (
        id, name, common_symbols, common_error_patterns,
        suggested_pattern_id, first_seen, last_seen, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.name||null,JSON.stringify(e.commonSymbols),JSON.stringify(e.commonErrorPatterns),e.suggestedPattern?.id||null,e.firstSeen,e.lastSeen,s,s]);for(let n of e.incidents)this.addToGroup(t,n);return this.save(),t}getGroup(e){this.initializeSync();let t=this.db.exec("SELECT * FROM groups WHERE id = ?",[e]);return t.length===0||t[0].values.length===0?null:this.rowToGroup(t[0].columns,t[0].values[0])}getGroups(e={}){this.initializeSync();let t=e.limit||100,s=this.db.exec("SELECT * FROM groups ORDER BY last_seen DESC LIMIT ?",[t]);return s.length===0?[]:s[0].values.map(n=>this.rowToGroup(s[0].columns,n))}addToGroup(e,t){this.initializeSync();let s=new Date().toISOString();this.db.run("INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",[e,t,s]),this.db.run("UPDATE incidents SET group_id = ? WHERE id = ?",[e,t]),this.db.run("UPDATE groups SET last_seen = ?, updated_at = ? WHERE id = ?",[s,s,e]),this.save();}recordResolution(e){this.initializeSync();let t=v4(),s=new Date().toISOString();this.db.run(`INSERT INTO resolutions (id, incident_id, pattern_id, commit_hash, pr_url, notes, resolved_at)
      VALUES (?, ?, ?, ?, ?, ?, ?)`,[t,e.incidentId,e.patternId||null,e.commitHash||null,e.prUrl||null,e.notes||null,s]),this.updateIncident(e.incidentId,{status:"resolved",resolvedAt:s,resolvedBy:e.patternId||"manual",resolution:{patternId:e.patternId,commitHash:e.commitHash,prUrl:e.prUrl,notes:e.notes}}),e.patternId&&this.updatePatternConfidence(e.patternId,"resolved"),this.save();}markRecurred(e){this.initializeSync(),this.db.run("UPDATE resolutions SET recurred = 1 WHERE incident_id = ?",[e]);let t=this.db.exec("SELECT pattern_id FROM resolutions WHERE incident_id = ?",[e]);t.length>0&&t[0].values.length>0&&t[0].values[0][0]&&this.updatePatternConfidence(t[0].values[0][0],"recurred"),this.save();}getResolutionHistory(e={}){this.initializeSync();let t=[],s=[];e.patternId&&(t.push("pattern_id = ?"),s.push(e.patternId)),e.symbol&&(t.push(`incident_id IN (
        SELECT id FROM incidents WHERE symbols LIKE ?
      )`),s.push(`%${e.symbol}%`));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=e.limit||100,r=this.db.exec(`SELECT * FROM resolutions ${n} ORDER BY resolved_at DESC LIMIT ?`,[...s,i]);if(r.length===0)return [];let a=r[0].columns;return r[0].values.map(o=>{let c={};return a.forEach((l,d)=>{c[l]=o[d];}),{id:c.id,incidentId:c.incident_id,patternId:c.pattern_id||void 0,commitHash:c.commit_hash||void 0,prUrl:c.pr_url||void 0,notes:c.notes||void 0,resolvedAt:c.resolved_at,recurred:c.recurred===1}})}getStats(e){this.initializeSync();let{start:t,end:s}=e,n=this.getIncidentCount({dateFrom:t,dateTo:s}),i=this.getIncidentCount({dateFrom:t,dateTo:s,status:"open"}),r=this.getIncidentCount({dateFrom:t,dateTo:s,status:"resolved"}),a=this.db.exec(`SELECT environment, COUNT(*) as count
      FROM incidents
      WHERE timestamp >= ? AND timestamp <= ?
      GROUP BY environment`,[t,s]),o={};if(a.length>0)for(let u of a[0].values)o[u[0]]=u[1];let c=this.db.exec(`SELECT DATE(timestamp) as date, COUNT(*) as count
      FROM incidents
      WHERE timestamp >= ? AND timestamp <= ?
      GROUP BY DATE(timestamp)
      ORDER BY date`,[t,s]),l=[];if(c.length>0)for(let u of c[0].values)l.push({date:u[0],count:u[1]});let d=this.getAllPatterns({includePrivate:true}),m=d.length>0?d.reduce((u,T)=>u+T.confidence.score,0)/d.length:0,g=d.sort((u,T)=>T.confidence.timesResolved-u.confidence.timesResolved).slice(0,5).map(u=>({patternId:u.id,resolvedCount:u.confidence.timesResolved})),p=d.filter(u=>u.confidence.timesMatched>0).map(u=>({patternId:u.id,recurrenceRate:u.confidence.timesRecurred/Math.max(1,u.confidence.timesResolved)})).sort((u,T)=>T.recurrenceRate-u.recurrenceRate).slice(0,5),E=new Map,S=this.getRecentIncidents({dateFrom:t,dateTo:s,limit:1e3});for(let u of S)for(let[,T]of Object.entries(u.symbols))T&&E.set(T,(E.get(T)||0)+1);let v=Array.from(E.entries()).sort((u,T)=>T[1]-u[1]).slice(0,10).map(([u,T])=>({symbol:u,count:T})),P=this.getResolutionHistory({limit:1e3}).filter(u=>u.resolvedAt>=t&&u.resolvedAt<=s),D=P.filter(u=>u.patternId).length,j=P.length-D;return {period:{start:t,end:s},incidents:{total:n,open:i,resolved:r,byEnvironment:o,byDay:l},patterns:{total:d.length,avgConfidence:Math.round(m),mostEffective:g,leastEffective:p},symbols:{mostIncidents:v,mostResolved:[],hotspots:v.slice(0,5).map(u=>({symbol:u.symbol,incidentRate:u.count/Math.max(1,n)}))},resolution:{avgTimeToResolve:0,resolvedWithPattern:D,resolvedManually:j,resolutionRate:n>0?r/n*100:0}}}getSymbolHealth(e){let t=this.getRecentIncidents({symbol:e,limit:1e3}),s=t.length,n=new Map;for(let r of t)if(r.resolution?.patternId){let a=n.get(r.resolution.patternId)||0;n.set(r.resolution.patternId,a+1);}let i=Array.from(n.entries()).sort((r,a)=>a[1]-r[1]).slice(0,5).map(([r,a])=>({patternId:r,count:a}));return {incidentCount:s,avgTimeToResolve:0,topPatterns:i}}exportPatterns(e={}){let t=this.getAllPatterns({includePrivate:e.includePrivate});return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:t}}importPatterns(e,t={}){let s=0,n=0;for(let i of e.patterns){let r=this.getPattern(i.id);if(r&&!t.overwrite){n++;continue}r?this.updatePattern(i.id,i):this.addPattern({...i,source:"imported"}),s++;}return {imported:s,skipped:n}}exportBackup(){let e=this.getRecentIncidents({limit:1e5}),t=this.getAllPatterns({includePrivate:true}),s=this.getGroups({limit:1e4});return {version:"1.0.0",exportedAt:new Date().toISOString(),incidents:e,patterns:t,groups:s}}importBackup(e){this.initializeSync(),this.db.run("DELETE FROM group_members"),this.db.run("DELETE FROM resolutions"),this.db.run("DELETE FROM groups"),this.db.run("DELETE FROM incidents"),this.db.run("DELETE FROM patterns");for(let n of e.patterns)this.addPattern(n);for(let n of e.incidents){let i=n.timestamp;this.db.run(`INSERT INTO incidents (
          id, timestamp, status, error_message, error_stack, error_code, error_type,
          symbols, flow_position, environment, service, version, user_id, request_id,
          group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
          created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.timestamp,n.status,n.error.message,n.error.stack||null,n.error.code||null,n.error.type||null,JSON.stringify(n.symbols),n.flowPosition?JSON.stringify(n.flowPosition):null,n.environment,n.service||null,n.version||null,n.userId||null,n.requestId||null,n.groupId||null,JSON.stringify(n.notes),JSON.stringify(n.relatedIncidents),n.resolvedAt||null,n.resolvedBy||null,n.resolution?JSON.stringify(n.resolution):null,i,i]);}let t=this.db.exec("SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents");t.length>0&&t[0].values.length>0&&t[0].values[0][0]&&(this.incidentCounter=t[0].values[0][0]);let s=new Date().toISOString();for(let n of e.groups){this.db.run(`INSERT INTO groups (
          id, name, common_symbols, common_error_patterns,
          suggested_pattern_id, first_seen, last_seen, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.name||null,JSON.stringify(n.commonSymbols),JSON.stringify(n.commonErrorPatterns),n.suggestedPattern?.id||null,n.firstSeen,n.lastSeen,s,s]);for(let i of n.incidents)this.db.run("INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",[n.id,i,s]);}this.save();}rowToIncident(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,timestamp:s.timestamp,status:s.status,error:{message:s.error_message,stack:s.error_stack||void 0,code:s.error_code||void 0,type:s.error_type||void 0},symbols:JSON.parse(s.symbols||"{}"),flowPosition:s.flow_position?JSON.parse(s.flow_position):void 0,environment:s.environment,service:s.service||void 0,version:s.version||void 0,userId:s.user_id||void 0,requestId:s.request_id||void 0,groupId:s.group_id||void 0,notes:JSON.parse(s.notes||"[]"),relatedIncidents:JSON.parse(s.related_incidents||"[]"),resolvedAt:s.resolved_at||void 0,resolvedBy:s.resolved_by||void 0,resolution:s.resolution?JSON.parse(s.resolution):void 0}}rowToPattern(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,name:s.name,description:s.description||"",pattern:JSON.parse(s.pattern),resolution:JSON.parse(s.resolution),confidence:JSON.parse(s.confidence),source:s.source,private:s.private===1,tags:JSON.parse(s.tags||"[]"),createdAt:s.created_at,updatedAt:s.updated_at}}rowToGroup(e,t){let s={};e.forEach((o,c)=>{s[o]=t[c];});let n=this.db.exec("SELECT incident_id FROM group_members WHERE group_id = ?",[s.id]),i=[];if(n.length>0)for(let o of n[0].values)i.push(o[0]);let r=this.db.exec(`SELECT DISTINCT environment FROM incidents
      WHERE id IN (SELECT incident_id FROM group_members WHERE group_id = ?)`,[s.id]),a=[];if(r.length>0)for(let o of r[0].values)a.push(o[0]);return {id:s.id,name:s.name||void 0,incidents:i,commonSymbols:JSON.parse(s.common_symbols||"{}"),commonErrorPatterns:JSON.parse(s.common_error_patterns||"[]"),count:i.length,firstSeen:s.first_seen,lastSeen:s.last_seen,environments:a,suggestedPattern:s.suggested_pattern_id&&this.getPattern(s.suggested_pattern_id)||void 0}}recordPracticeEvent(e){this.initializeSync();let t=`PE-${v4().substring(0,8)}`,s=new Date().toISOString();return this.db.run(`INSERT INTO practice_events (
        id, timestamp, habit_id, habit_category, result,
        engineer, session_id, lore_entry_id, task_description,
        symbols_touched, files_modified, related_incident_id, notes
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,s,e.habitId,e.habitCategory,e.result,e.engineer,e.sessionId,e.loreEntryId||null,e.taskDescription||null,JSON.stringify(e.symbolsTouched||[]),JSON.stringify(e.filesModified||[]),e.relatedIncidentId||null,e.notes||null]),this.save(),t}getPracticeEvents(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,n=[],i=[];e.habitId&&(n.push("habit_id = ?"),i.push(e.habitId)),e.habitCategory&&(n.push("habit_category = ?"),i.push(e.habitCategory)),e.result&&(n.push("result = ?"),i.push(e.result)),e.engineer&&(n.push("engineer = ?"),i.push(e.engineer)),e.sessionId&&(n.push("session_id = ?"),i.push(e.sessionId)),e.dateFrom&&(n.push("timestamp >= ?"),i.push(e.dateFrom)),e.dateTo&&(n.push("timestamp <= ?"),i.push(e.dateTo));let r=n.length>0?`WHERE ${n.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM practice_events ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...i,t,s]);return a.length===0?[]:a[0].values.map(o=>this.rowToPracticeEvent(a[0].columns,o))}getPracticeEventCount(e={}){this.initializeSync();let t=[],s=[];e.habitId&&(t.push("habit_id = ?"),s.push(e.habitId)),e.habitCategory&&(t.push("habit_category = ?"),s.push(e.habitCategory)),e.result&&(t.push("result = ?"),s.push(e.result)),e.engineer&&(t.push("engineer = ?"),s.push(e.engineer)),e.dateFrom&&(t.push("timestamp >= ?"),s.push(e.dateFrom)),e.dateTo&&(t.push("timestamp <= ?"),s.push(e.dateTo));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT COUNT(*) as count FROM practice_events ${n}`,s);return i.length===0||i[0].values.length===0?0:i[0].values[0][0]}getComplianceRate(e={}){this.initializeSync();let t=[],s=[];e.habitId&&(t.push("habit_id = ?"),s.push(e.habitId)),e.habitCategory&&(t.push("habit_category = ?"),s.push(e.habitCategory)),e.engineer&&(t.push("engineer = ?"),s.push(e.engineer)),e.dateFrom&&(t.push("timestamp >= ?"),s.push(e.dateFrom)),e.dateTo&&(t.push("timestamp <= ?"),s.push(e.dateTo));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT result, COUNT(*) as count
       FROM practice_events ${n}
       GROUP BY result`,s),r=0,a=0,o=0;if(i.length>0)for(let d of i[0].values){let m=d[0],g=d[1];m==="followed"?r=g:m==="skipped"?a=g:m==="partial"&&(o=g);}let c=r+a+o,l=c>0?(r+o*.5)/c*100:100;return {total:c,followed:r,skipped:a,partial:o,rate:Math.round(l)}}rowToPracticeEvent(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,timestamp:s.timestamp,habitId:s.habit_id,habitCategory:s.habit_category,result:s.result,engineer:s.engineer,sessionId:s.session_id,loreEntryId:s.lore_entry_id||void 0,taskDescription:s.task_description||void 0,symbolsTouched:JSON.parse(s.symbols_touched||"[]"),filesModified:JSON.parse(s.files_modified||"[]"),relatedIncidentId:s.related_incident_id||void 0,notes:s.notes||void 0}}inferSymbolType(e){return e.startsWith("#")?"component":e.startsWith("^")?"gate":e.startsWith("!")?"signal":e.startsWith("$")?"flow":e.startsWith("~")?"aspect":"raw"}insertLog(e){this.initializeSync();let t=e.id||v4(),s=e.timestamp||new Date().toISOString(),n=e.symbolType||this.inferSymbolType(e.symbol);return this.db.run(`INSERT INTO logs (
        id, timestamp, level, symbol, symbol_type, message, data_json,
        service, session_id, correlation_id, duration_ms, environment
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,s,e.level,e.symbol,n,e.message,e.data?JSON.stringify(e.data):null,e.service,e.sessionId||null,e.correlationId||null,e.durationMs??null,e.environment||null]),this.save(),t}insertLogBatch(e){this.initializeSync();let t=0,s=[];for(let n of e)try{let i=n.id||v4(),r=n.timestamp||new Date().toISOString(),a=n.symbolType||this.inferSymbolType(n.symbol);this.db.run(`INSERT INTO logs (
            id, timestamp, level, symbol, symbol_type, message, data_json,
            service, session_id, correlation_id, duration_ms, environment
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,r,n.level,n.symbol,a,n.message,n.data?JSON.stringify(n.data):null,n.service,n.sessionId||null,n.correlationId||null,n.durationMs??null,n.environment||null]),t++;}catch(i){s.push(i instanceof Error?i.message:String(i));}return this.save(),{accepted:t,errors:s}}queryLogs(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,n=[],i=[];e.level&&(n.push("level = ?"),i.push(e.level)),e.symbol&&(n.push("symbol LIKE ?"),i.push(`%${e.symbol}%`)),e.service&&(n.push("service = ?"),i.push(e.service)),e.sessionId&&(n.push("session_id = ?"),i.push(e.sessionId)),e.correlationId&&(n.push("correlation_id = ?"),i.push(e.correlationId)),e.search&&(n.push("message LIKE ?"),i.push(`%${e.search}%`)),e.since&&(n.push("timestamp >= ?"),i.push(e.since)),e.until&&(n.push("timestamp <= ?"),i.push(e.until));let r=n.length>0?`WHERE ${n.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM logs ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...i,t,s]);return a.length===0?[]:a[0].values.map(o=>this.rowToLogEntry(a[0].columns,o))}getLogCount(e={}){this.initializeSync();let t=[],s=[];e.level&&(t.push("level = ?"),s.push(e.level)),e.symbol&&(t.push("symbol LIKE ?"),s.push(`%${e.symbol}%`)),e.service&&(t.push("service = ?"),s.push(e.service)),e.since&&(t.push("timestamp >= ?"),s.push(e.since)),e.until&&(t.push("timestamp <= ?"),s.push(e.until));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT COUNT(*) as count FROM logs ${n}`,s);return i.length===0||i[0].values.length===0?0:i[0].values[0][0]}pruneLogs(e){if(this.initializeSync(),e<=0)return 0;let t=this.getLogCount();if(t<=e)return 0;let s=t-e;return this.db.run(`DELETE FROM logs WHERE id IN (
        SELECT id FROM logs ORDER BY timestamp ASC LIMIT ?
      )`,[s]),this.save(),s}rowToLogEntry(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,timestamp:s.timestamp,level:s.level,symbol:s.symbol,symbolType:s.symbol_type||"raw",message:s.message,data:s.data_json?JSON.parse(s.data_json):void 0,service:s.service,sessionId:s.session_id||void 0,correlationId:s.correlation_id||void 0,durationMs:s.duration_ms||void 0,environment:s.environment||void 0}}registerService(e){this.initializeSync();let t=new Date().toISOString();this.db.run(`INSERT INTO services (name, version, pid, started_at, last_seen_at, environment, metadata_json)
       VALUES (?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(name) DO UPDATE SET
         version = excluded.version,
         pid = excluded.pid,
         last_seen_at = excluded.last_seen_at,
         environment = excluded.environment,
         metadata_json = excluded.metadata_json`,[e.name,e.version||null,e.pid??null,t,t,e.environment||null,e.metadata?JSON.stringify(e.metadata):null]),this.save();}updateServiceLastSeen(e){this.initializeSync();let t=new Date().toISOString();this.db.run("UPDATE services SET last_seen_at = ? WHERE name = ?",[t,e]),this.save();}getServices(){this.initializeSync();let e=this.db.exec("SELECT * FROM services ORDER BY last_seen_at DESC");return e.length===0?[]:e[0].values.map(t=>{let s={};return e[0].columns.forEach((n,i)=>{s[n]=t[i];}),{name:s.name,version:s.version||void 0,pid:s.pid||void 0,startedAt:s.started_at,lastSeenAt:s.last_seen_at,environment:s.environment||void 0,metadata:s.metadata_json?JSON.parse(s.metadata_json):void 0}})}upsertAppState(e){this.initializeSync(),this.db.run(`INSERT INTO app_state (service, session_id, timestamp, state_json, active_flows_json, active_gates_json)
       VALUES (?, ?, ?, ?, ?, ?)
       ON CONFLICT(service, session_id) DO UPDATE SET
         timestamp = excluded.timestamp,
         state_json = excluded.state_json,
         active_flows_json = excluded.active_flows_json,
         active_gates_json = excluded.active_gates_json`,[e.service,e.sessionId,e.timestamp||new Date().toISOString(),JSON.stringify(e.state),e.activeFlows?JSON.stringify(e.activeFlows):null,e.activeGates?JSON.stringify(e.activeGates):null]),this.save();}getAppState(e,t){this.initializeSync();let s="SELECT * FROM app_state WHERE service = ?",n=[e];t&&(s+=" AND session_id = ?",n.push(t)),s+=" ORDER BY timestamp DESC";let i=this.db.exec(s,n);return i.length===0?[]:i[0].values.map(r=>this.rowToAppState(i[0].columns,r))}getAllAppStates(){this.initializeSync();let e=this.db.exec("SELECT * FROM app_state ORDER BY timestamp DESC");return e.length===0?[]:e[0].values.map(t=>this.rowToAppState(e[0].columns,t))}rowToAppState(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{service:s.service,sessionId:s.session_id,timestamp:s.timestamp,state:JSON.parse(s.state_json),activeFlows:s.active_flows_json?JSON.parse(s.active_flows_json):void 0,activeGates:s.active_gates_json?JSON.parse(s.active_gates_json):void 0}}insertMetric(e){this.initializeSync();let t=v4(),s=e.timestamp||new Date().toISOString();return this.db.run(`INSERT INTO metrics (
        id, timestamp, name, type, value, tags_json, service, environment
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[t,s,e.name,e.type,e.value,JSON.stringify(e.tags||{}),e.service,e.environment||null]),this.save(),t}insertMetricBatch(e){this.initializeSync();let t=0,s=[];for(let n of e)try{let i=v4(),r=n.timestamp||new Date().toISOString();this.db.run(`INSERT INTO metrics (
            id, timestamp, name, type, value, tags_json, service, environment
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[i,r,n.name,n.type,n.value,JSON.stringify(n.tags||{}),n.service,n.environment||null]),t++;}catch(i){s.push(i instanceof Error?i.message:String(i));}return this.save(),{accepted:t,errors:s}}queryMetrics(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,n=[],i=[];if(e.name&&(n.push("name = ?"),i.push(e.name)),e.type&&(n.push("type = ?"),i.push(e.type)),e.service&&(n.push("service = ?"),i.push(e.service)),e.tag){let o=e.tag.indexOf("=");if(o>0){let c=e.tag.substring(0,o),l=e.tag.substring(o+1);n.push("tags_json LIKE ?"),i.push(`%"${c}":"${l}"%`);}}e.since&&(n.push("timestamp >= ?"),i.push(e.since)),e.until&&(n.push("timestamp <= ?"),i.push(e.until));let r=n.length>0?`WHERE ${n.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM metrics ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...i,t,s]);return a.length===0?[]:a[0].values.map(o=>this.rowToMetricEntry(a[0].columns,o))}getMetricCount(e={}){this.initializeSync();let t=[],s=[];if(e.name&&(t.push("name = ?"),s.push(e.name)),e.type&&(t.push("type = ?"),s.push(e.type)),e.service&&(t.push("service = ?"),s.push(e.service)),e.tag){let r=e.tag.indexOf("=");if(r>0){let a=e.tag.substring(0,r),o=e.tag.substring(r+1);t.push("tags_json LIKE ?"),s.push(`%"${a}":"${o}"%`);}}e.since&&(t.push("timestamp >= ?"),s.push(e.since)),e.until&&(t.push("timestamp <= ?"),s.push(e.until));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT COUNT(*) as count FROM metrics ${n}`,s);return i.length===0||i[0].values.length===0?0:i[0].values[0][0]}aggregateMetric(e,t){this.initializeSync();let s=["name = ?"],n=[e];t?.service&&(s.push("service = ?"),n.push(t.service)),t?.since&&(s.push("timestamp >= ?"),n.push(t.since)),t?.until&&(s.push("timestamp <= ?"),n.push(t.until));let i=`WHERE ${s.join(" AND ")}`,r=this.db.exec(`SELECT COUNT(*) as count, SUM(value) as sum, MIN(value) as min, MAX(value) as max, AVG(value) as avg
       FROM metrics ${i}`,n);if(r.length===0||r[0].values.length===0)return {name:e,count:0,sum:0,min:0,max:0,avg:0};let a=r[0].values[0];return {name:e,count:a[0]||0,sum:a[1]||0,min:a[2]||0,max:a[3]||0,avg:a[4]||0}}pruneMetrics(e){if(this.initializeSync(),e<=0)return 0;let t=this.getMetricCount();if(t<=e)return 0;let s=t-e;return this.db.run(`DELETE FROM metrics WHERE id IN (
        SELECT id FROM metrics ORDER BY timestamp ASC LIMIT ?
      )`,[s]),this.save(),s}rowToMetricEntry(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,timestamp:s.timestamp,name:s.name,type:s.type,value:s.value,tags:s.tags_json?JSON.parse(s.tags_json):{},service:s.service,environment:s.environment||void 0}}insertSpan(e){this.initializeSync();let t=e.spanId||v4(),s=e.startTime||new Date().toISOString();return this.db.run(`INSERT INTO traces (
        trace_id, span_id, parent_span_id, service, symbol, operation,
        start_time, end_time, duration_ms, status, tags_json, log_ids_json
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.traceId,t,e.parentSpanId||null,e.service,e.symbol,e.operation,s,e.endTime||null,e.durationMs??null,e.status||"ok",JSON.stringify(e.tags||{}),JSON.stringify(e.logIds||[])]),this.save(),t}getTrace(e){this.initializeSync();let t=this.db.exec("SELECT * FROM traces WHERE trace_id = ? ORDER BY start_time ASC",[e]);if(t.length===0||t[0].values.length===0)return null;let s=t[0].values.map(m=>this.rowToTraceSpan(t[0].columns,m)),n=[...new Set(s.map(m=>m.service))],i=s.map(m=>m.startTime),r=s.filter(m=>m.endTime).map(m=>m.endTime),a=i.sort()[0],o=r.length>0?r.sort().reverse()[0]:a,c=new Date(a).getTime(),d=new Date(o).getTime()-c;return {traceId:e,spans:s,services:n,totalDurationMs:d>0?d:0,startTime:a,endTime:o}}queryTraces(e={}){this.initializeSync();let t=[],s=[];e.service&&(t.push("service = ?"),s.push(e.service)),e.symbol&&(t.push("symbol = ?"),s.push(e.symbol)),e.since&&(t.push("start_time >= ?"),s.push(e.since));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=Math.min(e.limit||20,20),r=this.db.exec(`SELECT DISTINCT trace_id FROM traces ${n} ORDER BY start_time DESC LIMIT ?`,[...s,i]);if(r.length===0)return [];let a=[];for(let o of r[0].values){let c=o[0],l=this.getTrace(c);l&&a.push(l);}return a}rowToTraceSpan(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{traceId:s.trace_id,spanId:s.span_id,parentSpanId:s.parent_span_id||void 0,service:s.service,symbol:s.symbol,operation:s.operation,startTime:s.start_time,endTime:s.end_time||void 0,durationMs:s.duration_ms||void 0,status:s.status||"ok",tags:s.tags_json?JSON.parse(s.tags_json):{},logs:s.log_ids_json?JSON.parse(s.log_ids_json):[]}}registerSchema(e){this.initializeSync();let t=new Date().toISOString();return this.db.run(`INSERT INTO schemas (
        id, version, name, description, scope_json, event_types_json,
        causality_json, visualization_json, tags_json, registered_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(id) DO UPDATE SET
         version = excluded.version,
         name = excluded.name,
         description = excluded.description,
         scope_json = excluded.scope_json,
         event_types_json = excluded.event_types_json,
         causality_json = excluded.causality_json,
         visualization_json = excluded.visualization_json,
         tags_json = excluded.tags_json,
         updated_at = excluded.updated_at`,[e.id,e.version,e.name,e.description||null,JSON.stringify(e.scope),JSON.stringify(e.eventTypes),e.causality?JSON.stringify(e.causality):null,e.visualization?JSON.stringify(e.visualization):null,JSON.stringify(e.tags||[]),t,t]),this.save(),{id:e.id,version:e.version,name:e.name,description:e.description,scope:e.scope,eventTypes:e.eventTypes,causality:e.causality,visualization:e.visualization,tags:e.tags||[],registeredAt:t,updatedAt:t}}getSchema(e){this.initializeSync();let t=this.db.exec("SELECT * FROM schemas WHERE id = ?",[e]);return t.length===0||t[0].values.length===0?null:this.rowToSchema(t[0].columns,t[0].values[0])}listSchemas(){this.initializeSync();let e=this.db.exec("SELECT * FROM schemas ORDER BY name ASC");return e.length===0?[]:e[0].values.map(t=>this.rowToSchema(e[0].columns,t))}rowToSchema(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,version:s.version,name:s.name,description:s.description||void 0,scope:JSON.parse(s.scope_json),eventTypes:JSON.parse(s.event_types_json),causality:s.causality_json?JSON.parse(s.causality_json):void 0,visualization:s.visualization_json?JSON.parse(s.visualization_json):void 0,tags:JSON.parse(s.tags_json||"[]"),registeredAt:s.registered_at,updatedAt:s.updated_at}}insertEventBatch(e,t,s){this.initializeSync();let n=this.getSchema(e),i=new Map;if(n)for(let o of n.eventTypes)i.set(o.type,{category:o.category,severity:o.severity||"info"});let r=0,a=[];for(let o of s)try{let c=o.id||v4(),l=o.timestamp||new Date().toISOString(),d=i.get(o.type),m=d?.category||"unknown",g=o.severity||d?.severity||"info",p=o.scopeValue!=null?String(o.scopeValue):null,E=typeof o.scopeValue=="number"?o.scopeValue:null;this.db.run(`INSERT INTO events (
            id, schema_id, event_type, category, timestamp, scope_value,
            scope_ordinal, session_id, service, data_json, severity,
            parent_event_id, depth
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[c,e,o.type,m,l,p,E,o.sessionId||null,t,o.data?JSON.stringify(o.data):null,g,o.parentEventId||null,o.depth??0]),r++;}catch(c){a.push(c instanceof Error?c.message:String(c));}return this.save(),{accepted:r,errors:a}}queryEvents(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,n=[],i=[];e.schemaId&&(n.push("schema_id = ?"),i.push(e.schemaId)),e.eventType&&(n.push("event_type = ?"),i.push(e.eventType)),e.category&&(n.push("category = ?"),i.push(e.category)),e.service&&(n.push("service = ?"),i.push(e.service)),e.sessionId&&(n.push("session_id = ?"),i.push(e.sessionId)),e.scopeValue&&(n.push("scope_value = ?"),i.push(e.scopeValue)),e.scopeFrom&&(n.push("scope_value >= ?"),i.push(e.scopeFrom)),e.scopeTo&&(n.push("scope_value <= ?"),i.push(e.scopeTo)),e.severity&&(n.push("severity = ?"),i.push(e.severity)),e.since&&(n.push("timestamp >= ?"),i.push(e.since)),e.until&&(n.push("timestamp <= ?"),i.push(e.until)),e.search&&(n.push("data_json LIKE ?"),i.push(`%${e.search}%`));let r=n.length>0?`WHERE ${n.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM events ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...i,t,s]);return a.length===0?[]:a[0].values.map(o=>this.rowToGenericEvent(a[0].columns,o))}queryEventsByScope(e,t){this.initializeSync();let s=this.db.exec(`SELECT * FROM events
       WHERE schema_id = ? AND scope_value = ?
       ORDER BY timestamp ASC`,[e,t]);return s.length===0?[]:s[0].values.map(n=>this.rowToGenericEvent(s[0].columns,n))}getEventScopes(e,t={}){this.initializeSync();let{limit:s=100,offset:n=0}=t,i=["schema_id = ?"],r=[e];t.sessionId&&(i.push("session_id = ?"),r.push(t.sessionId));let a=`WHERE ${i.join(" AND ")}`,o=this.db.exec(`SELECT
        scope_value,
        MIN(scope_ordinal) as scope_ordinal,
        COUNT(*) as event_count,
        MIN(timestamp) as first_timestamp,
        MAX(timestamp) as last_timestamp
       FROM events
       ${a}
       AND scope_value IS NOT NULL
       GROUP BY scope_value
       ORDER BY MIN(COALESCE(scope_ordinal, 0)) DESC, MIN(timestamp) DESC
       LIMIT ? OFFSET ?`,[...r,s,n]);if(o.length===0)return [];let c=[];for(let l of o[0].values){let d=l[0],m=l[1]!=null?l[1]:void 0,g=l[2],p=l[3],E=l[4],S=this.db.exec(`SELECT category, COUNT(*) as count FROM events
         WHERE schema_id = ? AND scope_value = ?
         GROUP BY category`,[e,d]),v={};if(S.length>0)for(let A of S[0].values)v[A[0]]=A[1];c.push({scopeValue:d,scopeOrdinal:m,eventCount:g,categories:v,firstTimestamp:p,lastTimestamp:E});}return c}getEventCount(e={}){this.initializeSync();let t=[],s=[];e.schemaId&&(t.push("schema_id = ?"),s.push(e.schemaId)),e.eventType&&(t.push("event_type = ?"),s.push(e.eventType)),e.service&&(t.push("service = ?"),s.push(e.service)),e.since&&(t.push("timestamp >= ?"),s.push(e.since)),e.until&&(t.push("timestamp <= ?"),s.push(e.until));let n=t.length>0?`WHERE ${t.join(" AND ")}`:"",i=this.db.exec(`SELECT COUNT(*) as count FROM events ${n}`,s);return i.length===0||i[0].values.length===0?0:i[0].values[0][0]}pruneEvents(e){if(this.initializeSync(),e<=0)return 0;let t=this.getEventCount();if(t<=e)return 0;let s=t-e;return this.db.run(`DELETE FROM events WHERE id IN (
        SELECT id FROM events ORDER BY timestamp ASC LIMIT ?
      )`,[s]),this.save(),s}rowToGenericEvent(e,t){let s={};return e.forEach((n,i)=>{s[n]=t[i];}),{id:s.id,schemaId:s.schema_id,eventType:s.event_type,category:s.category,timestamp:s.timestamp,scopeValue:s.scope_value||void 0,scopeOrdinal:s.scope_ordinal!=null?s.scope_ordinal:void 0,sessionId:s.session_id||void 0,service:s.service,data:s.data_json?JSON.parse(s.data_json):void 0,severity:s.severity||"info",parentEventId:s.parent_event_id||void 0,depth:s.depth||0}}close(){this.db&&(this.save(),this.db.close(),this.db=null);}};var k={minScore:30,maxResults:5,boostConfidence:true},R=class{constructor(e){this.storage=e;}match(e,t={}){let{minScore:s,maxResults:n,boostConfidence:i}={...k,...t},r=this.storage.getAllPatterns({includePrivate:true}),a=[];for(let o of r){if(!this.matchEnvironment(o,e))continue;let{score:c,matchedCriteria:l}=this.scoreMatch(o,e);if(c>=s){let d=c;if(i){let m=o.confidence.score/100;d=c*(.5+.5*m);}a.push({pattern:o,score:c,matchedCriteria:l,confidence:Math.round(d)}),this.storage.updatePatternConfidence(o.id,"matched");}}return a.sort((o,c)=>c.confidence-o.confidence).slice(0,n)}testPattern(e,t=100){let s=this.storage.getRecentIncidents({limit:t}),n=[],i=0;for(let r of s){if(!this.matchEnvironment(e,r))continue;let{score:a}=this.scoreMatch(e,r);a>=30&&(n.push(r),i+=a);}return {wouldMatch:n,matchCount:n.length,avgScore:n.length>0?Math.round(i/n.length):0}}scoreMatch(e,t){let s=0,n={symbols:[],errorKeywords:[],missingSignals:[]},i=this.matchSymbols(e.pattern.symbols,t.symbols,n.symbols);s+=Math.min(i,50);let r=this.matchErrorText(e,t,n.errorKeywords);s+=Math.min(r,25);let a=this.matchMissingSignals(e,t,n.missingSignals);return s+=Math.min(a,25),s=Math.min(s,100),{score:s,matchedCriteria:n}}matchSymbols(e,t,s){let n=0,i=["feature","component","flow","gate","signal","state","integration"];for(let r of i){let a=e[r],o=t[r];if(!(!a||!o)){if(typeof a=="string")this.matchSingleSymbol(a,o)&&(n+=a.includes("*")?5:10,s.push(r));else if(Array.isArray(a)){for(let c of a)if(this.matchSingleSymbol(c,o)){n+=7,s.push(r);break}}}}return n}matchSingleSymbol(e,t){if(e==="*")return  true;if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}if(e.startsWith("*")){let s=e.slice(1);return t.endsWith(s)}return e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(t):e===t}matchErrorText(e,t,s){let n=0,i=t.error.message.toLowerCase(),r=t.error.type?.toLowerCase();if(e.pattern.errorContains)for(let a of e.pattern.errorContains)i.includes(a.toLowerCase())&&(n+=5,s.push(a));if(e.pattern.errorMatches)try{new RegExp(e.pattern.errorMatches,"i").test(t.error.message)&&(n+=10,s.push(`regex:${e.pattern.errorMatches}`));}catch{}if(e.pattern.errorType&&r)for(let a of e.pattern.errorType)r.includes(a.toLowerCase())&&(n+=5,s.push(`type:${a}`));return n}matchMissingSignals(e,t,s){if(!e.pattern.missingSignals||!t.flowPosition?.missing)return 0;let n=0;for(let i of e.pattern.missingSignals)for(let r of t.flowPosition.missing)if(this.matchSingleSymbol(i,r)){n+=12,s.push(r);break}return n}matchEnvironment(e,t){return !e.pattern.environment||e.pattern.environment.length===0?true:e.pattern.environment.includes(t.environment)}};var _=class{build(e){if(!e.flowPosition)return null;let t=[],s=new Date(e.timestamp).getTime();t.push({timestamp:new Date(s-5e3).toISOString(),symbol:e.flowPosition.flowId,type:"flow-started"});let n=1e3;for(let r of e.flowPosition.actual){let a=this.inferEventType(r);t.push({timestamp:new Date(s-4e3+n).toISOString(),symbol:r,type:a}),n+=Math.random()*1e3+500;}let i=e.flowPosition.failedAt||e.flowPosition.missing[0]||e.symbols.gate||e.symbols.signal||"unknown";return t.push({timestamp:e.timestamp,symbol:i,type:"error",data:{message:e.error.message,missing:e.flowPosition.missing}}),{incidentId:e.id,flowId:e.flowPosition.flowId,events:t,failure:{at:e.timestamp,symbol:i,reason:e.error.message}}}renderAscii(e){let t=[];t.push(`${e.flowId} Timeline`),t.push("\u2550".repeat(40)),t.push("");for(let n of e.events){let i=this.formatTime(n.timestamp),r=this.getEventIcon(n.type),a=this.getEventStatus(n.type),o=`${i}  ${r} ${n.symbol}`;a&&(o+=` (${a})`),t.push(o),n.type==="error"&&n.data&&(t.push(`             \u2514\u2500 ${n.data.message}`),n.data.missing&&Array.isArray(n.data.missing)&&n.data.missing.length>0&&t.push(`             \u2514\u2500 Expected: ${n.data.missing.join(", ")}`));}let s=e.events.find(n=>n.type==="error")?.data?.missing;return s&&s.length>0&&(t.push(""),t.push(`Missing signals: ${s.join(", ")}`)),t.join(`
`)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(t=>({time:this.formatTime(t.timestamp),symbol:t.symbol,type:t.type,status:this.getEventStatus(t.type),data:t.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let t=new Date(e),s=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0"),i=String(t.getSeconds()).padStart(2,"0"),r=String(t.getMilliseconds()).padStart(3,"0");return `${s}:${n}:${i}.${r}`}};var L=class{constructor(e){this.storage=e;}getStats(e=7){let t=new Date().toISOString(),s=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.storage.getStats({start:s,end:t})}getSymbolHealth(e){return this.storage.getSymbolHealth(e)}getTrendingIssues(e=7){let t=Date.now(),s=e*24*60*60*1e3/2,n=new Date(t-e*24*60*60*1e3).toISOString(),i=new Date(t-s).toISOString(),r=new Date(t).toISOString(),a=this.storage.getRecentIncidents({dateFrom:n,dateTo:i,limit:1e3}),o=this.storage.getRecentIncidents({dateFrom:i,dateTo:r,limit:1e3}),c=this.countSymbols(a),l=this.countSymbols(o),d=[],m=new Set([...c.keys(),...l.keys()]);for(let g of m){let p=c.get(g)||0,E=l.get(g)||0;if(p===0&&E>0)d.push({symbol:g,trend:E*100});else if(p>0){let S=(E-p)/p*100;d.push({symbol:g,trend:S});}}return d.filter(g=>g.trend>0).sort((g,p)=>p.trend-g.trend).slice(0,10)}getResolutionMetrics(){let e=this.getStats(30);return {avgTimeToResolve:e.resolution.avgTimeToResolve,resolvedWithPattern:e.resolution.resolvedWithPattern,resolvedManually:e.resolution.resolvedManually,totalResolved:e.incidents.resolved,resolutionRate:e.resolution.resolutionRate}}getPatternEffectiveness(){return this.storage.getAllPatterns({includePrivate:true}).filter(t=>t.confidence.timesMatched>0).map(t=>({patternId:t.id,name:t.name,matches:t.confidence.timesMatched,resolutions:t.confidence.timesResolved,recurrences:t.confidence.timesRecurred,effectiveness:t.confidence.timesMatched>0?Math.round((t.confidence.timesResolved-t.confidence.timesRecurred)/t.confidence.timesMatched*100):0})).sort((t,s)=>s.effectiveness-t.effectiveness)}getIncidentsByHour(e=7){let t=new Date(Date.now()-e*24*60*60*1e3).toISOString(),s=this.storage.getRecentIncidents({dateFrom:t,limit:1e4}),n=new Map;for(let i=0;i<24;i++)n.set(i,0);for(let i of s){let r=new Date(i.timestamp).getHours();n.set(r,(n.get(r)||0)+1);}return Array.from(n.entries()).map(([i,r])=>({hour:i,count:r}))}getIncidentsByEnvironment(){let e=this.getStats(30),t=e.incidents.total;return Object.entries(e.incidents.byEnvironment).map(([s,n])=>({environment:s,count:n,percentage:t>0?Math.round(n/t*100):0})).sort((s,n)=>n.count-s.count)}getSymbolCorrelation(){let e=this.storage.getRecentIncidents({limit:1e3}),t=new Map,s=new Map;for(let i of e){let r=this.getSymbolsFromIncident(i);for(let a of r)s.set(a,(s.get(a)||0)+1);for(let a=0;a<r.length;a++)for(let o=a+1;o<r.length;o++){let c=[r[a],r[o]].sort().join("|");t.set(c,(t.get(c)||0)+1);}}let n=[];for(let[i,r]of t){let[a,o]=i.split("|"),c=s.get(a)||1,l=s.get(o)||1,d=r/Math.max(c,l);d>.3&&n.push({symbol1:a,symbol2:o,correlation:Math.round(d*100)/100});}return n.sort((i,r)=>r.correlation-i.correlation).slice(0,20)}generateDashboard(e=7){let t=this.getStats(e),s=[];s.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),s.push("\u2551                    PARADIGM SENTINEL DASHBOARD                  \u2551"),s.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");let n=t.incidents.byDay[t.incidents.byDay.length-1]?.count||0;s.push(`\u2551  Open: ${String(t.incidents.open).padEnd(4)} \u2502  Investigating: ${String(t.incidents.total-t.incidents.open-t.incidents.resolved).padEnd(3)} \u2502  Resolved: ${String(t.incidents.resolved).padEnd(4)} \u2502  Today: +${n}   \u2551`),s.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),s.push(""),s.push("Incidents by Day (last 7 days):"),s.push("\u2500".repeat(50));let i=Math.max(...t.incidents.byDay.map(r=>r.count),1);for(let r of t.incidents.byDay.slice(-7)){let a=Math.round(r.count/i*30),o="\u2588".repeat(a);s.push(`${r.date.substring(5)}  ${o} ${r.count}`);}s.push(""),s.push("Most Affected Symbols:"),s.push("\u2500".repeat(50));for(let{symbol:r,count:a}of t.symbols.mostIncidents.slice(0,5))s.push(`  ${r.padEnd(25)} ${a} incidents`);s.push(""),s.push("Top Patterns:"),s.push("\u2500".repeat(50));for(let{patternId:r,resolvedCount:a}of t.patterns.mostEffective.slice(0,5))s.push(`  ${r.padEnd(25)} ${a} resolved`);return s.push(""),s.push("Resolution Stats:"),s.push("\u2500".repeat(50)),s.push(`  Resolution rate: ${Math.round(t.resolution.resolutionRate)}%`),s.push(`  With pattern: ${t.resolution.resolvedWithPattern}`),s.push(`  Manual: ${t.resolution.resolvedManually}`),s.join(`
`)}countSymbols(e){let t=new Map;for(let s of e)for(let[,n]of Object.entries(s.symbols))n&&t.set(n,(t.get(n)||0)+1);return t}getSymbolsFromIncident(e){let t=[];for(let[,s]of Object.entries(e.symbols))s&&t.push(s);return t}};var C=class{constructor(e){this.storage=e;}suggestFromIncident(e){let t=this.generatePatternId(e),s=this.buildSymbolCriteria(e.symbols),n=this.extractErrorKeywords(e.error.message);return {id:t,name:this.generatePatternName(e),description:`Auto-suggested pattern from incident ${e.id}`,pattern:{symbols:s,errorContains:n.length>0?n:void 0,missingSignals:e.flowPosition?.missing},resolution:{description:e.resolution?.notes||"Resolution approach TBD",strategy:this.inferStrategy([e]),priority:"medium"},source:"suggested",private:false,tags:this.generateTags(e)}}suggestFromGroup(e){let t=`group-${e.id.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,s=this.buildSymbolCriteria(e.commonSymbols),n=e.incidents.slice(0,20).map(r=>this.storage.getIncident(r)).filter(r=>r!=null);return {id:t,name:e.name||`Pattern from group ${e.id}`,description:`Auto-suggested pattern from incident group with ${e.count} incidents`,pattern:{symbols:s,errorContains:e.commonErrorPatterns.length>0?e.commonErrorPatterns:void 0},resolution:{description:"Resolution approach TBD based on grouped incidents",strategy:n.length>0?this.inferStrategy(n):"fix-code",priority:this.getPriorityFromCount(e.count)},source:"suggested",private:false,tags:this.generateTagsFromGroup(e)}}findPatternCandidates(e=3){let t=this.storage.getRecentIncidents({limit:1e3,status:"resolved"}),s=new Map;for(let i of t){let r=this.getSymbolSignature(i.symbols),a=s.get(r)||[];a.push(i),s.set(r,a);}let n=[];for(let[,i]of s)if(i.length>=e){if(this.hasMatchingPattern(i[0]))continue;let a=this.suggestFromIncidents(i);n.push({incidents:i,suggestedPattern:a,occurrenceCount:i.length});}return n.sort((i,r)=>r.occurrenceCount-i.occurrenceCount)}suggestFromIncidents(e){let t=this.extractCommonSymbols(e),s=this.buildSymbolCriteria(t),n=this.extractCommonErrorKeywords(e),i=this.extractCommonMissingSignals(e);return {id:this.generatePatternId(e[0]),name:this.generatePatternName(e[0]),description:`Auto-suggested pattern from ${e.length} similar incidents`,pattern:{symbols:s,errorContains:n.length>0?n:void 0,missingSignals:i.length>0?i:void 0},resolution:{description:"Resolution approach based on previous resolutions",strategy:this.inferStrategy(e),priority:this.getPriorityFromCount(e.length)},source:"suggested",private:false,tags:this.generateTagsFromIncidents(e)}}buildSymbolCriteria(e){let t={};for(let[s,n]of Object.entries(e))n&&(t[s]=n);return t}extractErrorKeywords(e){let t=new Set(["the","a","an","is","are","was","were","in","on","at","to","for","of","with","and","or","but","not","no","be","been","have","has","had","do","does","did"]),s=e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(i=>i.length>2&&!t.has(i));return [...new Set(s)].slice(0,5)}extractCommonErrorKeywords(e){let t=new Map;for(let n of e){let i=this.extractErrorKeywords(n.error.message);for(let r of i)t.set(r,(t.get(r)||0)+1);}let s=Math.ceil(e.length*.5);return Array.from(t.entries()).filter(([,n])=>n>=s).map(([n])=>n).slice(0,5)}extractCommonSymbols(e){if(e.length===0)return {};let t=e[0].symbols,s={};for(let[n,i]of Object.entries(t)){if(!i)continue;e.every(a=>a.symbols[n]===i)&&(s[n]=i);}return s}extractCommonMissingSignals(e){let t=new Map;for(let n of e)if(n.flowPosition?.missing)for(let i of n.flowPosition.missing)t.set(i,(t.get(i)||0)+1);let s=Math.ceil(e.length*.5);return Array.from(t.entries()).filter(([,n])=>n>=s).map(([n])=>n)}generatePatternId(e){let t=[];e.symbols.gate?t.push(e.symbols.gate.replace(/[^a-z0-9]/gi,"")):e.symbols.feature?t.push(e.symbols.feature.replace(/[^a-z0-9]/gi,"")):e.symbols.component?t.push(e.symbols.component.replace(/[^a-z0-9]/gi,"")):e.symbols.integration?t.push(e.symbols.integration.replace(/[^a-z0-9]/gi,"")):t.push("unknown");let s=e.error.type?.toLowerCase()||"error";return t.push(s.replace(/[^a-z0-9]/gi,"")),t.push(String(Date.now()%1e3).padStart(3,"0")),t.join("-")}generatePatternName(e){let t=[];if(e.symbols.feature&&t.push(e.symbols.feature.replace("@","").replace(/-/g," ")),e.symbols.gate&&t.push("gate "+e.symbols.gate.replace("^","")),e.error.type&&t.push(e.error.type),t.length===0)return "Unnamed Pattern";let s=t.join(" - ");return s.charAt(0).toUpperCase()+s.slice(1)}generateTags(e){let t=[];return e.symbols.feature&&t.push("feature"),e.symbols.gate&&t.push("gate"),e.symbols.integration&&(t.push("integration"),t.push(e.symbols.integration.replace("&",""))),e.error.type&&t.push(e.error.type.toLowerCase()),t.push(e.environment),[...new Set(t)].slice(0,5)}generateTagsFromGroup(e){let t=["grouped"];e.commonSymbols.feature&&t.push("feature"),e.commonSymbols.gate&&t.push("gate"),e.commonSymbols.integration&&t.push("integration");for(let s of e.environments)t.push(s);return [...new Set(t)].slice(0,5)}generateTagsFromIncidents(e){let t=new Map;for(let s of e){let n=this.generateTags(s);for(let i of n)t.set(i,(t.get(i)||0)+1);}return Array.from(t.entries()).sort((s,n)=>n[1]-s[1]).slice(0,5).map(([s])=>s)}getSymbolSignature(e){let t=[];return e.feature&&t.push(`f:${e.feature}`),e.component&&t.push(`c:${e.component}`),e.flow&&t.push(`fl:${e.flow}`),e.gate&&t.push(`g:${e.gate}`),e.integration&&t.push(`i:${e.integration}`),t.sort().join("|")}hasMatchingPattern(e){let t=this.storage.getAllPatterns({includePrivate:true});for(let s of t){let n=0,i=["feature","component","flow","gate","signal","integration"];for(let r of i){let a=s.pattern.symbols[r],o=e.symbols[r];a&&o&&a===o&&n++;}if(n>=2)return  true}return  false}inferStrategy(e){let t=e.map(i=>i.error.message.toLowerCase()),s=i=>t.some(r=>i.some(a=>r.includes(a)));return s(["revert","rollback","regression","broke after deploy","since deploy"])?"rollback":s(["config","environment variable","env var","missing key","secret","credential"])?"config-change":s(["out of memory","oom","heap","memory limit","capacity","too many connections","pool exhausted"])?"scale-up":s(["timeout","network","econnrefused","econnreset","dns","socket hang up"])?"retry":s(["unavailable","service down","circuit breaker","fallback","503","502"])?"fallback":s(["validation","invalid","required","constraint","duplicate","not found","404"])?"fix-data":s(["permission","forbidden","403","401","unauthorized","access denied"])?"escalate":new Set(e.map(i=>i.error.type).filter(Boolean)).size>2?"investigate":"fix-code"}getPriorityFromCount(e){return e>=20?"critical":e>=10?"high":e>=5?"medium":"low"}};var B=fileURLToPath(import.meta.url),F=I.dirname(B);function G(){let h=I.join(F,"universal-patterns.json"),e=y.readFileSync(h,"utf-8");return JSON.parse(e)}function W(){let h=I.join(F,"paradigm-patterns.json"),e=y.readFileSync(h,"utf-8");return JSON.parse(e)}function M(){let h=G(),e=W();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...h.patterns,...e.patterns]}}var w=null,x=false;function U(){if(w||(w=new O),!x){try{let{patterns:h}=M();for(let e of h)try{w.addPattern(e);}catch{}}catch{}x=true;}return w}function Q(){return [{name:"sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., #checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}}},{name:"sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]}},{name:"sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference.",annotations:{readOnlyHint:false,destructiveHint:false},inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]}},{name:"sentinel_patterns",description:"List and filter failure patterns with confidence scores.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}}},{name:"sentinel_add_pattern",description:"Create a new failure pattern.",annotations:{readOnlyHint:false,destructiveHint:false},inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]}},{name:"sentinel_record",description:"Manually record a new incident.",annotations:{readOnlyHint:false,destructiveHint:false},inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]}},{name:"sentinel_stats",description:"Get statistics and health metrics.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}}},{name:"sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}}},{name:"sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}}},{name:"sentinel_services",description:"List all registered services with version, environment, and last-seen time.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{}}},{name:"sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}}},{name:"sentinel_validate_symbol",description:"Check if a symbol has been used in logs. Returns usage count and suggestions.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]}},{name:"sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}}},{name:"sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}}},{name:"sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops.",annotations:{readOnlyHint:true,destructiveHint:false},inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}}}]}async function Z(h,e){let t=U(),s=new R(t);switch(h){case "sentinel_triage":{let{symbol:n,status:i="all",environment:r,search:a,limit:o=10}=e,c=t.getRecentIncidents({limit:o,status:i,symbol:n,environment:r,search:a});if(c.length===0)return JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Use sentinel_record to create incidents or integrate the SDK."},null,2);let l=c.map(d=>{let m=s.match(d,{maxResults:3});return {id:d.id,timestamp:d.timestamp,status:d.status,error:d.error.message,symbols:d.symbols,environment:d.environment,matches:m.map(g=>({patternId:g.pattern.id,name:g.pattern.name,confidence:g.confidence,strategy:g.pattern.resolution.strategy,description:g.pattern.resolution.description}))}});return JSON.stringify({count:l.length,incidents:l},null,2)}case "sentinel_show":{let{incidentId:n,includeTimeline:i,includeSimilar:r}=e,a=t.getIncident(n);if(!a)return JSON.stringify({error:`Incident ${n} not found`});let o=s.match(a,{maxResults:5}),c={incident:a,matches:o.map(l=>({patternId:l.pattern.id,name:l.pattern.name,confidence:l.confidence,matchedCriteria:l.matchedCriteria,resolution:l.pattern.resolution}))};if(i&&a.flowPosition){let l=new _().build(a);l&&(c.timeline=new _().renderStructured(l));}if(r){let l=t.getRecentIncidents({symbol:Object.values(a.symbols)[0],limit:5}).filter(d=>d.id!==n);c.similar=l.map(d=>({id:d.id,error:d.error.message,status:d.status}));}return JSON.stringify(c,null,2)}case "sentinel_resolve":{let{incidentId:n,patternId:i,commitHash:r,prUrl:a,notes:o,wontFix:c}=e;return t.getIncident(n)?c?(t.updateIncident(n,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:o}}),JSON.stringify({success:true,message:`Incident ${n} marked as won't fix`})):(t.recordResolution({incidentId:n,patternId:i,commitHash:r,prUrl:a,notes:o}),JSON.stringify({success:true,message:`Incident ${n} resolved`,patternId:i,commitHash:r,prUrl:a})):JSON.stringify({error:`Incident ${n} not found`})}case "sentinel_patterns":{let{symbol:n,minConfidence:i,source:r}=e,a=t.getAllPatterns({source:r,minConfidence:i,includePrivate:false}),o=a;return n&&(o=a.filter(c=>{let l=c.pattern.symbols;return Object.values(l).some(d=>d?Array.isArray(d)?d.includes(n)||d.some(m=>n.match(m.replace("*",".*"))):d===n||n.match(d.replace("*",".*")):false)})),JSON.stringify({count:o.length,patterns:o.map(c=>({id:c.id,name:c.name,description:c.description,confidence:c.confidence.score,resolution:c.resolution,tags:c.tags}))},null,2)}case "sentinel_add_pattern":{let{id:n,name:i,description:r,pattern:a,resolution:o,tags:c}=e,l={id:n,name:i,description:r||"",pattern:{symbols:a.symbols||{},errorContains:a.errorContains,missingSignals:a.missingSignals},resolution:{description:o.description,strategy:o.strategy,priority:o.priority||"medium",codeHint:o.codeHint},source:"manual",private:false,tags:c||[]};return t.addPattern(l),JSON.stringify({success:true,message:`Pattern ${n} created`,pattern:l})}case "sentinel_record":{let{error:n,symbols:i,environment:r,service:a,version:o,flowPosition:c}=e,l=t.recordIncident({error:n,symbols:i,environment:r,service:a,version:o,flowPosition:c}),d=t.getIncident(l),m=d?s.match(d,{maxResults:3}):[];return JSON.stringify({success:true,incidentId:l,matches:m.map(g=>({patternId:g.pattern.id,confidence:g.confidence,resolution:g.pattern.resolution.description}))},null,2)}case "sentinel_stats":{let{period:n="7d",symbol:i}=e,r=new L(t);if(i){let l=r.getSymbolHealth(i);return JSON.stringify({symbol:i,health:l},null,2)}let a=n.match(/^(\d+)d$/),o=a?parseInt(a[1],10):7,c=r.getStats(o);return JSON.stringify({period:`${o}d`,stats:c},null,2)}case "sentinel_suggest_pattern":{let{incidentId:n,minOccurrences:i}=e,r=new C(t);if(n){let o=t.getIncident(n);if(!o)return JSON.stringify({error:`Incident ${n} not found`});let c=r.suggestFromIncident(o);return JSON.stringify({source:"incident",incidentId:n,suggestion:c},null,2)}let a=r.findPatternCandidates(i||3);return JSON.stringify({source:"analysis",candidates:a.slice(0,5).map(o=>({occurrences:o.occurrenceCount,sampleIncidents:o.incidents.slice(0,3).map(c=>c.id),suggestion:o.suggestedPattern}))},null,2)}case "sentinel_logs":{let{level:n,symbol:i,service:r,search:a,since:o,sessionId:c,correlationId:l,limit:d=50}=e,m=t.queryLogs({level:n,symbol:i,service:r,search:a,since:o,sessionId:c,correlationId:l,limit:d}),g=t.getLogCount({level:n,symbol:i,service:r,since:o});return JSON.stringify({count:m.length,total:g,logs:m.map(p=>({timestamp:p.timestamp,level:p.level,symbol:p.symbol,service:p.service,message:p.message,data:p.data,sessionId:p.sessionId,correlationId:p.correlationId,durationMs:p.durationMs}))},null,2)}case "sentinel_services":{let n=t.getServices();return JSON.stringify({count:n.length,services:n.map(i=>({name:i.name,version:i.version,environment:i.environment,lastSeen:i.lastSeenAt,startedAt:i.startedAt,pid:i.pid}))},null,2)}case "sentinel_app_state":{let{service:n}=e,i=n?t.getAppState(n):t.getAllAppStates();return JSON.stringify({states:i.map(r=>({service:r.service,sessionId:r.sessionId,state:r.state,activeFlows:r.activeFlows,activeGates:r.activeGates,timestamp:r.timestamp}))},null,2)}case "sentinel_validate_symbol":{let{symbol:n}=e,i=t.getLogCount({symbol:n});return JSON.stringify({symbol:n,usedInLogs:i>0,logCount:i,tip:i===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${i} log entries.`},null,2)}case "sentinel_flow_activity":{let{flowId:n,service:i,since:r}=e,o=t.queryLogs({symbol:n,service:i,since:r,limit:100}).filter(c=>["flow","signal","gate"].includes(c.symbolType)).map(c=>({timestamp:c.timestamp,symbol:c.symbol,symbolType:c.symbolType,service:c.service,message:c.message,level:c.level}));return JSON.stringify({count:o.length,events:o},null,2)}case "sentinel_metrics":{let{name:n,type:i,service:r,since:a,aggregate:o,limit:c}=e;if(o&&n){let d=t.aggregateMetric(n,{service:r,since:a});return JSON.stringify(d,null,2)}let l=t.queryMetrics({name:n,type:i,service:r,since:a,limit:Math.min(c||50,100)});return JSON.stringify({count:l.length,metrics:l.map(d=>({timestamp:d.timestamp,name:d.name,type:d.type,value:d.value,tags:d.tags,service:d.service}))},null,2)}case "sentinel_traces":{let{traceId:n,service:i,symbol:r,since:a,limit:o}=e;if(n){let l=t.getTrace(n);return l?JSON.stringify(l,null,2):JSON.stringify({error:"Trace not found"})}let c=t.queryTraces({service:i,symbol:r,since:a,limit:Math.min(o||10,20)});return JSON.stringify({count:c.length,traces:c.map(l=>({traceId:l.traceId,services:l.services,spanCount:l.spans.length,totalDurationMs:l.totalDurationMs,startTime:l.startTime,endTime:l.endTime}))},null,2)}default:return JSON.stringify({error:`Unknown tool: ${h}`})}}async function ee(){console.error("[sentinel-mcp] Starting..."),await U().ensureReady(),console.error("[sentinel-mcp] Storage initialized");let e=new Server({name:"sentinel",version:"0.2.0"},{capabilities:{tools:{}}});e.setRequestHandler(ListToolsRequestSchema,async()=>({tools:Q()})),e.setRequestHandler(CallToolRequestSchema,async s=>{let{name:n,arguments:i}=s.params;try{return {content:[{type:"text",text:await Z(n,i||{})}]}}catch(r){let a=r instanceof Error?r.message:String(r);return {content:[{type:"text",text:JSON.stringify({error:a})}],isError:true}}}),e.onerror=s=>{console.error("[sentinel-mcp] Server error:",s);};let t=new StdioServerTransport;await e.connect(t),console.error("[sentinel-mcp] Running on stdio");}ee().catch(h=>{console.error("[sentinel-mcp] Fatal:",h),process.exit(1);});