Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): sync status carries the notifier block; doctor commit_notifier names the resident or warns with the fix (approved append-only 4b hunks)
garrytan10c72561bedc
diff --git a/docs/guides/on-commit-sync.md b/docs/guides/on-commit-sync.mdindex 13faab0cee..4d4c5a7642 100644--- a/docs/guides/on-commit-sync.md+++ b/docs/guides/on-commit-sync.md@@ -106,8 +106,16 @@ a sync is finishing is still served.gbrain config get sync.on_commitgbrain sync status --source <id> --jsongbrain sync trigger --source <id> --json+gbrain doctor --only commit_notifier --json```+sync status prints a `notifier for <id>:` line (the `notifier` object in+`--json`): the resident that syncs the source and its detection mode, or none+running with the fix, plus the notifier state, retry schedule and pending+requests. Doctor `commit_notifier` reads the same record: with sync.on_commit on+it warns for a source no resident watches or a stalled notifier, and with it off+it warns only when a recorded request waits with no resident.+Search and query responses carry a freshness entry per source (current, behind,syncing, unknown or not_monitored, with the observed HEAD, when it was observed,the detection mode and the held-file count). not_monitored means no resident isdiff --git a/src/commands/doctor/checks/commit-notifier.ts b/src/commands/doctor/checks/commit-notifier.tsnew file mode 100644index 0000000000..508815c699--- /dev/null+++ b/src/commands/doctor/checks/commit-notifier.ts@@ -0,0 +1,52 @@+/**+ * commit_notifier (GBRA-133 PR 2a): names the resident that syncs each local source on commit (gbrain serve, gbrain jobs+ * work or the autopilot daemon; one owns the notifier per host), or says none is running with the fix. With+ * `sync.on_commit` on, a source no resident watches warns, and a stalled notifier (`notifier_stalled`,+ * `operator_blocked`) warns with the foreground sync that shows the error. With it off, a source with a pending sync+ * request and no resident warns (the request waits for a resident); otherwise the check is informational. Reader:+ * src/core/notifier/status.ts (the same block `gbrain sync status` prints). Database reads only; no git call.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';+import { checkError } from '../check-fix.ts';+import { loadAllSources, parseSourceConfig } from '../../../core/sources-load.ts';+import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';+import { parseOnCommit } from '../../../core/commit-notifier.ts';+import { SYNC_ON_COMMIT_KEY } from '../../../core/sync-config-keys.ts';+import { formatNotifierBlock, readNotifierBlock, type NotifierBlock } from '../../../core/notifier/status.ts';++const DOCS = 'docs/guides/on-commit-sync.md';++async function runCommitNotifierCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const engine = connectedEngine(ctx);+ const scope = doctorSourceIds(ctx);+ const sources = (await loadAllSources(engine)).filter(s => !s.archived && s.local_path && !isConnectorSourceKind(parseSourceConfig(s.config).kind)+ && (!scope || scope.includes(s.id)));+ if (!sources.length) {+ checks.push({ name: 'commit_notifier', status: 'ok', message: 'No local source to watch for commits.' });+ return checks;+ }+ const onCommit = parseOnCommit(await engine.getConfig(SYNC_ON_COMMIT_KEY));+ const blocks: Array<{ id: string; block: NotifierBlock | null }> = [];+ for (const s of sources) blocks.push({ id: s.id, block: await readNotifierBlock(engine, s.id, { remote: ctx.sourceIds !== undefined }) });+ const needsAttention = blocks.filter(({ block }) => block && (block.stalled || (!block.resident && (onCommit || block.pending_markers.length > 0))));+ const details = { sync_on_commit: onCommit, docs: DOCS, sources: blocks.map(({ id, block }) => ({ source_id: id, resident: block?.resident?.kind ?? null,+ state: block?.state ?? null, reason: block?.reason ?? null, stalled: block?.stalled ?? false, pending_markers: block?.pending_markers.length ?? 0 })) };+ const lines = blocks.map(({ id, block }) => block ? formatNotifierBlock(id, { ...block, fix: null }) : `notifier for ${id}: not observed yet`);+ if (needsAttention.length) {+ const first = needsAttention[0]!;+ checks.push({ name: 'commit_notifier', status: 'warn', details, ...(first.block?.fix ? { fix: first.block.fix } : {}),+ message: `${needsAttention.map(({ id, block }) => formatNotifierBlock(id, block!)).join('; ')}.` });+ return checks;+ }+ checks.push({ name: 'commit_notifier', status: 'ok', severity: 'info', details,+ message: `${onCommit ? '' : 'sync.on_commit is off; residents still run explicit sync requests. '}${lines.join('; ')}.` });+ } catch (error) {+ checks.push(checkError('commit_notifier', 'read the commit notifier state', error, { details: { health: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const commitNotifierEntry: DoctorEntry = { name: 'commit_notifier', emits: ['commit_notifier'], run: runCommitNotifierCheck };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 51cbbbb2fc..ab16f50758 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -126,6 +126,7 @@ import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';import { overwrittenEditsEntry } from './checks/overwritten-edits.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { managedSyncLatencyEntry } from './checks/managed-sync-latency.ts';+import { commitNotifierEntry } from './checks/commit-notifier.ts';import { managedSyncConvergenceEntry } from './checks/managed-sync-convergence.ts';import { managedSyncBlockedEntry } from './checks/managed-sync-blocked.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';@@ -230,6 +231,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [imageEmbeddingCoverageEntry,syncFreshnessEntry,managedSyncLatencyEntry,+ commitNotifierEntry,gitConvergenceEntry,decideHealthEntry,unlinkedFactsEntry,diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 56c0d40e42..7537c8d3c2 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -134,11 +134,14 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis// #6858 ask 6: commit→searchable / commit→embedded latency over 24 h (null for a source with no managed binding).const { readSyncFreshness, formatSyncFreshness } = await import('../../core/persistence/sync-freshness.ts');const [freshness = null] = await readSyncFreshness(engine, { sourceIds: [sourceId] }).catch(() => []);+ const { readNotifierBlock, formatNotifierBlock } = await import('../../core/notifier/status.ts');+ const notifierBlock = await readNotifierBlock(engine, sourceId).catch(() => null);+ const notifier = notifierBlock && { ...notifierBlock, fix: notifierBlock.fix ? renderAction(notifierBlock.fix, ctx) : null };const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })),git_push_holds: status.git_push_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),- capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, ...(notices.length ? { notices } : {}) };+ capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}) };if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));const c = status.cursor;console.log(syncStatusHeadline(status));@@ -146,6 +149,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis+ `${c.last_advance_at ? `, last advance ${c.last_advance_at}` : ''}` : 'no managed cursor'}`);console.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);if (freshness) console.log(` freshness: ${formatSyncFreshness(freshness)}`);+ if (notifierBlock) console.log(` ${formatNotifierBlock(sourceId, notifierBlock)}`);console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex eb73aeff5b..74191a16bb 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -183,6 +183,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['sync_freshness',// #6858 ask 6: p95 commit→searchable of managed sources over 24 h (doctor/checks/managed-sync-latency.ts).'managed_sync_latency',+ // GBRA-133 PR 2a: the resident that syncs each local source on commit, or none with the fix (doctor/checks/commit-notifier.ts).+ 'commit_notifier',// #5063: source checkouts with commits not on their upstream or stale uncommitted changes.'git_convergence',// #5186: an ownership marker committed to a source checkout's Git index.diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex f3343da400..a4a83e6f5e 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -899,7 +899,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1258 column(s) verified against live schema",+ "message": "1296 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -2159,6 +2159,28 @@"name": "managed_sync_latency","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/on-commit-sync.md",+ "sources": [+ {+ "pending_markers": 0,+ "reason": null,+ "resident": null,+ "source_id": "default",+ "stalled": false,+ "state": null+ }+ ],+ "sync_on_commit": false+ },+ "elapsed_ms": "<volatile>",+ "message": "sync.on_commit is off; residents still run explicit sync requests. notifier for default: none running; idle.",+ "name": "commit_notifier",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex e3d3b58e14..8ad11a81b0 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -946,7 +946,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1258 column(s) verified against live schema",+ "message": "1296 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -2215,6 +2215,28 @@"name": "managed_sync_latency","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/on-commit-sync.md",+ "sources": [+ {+ "pending_markers": 0,+ "reason": null,+ "resident": null,+ "source_id": "default",+ "stalled": false,+ "state": null+ }+ ],+ "sync_on_commit": false+ },+ "elapsed_ms": "<volatile>",+ "message": "sync.on_commit is off; residents still run explicit sync requests. notifier for default: none running; idle.",+ "name": "commit_notifier",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex e16784ffcf..a2d018c868 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -2219,6 +2219,28 @@"name": "managed_sync_latency","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/on-commit-sync.md",+ "sources": [+ {+ "pending_markers": 0,+ "reason": null,+ "resident": null,+ "source_id": "default",+ "stalled": false,+ "state": null+ }+ ],+ "sync_on_commit": false+ },+ "elapsed_ms": "<volatile>",+ "message": "sync.on_commit is off; residents still run explicit sync requests. notifier for default: none running; idle.",+ "name": "commit_notifier",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 359c8ec8bb..75a7c6e926 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -769,6 +769,10 @@"category": "brain","name": "managed_sync_latency"},+ {+ "category": "brain",+ "name": "commit_notifier"+ },{"category": "brain","name": "git_convergence"diff --git a/test/pathological/s-notifier-freshness-status.test.ts b/test/pathological/s-notifier-freshness-status.test.tsindex 473737fb8c..a14c0dfe09 100644--- a/test/pathological/s-notifier-freshness-status.test.ts+++ b/test/pathological/s-notifier-freshness-status.test.ts@@ -61,6 +61,14 @@ async function classicBrain(databaseUrl: string | undefined, run: (b: { engine:} finally { rmSync(home, { recursive: true, force: true }); }}+async function printed(run: () => Promise<void>): Promise<string> {+ const out: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };+ try { await run(); } finally { console.log = log; }+ return out.join('\n');+}+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,@@ -116,5 +124,34 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect((await searchFreshness(engine, false))[0]?.state).toBe('not_monitored');});}, 180_000);++ test('sync status --json carries the notifier block and prints it; doctor commit_notifier names the resident or warns with the fix', async () => {+ await classicBrain(databaseUrl, async ({ engine }) => {+ const { runSyncStatus } = await import('../../src/commands/sync/operator.ts');+ const { commitNotifierEntry } = await import('../../src/commands/doctor/checks/commit-notifier.ts');+ const doctor = async () => (await commitNotifierEntry.run({ engine, args: [], orphanRatioSourceId: undefined } as never)) as Array<{ name: string; status: string; message: string; fix?: { argv?: string[] } }>;+ const json = JSON.parse(await printed(() => runSyncStatus(engine, ['--source', SOURCE, '--json']))) as { notifier?: { resident: unknown; fix: { argv?: string[] } | null } };+ expect(json.notifier).toMatchObject({ resident: null, fix: { argv: ['gbrain', 'sync', '--source', SOURCE, '--no-pull'] } });+ expect(await printed(() => runSyncStatus(engine, ['--source', SOURCE]))).toContain(`notifier for ${SOURCE}: none running`);+ const [off] = await doctor();+ expect(off).toMatchObject({ name: 'commit_notifier', status: 'ok' });+ expect(off!.message).toContain('sync.on_commit is off');++ await engine.setConfig('sync.on_commit', 'true');+ const [unwatched] = await doctor();+ expect(unwatched).toMatchObject({ name: 'commit_notifier', status: 'warn', fix: { argv: ['gbrain', 'sync', '--source', SOURCE, '--no-pull'] } });+ expect(unwatched!.message).toContain('none running');+ const lines: string[] = [];+ const watcher = startServeHeadWatcher(engine, { log: line => lines.push(line), pollMs: 1000, debounceMs: 100 });+ try {+ await until('a live resident', async () => (await readNotifierBlock(engine, SOURCE))?.resident?.live === true, lines);+ const [watched] = await doctor();+ expect(watched).toMatchObject({ name: 'commit_notifier', status: 'ok' });+ expect(watched!.message).toContain(`notifier for ${SOURCE}: serve`);+ const live = JSON.parse(await printed(() => runSyncStatus(engine, ['--source', SOURCE, '--json']))) as { notifier?: { resident: { kind: string } | null; fix: unknown } };+ expect(live.notifier).toMatchObject({ resident: { kind: 'serve' }, fix: null });+ } finally { await watcher.stop(); await engine.setConfig('sync.on_commit', 'false'); }+ });+ }, 180_000);});}