Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: pin schemaHistoryDrift and the schema-history capture CLI

garrytana360f2908701
diff --git a/test/schema-history-drift.test.ts b/test/schema-history-drift.test.ts
new file mode 100644
index 0000000000..525cec966b
--- /dev/null
+++ b/test/schema-history-drift.test.ts
@@ -0,0 +1,70 @@
+/**
+ * Value: protects=schemaHistoryDrift reports real catalog drift but tolerates whitespace-only function bodies and paren-only trigger WHEN clauses;
+ * fails_when=the filter swallows a real body, trigger or table difference, or flags a benign reformat, so the history upgrade tests go blind or flaky;
+ * why_new=the upgrade tests only ever see no-drift and never prove the detector can fire; seam=none;
+ * no_claim=real engine catalogs (hand-built snapshots stand in; the upgrade tests cover real brains)
+ */
+import { describe, expect, test } from 'bun:test';
+import type { CatalogSnapshot, CatalogFunction } from './helpers/schema-diff.ts';
+import { schemaHistoryDrift, type InstalledSchema } from './helpers/schema-history.ts';
+
+const fn = (bodySha256: string, over: Partial<CatalogFunction> = {}): CatalogFunction => ({
+ name: 'touch', identityArguments: '', result: 'trigger', kind: 'f', language: 'plpgsql', volatility: 'v',
+ securityDefiner: false, config: [], bodySha256, ...over,
+});
+
+function schema(over: { body?: string; sha?: string; fnOver?: Partial<CatalogFunction>; when?: string; columns?: string[] } = {}): InstalledSchema {
+ const catalog: CatalogSnapshot = {
+ tables: [{
+ name: 'items', relkind: 'r', rowSecurity: false, forceRowSecurity: false,
+ columns: (over.columns ?? ['id', 'pending']).map((name, i) => ({
+ name, ordinal: i + 1, dataType: 'text', udtName: 'text', isNullable: true, columnDefault: null,
+ })),
+ }],
+ viewColumns: [], indexes: [], constraints: [],
+ triggers: [{ name: 'items_touch', table: 'items', definition: `CREATE TRIGGER items_touch AFTER UPDATE ON items FOR EACH ROW WHEN ${over.when ?? '((old.a IS DISTINCT FROM new.a) OR (old.b IS DISTINCT FROM new.b))'} EXECUTE FUNCTION touch()` }],
+ functions: [fn(over.sha ?? 'sha-a', over.fnOver)],
+ views: [], policies: [], grants: [], sequences: [], extensions: [],
+ };
+ return { catalog, functionBodies: new Map([['touch()', over.body ?? 'BEGIN RETURN NULL; END']]) };
+}
+
+describe('schemaHistoryDrift', () => {
+ test('identical installs and a whitespace-only function body difference are not drift', () => {
+ expect(schemaHistoryDrift(schema(), schema())).toBe('');
+ expect(schemaHistoryDrift(schema(), schema({ sha: 'sha-b', body: 'BEGIN\n RETURN NULL;\n END' }))).toBe('');
+ });
+
+ test('a function whose body content or attributes differ is drift, naming the function', () => {
+ expect(schemaHistoryDrift(schema(), schema({ sha: 'sha-b', body: 'BEGIN RETURN NEW; END' }))).toContain('[functions] touch() changed');
+ expect(schemaHistoryDrift(schema(), schema({ sha: 'sha-b', fnOver: { securityDefiner: true } }))).toContain('[functions] touch() changed');
+ });
+
+ test('a changed function whose body is missing from either body map is drift, not a silent pass', () => {
+ const upgraded = schema({ sha: 'sha-b' });
+ upgraded.functionBodies.clear();
+ expect(schemaHistoryDrift(schema(), upgraded)).toContain('[functions] touch() changed');
+ });
+
+ test('a trigger WHEN clause that differs only in parentheses is not drift; a changed expression is', () => {
+ expect(schemaHistoryDrift(schema(), schema({ when: '(old.a IS DISTINCT FROM new.a OR old.b IS DISTINCT FROM new.b)' }))).toBe('');
+ expect(schemaHistoryDrift(schema(), schema({ when: '((old.a IS DISTINCT FROM new.a) OR (old.c IS DISTINCT FROM new.c))' }))).toContain('[triggers] items.items_touch changed');
+ });
+
+ test('a trigger WHEN clause whose arithmetic or call parentheses differ is drift', () => {
+ for (const [a, b] of [['((a + b) * c > 0)', '(a + b * c > 0)'], ['(a - (b - c) > 0)', '(a - b - c > 0)'], ['(lower(a) = b)', '(lower(a = b))']]) {
+ expect(schemaHistoryDrift(schema({ when: a }), schema({ when: b }))).toContain('[triggers] items.items_touch changed');
+ }
+ });
+
+ test('a trigger WHEN clause regrouped across AND and OR is drift, not a parentheses-only difference', () => {
+ expect(schemaHistoryDrift(
+ schema({ when: '(((old.a IS DISTINCT FROM new.a) OR (old.b IS DISTINCT FROM new.b)) AND new.c)' }),
+ schema({ when: '((old.a IS DISTINCT FROM new.a) OR ((old.b IS DISTINCT FROM new.b) AND new.c))' }),
+ )).toContain('[triggers] items.items_touch changed');
+ });
+
+ test('a column the upgraded brain lacks is drift (the #7645 shape)', () => {
+ expect(schemaHistoryDrift(schema(), schema({ columns: ['id'] }))).toContain('[tables] items.pending MISSING');
+ });
+});
diff --git a/test/scripts/capture-schema-history-fixture-cli.test.ts b/test/scripts/capture-schema-history-fixture-cli.test.ts
new file mode 100644
index 0000000000..4271b58930
--- /dev/null
+++ b/test/scripts/capture-schema-history-fixture-cli.test.ts
@@ -0,0 +1,33 @@
+/**
+ * Value: protects=the capture CLI end to end on the current tree: it round-trips, writes a gzipped dump at the latest schema version, and blanks generated secrets;
+ * fails_when=main()'s fidelity gate, the secret blanking or the derived_generation_items.pending column drop out of a captured fixture, or the CLI stops writing --out;
+ * why_new=capture-schema-history-fixture.test.ts calls dumpBrainSchema on a toy schema and never runs main, blankSecrets or the fidelity gate; seam=none;
+ * no_claim=the postgres engine path and older release trees (PGLite on the current tree only)
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { LATEST_VERSION } from '../../src/core/migrate.ts';
+
+const root = resolve(import.meta.dir, '..', '..');
+const dir = mkdtempSync(join(tmpdir(), 'capture-fixture-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+test('capturing the current tree as pglite writes a restorable dump with generated secrets blanked', () => {
+ const out = join(dir, 'fixture.sql.gz');
+ const run = Bun.spawnSync(['bun', 'scripts/capture-schema-history-fixture.ts', '--tree', root, '--engine', 'pglite', '--out', out], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'pipe' });
+ expect(run.stderr.toString()).not.toContain('differs from the release');
+ expect(run.exitCode).toBe(0);
+ expect(run.stdout.toString()).toContain(`schema v${LATEST_VERSION}, pglite`);
+
+ const sql = Buffer.from(Bun.gunzipSync(readFileSync(out))).toString('utf8');
+ expect(sql).toContain(`a fresh brain at schema v${LATEST_VERSION}`);
+ expect(sql).toMatch(/CREATE TABLE "derived_generation_items" \([^;]*"pending" boolean DEFAULT false NOT NULL/);
+ expect(sql).toContain('"token_secret"');
+ expect(sql).not.toMatch(/"token_secret"\s*:\s*"(?!0+")/);
+
+ const usage = Bun.spawnSync(['bun', 'scripts/capture-schema-history-fixture.ts', '--engine', 'pglite'], { cwd: root, env: process.env, stdout: 'pipe', stderr: 'pipe' });
+ expect(usage.exitCode).toBe(1);
+ expect(usage.stderr.toString()).toContain('Usage: capture-schema-history-fixture.ts --tree');
+}, 120_000);