Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: lazy migrations + MCP client SDK, fast-path tests

time-attack03c0417c6aae
diff --git a/scripts/build-schema-migrations.ts b/scripts/build-schema-migrations.ts
index 76bd802d4f..e613d98897 100644
--- a/scripts/build-schema-migrations.ts
+++ b/scripts/build-schema-migrations.ts
@@ -21,7 +21,12 @@
* HISTORICAL_ARRAY_ORDER come first in that order; every other version follows
* ascending. New migrations therefore append in version order.
*
- * Seams for tests: --dir <path> (migrations dir), --out <path> (registry path).
+ * It also writes `latest.generated.ts`, the highest version as a constant, so a
+ * connect-time "anything pending?" check (src/core/migrate-pending.ts) never
+ * loads the ~220 migration modules the registry imports.
+ *
+ * Seams for tests: --dir <path> (migrations dir), --out <path> (registry path),
+ * --out-latest <path> (latest-version path).
*/
import { spawnSync } from 'node:child_process';
@@ -32,6 +37,7 @@ import ts from 'typescript';
const REPO = resolve(import.meta.dir, '..');
const DEFAULT_DIR = join(REPO, 'src/core/schema-migrations');
const REGISTRY_NAME = 'registry.generated.ts';
+const LATEST_NAME = 'latest.generated.ts';
const SEE = 'See: docs/TESTING.md#schema-migration-registry';
/**
@@ -55,7 +61,7 @@ export interface MigrationFile {
export class RegistryError extends Error {}
const FILE_RE = /^v(\d{3,})-([a-z0-9]+(?:-[a-z0-9]+)*)\.ts$/;
-const NON_MIGRATION_FILES = new Set(['types.ts', 'helpers.ts', REGISTRY_NAME]);
+const NON_MIGRATION_FILES = new Set(['types.ts', 'helpers.ts', REGISTRY_NAME, LATEST_NAME]);
export function pad(version: number): string {
return String(version).padStart(3, '0');
@@ -211,6 +217,19 @@ export function renderRegistry(files: MigrationFile[]): string {
].join('\n');
}
+export function renderLatest(files: MigrationFile[]): string {
+ return [
+ '// AUTO-GENERATED by scripts/build-schema-migrations.ts from src/core/schema-migrations/v<NNN>-*.ts.',
+ '// Do not edit or hand-merge. Regenerate: bun run build:schema-migrations',
+ '//',
+ '// The highest schema migration version (migrate.ts LATEST_VERSION), importable without',
+ '// loading the migrations themselves.',
+ '',
+ `export const LATEST_SCHEMA_VERSION = ${files.length > 0 ? Math.max(...files.map((m) => m.version)) : 1};`,
+ '',
+ ].join('\n');
+}
+
export function scaffold(dir: string, rawName: string): string {
if (!/^[a-z0-9]+(?:[_-][a-z0-9]+)*$/.test(rawName)) {
fail(`migration name '${rawName}' is not lower-case snake_case`,
@@ -244,12 +263,14 @@ export function scaffold(dir: string, rawName: string): string {
function main(argv: string[]): number {
let dir = DEFAULT_DIR;
let out: string | undefined;
+ let outLatest: string | undefined;
let check = false;
let newName: string | undefined;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === '--dir') dir = resolve(argv[++i]!);
else if (a === '--out') out = resolve(argv[++i]!);
+ else if (a === '--out-latest') outLatest = resolve(argv[++i]!);
else if (a === '--check') check = true;
else if (a === '--new') newName = argv[++i];
else {
@@ -262,25 +283,31 @@ function main(argv: string[]): number {
return 2;
}
const target = out ?? join(dir, REGISTRY_NAME);
+ const latestTarget = outLatest ?? join(dir, LATEST_NAME);
try {
if (newName) console.log(`Created ${rel(scaffold(dir, newName))}`);
- const text = renderRegistry(scanMigrations(dir));
+ const files = scanMigrations(dir);
+ const outputs: Array<[string, string]> = [[target, renderRegistry(files)], [latestTarget, renderLatest(files)]];
if (check) {
- const committed = existsSync(target) ? readFileSync(target, 'utf8') : '';
- if (committed !== text) {
- console.error([
- `FAIL: ${rel(target)} is stale (does not match the migration files in ${rel(dir)}).`,
- 'Why: the registry is generated; an added, renamed or removed migration file (or a hand edit/merge of the registry) makes it drift.',
- 'Fix: bun run build:schema-migrations (then commit the regenerated registry; never hand-merge it)',
- SEE,
- ].join('\n'));
- return 1;
+ for (const [file, text] of outputs) {
+ const committed = existsSync(file) ? readFileSync(file, 'utf8') : '';
+ if (committed !== text) {
+ console.error([
+ `FAIL: ${rel(file)} is stale (does not match the migration files in ${rel(dir)}).`,
+ 'Why: the registry is generated; an added, renamed or removed migration file (or a hand edit/merge of the registry) makes it drift.',
+ 'Fix: bun run build:schema-migrations (then commit the regenerated registry; never hand-merge it)',
+ SEE,
+ ].join('\n'));
+ return 1;
+ }
+ console.log(`✓ ${rel(file)} is fresh`);
}
- console.log(`✓ ${rel(target)} is fresh`);
return 0;
}
- writeFileSync(target, text);
- console.log(`Generated ${rel(target)}`);
+ for (const [file, text] of outputs) {
+ writeFileSync(file, text);
+ console.log(`Generated ${rel(file)}`);
+ }
return 0;
} catch (e) {
if (e instanceof RegistryError) {
diff --git a/scripts/check-schema-migrations-fresh.sh b/scripts/check-schema-migrations-fresh.sh
index 15c18b16fa..16ccf6afca 100755
--- a/scripts/check-schema-migrations-fresh.sh
+++ b/scripts/check-schema-migrations-fresh.sh
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
-# W3 — CI guard for src/core/schema-migrations/registry.generated.ts freshness.
+# W3 — CI guard for src/core/schema-migrations/registry.generated.ts (and
+# latest.generated.ts) freshness.
#
# Mirrors scripts/check-tool-catalog-fresh.sh: regenerate the registry into a
# tmp file, diff against the committed one, fail on drift. The generator also
@@ -12,22 +13,27 @@
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-COMMITTED="$REPO_ROOT/src/core/schema-migrations/registry.generated.ts"
+DIR="src/core/schema-migrations"
TMP="$(mktemp)"
-trap 'rm -f "$TMP"' EXIT
+TMP_LATEST="$(mktemp)"
+trap 'rm -f "$TMP" "$TMP_LATEST"' EXIT
cd "$REPO_ROOT"
-bun scripts/build-schema-migrations.ts --out "$TMP" >/dev/null
+bun scripts/build-schema-migrations.ts --out "$TMP" --out-latest "$TMP_LATEST" >/dev/null
-if ! diff -q "$COMMITTED" "$TMP" >/dev/null 2>&1; then
- echo "FAIL: src/core/schema-migrations/registry.generated.ts is stale (does not match the migration files)." >&2
- echo "Why: the registry is generated from src/core/schema-migrations/v<NNN>-*.ts; an added, renamed or" >&2
- echo " removed migration file, or a hand edit/merge of the registry, makes it drift." >&2
- echo "Fix: bun run build:schema-migrations (commit the result; never hand-merge the registry)" >&2
- echo "See: docs/TESTING.md#schema-migration-registry" >&2
- echo "" >&2
- diff -u "$COMMITTED" "$TMP" | head -40 >&2 || true
- exit 1
-fi
+for pair in "registry.generated.ts:$TMP" "latest.generated.ts:$TMP_LATEST"; do
+ name="${pair%%:*}"
+ fresh="${pair#*:}"
+ if ! diff -q "$DIR/$name" "$fresh" >/dev/null 2>&1; then
+ echo "FAIL: $DIR/$name is stale (does not match the migration files)." >&2
+ echo "Why: the registry is generated from src/core/schema-migrations/v<NNN>-*.ts; an added, renamed or" >&2
+ echo " removed migration file, or a hand edit/merge of the registry, makes it drift." >&2
+ echo "Fix: bun run build:schema-migrations (commit the result; never hand-merge the registry)" >&2
+ echo "See: docs/TESTING.md#schema-migration-registry" >&2
+ echo "" >&2
+ diff -u "$DIR/$name" "$fresh" | head -40 >&2 || true
+ exit 1
+ fi
+done
-echo "✓ src/core/schema-migrations/registry.generated.ts is fresh"
+echo "✓ src/core/schema-migrations/registry.generated.ts and latest.generated.ts are fresh"
diff --git a/scripts/lib/restamp.ts b/scripts/lib/restamp.ts
index 3698d6ec8b..f303c04fd2 100644
--- a/scripts/lib/restamp.ts
+++ b/scripts/lib/restamp.ts
@@ -230,6 +230,7 @@ export interface LeftoverRef extends AddedLine { oldVersion: number }
/** Generated or regenerated paths: never scanned for leftover references. */
export const GENERATED_PATHS = [
`${MIGRATIONS_DIR}/registry.generated.ts`,
+ `${MIGRATIONS_DIR}/latest.generated.ts`,
'test/fixtures/goldens/migrations/records.json',
'llms.txt',
'llms-full.txt',
diff --git a/src/cli/main.ts b/src/cli/main.ts
index dcc3be5501..894aca065b 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2839,8 +2839,11 @@ async function completeEngineStartup(engine: BrainEngine): Promise<void> {
// itself (the common case); the revised wording fires only when
// migrations are genuinely stuck.
try {
- const { tryRunPendingMigrations } = await import('../core/migrate.ts');
- const result = await tryRunPendingMigrations(engine);
+ // migrate.ts loads every migration module; only a brain that is behind needs it.
+ const { hasPendingMigrations } = await import('../core/migrate-pending.ts');
+ const result = await hasPendingMigrations(engine)
+ ? await (await import('../core/migrate.ts')).tryRunPendingMigrations(engine)
+ : { status: 'not_needed' as const };
if (result.status === 'persistent') {
writeCliNotice(migrationsNotice('Schema migrations are pending: another process attempted them but they did not complete within the retry window (usually transient). If it persists, check `gbrain doctor` for stale advisory locks and `gbrain jobs supervisor status` for crashed migration workers.'));
} else if (result.status === 'error') {
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 5cb16cee51..e5d7e63c88 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -20,8 +20,8 @@
import { randomUUID } from 'node:crypto';
import { isPersistenceIpcMutation } from './persistence/ipc.ts';
import { replayWhilePending } from './persistence/write-wait.ts';
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
-import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import type { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { anySignal } from './abort-check.ts';
import { canonicalCodeFor } from './error-catalogue.ts';
@@ -161,6 +161,28 @@ function rateLimitedMintDetail(retryAfterS: number | undefined): RemoteMcpErrorD
};
}
+type HttpClientSdk = typeof import('@modelcontextprotocol/sdk/client/index.js')
+ & typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js');
+let httpClientSdk: HttpClientSdk | undefined;
+
+/**
+ * The SDK's client + Streamable HTTP transport, loaded by the first remote
+ * call (buildClient). Only thin-client calls use them, so a local CLI command
+ * never pays for their import graph.
+ */
+async function loadHttpClientSdk(): Promise<HttpClientSdk> {
+ httpClientSdk ??= {
+ ...(await import('@modelcontextprotocol/sdk/client/index.js')),
+ ...(await import('@modelcontextprotocol/sdk/client/streamableHttp.js')),
+ };
+ return httpClientSdk;
+}
+
+/** A transport error: only possible once loadHttpClientSdk has loaded the transport that throws it. */
+function isStreamableHttpError(e: unknown): e is StreamableHTTPError {
+ return httpClientSdk !== undefined && e instanceof httpClientSdk.StreamableHTTPError;
+}
+
/**
* v0.31.1: convert any thrown value into a RemoteMcpError. Used by the
* outermost catch in `callRemoteTool` so the dispatcher's exhaustive switch
@@ -204,7 +226,7 @@ export function toRemoteMcpError(e: unknown, mcpUrl: string, signal?: AbortSigna
{
mcp_url: mcpUrl,
kind: 'unreachable',
- ...(e instanceof StreamableHTTPError && e.code !== undefined && e.code > 0
+ ...(isStreamableHttpError(e) && e.code !== undefined && e.code > 0
? { status: e.code } : {}),
},
);
@@ -345,6 +367,7 @@ async function getAccessToken(config: GBrainConfig, force = false, signal?: Abor
* them in fetch so cancellation covers HTTP bodies as well as SDK requests.
*/
async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSignal): Promise<Client> {
+ const { Client, StreamableHTTPClientTransport } = await loadHttpClientSdk();
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {
requestInit: {
headers: {
@@ -511,7 +534,7 @@ export async function callRemoteTool(
// Application errors can contain arbitrary text (including client IDs
// with "401"). Only a rejected HTTP request authorizes a replay.
signal.throwIfAborted();
- if (!(e instanceof StreamableHTTPError) || e.code !== 401) throw e;
+ if (!isStreamableHttpError(e) || e.code !== 401) throw e;
submitted = false; // This attempt was explicitly refused, not accepted.
// Drop cached token and retry once with a fresh mint.
tokenCache.delete(remote.mcp_url);
@@ -533,7 +556,7 @@ export async function callRemoteTool(
} catch (e2) {
if (e2 instanceof RemoteMcpError && e2.detail?.write_request) throw e2;
signal.throwIfAborted();
- if (e2 instanceof StreamableHTTPError && e2.code === 401) {
+ if (isStreamableHttpError(e2) && e2.code === 401) {
submitted = false;
tokenCache.delete(remote.mcp_url);
throw new RemoteMcpError(
diff --git a/src/core/migrate-pending.ts b/src/core/migrate-pending.ts
new file mode 100644
index 0000000000..bd5b31fee2
--- /dev/null
+++ b/src/core/migrate-pending.ts
@@ -0,0 +1,30 @@
+import type { BrainEngine } from './engine.ts';
+import { LATEST_SCHEMA_VERSION } from './schema-migrations/latest.generated.ts';
+
+/**
+ * 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);
+ return current < LATEST_SCHEMA_VERSION;
+ } catch {
+ return true;
+ }
+}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 2fd7e1bd46..9a22dc4a16 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from './engine.ts';
import type { Migration } from './schema-migrations/types.ts';
import { MIGRATIONS } from './schema-migrations/registry.generated.ts';
+import { hasPendingMigrations } from './migrate-pending.ts';
import { setQuietMigrationNotices } from './schema-migrations/helpers.ts';
// runMigrations executes while an initialized engine is live. Keep its helper
// modules in the static graph rather than importing them from async handlers.
@@ -245,31 +246,7 @@ async function runMigrationSQL(
}
}
-/**
- * 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). 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);
- return current < LATEST_VERSION;
- } catch {
- return true;
- }
-}
+export { hasPendingMigrations };
/**
* v0.41.6.0 D4 — race-tolerant CLI-side migration runner.
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 069d01442c..502ebc34b6 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -71,7 +71,6 @@ import {
isNovelDimension, isBackdatedObservation,
} from './chronicle/ontology.ts';
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
-import { runMigrations } from './migrate.ts';
import { supportsHnswIterativeScan } from './vector-index.ts';
import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';
import { beforePlannerRead, plannerRead } from './planner-stats.ts';
@@ -1139,7 +1138,7 @@ export class PGLiteEngine implements BrainEngine {
await this.applyForwardReferenceBootstrap();
await this.db.exec(getPGLiteSchema(dims, model));
- const { applied } = await runMigrations(this);
+ const { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
if (applied > 0) {
process.stderr.write(` ${applied} migration(s) applied\n`);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index ac0ae0be74..8a57153dff 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -61,7 +61,6 @@ import { DREAM_VERDICT_TTL_SECONDS, clampSearchLimit } from './engine.ts';
import { searchLimitCap } from './search/eval-pool-depth.ts';
import { executeRawJsonb, type SqlValue } from './sql-query.ts';
import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
-import { runMigrations } from './migrate.ts';
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { verifySchema } from './schema-verify.ts';
import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';
@@ -559,7 +558,7 @@ export class PostgresEngine implements BrainEngine {
await conn.unsafe(sqlText);
// Run any pending migrations automatically
- const { applied } = await runMigrations(this);
+ const { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
if (applied > 0) {
process.stderr.write(` ${applied} migration(s) applied\n`);
}
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
new file mode 100644
index 0000000000..cbe69fa2f9
--- /dev/null
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -0,0 +1,7 @@
+// AUTO-GENERATED by scripts/build-schema-migrations.ts from src/core/schema-migrations/v<NNN>-*.ts.
+// Do not edit or hand-merge. Regenerate: bun run build:schema-migrations
+//
+// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
+// loading the migrations themselves.
+
+export const LATEST_SCHEMA_VERSION = 222;
diff --git a/test/cli-fast-path.test.ts b/test/cli-fast-path.test.ts
new file mode 100644
index 0000000000..4a44ced508
--- /dev/null
+++ b/test/cli-fast-path.test.ts
@@ -0,0 +1,74 @@
+/**
+ * Cold start: src/cli.ts answers `--version` and top-level help without
+ * loading the dispatcher, and the dispatcher keeps three heavy graphs off
+ * every command (the ~220 schema migrations, the version-upgrade orchestrator
+ * registry and the MCP HTTP client SDK).
+ *
+ * Fails when a static import drags src/cli/main.ts (and with it every
+ * operation and command module) back into the entry point's graph, when the
+ * fast path stops matching the dispatcher's own branches, or when one of the
+ * lazy graphs becomes a static import of the dispatcher again.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { join, resolve } from 'node:path';
+import { cliFastPath } from '../src/cli.ts';
+import { VERSION } from '../src/version.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+
+/** Every module a fresh Bun process holds after importing `file` (import.meta.main stays false). */
+function loadedModules(file: string): string[] {
+ const script = `await import(${JSON.stringify(join(REPO, file))}); console.log(JSON.stringify(Object.keys(require.cache)));`;
+ const r = spawnSync(process.execPath, ['--no-env-file', '-e', script], { cwd: REPO, encoding: 'utf8', timeout: 60_000 });
+ expect(r.status).toBe(0);
+ return JSON.parse(r.stdout.trim().split('\n').pop()!) as string[];
+}
+
+describe('cliFastPath mirrors main()\'s first branches', () => {
+ test('version and help forms take the fast path, global flags included', () => {
+ expect(cliFastPath(['--version'])).toBe('version');
+ expect(cliFastPath(['version'])).toBe('version');
+ expect(cliFastPath(['--quiet', '--version'])).toBe('version');
+ expect(cliFastPath([])).toBe('help');
+ expect(cliFastPath(['--help'])).toBe('help');
+ expect(cliFastPath(['-h'])).toBe('help');
+ expect(cliFastPath(['--quiet'])).toBe('help');
+ });
+
+ test('commands, per-command help and global-flag errors go to the dispatcher', () => {
+ expect(cliFastPath(['get', 'some/page'])).toBeNull();
+ expect(cliFastPath(['get', '--help'])).toBeNull();
+ expect(cliFastPath(['--tools-json'])).toBeNull();
+ expect(cliFastPath(['--brain'])).toBeNull();
+ });
+});
+
+describe('import graphs', () => {
+ test('the entry point does not load the dispatcher or the operation table', () => {
+ const mods = loadedModules('src/cli.ts');
+ expect(mods.some((m) => m.endsWith('/src/cli/main.ts'))).toBe(false);
+ expect(mods.some((m) => m.endsWith('/src/core/operations.ts'))).toBe(false);
+ expect(mods.length).toBeLessThan(150);
+ });
+
+ test('the dispatcher does not statically load migrations, the upgrade registry or the MCP HTTP client', () => {
+ const mods = loadedModules('src/cli/main.ts');
+ expect(mods.filter((m) => /\/src\/core\/schema-migrations\/v\d+-/.test(m))).toEqual([]);
+ expect(mods.some((m) => m.endsWith('/src/core/migrate.ts'))).toBe(false);
+ expect(mods.some((m) => m.endsWith('/src/commands/migrations/index.ts'))).toBe(false);
+ expect(mods.filter((m) => m.includes('/@modelcontextprotocol/sdk/dist/esm/client/'))).toEqual([]);
+ });
+});
+
+describe('fast-path output', () => {
+ test('--version and help print what the dispatcher printed, exit 0', () => {
+ const version = spawnSync(process.execPath, ['--no-env-file', join(REPO, 'src/cli.ts'), '--version'], { cwd: REPO, encoding: 'utf8', timeout: 60_000 });
+ expect(version.status).toBe(0);
+ expect(version.stdout).toBe(`gbrain ${VERSION}\n`);
+ const help = spawnSync(process.execPath, ['--no-env-file', join(REPO, 'src/cli.ts'), '--help'], { cwd: REPO, encoding: 'utf8', timeout: 60_000 });
+ expect(help.status).toBe(0);
+ expect(help.stdout.startsWith(`gbrain ${VERSION} -- personal knowledge brain\n`)).toBe(true);
+ expect(help.stdout).toContain('Run gbrain <command> --help for command-specific help.');
+ });
+});
diff --git a/test/scripts/build-schema-migrations.test.ts b/test/scripts/build-schema-migrations.test.ts
index 3f729e778a..c617a4eeb1 100644
--- a/test/scripts/build-schema-migrations.test.ts
+++ b/test/scripts/build-schema-migrations.test.ts
@@ -17,12 +17,14 @@ import {
HISTORICAL_ARRAY_ORDER,
RegistryError,
registryOrder,
+ renderLatest,
renderRegistry,
scaffold,
scanMigrations,
} from '../../scripts/build-schema-migrations.ts';
import { baseMigrations } from '../../scripts/check-schema-migration-order.ts';
-import { MIGRATIONS } from '../../src/core/migrate.ts';
+import { LATEST_VERSION, MIGRATIONS } from '../../src/core/migrate.ts';
+import { LATEST_SCHEMA_VERSION } from '../../src/core/schema-migrations/latest.generated.ts';
const REPO = resolve(import.meta.dir, '..', '..');
const DIR = join(REPO, 'src/core/schema-migrations');
@@ -57,6 +59,12 @@ describe('committed registry', () => {
expect(readFileSync(join(DIR, 'registry.generated.ts'), 'utf8')).toBe(renderRegistry(scanMigrations(DIR)));
});
+ test('latest.generated.ts is what the generator produces and equals migrate.ts LATEST_VERSION', () => {
+ // test-reads-source-ok[structural]: generated-file freshness contract.
+ expect(readFileSync(join(DIR, 'latest.generated.ts'), 'utf8')).toBe(renderLatest(scanMigrations(DIR)));
+ expect(LATEST_SCHEMA_VERSION).toBe(LATEST_VERSION);
+ });
+
test('covers every migration file once, uses static imports only, and keeps master order', () => {
const files = scanMigrations(DIR);
expect(files.length).toBe(MIGRATIONS.length);
@@ -149,6 +157,20 @@ describe('generator diagnostics (FAIL/Why/Fix/See)', () => {
expect(run().status).toBe(0);
expect(run('--check').status).toBe(0);
});
+
+ test('the latest-version file tracks the highest migration and --check catches it stale', () => {
+ const d = fixture({ 'v002-a.ts': mig(2, 'a'), 'v178-b.ts': mig(178, 'b') });
+ const run = (...args: string[]) => spawnSync('bun', [GENERATOR, '--dir', d, ...args], { encoding: 'utf8' });
+ expect(run().status).toBe(0);
+ expect(readFileSync(join(d, 'latest.generated.ts'), 'utf8')).toContain('export const LATEST_SCHEMA_VERSION = 178;');
+ writeFileSync(join(d, 'v179-c.ts'), mig(179, 'c'));
+ writeFileSync(join(d, 'registry.generated.ts'), renderRegistry(scanMigrations(d)));
+ const stale = run('--check');
+ expect(stale.status).toBe(1);
+ expect(stale.stderr).toContain('latest.generated.ts is stale');
+ expect(run().status).toBe(0);
+ expect(readFileSync(join(d, 'latest.generated.ts'), 'utf8')).toContain('export const LATEST_SCHEMA_VERSION = 179;');
+ });
});
describe('out-of-order landing check', () => {