Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
import type { BrainEngine } from './engine.ts';
import { engineKey } from './engine-key.ts';
import { LATEST_SCHEMA_VERSION } from './schema-migrations/latest.generated.ts';
const SCHEMA_VERSION_SEEN = Symbol('gbrain.schemaVersionSeen');
const SCHEMA_VERSION_AT_CONNECT = Symbol('gbrain.schemaVersionAtConnect');
type Recorded = { [SCHEMA_VERSION_SEEN]?: number; [SCHEMA_VERSION_AT_CONNECT]?: number };
/** GST-2687: records config `version` on the engine as it just read or wrote it (the connect gate below, migrations); a transaction or view records on its engine. */
export function noteSchemaVersion(engine: object, version: number): void {
const recorded = engineKey(engine) as Recorded;
recorded[SCHEMA_VERSION_SEEN] = Number.isInteger(version) ? version : undefined;
if (recorded[SCHEMA_VERSION_AT_CONNECT] === undefined && Number.isInteger(version)) recorded[SCHEMA_VERSION_AT_CONNECT] = version;
}
/** The first schema version recorded on `engine`, read before this process migrated anything; above 1, the brain's schema existed before this run. */
export function schemaVersionAtConnect(engine: object): number | undefined {
return (engineKey(engine) as Recorded)[SCHEMA_VERSION_AT_CONNECT];
}
/** The schema version `engine` (or the engine a transaction or view belongs to) last recorded, read with no query; undefined when none was. */
export function schemaVersionSeen(engine: object): number | undefined {
return (engineKey(engine) as Recorded)[SCHEMA_VERSION_SEEN];
}
/**
* Cheap probe: does this engine have schema migrations pending?
*
* Reads the `version` config row in a single round-trip (no schema replay,
* no migration apply) and compares it with the generated latest version, so
* it never loads the migration modules themselves (migrate.ts does; it
* re-exports this). Used by `connectEngine` to gate `initSchema()` so
* short-lived CLI invocations on already-migrated brains don't pay the
* full bootstrap-probe + SCHEMA_SQL replay + ledger-check cost on every
* `gbrain stats` / `gbrain query` / `gbrain doctor`.
*
* Defensive: treats a getConfig failure (config table missing, query error)
* as "yes pending" so the caller falls through to the full initSchema path.
* Worst case on a wedged brain is one extra schema replay — same as before.
*
* Closes #651 in cooperation with the post-upgrade auto-apply hook (X1)
* without the perf cost #652 would have introduced on every CLI call.
*/
export async function hasPendingMigrations(engine: BrainEngine): Promise<boolean> {
try {
const currentStr = await engine.getConfig('version');
const current = parseInt(currentStr || '1', 10);
noteSchemaVersion(engine, current);
return current < LATEST_SCHEMA_VERSION;
} catch {
return true;
}
}