Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
notifier: watch classic sources on the host that last synced them
garrytand9a314fb0bf9
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.tsindex c3c65fbb60..e1f300b1ee 100644--- a/src/core/notifier/resident.ts+++ b/src/core/notifier/resident.ts@@ -89,6 +89,7 @@ export async function listHostSources(engine: BrainEngine, hostId: string, env:} else {kind = 'classic';root = row.local_path;+ if (!root) { skipped.push({ sourceId: row.id, reason: 'no local checkout path' }); continue; }if (!bind.has(row.id) && row.syncer !== hostId) {skipped.push({ sourceId: row.id, reason: row.syncer? `classic source last synced on host ${row.syncer.slice(0, 8)}; its resident there watches it (or bind it here with GBRAIN_NOTIFIER_CLASSIC_SOURCES=${row.id})`diff --git a/src/core/notifier/store.ts b/src/core/notifier/store.tsindex bea3ce4db5..6694980757 100644--- a/src/core/notifier/store.ts+++ b/src/core/notifier/store.ts@@ -20,6 +20,7 @@* it as "no markers, nothing monitored".*/import type { BrainEngine } from '../engine.ts';+import { localHostId } from '../persistence/identity.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -276,3 +277,11 @@ export async function recordSyncerHost(engine: Exec, sourceId: string, hostId: sON CONFLICT (source_id) DO UPDATE SET syncer_host_id = EXCLUDED.syncer_host_id, syncer_recorded_at = now(), updated_at = now()WHERE sync_notifier_sources.syncer_host_id IS DISTINCT FROM EXCLUDED.syncer_host_id`, [sourceId, hostId]);}++/**+ * Called where a sync advances a source's last_commit (sync-anchor.ts writeSyncAnchor): records this host as the+ * source's syncer, so this host's resident notifier watches it. Best effort: a sync never fails on it.+ */+export async function recordLocalSyncer(engine: Exec, sourceId: string): Promise<void> {+ try { await recordSyncerHost(engine, sourceId, localHostId()); } catch { /* the notifier reports the source as unrecorded */ }+}diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.tsindex 32bc4b47b2..9735d9d36c 100644--- a/src/core/sync-anchor.ts+++ b/src/core/sync-anchor.ts@@ -270,6 +270,8 @@ export async function writeSyncAnchor([value, sourceId],);}+ // GBRA-133 PR 2a: the host that advanced a classic source is the one whose resident notifier watches it.+ await (await import('./notifier/store.ts')).recordLocalSyncer(engine, sourceId);} else {// #4369: repo_path repoints require directory-identity EQUALITY// (ownsSourceSyncAnchor); last_commit advances above use the weakerdiff --git a/test/e2e/s-notifier-classic-serve-postgres.test.ts b/test/e2e/s-notifier-classic-serve-postgres.test.tsnew file mode 100644index 0000000000..3f7a8f38e8--- /dev/null+++ b/test/e2e/s-notifier-classic-serve-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-notifier-classic-serve.test.ts'));diff --git a/test/pathological/s-notifier-classic-serve.test.ts b/test/pathological/s-notifier-classic-serve.test.tsnew file mode 100644index 0000000000..730e52f72d--- /dev/null+++ b/test/pathological/s-notifier-classic-serve.test.ts@@ -0,0 +1,92 @@+/**+ * GBRA-133 PR 2a.1 (latency finding 6.6): a resident serve watched managed sources only (serve-head-watcher.ts:98 on+ * v0.60.309.0 returned no sources unless the brain was managed), so a commit in a classic brain's checkout was never+ * synced by the serve: measured "never" on both engines.+ *+ * Protects: a classic source last synced on this host (sync_notifier_sources.syncer_host_id, recorded where+ * last_commit advances) is watched by the host's notifier, and a new commit becomes searchable without a manual sync;+ * a classic source whose recorded syncer is another host is skipped with the reason, never synced from here.+ * Real git, real delegated runner, real store. 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 { 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 { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+function commit(root: string, file: string, body: string): string {+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, file), body);+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', `add ${file}`);+ return git(root, 'rev-parse', 'HEAD');+}+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}; notifier log: ${JSON.stringify(lines)}`);+ await Bun.sleep(100);+ }+}+const searchable = async (engine: BrainEngine, word: string, slug: string) => (await engine.searchKeyword(word, { limit: 20 })).some(r => r.slug === slug);+const lastCommit = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]?.last_commit ?? null;++async function classicBrain(databaseUrl: string | undefined, run: (b: { engine: BrainEngine; root: string; other: string }) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-notifier-classic-'));+ 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, 'acme-example'); mkdirSync(root); git(root, 'init', '-q');+ commit(root, 'notes/alice-example.md', '---\ntitle: Alice Example\n---\nAlice Example keeps the acme-example ledger.\n');+ const other = join(home, 'other-example'); mkdirSync(other); git(other, 'init', '-q');+ commit(other, 'notes/bob-example.md', '---\ntitle: Bob Example\n---\nBob Example keeps a ledger.\n');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('acme-example','acme-example',$1,'{}'), ('other-example','other-example',$2,'{}')", [root, other]);+ await performSync(engine, { sourceId: 'acme-example', repoPath: root, noPull: true, noEmbed: true });+ await performSync(engine, { sourceId: 'other-example', repoPath: other, noPull: true, noEmbed: true });+ await run({ engine, root, other });+ } finally {+ await until('the runner to idle', async () => !isDelegatedSyncRunning(), [], 60_000).catch(() => undefined);+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close();+ }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`classic source with a resident serve (${backend})`, () => {+ test('a commit in a classic checkout synced on this host becomes searchable without a manual sync', async () => {+ await classicBrain(databaseUrl, async ({ engine, root }) => {+ // The other source was last synced by another host: it is skipped with the reason, never synced here.+ await engine.executeRaw("UPDATE sync_notifier_sources SET syncer_host_id='00000000-0000-4000-8000-000000000001' WHERE source_id='other-example'").catch(() => undefined);+ await engine.setConfig('sync.on_commit', 'true');+ const lines: string[] = [];+ const watcher = startServeHeadWatcher(engine, { log: line => lines.push(line), pollMs: 1000, debounceMs: 100 });+ try {+ const head = commit(root, 'notes/acme-example.md', '---\ntitle: Acme Example\n---\nAcme Example ships the quarterly zeppelin report.\n');+ await until('the classic commit to become searchable', async () => searchable(engine, 'zeppelin', 'notes/acme-example'), lines);+ await until('last_commit to reach HEAD', async () => (await lastCommit(engine, 'acme-example')) === head && !isDelegatedSyncRunning(), lines);+ await watcher.tick();+ const snap = watcher.snapshot();+ expect(snap.sources.map(s => [s.source_id, s.kind])).toEqual([['acme-example', 'classic']]);+ expect(snap.skipped).toEqual(expect.arrayContaining([expect.objectContaining({ sourceId: 'other-example', reason: expect.stringContaining('last synced on host 00000000') })]));+ expect(snap.skipped.map(s => s.sourceId)).not.toContain('acme-example');+ expect(watcher.decisions.filter(d => d.decision === 'start').map(d => d.source)).toContain('acme-example');+ expect(lines.some(l => l.includes('started classic sync job'))).toBe(true);+ expect(git(root, 'status', '--porcelain')).toBe('');+ } finally { await watcher.stop(); await engine.setConfig('sync.on_commit', 'false'); }+ });+ }, 180_000);+ });+}