Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
B2: facts queue jobs run in the engine scope they were enqueued from
garrytan502fe2eab7e2
diff --git a/src/core/engine-scope.ts b/src/core/engine-scope.tsindex 165ee4c846..b19810da64 100644--- a/src/core/engine-scope.ts+++ b/src/core/engine-scope.ts@@ -17,6 +17,16 @@ export function withEngineScope<T>(engine: object, fn: () => T): T {return processHasEmbeddedEngines() ? scope.run(engine, fn) : fn();}+/** The engine scope the current call runs in, for deferred work to resume in with runInEngineScope. */+export function currentEngineScope(): object | undefined {+ return scope.getStore();+}++/** Run fn in a captured engine scope, or outside every scope when none was captured, whatever scope the caller is in. */+export function runInEngineScope<T>(engine: object | undefined, fn: () => T): T {+ return engine ? scope.run(engine, fn) : scope.exit(fn);+}+/** True for a call that entered no engine scope while the process holds an open embedded engine. */export function unscopedInEmbeddedProcess(): boolean {return processHoldsEmbeddedEngines() && scope.getStore() === undefined;diff --git a/src/core/facts/queue.ts b/src/core/facts/queue.tsindex 46d78cebc6..0ac0b4f722 100644--- a/src/core/facts/queue.ts+++ b/src/core/facts/queue.ts@@ -21,6 +21,7 @@import { withoutCallerAccess } from '../search/private-visibility.ts';import { currentAIAttribution, withAIAttribution, type AIAttribution } from '../ai/invocation-guard.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';+import { currentEngineScope, runInEngineScope } from '../engine-scope.ts';export interface FactsQueueCounters {enqueued: number;@@ -50,6 +51,8 @@ interface QueueEntry {enqueuedAt: number;/** Model calls the job makes are attributed to whoever enqueued it. */attribution: AIAttribution;+ /** The pump runs in whichever caller's async context started it, so each job resumes its own enqueuer's engine scope. */+ engine: object | undefined;}export class FactsQueue {@@ -104,7 +107,7 @@ export class FactsQueue {this.pending.shift();this.counters.dropped_overflow += 1;}- this.pending.push({ job, sessionId, enqueuedAt: Date.now(), attribution: { ...currentAIAttribution(), effect: 'facts-queue' } });+ this.pending.push({ job, sessionId, enqueuedAt: Date.now(), attribution: { ...currentAIAttribution(), effect: 'facts-queue' }, engine: currentEngineScope() });this.counters.enqueued += 1;// Non-blocking pump: schedule on microtask so callers stay sync. GBRA-218: outside the enqueuing caller's access record.withoutCallerAccess(() => queueMicrotask(() => { void this.pump(); }));@@ -218,7 +221,7 @@ export class FactsQueue {private async runEntry(entry: QueueEntry): Promise<void> {try {- await withAIAttribution(entry.attribution, () => entry.job(this.internalAbort.signal));+ await runInEngineScope(entry.engine, () => withAIAttribution(entry.attribution, () => entry.job(this.internalAbort.signal)));this.counters.completed += 1;} catch (err) {// Don't propagate; caller sees nothing — the queue surface is fire-and-diff --git a/test/engine-gateway.test.ts b/test/engine-gateway.test.tsindex 6aa0599290..a72acc9742 100644--- a/test/engine-gateway.test.ts+++ b/test/engine-gateway.test.ts@@ -15,6 +15,7 @@ import Anthropic from '@anthropic-ai/sdk';import { anthropicClientOptions, resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';import { embeddedEngineInScope } from '../src/core/engine-scope.ts';import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { FactsQueue } from '../src/core/facts/queue.ts';import { makeSubagentHandler } from '../src/core/minions/handlers/subagent.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { applyReranker } from '../src/core/search/rerank.ts';@@ -328,6 +329,31 @@ describe('chat usage and unscoped calls', () => {});});+describe('facts queue', () => {+ test('a queued facts job runs in the scope it was enqueued from, whichever engine started the pump', async () => {+ installStubs();+ configureProcessGateway();+ const keyA = key('a'), keyB = key('b');+ const a = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } }, models: { chat: 'openai:gpt-5.6' } } }));+ const b = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyB } }, models: { chat: 'openai:gpt-5.6' } } }));+ const keyOf = (engine: BrainEngine) => (engine === a ? keyA : keyB);+ try {+ for (const [first, second] of [[a, b], [b, a]]) {+ sent.length = 0;+ const queue = new FactsQueue();+ const job = async () => { await chat({ messages: [{ role: 'user', content: 'extract facts' }] }); };+ withEngineScope(first!, () => queue.enqueue(job, 'shared-session'));+ withEngineScope(second!, () => queue.enqueue(job, 'shared-session'));+ queue.enqueue(job, 'shared-session');+ expect((await queue.drainPending({ timeout: 30_000 })).unfinished).toBe(0);+ expect(sent.filter(s => s.kind === 'chat').map(s => s.auth)).toEqual([`Bearer ${keyOf(first!)}`, `Bearer ${keyOf(second!)}`, `Bearer ${PROCESS_KEY}`]);+ }+ } finally {+ await Promise.all([a.disconnect(), b.disconnect()]);+ }+ }, 120_000);+});+describe('search reranking on an engine', () => {test('search uses the engine\'s settings.ai.models.reranker unless the brain or the call names one', async () => {const engine = await openEngine(settingsFor({ ai: { providers: { voyage: { apiKey: key('v') } }, models: { reranker: 'voyage:rerank-2.5' } } }));