@a-company/sentinel 0.2.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2624 @@
1
+ // src/storage.ts
2
+ import initSqlJs from "sql.js";
3
+ import { v4 as uuidv4 } from "uuid";
4
+ import * as path from "path";
5
+ import * as fs from "fs";
6
+ var SCHEMA_VERSION = 5;
7
+ var DEFAULT_CONFIDENCE = {
8
+ score: 50,
9
+ timesMatched: 0,
10
+ timesResolved: 0,
11
+ timesRecurred: 0
12
+ };
13
+ var SQL = null;
14
+ var SentinelStorage = class {
15
+ db = null;
16
+ dbPath;
17
+ incidentCounter = 0;
18
+ initialized = false;
19
+ constructor(dbPath) {
20
+ this.dbPath = dbPath || this.getDefaultDbPath();
21
+ }
22
+ getDefaultDbPath() {
23
+ const dataDir = process.env.SENTINEL_DATA_DIR || process.env.PARADIGM_DATA_DIR || path.join(process.cwd(), ".paradigm", "sentinel");
24
+ return path.join(dataDir, "sentinel.db");
25
+ }
26
+ createSchema() {
27
+ if (!this.db) return;
28
+ this.db.run(`
29
+ -- Metadata table for schema versioning
30
+ CREATE TABLE IF NOT EXISTS metadata (
31
+ key TEXT PRIMARY KEY,
32
+ value TEXT NOT NULL
33
+ );
34
+
35
+ -- Incidents table
36
+ CREATE TABLE IF NOT EXISTS incidents (
37
+ id TEXT PRIMARY KEY,
38
+ timestamp TEXT NOT NULL,
39
+ status TEXT NOT NULL DEFAULT 'open',
40
+ error_message TEXT NOT NULL,
41
+ error_stack TEXT,
42
+ error_code TEXT,
43
+ error_type TEXT,
44
+ symbols TEXT NOT NULL,
45
+ flow_position TEXT,
46
+ environment TEXT NOT NULL,
47
+ service TEXT,
48
+ version TEXT,
49
+ user_id TEXT,
50
+ request_id TEXT,
51
+ group_id TEXT,
52
+ notes TEXT DEFAULT '[]',
53
+ related_incidents TEXT DEFAULT '[]',
54
+ resolved_at TEXT,
55
+ resolved_by TEXT,
56
+ resolution TEXT,
57
+ created_at TEXT NOT NULL,
58
+ updated_at TEXT NOT NULL
59
+ );
60
+
61
+ -- Patterns table
62
+ CREATE TABLE IF NOT EXISTS patterns (
63
+ id TEXT PRIMARY KEY,
64
+ name TEXT NOT NULL,
65
+ description TEXT,
66
+ pattern TEXT NOT NULL,
67
+ resolution TEXT NOT NULL,
68
+ confidence TEXT NOT NULL,
69
+ source TEXT NOT NULL DEFAULT 'manual',
70
+ private INTEGER NOT NULL DEFAULT 0,
71
+ tags TEXT DEFAULT '[]',
72
+ created_at TEXT NOT NULL,
73
+ updated_at TEXT NOT NULL
74
+ );
75
+
76
+ -- Incident groups
77
+ CREATE TABLE IF NOT EXISTS groups (
78
+ id TEXT PRIMARY KEY,
79
+ name TEXT,
80
+ common_symbols TEXT,
81
+ common_error_patterns TEXT,
82
+ suggested_pattern_id TEXT,
83
+ first_seen TEXT NOT NULL,
84
+ last_seen TEXT NOT NULL,
85
+ created_at TEXT NOT NULL,
86
+ updated_at TEXT NOT NULL
87
+ );
88
+
89
+ -- Group members
90
+ CREATE TABLE IF NOT EXISTS group_members (
91
+ group_id TEXT NOT NULL,
92
+ incident_id TEXT NOT NULL,
93
+ added_at TEXT NOT NULL,
94
+ PRIMARY KEY (group_id, incident_id)
95
+ );
96
+
97
+ -- Resolutions history
98
+ CREATE TABLE IF NOT EXISTS resolutions (
99
+ id TEXT PRIMARY KEY,
100
+ incident_id TEXT NOT NULL,
101
+ pattern_id TEXT,
102
+ commit_hash TEXT,
103
+ pr_url TEXT,
104
+ notes TEXT,
105
+ resolved_at TEXT NOT NULL,
106
+ recurred INTEGER DEFAULT 0
107
+ );
108
+
109
+ -- Practice events (habits system)
110
+ CREATE TABLE IF NOT EXISTS practice_events (
111
+ id TEXT PRIMARY KEY,
112
+ timestamp TEXT NOT NULL,
113
+ habit_id TEXT NOT NULL,
114
+ habit_category TEXT NOT NULL,
115
+ result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
116
+ engineer TEXT NOT NULL,
117
+ session_id TEXT NOT NULL,
118
+ lore_entry_id TEXT,
119
+ task_description TEXT,
120
+ symbols_touched TEXT DEFAULT '[]',
121
+ files_modified TEXT DEFAULT '[]',
122
+ related_incident_id TEXT,
123
+ notes TEXT
124
+ );
125
+
126
+ -- Structured logs table
127
+ CREATE TABLE IF NOT EXISTS logs (
128
+ id TEXT PRIMARY KEY,
129
+ timestamp TEXT NOT NULL,
130
+ level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
131
+ symbol TEXT NOT NULL,
132
+ symbol_type TEXT NOT NULL DEFAULT 'raw',
133
+ message TEXT NOT NULL,
134
+ data_json TEXT,
135
+ service TEXT NOT NULL,
136
+ session_id TEXT,
137
+ correlation_id TEXT,
138
+ duration_ms REAL,
139
+ environment TEXT
140
+ );
141
+
142
+ -- Service registry
143
+ CREATE TABLE IF NOT EXISTS services (
144
+ name TEXT PRIMARY KEY,
145
+ version TEXT,
146
+ pid INTEGER,
147
+ started_at TEXT NOT NULL,
148
+ last_seen_at TEXT NOT NULL,
149
+ environment TEXT,
150
+ metadata_json TEXT
151
+ );
152
+
153
+ -- Live app state snapshots (latest-wins per service+session)
154
+ CREATE TABLE IF NOT EXISTS app_state (
155
+ service TEXT NOT NULL,
156
+ session_id TEXT NOT NULL,
157
+ timestamp TEXT NOT NULL,
158
+ state_json TEXT NOT NULL,
159
+ active_flows_json TEXT,
160
+ active_gates_json TEXT,
161
+ PRIMARY KEY (service, session_id)
162
+ );
163
+
164
+ -- Metrics table
165
+ CREATE TABLE IF NOT EXISTS metrics (
166
+ id TEXT PRIMARY KEY,
167
+ timestamp TEXT NOT NULL,
168
+ name TEXT NOT NULL,
169
+ type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
170
+ value REAL NOT NULL,
171
+ tags_json TEXT DEFAULT '{}',
172
+ service TEXT NOT NULL,
173
+ environment TEXT
174
+ );
175
+
176
+ -- Traces table
177
+ CREATE TABLE IF NOT EXISTS traces (
178
+ trace_id TEXT NOT NULL,
179
+ span_id TEXT PRIMARY KEY,
180
+ parent_span_id TEXT,
181
+ service TEXT NOT NULL,
182
+ symbol TEXT NOT NULL,
183
+ operation TEXT NOT NULL,
184
+ start_time TEXT NOT NULL,
185
+ end_time TEXT,
186
+ duration_ms REAL,
187
+ status TEXT NOT NULL DEFAULT 'ok',
188
+ tags_json TEXT DEFAULT '{}',
189
+ log_ids_json TEXT DEFAULT '[]'
190
+ );
191
+
192
+ -- Indexes
193
+ CREATE INDEX IF NOT EXISTS idx_incidents_timestamp ON incidents(timestamp);
194
+ CREATE INDEX IF NOT EXISTS idx_incidents_status ON incidents(status);
195
+ CREATE INDEX IF NOT EXISTS idx_incidents_environment ON incidents(environment);
196
+ CREATE INDEX IF NOT EXISTS idx_patterns_source ON patterns(source);
197
+ CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
198
+ CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
199
+ CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
200
+ CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
201
+ CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
202
+ CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
203
+ CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
204
+ CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
205
+ CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
206
+ CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
207
+ CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
208
+ CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
209
+ CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
210
+ CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
211
+ CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
212
+ CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
213
+ `);
214
+ this.db.run(
215
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', ?)",
216
+ [String(SCHEMA_VERSION)]
217
+ );
218
+ }
219
+ save() {
220
+ if (!this.db) return;
221
+ const data = this.db.export();
222
+ const buffer = Buffer.from(data);
223
+ fs.writeFileSync(this.dbPath, buffer);
224
+ }
225
+ // ─── Incidents ───────────────────────────────────────────────────
226
+ recordIncident(input) {
227
+ const db = this.db;
228
+ if (!db) {
229
+ this.initializeSync();
230
+ }
231
+ this.incidentCounter++;
232
+ const id = `INC-${String(this.incidentCounter).padStart(3, "0")}`;
233
+ const now = (/* @__PURE__ */ new Date()).toISOString();
234
+ this.db.run(
235
+ `INSERT INTO incidents (
236
+ id, timestamp, status, error_message, error_stack, error_code, error_type,
237
+ symbols, flow_position, environment, service, version, user_id, request_id,
238
+ group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
239
+ created_at, updated_at
240
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
241
+ [
242
+ id,
243
+ input.timestamp || now,
244
+ input.status || "open",
245
+ input.error.message,
246
+ input.error.stack || null,
247
+ input.error.code || null,
248
+ input.error.type || null,
249
+ JSON.stringify(input.symbols),
250
+ input.flowPosition ? JSON.stringify(input.flowPosition) : null,
251
+ input.environment,
252
+ input.service || null,
253
+ input.version || null,
254
+ input.userId || null,
255
+ input.requestId || null,
256
+ input.groupId || null,
257
+ "[]",
258
+ "[]",
259
+ input.resolvedAt || null,
260
+ input.resolvedBy || null,
261
+ input.resolution ? JSON.stringify(input.resolution) : null,
262
+ now,
263
+ now
264
+ ]
265
+ );
266
+ this.save();
267
+ return id;
268
+ }
269
+ initializeSync() {
270
+ if (this.initialized && this.db) return;
271
+ if (!this.db && SQL) {
272
+ const dir = path.dirname(this.dbPath);
273
+ if (!fs.existsSync(dir)) {
274
+ fs.mkdirSync(dir, { recursive: true });
275
+ }
276
+ if (fs.existsSync(this.dbPath)) {
277
+ const fileData = fs.readFileSync(this.dbPath);
278
+ this.db = new SQL.Database(fileData);
279
+ } else {
280
+ this.db = new SQL.Database();
281
+ this.createSchema();
282
+ }
283
+ try {
284
+ const result = this.db.exec(
285
+ "SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents"
286
+ );
287
+ if (result.length > 0 && result[0].values.length > 0 && result[0].values[0][0]) {
288
+ this.incidentCounter = result[0].values[0][0];
289
+ }
290
+ } catch {
291
+ this.incidentCounter = 0;
292
+ }
293
+ this.migrateSchema();
294
+ this.initialized = true;
295
+ this.save();
296
+ }
297
+ }
298
+ /**
299
+ * Run schema migrations from older versions
300
+ */
301
+ migrateSchema() {
302
+ if (!this.db) return;
303
+ let currentVersion = 1;
304
+ try {
305
+ const result = this.db.exec(
306
+ "SELECT value FROM metadata WHERE key = 'schema_version'"
307
+ );
308
+ if (result.length > 0 && result[0].values.length > 0) {
309
+ currentVersion = parseInt(result[0].values[0][0], 10) || 1;
310
+ }
311
+ } catch {
312
+ }
313
+ if (currentVersion < 2) {
314
+ try {
315
+ this.db.run(`
316
+ CREATE TABLE IF NOT EXISTS practice_events (
317
+ id TEXT PRIMARY KEY,
318
+ timestamp TEXT NOT NULL,
319
+ habit_id TEXT NOT NULL,
320
+ habit_category TEXT NOT NULL,
321
+ result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
322
+ engineer TEXT NOT NULL,
323
+ session_id TEXT NOT NULL,
324
+ lore_entry_id TEXT,
325
+ task_description TEXT,
326
+ symbols_touched TEXT DEFAULT '[]',
327
+ files_modified TEXT DEFAULT '[]',
328
+ related_incident_id TEXT,
329
+ notes TEXT
330
+ );
331
+
332
+ CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
333
+ CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
334
+ CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
335
+ CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
336
+ `);
337
+ } catch {
338
+ }
339
+ this.db.run(
340
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '2')"
341
+ );
342
+ currentVersion = 2;
343
+ }
344
+ if (currentVersion < 3) {
345
+ try {
346
+ this.db.run(`
347
+ CREATE TABLE IF NOT EXISTS logs (
348
+ id TEXT PRIMARY KEY,
349
+ timestamp TEXT NOT NULL,
350
+ level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
351
+ symbol TEXT NOT NULL,
352
+ symbol_type TEXT NOT NULL DEFAULT 'raw',
353
+ message TEXT NOT NULL,
354
+ data_json TEXT,
355
+ service TEXT NOT NULL,
356
+ session_id TEXT,
357
+ correlation_id TEXT,
358
+ duration_ms REAL,
359
+ environment TEXT
360
+ );
361
+
362
+ CREATE TABLE IF NOT EXISTS services (
363
+ name TEXT PRIMARY KEY,
364
+ version TEXT,
365
+ pid INTEGER,
366
+ started_at TEXT NOT NULL,
367
+ last_seen_at TEXT NOT NULL,
368
+ environment TEXT,
369
+ metadata_json TEXT
370
+ );
371
+
372
+ CREATE TABLE IF NOT EXISTS app_state (
373
+ service TEXT NOT NULL,
374
+ session_id TEXT NOT NULL,
375
+ timestamp TEXT NOT NULL,
376
+ state_json TEXT NOT NULL,
377
+ active_flows_json TEXT,
378
+ active_gates_json TEXT,
379
+ PRIMARY KEY (service, session_id)
380
+ );
381
+
382
+ CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
383
+ CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
384
+ CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
385
+ CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
386
+ CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
387
+ CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
388
+ `);
389
+ } catch {
390
+ }
391
+ this.db.run(
392
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '3')"
393
+ );
394
+ currentVersion = 3;
395
+ }
396
+ if (currentVersion < 4) {
397
+ try {
398
+ this.db.run(`
399
+ CREATE TABLE IF NOT EXISTS metrics (
400
+ id TEXT PRIMARY KEY,
401
+ timestamp TEXT NOT NULL,
402
+ name TEXT NOT NULL,
403
+ type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
404
+ value REAL NOT NULL,
405
+ tags_json TEXT DEFAULT '{}',
406
+ service TEXT NOT NULL,
407
+ environment TEXT
408
+ );
409
+
410
+ CREATE TABLE IF NOT EXISTS traces (
411
+ trace_id TEXT NOT NULL,
412
+ span_id TEXT PRIMARY KEY,
413
+ parent_span_id TEXT,
414
+ service TEXT NOT NULL,
415
+ symbol TEXT NOT NULL,
416
+ operation TEXT NOT NULL,
417
+ start_time TEXT NOT NULL,
418
+ end_time TEXT,
419
+ duration_ms REAL,
420
+ status TEXT NOT NULL DEFAULT 'ok',
421
+ tags_json TEXT DEFAULT '{}',
422
+ log_ids_json TEXT DEFAULT '[]'
423
+ );
424
+
425
+ CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
426
+ CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
427
+ CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
428
+ CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
429
+ CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
430
+ CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
431
+ `);
432
+ } catch {
433
+ }
434
+ this.db.run(
435
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '4')"
436
+ );
437
+ currentVersion = 4;
438
+ }
439
+ if (currentVersion < 5) {
440
+ try {
441
+ this.db.run(`
442
+ CREATE TABLE IF NOT EXISTS schemas (
443
+ id TEXT PRIMARY KEY,
444
+ version TEXT NOT NULL,
445
+ name TEXT NOT NULL,
446
+ description TEXT,
447
+ scope_json TEXT NOT NULL,
448
+ event_types_json TEXT NOT NULL,
449
+ causality_json TEXT,
450
+ visualization_json TEXT,
451
+ tags_json TEXT DEFAULT '[]',
452
+ registered_at TEXT NOT NULL,
453
+ updated_at TEXT NOT NULL
454
+ );
455
+
456
+ CREATE TABLE IF NOT EXISTS events (
457
+ id TEXT PRIMARY KEY,
458
+ schema_id TEXT NOT NULL,
459
+ event_type TEXT NOT NULL,
460
+ category TEXT NOT NULL,
461
+ timestamp TEXT NOT NULL,
462
+ scope_value TEXT,
463
+ scope_ordinal INTEGER,
464
+ session_id TEXT,
465
+ service TEXT NOT NULL,
466
+ data_json TEXT,
467
+ severity TEXT DEFAULT 'info',
468
+ parent_event_id TEXT,
469
+ depth INTEGER DEFAULT 0
470
+ );
471
+
472
+ CREATE INDEX IF NOT EXISTS idx_events_schema ON events(schema_id);
473
+ CREATE INDEX IF NOT EXISTS idx_events_type ON events(event_type);
474
+ CREATE INDEX IF NOT EXISTS idx_events_scope ON events(schema_id, scope_value);
475
+ CREATE INDEX IF NOT EXISTS idx_events_scope_ord ON events(schema_id, scope_ordinal);
476
+ CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
477
+ CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
478
+ CREATE INDEX IF NOT EXISTS idx_events_service ON events(service);
479
+ `);
480
+ } catch {
481
+ }
482
+ this.db.run(
483
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '5')"
484
+ );
485
+ }
486
+ }
487
+ /**
488
+ * Ensure the storage is ready for use. Must be called once before using storage methods.
489
+ */
490
+ async ensureReady() {
491
+ if (!SQL) {
492
+ SQL = await initSqlJs();
493
+ }
494
+ this.initializeSync();
495
+ }
496
+ getIncident(id) {
497
+ this.initializeSync();
498
+ const result = this.db.exec("SELECT * FROM incidents WHERE id = ?", [id]);
499
+ if (result.length === 0 || result[0].values.length === 0) return null;
500
+ return this.rowToIncident(result[0].columns, result[0].values[0]);
501
+ }
502
+ getRecentIncidents(options = {}) {
503
+ this.initializeSync();
504
+ const { limit = 50, offset = 0 } = options;
505
+ const conditions = [];
506
+ const params = [];
507
+ if (options.status && options.status !== "all") {
508
+ conditions.push("status = ?");
509
+ params.push(options.status);
510
+ }
511
+ if (options.environment) {
512
+ conditions.push("environment = ?");
513
+ params.push(options.environment);
514
+ }
515
+ if (options.symbol) {
516
+ conditions.push("symbols LIKE ?");
517
+ params.push(`%${options.symbol}%`);
518
+ }
519
+ if (options.search) {
520
+ conditions.push("(error_message LIKE ? OR notes LIKE ?)");
521
+ params.push(`%${options.search}%`, `%${options.search}%`);
522
+ }
523
+ if (options.dateFrom) {
524
+ conditions.push("timestamp >= ?");
525
+ params.push(options.dateFrom);
526
+ }
527
+ if (options.dateTo) {
528
+ conditions.push("timestamp <= ?");
529
+ params.push(options.dateTo);
530
+ }
531
+ if (options.groupId) {
532
+ conditions.push("group_id = ?");
533
+ params.push(options.groupId);
534
+ }
535
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
536
+ const result = this.db.exec(
537
+ `SELECT * FROM incidents ${whereClause} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,
538
+ [...params, limit, offset]
539
+ );
540
+ if (result.length === 0) return [];
541
+ return result[0].values.map(
542
+ (row) => this.rowToIncident(result[0].columns, row)
543
+ );
544
+ }
545
+ updateIncident(id, updates) {
546
+ this.initializeSync();
547
+ const now = (/* @__PURE__ */ new Date()).toISOString();
548
+ const setClauses = ["updated_at = ?"];
549
+ const params = [now];
550
+ if (updates.status !== void 0) {
551
+ setClauses.push("status = ?");
552
+ params.push(updates.status);
553
+ }
554
+ if (updates.error !== void 0) {
555
+ setClauses.push("error_message = ?");
556
+ params.push(updates.error.message);
557
+ if (updates.error.stack !== void 0) {
558
+ setClauses.push("error_stack = ?");
559
+ params.push(updates.error.stack || null);
560
+ }
561
+ }
562
+ if (updates.symbols !== void 0) {
563
+ setClauses.push("symbols = ?");
564
+ params.push(JSON.stringify(updates.symbols));
565
+ }
566
+ if (updates.flowPosition !== void 0) {
567
+ setClauses.push("flow_position = ?");
568
+ params.push(
569
+ updates.flowPosition ? JSON.stringify(updates.flowPosition) : null
570
+ );
571
+ }
572
+ if (updates.groupId !== void 0) {
573
+ setClauses.push("group_id = ?");
574
+ params.push(updates.groupId || null);
575
+ }
576
+ if (updates.resolvedAt !== void 0) {
577
+ setClauses.push("resolved_at = ?");
578
+ params.push(updates.resolvedAt || null);
579
+ }
580
+ if (updates.resolvedBy !== void 0) {
581
+ setClauses.push("resolved_by = ?");
582
+ params.push(updates.resolvedBy || null);
583
+ }
584
+ if (updates.resolution !== void 0) {
585
+ setClauses.push("resolution = ?");
586
+ params.push(
587
+ updates.resolution ? JSON.stringify(updates.resolution) : null
588
+ );
589
+ }
590
+ params.push(id);
591
+ this.db.run(
592
+ `UPDATE incidents SET ${setClauses.join(", ")} WHERE id = ?`,
593
+ params
594
+ );
595
+ this.save();
596
+ }
597
+ addIncidentNote(incidentId, note) {
598
+ this.initializeSync();
599
+ const incident = this.getIncident(incidentId);
600
+ if (!incident) return;
601
+ const newNote = {
602
+ id: uuidv4(),
603
+ ...note
604
+ };
605
+ const notes = [...incident.notes, newNote];
606
+ this.db.run(
607
+ "UPDATE incidents SET notes = ?, updated_at = ? WHERE id = ?",
608
+ [JSON.stringify(notes), (/* @__PURE__ */ new Date()).toISOString(), incidentId]
609
+ );
610
+ this.save();
611
+ }
612
+ linkIncidents(incidentId, relatedId) {
613
+ this.initializeSync();
614
+ const incident = this.getIncident(incidentId);
615
+ if (!incident) return;
616
+ if (!incident.relatedIncidents.includes(relatedId)) {
617
+ const related = [...incident.relatedIncidents, relatedId];
618
+ this.db.run(
619
+ "UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",
620
+ [JSON.stringify(related), (/* @__PURE__ */ new Date()).toISOString(), incidentId]
621
+ );
622
+ }
623
+ const relatedIncident = this.getIncident(relatedId);
624
+ if (relatedIncident && !relatedIncident.relatedIncidents.includes(incidentId)) {
625
+ const related = [...relatedIncident.relatedIncidents, incidentId];
626
+ this.db.run(
627
+ "UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",
628
+ [JSON.stringify(related), (/* @__PURE__ */ new Date()).toISOString(), relatedId]
629
+ );
630
+ }
631
+ this.save();
632
+ }
633
+ getIncidentCount(options = {}) {
634
+ this.initializeSync();
635
+ const conditions = [];
636
+ const params = [];
637
+ if (options.status && options.status !== "all") {
638
+ conditions.push("status = ?");
639
+ params.push(options.status);
640
+ }
641
+ if (options.environment) {
642
+ conditions.push("environment = ?");
643
+ params.push(options.environment);
644
+ }
645
+ if (options.dateFrom) {
646
+ conditions.push("timestamp >= ?");
647
+ params.push(options.dateFrom);
648
+ }
649
+ if (options.dateTo) {
650
+ conditions.push("timestamp <= ?");
651
+ params.push(options.dateTo);
652
+ }
653
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
654
+ const result = this.db.exec(
655
+ `SELECT COUNT(*) as count FROM incidents ${whereClause}`,
656
+ params
657
+ );
658
+ if (result.length === 0 || result[0].values.length === 0) return 0;
659
+ return result[0].values[0][0];
660
+ }
661
+ // ─── Patterns ────────────────────────────────────────────────────
662
+ addPattern(input) {
663
+ this.initializeSync();
664
+ const now = (/* @__PURE__ */ new Date()).toISOString();
665
+ const confidence = {
666
+ ...DEFAULT_CONFIDENCE,
667
+ ...input.confidence
668
+ };
669
+ this.db.run(
670
+ `INSERT INTO patterns (
671
+ id, name, description, pattern, resolution, confidence,
672
+ source, private, tags, created_at, updated_at
673
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
674
+ [
675
+ input.id,
676
+ input.name,
677
+ input.description || null,
678
+ JSON.stringify(input.pattern),
679
+ JSON.stringify(input.resolution),
680
+ JSON.stringify(confidence),
681
+ input.source,
682
+ input.private ? 1 : 0,
683
+ JSON.stringify(input.tags || []),
684
+ now,
685
+ now
686
+ ]
687
+ );
688
+ this.save();
689
+ return input.id;
690
+ }
691
+ getPattern(id) {
692
+ this.initializeSync();
693
+ const result = this.db.exec("SELECT * FROM patterns WHERE id = ?", [id]);
694
+ if (result.length === 0 || result[0].values.length === 0) return null;
695
+ return this.rowToPattern(result[0].columns, result[0].values[0]);
696
+ }
697
+ getAllPatterns(options = {}) {
698
+ this.initializeSync();
699
+ const conditions = [];
700
+ const params = [];
701
+ if (options.source) {
702
+ conditions.push("source = ?");
703
+ params.push(options.source);
704
+ }
705
+ if (options.minConfidence !== void 0) {
706
+ conditions.push("json_extract(confidence, '$.score') >= ?");
707
+ params.push(options.minConfidence);
708
+ }
709
+ if (!options.includePrivate) {
710
+ conditions.push("private = 0");
711
+ }
712
+ if (options.tags && options.tags.length > 0) {
713
+ const tagConditions = options.tags.map(() => "tags LIKE ?");
714
+ conditions.push(`(${tagConditions.join(" OR ")})`);
715
+ params.push(...options.tags.map((tag) => `%"${tag}"%`));
716
+ }
717
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
718
+ const result = this.db.exec(
719
+ `SELECT * FROM patterns ${whereClause} ORDER BY json_extract(confidence, '$.score') DESC`,
720
+ params
721
+ );
722
+ if (result.length === 0) return [];
723
+ return result[0].values.map(
724
+ (row) => this.rowToPattern(result[0].columns, row)
725
+ );
726
+ }
727
+ updatePattern(id, updates) {
728
+ this.initializeSync();
729
+ const now = (/* @__PURE__ */ new Date()).toISOString();
730
+ const setClauses = ["updated_at = ?"];
731
+ const params = [now];
732
+ if (updates.name !== void 0) {
733
+ setClauses.push("name = ?");
734
+ params.push(updates.name);
735
+ }
736
+ if (updates.description !== void 0) {
737
+ setClauses.push("description = ?");
738
+ params.push(updates.description || null);
739
+ }
740
+ if (updates.pattern !== void 0) {
741
+ setClauses.push("pattern = ?");
742
+ params.push(JSON.stringify(updates.pattern));
743
+ }
744
+ if (updates.resolution !== void 0) {
745
+ setClauses.push("resolution = ?");
746
+ params.push(JSON.stringify(updates.resolution));
747
+ }
748
+ if (updates.confidence !== void 0) {
749
+ setClauses.push("confidence = ?");
750
+ params.push(JSON.stringify(updates.confidence));
751
+ }
752
+ if (updates.source !== void 0) {
753
+ setClauses.push("source = ?");
754
+ params.push(updates.source);
755
+ }
756
+ if (updates.private !== void 0) {
757
+ setClauses.push("private = ?");
758
+ params.push(updates.private ? 1 : 0);
759
+ }
760
+ if (updates.tags !== void 0) {
761
+ setClauses.push("tags = ?");
762
+ params.push(JSON.stringify(updates.tags));
763
+ }
764
+ params.push(id);
765
+ this.db.run(
766
+ `UPDATE patterns SET ${setClauses.join(", ")} WHERE id = ?`,
767
+ params
768
+ );
769
+ this.save();
770
+ }
771
+ deletePattern(id) {
772
+ this.initializeSync();
773
+ this.db.run("DELETE FROM patterns WHERE id = ?", [id]);
774
+ this.save();
775
+ }
776
+ updatePatternConfidence(patternId, event) {
777
+ const pattern = this.getPattern(patternId);
778
+ if (!pattern) return;
779
+ const now = (/* @__PURE__ */ new Date()).toISOString();
780
+ const confidence = { ...pattern.confidence };
781
+ switch (event) {
782
+ case "matched":
783
+ confidence.timesMatched++;
784
+ confidence.lastMatched = now;
785
+ break;
786
+ case "resolved":
787
+ confidence.timesResolved++;
788
+ confidence.lastResolved = now;
789
+ confidence.score = Math.min(100, confidence.score + 2);
790
+ break;
791
+ case "recurred":
792
+ confidence.timesRecurred++;
793
+ confidence.score = Math.max(10, confidence.score - 5);
794
+ break;
795
+ }
796
+ this.updatePattern(patternId, { confidence });
797
+ }
798
+ // ─── Groups ──────────────────────────────────────────────────────
799
+ createGroup(input) {
800
+ this.initializeSync();
801
+ const id = `GRP-${uuidv4().substring(0, 8)}`;
802
+ const now = (/* @__PURE__ */ new Date()).toISOString();
803
+ this.db.run(
804
+ `INSERT INTO groups (
805
+ id, name, common_symbols, common_error_patterns,
806
+ suggested_pattern_id, first_seen, last_seen, created_at, updated_at
807
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
808
+ [
809
+ id,
810
+ input.name || null,
811
+ JSON.stringify(input.commonSymbols),
812
+ JSON.stringify(input.commonErrorPatterns),
813
+ input.suggestedPattern?.id || null,
814
+ input.firstSeen,
815
+ input.lastSeen,
816
+ now,
817
+ now
818
+ ]
819
+ );
820
+ for (const incidentId of input.incidents) {
821
+ this.addToGroup(id, incidentId);
822
+ }
823
+ this.save();
824
+ return id;
825
+ }
826
+ getGroup(id) {
827
+ this.initializeSync();
828
+ const result = this.db.exec("SELECT * FROM groups WHERE id = ?", [id]);
829
+ if (result.length === 0 || result[0].values.length === 0) return null;
830
+ return this.rowToGroup(result[0].columns, result[0].values[0]);
831
+ }
832
+ getGroups(options = {}) {
833
+ this.initializeSync();
834
+ const limit = options.limit || 100;
835
+ const result = this.db.exec(
836
+ "SELECT * FROM groups ORDER BY last_seen DESC LIMIT ?",
837
+ [limit]
838
+ );
839
+ if (result.length === 0) return [];
840
+ return result[0].values.map(
841
+ (row) => this.rowToGroup(result[0].columns, row)
842
+ );
843
+ }
844
+ addToGroup(groupId, incidentId) {
845
+ this.initializeSync();
846
+ const now = (/* @__PURE__ */ new Date()).toISOString();
847
+ this.db.run(
848
+ "INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",
849
+ [groupId, incidentId, now]
850
+ );
851
+ this.db.run("UPDATE incidents SET group_id = ? WHERE id = ?", [
852
+ groupId,
853
+ incidentId
854
+ ]);
855
+ this.db.run(
856
+ "UPDATE groups SET last_seen = ?, updated_at = ? WHERE id = ?",
857
+ [now, now, groupId]
858
+ );
859
+ this.save();
860
+ }
861
+ // ─── Resolutions ─────────────────────────────────────────────────
862
+ recordResolution(resolution) {
863
+ this.initializeSync();
864
+ const id = uuidv4();
865
+ const now = (/* @__PURE__ */ new Date()).toISOString();
866
+ this.db.run(
867
+ `INSERT INTO resolutions (id, incident_id, pattern_id, commit_hash, pr_url, notes, resolved_at)
868
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
869
+ [
870
+ id,
871
+ resolution.incidentId,
872
+ resolution.patternId || null,
873
+ resolution.commitHash || null,
874
+ resolution.prUrl || null,
875
+ resolution.notes || null,
876
+ now
877
+ ]
878
+ );
879
+ this.updateIncident(resolution.incidentId, {
880
+ status: "resolved",
881
+ resolvedAt: now,
882
+ resolvedBy: resolution.patternId || "manual",
883
+ resolution: {
884
+ patternId: resolution.patternId,
885
+ commitHash: resolution.commitHash,
886
+ prUrl: resolution.prUrl,
887
+ notes: resolution.notes
888
+ }
889
+ });
890
+ if (resolution.patternId) {
891
+ this.updatePatternConfidence(resolution.patternId, "resolved");
892
+ }
893
+ this.save();
894
+ }
895
+ markRecurred(incidentId) {
896
+ this.initializeSync();
897
+ this.db.run(
898
+ "UPDATE resolutions SET recurred = 1 WHERE incident_id = ?",
899
+ [incidentId]
900
+ );
901
+ const result = this.db.exec(
902
+ "SELECT pattern_id FROM resolutions WHERE incident_id = ?",
903
+ [incidentId]
904
+ );
905
+ if (result.length > 0 && result[0].values.length > 0 && result[0].values[0][0]) {
906
+ this.updatePatternConfidence(result[0].values[0][0], "recurred");
907
+ }
908
+ this.save();
909
+ }
910
+ getResolutionHistory(options = {}) {
911
+ this.initializeSync();
912
+ const conditions = [];
913
+ const params = [];
914
+ if (options.patternId) {
915
+ conditions.push("pattern_id = ?");
916
+ params.push(options.patternId);
917
+ }
918
+ if (options.symbol) {
919
+ conditions.push(`incident_id IN (
920
+ SELECT id FROM incidents WHERE symbols LIKE ?
921
+ )`);
922
+ params.push(`%${options.symbol}%`);
923
+ }
924
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
925
+ const limit = options.limit || 100;
926
+ const result = this.db.exec(
927
+ `SELECT * FROM resolutions ${whereClause} ORDER BY resolved_at DESC LIMIT ?`,
928
+ [...params, limit]
929
+ );
930
+ if (result.length === 0) return [];
931
+ const columns = result[0].columns;
932
+ return result[0].values.map((row) => {
933
+ const obj = {};
934
+ columns.forEach((col, i) => {
935
+ obj[col] = row[i];
936
+ });
937
+ return {
938
+ id: obj.id,
939
+ incidentId: obj.incident_id,
940
+ patternId: obj.pattern_id || void 0,
941
+ commitHash: obj.commit_hash || void 0,
942
+ prUrl: obj.pr_url || void 0,
943
+ notes: obj.notes || void 0,
944
+ resolvedAt: obj.resolved_at,
945
+ recurred: obj.recurred === 1
946
+ };
947
+ });
948
+ }
949
+ // ─── Stats ───────────────────────────────────────────────────────
950
+ getStats(period) {
951
+ this.initializeSync();
952
+ const { start, end } = period;
953
+ const total = this.getIncidentCount({ dateFrom: start, dateTo: end });
954
+ const open = this.getIncidentCount({
955
+ dateFrom: start,
956
+ dateTo: end,
957
+ status: "open"
958
+ });
959
+ const resolved = this.getIncidentCount({
960
+ dateFrom: start,
961
+ dateTo: end,
962
+ status: "resolved"
963
+ });
964
+ const envResult = this.db.exec(
965
+ `SELECT environment, COUNT(*) as count
966
+ FROM incidents
967
+ WHERE timestamp >= ? AND timestamp <= ?
968
+ GROUP BY environment`,
969
+ [start, end]
970
+ );
971
+ const byEnvironment = {};
972
+ if (envResult.length > 0) {
973
+ for (const row of envResult[0].values) {
974
+ byEnvironment[row[0]] = row[1];
975
+ }
976
+ }
977
+ const dayResult = this.db.exec(
978
+ `SELECT DATE(timestamp) as date, COUNT(*) as count
979
+ FROM incidents
980
+ WHERE timestamp >= ? AND timestamp <= ?
981
+ GROUP BY DATE(timestamp)
982
+ ORDER BY date`,
983
+ [start, end]
984
+ );
985
+ const byDay = [];
986
+ if (dayResult.length > 0) {
987
+ for (const row of dayResult[0].values) {
988
+ byDay.push({ date: row[0], count: row[1] });
989
+ }
990
+ }
991
+ const patterns = this.getAllPatterns({ includePrivate: true });
992
+ const avgConfidence = patterns.length > 0 ? patterns.reduce((sum, p) => sum + p.confidence.score, 0) / patterns.length : 0;
993
+ const mostEffective = patterns.sort((a, b) => b.confidence.timesResolved - a.confidence.timesResolved).slice(0, 5).map((p) => ({ patternId: p.id, resolvedCount: p.confidence.timesResolved }));
994
+ const leastEffective = patterns.filter((p) => p.confidence.timesMatched > 0).map((p) => ({
995
+ patternId: p.id,
996
+ recurrenceRate: p.confidence.timesRecurred / Math.max(1, p.confidence.timesResolved)
997
+ })).sort((a, b) => b.recurrenceRate - a.recurrenceRate).slice(0, 5);
998
+ const symbolCounts = /* @__PURE__ */ new Map();
999
+ const incidents = this.getRecentIncidents({
1000
+ dateFrom: start,
1001
+ dateTo: end,
1002
+ limit: 1e3
1003
+ });
1004
+ for (const incident of incidents) {
1005
+ for (const [, value] of Object.entries(incident.symbols)) {
1006
+ if (value) {
1007
+ symbolCounts.set(value, (symbolCounts.get(value) || 0) + 1);
1008
+ }
1009
+ }
1010
+ }
1011
+ const mostIncidents = Array.from(symbolCounts.entries()).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([symbol, count]) => ({ symbol, count }));
1012
+ const resolutions = this.getResolutionHistory({ limit: 1e3 });
1013
+ const periodResolutions = resolutions.filter(
1014
+ (r) => r.resolvedAt >= start && r.resolvedAt <= end
1015
+ );
1016
+ const resolvedWithPattern = periodResolutions.filter(
1017
+ (r) => r.patternId
1018
+ ).length;
1019
+ const resolvedManually = periodResolutions.length - resolvedWithPattern;
1020
+ return {
1021
+ period: { start, end },
1022
+ incidents: {
1023
+ total,
1024
+ open,
1025
+ resolved,
1026
+ byEnvironment,
1027
+ byDay
1028
+ },
1029
+ patterns: {
1030
+ total: patterns.length,
1031
+ avgConfidence: Math.round(avgConfidence),
1032
+ mostEffective,
1033
+ leastEffective
1034
+ },
1035
+ symbols: {
1036
+ mostIncidents,
1037
+ mostResolved: [],
1038
+ hotspots: mostIncidents.slice(0, 5).map((s) => ({
1039
+ symbol: s.symbol,
1040
+ incidentRate: s.count / Math.max(1, total)
1041
+ }))
1042
+ },
1043
+ resolution: {
1044
+ avgTimeToResolve: 0,
1045
+ resolvedWithPattern,
1046
+ resolvedManually,
1047
+ resolutionRate: total > 0 ? resolved / total * 100 : 0
1048
+ }
1049
+ };
1050
+ }
1051
+ getSymbolHealth(symbol) {
1052
+ const incidents = this.getRecentIncidents({ symbol, limit: 1e3 });
1053
+ const incidentCount = incidents.length;
1054
+ const patternCounts = /* @__PURE__ */ new Map();
1055
+ for (const incident of incidents) {
1056
+ if (incident.resolution?.patternId) {
1057
+ const count = patternCounts.get(incident.resolution.patternId) || 0;
1058
+ patternCounts.set(incident.resolution.patternId, count + 1);
1059
+ }
1060
+ }
1061
+ const topPatterns = Array.from(patternCounts.entries()).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([patternId, count]) => ({ patternId, count }));
1062
+ return {
1063
+ incidentCount,
1064
+ avgTimeToResolve: 0,
1065
+ topPatterns
1066
+ };
1067
+ }
1068
+ // ─── Import/Export ───────────────────────────────────────────────
1069
+ exportPatterns(options = {}) {
1070
+ const patterns = this.getAllPatterns({
1071
+ includePrivate: options.includePrivate
1072
+ });
1073
+ return {
1074
+ version: "1.0.0",
1075
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1076
+ patterns
1077
+ };
1078
+ }
1079
+ importPatterns(data, options = {}) {
1080
+ let imported = 0;
1081
+ let skipped = 0;
1082
+ for (const pattern of data.patterns) {
1083
+ const existing = this.getPattern(pattern.id);
1084
+ if (existing && !options.overwrite) {
1085
+ skipped++;
1086
+ continue;
1087
+ }
1088
+ if (existing) {
1089
+ this.updatePattern(pattern.id, pattern);
1090
+ } else {
1091
+ this.addPattern({
1092
+ ...pattern,
1093
+ source: "imported"
1094
+ });
1095
+ }
1096
+ imported++;
1097
+ }
1098
+ return { imported, skipped };
1099
+ }
1100
+ exportBackup() {
1101
+ const incidents = this.getRecentIncidents({ limit: 1e5 });
1102
+ const patterns = this.getAllPatterns({ includePrivate: true });
1103
+ const groups = this.getGroups({ limit: 1e4 });
1104
+ return {
1105
+ version: "1.0.0",
1106
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1107
+ incidents,
1108
+ patterns,
1109
+ groups
1110
+ };
1111
+ }
1112
+ importBackup(data) {
1113
+ this.initializeSync();
1114
+ this.db.run("DELETE FROM group_members");
1115
+ this.db.run("DELETE FROM resolutions");
1116
+ this.db.run("DELETE FROM groups");
1117
+ this.db.run("DELETE FROM incidents");
1118
+ this.db.run("DELETE FROM patterns");
1119
+ for (const pattern of data.patterns) {
1120
+ this.addPattern(pattern);
1121
+ }
1122
+ for (const incident of data.incidents) {
1123
+ const now2 = incident.timestamp;
1124
+ this.db.run(
1125
+ `INSERT INTO incidents (
1126
+ id, timestamp, status, error_message, error_stack, error_code, error_type,
1127
+ symbols, flow_position, environment, service, version, user_id, request_id,
1128
+ group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
1129
+ created_at, updated_at
1130
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1131
+ [
1132
+ incident.id,
1133
+ incident.timestamp,
1134
+ incident.status,
1135
+ incident.error.message,
1136
+ incident.error.stack || null,
1137
+ incident.error.code || null,
1138
+ incident.error.type || null,
1139
+ JSON.stringify(incident.symbols),
1140
+ incident.flowPosition ? JSON.stringify(incident.flowPosition) : null,
1141
+ incident.environment,
1142
+ incident.service || null,
1143
+ incident.version || null,
1144
+ incident.userId || null,
1145
+ incident.requestId || null,
1146
+ incident.groupId || null,
1147
+ JSON.stringify(incident.notes),
1148
+ JSON.stringify(incident.relatedIncidents),
1149
+ incident.resolvedAt || null,
1150
+ incident.resolvedBy || null,
1151
+ incident.resolution ? JSON.stringify(incident.resolution) : null,
1152
+ now2,
1153
+ now2
1154
+ ]
1155
+ );
1156
+ }
1157
+ const result = this.db.exec(
1158
+ "SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents"
1159
+ );
1160
+ if (result.length > 0 && result[0].values.length > 0 && result[0].values[0][0]) {
1161
+ this.incidentCounter = result[0].values[0][0];
1162
+ }
1163
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1164
+ for (const group of data.groups) {
1165
+ this.db.run(
1166
+ `INSERT INTO groups (
1167
+ id, name, common_symbols, common_error_patterns,
1168
+ suggested_pattern_id, first_seen, last_seen, created_at, updated_at
1169
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1170
+ [
1171
+ group.id,
1172
+ group.name || null,
1173
+ JSON.stringify(group.commonSymbols),
1174
+ JSON.stringify(group.commonErrorPatterns),
1175
+ group.suggestedPattern?.id || null,
1176
+ group.firstSeen,
1177
+ group.lastSeen,
1178
+ now,
1179
+ now
1180
+ ]
1181
+ );
1182
+ for (const incidentId of group.incidents) {
1183
+ this.db.run(
1184
+ "INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",
1185
+ [group.id, incidentId, now]
1186
+ );
1187
+ }
1188
+ }
1189
+ this.save();
1190
+ }
1191
+ // ─── Helper Methods ──────────────────────────────────────────────
1192
+ rowToIncident(columns, row) {
1193
+ const obj = {};
1194
+ columns.forEach((col, i) => {
1195
+ obj[col] = row[i];
1196
+ });
1197
+ return {
1198
+ id: obj.id,
1199
+ timestamp: obj.timestamp,
1200
+ status: obj.status,
1201
+ error: {
1202
+ message: obj.error_message,
1203
+ stack: obj.error_stack || void 0,
1204
+ code: obj.error_code || void 0,
1205
+ type: obj.error_type || void 0
1206
+ },
1207
+ symbols: JSON.parse(obj.symbols || "{}"),
1208
+ flowPosition: obj.flow_position ? JSON.parse(obj.flow_position) : void 0,
1209
+ environment: obj.environment,
1210
+ service: obj.service || void 0,
1211
+ version: obj.version || void 0,
1212
+ userId: obj.user_id || void 0,
1213
+ requestId: obj.request_id || void 0,
1214
+ groupId: obj.group_id || void 0,
1215
+ notes: JSON.parse(obj.notes || "[]"),
1216
+ relatedIncidents: JSON.parse(obj.related_incidents || "[]"),
1217
+ resolvedAt: obj.resolved_at || void 0,
1218
+ resolvedBy: obj.resolved_by || void 0,
1219
+ resolution: obj.resolution ? JSON.parse(obj.resolution) : void 0
1220
+ };
1221
+ }
1222
+ rowToPattern(columns, row) {
1223
+ const obj = {};
1224
+ columns.forEach((col, i) => {
1225
+ obj[col] = row[i];
1226
+ });
1227
+ return {
1228
+ id: obj.id,
1229
+ name: obj.name,
1230
+ description: obj.description || "",
1231
+ pattern: JSON.parse(obj.pattern),
1232
+ resolution: JSON.parse(obj.resolution),
1233
+ confidence: JSON.parse(obj.confidence),
1234
+ source: obj.source,
1235
+ private: obj.private === 1,
1236
+ tags: JSON.parse(obj.tags || "[]"),
1237
+ createdAt: obj.created_at,
1238
+ updatedAt: obj.updated_at
1239
+ };
1240
+ }
1241
+ rowToGroup(columns, row) {
1242
+ const obj = {};
1243
+ columns.forEach((col, i) => {
1244
+ obj[col] = row[i];
1245
+ });
1246
+ const membersResult = this.db.exec(
1247
+ "SELECT incident_id FROM group_members WHERE group_id = ?",
1248
+ [obj.id]
1249
+ );
1250
+ const incidents = [];
1251
+ if (membersResult.length > 0) {
1252
+ for (const r of membersResult[0].values) {
1253
+ incidents.push(r[0]);
1254
+ }
1255
+ }
1256
+ const envResult = this.db.exec(
1257
+ `SELECT DISTINCT environment FROM incidents
1258
+ WHERE id IN (SELECT incident_id FROM group_members WHERE group_id = ?)`,
1259
+ [obj.id]
1260
+ );
1261
+ const environments = [];
1262
+ if (envResult.length > 0) {
1263
+ for (const r of envResult[0].values) {
1264
+ environments.push(r[0]);
1265
+ }
1266
+ }
1267
+ return {
1268
+ id: obj.id,
1269
+ name: obj.name || void 0,
1270
+ incidents,
1271
+ commonSymbols: JSON.parse(obj.common_symbols || "{}"),
1272
+ commonErrorPatterns: JSON.parse(
1273
+ obj.common_error_patterns || "[]"
1274
+ ),
1275
+ count: incidents.length,
1276
+ firstSeen: obj.first_seen,
1277
+ lastSeen: obj.last_seen,
1278
+ environments,
1279
+ suggestedPattern: obj.suggested_pattern_id ? this.getPattern(obj.suggested_pattern_id) || void 0 : void 0
1280
+ };
1281
+ }
1282
+ // ─── Practice Events ─────────────────────────────────────────────
1283
+ recordPracticeEvent(input) {
1284
+ this.initializeSync();
1285
+ const id = `PE-${uuidv4().substring(0, 8)}`;
1286
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1287
+ this.db.run(
1288
+ `INSERT INTO practice_events (
1289
+ id, timestamp, habit_id, habit_category, result,
1290
+ engineer, session_id, lore_entry_id, task_description,
1291
+ symbols_touched, files_modified, related_incident_id, notes
1292
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1293
+ [
1294
+ id,
1295
+ now,
1296
+ input.habitId,
1297
+ input.habitCategory,
1298
+ input.result,
1299
+ input.engineer,
1300
+ input.sessionId,
1301
+ input.loreEntryId || null,
1302
+ input.taskDescription || null,
1303
+ JSON.stringify(input.symbolsTouched || []),
1304
+ JSON.stringify(input.filesModified || []),
1305
+ input.relatedIncidentId || null,
1306
+ input.notes || null
1307
+ ]
1308
+ );
1309
+ this.save();
1310
+ return id;
1311
+ }
1312
+ getPracticeEvents(options = {}) {
1313
+ this.initializeSync();
1314
+ const { limit = 100, offset = 0 } = options;
1315
+ const conditions = [];
1316
+ const params = [];
1317
+ if (options.habitId) {
1318
+ conditions.push("habit_id = ?");
1319
+ params.push(options.habitId);
1320
+ }
1321
+ if (options.habitCategory) {
1322
+ conditions.push("habit_category = ?");
1323
+ params.push(options.habitCategory);
1324
+ }
1325
+ if (options.result) {
1326
+ conditions.push("result = ?");
1327
+ params.push(options.result);
1328
+ }
1329
+ if (options.engineer) {
1330
+ conditions.push("engineer = ?");
1331
+ params.push(options.engineer);
1332
+ }
1333
+ if (options.sessionId) {
1334
+ conditions.push("session_id = ?");
1335
+ params.push(options.sessionId);
1336
+ }
1337
+ if (options.dateFrom) {
1338
+ conditions.push("timestamp >= ?");
1339
+ params.push(options.dateFrom);
1340
+ }
1341
+ if (options.dateTo) {
1342
+ conditions.push("timestamp <= ?");
1343
+ params.push(options.dateTo);
1344
+ }
1345
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1346
+ const result = this.db.exec(
1347
+ `SELECT * FROM practice_events ${whereClause} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,
1348
+ [...params, limit, offset]
1349
+ );
1350
+ if (result.length === 0) return [];
1351
+ return result[0].values.map(
1352
+ (row) => this.rowToPracticeEvent(result[0].columns, row)
1353
+ );
1354
+ }
1355
+ getPracticeEventCount(options = {}) {
1356
+ this.initializeSync();
1357
+ const conditions = [];
1358
+ const params = [];
1359
+ if (options.habitId) {
1360
+ conditions.push("habit_id = ?");
1361
+ params.push(options.habitId);
1362
+ }
1363
+ if (options.habitCategory) {
1364
+ conditions.push("habit_category = ?");
1365
+ params.push(options.habitCategory);
1366
+ }
1367
+ if (options.result) {
1368
+ conditions.push("result = ?");
1369
+ params.push(options.result);
1370
+ }
1371
+ if (options.engineer) {
1372
+ conditions.push("engineer = ?");
1373
+ params.push(options.engineer);
1374
+ }
1375
+ if (options.dateFrom) {
1376
+ conditions.push("timestamp >= ?");
1377
+ params.push(options.dateFrom);
1378
+ }
1379
+ if (options.dateTo) {
1380
+ conditions.push("timestamp <= ?");
1381
+ params.push(options.dateTo);
1382
+ }
1383
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1384
+ const result = this.db.exec(
1385
+ `SELECT COUNT(*) as count FROM practice_events ${whereClause}`,
1386
+ params
1387
+ );
1388
+ if (result.length === 0 || result[0].values.length === 0) return 0;
1389
+ return result[0].values[0][0];
1390
+ }
1391
+ getComplianceRate(options = {}) {
1392
+ this.initializeSync();
1393
+ const conditions = [];
1394
+ const params = [];
1395
+ if (options.habitId) {
1396
+ conditions.push("habit_id = ?");
1397
+ params.push(options.habitId);
1398
+ }
1399
+ if (options.habitCategory) {
1400
+ conditions.push("habit_category = ?");
1401
+ params.push(options.habitCategory);
1402
+ }
1403
+ if (options.engineer) {
1404
+ conditions.push("engineer = ?");
1405
+ params.push(options.engineer);
1406
+ }
1407
+ if (options.dateFrom) {
1408
+ conditions.push("timestamp >= ?");
1409
+ params.push(options.dateFrom);
1410
+ }
1411
+ if (options.dateTo) {
1412
+ conditions.push("timestamp <= ?");
1413
+ params.push(options.dateTo);
1414
+ }
1415
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1416
+ const result = this.db.exec(
1417
+ `SELECT result, COUNT(*) as count
1418
+ FROM practice_events ${whereClause}
1419
+ GROUP BY result`,
1420
+ params
1421
+ );
1422
+ let followed = 0;
1423
+ let skipped = 0;
1424
+ let partial = 0;
1425
+ if (result.length > 0) {
1426
+ for (const row of result[0].values) {
1427
+ const r = row[0];
1428
+ const count = row[1];
1429
+ if (r === "followed") followed = count;
1430
+ else if (r === "skipped") skipped = count;
1431
+ else if (r === "partial") partial = count;
1432
+ }
1433
+ }
1434
+ const total = followed + skipped + partial;
1435
+ const rate = total > 0 ? (followed + partial * 0.5) / total * 100 : 100;
1436
+ return { total, followed, skipped, partial, rate: Math.round(rate) };
1437
+ }
1438
+ rowToPracticeEvent(columns, row) {
1439
+ const obj = {};
1440
+ columns.forEach((col, i) => {
1441
+ obj[col] = row[i];
1442
+ });
1443
+ return {
1444
+ id: obj.id,
1445
+ timestamp: obj.timestamp,
1446
+ habitId: obj.habit_id,
1447
+ habitCategory: obj.habit_category,
1448
+ result: obj.result,
1449
+ engineer: obj.engineer,
1450
+ sessionId: obj.session_id,
1451
+ loreEntryId: obj.lore_entry_id || void 0,
1452
+ taskDescription: obj.task_description || void 0,
1453
+ symbolsTouched: JSON.parse(obj.symbols_touched || "[]"),
1454
+ filesModified: JSON.parse(obj.files_modified || "[]"),
1455
+ relatedIncidentId: obj.related_incident_id || void 0,
1456
+ notes: obj.notes || void 0
1457
+ };
1458
+ }
1459
+ // ─── Structured Logs ─────────────────────────────────────────────
1460
+ inferSymbolType(symbol) {
1461
+ if (symbol.startsWith("#")) return "component";
1462
+ if (symbol.startsWith("^")) return "gate";
1463
+ if (symbol.startsWith("!")) return "signal";
1464
+ if (symbol.startsWith("$")) return "flow";
1465
+ if (symbol.startsWith("~")) return "aspect";
1466
+ return "raw";
1467
+ }
1468
+ insertLog(input) {
1469
+ this.initializeSync();
1470
+ const id = input.id || uuidv4();
1471
+ const timestamp = input.timestamp || (/* @__PURE__ */ new Date()).toISOString();
1472
+ const symbolType = input.symbolType || this.inferSymbolType(input.symbol);
1473
+ this.db.run(
1474
+ `INSERT INTO logs (
1475
+ id, timestamp, level, symbol, symbol_type, message, data_json,
1476
+ service, session_id, correlation_id, duration_ms, environment
1477
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1478
+ [
1479
+ id,
1480
+ timestamp,
1481
+ input.level,
1482
+ input.symbol,
1483
+ symbolType,
1484
+ input.message,
1485
+ input.data ? JSON.stringify(input.data) : null,
1486
+ input.service,
1487
+ input.sessionId || null,
1488
+ input.correlationId || null,
1489
+ input.durationMs ?? null,
1490
+ input.environment || null
1491
+ ]
1492
+ );
1493
+ this.save();
1494
+ return id;
1495
+ }
1496
+ insertLogBatch(entries) {
1497
+ this.initializeSync();
1498
+ let accepted = 0;
1499
+ const errors = [];
1500
+ for (const input of entries) {
1501
+ try {
1502
+ const id = input.id || uuidv4();
1503
+ const timestamp = input.timestamp || (/* @__PURE__ */ new Date()).toISOString();
1504
+ const symbolType = input.symbolType || this.inferSymbolType(input.symbol);
1505
+ this.db.run(
1506
+ `INSERT INTO logs (
1507
+ id, timestamp, level, symbol, symbol_type, message, data_json,
1508
+ service, session_id, correlation_id, duration_ms, environment
1509
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1510
+ [
1511
+ id,
1512
+ timestamp,
1513
+ input.level,
1514
+ input.symbol,
1515
+ symbolType,
1516
+ input.message,
1517
+ input.data ? JSON.stringify(input.data) : null,
1518
+ input.service,
1519
+ input.sessionId || null,
1520
+ input.correlationId || null,
1521
+ input.durationMs ?? null,
1522
+ input.environment || null
1523
+ ]
1524
+ );
1525
+ accepted++;
1526
+ } catch (err) {
1527
+ errors.push(err instanceof Error ? err.message : String(err));
1528
+ }
1529
+ }
1530
+ this.save();
1531
+ return { accepted, errors };
1532
+ }
1533
+ queryLogs(options = {}) {
1534
+ this.initializeSync();
1535
+ const { limit = 100, offset = 0 } = options;
1536
+ const conditions = [];
1537
+ const params = [];
1538
+ if (options.level) {
1539
+ conditions.push("level = ?");
1540
+ params.push(options.level);
1541
+ }
1542
+ if (options.symbol) {
1543
+ conditions.push("symbol LIKE ?");
1544
+ params.push(`%${options.symbol}%`);
1545
+ }
1546
+ if (options.service) {
1547
+ conditions.push("service = ?");
1548
+ params.push(options.service);
1549
+ }
1550
+ if (options.sessionId) {
1551
+ conditions.push("session_id = ?");
1552
+ params.push(options.sessionId);
1553
+ }
1554
+ if (options.correlationId) {
1555
+ conditions.push("correlation_id = ?");
1556
+ params.push(options.correlationId);
1557
+ }
1558
+ if (options.search) {
1559
+ conditions.push("message LIKE ?");
1560
+ params.push(`%${options.search}%`);
1561
+ }
1562
+ if (options.since) {
1563
+ conditions.push("timestamp >= ?");
1564
+ params.push(options.since);
1565
+ }
1566
+ if (options.until) {
1567
+ conditions.push("timestamp <= ?");
1568
+ params.push(options.until);
1569
+ }
1570
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1571
+ const result = this.db.exec(
1572
+ `SELECT * FROM logs ${whereClause} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,
1573
+ [...params, limit, offset]
1574
+ );
1575
+ if (result.length === 0) return [];
1576
+ return result[0].values.map(
1577
+ (row) => this.rowToLogEntry(result[0].columns, row)
1578
+ );
1579
+ }
1580
+ getLogCount(options = {}) {
1581
+ this.initializeSync();
1582
+ const conditions = [];
1583
+ const params = [];
1584
+ if (options.level) {
1585
+ conditions.push("level = ?");
1586
+ params.push(options.level);
1587
+ }
1588
+ if (options.symbol) {
1589
+ conditions.push("symbol LIKE ?");
1590
+ params.push(`%${options.symbol}%`);
1591
+ }
1592
+ if (options.service) {
1593
+ conditions.push("service = ?");
1594
+ params.push(options.service);
1595
+ }
1596
+ if (options.since) {
1597
+ conditions.push("timestamp >= ?");
1598
+ params.push(options.since);
1599
+ }
1600
+ if (options.until) {
1601
+ conditions.push("timestamp <= ?");
1602
+ params.push(options.until);
1603
+ }
1604
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1605
+ const result = this.db.exec(
1606
+ `SELECT COUNT(*) as count FROM logs ${whereClause}`,
1607
+ params
1608
+ );
1609
+ if (result.length === 0 || result[0].values.length === 0) return 0;
1610
+ return result[0].values[0][0];
1611
+ }
1612
+ pruneLogs(maxCount) {
1613
+ this.initializeSync();
1614
+ if (maxCount <= 0) return 0;
1615
+ const currentCount = this.getLogCount();
1616
+ if (currentCount <= maxCount) return 0;
1617
+ const deleteCount = currentCount - maxCount;
1618
+ this.db.run(
1619
+ `DELETE FROM logs WHERE id IN (
1620
+ SELECT id FROM logs ORDER BY timestamp ASC LIMIT ?
1621
+ )`,
1622
+ [deleteCount]
1623
+ );
1624
+ this.save();
1625
+ return deleteCount;
1626
+ }
1627
+ rowToLogEntry(columns, row) {
1628
+ const obj = {};
1629
+ columns.forEach((col, i) => {
1630
+ obj[col] = row[i];
1631
+ });
1632
+ return {
1633
+ id: obj.id,
1634
+ timestamp: obj.timestamp,
1635
+ level: obj.level,
1636
+ symbol: obj.symbol,
1637
+ symbolType: obj.symbol_type || "raw",
1638
+ message: obj.message,
1639
+ data: obj.data_json ? JSON.parse(obj.data_json) : void 0,
1640
+ service: obj.service,
1641
+ sessionId: obj.session_id || void 0,
1642
+ correlationId: obj.correlation_id || void 0,
1643
+ durationMs: obj.duration_ms || void 0,
1644
+ environment: obj.environment || void 0
1645
+ };
1646
+ }
1647
+ // ─── Service Registry ──────────────────────────────────────────
1648
+ registerService(reg) {
1649
+ this.initializeSync();
1650
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1651
+ this.db.run(
1652
+ `INSERT INTO services (name, version, pid, started_at, last_seen_at, environment, metadata_json)
1653
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1654
+ ON CONFLICT(name) DO UPDATE SET
1655
+ version = excluded.version,
1656
+ pid = excluded.pid,
1657
+ last_seen_at = excluded.last_seen_at,
1658
+ environment = excluded.environment,
1659
+ metadata_json = excluded.metadata_json`,
1660
+ [
1661
+ reg.name,
1662
+ reg.version || null,
1663
+ reg.pid ?? null,
1664
+ now,
1665
+ now,
1666
+ reg.environment || null,
1667
+ reg.metadata ? JSON.stringify(reg.metadata) : null
1668
+ ]
1669
+ );
1670
+ this.save();
1671
+ }
1672
+ updateServiceLastSeen(name) {
1673
+ this.initializeSync();
1674
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1675
+ this.db.run(
1676
+ "UPDATE services SET last_seen_at = ? WHERE name = ?",
1677
+ [now, name]
1678
+ );
1679
+ this.save();
1680
+ }
1681
+ getServices() {
1682
+ this.initializeSync();
1683
+ const result = this.db.exec(
1684
+ "SELECT * FROM services ORDER BY last_seen_at DESC"
1685
+ );
1686
+ if (result.length === 0) return [];
1687
+ return result[0].values.map((row) => {
1688
+ const obj = {};
1689
+ result[0].columns.forEach((col, i) => {
1690
+ obj[col] = row[i];
1691
+ });
1692
+ return {
1693
+ name: obj.name,
1694
+ version: obj.version || void 0,
1695
+ pid: obj.pid || void 0,
1696
+ startedAt: obj.started_at,
1697
+ lastSeenAt: obj.last_seen_at,
1698
+ environment: obj.environment || void 0,
1699
+ metadata: obj.metadata_json ? JSON.parse(obj.metadata_json) : void 0
1700
+ };
1701
+ });
1702
+ }
1703
+ // ─── App State ──────────────────────────────────────────────────
1704
+ upsertAppState(state) {
1705
+ this.initializeSync();
1706
+ this.db.run(
1707
+ `INSERT INTO app_state (service, session_id, timestamp, state_json, active_flows_json, active_gates_json)
1708
+ VALUES (?, ?, ?, ?, ?, ?)
1709
+ ON CONFLICT(service, session_id) DO UPDATE SET
1710
+ timestamp = excluded.timestamp,
1711
+ state_json = excluded.state_json,
1712
+ active_flows_json = excluded.active_flows_json,
1713
+ active_gates_json = excluded.active_gates_json`,
1714
+ [
1715
+ state.service,
1716
+ state.sessionId,
1717
+ state.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
1718
+ JSON.stringify(state.state),
1719
+ state.activeFlows ? JSON.stringify(state.activeFlows) : null,
1720
+ state.activeGates ? JSON.stringify(state.activeGates) : null
1721
+ ]
1722
+ );
1723
+ this.save();
1724
+ }
1725
+ getAppState(service, sessionId) {
1726
+ this.initializeSync();
1727
+ let query = "SELECT * FROM app_state WHERE service = ?";
1728
+ const params = [service];
1729
+ if (sessionId) {
1730
+ query += " AND session_id = ?";
1731
+ params.push(sessionId);
1732
+ }
1733
+ query += " ORDER BY timestamp DESC";
1734
+ const result = this.db.exec(query, params);
1735
+ if (result.length === 0) return [];
1736
+ return result[0].values.map((row) => this.rowToAppState(result[0].columns, row));
1737
+ }
1738
+ getAllAppStates() {
1739
+ this.initializeSync();
1740
+ const result = this.db.exec(
1741
+ "SELECT * FROM app_state ORDER BY timestamp DESC"
1742
+ );
1743
+ if (result.length === 0) return [];
1744
+ return result[0].values.map((row) => this.rowToAppState(result[0].columns, row));
1745
+ }
1746
+ rowToAppState(columns, row) {
1747
+ const obj = {};
1748
+ columns.forEach((col, i) => {
1749
+ obj[col] = row[i];
1750
+ });
1751
+ return {
1752
+ service: obj.service,
1753
+ sessionId: obj.session_id,
1754
+ timestamp: obj.timestamp,
1755
+ state: JSON.parse(obj.state_json),
1756
+ activeFlows: obj.active_flows_json ? JSON.parse(obj.active_flows_json) : void 0,
1757
+ activeGates: obj.active_gates_json ? JSON.parse(obj.active_gates_json) : void 0
1758
+ };
1759
+ }
1760
+ // ─── Metrics ───────────────────────────────────────────────────
1761
+ insertMetric(input) {
1762
+ this.initializeSync();
1763
+ const id = uuidv4();
1764
+ const timestamp = input.timestamp || (/* @__PURE__ */ new Date()).toISOString();
1765
+ this.db.run(
1766
+ `INSERT INTO metrics (
1767
+ id, timestamp, name, type, value, tags_json, service, environment
1768
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
1769
+ [
1770
+ id,
1771
+ timestamp,
1772
+ input.name,
1773
+ input.type,
1774
+ input.value,
1775
+ JSON.stringify(input.tags || {}),
1776
+ input.service,
1777
+ input.environment || null
1778
+ ]
1779
+ );
1780
+ this.save();
1781
+ return id;
1782
+ }
1783
+ insertMetricBatch(entries) {
1784
+ this.initializeSync();
1785
+ let accepted = 0;
1786
+ const errors = [];
1787
+ for (const input of entries) {
1788
+ try {
1789
+ const id = uuidv4();
1790
+ const timestamp = input.timestamp || (/* @__PURE__ */ new Date()).toISOString();
1791
+ this.db.run(
1792
+ `INSERT INTO metrics (
1793
+ id, timestamp, name, type, value, tags_json, service, environment
1794
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
1795
+ [
1796
+ id,
1797
+ timestamp,
1798
+ input.name,
1799
+ input.type,
1800
+ input.value,
1801
+ JSON.stringify(input.tags || {}),
1802
+ input.service,
1803
+ input.environment || null
1804
+ ]
1805
+ );
1806
+ accepted++;
1807
+ } catch (err) {
1808
+ errors.push(err instanceof Error ? err.message : String(err));
1809
+ }
1810
+ }
1811
+ this.save();
1812
+ return { accepted, errors };
1813
+ }
1814
+ queryMetrics(options = {}) {
1815
+ this.initializeSync();
1816
+ const { limit = 100, offset = 0 } = options;
1817
+ const conditions = [];
1818
+ const params = [];
1819
+ if (options.name) {
1820
+ conditions.push("name = ?");
1821
+ params.push(options.name);
1822
+ }
1823
+ if (options.type) {
1824
+ conditions.push("type = ?");
1825
+ params.push(options.type);
1826
+ }
1827
+ if (options.service) {
1828
+ conditions.push("service = ?");
1829
+ params.push(options.service);
1830
+ }
1831
+ if (options.tag) {
1832
+ const eqIdx = options.tag.indexOf("=");
1833
+ if (eqIdx > 0) {
1834
+ const tagKey = options.tag.substring(0, eqIdx);
1835
+ const tagValue = options.tag.substring(eqIdx + 1);
1836
+ conditions.push("tags_json LIKE ?");
1837
+ params.push(`%"${tagKey}":"${tagValue}"%`);
1838
+ }
1839
+ }
1840
+ if (options.since) {
1841
+ conditions.push("timestamp >= ?");
1842
+ params.push(options.since);
1843
+ }
1844
+ if (options.until) {
1845
+ conditions.push("timestamp <= ?");
1846
+ params.push(options.until);
1847
+ }
1848
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1849
+ const result = this.db.exec(
1850
+ `SELECT * FROM metrics ${whereClause} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,
1851
+ [...params, limit, offset]
1852
+ );
1853
+ if (result.length === 0) return [];
1854
+ return result[0].values.map(
1855
+ (row) => this.rowToMetricEntry(result[0].columns, row)
1856
+ );
1857
+ }
1858
+ getMetricCount(options = {}) {
1859
+ this.initializeSync();
1860
+ const conditions = [];
1861
+ const params = [];
1862
+ if (options.name) {
1863
+ conditions.push("name = ?");
1864
+ params.push(options.name);
1865
+ }
1866
+ if (options.type) {
1867
+ conditions.push("type = ?");
1868
+ params.push(options.type);
1869
+ }
1870
+ if (options.service) {
1871
+ conditions.push("service = ?");
1872
+ params.push(options.service);
1873
+ }
1874
+ if (options.tag) {
1875
+ const eqIdx = options.tag.indexOf("=");
1876
+ if (eqIdx > 0) {
1877
+ const tagKey = options.tag.substring(0, eqIdx);
1878
+ const tagValue = options.tag.substring(eqIdx + 1);
1879
+ conditions.push("tags_json LIKE ?");
1880
+ params.push(`%"${tagKey}":"${tagValue}"%`);
1881
+ }
1882
+ }
1883
+ if (options.since) {
1884
+ conditions.push("timestamp >= ?");
1885
+ params.push(options.since);
1886
+ }
1887
+ if (options.until) {
1888
+ conditions.push("timestamp <= ?");
1889
+ params.push(options.until);
1890
+ }
1891
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1892
+ const result = this.db.exec(
1893
+ `SELECT COUNT(*) as count FROM metrics ${whereClause}`,
1894
+ params
1895
+ );
1896
+ if (result.length === 0 || result[0].values.length === 0) return 0;
1897
+ return result[0].values[0][0];
1898
+ }
1899
+ aggregateMetric(name, options) {
1900
+ this.initializeSync();
1901
+ const conditions = ["name = ?"];
1902
+ const params = [name];
1903
+ if (options?.service) {
1904
+ conditions.push("service = ?");
1905
+ params.push(options.service);
1906
+ }
1907
+ if (options?.since) {
1908
+ conditions.push("timestamp >= ?");
1909
+ params.push(options.since);
1910
+ }
1911
+ if (options?.until) {
1912
+ conditions.push("timestamp <= ?");
1913
+ params.push(options.until);
1914
+ }
1915
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
1916
+ const result = this.db.exec(
1917
+ `SELECT COUNT(*) as count, SUM(value) as sum, MIN(value) as min, MAX(value) as max, AVG(value) as avg
1918
+ FROM metrics ${whereClause}`,
1919
+ params
1920
+ );
1921
+ if (result.length === 0 || result[0].values.length === 0) {
1922
+ return { name, count: 0, sum: 0, min: 0, max: 0, avg: 0 };
1923
+ }
1924
+ const row = result[0].values[0];
1925
+ return {
1926
+ name,
1927
+ count: row[0] || 0,
1928
+ sum: row[1] || 0,
1929
+ min: row[2] || 0,
1930
+ max: row[3] || 0,
1931
+ avg: row[4] || 0
1932
+ };
1933
+ }
1934
+ pruneMetrics(maxCount) {
1935
+ this.initializeSync();
1936
+ if (maxCount <= 0) return 0;
1937
+ const currentCount = this.getMetricCount();
1938
+ if (currentCount <= maxCount) return 0;
1939
+ const deleteCount = currentCount - maxCount;
1940
+ this.db.run(
1941
+ `DELETE FROM metrics WHERE id IN (
1942
+ SELECT id FROM metrics ORDER BY timestamp ASC LIMIT ?
1943
+ )`,
1944
+ [deleteCount]
1945
+ );
1946
+ this.save();
1947
+ return deleteCount;
1948
+ }
1949
+ rowToMetricEntry(columns, row) {
1950
+ const obj = {};
1951
+ columns.forEach((col, i) => {
1952
+ obj[col] = row[i];
1953
+ });
1954
+ return {
1955
+ id: obj.id,
1956
+ timestamp: obj.timestamp,
1957
+ name: obj.name,
1958
+ type: obj.type,
1959
+ value: obj.value,
1960
+ tags: obj.tags_json ? JSON.parse(obj.tags_json) : {},
1961
+ service: obj.service,
1962
+ environment: obj.environment || void 0
1963
+ };
1964
+ }
1965
+ // ─── Traces ───────────────────────────────────────────────────
1966
+ insertSpan(input) {
1967
+ this.initializeSync();
1968
+ const spanId = input.spanId || uuidv4();
1969
+ const startTime = input.startTime || (/* @__PURE__ */ new Date()).toISOString();
1970
+ this.db.run(
1971
+ `INSERT INTO traces (
1972
+ trace_id, span_id, parent_span_id, service, symbol, operation,
1973
+ start_time, end_time, duration_ms, status, tags_json, log_ids_json
1974
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1975
+ [
1976
+ input.traceId,
1977
+ spanId,
1978
+ input.parentSpanId || null,
1979
+ input.service,
1980
+ input.symbol,
1981
+ input.operation,
1982
+ startTime,
1983
+ input.endTime || null,
1984
+ input.durationMs ?? null,
1985
+ input.status || "ok",
1986
+ JSON.stringify(input.tags || {}),
1987
+ JSON.stringify(input.logIds || [])
1988
+ ]
1989
+ );
1990
+ this.save();
1991
+ return spanId;
1992
+ }
1993
+ getTrace(traceId) {
1994
+ this.initializeSync();
1995
+ const result = this.db.exec(
1996
+ "SELECT * FROM traces WHERE trace_id = ? ORDER BY start_time ASC",
1997
+ [traceId]
1998
+ );
1999
+ if (result.length === 0 || result[0].values.length === 0) return null;
2000
+ const spans = result[0].values.map(
2001
+ (row) => this.rowToTraceSpan(result[0].columns, row)
2002
+ );
2003
+ const services = [...new Set(spans.map((s) => s.service))];
2004
+ const startTimes = spans.map((s) => s.startTime);
2005
+ const endTimes = spans.filter((s) => s.endTime).map((s) => s.endTime);
2006
+ const startTime = startTimes.sort()[0];
2007
+ const endTime = endTimes.length > 0 ? endTimes.sort().reverse()[0] : startTime;
2008
+ const startMs = new Date(startTime).getTime();
2009
+ const endMs = new Date(endTime).getTime();
2010
+ const totalDurationMs = endMs - startMs;
2011
+ return {
2012
+ traceId,
2013
+ spans,
2014
+ services,
2015
+ totalDurationMs: totalDurationMs > 0 ? totalDurationMs : 0,
2016
+ startTime,
2017
+ endTime
2018
+ };
2019
+ }
2020
+ queryTraces(options = {}) {
2021
+ this.initializeSync();
2022
+ const conditions = [];
2023
+ const params = [];
2024
+ if (options.service) {
2025
+ conditions.push("service = ?");
2026
+ params.push(options.service);
2027
+ }
2028
+ if (options.symbol) {
2029
+ conditions.push("symbol = ?");
2030
+ params.push(options.symbol);
2031
+ }
2032
+ if (options.since) {
2033
+ conditions.push("start_time >= ?");
2034
+ params.push(options.since);
2035
+ }
2036
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2037
+ const traceLimit = Math.min(options.limit || 20, 20);
2038
+ const result = this.db.exec(
2039
+ `SELECT DISTINCT trace_id FROM traces ${whereClause} ORDER BY start_time DESC LIMIT ?`,
2040
+ [...params, traceLimit]
2041
+ );
2042
+ if (result.length === 0) return [];
2043
+ const traces = [];
2044
+ for (const row of result[0].values) {
2045
+ const traceId = row[0];
2046
+ const trace = this.getTrace(traceId);
2047
+ if (trace) {
2048
+ traces.push(trace);
2049
+ }
2050
+ }
2051
+ return traces;
2052
+ }
2053
+ rowToTraceSpan(columns, row) {
2054
+ const obj = {};
2055
+ columns.forEach((col, i) => {
2056
+ obj[col] = row[i];
2057
+ });
2058
+ return {
2059
+ traceId: obj.trace_id,
2060
+ spanId: obj.span_id,
2061
+ parentSpanId: obj.parent_span_id || void 0,
2062
+ service: obj.service,
2063
+ symbol: obj.symbol,
2064
+ operation: obj.operation,
2065
+ startTime: obj.start_time,
2066
+ endTime: obj.end_time || void 0,
2067
+ durationMs: obj.duration_ms || void 0,
2068
+ status: obj.status || "ok",
2069
+ tags: obj.tags_json ? JSON.parse(obj.tags_json) : {},
2070
+ logs: obj.log_ids_json ? JSON.parse(obj.log_ids_json) : []
2071
+ };
2072
+ }
2073
+ // ─── Schema Registry ─────────────────────────────────────────────
2074
+ registerSchema(schema) {
2075
+ this.initializeSync();
2076
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2077
+ this.db.run(
2078
+ `INSERT INTO schemas (
2079
+ id, version, name, description, scope_json, event_types_json,
2080
+ causality_json, visualization_json, tags_json, registered_at, updated_at
2081
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2082
+ ON CONFLICT(id) DO UPDATE SET
2083
+ version = excluded.version,
2084
+ name = excluded.name,
2085
+ description = excluded.description,
2086
+ scope_json = excluded.scope_json,
2087
+ event_types_json = excluded.event_types_json,
2088
+ causality_json = excluded.causality_json,
2089
+ visualization_json = excluded.visualization_json,
2090
+ tags_json = excluded.tags_json,
2091
+ updated_at = excluded.updated_at`,
2092
+ [
2093
+ schema.id,
2094
+ schema.version,
2095
+ schema.name,
2096
+ schema.description || null,
2097
+ JSON.stringify(schema.scope),
2098
+ JSON.stringify(schema.eventTypes),
2099
+ schema.causality ? JSON.stringify(schema.causality) : null,
2100
+ schema.visualization ? JSON.stringify(schema.visualization) : null,
2101
+ JSON.stringify(schema.tags || []),
2102
+ now,
2103
+ now
2104
+ ]
2105
+ );
2106
+ this.save();
2107
+ return {
2108
+ id: schema.id,
2109
+ version: schema.version,
2110
+ name: schema.name,
2111
+ description: schema.description,
2112
+ scope: schema.scope,
2113
+ eventTypes: schema.eventTypes,
2114
+ causality: schema.causality,
2115
+ visualization: schema.visualization,
2116
+ tags: schema.tags || [],
2117
+ registeredAt: now,
2118
+ updatedAt: now
2119
+ };
2120
+ }
2121
+ getSchema(id) {
2122
+ this.initializeSync();
2123
+ const result = this.db.exec("SELECT * FROM schemas WHERE id = ?", [id]);
2124
+ if (result.length === 0 || result[0].values.length === 0) return null;
2125
+ return this.rowToSchema(result[0].columns, result[0].values[0]);
2126
+ }
2127
+ listSchemas() {
2128
+ this.initializeSync();
2129
+ const result = this.db.exec("SELECT * FROM schemas ORDER BY name ASC");
2130
+ if (result.length === 0) return [];
2131
+ return result[0].values.map(
2132
+ (row) => this.rowToSchema(result[0].columns, row)
2133
+ );
2134
+ }
2135
+ rowToSchema(columns, row) {
2136
+ const obj = {};
2137
+ columns.forEach((col, i) => {
2138
+ obj[col] = row[i];
2139
+ });
2140
+ return {
2141
+ id: obj.id,
2142
+ version: obj.version,
2143
+ name: obj.name,
2144
+ description: obj.description || void 0,
2145
+ scope: JSON.parse(obj.scope_json),
2146
+ eventTypes: JSON.parse(obj.event_types_json),
2147
+ causality: obj.causality_json ? JSON.parse(obj.causality_json) : void 0,
2148
+ visualization: obj.visualization_json ? JSON.parse(obj.visualization_json) : void 0,
2149
+ tags: JSON.parse(obj.tags_json || "[]"),
2150
+ registeredAt: obj.registered_at,
2151
+ updatedAt: obj.updated_at
2152
+ };
2153
+ }
2154
+ // ─── Generic Events ────────────────────────────────────────────
2155
+ insertEventBatch(schemaId, service, inputs) {
2156
+ this.initializeSync();
2157
+ const schema = this.getSchema(schemaId);
2158
+ const typeMap = /* @__PURE__ */ new Map();
2159
+ if (schema) {
2160
+ for (const et of schema.eventTypes) {
2161
+ typeMap.set(et.type, {
2162
+ category: et.category,
2163
+ severity: et.severity || "info"
2164
+ });
2165
+ }
2166
+ }
2167
+ let accepted = 0;
2168
+ const errors = [];
2169
+ for (const input of inputs) {
2170
+ try {
2171
+ const id = input.id || uuidv4();
2172
+ const timestamp = input.timestamp || (/* @__PURE__ */ new Date()).toISOString();
2173
+ const resolved = typeMap.get(input.type);
2174
+ const category = resolved?.category || "unknown";
2175
+ const severity = input.severity || resolved?.severity || "info";
2176
+ const scopeValue = input.scopeValue != null ? String(input.scopeValue) : null;
2177
+ const scopeOrdinal = typeof input.scopeValue === "number" ? input.scopeValue : null;
2178
+ this.db.run(
2179
+ `INSERT INTO events (
2180
+ id, schema_id, event_type, category, timestamp, scope_value,
2181
+ scope_ordinal, session_id, service, data_json, severity,
2182
+ parent_event_id, depth
2183
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2184
+ [
2185
+ id,
2186
+ schemaId,
2187
+ input.type,
2188
+ category,
2189
+ timestamp,
2190
+ scopeValue,
2191
+ scopeOrdinal,
2192
+ input.sessionId || null,
2193
+ service,
2194
+ input.data ? JSON.stringify(input.data) : null,
2195
+ severity,
2196
+ input.parentEventId || null,
2197
+ input.depth ?? 0
2198
+ ]
2199
+ );
2200
+ accepted++;
2201
+ } catch (err) {
2202
+ errors.push(err instanceof Error ? err.message : String(err));
2203
+ }
2204
+ }
2205
+ this.save();
2206
+ return { accepted, errors };
2207
+ }
2208
+ queryEvents(options = {}) {
2209
+ this.initializeSync();
2210
+ const { limit = 100, offset = 0 } = options;
2211
+ const conditions = [];
2212
+ const params = [];
2213
+ if (options.schemaId) {
2214
+ conditions.push("schema_id = ?");
2215
+ params.push(options.schemaId);
2216
+ }
2217
+ if (options.eventType) {
2218
+ conditions.push("event_type = ?");
2219
+ params.push(options.eventType);
2220
+ }
2221
+ if (options.category) {
2222
+ conditions.push("category = ?");
2223
+ params.push(options.category);
2224
+ }
2225
+ if (options.service) {
2226
+ conditions.push("service = ?");
2227
+ params.push(options.service);
2228
+ }
2229
+ if (options.sessionId) {
2230
+ conditions.push("session_id = ?");
2231
+ params.push(options.sessionId);
2232
+ }
2233
+ if (options.scopeValue) {
2234
+ conditions.push("scope_value = ?");
2235
+ params.push(options.scopeValue);
2236
+ }
2237
+ if (options.scopeFrom) {
2238
+ conditions.push("scope_value >= ?");
2239
+ params.push(options.scopeFrom);
2240
+ }
2241
+ if (options.scopeTo) {
2242
+ conditions.push("scope_value <= ?");
2243
+ params.push(options.scopeTo);
2244
+ }
2245
+ if (options.severity) {
2246
+ conditions.push("severity = ?");
2247
+ params.push(options.severity);
2248
+ }
2249
+ if (options.since) {
2250
+ conditions.push("timestamp >= ?");
2251
+ params.push(options.since);
2252
+ }
2253
+ if (options.until) {
2254
+ conditions.push("timestamp <= ?");
2255
+ params.push(options.until);
2256
+ }
2257
+ if (options.search) {
2258
+ conditions.push("data_json LIKE ?");
2259
+ params.push(`%${options.search}%`);
2260
+ }
2261
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2262
+ const result = this.db.exec(
2263
+ `SELECT * FROM events ${whereClause} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,
2264
+ [...params, limit, offset]
2265
+ );
2266
+ if (result.length === 0) return [];
2267
+ return result[0].values.map(
2268
+ (row) => this.rowToGenericEvent(result[0].columns, row)
2269
+ );
2270
+ }
2271
+ queryEventsByScope(schemaId, scopeValue) {
2272
+ this.initializeSync();
2273
+ const result = this.db.exec(
2274
+ `SELECT * FROM events
2275
+ WHERE schema_id = ? AND scope_value = ?
2276
+ ORDER BY timestamp ASC`,
2277
+ [schemaId, scopeValue]
2278
+ );
2279
+ if (result.length === 0) return [];
2280
+ return result[0].values.map(
2281
+ (row) => this.rowToGenericEvent(result[0].columns, row)
2282
+ );
2283
+ }
2284
+ getEventScopes(schemaId, options = {}) {
2285
+ this.initializeSync();
2286
+ const { limit = 100, offset = 0 } = options;
2287
+ const conditions = ["schema_id = ?"];
2288
+ const params = [schemaId];
2289
+ if (options.sessionId) {
2290
+ conditions.push("session_id = ?");
2291
+ params.push(options.sessionId);
2292
+ }
2293
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
2294
+ const result = this.db.exec(
2295
+ `SELECT
2296
+ scope_value,
2297
+ MIN(scope_ordinal) as scope_ordinal,
2298
+ COUNT(*) as event_count,
2299
+ MIN(timestamp) as first_timestamp,
2300
+ MAX(timestamp) as last_timestamp
2301
+ FROM events
2302
+ ${whereClause}
2303
+ AND scope_value IS NOT NULL
2304
+ GROUP BY scope_value
2305
+ ORDER BY MIN(COALESCE(scope_ordinal, 0)) DESC, MIN(timestamp) DESC
2306
+ LIMIT ? OFFSET ?`,
2307
+ [...params, limit, offset]
2308
+ );
2309
+ if (result.length === 0) return [];
2310
+ const scopes = [];
2311
+ for (const row of result[0].values) {
2312
+ const scopeValue = row[0];
2313
+ const scopeOrdinal = row[1] != null ? row[1] : void 0;
2314
+ const eventCount = row[2];
2315
+ const firstTimestamp = row[3];
2316
+ const lastTimestamp = row[4];
2317
+ const catResult = this.db.exec(
2318
+ `SELECT category, COUNT(*) as count FROM events
2319
+ WHERE schema_id = ? AND scope_value = ?
2320
+ GROUP BY category`,
2321
+ [schemaId, scopeValue]
2322
+ );
2323
+ const categories = {};
2324
+ if (catResult.length > 0) {
2325
+ for (const catRow of catResult[0].values) {
2326
+ categories[catRow[0]] = catRow[1];
2327
+ }
2328
+ }
2329
+ scopes.push({
2330
+ scopeValue,
2331
+ scopeOrdinal,
2332
+ eventCount,
2333
+ categories,
2334
+ firstTimestamp,
2335
+ lastTimestamp
2336
+ });
2337
+ }
2338
+ return scopes;
2339
+ }
2340
+ getEventCount(options = {}) {
2341
+ this.initializeSync();
2342
+ const conditions = [];
2343
+ const params = [];
2344
+ if (options.schemaId) {
2345
+ conditions.push("schema_id = ?");
2346
+ params.push(options.schemaId);
2347
+ }
2348
+ if (options.eventType) {
2349
+ conditions.push("event_type = ?");
2350
+ params.push(options.eventType);
2351
+ }
2352
+ if (options.service) {
2353
+ conditions.push("service = ?");
2354
+ params.push(options.service);
2355
+ }
2356
+ if (options.since) {
2357
+ conditions.push("timestamp >= ?");
2358
+ params.push(options.since);
2359
+ }
2360
+ if (options.until) {
2361
+ conditions.push("timestamp <= ?");
2362
+ params.push(options.until);
2363
+ }
2364
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2365
+ const result = this.db.exec(
2366
+ `SELECT COUNT(*) as count FROM events ${whereClause}`,
2367
+ params
2368
+ );
2369
+ if (result.length === 0 || result[0].values.length === 0) return 0;
2370
+ return result[0].values[0][0];
2371
+ }
2372
+ pruneEvents(maxCount) {
2373
+ this.initializeSync();
2374
+ if (maxCount <= 0) return 0;
2375
+ const currentCount = this.getEventCount();
2376
+ if (currentCount <= maxCount) return 0;
2377
+ const deleteCount = currentCount - maxCount;
2378
+ this.db.run(
2379
+ `DELETE FROM events WHERE id IN (
2380
+ SELECT id FROM events ORDER BY timestamp ASC LIMIT ?
2381
+ )`,
2382
+ [deleteCount]
2383
+ );
2384
+ this.save();
2385
+ return deleteCount;
2386
+ }
2387
+ rowToGenericEvent(columns, row) {
2388
+ const obj = {};
2389
+ columns.forEach((col, i) => {
2390
+ obj[col] = row[i];
2391
+ });
2392
+ return {
2393
+ id: obj.id,
2394
+ schemaId: obj.schema_id,
2395
+ eventType: obj.event_type,
2396
+ category: obj.category,
2397
+ timestamp: obj.timestamp,
2398
+ scopeValue: obj.scope_value || void 0,
2399
+ scopeOrdinal: obj.scope_ordinal != null ? obj.scope_ordinal : void 0,
2400
+ sessionId: obj.session_id || void 0,
2401
+ service: obj.service,
2402
+ data: obj.data_json ? JSON.parse(obj.data_json) : void 0,
2403
+ severity: obj.severity || "info",
2404
+ parentEventId: obj.parent_event_id || void 0,
2405
+ depth: obj.depth || 0
2406
+ };
2407
+ }
2408
+ close() {
2409
+ if (this.db) {
2410
+ this.save();
2411
+ this.db.close();
2412
+ this.db = null;
2413
+ }
2414
+ }
2415
+ };
2416
+
2417
+ // src/types.ts
2418
+ var DEFAULT_AUTH_CONFIG = {
2419
+ enabled: false,
2420
+ tokens: []
2421
+ };
2422
+ var DEFAULT_RATE_LIMIT_CONFIG = {
2423
+ enabled: false,
2424
+ global: {
2425
+ maxRequestsPerMinute: 600,
2426
+ maxEntriesPerBatch: 500,
2427
+ samplingRate: 1
2428
+ },
2429
+ perService: {}
2430
+ };
2431
+ var DEFAULT_SERVER_CONFIG = {
2432
+ port: 3838,
2433
+ maxLogs: 1e4,
2434
+ maxBatchSize: 500,
2435
+ wsMaxSubscribers: 256,
2436
+ pruneIntervalInserts: 100,
2437
+ logRetentionDays: 0,
2438
+ auth: DEFAULT_AUTH_CONFIG,
2439
+ rateLimit: DEFAULT_RATE_LIMIT_CONFIG
2440
+ };
2441
+
2442
+ // src/config.ts
2443
+ import * as fs2 from "fs";
2444
+ import * as path2 from "path";
2445
+ var CONFIG_FILES = [".sentinel.yaml", ".sentinel.yml"];
2446
+ function loadConfig(projectDir) {
2447
+ for (const filename of CONFIG_FILES) {
2448
+ const filePath = path2.join(projectDir, filename);
2449
+ if (fs2.existsSync(filePath)) {
2450
+ const content = fs2.readFileSync(filePath, "utf-8");
2451
+ return parseSimpleYaml(content);
2452
+ }
2453
+ }
2454
+ return null;
2455
+ }
2456
+ function writeConfig(projectDir, config) {
2457
+ const filePath = path2.join(projectDir, ".sentinel.yaml");
2458
+ const content = serializeSimpleYaml(config);
2459
+ fs2.writeFileSync(filePath, content, "utf-8");
2460
+ }
2461
+ function parseSimpleYaml(content) {
2462
+ const config = { version: "1.0", project: "" };
2463
+ const lines = content.split("\n");
2464
+ let currentSection = null;
2465
+ let currentSubSection = null;
2466
+ for (const line of lines) {
2467
+ const trimmed = line.trimEnd();
2468
+ if (!trimmed || trimmed.startsWith("#")) continue;
2469
+ const topMatch = trimmed.match(/^(\w+):\s*(.+)$/);
2470
+ if (topMatch) {
2471
+ const [, key, value] = topMatch;
2472
+ if (key === "version") config.version = value.replace(/['"]/g, "");
2473
+ else if (key === "project") config.project = value.replace(/['"]/g, "");
2474
+ else if (key === "environment") config.environment = value.replace(/['"]/g, "");
2475
+ currentSection = null;
2476
+ currentSubSection = null;
2477
+ continue;
2478
+ }
2479
+ const sectionMatch = trimmed.match(/^(\w+):$/);
2480
+ if (sectionMatch) {
2481
+ currentSection = sectionMatch[1];
2482
+ currentSubSection = null;
2483
+ if (currentSection === "symbols" && !config.symbols) {
2484
+ config.symbols = {};
2485
+ }
2486
+ if (currentSection === "routes" && !config.routes) {
2487
+ config.routes = {};
2488
+ }
2489
+ if (currentSection === "scrub" && !config.scrub) {
2490
+ config.scrub = {};
2491
+ }
2492
+ if (currentSection === "server" && !config.server) {
2493
+ config.server = {};
2494
+ }
2495
+ continue;
2496
+ }
2497
+ const subMatch = trimmed.match(/^\s{2}(\w+):$/);
2498
+ if (subMatch && currentSection) {
2499
+ currentSubSection = subMatch[1];
2500
+ if (currentSection === "symbols" && config.symbols) {
2501
+ config.symbols[currentSubSection] = [];
2502
+ }
2503
+ if (currentSection === "scrub" && config.scrub) {
2504
+ config.scrub[currentSubSection] = [];
2505
+ }
2506
+ continue;
2507
+ }
2508
+ const listMatch = trimmed.match(/^\s+-\s+(.+)$/);
2509
+ if (listMatch && currentSection && currentSubSection) {
2510
+ const value = listMatch[1].replace(/['"]/g, "");
2511
+ if (currentSection === "symbols" && config.symbols) {
2512
+ const arr = config.symbols[currentSubSection];
2513
+ if (Array.isArray(arr)) arr.push(value);
2514
+ }
2515
+ if (currentSection === "scrub" && config.scrub) {
2516
+ const arr = config.scrub[currentSubSection];
2517
+ if (Array.isArray(arr)) arr.push(value);
2518
+ }
2519
+ continue;
2520
+ }
2521
+ const routeMatch = trimmed.match(/^\s+(['"]?\/[^'"]+['"]?):\s+['"]?([^'"]+)['"]?$/);
2522
+ if (routeMatch && currentSection === "routes" && config.routes) {
2523
+ const route = routeMatch[1].replace(/['"]/g, "");
2524
+ config.routes[route] = routeMatch[2];
2525
+ continue;
2526
+ }
2527
+ const serverKvMatch = trimmed.match(/^\s+(\w+):\s+(\d+)$/);
2528
+ if (serverKvMatch && currentSection === "server" && config.server) {
2529
+ const key = serverKvMatch[1];
2530
+ const value = parseInt(serverKvMatch[2], 10);
2531
+ if (key in { port: 1, maxLogs: 1, maxBatchSize: 1, wsMaxSubscribers: 1, pruneIntervalInserts: 1, logRetentionDays: 1 }) {
2532
+ config.server[key] = value;
2533
+ }
2534
+ continue;
2535
+ }
2536
+ }
2537
+ return config;
2538
+ }
2539
+ function serializeSimpleYaml(config) {
2540
+ const lines = [];
2541
+ lines.push(`# Sentinel Configuration`);
2542
+ lines.push(`# Auto-generated \u2014 edit freely`);
2543
+ lines.push("");
2544
+ lines.push(`version: "${config.version}"`);
2545
+ lines.push(`project: "${config.project}"`);
2546
+ if (config.environment) {
2547
+ lines.push(`environment: "${config.environment}"`);
2548
+ }
2549
+ if (config.symbols) {
2550
+ lines.push("");
2551
+ lines.push("symbols:");
2552
+ for (const [key, values] of Object.entries(config.symbols)) {
2553
+ if (values && values.length > 0) {
2554
+ lines.push(` ${key}:`);
2555
+ for (const v of values) {
2556
+ lines.push(` - ${v}`);
2557
+ }
2558
+ }
2559
+ }
2560
+ }
2561
+ if (config.routes && Object.keys(config.routes).length > 0) {
2562
+ lines.push("");
2563
+ lines.push("routes:");
2564
+ for (const [route, symbol] of Object.entries(config.routes)) {
2565
+ lines.push(` "${route}": ${symbol}`);
2566
+ }
2567
+ }
2568
+ if (config.scrub) {
2569
+ lines.push("");
2570
+ lines.push("scrub:");
2571
+ if (config.scrub.headers?.length) {
2572
+ lines.push(" headers:");
2573
+ for (const h of config.scrub.headers) {
2574
+ lines.push(` - ${h}`);
2575
+ }
2576
+ }
2577
+ if (config.scrub.fields?.length) {
2578
+ lines.push(" fields:");
2579
+ for (const f of config.scrub.fields) {
2580
+ lines.push(` - ${f}`);
2581
+ }
2582
+ }
2583
+ }
2584
+ if (config.server && Object.keys(config.server).length > 0) {
2585
+ lines.push("");
2586
+ lines.push("server:");
2587
+ for (const [key, value] of Object.entries(config.server)) {
2588
+ if (value !== void 0) {
2589
+ lines.push(` ${key}: ${value}`);
2590
+ }
2591
+ }
2592
+ }
2593
+ lines.push("");
2594
+ return lines.join("\n");
2595
+ }
2596
+ function loadServerConfig(projectDir) {
2597
+ const config = { ...DEFAULT_SERVER_CONFIG };
2598
+ const yamlConfig = projectDir ? loadConfig(projectDir) : null;
2599
+ const globalDir = path2.join(process.env.HOME || "~", ".paradigm");
2600
+ const globalConfig = loadConfig(globalDir);
2601
+ for (const src of [globalConfig, yamlConfig]) {
2602
+ if (src?.server) {
2603
+ if (src.server.port !== void 0) config.port = src.server.port;
2604
+ if (src.server.maxLogs !== void 0) config.maxLogs = src.server.maxLogs;
2605
+ if (src.server.maxBatchSize !== void 0) config.maxBatchSize = src.server.maxBatchSize;
2606
+ if (src.server.wsMaxSubscribers !== void 0) config.wsMaxSubscribers = src.server.wsMaxSubscribers;
2607
+ if (src.server.pruneIntervalInserts !== void 0) config.pruneIntervalInserts = src.server.pruneIntervalInserts;
2608
+ if (src.server.logRetentionDays !== void 0) config.logRetentionDays = src.server.logRetentionDays;
2609
+ }
2610
+ }
2611
+ if (process.env.SENTINEL_PORT) config.port = parseInt(process.env.SENTINEL_PORT, 10);
2612
+ if (process.env.SENTINEL_MAX_LOGS) config.maxLogs = parseInt(process.env.SENTINEL_MAX_LOGS, 10);
2613
+ return config;
2614
+ }
2615
+
2616
+ export {
2617
+ SentinelStorage,
2618
+ DEFAULT_AUTH_CONFIG,
2619
+ DEFAULT_RATE_LIMIT_CONFIG,
2620
+ DEFAULT_SERVER_CONFIG,
2621
+ loadConfig,
2622
+ writeConfig,
2623
+ loadServerConfig
2624
+ };