Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: schema-ahead check reads the live migration list; mirror check keeps master's statement
garrytan1d6a2edb5b04
diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 94550f9e3c..60dad96b96 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -84,6 +84,8 @@ export { MIGRATIONS };export const LATEST_VERSION = MIGRATIONS.length > 0? Math.max(...MIGRATIONS.map(m => m.version)): 1;+/** The newest migration runMigrations would apply now, read from the live registry (LATEST_VERSION is fixed at load). */+export const registeredLatestVersion = (): number => Math.max(1, ...MIGRATIONS.map(m => m.version));/*** Row returned by `getIdleBlockers`. The shape is the public contractdiff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.tsindex 21565c97e0..74a263b8c8 100644--- a/src/core/persistence/mirror-read-only.ts+++ b/src/core/persistence/mirror-read-only.ts@@ -31,11 +31,10 @@ export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string,* legacy disk writers (write-through, fact fences, timeline, forget, unfenced facts) skip on it as managed publication does.*/export async function readOnlyCheckout(engine: SqlEngine, sourceId: string, lock = false): Promise<'mirror_read_only' | 'url_clone' | null> {- const [row] = await engine.executeRaw<{ local_path: string | null; config: unknown }>(- `SELECT local_path, config FROM sources WHERE id = $1${lock ? ' FOR SHARE' : ''}`, [sourceId]);+ const [row] = await engine.executeRaw<{ read_only: boolean; local_path: string | null; config: unknown }>(+ `SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only, local_path, config FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);if (!row) return null;- const config = typeof row.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : (row.config ?? {}) as Record<string, unknown>;- if (String(config.mirror_read_only) === 'true') return 'mirror_read_only';+ if (row.read_only === true) return 'mirror_read_only';return await urlCloneReadOnly(engine, sourceId, row) ? 'url_clone' : null;}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex dc33058044..1e424a3b99 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1166,9 +1166,9 @@ export class PGLiteEngine implements BrainEngine {dims = storedIdentity.dimensions;model = storedIdentity.model;}- const { runMigrations, withSchemaMigrationLock } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect+ const { runMigrations, withSchemaMigrationLock, registeredLatestVersion } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connectawait withSchemaMigrationLock(this, async () => {- await assertSchemaNotAhead(async (q) => (await this.db.query<Record<string, unknown>>(q)).rows); // #7776+ await assertSchemaNotAhead(async (q) => (await this.db.query<Record<string, unknown>>(q)).rows, registeredLatestVersion()); // #7776await this.applyForwardReferenceBootstrap();await this.db.exec(getPGLiteSchema(dims, model));diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d2405a32bf..d9d95ac7d8 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -608,7 +608,7 @@ export class PostgresEngine implements BrainEngine {let sqlText = getPostgresSchema(dims, model);// GBRA-467: the schema migration lock covers the bootstrap, the replay and the migrations (holdSchemaMigrationLock).- const { runMigrations, withSchemaMigrationLock } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect+ const { runMigrations, withSchemaMigrationLock, registeredLatestVersion } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connectconst t0 = Date.now();logConnectionEvent({pool: this.connectionManager?.isDualPoolActive() ? 'ddl' : 'read',@@ -617,7 +617,7 @@ export class PostgresEngine implements BrainEngine {});try {await withSchemaMigrationLock(this, async () => {- await assertSchemaNotAhead((q) => pool.unsafe(q)); // #7776: an older binary never replays its schema over a newer one+ await assertSchemaNotAhead((q) => pool.unsafe(q), registeredLatestVersion()); // #7776: an older binary never replays its schema over a newer one// Another initSchema may have recorded an identity between the read above and this lock: check it again here.const lockedIdentity = storedIdentity ? null : await readStoredEmbeddingIdentity(this);if (lockedIdentity?.model) {diff --git a/src/core/schema-client-behind.ts b/src/core/schema-client-behind.tsindex a7207598d0..a7c2d1b654 100644--- a/src/core/schema-client-behind.ts+++ b/src/core/schema-client-behind.ts@@ -10,21 +10,21 @@ import { LATEST_SCHEMA_VERSION } from './schema-migrations/latest.generated.ts';type Query = (sql: string) => Promise<ReadonlyArray<Record<string, unknown>>>;-export function clientBehindError(version: number): OperationError {+export function clientBehindError(version: number, newest = LATEST_SCHEMA_VERSION): OperationError {return opError('client_behind',- `The brain schema is at v${version}, newer than this gbrain binary (v${LATEST_SCHEMA_VERSION}); schema setup refused before replaying this binary's schema, so nothing changed.`,+ `The brain schema is at v${version}, newer than this gbrain binary (v${newest}); schema setup refused before replaying this binary's schema, so nothing changed.`,'Upgrade gbrain on this host (gbrain upgrade) to the release that migrated the database or newer, then rerun the command; reads keep working on this binary meanwhile.',{ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false,why: "An older binary's schema replay would reinstall superseded function bodies over the newer schema; a current binary replays matching ones.",verify: { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'] } } });}-/** Throws `client_behind` when the database's schema version is newer than this binary. */+/** Throws `client_behind` when the database's schema version is newer than `newest`, the newest migration runMigrations would apply. */// engine-sql-ok: a two-statement version probe both engines run on their DDL connection before the schema replay-export async function assertSchemaNotAhead(query: Query): Promise<void> {+export async function assertSchemaNotAhead(query: Query, newest = LATEST_SCHEMA_VERSION): Promise<void> {const [probe] = await query(`SELECT to_regclass('config') IS NOT NULL AS present`);if (!probe?.present) return;const [row] = await query(`SELECT value FROM config WHERE key = 'version'`);const version = parseInt(String(row?.value ?? '0'), 10);- if (version > LATEST_SCHEMA_VERSION) throw clientBehindError(version);+ if (version > newest) throw clientBehindError(version, newest);}diff --git a/test/cycle/dream-reverse-write-commit.test.ts b/test/cycle/dream-reverse-write-commit.test.tsindex 58c1b61513..f6787cb1c6 100644--- a/test/cycle/dream-reverse-write-commit.test.ts+++ b/test/cycle/dream-reverse-write-commit.test.ts@@ -91,7 +91,7 @@ const dirty = (b: Brain) => b.git('status', '--porcelain', '--untracked-files=alconst filesUnder = (dir: string): string[] => !existsSync(dir) ? [] : readdirSync(dir, { recursive: true, withFileTypes: true }).filter(e => e.isFile() && e.name.endsWith('.md')).map(e => e.name);const setMirror = (engine: BrainEngine, sourceId: string, readOnly: boolean) =>- engine.executeRaw(`UPDATE sources SET config = $2::jsonb WHERE id = $1`, [sourceId, JSON.stringify(readOnly ? { mirror_read_only: true } : {})]);+ engine.executeRaw(`UPDATE sources SET config = $2::text::jsonb WHERE id = $1`, [sourceId, JSON.stringify(readOnly ? { mirror_read_only: true } : {})]);const failedHolds = (held: string[], slug: string) => held.filter(h => h.startsWith(`${slug} (write_through_failed`));function refuseCommits(b: Brain): void {