All files / src/storage store.ts

94.91% Statements 634/668
75.25% Branches 73/97
95.83% Functions 23/24
94.91% Lines 634/668

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 6691x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x     75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 76x 76x 75x 75x 75x 75x 75x     75x 75x 75x 75x 75x 75x 75x 75x 75x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 75x 75x 75x 75x 75x 14x 14x 14x 14x 14x 14x 14x 14x 11x 11x 11x 11x 11x 14x 75x 75x 75x 75x 75x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x       2x 2x       2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 75x 75x 75x 75x 75x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x       1x 1x       1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 75x 75x 75x 75x 75x 75x 75x 75x 75x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 75x 75x 75x 75x 75x 16x 16x 16x 16x 16x 16x 16x 16x 14x 14x 14x 14x 16x 16x 16x 16x 75x 75x 75x 75x 75x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x       2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 2x 2x 75x 75x 75x 75x 75x 75x 75x 75x 75x 39x 39x 39x 39x 39x 39x 39x 39x 75x 75x 75x 75x 75x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 75x 75x 75x 75x 75x 4x 4x 4x 4x 4x 4x 4x 4x 75x 75x 75x 75x 75x 2x 2x 2x 2x 2x 2x 2x 2x 75x 75x 75x 75x 75x 75x 75x 75x 75x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 75x 75x 75x 75x 75x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 4x 4x 75x 75x 75x 75x 75x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 75x 75x 75x 75x 75x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 75x 75x 75x 75x 75x 2x 2x 2x 2x 2x 2x 2x 2x 2x 75x 75x 75x 75x 75x 75x 75x 75x 75x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 75x 75x 75x 75x 75x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 75x 1x 1x 1x  
/**
 * SQLite Storage Implementation
 *
 * Provides persistent storage for runs, outcomes, routing rules, and suggestions.
 *
 * @packageDocumentation
 */
 
import Database from 'better-sqlite3';
import { nanoid } from 'nanoid';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
 
import { SCHEMA_SQL, generateSeedSQL } from './schema.js';
import type {
  RunRecord,
  OutcomeRecord,
  RuleRecord,
  SuggestionRecord,
  TaskType,
  RuleSource,
  OutcomeQuality,
} from '../types.js';
 
/**
 * Default database path.
 */
export function getDefaultDbPath(): string {
  return path.join(os.homedir(), '.relayplane', 'data.db');
}
 
/**
 * SQLite storage class for RelayPlane data.
 */
export class Store {
  private db: Database.Database;
  private readonly dbPath: string;
 
