feat: add backfill-metrics script and cw backfill-metrics CLI command

Populates the agent_metrics table from existing agent_log_chunks data after
the schema migration. Reads chunks in batches of 500, accumulates per-agent
counts in memory, then upserts with additive ON CONFLICT DO UPDATE to match
the ongoing insertChunk write-path behavior.

- apps/server/scripts/backfill-metrics.ts: core backfillMetrics(db) + CLI wrapper backfillMetricsFromPath(dbPath)
- apps/server/scripts/backfill-metrics.test.ts: 8 tests covering all chunk types, malformed JSON, isolation, empty DB, and re-run double-count behavior
- apps/server/cli/index.ts: new top-level `cw backfill-metrics [--db <path>]` command
- docs/database-migrations.md: Post-migration backfill scripts section documenting when and how to run the script

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lukas May
2026-03-06 21:36:08 +01:00
parent 6eb1f8fc2a
commit db2196f1d1
4 changed files with 301 additions and 0 deletions

View File

@@ -13,6 +13,8 @@ import { createDefaultTrpcClient } from './trpc-client.js';
import { createContainer } from '../container.js';
import { findWorkspaceRoot, writeCwrc, defaultCwConfig } from '../config/index.js';
import { createModuleLogger } from '../logger/index.js';
import { backfillMetricsFromPath } from '../scripts/backfill-metrics.js';
import { getDbPath } from '../db/index.js';
/** Environment variable for custom port */
const CW_PORT_ENV = 'CW_PORT';
@@ -134,6 +136,22 @@ export function createCli(serverHandler?: (port?: number) => Promise<void>): Com
}
});
// Backfill metrics command (standalone — no server, no tRPC)
program
.command('backfill-metrics')
.description('Populate agent_metrics table from existing agent_log_chunks (run once after upgrading)')
.option('--db <path>', 'Path to the SQLite database file (defaults to configured DB path)')
.action(async (options: { db?: string }) => {
const dbPath = options.db ?? getDbPath();
console.log(`Backfilling metrics from ${dbPath}...`);
try {
await backfillMetricsFromPath(dbPath);
} catch (error) {
console.error('Backfill failed:', (error as Error).message);
process.exit(1);
}
});
// Agent command group
const agentCommand = program
.command('agent')