principles-disciple 1.148.0 → 1.150.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.
@@ -1,731 +0,0 @@
1
- import Database from 'better-sqlite3';
2
- import fs from 'fs';
3
- import path from 'path';
4
- import os from 'os';
5
- import { WorkspaceNotFoundError } from '../config/index.js';
6
- const CENTRAL_DB_DIR = '.central';
7
- const CENTRAL_DB_NAME = 'aggregated.db';
8
- /**
9
- * Central database that aggregates data from all agent workspaces.
10
- * Stored in ~/.openclaw/.central/ (NOT in memory/ which is for embeddings)
11
- */
12
- export class CentralDatabase {
13
- dbPath;
14
- db;
15
- workspaces = [];
16
- _closed = false;
17
- /** Whether this connection has been closed. Used by the singleton to auto-reopen. */
18
- get isClosed() {
19
- return this._closed;
20
- }
21
- constructor(dbPath) {
22
- const openClawDir = os.homedir();
23
- this.dbPath = dbPath
24
- || (process.env.PD_CENTRAL_DB_PATH ? path.resolve(process.env.PD_CENTRAL_DB_PATH) : null)
25
- || path.join(openClawDir, '.openclaw', CENTRAL_DB_DIR, CENTRAL_DB_NAME);
26
- // Ensure directory exists
27
- fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
28
- this.db = new Database(this.dbPath);
29
- this.db.pragma('journal_mode = WAL');
30
- this.db.pragma('synchronous = NORMAL');
31
- this.initSchema();
32
- this.discoverWorkspaces();
33
- }
34
- dispose() {
35
- this.db.close();
36
- this._closed = true;
37
- }
38
- static tableExists(db, tableName) {
39
- const result = db.prepare(`
40
- SELECT name FROM sqlite_master WHERE type='table' AND name=?
41
- `).get(tableName);
42
- return !!result;
43
- }
44
- initSchema() {
45
- this.db.exec(`
46
- CREATE TABLE IF NOT EXISTS schema_version (
47
- version INTEGER NOT NULL
48
- );
49
-
50
- CREATE TABLE IF NOT EXISTS workspaces (
51
- name TEXT PRIMARY KEY,
52
- path TEXT NOT NULL,
53
- last_sync TEXT
54
- );
55
-
56
- CREATE TABLE IF NOT EXISTS workspace_config (
57
- workspace_name TEXT PRIMARY KEY,
58
- enabled INTEGER NOT NULL DEFAULT 1,
59
- display_name TEXT,
60
- sync_enabled INTEGER NOT NULL DEFAULT 1,
61
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
62
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
63
- );
64
-
65
- CREATE TABLE IF NOT EXISTS global_config (
66
- key TEXT PRIMARY KEY,
67
- value TEXT NOT NULL,
68
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
69
- );
70
-
71
- CREATE TABLE IF NOT EXISTS aggregated_sessions (
72
- session_id TEXT PRIMARY KEY,
73
- workspace TEXT NOT NULL,
74
- started_at TEXT NOT NULL,
75
- updated_at TEXT NOT NULL
76
- );
77
-
78
- CREATE TABLE IF NOT EXISTS aggregated_tool_calls (
79
- id INTEGER PRIMARY KEY AUTOINCREMENT,
80
- workspace TEXT NOT NULL,
81
- session_id TEXT NOT NULL,
82
- tool_name TEXT NOT NULL,
83
- outcome TEXT NOT NULL,
84
- duration_ms INTEGER,
85
- error_type TEXT,
86
- error_message TEXT,
87
- created_at TEXT NOT NULL
88
- );
89
-
90
- CREATE TABLE IF NOT EXISTS aggregated_pain_events (
91
- id INTEGER PRIMARY KEY AUTOINCREMENT,
92
- workspace TEXT NOT NULL,
93
- session_id TEXT NOT NULL,
94
- source TEXT NOT NULL,
95
- score REAL NOT NULL,
96
- reason TEXT,
97
- created_at TEXT NOT NULL
98
- );
99
-
100
- CREATE TABLE IF NOT EXISTS aggregated_user_corrections (
101
- id INTEGER PRIMARY KEY AUTOINCREMENT,
102
- workspace TEXT NOT NULL,
103
- session_id TEXT NOT NULL,
104
- correction_cue TEXT,
105
- created_at TEXT NOT NULL
106
- );
107
-
108
- CREATE TABLE IF NOT EXISTS aggregated_principle_events (
109
- id INTEGER PRIMARY KEY AUTOINCREMENT,
110
- workspace TEXT NOT NULL,
111
- principle_id TEXT,
112
- event_type TEXT NOT NULL,
113
- created_at TEXT NOT NULL
114
- );
115
-
116
- CREATE TABLE IF NOT EXISTS aggregated_thinking_events (
117
- id INTEGER PRIMARY KEY AUTOINCREMENT,
118
- workspace TEXT NOT NULL,
119
- session_id TEXT NOT NULL,
120
- model_id TEXT NOT NULL,
121
- matched_pattern TEXT NOT NULL,
122
- created_at TEXT NOT NULL
123
- );
124
-
125
- CREATE TABLE IF NOT EXISTS aggregated_correction_samples (
126
- sample_id TEXT PRIMARY KEY,
127
- workspace TEXT NOT NULL,
128
- session_id TEXT NOT NULL,
129
- bad_assistant_turn_id INTEGER NOT NULL,
130
- quality_score REAL,
131
- review_status TEXT,
132
- created_at TEXT NOT NULL
133
- );
134
-
135
- CREATE TABLE IF NOT EXISTS aggregated_task_outcomes (
136
- id INTEGER PRIMARY KEY AUTOINCREMENT,
137
- workspace TEXT NOT NULL,
138
- session_id TEXT NOT NULL,
139
- task_id TEXT,
140
- outcome TEXT NOT NULL,
141
- created_at TEXT NOT NULL
142
- );
143
-
144
- CREATE TABLE IF NOT EXISTS sync_log (
145
- id INTEGER PRIMARY KEY AUTOINCREMENT,
146
- workspace TEXT NOT NULL,
147
- synced_at TEXT NOT NULL,
148
- records_synced INTEGER NOT NULL
149
- );
150
-
151
- -- Indexes for performance
152
- CREATE INDEX IF NOT EXISTS idx_tool_calls_workspace ON aggregated_tool_calls(workspace);
153
- CREATE INDEX IF NOT EXISTS idx_tool_calls_outcome ON aggregated_tool_calls(outcome);
154
- CREATE INDEX IF NOT EXISTS idx_tool_calls_created ON aggregated_tool_calls(created_at);
155
- CREATE INDEX IF NOT EXISTS idx_pain_workspace ON aggregated_pain_events(workspace);
156
- CREATE INDEX IF NOT EXISTS idx_pain_created ON aggregated_pain_events(created_at);
157
- CREATE INDEX IF NOT EXISTS idx_thinking_workspace ON aggregated_thinking_events(workspace);
158
- CREATE INDEX IF NOT EXISTS idx_thinking_model ON aggregated_thinking_events(model_id);
159
- CREATE INDEX IF NOT EXISTS idx_corrections_workspace ON aggregated_correction_samples(workspace);
160
- CREATE INDEX IF NOT EXISTS idx_sessions_workspace ON aggregated_sessions(workspace);
161
- `);
162
- }
163
- discoverWorkspaces() {
164
- const openClawDir = os.homedir();
165
- const workspacesDir = path.join(openClawDir, '.openclaw');
166
- this.workspaces.length = 0;
167
- if (!fs.existsSync(workspacesDir))
168
- return;
169
- const entries = fs.readdirSync(workspacesDir);
170
- for (const entry of entries) {
171
- if (entry.startsWith('workspace-') && entry !== 'workspace') {
172
- const workspacePath = path.join(workspacesDir, entry);
173
- const stat = fs.statSync(workspacePath);
174
- if (stat.isDirectory()) {
175
- this.workspaces.push({
176
- name: entry,
177
- path: workspacePath,
178
- lastSync: null,
179
- });
180
- }
181
- }
182
- }
183
- }
184
- /**
185
- * Sync data from a single workspace into the central database
186
- */
187
- syncWorkspace(workspaceName) {
188
- const workspace = this.workspaces.find(w => w.name === workspaceName);
189
- if (!workspace) {
190
- throw new WorkspaceNotFoundError(workspaceName);
191
- }
192
- const trajectoryDbPath = path.join(workspace.path, '.state', 'trajectory.db');
193
- if (!fs.existsSync(trajectoryDbPath)) {
194
- return 0;
195
- }
196
- const sourceDb = new Database(trajectoryDbPath, { readonly: true });
197
- let totalSynced = 0;
198
- try {
199
- // Sync sessions
200
- const sessions = sourceDb.prepare(`
201
- SELECT session_id, started_at, updated_at FROM sessions
202
- `).all();
203
- const insertSession = this.db.prepare(`
204
- INSERT OR REPLACE INTO aggregated_sessions (session_id, workspace, started_at, updated_at)
205
- VALUES (?, ?, ?, ?)
206
- `);
207
- for (const s of sessions) {
208
- insertSession.run(s.session_id, workspaceName, s.started_at, s.updated_at);
209
- totalSynced++;
210
- }
211
- // Sync tool_calls
212
- const toolCalls = sourceDb.prepare(`
213
- SELECT session_id, tool_name, outcome, duration_ms, error_type, error_message, created_at
214
- FROM tool_calls
215
- `).all();
216
- const insertTool = this.db.prepare(`
217
- INSERT INTO aggregated_tool_calls
218
- (workspace, session_id, tool_name, outcome, duration_ms, error_type, error_message, created_at)
219
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
220
- `);
221
- for (const t of toolCalls) {
222
- insertTool.run(workspaceName, t.session_id, t.tool_name, t.outcome, t.duration_ms, t.error_type, t.error_message, t.created_at);
223
- totalSynced++;
224
- }
225
- // Sync pain_events
226
- const painEvents = sourceDb.prepare(`
227
- SELECT session_id, source, score, reason, created_at FROM pain_events
228
- `).all();
229
- const insertPain = this.db.prepare(`
230
- INSERT INTO aggregated_pain_events (workspace, session_id, source, score, reason, created_at)
231
- VALUES (?, ?, ?, ?, ?, ?)
232
- `);
233
- for (const p of painEvents) {
234
- insertPain.run(workspaceName, p.session_id, p.source, p.score, p.reason, p.created_at);
235
- totalSynced++;
236
- }
237
- // Sync user corrections
238
- const corrections = sourceDb.prepare(`
239
- SELECT session_id, correction_cue, created_at FROM user_turns
240
- WHERE correction_detected = 1
241
- `).all();
242
- const insertCorr = this.db.prepare(`
243
- INSERT INTO aggregated_user_corrections (workspace, session_id, correction_cue, created_at)
244
- VALUES (?, ?, ?, ?)
245
- `);
246
- for (const c of corrections) {
247
- insertCorr.run(workspaceName, c.session_id, c.correction_cue, c.created_at);
248
- totalSynced++;
249
- }
250
- // Sync principle_events
251
- const principles = sourceDb.prepare(`
252
- SELECT principle_id, event_type, created_at FROM principle_events
253
- `).all();
254
- const insertPrinciple = this.db.prepare(`
255
- INSERT INTO aggregated_principle_events (workspace, principle_id, event_type, created_at)
256
- VALUES (?, ?, ?, ?)
257
- `);
258
- for (const p of principles) {
259
- insertPrinciple.run(workspaceName, p.principle_id, p.event_type, p.created_at);
260
- totalSynced++;
261
- }
262
- // Sync thinking_model_events (may not exist in older workspaces)
263
- if (CentralDatabase.tableExists(sourceDb, 'thinking_model_events')) {
264
- const thinking = sourceDb.prepare(`
265
- SELECT session_id, model_id, matched_pattern, created_at FROM thinking_model_events
266
- `).all();
267
- const insertThinking = this.db.prepare(`
268
- INSERT INTO aggregated_thinking_events (workspace, session_id, model_id, matched_pattern, created_at)
269
- VALUES (?, ?, ?, ?, ?)
270
- `);
271
- for (const t of thinking) {
272
- insertThinking.run(workspaceName, t.session_id, t.model_id, t.matched_pattern, t.created_at);
273
- totalSynced++;
274
- }
275
- }
276
- // Sync correction_samples
277
- const samples = sourceDb.prepare(`
278
- SELECT sample_id, session_id, bad_assistant_turn_id, quality_score, review_status, created_at
279
- FROM correction_samples
280
- `).all();
281
- const insertSample = this.db.prepare(`
282
- INSERT OR REPLACE INTO aggregated_correction_samples
283
- (sample_id, workspace, session_id, bad_assistant_turn_id, quality_score, review_status, created_at)
284
- VALUES (?, ?, ?, ?, ?, ?, ?)
285
- `);
286
- for (const s of samples) {
287
- insertSample.run(s.sample_id, workspaceName, s.session_id, s.bad_assistant_turn_id, s.quality_score, s.review_status, s.created_at);
288
- totalSynced++;
289
- }
290
- // Sync task_outcomes
291
- const outcomes = sourceDb.prepare(`
292
- SELECT session_id, task_id, outcome, created_at FROM task_outcomes
293
- `).all();
294
- const insertOutcome = this.db.prepare(`
295
- INSERT INTO aggregated_task_outcomes (workspace, session_id, task_id, outcome, created_at)
296
- VALUES (?, ?, ?, ?, ?)
297
- `);
298
- for (const o of outcomes) {
299
- insertOutcome.run(workspaceName, o.session_id, o.task_id, o.outcome, o.created_at);
300
- totalSynced++;
301
- }
302
- // Update last sync time
303
- this.db.prepare(`
304
- INSERT OR REPLACE INTO workspaces (name, path, last_sync)
305
- VALUES (?, ?, datetime('now'))
306
- `).run(workspaceName, workspace.path);
307
- // Log sync
308
- this.db.prepare(`
309
- INSERT INTO sync_log (workspace, synced_at, records_synced)
310
- VALUES (?, datetime('now'), ?)
311
- `).run(workspaceName, totalSynced);
312
- return totalSynced;
313
- }
314
- finally {
315
- sourceDb.close();
316
- }
317
- }
318
- syncEnabled() {
319
- const results = new Map();
320
- for (const ws of this.getEnabledWorkspaces()) {
321
- try {
322
- const count = this.syncWorkspace(ws.name);
323
- results.set(ws.name, count);
324
- }
325
- catch (error) {
326
- console.error(`Failed to sync workspace ${ws.name}:`, error);
327
- results.set(ws.name, 0);
328
- }
329
- }
330
- return results;
331
- }
332
- /**
333
- * Sync all workspaces (legacy method - syncs all regardless of config)
334
- */
335
- syncAll() {
336
- const results = new Map();
337
- for (const ws of this.workspaces) {
338
- try {
339
- const count = this.syncWorkspace(ws.name);
340
- results.set(ws.name, count);
341
- }
342
- catch (error) {
343
- console.error(`Failed to sync workspace ${ws.name}:`, error);
344
- results.set(ws.name, 0);
345
- }
346
- }
347
- return results;
348
- }
349
- getEnabledWorkspaceFilter() {
350
- const enabled = this.getWorkspaceConfigs().filter(c => c.enabled && c.syncEnabled);
351
- if (enabled.length === 0)
352
- return "''";
353
- return enabled.map(c => `'${c.workspaceName.replace(/'/g, "''")}'`).join(', ');
354
- }
355
- /**
356
- * Get aggregated overview stats (only from enabled workspaces)
357
- */
358
- getOverviewStats() {
359
- const filter = this.getEnabledWorkspaceFilter();
360
- const totalSessions = this.db.prepare(`
361
- SELECT COUNT(DISTINCT session_id) as count FROM aggregated_sessions
362
- WHERE workspace IN (${filter})
363
- `).get();
364
- const toolStats = this.db.prepare(`
365
- SELECT
366
- COUNT(*) as total,
367
- SUM(CASE WHEN outcome = 'failure' THEN 1 ELSE 0 END) as failures
368
- FROM aggregated_tool_calls
369
- WHERE workspace IN (${filter})
370
- `).get();
371
- const painEvents = this.db.prepare(`
372
- SELECT COUNT(*) as count FROM aggregated_pain_events
373
- WHERE workspace IN (${filter})
374
- `).get();
375
- const corrections = this.db.prepare(`
376
- SELECT COUNT(*) as count FROM aggregated_user_corrections
377
- WHERE workspace IN (${filter})
378
- `).get();
379
- const thinkingEvents = this.db.prepare(`
380
- SELECT COUNT(*) as count FROM aggregated_thinking_events
381
- WHERE workspace IN (${filter})
382
- `).get();
383
- const sampleStats = this.db.prepare(`
384
- SELECT
385
- COUNT(*) as total,
386
- SUM(CASE WHEN review_status = 'pending' THEN 1 ELSE 0 END) as pending,
387
- SUM(CASE WHEN review_status = 'approved' THEN 1 ELSE 0 END) as approved,
388
- SUM(CASE WHEN review_status = 'rejected' THEN 1 ELSE 0 END) as rejected
389
- FROM aggregated_correction_samples
390
- WHERE workspace IN (${filter})
391
- `).get();
392
- const workspaces = this.db.prepare(`
393
- SELECT name FROM workspaces ORDER BY name
394
- `).all();
395
- const enabledConfigs = this.getWorkspaceConfigs().filter(c => c.enabled && c.syncEnabled);
396
- const enabledWorkspaceNames = enabledConfigs.map(c => c.workspaceName);
397
- return {
398
- totalSessions: totalSessions.count,
399
- totalToolCalls: toolStats.total,
400
- totalFailures: toolStats.failures || 0,
401
- totalPainEvents: painEvents.count,
402
- totalCorrections: corrections.count,
403
- totalThinkingEvents: thinkingEvents.count,
404
- totalSamples: sampleStats.total,
405
- pendingSamples: sampleStats.pending || 0,
406
- approvedSamples: sampleStats.approved || 0,
407
- rejectedSamples: sampleStats.rejected || 0,
408
- workspaceCount: workspaces.length,
409
- enabledWorkspaceCount: enabledConfigs.length,
410
- workspaceNames: workspaces.map(w => w.name),
411
- enabledWorkspaceNames,
412
- };
413
- }
414
- /**
415
- * Get daily trend data
416
- */
417
- getDailyTrend(days = 7) {
418
- const cutoffDate = new Date();
419
- cutoffDate.setDate(cutoffDate.getDate() - days);
420
- const [cutoffStr] = cutoffDate.toISOString().split('T');
421
- const toolDaily = this.db.prepare(`
422
- SELECT
423
- substr(created_at, 1, 10) as day,
424
- COUNT(*) as tool_calls,
425
- SUM(CASE WHEN outcome = 'failure' THEN 1 ELSE 0 END) as failures
426
- FROM aggregated_tool_calls
427
- WHERE substr(created_at, 1, 10) >= ?
428
- GROUP BY substr(created_at, 1, 10)
429
- ORDER BY day
430
- `).all(cutoffStr);
431
- const correctionsDaily = this.db.prepare(`
432
- SELECT
433
- substr(created_at, 1, 10) as day,
434
- COUNT(*) as corrections
435
- FROM aggregated_user_corrections
436
- WHERE substr(created_at, 1, 10) >= ?
437
- GROUP BY substr(created_at, 1, 10)
438
- `).all(cutoffStr);
439
- const thinkingDaily = this.db.prepare(`
440
- SELECT
441
- substr(created_at, 1, 10) as day,
442
- COUNT(*) as thinking_turns
443
- FROM aggregated_thinking_events
444
- WHERE substr(created_at, 1, 10) >= ?
445
- GROUP BY substr(created_at, 1, 10)
446
- `).all(cutoffStr);
447
- // Merge all trends
448
- const dayMap = new Map();
449
- for (const t of toolDaily) {
450
- dayMap.set(t.day, {
451
- day: t.day,
452
- toolCalls: t.tool_calls,
453
- failures: t.failures || 0,
454
- userCorrections: 0,
455
- thinkingTurns: 0,
456
- });
457
- }
458
- for (const c of correctionsDaily) {
459
- const existing = dayMap.get(c.day);
460
- if (existing) {
461
- existing.userCorrections = c.corrections;
462
- }
463
- else {
464
- dayMap.set(c.day, {
465
- day: c.day,
466
- toolCalls: 0,
467
- failures: 0,
468
- userCorrections: c.corrections,
469
- thinkingTurns: 0,
470
- });
471
- }
472
- }
473
- for (const t of thinkingDaily) {
474
- const existing = dayMap.get(t.day);
475
- if (existing) {
476
- existing.thinkingTurns = t.thinking_turns;
477
- }
478
- else {
479
- dayMap.set(t.day, {
480
- day: t.day,
481
- toolCalls: 0,
482
- failures: 0,
483
- userCorrections: 0,
484
- thinkingTurns: t.thinking_turns,
485
- });
486
- }
487
- }
488
- return Array.from(dayMap.values()).sort((a, b) => a.day.localeCompare(b.day));
489
- }
490
- /**
491
- * Get top regressions
492
- */
493
- getTopRegressions(limit = 5) {
494
- return this.db.prepare(`
495
- SELECT
496
- tool_name as toolName,
497
- error_type as errorType,
498
- COUNT(*) as occurrences
499
- FROM aggregated_tool_calls
500
- WHERE outcome = 'failure' AND error_type IS NOT NULL
501
- GROUP BY tool_name, error_type
502
- ORDER BY occurrences DESC
503
- LIMIT ?
504
- `).all(limit);
505
- }
506
- /**
507
- * Get thinking model stats
508
- */
509
- getThinkingModelStats() {
510
- const totalModels = this.db.prepare(`
511
- SELECT COUNT(DISTINCT model_id) as count FROM aggregated_thinking_events
512
- `).get();
513
- // Consider a model "active" if it has events in the last 7 days
514
- const recentDate = new Date();
515
- recentDate.setDate(recentDate.getDate() - 7);
516
- const recentStr = recentDate.toISOString();
517
- const activeModels = this.db.prepare(`
518
- SELECT COUNT(DISTINCT model_id) as count FROM aggregated_thinking_events
519
- WHERE created_at >= ?
520
- `).get(recentStr);
521
- const totalToolCalls = this.db.prepare(`
522
- SELECT COUNT(*) as count FROM aggregated_tool_calls
523
- `).get();
524
- const models = this.db.prepare(`
525
- SELECT
526
- model_id as modelId,
527
- COUNT(*) as hits
528
- FROM aggregated_thinking_events
529
- GROUP BY model_id
530
- ORDER BY hits DESC
531
- `).all();
532
- return {
533
- totalModels: totalModels.count,
534
- activeModels: activeModels.count,
535
- models: models.map(m => ({
536
- ...m,
537
- coverageRate: totalToolCalls.count > 0 ? m.hits / totalToolCalls.count : 0,
538
- })),
539
- };
540
- }
541
- /**
542
- * Get workspace list
543
- */
544
- getWorkspaces() {
545
- return this.db.prepare(`
546
- SELECT name, path, last_sync as lastSync FROM workspaces ORDER BY name
547
- `).all();
548
- }
549
- getWorkspaceConfigs() {
550
- const configs = this.db.prepare(`
551
- SELECT workspace_name, enabled, display_name, sync_enabled
552
- FROM workspace_config
553
- ORDER BY workspace_name
554
- `).all();
555
- return configs.map(c => ({
556
- workspaceName: c.workspace_name,
557
- enabled: c.enabled === 1,
558
- displayName: c.display_name,
559
- syncEnabled: c.sync_enabled === 1,
560
- }));
561
- }
562
- updateWorkspaceConfig(workspaceName, updates) {
563
- const existing = this.db.prepare(`
564
- SELECT workspace_name FROM workspace_config WHERE workspace_name = ?
565
- `).get(workspaceName);
566
- if (existing) {
567
- const setClauses = ['updated_at = datetime(\'now\')'];
568
- const params = [];
569
- if (updates.enabled !== undefined) {
570
- setClauses.push('enabled = ?');
571
- params.push(updates.enabled ? 1 : 0);
572
- }
573
- if (updates.displayName !== undefined) {
574
- setClauses.push('display_name = ?');
575
- params.push(updates.displayName);
576
- }
577
- if (updates.syncEnabled !== undefined) {
578
- setClauses.push('sync_enabled = ?');
579
- params.push(updates.syncEnabled ? 1 : 0);
580
- }
581
- params.push(workspaceName);
582
- this.db.prepare(`
583
- UPDATE workspace_config SET ${setClauses.join(', ')} WHERE workspace_name = ?
584
- `).run(...params);
585
- }
586
- else {
587
- this.db.prepare(`
588
- INSERT INTO workspace_config (workspace_name, enabled, display_name, sync_enabled)
589
- VALUES (?, ?, ?, ?)
590
- `).run(workspaceName, updates.enabled !== undefined ? (updates.enabled ? 1 : 0) : 1, updates.displayName ?? null, updates.syncEnabled !== undefined ? (updates.syncEnabled ? 1 : 0) : 1);
591
- }
592
- }
593
- isWorkspaceEnabled(workspaceName) {
594
- const config = this.db.prepare(`
595
- SELECT enabled, sync_enabled FROM workspace_config WHERE workspace_name = ?
596
- `).get(workspaceName);
597
- if (!config)
598
- return true;
599
- return config.enabled === 1 && config.sync_enabled === 1;
600
- }
601
- getEnabledWorkspaces() {
602
- return this.workspaces.filter(ws => this.isWorkspaceEnabled(ws.name));
603
- }
604
- addCustomWorkspace(name, workspacePath) {
605
- if (!this.workspaces.find(ws => ws.name === name)) {
606
- this.workspaces.push({ name, path: workspacePath, lastSync: null });
607
- this.db.prepare(`
608
- INSERT INTO workspaces (name, path, last_sync) VALUES (?, ?, NULL)
609
- `).run(name, workspacePath);
610
- this.db.prepare(`
611
- INSERT INTO workspace_config (workspace_name, enabled, display_name, sync_enabled)
612
- VALUES (?, 1, ?, 1)
613
- `).run(name, name);
614
- }
615
- }
616
- removeWorkspace(workspaceName) {
617
- this.updateWorkspaceConfig(workspaceName, { enabled: false, syncEnabled: false });
618
- }
619
- getGlobalConfig(key) {
620
- const result = this.db.prepare(`
621
- SELECT value FROM global_config WHERE key = ?
622
- `).get(key);
623
- return result?.value ?? null;
624
- }
625
- setGlobalConfig(key, value) {
626
- this.db.prepare(`
627
- INSERT OR REPLACE INTO global_config (key, value, updated_at)
628
- VALUES (?, ?, datetime('now'))
629
- `).run(key, value);
630
- }
631
- /**
632
- * Clear all aggregated data (for testing/reset)
633
- */
634
- clearAll() {
635
- this.db.exec(`
636
- DELETE FROM aggregated_sessions;
637
- DELETE FROM aggregated_tool_calls;
638
- DELETE FROM aggregated_pain_events;
639
- DELETE FROM aggregated_user_corrections;
640
- DELETE FROM aggregated_principle_events;
641
- DELETE FROM aggregated_thinking_events;
642
- DELETE FROM aggregated_correction_samples;
643
- DELETE FROM aggregated_task_outcomes;
644
- DELETE FROM workspaces;
645
- DELETE FROM sync_log;
646
- `);
647
- }
648
- /**
649
- * Get total task outcomes count across enabled workspaces (D-02)
650
- */
651
- getTaskOutcomes() {
652
- const filter = this.getEnabledWorkspaceFilter();
653
- const row = this.db.prepare(`
654
- SELECT COUNT(*) as count FROM aggregated_task_outcomes
655
- WHERE workspace IN (${filter})
656
- `).get();
657
- return row?.count ?? 0;
658
- }
659
- /**
660
- * Get total principle events count across enabled workspaces (D-03)
661
- */
662
- getPrincipleEventCount() {
663
- const filter = this.getEnabledWorkspaceFilter();
664
- const row = this.db.prepare(`
665
- SELECT COUNT(*) as count FROM aggregated_principle_events
666
- WHERE workspace IN (${filter})
667
- `).get();
668
- return row?.count ?? 0;
669
- }
670
- /**
671
- * Get sample counts grouped by review_status across enabled workspaces (D-06)
672
- */
673
- getSampleCountersByStatus() {
674
- const filter = this.getEnabledWorkspaceFilter();
675
- const rows = this.db.prepare(`
676
- SELECT review_status, COUNT(*) as count
677
- FROM aggregated_correction_samples
678
- WHERE workspace IN (${filter})
679
- GROUP BY review_status
680
- `).all();
681
- return Object.fromEntries(rows.map(r => [r.review_status, r.count]));
682
- }
683
- /**
684
- * Get top N most recent pending/approved samples across all enabled workspaces (D-04)
685
- */
686
- getSamplePreview(limit = 5) {
687
- const filter = this.getEnabledWorkspaceFilter();
688
- const rows = this.db.prepare(`
689
- SELECT sample_id, session_id, workspace, quality_score, review_status, created_at
690
- FROM aggregated_correction_samples
691
- WHERE workspace IN (${filter})
692
- AND review_status IN ('pending', 'approved')
693
- ORDER BY created_at DESC
694
- LIMIT ?
695
- `).all(limit);
696
- return rows.map(r => ({
697
- sampleId: r.sample_id,
698
- sessionId: r.session_id,
699
- workspace: r.workspace,
700
- qualityScore: r.quality_score ?? 0,
701
- reviewStatus: r.review_status ?? 'pending',
702
- createdAt: r.created_at,
703
- }));
704
- }
705
- /**
706
- * Get the most recent lastSync timestamp across all workspaces (D-05)
707
- */
708
- getMostRecentSync() {
709
- const row = this.db.prepare(`
710
- SELECT MAX(last_sync) as lastSync FROM workspaces
711
- `).get();
712
- return row?.lastSync ?? null;
713
- }
714
- }
715
- // Singleton instance
716
- let centralDbInstance = null;
717
- export function getCentralDatabase() {
718
- if (!centralDbInstance || centralDbInstance.isClosed) {
719
- centralDbInstance = new CentralDatabase();
720
- }
721
- return centralDbInstance;
722
- }
723
- /**
724
- * Reset the singleton instance. Used for testing.
725
- */
726
- export function resetCentralDatabase() {
727
- if (centralDbInstance && !centralDbInstance.isClosed) {
728
- centralDbInstance.dispose();
729
- }
730
- centralDbInstance = null;
731
- }