  /**
   * Creates a new Store instance.
   *
   * @param dbPath - Path to the SQLite database file. Defaults to ~/.relayplane/data.db
   */
  constructor(dbPath?: string) {
    this.dbPath = dbPath ?? getDefaultDbPath();
 
    // Ensure directory exists
    const dir = path.dirname(this.dbPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
 
    // Open database
    this.db = new Database(this.dbPath);
 
    // Enable WAL mode for better concurrent access
    this.db.pragma('journal_mode = WAL');
 
    // Enable foreign keys
    this.db.pragma('foreign_keys = ON');
 
    // Initialize schema
    this.initializeSchema();
  }
 
  /**
   * Initializes the database schema.
   */
  private initializeSchema(): void {
    this.db.exec(SCHEMA_SQL);
    this.db.exec(generateSeedSQL());
  }
 
  /**
   * Closes the database connection.
   */
  close(): void {
    this.db.close();
  }
 
  /**
   * Gets the database path.
   */
  getDbPath(): string {
    return this.dbPath;
  }
 
  // ============================================================================
  // Runs
  // ============================================================================
 
  /**
   * Records a new run.
   */
  recordRun(run: Omit<RunRecord, 'id' | 'createdAt'>): string {
    const id = nanoid();
    const stmt = this.db.prepare(`
      INSERT INTO runs (id, prompt, system_prompt, task_type, model, success, output, error, duration_ms, tokens_in, tokens_out, metadata, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
    `);
 
    stmt.run(
      id,
      run.prompt,
      run.systemPrompt,
      run.taskType,
      run.model,
      run.success ? 1 : 0,
      run.output,
      run.error,
      run.durationMs,
      run.tokensIn,
      run.tokensOut,
      run.metadata
    );
 
    return id;
  }
 
  /**
   * Gets a run by ID.
   */
  getRun(id: string): RunRecord | null {
    const stmt = this.db.prepare(`
      SELECT id, prompt, system_prompt as systemPrompt, task_type as taskType, model, success, output, error, duration_ms as durationMs, tokens_in as tokensIn, tokens_out as tokensOut, metadata, created_at as createdAt
      FROM runs
      WHERE id = ?
    `);
 
    const row = stmt.get(id) as RunRecord | undefined;
    if (!row) return null;
 
    return {
      ...row,
      success: Boolean(row.success),
    };
  }
 
  /**
   * Gets runs with optional filters.
   */
  getRuns(options?: {
    taskType?: TaskType;
    model?: string;
    limit?: number;
    offset?: number;
    from?: string;
    to?: string;
  }): RunRecord[] {
    const conditions: string[] = [];
    const params: unknown[] = [];
 
    if (options?.taskType) {
      conditions.push('task_type = ?');
      params.push(options.taskType);
    }
 
    if (options?.model) {
      conditions.push('model = ?');
      params.push(options.model);
    }
 
    if (options?.from) {
      conditions.push('created_at >= ?');
      params.push(options.from);
    }
 
    if (options?.to) {
      conditions.push('created_at <= ?');
      params.push(options.to);
    }
 
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const limit = options?.limit ?? 100;
    const offset = options?.offset ?? 0;
 
    const stmt = this.db.prepare(`
      SELECT id, prompt, system_prompt as systemPrompt, task_type as taskType, model, success, output, error, duration_ms as durationMs, tokens_in as tokensIn, tokens_out as tokensOut, metadata, created_at as createdAt
      FROM runs
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ? OFFSET ?
    `);
 
    params.push(limit, offset);
 
    const rows = stmt.all(...params) as RunRecord[];
    return rows.map((row) => ({
      ...row,
      success: Boolean(row.success),
    }));
  }
 
  /**
   * Counts runs with optional filters.
   */
  countRuns(options?: {
    taskType?: TaskType;
    model?: string;
    from?: string;
    to?: string;
  }): number {
    const conditions: string[] = [];
    const params: unknown[] = [];
 
    if (options?.taskType) {
      conditions.push('task_type = ?');
      params.push(options.taskType);
    }
 
    if (options?.model) {
      conditions.push('model = ?');
      params.push(options.model);
    }
 
    if (options?.from) {
      conditions.push('created_at >= ?');
      params.push(options.from);
    }
 
    if (options?.to) {
      conditions.push('created_at <= ?');
      params.push(options.to);
    }
 
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
 
    const stmt = this.db.prepare(`
      SELECT COUNT(*) as count
      FROM runs
      ${whereClause}
    `);
 
    const row = stmt.get(...params) as { count: number };
    return row.count;
  }
 
  // ============================================================================
  // Outcomes
  // ============================================================================
 
  /**
   * Records an outcome for a run.
   */
  recordOutcome(outcome: Omit<OutcomeRecord, 'id' | 'createdAt'>): string {
    const id = nanoid();
    const stmt = this.db.prepare(`
      INSERT INTO outcomes (id, run_id, success, quality, latency_satisfactory, cost_satisfactory, feedback, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
      ON CONFLICT(run_id) DO UPDATE SET
        success = excluded.success,
        quality = excluded.quality,
        latency_satisfactory = excluded.latency_satisfactory,
        cost_satisfactory = excluded.cost_satisfactory,
        feedback = excluded.feedback,
        created_at = datetime('now')
    `);
 
    stmt.run(
      id,
      outcome.runId,
      outcome.success ? 1 : 0,
      outcome.quality,
      outcome.latencySatisfactory != null ? (outcome.latencySatisfactory ? 1 : 0) : null,
      outcome.costSatisfactory != null ? (outcome.costSatisfactory ? 1 : 0) : null,
      outcome.feedback
    );
 
    return id;
  }
 
  /**
   * Gets an outcome for a run.
   */
  getOutcome(runId: string): OutcomeRecord | null {
    const stmt = this.db.prepare(`
      SELECT id, run_id as runId, success, quality, latency_satisfactory as latencySatisfactory, cost_satisfactory as costSatisfactory, feedback, created_at as createdAt
      FROM outcomes
      WHERE run_id = ?
    `);
 
    const row = stmt.get(runId) as OutcomeRecord | undefined;
    if (!row) return null;
 
    return {
      ...row,
      success: Boolean(row.success),
      latencySatisfactory: row.latencySatisfactory != null ? Boolean(row.latencySatisfactory) : null,
      costSatisfactory: row.costSatisfactory != null ? Boolean(row.costSatisfactory) : null,
    };
  }
 
  /**
   * Gets outcomes with optional filters.
   */
  getOutcomes(options?: {
    taskType?: TaskType;
    model?: string;
    limit?: number;
    from?: string;
    to?: string;
  }): Array<OutcomeRecord & { taskType: TaskType; model: string }> {
    const conditions: string[] = [];
    const params: unknown[] = [];
 
    if (options?.taskType) {
      conditions.push('r.task_type = ?');
      params.push(options.taskType);
    }
 
    if (options?.model) {
      conditions.push('r.model = ?');
      params.push(options.model);
    }
 
    if (options?.from) {
      conditions.push('o.created_at >= ?');
      params.push(options.from);
    }
 
    if (options?.to) {
      conditions.push('o.created_at <= ?');
      params.push(options.to);
    }
 
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const limit = options?.limit ?? 100;
 
    const stmt = this.db.prepare(`
      SELECT o.id, o.run_id as runId, o.success, o.quality, o.latency_satisfactory as latencySatisfactory, o.cost_satisfactory as costSatisfactory, o.feedback, o.created_at as createdAt, r.task_type as taskType, r.model
      FROM outcomes o
      JOIN runs r ON o.run_id = r.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ?
    `);
 
    params.push(limit);
 
    const rows = stmt.all(...params) as Array<OutcomeRecord & { taskType: TaskType; model: string }>;
    return rows.map((row) => ({
      ...row,
      success: Boolean(row.success),
      latencySatisfactory: row.latencySatisfactory != null ? Boolean(row.latencySatisfactory) : null,
      costSatisfactory: row.costSatisfactory != null ? Boolean(row.costSatisfactory) : null,
    }));
  }
 
  // ============================================================================
  // Routing Rules
  // ============================================================================
 
  /**
   * Gets a routing rule for a task type.
   */
  getRule(taskType: TaskType): RuleRecord | null {
    const stmt = this.db.prepare(`
      SELECT id, task_type as taskType, preferred_model as preferredModel, source, confidence, sample_count as sampleCount, created_at as createdAt, updated_at as updatedAt
      FROM routing_rules
      WHERE task_type = ?
    `);
 
    return (stmt.get(taskType) as RuleRecord | undefined) ?? null;
  }
 
  /**
   * Sets a routing rule for a task type.
   */
  setRule(taskType: TaskType, preferredModel: string, source: RuleSource, confidence?: number, sampleCount?: number): string {
    const existingRule = this.getRule(taskType);
    const id = existingRule?.id ?? nanoid();
 
    const stmt = this.db.prepare(`
      INSERT INTO routing_rules (id, task_type, preferred_model, source, confidence, sample_count, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
      ON CONFLICT(task_type) DO UPDATE SET
        preferred_model = excluded.preferred_model,
        source = excluded.source,
        confidence = excluded.confidence,
        sample_count = excluded.sample_count,
        updated_at = datetime('now')
    `);
 
    stmt.run(id, taskType, preferredModel, source, confidence ?? null, sampleCount ?? null);
 
    return id;
  }
 
  /**
   * Lists all routing rules.
   */
  listRules(): RuleRecord[] {
    const stmt = this.db.prepare(`
      SELECT id, task_type as taskType, preferred_model as preferredModel, source, confidence, sample_count as sampleCount, created_at as createdAt, updated_at as updatedAt
      FROM routing_rules
      ORDER BY task_type
    `);
 
    return stmt.all() as RuleRecord[];
  }
 
  /**
   * Deletes a routing rule and resets to default.
   */
  deleteRule(taskType: TaskType): boolean {
    // Find the default rule for this task type
    const defaultRule = DEFAULT_ROUTING_RULES.find((r) => r.taskType === taskType);
    if (!defaultRule) return false;
 
    // Reset to default
    this.setRule(taskType, defaultRule.preferredModel, 'default');
    return true;
  }
 
  // ============================================================================
  // Suggestions
  // ============================================================================
 
  /**
   * Records a suggestion.
   */
  recordSuggestion(suggestion: Omit<SuggestionRecord, 'id' | 'createdAt' | 'acceptedAt'>): string {
    const id = nanoid();
    const stmt = this.db.prepare(`
      INSERT INTO suggestions (id, task_type, current_model, suggested_model, reason, confidence, expected_improvement, sample_count, accepted, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
    `);
 
    stmt.run(
      id,
      suggestion.taskType,
      suggestion.currentModel,
      suggestion.suggestedModel,
      suggestion.reason,
      suggestion.confidence,
      suggestion.expectedImprovement,
      suggestion.sampleCount,
      suggestion.accepted ?? null
    );
 
    return id;
  }
 
  /**
   * Gets a suggestion by ID.
   */
  getSuggestion(id: string): SuggestionRecord | null {
    const stmt = this.db.prepare(`
      SELECT id, task_type as taskType, current_model as currentModel, suggested_model as suggestedModel, reason, confidence, expected_improvement as expectedImprovement, sample_count as sampleCount, accepted, created_at as createdAt, accepted_at as acceptedAt
      FROM suggestions
      WHERE id = ?
    `);
 
    const row = stmt.get(id) as SuggestionRecord | undefined;
    if (!row) return null;
 
    return {
      ...row,
      accepted: row.accepted != null ? Boolean(row.accepted) : null,
    };
  }
 
  /**
   * Gets pending (unaccepted) suggestions.
   */
  getPendingSuggestions(): SuggestionRecord[] {
    const stmt = this.db.prepare(`
      SELECT id, task_type as taskType, current_model as currentModel, suggested_model as suggestedModel, reason, confidence, expected_improvement as expectedImprovement, sample_count as sampleCount, accepted, created_at as createdAt, accepted_at as acceptedAt
      FROM suggestions
      WHERE accepted IS NULL
      ORDER BY confidence DESC
    `);
 
    const rows = stmt.all() as SuggestionRecord[];
    return rows.map((row) => ({
      ...row,
      accepted: row.accepted != null ? Boolean(row.accepted) : null,
    }));
  }
 
  /**
   * Accepts a suggestion.
   */
  acceptSuggestion(id: string): boolean {
    const suggestion = this.getSuggestion(id);
    if (!suggestion) return false;
 
    // Update the suggestion
    const updateStmt = this.db.prepare(`
      UPDATE suggestions
      SET accepted = 1, accepted_at = datetime('now')
      WHERE id = ?
    `);
    updateStmt.run(id);
 
    // Update the routing rule
    this.setRule(
      suggestion.taskType,
      suggestion.suggestedModel,
      'learned',
      suggestion.confidence,
      suggestion.sampleCount
    );
 
    return true;
  }
 
  /**
   * Rejects a suggestion.
   */
  rejectSuggestion(id: string): boolean {
    const stmt = this.db.prepare(`
      UPDATE suggestions
      SET accepted = 0, accepted_at = datetime('now')
      WHERE id = ?
    `);
 
    const result = stmt.run(id);
    return result.changes > 0;
  }
 
  // ============================================================================
  // Statistics
  // ============================================================================
 
  /**
   * Gets aggregated statistics.
   */
  getStats(options?: { from?: string; to?: string }): {
    totalRuns: number;
    successfulRuns: number;
    avgDurationMs: number;
    byTaskType: Record<string, { runs: number; successRate: number; avgDurationMs: number }>;
    byModel: Record<string, { runs: number; successRate: number; avgDurationMs: number }>;
  } {
    const conditions: string[] = [];
    const params: unknown[] = [];
 
    if (options?.from) {
      conditions.push('created_at >= ?');
      params.push(options.from);
    }
 
    if (options?.to) {
      conditions.push('created_at <= ?');
      params.push(options.to);
    }
 
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
 
    // Overall stats
    const overallStmt = this.db.prepare(`
      SELECT 
        COUNT(*) as totalRuns,
        SUM(success) as successfulRuns,
        AVG(duration_ms) as avgDurationMs
      FROM runs
      ${whereClause}
    `);
 
    const overall = overallStmt.get(...params) as {
      totalRuns: number;
      successfulRuns: number;
      avgDurationMs: number;
    };
 
    // Stats by task type
    const byTaskTypeStmt = this.db.prepare(`
      SELECT 
        task_type as taskType,
        COUNT(*) as runs,
        AVG(success) as successRate,
        AVG(duration_ms) as avgDurationMs
      FROM runs
      ${whereClause}
      GROUP BY task_type
    `);
 
    const byTaskTypeRows = byTaskTypeStmt.all(...params) as Array<{
      taskType: string;
      runs: number;
      successRate: number;
      avgDurationMs: number;
    }>;
 
    const byTaskType: Record<string, { runs: number; successRate: number; avgDurationMs: number }> = {};
    for (const row of byTaskTypeRows) {
      byTaskType[row.taskType] = {
        runs: row.runs,
        successRate: row.successRate,
        avgDurationMs: row.avgDurationMs,
      };
    }
 
    // Stats by model
    const byModelStmt = this.db.prepare(`
      SELECT 
        model,
        COUNT(*) as runs,
        AVG(success) as successRate,
        AVG(duration_ms) as avgDurationMs
      FROM runs
      ${whereClause}
      GROUP BY model
    `);
 
    const byModelRows = byModelStmt.all(...params) as Array<{
      model: string;
      runs: number;
      successRate: number;
      avgDurationMs: number;
    }>;
 
    const byModel: Record<string, { runs: number; successRate: number; avgDurationMs: number }> = {};
    for (const row of byModelRows) {
      byModel[row.model] = {
        runs: row.runs,
        successRate: row.successRate,
        avgDurationMs: row.avgDurationMs,
      };
    }
 
    return {
      totalRuns: overall.totalRuns,
      successfulRuns: overall.successfulRuns ?? 0,
      avgDurationMs: overall.avgDurationMs ?? 0,
      byTaskType,
      byModel,
    };
  }
 
  /**
   * Gets statistics for learning (outcomes joined with runs).
   */
  getLearningStats(taskType: TaskType): Array<{
    model: string;
    runs: number;
    successRate: number;
    avgDurationMs: number;
    outcomeSuccessRate: number;
  }> {
    const stmt = this.db.prepare(`
      SELECT 
        r.model,
        COUNT(*) as runs,
        AVG(r.success) as successRate,
        AVG(r.duration_ms) as avgDurationMs,
        AVG(CASE WHEN o.success IS NOT NULL THEN o.success ELSE r.success END) as outcomeSuccessRate
      FROM runs r
      LEFT JOIN outcomes o ON r.id = o.run_id
      WHERE r.task_type = ?
      GROUP BY r.model
      HAVING runs >= 5
    `);
 
    return stmt.all(taskType) as Array<{
      model: string;
      runs: number;
      successRate: number;
      avgDurationMs: number;
      outcomeSuccessRate: number;
    }>;
  }
}
 
// Import for seed data
import { DEFAULT_ROUTING_RULES } from './schema.js';