#!/usr/bin/env node
import L from'sql.js';import {v4}from'uuid';import*as v from'path';import*as y from'fs';var R=5,X={score:50,timesMatched:0,timesResolved:0,timesRecurred:0},S=null,w=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||v.join(process.cwd(),".paradigm","sentinel");return v.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(R)]));}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 t=`INC-${String(this.incidentCounter).padStart(3,"0")}`,s=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.timestamp||s,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,s,s]),this.save(),t}initializeSync(){if(!(this.initialized&&this.db)&&!this.db&&S){let e=v.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 S.Database(t);}else this.db=new S.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(){S||(S=await L()),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,i=[],n=[];e.status&&e.status!=="all"&&(i.push("status = ?"),n.push(e.status)),e.environment&&(i.push("environment = ?"),n.push(e.environment)),e.symbol&&(i.push("symbols LIKE ?"),n.push(`%${e.symbol}%`)),e.search&&(i.push("(error_message LIKE ? OR notes LIKE ?)"),n.push(`%${e.search}%`,`%${e.search}%`)),e.dateFrom&&(i.push("timestamp >= ?"),n.push(e.dateFrom)),e.dateTo&&(i.push("timestamp <= ?"),n.push(e.dateTo)),e.groupId&&(i.push("group_id = ?"),n.push(e.groupId));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM incidents ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...n,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(),i=["updated_at = ?"],n=[s];t.status!==void 0&&(i.push("status = ?"),n.push(t.status)),t.error!==void 0&&(i.push("error_message = ?"),n.push(t.error.message),t.error.stack!==void 0&&(i.push("error_stack = ?"),n.push(t.error.stack||null))),t.symbols!==void 0&&(i.push("symbols = ?"),n.push(JSON.stringify(t.symbols))),t.flowPosition!==void 0&&(i.push("flow_position = ?"),n.push(t.flowPosition?JSON.stringify(t.flowPosition):null)),t.groupId!==void 0&&(i.push("group_id = ?"),n.push(t.groupId||null)),t.resolvedAt!==void 0&&(i.push("resolved_at = ?"),n.push(t.resolvedAt||null)),t.resolvedBy!==void 0&&(i.push("resolved_by = ?"),n.push(t.resolvedBy||null)),t.resolution!==void 0&&(i.push("resolution = ?"),n.push(t.resolution?JSON.stringify(t.resolution):null)),n.push(e),this.db.run(`UPDATE incidents SET ${i.join(", ")} WHERE id = ?`,n),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 i={id:v4(),...t},n=[...s.notes,i];this.db.run("UPDATE incidents SET notes = ?, updated_at = ? WHERE id = ?",[JSON.stringify(n),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 n=[...s.relatedIncidents,t];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(n),new Date().toISOString(),e]);}let i=this.getIncident(t);if(i&&!i.relatedIncidents.includes(e)){let n=[...i.relatedIncidents,e];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(n),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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT COUNT(*) as count FROM incidents ${i}`,s);return n.length===0||n[0].values.length===0?0:n[0].values[0][0]}addPattern(e){this.initializeSync();let t=new Date().toISOString(),s={...X,...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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT * FROM patterns ${i} ORDER BY json_extract(confidence, '$.score') DESC`,s);return n.length===0?[]:n[0].values.map(r=>this.rowToPattern(n[0].columns,r))}updatePattern(e,t){this.initializeSync();let s=new Date().toISOString(),i=["updated_at = ?"],n=[s];t.name!==void 0&&(i.push("name = ?"),n.push(t.name)),t.description!==void 0&&(i.push("description = ?"),n.push(t.description||null)),t.pattern!==void 0&&(i.push("pattern = ?"),n.push(JSON.stringify(t.pattern))),t.resolution!==void 0&&(i.push("resolution = ?"),n.push(JSON.stringify(t.resolution))),t.confidence!==void 0&&(i.push("confidence = ?"),n.push(JSON.stringify(t.confidence))),t.source!==void 0&&(i.push("source = ?"),n.push(t.source)),t.private!==void 0&&(i.push("private = ?"),n.push(t.private?1:0)),t.tags!==void 0&&(i.push("tags = ?"),n.push(JSON.stringify(t.tags))),n.push(e),this.db.run(`UPDATE patterns SET ${i.join(", ")} WHERE id = ?`,n),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 i=new Date().toISOString(),n={...s.confidence};switch(t){case "matched":n.timesMatched++,n.lastMatched=i;break;case "resolved":n.timesResolved++,n.lastResolved=i,n.score=Math.min(100,n.score+2);break;case "recurred":n.timesRecurred++,n.score=Math.max(10,n.score-5);break}this.updatePattern(e,{confidence:n});}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 i of e.incidents)this.addToGroup(t,i);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(i=>this.rowToGroup(s[0].columns,i))}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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=e.limit||100,r=this.db.exec(`SELECT * FROM resolutions ${i} ORDER BY resolved_at DESC LIMIT ?`,[...s,n]);if(r.length===0)return [];let a=r[0].columns;return r[0].values.map(o=>{let d={};return a.forEach((p,u)=>{d[p]=o[u];}),{id:d.id,incidentId:d.incident_id,patternId:d.pattern_id||void 0,commitHash:d.commit_hash||void 0,prUrl:d.pr_url||void 0,notes:d.notes||void 0,resolvedAt:d.resolved_at,recurred:d.recurred===1}})}getStats(e){this.initializeSync();let{start:t,end:s}=e,i=this.getIncidentCount({dateFrom:t,dateTo:s}),n=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 l of a[0].values)o[l[0]]=l[1];let d=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]),p=[];if(d.length>0)for(let l of d[0].values)p.push({date:l[0],count:l[1]});let u=this.getAllPatterns({includePrivate:true}),T=u.length>0?u.reduce((l,h)=>l+h.confidence.score,0)/u.length:0,E=u.sort((l,h)=>h.confidence.timesResolved-l.confidence.timesResolved).slice(0,5).map(l=>({patternId:l.id,resolvedCount:l.confidence.timesResolved})),m=u.filter(l=>l.confidence.timesMatched>0).map(l=>({patternId:l.id,recurrenceRate:l.confidence.timesRecurred/Math.max(1,l.confidence.timesResolved)})).sort((l,h)=>h.recurrenceRate-l.recurrenceRate).slice(0,5),c=new Map,I=this.getRecentIncidents({dateFrom:t,dateTo:s,limit:1e3});for(let l of I)for(let[,h]of Object.entries(l.symbols))h&&c.set(h,(c.get(h)||0)+1);let _=Array.from(c.entries()).sort((l,h)=>h[1]-l[1]).slice(0,10).map(([l,h])=>({symbol:l,count:h})),N=this.getResolutionHistory({limit:1e3}).filter(l=>l.resolvedAt>=t&&l.resolvedAt<=s),O=N.filter(l=>l.patternId).length,b=N.length-O;return {period:{start:t,end:s},incidents:{total:i,open:n,resolved:r,byEnvironment:o,byDay:p},patterns:{total:u.length,avgConfidence:Math.round(T),mostEffective:E,leastEffective:m},symbols:{mostIncidents:_,mostResolved:[],hotspots:_.slice(0,5).map(l=>({symbol:l.symbol,incidentRate:l.count/Math.max(1,i)}))},resolution:{avgTimeToResolve:0,resolvedWithPattern:O,resolvedManually:b,resolutionRate:i>0?r/i*100:0}}}getSymbolHealth(e){let t=this.getRecentIncidents({symbol:e,limit:1e3}),s=t.length,i=new Map;for(let r of t)if(r.resolution?.patternId){let a=i.get(r.resolution.patternId)||0;i.set(r.resolution.patternId,a+1);}let n=Array.from(i.entries()).sort((r,a)=>a[1]-r[1]).slice(0,5).map(([r,a])=>({patternId:r,count:a}));return {incidentCount:s,avgTimeToResolve:0,topPatterns:n}}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,i=0;for(let n of e.patterns){let r=this.getPattern(n.id);if(r&&!t.overwrite){i++;continue}r?this.updatePattern(n.id,n):this.addPattern({...n,source:"imported"}),s++;}return {imported:s,skipped:i}}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 i of e.patterns)this.addPattern(i);for(let i of e.incidents){let n=i.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.timestamp,i.status,i.error.message,i.error.stack||null,i.error.code||null,i.error.type||null,JSON.stringify(i.symbols),i.flowPosition?JSON.stringify(i.flowPosition):null,i.environment,i.service||null,i.version||null,i.userId||null,i.requestId||null,i.groupId||null,JSON.stringify(i.notes),JSON.stringify(i.relatedIncidents),i.resolvedAt||null,i.resolvedBy||null,i.resolution?JSON.stringify(i.resolution):null,n,n]);}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 i 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.name||null,JSON.stringify(i.commonSymbols),JSON.stringify(i.commonErrorPatterns),i.suggestedPattern?.id||null,i.firstSeen,i.lastSeen,s,s]);for(let n of i.incidents)this.db.run("INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",[i.id,n,s]);}this.save();}rowToIncident(e,t){let s={};return e.forEach((i,n)=>{s[i]=t[n];}),{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((i,n)=>{s[i]=t[n];}),{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,d)=>{s[o]=t[d];});let i=this.db.exec("SELECT incident_id FROM group_members WHERE group_id = ?",[s.id]),n=[];if(i.length>0)for(let o of i[0].values)n.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:n,commonSymbols:JSON.parse(s.common_symbols||"{}"),commonErrorPatterns:JSON.parse(s.common_error_patterns||"[]"),count:n.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,i=[],n=[];e.habitId&&(i.push("habit_id = ?"),n.push(e.habitId)),e.habitCategory&&(i.push("habit_category = ?"),n.push(e.habitCategory)),e.result&&(i.push("result = ?"),n.push(e.result)),e.engineer&&(i.push("engineer = ?"),n.push(e.engineer)),e.sessionId&&(i.push("session_id = ?"),n.push(e.sessionId)),e.dateFrom&&(i.push("timestamp >= ?"),n.push(e.dateFrom)),e.dateTo&&(i.push("timestamp <= ?"),n.push(e.dateTo));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM practice_events ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...n,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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT COUNT(*) as count FROM practice_events ${i}`,s);return n.length===0||n[0].values.length===0?0:n[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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT result, COUNT(*) as count
       FROM practice_events ${i}
       GROUP BY result`,s),r=0,a=0,o=0;if(n.length>0)for(let u of n[0].values){let T=u[0],E=u[1];T==="followed"?r=E:T==="skipped"?a=E:T==="partial"&&(o=E);}let d=r+a+o,p=d>0?(r+o*.5)/d*100:100;return {total:d,followed:r,skipped:a,partial:o,rate:Math.round(p)}}rowToPracticeEvent(e,t){let s={};return e.forEach((i,n)=>{s[i]=t[n];}),{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(),i=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,i,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 i of e)try{let n=i.id||v4(),r=i.timestamp||new Date().toISOString(),a=i.symbolType||this.inferSymbolType(i.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,r,i.level,i.symbol,a,i.message,i.data?JSON.stringify(i.data):null,i.service,i.sessionId||null,i.correlationId||null,i.durationMs??null,i.environment||null]),t++;}catch(n){s.push(n instanceof Error?n.message:String(n));}return this.save(),{accepted:t,errors:s}}queryLogs(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,i=[],n=[];e.level&&(i.push("level = ?"),n.push(e.level)),e.symbol&&(i.push("symbol LIKE ?"),n.push(`%${e.symbol}%`)),e.service&&(i.push("service = ?"),n.push(e.service)),e.sessionId&&(i.push("session_id = ?"),n.push(e.sessionId)),e.correlationId&&(i.push("correlation_id = ?"),n.push(e.correlationId)),e.search&&(i.push("message LIKE ?"),n.push(`%${e.search}%`)),e.since&&(i.push("timestamp >= ?"),n.push(e.since)),e.until&&(i.push("timestamp <= ?"),n.push(e.until));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM logs ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...n,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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT COUNT(*) as count FROM logs ${i}`,s);return n.length===0||n[0].values.length===0?0:n[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((i,n)=>{s[i]=t[n];}),{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((i,n)=>{s[i]=t[n];}),{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 = ?",i=[e];t&&(s+=" AND session_id = ?",i.push(t)),s+=" ORDER BY timestamp DESC";let n=this.db.exec(s,i);return n.length===0?[]:n[0].values.map(r=>this.rowToAppState(n[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((i,n)=>{s[i]=t[n];}),{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 i of e)try{let n=v4(),r=i.timestamp||new Date().toISOString();this.db.run(`INSERT INTO metrics (
            id, timestamp, name, type, value, tags_json, service, environment
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[n,r,i.name,i.type,i.value,JSON.stringify(i.tags||{}),i.service,i.environment||null]),t++;}catch(n){s.push(n instanceof Error?n.message:String(n));}return this.save(),{accepted:t,errors:s}}queryMetrics(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,i=[],n=[];if(e.name&&(i.push("name = ?"),n.push(e.name)),e.type&&(i.push("type = ?"),n.push(e.type)),e.service&&(i.push("service = ?"),n.push(e.service)),e.tag){let o=e.tag.indexOf("=");if(o>0){let d=e.tag.substring(0,o),p=e.tag.substring(o+1);i.push("tags_json LIKE ?"),n.push(`%"${d}":"${p}"%`);}}e.since&&(i.push("timestamp >= ?"),n.push(e.since)),e.until&&(i.push("timestamp <= ?"),n.push(e.until));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM metrics ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...n,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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT COUNT(*) as count FROM metrics ${i}`,s);return n.length===0||n[0].values.length===0?0:n[0].values[0][0]}aggregateMetric(e,t){this.initializeSync();let s=["name = ?"],i=[e];t?.service&&(s.push("service = ?"),i.push(t.service)),t?.since&&(s.push("timestamp >= ?"),i.push(t.since)),t?.until&&(s.push("timestamp <= ?"),i.push(t.until));let n=`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 ${n}`,i);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((i,n)=>{s[i]=t[n];}),{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(u=>this.rowToTraceSpan(t[0].columns,u)),i=[...new Set(s.map(u=>u.service))],n=s.map(u=>u.startTime),r=s.filter(u=>u.endTime).map(u=>u.endTime),a=n.sort()[0],o=r.length>0?r.sort().reverse()[0]:a,d=new Date(a).getTime(),p=new Date(o).getTime()-d;return {traceId:e,spans:s,services:i,totalDurationMs:p>0?p: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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=Math.min(e.limit||20,20),r=this.db.exec(`SELECT DISTINCT trace_id FROM traces ${i} ORDER BY start_time DESC LIMIT ?`,[...s,n]);if(r.length===0)return [];let a=[];for(let o of r[0].values){let d=o[0],p=this.getTrace(d);p&&a.push(p);}return a}rowToTraceSpan(e,t){let s={};return e.forEach((i,n)=>{s[i]=t[n];}),{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((i,n)=>{s[i]=t[n];}),{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 i=this.getSchema(e),n=new Map;if(i)for(let o of i.eventTypes)n.set(o.type,{category:o.category,severity:o.severity||"info"});let r=0,a=[];for(let o of s)try{let d=o.id||v4(),p=o.timestamp||new Date().toISOString(),u=n.get(o.type),T=u?.category||"unknown",E=o.severity||u?.severity||"info",m=o.scopeValue!=null?String(o.scopeValue):null,c=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[d,e,o.type,T,p,m,c,o.sessionId||null,t,o.data?JSON.stringify(o.data):null,E,o.parentEventId||null,o.depth??0]),r++;}catch(d){a.push(d instanceof Error?d.message:String(d));}return this.save(),{accepted:r,errors:a}}queryEvents(e={}){this.initializeSync();let{limit:t=100,offset:s=0}=e,i=[],n=[];e.schemaId&&(i.push("schema_id = ?"),n.push(e.schemaId)),e.eventType&&(i.push("event_type = ?"),n.push(e.eventType)),e.category&&(i.push("category = ?"),n.push(e.category)),e.service&&(i.push("service = ?"),n.push(e.service)),e.sessionId&&(i.push("session_id = ?"),n.push(e.sessionId)),e.scopeValue&&(i.push("scope_value = ?"),n.push(e.scopeValue)),e.scopeFrom&&(i.push("scope_value >= ?"),n.push(e.scopeFrom)),e.scopeTo&&(i.push("scope_value <= ?"),n.push(e.scopeTo)),e.severity&&(i.push("severity = ?"),n.push(e.severity)),e.since&&(i.push("timestamp >= ?"),n.push(e.since)),e.until&&(i.push("timestamp <= ?"),n.push(e.until)),e.search&&(i.push("data_json LIKE ?"),n.push(`%${e.search}%`));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM events ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...n,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(i=>this.rowToGenericEvent(s[0].columns,i))}getEventScopes(e,t={}){this.initializeSync();let{limit:s=100,offset:i=0}=t,n=["schema_id = ?"],r=[e];t.sessionId&&(n.push("session_id = ?"),r.push(t.sessionId));let a=`WHERE ${n.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,i]);if(o.length===0)return [];let d=[];for(let p of o[0].values){let u=p[0],T=p[1]!=null?p[1]:void 0,E=p[2],m=p[3],c=p[4],I=this.db.exec(`SELECT category, COUNT(*) as count FROM events
         WHERE schema_id = ? AND scope_value = ?
         GROUP BY category`,[e,u]),_={};if(I.length>0)for(let N of I[0].values)_[N[0]]=N[1];d.push({scopeValue:u,scopeOrdinal:T,eventCount:E,categories:_,firstTimestamp:m,lastTimestamp:c});}return d}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 i=t.length>0?`WHERE ${t.join(" AND ")}`:"",n=this.db.exec(`SELECT COUNT(*) as count FROM events ${i}`,s);return n.length===0||n[0].values.length===0?0:n[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((i,n)=>{s[i]=t[n];}),{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);}},A={enabled:false,tokens:[]},x={enabled:false,global:{maxRequestsPerMinute:600,maxEntriesPerBatch:500,samplingRate:1},perService:{}},C={port:3838,maxLogs:1e4,maxBatchSize:500,wsMaxSubscribers:256,pruneIntervalInserts:100,logRetentionDays:0,auth:A,rateLimit:x},D=[".sentinel.yaml",".sentinel.yml"];function f(e){for(let t of D){let s=v.join(e,t);if(y.existsSync(s)){let i=y.readFileSync(s,"utf-8");return F(i)}}return null}function P(e,t){let s=v.join(e,".sentinel.yaml"),i=U(t);y.writeFileSync(s,i,"utf-8");}function F(e){let t={version:"1.0",project:""},s=e.split(`
`),i=null,n=null;for(let r of s){let a=r.trimEnd();if(!a||a.startsWith("#"))continue;let o=a.match(/^(\w+):\s*(.+)$/);if(o){let[,m,c]=o;m==="version"?t.version=c.replace(/['"]/g,""):m==="project"?t.project=c.replace(/['"]/g,""):m==="environment"&&(t.environment=c.replace(/['"]/g,"")),i=null,n=null;continue}let d=a.match(/^(\w+):$/);if(d){i=d[1],n=null,i==="symbols"&&!t.symbols&&(t.symbols={}),i==="routes"&&!t.routes&&(t.routes={}),i==="scrub"&&!t.scrub&&(t.scrub={}),i==="server"&&!t.server&&(t.server={});continue}let p=a.match(/^\s{2}(\w+):$/);if(p&&i){n=p[1],i==="symbols"&&t.symbols&&(t.symbols[n]=[]),i==="scrub"&&t.scrub&&(t.scrub[n]=[]);continue}let u=a.match(/^\s+-\s+(.+)$/);if(u&&i&&n){let m=u[1].replace(/['"]/g,"");if(i==="symbols"&&t.symbols){let c=t.symbols[n];Array.isArray(c)&&c.push(m);}if(i==="scrub"&&t.scrub){let c=t.scrub[n];Array.isArray(c)&&c.push(m);}continue}let T=a.match(/^\s+(['"]?\/[^'"]+['"]?):\s+['"]?([^'"]+)['"]?$/);if(T&&i==="routes"&&t.routes){let m=T[1].replace(/['"]/g,"");t.routes[m]=T[2];continue}let E=a.match(/^\s+(\w+):\s+(\d+)$/);if(E&&i==="server"&&t.server){let m=E[1],c=parseInt(E[2],10);m in{port:1,maxLogs:1,maxBatchSize:1,wsMaxSubscribers:1,pruneIntervalInserts:1,logRetentionDays:1}&&(t.server[m]=c);continue}}return t}function U(e){let t=[];if(t.push("# Sentinel Configuration"),t.push("# Auto-generated \u2014 edit freely"),t.push(""),t.push(`version: "${e.version}"`),t.push(`project: "${e.project}"`),e.environment&&t.push(`environment: "${e.environment}"`),e.symbols){t.push(""),t.push("symbols:");for(let[s,i]of Object.entries(e.symbols))if(i&&i.length>0){t.push(`  ${s}:`);for(let n of i)t.push(`    - ${n}`);}}if(e.routes&&Object.keys(e.routes).length>0){t.push(""),t.push("routes:");for(let[s,i]of Object.entries(e.routes))t.push(`  "${s}": ${i}`);}if(e.scrub){if(t.push(""),t.push("scrub:"),e.scrub.headers?.length){t.push("  headers:");for(let s of e.scrub.headers)t.push(`    - ${s}`);}if(e.scrub.fields?.length){t.push("  fields:");for(let s of e.scrub.fields)t.push(`    - ${s}`);}}if(e.server&&Object.keys(e.server).length>0){t.push(""),t.push("server:");for(let[s,i]of Object.entries(e.server))i!==void 0&&t.push(`  ${s}: ${i}`);}return t.push(""),t.join(`
`)}function z(e){let t={...C},s=e?f(e):null,i=v.join(process.env.HOME||"~",".paradigm"),n=f(i);for(let r of [n,s])r?.server&&(r.server.port!==void 0&&(t.port=r.server.port),r.server.maxLogs!==void 0&&(t.maxLogs=r.server.maxLogs),r.server.maxBatchSize!==void 0&&(t.maxBatchSize=r.server.maxBatchSize),r.server.wsMaxSubscribers!==void 0&&(t.wsMaxSubscribers=r.server.wsMaxSubscribers),r.server.pruneIntervalInserts!==void 0&&(t.pruneIntervalInserts=r.server.pruneIntervalInserts),r.server.logRetentionDays!==void 0&&(t.logRetentionDays=r.server.logRetentionDays));return process.env.SENTINEL_PORT&&(t.port=parseInt(process.env.SENTINEL_PORT,10)),process.env.SENTINEL_MAX_LOGS&&(t.maxLogs=parseInt(process.env.SENTINEL_MAX_LOGS,10)),t}var J={id:"paradigm-logger",version:"1.0.0",name:"Paradigm Logger",description:"Structured logs from @a-company/paradigm-logger with symbolic context",scope:{field:"correlationId",type:"string",label:"Correlation",ordering:"independent",sessionField:"sessionId"},eventTypes:[{type:"log:debug",category:"logs",label:"Debug Log",severity:"debug",frequency:"high",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true},{name:"durationMs",type:"number",display:true}]},{type:"log:info",category:"logs",label:"Info Log",severity:"info",frequency:"high",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true},{name:"durationMs",type:"number",display:true}]},{type:"log:warn",category:"logs",label:"Warning Log",severity:"warn",frequency:"medium",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true}]},{type:"log:error",category:"logs",label:"Error Log",severity:"error",frequency:"low",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true}]},{type:"metric:counter",category:"metrics",label:"Counter Metric",severity:"info",frequency:"high",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"metric:gauge",category:"metrics",label:"Gauge Metric",severity:"info",frequency:"medium",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"metric:histogram",category:"metrics",label:"Histogram Metric",severity:"info",frequency:"medium",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"trace:span",category:"traces",label:"Trace Span",severity:"info",frequency:"medium",fields:[{name:"traceId",type:"string",indexed:true,display:true},{name:"spanId",type:"string",indexed:true},{name:"operation",type:"string",display:true},{name:"durationMs",type:"number",display:true},{name:"status",type:"string",display:true}]},{type:"incident:recorded",category:"incidents",label:"Incident Recorded",severity:"error",frequency:"low",fields:[{name:"incidentId",type:"string",indexed:true,display:true},{name:"errorMessage",type:"string",display:true},{name:"symbols",type:"object"},{name:"environment",type:"string",display:true}]}],visualization:{defaultView:"table",categoryColors:{logs:"#3b82f6",metrics:"#22c55e",traces:"#a855f7",incidents:"#ef4444"},summaryFields:["symbol","message","service"],defaultExcluded:["log:debug"]},tags:["builtin","paradigm"]},$={id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol",scope:{field:"threadId",type:"string",label:"Thread",ordering:"independent",sessionField:"sessionId"},eventTypes:[{type:"note:question",category:"dialogue",label:"Question",severity:"info",frequency:"high",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:context",category:"dialogue",label:"Context",severity:"info",frequency:"high",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:clarification",category:"dialogue",label:"Clarification",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:verification",category:"dialogue",label:"Verification",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:reference",category:"dialogue",label:"Reference",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:proposal",category:"action",label:"Proposal",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"diff",type:"string"},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:action",category:"action",label:"Action",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"diff",type:"string"},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:decision",category:"outcome",label:"Decision",severity:"warn",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"decision",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:approval",category:"outcome",label:"Approval",severity:"info",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"note:rejection",category:"outcome",label:"Rejection",severity:"warn",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"note:alert",category:"system",label:"Alert",severity:"error",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:handoff",category:"lifecycle",label:"Handoff",severity:"info",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"thread:created",category:"lifecycle",label:"Thread Created",severity:"info",frequency:"low",fields:[{name:"topic",type:"string",display:true},{name:"initiator",type:"string",indexed:true,display:true}]},{type:"thread:resolved",category:"lifecycle",label:"Thread Resolved",severity:"info",frequency:"low",fields:[{name:"topic",type:"string",display:true},{name:"decision",type:"string",display:true}]},{type:"participant:joined",category:"lifecycle",label:"Participant Joined",severity:"info",frequency:"low",fields:[{name:"participantId",type:"string",indexed:true,display:true},{name:"participantName",type:"string",display:true},{name:"participantRole",type:"string",display:true}]},{type:"participant:left",category:"lifecycle",label:"Participant Left",severity:"info",frequency:"low",fields:[{name:"participantId",type:"string",indexed:true,display:true},{name:"participantName",type:"string",display:true}]},{type:"file:requested",category:"transfer",label:"File Requested",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"requester",type:"string",indexed:true,display:true},{name:"reason",type:"string",display:true},{name:"urgency",type:"string",display:true}]},{type:"file:approved",category:"transfer",label:"File Approved",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"size",type:"number",display:true},{name:"hash",type:"string"}]},{type:"file:denied",category:"transfer",label:"File Denied",severity:"warn",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"reason",type:"string",display:true}]},{type:"file:delivered",category:"transfer",label:"File Delivered",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"size",type:"number",display:true},{name:"hash",type:"string"}]}],visualization:{defaultView:"tree",categoryColors:{dialogue:"#7dd3fc",action:"#86efac",outcome:"#fbbf24",system:"#f87171",lifecycle:"#a78bfa",transfer:"#34d399"},summaryFields:["sender","text","senderRole"],defaultExcluded:[]},tags:["builtin","symphony"]};export{w as a,A as b,x as c,C as d,f as e,P as f,z as g,J as h,$ as i};