SPB Git

Repository Public MIT

migrations.ts 14.2 KB 392 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/migrations.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Versioned, additive SQLite migrations of VQuant Next (contract: docs/next/CONTRACT.md §0).47 *48 * Rules: a migration only creates tables/indexes or adds columns; it never drops, renames or rewrites existing49 * data. Each one is applied once, inside a transaction, and recorded in vq_schema_migrations. `down` documents50 * the exact SQL that removes what the migration added (run by hand for a rollback; older code ignores the51 * additions, so rolling the code back does not require it).52 *53 * The first time a database meets these migrations, a full snapshot is written to backups/pre-next-<date>.db.54 */55import type Database from "better-sqlite3";56import fs from "node:fs";57import path from "node:path";58import { isSqlite, pool } from "../db";59import { logger } from "../utils/logger";6061type Db = Database.Database;6263export interface Migration {64  id: string;65  up(db: Db): void;66  down: string;67}6869const tableExists = (db: Db, table: string) => !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);7071/** Adds a column unless it is already there. */72export function ensureColumn(db: Db, table: string, column: string, ddl: string): void {73  const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];74  if (cols.length > 0 && !cols.some((c) => c.name === column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);75}7677export const MIGRATIONS: Migration[] = [78  {79    id: "001_objects",80    up(db) {81      db.exec(`82        CREATE TABLE IF NOT EXISTS vq_objects (83          owner TEXT NOT NULL,84          kind TEXT NOT NULL,85          id TEXT NOT NULL,86          rev INTEGER NOT NULL,87          seq INTEGER NOT NULL,88          data TEXT NOT NULL,89          created_at INTEGER NOT NULL,90          updated_at INTEGER NOT NULL,91          deleted INTEGER NOT NULL DEFAULT 0,92          device TEXT,93          PRIMARY KEY (owner, kind, id)94        );95        CREATE INDEX IF NOT EXISTS idx_vq_objects_seq ON vq_objects(owner, seq);96        CREATE TABLE IF NOT EXISTS vq_sync_seq (owner TEXT PRIMARY KEY, seq INTEGER NOT NULL);97        CREATE TABLE IF NOT EXISTS vq_object_versions (98          owner TEXT NOT NULL,99          kind TEXT NOT NULL,100          id TEXT NOT NULL,101          rev INTEGER NOT NULL,102          data TEXT NOT NULL,103          updated_at INTEGER NOT NULL,104          device TEXT,105          PRIMARY KEY (owner, kind, id, rev)106        );107      `);108    },109    down: "DROP TABLE vq_object_versions; DROP TABLE vq_sync_seq; DROP TABLE vq_objects;",110  },111  {112    id: "002_usage",113    up(db) {114      db.exec(`115        CREATE TABLE IF NOT EXISTS vq_usage (116          id INTEGER PRIMARY KEY AUTOINCREMENT,117          owner TEXT NOT NULL,118          session_id TEXT,119          generation_id TEXT,120          at INTEGER NOT NULL,121          model TEXT NOT NULL,122          provider TEXT NOT NULL,123          role TEXT NOT NULL,124          input_tokens INTEGER NOT NULL DEFAULT 0,125          output_tokens INTEGER NOT NULL DEFAULT 0,126          cost_usd REAL127        );128        CREATE INDEX IF NOT EXISTS idx_vq_usage_owner_at ON vq_usage(owner, at);129        CREATE INDEX IF NOT EXISTS idx_vq_usage_generation ON vq_usage(generation_id);130      `);131    },132    down: "DROP TABLE vq_usage;",133  },134  {135    id: "003_audit",136    up(db) {137      db.exec(`138        CREATE TABLE IF NOT EXISTS vq_audit (139          id INTEGER PRIMARY KEY AUTOINCREMENT,140          at INTEGER NOT NULL,141          owner TEXT,142          device TEXT,143          action TEXT NOT NULL,144          target TEXT,145          ip TEXT,146          detail TEXT147        );148        CREATE INDEX IF NOT EXISTS idx_vq_audit_owner_at ON vq_audit(owner, at);149      `);150    },151    down: "DROP TABLE vq_audit;",152  },153  {154    id: "004_trace",155    up(db) {156      // tool_calls is normally created lazily by services/toolRuntime.ts (same definition).157      db.exec(`158        CREATE TABLE IF NOT EXISTS tool_calls (159          id INTEGER PRIMARY KEY AUTOINCREMENT,160          at INTEGER NOT NULL,161          session_id TEXT,162          agent TEXT NOT NULL,163          tool TEXT NOT NULL,164          ok INTEGER NOT NULL,165          ms INTEGER NOT NULL,166          attempts INTEGER NOT NULL DEFAULT 1,167          note TEXT,168          error TEXT169        );170        CREATE INDEX IF NOT EXISTS idx_tool_calls_at ON tool_calls(at);171        CREATE INDEX IF NOT EXISTS idx_tool_calls_tool ON tool_calls(tool, ok);172      `);173      ensureColumn(db, "tool_calls", "generation_id", "TEXT");174      ensureColumn(db, "tool_calls", "owner", "TEXT");175      db.exec(`176        CREATE INDEX IF NOT EXISTS idx_tool_calls_generation ON tool_calls(generation_id);177        CREATE TABLE IF NOT EXISTS vq_generation_trace (178          generation_id TEXT PRIMARY KEY,179          owner TEXT NOT NULL,180          session_id TEXT,181          at INTEGER NOT NULL,182          status TEXT,183          data TEXT NOT NULL184        );185        CREATE INDEX IF NOT EXISTS idx_vq_generation_trace_session ON vq_generation_trace(owner, session_id);186      `);187    },188    down: "DROP TABLE vq_generation_trace; ALTER TABLE tool_calls DROP COLUMN generation_id; ALTER TABLE tool_calls DROP COLUMN owner;",189  },190  {191    id: "005_memory_scope",192    up(db) {193      // agent_memories is created lazily by services/workspace.ts; when it is not there yet that module creates it194      // and calls ensureMemoryColumns() itself.195      if (tableExists(db, "agent_memories")) ensureMemoryColumns(db);196    },197    down: "ALTER TABLE agent_memories DROP COLUMN scope; … kind, expires_at, pinned, source (same form).",198  },199  {200    id: "006_quant_jobs",201    up(db) {202      if (tableExists(db, "vq_quant_jobs")) ensureQuantJobColumns(db);203    },204    down: "ALTER TABLE vq_quant_jobs DROP COLUMN progress; … engine_version, project_id, session_id (same form).",205  },206  {207    id: "007_research",208    up(db) {209      // Autonomous research (contract §9): workspaces, the experiment ledger, background runs, research notes and210      // approvals. Owned by server/services/research/store.ts.211      db.exec(`212        CREATE TABLE IF NOT EXISTS vq_research_workspaces (213          id TEXT NOT NULL,214          owner TEXT NOT NULL,215          kind TEXT NOT NULL,216          ref TEXT NOT NULL,217          title TEXT,218          created_at INTEGER NOT NULL,219          updated_at INTEGER NOT NULL,220          PRIMARY KEY (owner, id)221        );222        CREATE TABLE IF NOT EXISTS vq_research_sessions (223          owner TEXT NOT NULL,224          session_id TEXT NOT NULL,225          workspace_id TEXT NOT NULL,226          PRIMARY KEY (owner, session_id)227        );228        CREATE TABLE IF NOT EXISTS vq_experiments (229          id TEXT PRIMARY KEY,230          owner TEXT NOT NULL,231          workspace_id TEXT NOT NULL,232          session_id TEXT,233          generation_id TEXT,234          seq INTEGER NOT NULL,235          kind TEXT NOT NULL,236          title TEXT,237          hypothesis TEXT,238          method TEXT,239          code_ref TEXT,240          code_hash TEXT,241          env_hash TEXT,242          run_id TEXT,243          status TEXT NOT NULL,244          metrics TEXT,245          diagnostics TEXT,246          artifacts TEXT,247          notes TEXT,248          error TEXT,249          started_at INTEGER NOT NULL,250          finished_at INTEGER,251          duration_ms INTEGER252        );253        CREATE INDEX IF NOT EXISTS idx_vq_experiments_ws ON vq_experiments(owner, workspace_id, seq);254        CREATE TABLE IF NOT EXISTS vq_research_runs (255          id TEXT PRIMARY KEY,256          owner TEXT NOT NULL,257          workspace_id TEXT NOT NULL,258          session_id TEXT,259          generation_id TEXT,260          label TEXT,261          code_ref TEXT NOT NULL,262          code_hash TEXT,263          args TEXT,264          network TEXT NOT NULL DEFAULT 'default',265          status TEXT NOT NULL,266          pid INTEGER,267          progress REAL,268          exit_code INTEGER,269          error TEXT,270          limits TEXT,271          started_at INTEGER NOT NULL,272          finished_at INTEGER273        );274        CREATE INDEX IF NOT EXISTS idx_vq_research_runs_ws ON vq_research_runs(owner, workspace_id, started_at);275        CREATE TABLE IF NOT EXISTS vq_research_notes (276          id TEXT PRIMARY KEY,277          owner TEXT NOT NULL,278          workspace_id TEXT NOT NULL,279          kind TEXT NOT NULL,280          title TEXT NOT NULL,281          body TEXT NOT NULL,282          session_id TEXT,283          created_at INTEGER NOT NULL,284          updated_at INTEGER NOT NULL285        );286        CREATE INDEX IF NOT EXISTS idx_vq_research_notes_ws ON vq_research_notes(owner, workspace_id, kind);287        CREATE TABLE IF NOT EXISTS vq_research_approvals (288          id TEXT PRIMARY KEY,289          owner TEXT NOT NULL,290          workspace_id TEXT,291          session_id TEXT,292          generation_id TEXT,293          action TEXT NOT NULL,294          reason TEXT,295          detail TEXT,296          status TEXT NOT NULL,297          created_at INTEGER NOT NULL,298          resolved_at INTEGER,299          device TEXT300        );301        CREATE INDEX IF NOT EXISTS idx_vq_research_approvals_owner ON vq_research_approvals(owner, status, created_at);302      `);303    },304    down: "DROP TABLE vq_research_approvals; DROP TABLE vq_research_notes; DROP TABLE vq_research_runs; DROP TABLE vq_experiments; DROP TABLE vq_research_sessions; DROP TABLE vq_research_workspaces;",305  },306  {307    id: "008_research_figures",308    up(db) {309      // Figures of a research workspace with their linter verdict, so a study reopened later shows what was live.310      db.exec(`311        CREATE TABLE IF NOT EXISTS vq_research_figures (312          id TEXT PRIMARY KEY,313          owner TEXT NOT NULL,314          workspace_id TEXT NOT NULL,315          session_id TEXT,316          generation_id TEXT,317          tool_id TEXT,318          at INTEGER NOT NULL,319          title TEXT,320          url TEXT,321          files TEXT,322          status TEXT NOT NULL,323          fixes TEXT,324          findings TEXT,325          code_hash TEXT326        );327        CREATE INDEX IF NOT EXISTS idx_vq_research_figures_ws ON vq_research_figures(owner, workspace_id, at);328      `);329    },330    down: "DROP TABLE vq_research_figures;",331  },332];333334/** Columns of agent_memories added by VQuant Next (called by the migration and by workspace.ts after its CREATE). */335export function ensureMemoryColumns(db: Db): void {336  ensureColumn(db, "agent_memories", "scope", "TEXT NOT NULL DEFAULT 'user'");337  ensureColumn(db, "agent_memories", "kind", "TEXT NOT NULL DEFAULT 'preference'");338  ensureColumn(db, "agent_memories", "expires_at", "INTEGER");339  ensureColumn(db, "agent_memories", "pinned", "INTEGER NOT NULL DEFAULT 0");340  ensureColumn(db, "agent_memories", "source", "TEXT NOT NULL DEFAULT 'agent'");341}342343/** Columns of vq_quant_jobs added by VQuant Next (called by the migration and by routes/quant.ts after its CREATE). */344export function ensureQuantJobColumns(db: Db): void {345  ensureColumn(db, "vq_quant_jobs", "progress", "REAL");346  ensureColumn(db, "vq_quant_jobs", "engine_version", "TEXT");347  ensureColumn(db, "vq_quant_jobs", "project_id", "TEXT");348  ensureColumn(db, "vq_quant_jobs", "session_id", "TEXT");349}350351let done = false;352353/** Applies pending migrations. Idempotent; called once at boot (and by tests on a temporary database). */354export function runMigrations(db?: Db): string[] {355  if (!db) {356    if (done) return [];357    if (!isSqlite) throw new Error("VQuant Next needs the SQLite database");358    db = pool as Db;359  }360  const firstTime = !tableExists(db, "vq_schema_migrations");361  db.exec("CREATE TABLE IF NOT EXISTS vq_schema_migrations (id TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)");362  const applied = new Set((db.prepare("SELECT id FROM vq_schema_migrations").all() as { id: string }[]).map((r) => r.id));363  const pending = MIGRATIONS.filter((m) => !applied.has(m.id));364365  // One full snapshot before the very first VQuant Next migration touches an existing database.366  if (firstTime && pending.length > 0 && db === pool && tableExists(db, "conversation_sessions") && process.env.VQ_SKIP_MIGRATION_BACKUP !== "1") {367    try {368      const dir = path.join(process.cwd(), "backups");369      fs.mkdirSync(dir, { recursive: true });370      const file = path.join(dir, `pre-next-${new Date().toISOString().slice(0, 10).replace(/-/g, "")}.db`);371      if (!fs.existsSync(file)) {372        db.prepare("VACUUM INTO ?").run(file);373        logger.info(`[migrations] snapshot before VQuant Next: ${file}`);374      }375    } catch (e) {376      throw new Error(`Could not snapshot the database before migrating (${(e as Error).message}); nothing was changed.`);377    }378  }379380  const ran: string[] = [];381  for (const m of pending) {382    db.transaction(() => {383      m.up(db!);384      db!.prepare("INSERT INTO vq_schema_migrations (id, applied_at) VALUES (?, ?)").run(m.id, Date.now());385    })();386    ran.push(m.id);387    logger.info(`[migrations] applied ${m.id}`);388  }389  if (db === pool) done = true;390  return ran;391}392
Files main
Menu

Theme