Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
5.1 KB
Raw Blame
/**
 * Migration v145 (facts_kind_idea_alter) — F5.
 *
 * Widens the facts.kind CHECK with 'idea'. The constraint shipped INLINE in
 * v45's CREATE TABLE, so Postgres autogenerated its name (facts_kind_check)
 * and pre-v145 brains carry the 5-kind predicate: an INSERT with kind='idea'
 * violates it. v145 probes pg_constraint for the autogen name, drops it if
 * present, and re-adds the widened CHECK under the same deterministic name
 * (the v47 facts_notability_alter alter-counterpart pattern).
 *
 * Pinned contracts:
 * 1. v145 exists with the canonical name, idempotent flag, and a sql block
 *    carrying the probe + the widened 6-kind predicate.
 * 2. Fresh init: the facts kind CHECK admits 'idea'; an INSERT succeeds.
 * 3. Upgrade: on a brain restored to the pre-v145 5-kind CHECK (positive
 *    control: kind='idea' verifiably rejected), a ledger rewind to 144 →
 *    runMigrations swaps the constraint, the INSERT succeeds, re-run applies
 *    nothing, and re-executing the v145 SQL directly converges (drop+re-add
 *    of an identical predicate — exactly one constraint row remains).
 */

import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';

let engine: PGLiteEngine;

const V145_SQL = MIGRATIONS.find(m => m.version === 145)?.sql ?? '';
const WIDENED_LIST = "'event','preference','commitment','belief','fact','idea'";
const NARROW_LIST = "'event','preference','commitment','belief','fact'";

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({ database_url: '' }); // in-memory
  await engine.initSchema();
});

afterAll(async () => {
  await engine.disconnect();
});

/** All facts_kind_check constraint definitions currently on facts. */
async function kindCheckDefs(): Promise<string[]> {
  const rows = await engine.executeRaw<{ def: string }>(
    `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint
      WHERE conname = 'facts_kind_check' AND conrelid = 'facts'::regclass`,
  );
  return rows.map(r => r.def);
}

async function insertIdeaFact(fact: string): Promise<void> {
  await engine.executeRaw(
    `INSERT INTO facts (fact, kind, source) VALUES ($1, 'idea', 'test:v145')`,
    [fact],
  );
}

describe('migration v145 — structure', () => {
  test('exists with canonical name, idempotent flag, probe + widened predicate', () => {
    const v145 = MIGRATIONS.find(m => m.version === 145);
    expect(v145).toBeDefined();
    expect(v145?.name).toBe('facts_kind_idea_alter');
    expect(v145?.idempotent).toBe(true);
    expect(V145_SQL).toContain(`conname = 'facts_kind_check'`);
    expect(V145_SQL).toContain('DROP CONSTRAINT facts_kind_check');
    expect(V145_SQL).toContain(`CHECK (kind IN (${WIDENED_LIST}))`);
    expect(LATEST_VERSION).toBeGreaterThanOrEqual(145);
  });
});

describe('migration v145 — fresh init (PGLite)', () => {
  test("fresh schema's kind CHECK admits 'idea'; INSERT succeeds", async () => {
    const defs = await kindCheckDefs();
    expect(defs).toHaveLength(1);
    expect(defs[0]).toContain('idea');

    await insertIdeaFact('fresh-init idea row');
    const rows = await engine.executeRaw<{ kind: string }>(
      `SELECT kind FROM facts WHERE fact = 'fresh-init idea row'`,
    );
    expect(rows.map(r => r.kind)).toEqual(['idea']);
  });
});

describe('migration v145 — upgrade from a pre-v145 brain (PGLite)', () => {
  test('swaps the 5-kind constraint for the widened one; re-run applies nothing', async () => {
    // Simulate a pre-v145 brain: clear idea rows (they'd violate the narrow
    // CHECK on re-add), then restore the 5-kind constraint under the autogen
    // name v45's inline DDL produced.
    await engine.executeRaw(`DELETE FROM facts WHERE kind = 'idea'`);
    await engine.executeRaw('ALTER TABLE facts DROP CONSTRAINT IF EXISTS facts_kind_check');
    await engine.executeRaw(
      `ALTER TABLE facts ADD CONSTRAINT facts_kind_check CHECK (kind IN (${NARROW_LIST}))`,
    );

    // Positive control: the pre-v145 shape verifiably rejects kind='idea'.
    await expect(insertIdeaFact('blocked idea row')).rejects.toThrow();

    // Apply v145 via the real migration runner (ledger rewind below 145).
    await engine.setConfig('version', '144');
    const res = await runMigrations(engine);
    expect(res.applied).toBeGreaterThanOrEqual(1);
    expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));

    const defs = await kindCheckDefs();
    expect(defs).toHaveLength(1);
    expect(defs[0]).toContain('idea');
    await insertIdeaFact('post-upgrade idea row');

    // Ledger idempotency: re-run applies nothing.
    const rerun = await runMigrations(engine);
    expect(rerun.applied).toBe(0);

    // SQL-level idempotency: re-executing the v145 block on an up-to-date
    // brain converges (conditional drop + re-add of the identical predicate)
    // — no error, still exactly one constraint, still widened.
    await engine.runMigration(145, V145_SQL);
    const after = await kindCheckDefs();
    expect(after).toHaveLength(1);
    expect(after[0]).toContain('idea');
    await insertIdeaFact('post-rerun idea row');
  });
});