Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

notifier: search freshness notice and the sync-status notifier block (2a.2, 2a.5)

garrytan9ac1610de154
diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.ts
new file mode 100644
index 0000000000..7b1182f093
--- /dev/null
+++ b/src/core/notifier/status.ts
@@ -0,0 +1,142 @@
+/**
+ * GBRA-133 PR 2a.2 / 2a.5: what the notifier tells the user and the agent, read from its durable rows only (no git
+ * call, no file read): the per-source notifier block for sync status and doctor, and the freshness notice that rides
+ * search and query results.
+ *
+ * Liveness: on Postgres the owner is live while its host lease has not expired (renewed every heartbeat); on PGLite
+ * there is no lease (the brain's lock holder owns the notifier), so the owner is live when it is this process or a
+ * running pid on this host. A source with no coverage row, or whose owner is gone, reads not_monitored, never current.
+ */
+import type { BrainEngine } from '../engine.ts';
+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';
+
+type Exec = Pick<BrainEngine, 'executeRaw' | 'kind'>;
+
+export type FreshnessState = 'current' | 'behind' | 'syncing' | 'unknown' | 'not_monitored';
+
+export interface SourceFreshness {
+ source_id: string;
+ state: FreshnessState;
+ observed_head: string | null;
+ observed_at: string | null;
+ mode: DetectionMode | null;
+ held_count: number;
+}
+
+export interface NotifierBlock {
+ /** The resident that syncs this source, or null with the fix when none is running. */
+ resident: { kind: string; pid: number | null; host_id: string | null; live: boolean } | null;
+ state: NotifierState | null;
+ reason: string | null;
+ detection_mode: DetectionMode | null;
+ first_due_at: string | null;
+ attempts: number;
+ next_retry_at: string | null;
+ last_error: { code: string | null; message: string | null; at: string | null; trace_path?: string | null } | null;
+ observed_head: string | null;
+ observed_at: string | null;
+ pending_markers: Array<{ intent: string; wanted_head: string | null; first_due_at: string; requested_by: string }>;
+ stalled: boolean;
+ /** Set when nothing will sync the source on its own or the notifier stalled. */
+ fix: Action | null;
+}
+
+interface Row {
+ id: string; last_commit: string | null; state: NotifierState | null; reason: string | null; first_due_at: unknown; attempts: unknown;
+ next_retry_at: unknown; last_error_code: string | null; last_error: string | null; last_error_at: unknown; trace_path: string | null;
+ observed_head: string | null; observed_at: unknown; detection_mode: DetectionMode | null; owner_host_id: string | null; owner_kind: string | null;
+ owner_pid: unknown; lease_live: unknown; due_markers: unknown;
+}
+
+const iso = (v: unknown): string | null => v === null || v === undefined ? null : v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString();
+const truthy = (v: unknown) => v === true || v === 't' || v === 1;
+
+async function readRows(engine: Exec, sourceIds: string[] | null): Promise<Row[]> {
+ return engine.executeRaw<Row>(
+ `SELECT s.id, s.last_commit, n.state, n.reason, n.first_due_at, n.attempts, n.next_retry_at, n.last_error_code, n.last_error, n.last_error_at,
+ n.trace_path, n.observed_head, n.observed_at, n.detection_mode, n.owner_host_id, n.owner_kind, n.owner_pid,
+ EXISTS (SELECT 1 FROM sync_notifier_leases l WHERE l.host_id = n.owner_host_id AND l.expires_at > now()) AS lease_live,
+ (SELECT count(*) FROM sync_wanted_markers m WHERE m.source_id = s.id
+ AND (m.intent <> 'freshness' OR m.wanted_head IS NULL OR m.wanted_head IS DISTINCT FROM s.last_commit)) AS due_markers
+ FROM sources s LEFT JOIN sync_notifier_sources n ON n.source_id = s.id
+ WHERE NOT s.archived AND ($1::text[] IS NULL OR s.id = ANY($1::text[]))
+ ORDER BY s.id LIMIT 200`, [sourceIds]);
+}
+
+function ownerLive(engine: Exec, row: Pick<Row, 'owner_host_id' | 'owner_pid' | 'lease_live'>): boolean {
+ if (!row.owner_host_id) return false;
+ if (engine.kind !== 'pglite') return truthy(row.lease_live);
+ const pid = row.owner_pid === null || row.owner_pid === undefined ? null : Number(row.owner_pid);
+ if (pid === null || row.owner_host_id !== localHostId()) return false;
+ if (pid === process.pid) return residentNotifier() !== null;
+ try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
+}
+
+function freshnessOf(engine: Exec, row: Row, held: number): SourceFreshness {
+ const base = { source_id: row.id, observed_head: row.observed_head, observed_at: iso(row.observed_at), mode: row.detection_mode, held_count: held };
+ if (!row.observed_at || !ownerLive(engine, row)) return { ...base, state: 'not_monitored' };
+ if (row.state === 'running') return { ...base, state: 'syncing' };
+ const behind = (row.state !== null && row.state !== 'idle') || Number(row.due_markers ?? 0) > 0 || row.observed_head !== row.last_commit;
+ return { ...base, state: behind ? 'behind' : 'current' };
+}
+
+/**
+ * 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.
+ */
+export async function readSourceFreshness(engine: Exec, 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 {
+ 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)}`);
+ 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 }));
+ }
+}
+
+const syncNowFix = (sourceId: string, why: string): Action => ({ argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, why });
+
+/**
+ * The notifier block of `gbrain sync status` (and doctor): the resident that syncs the source or none with the fix,
+ * its state, the retry schedule, the last error and, for a local caller, the trace file. Remote callers get no trace
+ * path, pid or host id (the sync_status projection rule).
+ */
+export async function readNotifierBlock(engine: Exec, sourceId: string, opts: { remote?: boolean } = {}): Promise<NotifierBlock | null> {
+ let row: Row | undefined;
+ let markers: Array<{ intent: string; wanted_head: string | null; first_due_at: unknown; requested_by: string }> = [];
+ try {
+ [row] = await readRows(engine, [sourceId]);
+ markers = await engine.executeRaw('SELECT intent, wanted_head, first_due_at, requested_by FROM sync_wanted_markers WHERE source_id = $1 ORDER BY first_due_at, intent', [sourceId]);
+ } catch (error) { if (missingTable(error)) return null; throw error; }
+ if (!row) return null;
+ const remote = opts.remote === true;
+ const live = ownerLive(engine, row);
+ const stalled = row.reason === 'notifier_stalled' || row.state === 'operator_blocked';
+ const resident = live ? { kind: row.owner_kind ?? 'unknown', pid: remote ? null : row.owner_pid === null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id, live } : null;
+ const fix = !live
+ ? syncNowFix(sourceId, 'No resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches this source; this syncs the checkout HEAD now. A resident started later catches up on its own.')
+ : stalled ? syncNowFix(sourceId, `The notifier made no progress after ${Number(row.attempts ?? 0)} attempts (${row.last_error_code ?? row.reason ?? 'blocked'}); a foreground sync shows the error`
+ + `${!remote && row.trace_path ? `, and the trace is ${row.trace_path}` : ''}.`) : null;
+ return {
+ resident, state: row.state, reason: row.reason, detection_mode: row.detection_mode, first_due_at: iso(row.first_due_at), attempts: Number(row.attempts ?? 0),
+ next_retry_at: iso(row.next_retry_at),
+ last_error: row.last_error_code || row.last_error ? { code: row.last_error_code, message: row.last_error, at: iso(row.last_error_at), ...(remote ? {} : { trace_path: row.trace_path }) } : null,
+ observed_head: row.observed_head, observed_at: iso(row.observed_at),
+ pending_markers: markers.map(m => ({ intent: m.intent, wanted_head: m.wanted_head, first_due_at: iso(m.first_due_at)!, requested_by: m.requested_by })),
+ stalled, fix,
+ };
+}
+
+/** One line for the human sync status and doctor. */
+export function formatNotifierBlock(sourceId: string, b: NotifierBlock): string {
+ const who = b.resident ? `${b.resident.kind}${b.resident.pid ? ` (PID ${b.resident.pid})` : ''}, ${b.detection_mode ?? 'not observed yet'}` : 'none running';
+ const state = b.state ? `${b.state}${b.reason ? ` (${b.reason})` : ''}${b.next_retry_at && b.state === 'retry' ? `, next retry ${b.next_retry_at}` : ''}${b.attempts ? `, ${b.attempts} attempt(s)` : ''}` : 'idle';
+ const markers = b.pending_markers.length ? `; wanted: ${b.pending_markers.map(m => `${m.intent}${m.wanted_head ? ` ${m.wanted_head.slice(0, 8)}` : ''}`).join(', ')}` : '';
+ const fix = b.fix ? `. Fix: ${b.fix.argv?.join(' ')}` : '';
+ return `notifier for ${sourceId}: ${who}; ${state}${markers}${b.last_error?.trace_path ? `; trace ${b.last_error.trace_path}` : ''}${fix}`;
+}
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 3769d3b4ee..0b20dfd8a3 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -1,4 +1,5 @@
import { searchAnswerFeedback } from '../feedback/record.ts';
+import { readSourceFreshness } from '../notifier/status.ts';
import { recordRecallOutcome } from '../funnel.ts';
import type { RelationalPlanMeta } from '../search/relational-recall.ts';
import type { Notice } from '../agent-output.ts';
@@ -431,14 +432,18 @@ async function buildRetrievalResponseMeta(
const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);
// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres
// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.
- const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles] = await Promise.all([
+ const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles, sourceFreshness] = await Promise.all([
ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),
probeProjectionReadiness(ctx.engine, { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes }),
// Facts saved about the entity the query names come first (newest first, one hop through entities they name).
opts.entity && ctx.emitResponseMeta ? entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : [],
matchingSavedFacts(ctx, scope, queryText, aliases),
stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []),
+ // GBRA-133 PR 2a.5: per-source freshness from the notifier's cached coverage record (no git call).
+ readSourceFreshness(ctx.engine, scope),
]);
+ const heldBySource = new Map(heldFiles.map(h => [h.source_id, h.missing + h.stale]));
+ const freshness = sourceFreshness.map(f => ({ ...f, held_count: heldBySource.get(f.source_id) ?? 0 }));
// A fact the facts arm already returned as a row is not repeated beside the blocks.
const factRowIds = new Set((results as SearchResult[]).flatMap(r => r.fact_row ? [r.fact_row.id] : []));
const savedFacts = [...entityFacts, ...matchedFacts.filter(m => !entityFacts.some(e => e.id === m.id))]
@@ -475,6 +480,7 @@ async function buildRetrievalResponseMeta(
...(savedFacts.length ? { saved_facts: savedFacts } : {}),
...(aliases.length ? { other_names: aliases } : {}),
...(heldFiles.length ? { held_files: heldFiles } : {}),
+ ...(freshness.length ? { freshness } : {}),
...(hint || readiness.hint ? { hint: [hint, readiness.hint].filter(Boolean).join(' ') } : {}),
...(opts.feedbackOp ? await searchAnswerFeedback(ctx, opts.feedbackOp, results as SearchResult[]) : {}),
};
diff --git a/test/e2e/s-notifier-freshness-status-postgres.test.ts b/test/e2e/s-notifier-freshness-status-postgres.test.ts
new file mode 100644
index 0000000000..ae57c52250
--- /dev/null
+++ b/test/e2e/s-notifier-freshness-status-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-notifier-freshness-status.test.ts'));
diff --git a/test/pathological/s-notifier-freshness-status.test.ts b/test/pathological/s-notifier-freshness-status.test.ts
new file mode 100644
index 0000000000..473737fb8c
--- /dev/null
+++ b/test/pathological/s-notifier-freshness-status.test.ts
@@ -0,0 +1,120 @@
+/**
+ * GBRA-133 PR 2a.2 / 2a.5: the user and the agent can see who syncs a source and how fresh a search answer is.
+ *
+ * Protects:
+ * - search results carry a per-source freshness entry from the notifier's cached coverage record: not_monitored when
+ * no resident watches the source (never current), current once a live resident observed HEAD = last_commit;
+ * - the sync-status notifier block names the resident (kind, pid) or says none is running with the fix
+ * gbrain sync --source <id> --no-pull;
+ * - a stalled notifier (notifier_stalled) is reported with the fix and the trace path to a local caller, and a remote
+ * projection carries no trace path, pid or host id.
+ * On v0.60.309.0 search carried no freshness and nothing recorded the notifier. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { performSync } from '../../src/commands/sync.ts';
+import { startServeHeadWatcher } from '../../src/core/serve-head-watcher.ts';
+import { __resetDelegatedSyncForTests, isDelegatedSyncRunning } from '../../src/core/serve-sync-runner.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { writeState } from '../../src/core/notifier/store.ts';
+import { formatNotifierBlock, readNotifierBlock } from '../../src/core/notifier/status.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+const SOURCE = 'acme-example';
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+async function until(what: string, fn: () => Promise<boolean>, lines: string[] = [], timeoutMs = 60_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await fn())) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}; log: ${JSON.stringify(lines)}`);
+ await Bun.sleep(100);
+ }
+}
+
+async function classicBrain(databaseUrl: string | undefined, run: (b: { engine: BrainEngine; root: string }) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-notifier-freshness-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_NOTIFIER: undefined, GBRAIN_NOTIFIER_CLASSIC_SOURCES: undefined }, async () => {
+ __resetDelegatedSyncForTests();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, SOURCE); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/alice-example.md'), '---\ntitle: Alice Example\n---\nAlice Example keeps the acme-example juniper ledger.\n');
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [SOURCE, root]);
+ await performSync(engine, { sourceId: SOURCE, repoPath: root, noPull: true, noEmbed: true });
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ await run({ engine, root });
+ } finally {
+ await until('the runner to idle', async () => !isDelegatedSyncRunning()).catch(() => undefined);
+ __resetDelegatedSyncForTests();
+ await disposePersistenceConsumer(engine).catch(() => undefined);
+ await close();
+ }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function searchFreshness(engine: BrainEngine, remote: boolean): Promise<Array<Record<string, unknown>>> {
+ 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 ?? [];
+}
+
+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 () => {
+ await classicBrain(databaseUrl, async ({ engine }) => {
+ 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);
+ expect(block?.resident).toBeNull();
+ expect(block?.fix?.argv).toEqual(['gbrain', 'sync', '--source', SOURCE, '--no-pull']);
+ expect(formatNotifierBlock(SOURCE, block!)).toContain('none running');
+ });
+ }, 120_000);
+
+ test('a live resident: search reads current; a stalled notifier names the fix and trace locally, never remotely', async () => {
+ await classicBrain(databaseUrl, async ({ engine }) => {
+ await engine.setConfig('sync.on_commit', 'true');
+ const lines: string[] = [];
+ const watcher = startServeHeadWatcher(engine, { log: line => lines.push(line), pollMs: 1000, debounceMs: 100 });
+ try {
+ await until('the coverage record', async () => (await searchFreshness(engine, false))[0]?.state === 'current', lines);
+ const [current] = await searchFreshness(engine, false);
+ expect(current).toMatchObject({ source_id: SOURCE, state: 'current', observed_head: git(join(process.env.GBRAIN_HOME!, SOURCE), 'rev-parse', 'HEAD') });
+ expect(['watch', 'poll']).toContain(current!.mode as string);
+ const live = await readNotifierBlock(engine, SOURCE);
+ expect(live?.resident).toMatchObject({ kind: 'serve', pid: process.pid, live: true });
+ expect(live?.fix).toBeNull();
+
+ await writeState(engine, SOURCE, { state: 'retry', reason: 'notifier_stalled', firstDue: 'keep', attempts: 6, nextRetryInMs: 300_000,
+ error: { code: 'notifier_stalled', message: 'sync_failed: example failure', tracePath: '/tmp/example-trace.jsonl' } });
+ const local = await readNotifierBlock(engine, SOURCE);
+ expect(local).toMatchObject({ state: 'retry', reason: 'notifier_stalled', stalled: true, attempts: 6 });
+ expect(local?.next_retry_at).not.toBeNull();
+ expect(local?.last_error?.trace_path).toBe('/tmp/example-trace.jsonl');
+ expect(local?.fix?.why).toContain('/tmp/example-trace.jsonl');
+ expect(formatNotifierBlock(SOURCE, local!)).toContain('notifier_stalled');
+ const remote = await readNotifierBlock(engine, SOURCE, { remote: true });
+ expect(remote?.resident).toMatchObject({ kind: 'serve', pid: null, host_id: null });
+ expect(JSON.stringify(remote)).not.toContain('/tmp/example-trace.jsonl');
+ const [behind] = await searchFreshness(engine, true);
+ expect(behind).toMatchObject({ state: 'behind' });
+ expect(JSON.stringify(behind)).not.toContain('/tmp/');
+ } finally { await watcher.stop(); await engine.setConfig('sync.on_commit', 'false'); }
+ expect((await searchFreshness(engine, false))[0]?.state).toBe('not_monitored');
+ });
+ }, 180_000);
+ });
+}