Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
notifier: search carries freshness only once the brain opts in or a resident recorded coverage
garrytan7cddb9bb457c
diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.tsindex 7b1182f093..2074fae15b 100644--- a/src/core/notifier/status.ts+++ b/src/core/notifier/status.ts@@ -12,8 +12,11 @@ import type { Action } from '../agent-output.ts';import { localHostId } from '../persistence/identity.ts';import { missingTable, type DetectionMode, type NotifierState } from './store.ts';import { residentNotifier } from './resident.ts';+import { parseOnCommit } from '../commit-notifier.ts';+import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';type Exec = Pick<BrainEngine, 'executeRaw' | 'kind'>;+type FreshnessExec = Exec & Pick<BrainEngine, 'getConfig'>;export type FreshnessState = 'current' | 'behind' | 'syncing' | 'unknown' | 'not_monitored';@@ -83,18 +86,34 @@ function freshnessOf(engine: Exec, row: Row, held: number): SourceFreshness {return { ...base, state: behind ? 'behind' : 'current' };}+/**+ * Whether search carries the freshness notice: the brain opted in (`sync.on_commit` on) or a resident has recorded+ * coverage for some source. A brain that never ran a resident with the flag off keeps its search output unchanged;+ * once the notice is on, a source nobody watches still reads not_monitored.+ */+async function freshnessReported(engine: FreshnessExec): Promise<boolean> {+ const [flag, [covered]] = await Promise.all([+ engine.getConfig(SYNC_ON_COMMIT_KEY),+ engine.executeRaw<{ covered: unknown }>('SELECT EXISTS (SELECT 1 FROM sync_notifier_sources WHERE observed_at IS NOT NULL) AS covered'),+ ]);+ return parseOnCommit(flag) || truthy(covered?.covered);+}+/*** The freshness notice for search and query: one entry per source in the caller's scope, from the cached coverage- * record. A brain without the v261 tables, or a failed read, answers unknown for the scope instead of failing the search.+ * record, or none when the brain does not report freshness (freshnessReported). A brain without the v261 tables reports+ * none; another failed read answers unknown for the scope instead of failing the search.*/-export async function readSourceFreshness(engine: Exec, scope: { sourceId?: string; sourceIds?: string[] }, held: ReadonlyArray<{ source_id: string; missing: number; stale: number }> = []): Promise<SourceFreshness[]> {+export async function readSourceFreshness(engine: FreshnessExec, scope: { sourceId?: string; sourceIds?: string[] }, held: ReadonlyArray<{ source_id: string; missing: number; stale: number }> = []): Promise<SourceFreshness[]> {const ids = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);if (ids && ids.length === 0) return [];const heldBy = new Map(held.map(h => [h.source_id, h.missing + h.stale]));try {+ if (!await freshnessReported(engine)) return [];return (await readRows(engine, ids)).map(row => freshnessOf(engine, row, heldBy.get(row.id) ?? 0));} catch (error) {- if (!missingTable(error)) console.error(`[notifier] reading source freshness failed: ${error instanceof Error ? error.message : String(error)}`);+ if (missingTable(error)) return [];+ console.error(`[notifier] reading source freshness failed: ${error instanceof Error ? error.message : String(error)}`);return (ids ?? []).map(id => ({ source_id: id, state: 'unknown' as const, observed_head: null, observed_at: null, mode: null, held_count: heldBy.get(id) ?? 0 }));}}diff --git a/test/pathological/s-notifier-freshness-status.test.ts b/test/pathological/s-notifier-freshness-status.test.tsindex a14c0dfe09..299076b6b9 100644--- a/test/pathological/s-notifier-freshness-status.test.ts+++ b/test/pathological/s-notifier-freshness-status.test.ts@@ -69,20 +69,39 @@ async function printed(run: () => Promise<void>): Promise<string> {return out.join('\n');}-async function searchFreshness(engine: BrainEngine, remote: boolean): Promise<Array<Record<string, unknown>>> {+/** The search response's freshness entries; undefined when the response carries no freshness key at all. */+async function searchFreshnessKey(engine: BrainEngine, remote: boolean): Promise<Array<Record<string, unknown>> | undefined> {const meta: Array<{ key: string; value: unknown }> = [];const ctx = { engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: SOURCE,emitResponseMeta: (key: string, value: unknown) => { meta.push({ key, value }); } } as unknown as OperationContext;const rows = await operations.find(o => o.name === 'search')!.handler(ctx, { query: 'juniper' }) as Array<{ slug: string }>;expect(rows.map(r => r.slug)).toContain('notes/alice-example');const retrieval = meta.find(m => m.key === 'retrieval')?.value as { freshness?: Array<Record<string, unknown>> } | undefined;- return retrieval?.freshness ?? [];+ expect(retrieval).toBeDefined();+ return retrieval!.freshness;}+const searchFreshness = async (engine: BrainEngine, remote: boolean) => (await searchFreshnessKey(engine, remote)) ?? [];for (const { backend, databaseUrl } of pathologicalArms()) {describe(`notifier status and search freshness (${backend})`, () => {- test('no resident: search reads not_monitored and the notifier block names no resident with the fix', async () => {+ test('the freshness gate: absent until the brain opts in or a resident records coverage, then not_monitored for an unwatched source', async () => {await classicBrain(databaseUrl, async ({ engine }) => {+ await engine.setConfig('sync.on_commit', 'false');+ expect(await searchFreshnessKey(engine, false)).toBeUndefined();+ // The classic sync above recorded this host as the syncer (a row with no coverage); a resident's observation adds it.+ await engine.executeRaw('UPDATE sync_notifier_sources SET observed_at = now(), detection_mode = $2, owner_host_id = $3, owner_kind = $4, owner_pid = $5 WHERE source_id = $1',+ [SOURCE, 'poll', '00000000-0000-4000-8000-0000000000bb', 'serve', 1]);+ expect(await searchFreshnessKey(engine, false)).toEqual([expect.objectContaining({ source_id: SOURCE, state: 'not_monitored' })]);+ await engine.executeRaw('UPDATE sync_notifier_sources SET observed_at = NULL, detection_mode = NULL, owner_host_id = NULL, owner_kind = NULL, owner_pid = NULL WHERE source_id = $1', [SOURCE]);+ expect(await searchFreshnessKey(engine, false)).toBeUndefined();+ await engine.setConfig('sync.on_commit', 'true');+ expect(await searchFreshnessKey(engine, false)).toEqual([expect.objectContaining({ source_id: SOURCE, state: 'not_monitored', held_count: 0 })]);+ });+ }, 120_000);++ test('no resident: with sync.on_commit on, search reads not_monitored and the notifier block names no resident with the fix', async () => {+ await classicBrain(databaseUrl, async ({ engine }) => {+ await engine.setConfig('sync.on_commit', 'true');const fresh = await searchFreshness(engine, false);expect(fresh).toEqual([expect.objectContaining({ source_id: SOURCE, state: 'not_monitored', held_count: 0 })]);const block = await readNotifierBlock(engine, SOURCE);diff --git a/test/pathological/s-notifier-residents.test.ts b/test/pathological/s-notifier-residents.test.tsindex af930f9e77..4b95fa167a 100644--- a/test/pathological/s-notifier-residents.test.ts+++ b/test/pathological/s-notifier-residents.test.ts@@ -109,6 +109,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {await brain(databaseUrl, async engine => {await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('acme-example','acme-example','/nonexistent/acme-example','{}') ON CONFLICT (id) DO NOTHING");await engine.executeRaw('INSERT INTO sync_notifier_sources (source_id, syncer_host_id) VALUES ($1, $2) ON CONFLICT (source_id) DO UPDATE SET syncer_host_id = EXCLUDED.syncer_host_id', ['acme-example', HOST]);+ await engine.setConfig('sync.on_commit', 'true');__resetResidentNotifierForTests();let revParses = 0;const lines: string[] = [];@@ -122,7 +123,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(fresh).toEqual([expect.objectContaining({ source_id: 'acme-example', state: 'not_monitored' })]);await until('the background first pass to ask for HEAD', () => revParses > 0, lines);expect((await readSourceFreshness(engine, { sourceId: 'acme-example' }))[0]!.state).toBe('not_monitored');- } finally { await started?.stop(); __resetResidentNotifierForTests(); await engine.executeRaw("DELETE FROM sources WHERE id='acme-example'"); }+ } finally { await started?.stop(); __resetResidentNotifierForTests(); await engine.executeRaw("DELETE FROM sources WHERE id='acme-example'"); await engine.setConfig('sync.on_commit', 'false'); }});}, 60_000);});