Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: engine scope entry after the engine-free checks (import refusal, empty type filters), no self-call re-entry, runServeHttp registers inline
garrytanfec065ff6332
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex b101a9b643..af27d02253 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -846,23 +846,20 @@ export async function buildServeHttpApp(app: express.Express, engine: BrainEngin/** The HTTP server runs in a local scope; each POST /mcp enters its engine's scope (serve-http-mcp.ts). */export function runServeHttp(engine: BrainEngine, options: ServeHttpOptions) {- return withLocalScope(() => serveHttp(engine, options));-}--async function serveHttp(engine: BrainEngine, options: ServeHttpOptions) {- const { port, tokenTtl, enableDcr, enableDcrInsecure } = options;- // Express 5 app- const app = express();- const { bind, config, sql, issuerUrl, skillStatus, bootstrapToken, bootstrapFromEnv, suppressBootstrapPrint } =- await buildServeHttpApp(app, engine, options);-- // ---------------------------------------------------------------------------- // Start server- // ---------------------------------------------------------------------------- const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;-- const httpServer = await listenOrRefuse(app, port, bind, options.adoptServer);- console.error(`+ return withLocalScope(async () => {+ const { port, tokenTtl, enableDcr, enableDcrInsecure } = options;+ // Express 5 app+ const app = express();+ const { bind, config, sql, issuerUrl, skillStatus, bootstrapToken, bootstrapFromEnv, suppressBootstrapPrint } =+ await buildServeHttpApp(app, engine, options);++ // ---------------------------------------------------------------------------+ // Start server+ // ---------------------------------------------------------------------------+ const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;++ const httpServer = await listenOrRefuse(app, port, bind, options.adoptServer);+ console.error(`╔══════════════════════════════════════════════════════╗║ GBrain MCP Server v${VERSION.padEnd(37)}║╠══════════════════════════════════════════════════════╣@@ -886,62 +883,63 @@ ${bootstrapFromEnv: `║ Admin Token (paste into /admin login): ║\n║ ${bootstrapToken.substring(0, 50)} ║\n║ ${bootstrapToken.substring(50).padEnd(50)} ║\n╚══════════════════════════════════════════════════════╝`}`);- // #4474: bind the resolve-IPC unix socket under --http too. This is the- // exact posture `gbrain bootstrap harness` targets — without the listener- // every wired lifecycle hook (SessionStart / UserPromptSubmit / PreCompact)- // degrades to `no_serve` forever, and on a PGLite brain there is no local- // recovery (the http serve owns the single-writer lock, so a second stdio- // serve can't provide the socket). Shares the stdio path's wiring via- // bindResolveIpcForServe; best-effort — failure to bind never blocks the- // HTTP server.- const ipcBinding = await bindResolveIpcForServe(- engine,- (await resolveMcpStdioSourceScope(engine)).sourceId,- await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? config),- );- if (ipcBinding.socketPath) {- console.error(` Resolve IPC: ${ipcBinding.socketPath}`);- }+ // #4474: bind the resolve-IPC unix socket under --http too. This is the+ // exact posture `gbrain bootstrap harness` targets — without the listener+ // every wired lifecycle hook (SessionStart / UserPromptSubmit / PreCompact)+ // degrades to `no_serve` forever, and on a PGLite brain there is no local+ // recovery (the http serve owns the single-writer lock, so a second stdio+ // serve can't provide the socket). Shares the stdio path's wiring via+ // bindResolveIpcForServe; best-effort — failure to bind never blocks the+ // HTTP server.+ const ipcBinding = await bindResolveIpcForServe(+ engine,+ (await resolveMcpStdioSourceScope(engine)).sourceId,+ await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? config),+ );+ if (ipcBinding.socketPath) {+ console.error(` Resolve IPC: ${ipcBinding.socketPath}`);+ }- // SIGTERM/SIGHUP route through process-cleanup's pass and then- // `process.exit`, which skips cli.ts's finally-teardown — so on those- // signals the PGLite write handle was never closed. An unclosed PGLite- // can leave the control file pointing at a checkpoint record whose WAL- // page never reached disk; every later start then dies with- // `PANIC: could not locate a valid checkpoint record` (surfaced as the- // misleading WASM-init hint) and the daemon crash-loops until a human- // intervenes. Registering the engine here gives abnormal termination- // the same clean close the SIGINT path already gets via the cli- // teardown. Deregistered on normal return so the cli finally remains- // the single owner of orderly shutdown.- const deregisterIpcCleanup = registerCleanup('resolve-ipc-close', async () => {- ipcBinding.close();- });- // Automatic facts drain (Lane D): the resident HTTP serve owns a PGLite brain the way stdio serve does.- const { startFactsDrainScheduler } = await import('../core/facts/drain-scheduler.ts');- const factsDrain = startFactsDrainScheduler(engine, { owner: 'serve_http', log: (line) => console.error(line) });- // #6317 (B4): one notice when a managed source's sync data stops moving (reader in persistence/sync-movement.ts).- const { startMovementWatch } = await import('../core/persistence/sync-movement.ts');- const movementWatch = startMovementWatch(engine, { log: (line) => console.error(line) });- // #6858 ask 6: on-commit sync of this host's managed checkouts while `sync.on_commit` is on (serve-head-watcher.ts).- const { startServeHeadWatcher } = await import('../core/serve-head-watcher.ts');- const headWatcher = startServeHeadWatcher(engine, { log: (line) => console.error(line), resident: 'serve-http' });- const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', async () => {- await headWatcher.stop();- movementWatch.stop();- await factsDrain.stop();- await engine.disconnect();+ // SIGTERM/SIGHUP route through process-cleanup's pass and then+ // `process.exit`, which skips cli.ts's finally-teardown — so on those+ // signals the PGLite write handle was never closed. An unclosed PGLite+ // can leave the control file pointing at a checkpoint record whose WAL+ // page never reached disk; every later start then dies with+ // `PANIC: could not locate a valid checkpoint record` (surfaced as the+ // misleading WASM-init hint) and the daemon crash-loops until a human+ // intervenes. Registering the engine here gives abnormal termination+ // the same clean close the SIGINT path already gets via the cli+ // teardown. Deregistered on normal return so the cli finally remains+ // the single owner of orderly shutdown.+ const deregisterIpcCleanup = registerCleanup('resolve-ipc-close', async () => {+ ipcBinding.close();+ });+ // Automatic facts drain (Lane D): the resident HTTP serve owns a PGLite brain the way stdio serve does.+ const { startFactsDrainScheduler } = await import('../core/facts/drain-scheduler.ts');+ const factsDrain = startFactsDrainScheduler(engine, { owner: 'serve_http', log: (line) => console.error(line) });+ // #6317 (B4): one notice when a managed source's sync data stops moving (reader in persistence/sync-movement.ts).+ const { startMovementWatch } = await import('../core/persistence/sync-movement.ts');+ const movementWatch = startMovementWatch(engine, { log: (line) => console.error(line) });+ // #6858 ask 6: on-commit sync of this host's managed checkouts while `sync.on_commit` is on (serve-head-watcher.ts).+ const { startServeHeadWatcher } = await import('../core/serve-head-watcher.ts');+ const headWatcher = startServeHeadWatcher(engine, { log: (line) => console.error(line), resident: 'serve-http' });+ const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', async () => {+ await headWatcher.stop();+ movementWatch.stop();+ await factsDrain.stop();+ await engine.disconnect();+ });+ try {+ await waitForHttpServerLifecycle(httpServer);+ } finally {+ await headWatcher.stop();+ movementWatch.stop();+ await factsDrain.stop();+ // Close the IPC listener + reap the socket file on orderly shutdown+ // (abnormal termination goes through the registered cleanup above).+ ipcBinding.close();+ deregisterIpcCleanup();+ deregisterEngineCleanup();+ }});- try {- await waitForHttpServerLifecycle(httpServer);- } finally {- await headWatcher.stop();- movementWatch.stop();- await factsDrain.stop();- // Close the IPC listener + reap the socket file on orderly shutdown- // (abnormal termination goes through the registered cleanup above).- ipcBinding.close();- deregisterIpcCleanup();- deregisterEngineCleanup();- }}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1e386f5dbb..e3b89475ad 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -353,19 +353,12 @@ export async function importFromContent(onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void;} & ImportFenceOptions = {},): Promise<ImportResult> {- if (needsEngineScope(engine)) return withEngineScope(engine, () => importFromContent(engine, slug, content, opts));// Normalize BEFORE any tx write: putPage lowercases via validateSlug but// upsertChunks used to query by the caller's raw slug, so a mixed-case slug// created the page row then failed the chunk upsert with "Page not found",// rolling back the whole import (#430).slug = validateSlug(slug);- // v0.18.0+ multi-source: when caller is syncing under a non-default source,- // every per-page tx call must carry `sourceId` so writes target the right- // (source_id, slug) row. Pre-fix, putPage relied on the schema DEFAULT and- // silently fabricated a duplicate at (default, slug) — causing later- // bare-slug subqueries (getTags, deleteChunks, etc.) to crash with 21000.- const sourceId = opts.sourceId;// Reject oversized payloads before any parsing, chunking, or embedding happens.// Uses Buffer.byteLength to count UTF-8 bytes the same way disk size would,// so the network path behaves identically to the file path.@@ -373,6 +366,23 @@ export async function importFromContent(if (screen.status === 'refused') {return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal, skip_reason: screen.refusal.code };}+ if (needsEngineScope(engine)) return withEngineScope(engine, () => importScreenedContent(engine, slug, content, opts, screen));+ return importScreenedContent(engine, slug, content, opts, screen);+}++async function importScreenedContent(+ engine: BrainEngine,+ slug: string,+ content: string,+ opts: NonNullable<Parameters<typeof importFromContent>[3]>,+ screen: ReturnType<typeof screenImportContent>,+): Promise<ImportResult> {+ // v0.18.0+ multi-source: when caller is syncing under a non-default source,+ // every per-page tx call must carry `sourceId` so writes target the right+ // (source_id, slug) row. Pre-fix, putPage relied on the schema DEFAULT and+ // silently fabricated a duplicate at (default, slug) — causing later+ // bare-slug subqueries (getTags, deleteChunks, etc.) to crash with 21000.+ const sourceId = opts.sourceId;const parsed = (screen as { parsed: ParsedMarkdown }).parsed;if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct content import', { sourceId: sourceId ?? 'default' });// Canonicalize only free-prose fields before protected-fence parsing, hiddendiff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 0285ef9be8..a879cb37df 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -1081,8 +1081,8 @@ export async function hybridSearch(query: string,opts?: HybridSearchOpts,): Promise<SearchResult[]> {- if (needsEngineScope(engine)) return withEngineScope(engine, () => hybridSearch(engine, query, opts));if (opts?.types?.length === 0) return [];+ if (needsEngineScope(engine)) return withEngineScope(engine, () => hybridSearch(engine, query, opts));const timer = opts?._timings ?? UNTIMED;if (opts?.type || opts?.types?.length) {const { expandEngineTypeFilters } = await import('../schema-pack/query-types.ts');@@ -1207,8 +1207,8 @@ export async function hybridSearchCached(query: string,opts?: HybridSearchOpts,): Promise<SearchResult[]> {- if (needsEngineScope(engine)) return withEngineScope(engine, () => hybridSearchCached(engine, query, opts));if (opts?.types?.length === 0) return [];+ if (needsEngineScope(engine)) return withEngineScope(engine, () => hybridSearchCached(engine, query, opts));const timer = opts?._timings ?? UNTIMED;const { modeInputForCache, resolvedForCache, knobsHash } = await timer.stage('setup', () => resolveCacheSearchMode(engine, opts));const queryPrefix = opts?._queryPrefix ?? await timer.stage('setup', () => loadEmbeddingQueryPrefix(engine));