Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): managed_sync_latency warns when it cannot date synced commits, and honors doctor --source
garrytanfe58d09ca184
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 44ab5fa0e6..c22f304989 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,7 +34,7 @@ To turn it on, run `gbrain config set sync.on_commit true` on the brain host. Th- New `src/core/serve-head-watcher.ts`, started next to the movement watch in `gbrain serve` and `gbrain serve --http`. With `sync.on_commit` on it polls `git rev-parse HEAD` in the checkout of each managed source this host owns every 3 s (`GBRAIN_SERVE_HEAD_POLL_MS`, 1 to 30 s), with an `fs.watch` on the git directory that only brings the next poll forward, debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the existing `startDelegatedSync` as this host's CLI writer. It never starts beside a running delegated sync or a held drain lease, skips a commit the source has already synced, resumes a resumable stop up to three times, never writes into the checkout or `.git`, and logs each distinct error once. With the setting off it makes no git call.- New `src/core/persistence/sync-freshness.ts`: commit→searchable and commit→embedded p50/p95 per managed source from existing columns (the commit's committer time from git, `persistence_requests.completed_at` of committed `managed_sync_import` receipts, `content_chunks.embedded_at`). Commit→embedded counts only a receipt that is still the page's current revision, and only an embedding at or after its write, so a later revision never rewrites an earlier sample. First syncs and working-tree entries are not counted; a run that spans several commits is dated by its newest. No schema change.- New config keys `sync.on_commit` and `sync.freshness_target_seconds` (tunables in `src/core/sync-config-keys.ts`).-- New doctor check `managed_sync_latency` (`src/commands/doctor/checks/managed-sync-latency.ts`); the doctor goldens are regenerated for it.+- New doctor check `managed_sync_latency` (`src/commands/doctor/checks/managed-sync-latency.ts`); the doctor goldens are regenerated for it. With grading on it also warns when the synced commits are not in this host's git checkout (the latency cannot be measured), and `doctor --source` grades only that source.- Tests: `test/serve-head-watcher.test.ts` (debounce, single flight, follow-up, resume cap, error handling, stop), `test/serve-head-watcher-managed.serial.test.ts` (a real managed source on PGLite and Postgres: a commit becomes searchable with no manual sync), `test/serve-http-head-watcher.serial.test.ts` (the watcher starts with `gbrain serve --http` and its poll interval is cleared on shutdown), `test/sync-freshness-6858.test.ts` (percentiles, exclusions, doctor thresholds, the additive `sync status --json` block). The two database tests are listed in `test/postgres-unit-arms.txt`.## [0.60.272.0] - 2026-10-16diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 28cc44ed6d..b3c1661ca3 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -246,7 +246,9 @@ counted, and a run that spans several commits is dated by its newest. Doctor`managed_sync_latency` warns when p95 commit→searchable is over`sync.freshness_target_seconds` (default 300) and fails over one hour; itgrades only a brain with `sync.on_commit` on or a target set, and otherwise-reports the numbers. A stopped or stalled sync is reported by doctor+reports the numbers. With grading on, it also warns when the synced commits are+not in this host's git checkout, so their latency cannot be measured.+`gbrain doctor --source <id>` grades only that source. A stopped or stalled sync is reported by doctor`managed_sync_not_moving`, not by this check.## Implementationdiff --git a/llms-full.txt b/llms-full.txtindex 8f16f01433..77c3c001e6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6850,7 +6850,9 @@ counted, and a run that spans several commits is dated by its newest. Doctor`managed_sync_latency` warns when p95 commit→searchable is over`sync.freshness_target_seconds` (default 300) and fails over one hour; itgrades only a brain with `sync.on_commit` on or a target set, and otherwise-reports the numbers. A stopped or stalled sync is reported by doctor+reports the numbers. With grading on, it also warns when the synced commits are+not in this host's git checkout, so their latency cannot be measured.+`gbrain doctor --source <id>` grades only that source. A stopped or stalled sync is reported by doctor`managed_sync_not_moving`, not by this check.## Implementationdiff --git a/src/commands/doctor/checks/managed-sync-latency.ts b/src/commands/doctor/checks/managed-sync-latency.tsindex 0a3a1dac7d..066af2b750 100644--- a/src/commands/doctor/checks/managed-sync-latency.ts+++ b/src/commands/doctor/checks/managed-sync-latency.ts@@ -2,13 +2,15 @@* managed_sync_latency (#6858 ask 6): the p95 commit→searchable latency of each managed source over the last 24 h* (reader: persistence/sync-freshness.ts, which also reports commit→embedded). It grades only a brain that asked for low* latency, with `sync.on_commit` true or `sync.freshness_target_seconds` set: a p95 over the target (default 300 s)- * warns and one over max(1 h, target) fails. Otherwise, with no samples, and on a brain that is not managed it reports- * ok with the numbers, so a cron-synced brain sees no new warning. A stopped run belongs to managed_sync_blocked (#6861) and a+ * warns and one over max(1 h, target) fails, and committed targets it cannot date (the commit is not in this host's git+ * checkout) with no sample warn that the latency could not be measured. Otherwise, with nothing to measure, and on a+ * brain that is not managed it reports ok with the numbers, so a cron-synced brain sees no new warning. `doctor+ * --source` (and a remote caller's sources) scope it like every source-aware check (doctorSourceIds). A stopped run belongs to managed_sync_blocked (#6861) and a* run that stopped moving to managed_sync_not_moving; this check reads latency only. Reads the database and runs one* read-only `git log` per sampled source.*/import type { Check } from '../../doctor.ts';-import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';import { agentFix, checkError } from '../check-fix.ts';import { readManagedMode } from '../../../core/persistence/managed-mode.ts';import { FRESHNESS_FAIL_SECONDS, formatLatency, readFreshnessTarget, readSyncFreshness, type SourceFreshness } from '../../../core/persistence/sync-freshness.ts';@@ -30,7 +32,7 @@ async function runManagedSyncLatencyCheck(ctx: DoctorContext): Promise<Check[]>const target = await readFreshnessTarget(engine);const failSeconds = Math.max(FRESHNESS_FAIL_SECONDS, target.seconds);const graded = onCommit || target.explicit;- const freshness = await readSyncFreshness(engine);+ const freshness = await readSyncFreshness(engine, { sourceIds: doctorSourceIds(ctx) });const sampled = freshness.filter(f => f.commit_to_searchable.samples > 0);const details = { graded, on_commit: onCommit, target_seconds: target.seconds, fail_seconds: failSeconds, sources: freshness, docs: DOCS };const failing = sampled.filter(f => p95(f) > failSeconds);@@ -38,9 +40,19 @@ async function runManagedSyncLatencyCheck(ctx: DoctorContext): Promise<Check[]>const first = failing[0] ?? slow[0];const fix = first ? agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],`Read-only: shows whether ${first.source_id}'s managed sync is behind, held or stopped, and the next step it names.`, 'managed_sync_latency', { docs: DOCS }) : undefined;- if (!sampled.length) {+ const undated = freshness.filter(f => f.unresolved_commits > 0);+ const undatedCount = undated.reduce((n, f) => n + f.unresolved_commits, 0);+ const undatedLine = undated.map(f => `${f.source_id} (${f.unresolved_commits})`).join(', ');+ if (!sampled.length && graded && undatedCount) {+ checks.push({ name: 'managed_sync_latency', status: 'warn', details,+ fix: agentFix(['gbrain', 'sync', 'status', '--source', undated[0]!.source_id, '--json'],+ `Read-only: shows ${undated[0]!.source_id}'s managed sync state and checkout; the latency needs the synced commits in this host's checkout.`, 'managed_sync_latency', { docs: DOCS }),+ message: `Commit→searchable latency could not be measured for ${undatedCount} commit(s) synced in the last ${freshness[0]?.window_hours ?? 24} h: ${undatedLine}. The commit is not in this host's local git checkout, so its commit time is unknown.` });+ } else if (!sampled.length) {checks.push({ name: 'managed_sync_latency', status: 'ok', details,- message: `No commit→searchable samples in the last ${freshness[0]?.window_hours ?? 24} h (no managed sync imported a new commit).` });+ message: undatedCount+ ? `No commit→searchable samples in the last ${freshness[0]?.window_hours ?? 24} h: ${undatedCount} synced commit(s) are not in this host's local git checkout (${undatedLine}); not graded (sync.on_commit is off and no target is set).`+ : `No commit→searchable samples in the last ${freshness[0]?.window_hours ?? 24} h (no managed sync imported a new commit).` });} else if (graded && failing.length) {checks.push({ name: 'managed_sync_latency', status: 'fail', readiness_state: 'degraded', details, fix,message: `${failing.map(line).join('; ')}: p95 commit→searchable is over ${formatLatency(failSeconds)}. New commits take that long to reach search.` });diff --git a/test/sync-freshness-6858.test.ts b/test/sync-freshness-6858.test.tsindex 3face6bf67..663346a3a5 100644--- a/test/sync-freshness-6858.test.ts+++ b/test/sync-freshness-6858.test.ts@@ -69,7 +69,8 @@ async function receipt(engine: BrainEngine, f: Fixture, afterSeconds: number, opVALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,$4,$5,$6::uuid,'d','{}'::jsonb,$7::text::jsonb,1,16384,'committed',$8::timestamptz)`,[randomUUID(), f.id, f.incarnation, slug, pageId, f.worktreeId, JSON.stringify(intent), new Date(completed).toISOString()]);}-const doctor = async (engine: BrainEngine) => (await managedSyncLatencyEntry.run({ engine } as unknown as Parameters<typeof managedSyncLatencyEntry.run>[0]) as unknown as Array<Record<string, any>>)[0]!;+const doctor = async (engine: BrainEngine, scope: { sourceIds?: string[]; orphanRatioSourceId?: string } = {}) =>+ (await managedSyncLatencyEntry.run({ engine, ...scope } as unknown as Parameters<typeof managedSyncLatencyEntry.run>[0]) as unknown as Array<Record<string, any>>)[0]!;async function reset(engine: BrainEngine): Promise<void> {await engine.executeRaw('DELETE FROM persistence_requests');await engine.executeRaw("DELETE FROM config WHERE key IN ('sync.on_commit','sync.freshness_target_seconds')");@@ -173,6 +174,45 @@ describe('sync freshness (#6858 ask 6)', () => {}}), 120_000);+ test('doctor warns when grading is on and synced commits cannot be dated; ok only when there was nothing to measure', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const { name, engine } of engines) {+ await reset(engine);+ const f = await managedSource(engine, 60);+ await receipt(engine, f, 10, { intent: { target: 'e'.repeat(40) } });+ await receipt(engine, f, 12, { intent: { target: 'd'.repeat(40) } });+ const ungraded = await doctor(engine, { sourceIds: [f.id] });+ expect(ungraded, name).toMatchObject({ status: 'ok', details: { graded: false } });+ expect(ungraded.message).toContain('2 synced commit(s) are not in this host');+ await engine.setConfig('sync.on_commit', 'true');+ const warn = await doctor(engine, { sourceIds: [f.id] });+ expect(warn, name).toMatchObject({ status: 'warn', details: { graded: true, sources: [{ source_id: f.id, unresolved_commits: 2 }] } });+ expect(warn.message).toBe(`Commit→searchable latency could not be measured for 2 commit(s) synced in the last 24 h: ${f.id} (2). The commit is not in this host's local git checkout, so its commit time is unknown.`);+ expect(warn.fix.argv).toEqual(['gbrain', 'sync', 'status', '--source', f.id, '--json']);+ await engine.executeRaw('DELETE FROM persistence_requests');+ expect(await doctor(engine, { sourceIds: [f.id] }), name).toMatchObject({ status: 'ok', message: expect.stringContaining('no managed sync imported a new commit') });+ }+ }), 120_000);++ test('doctor --source grades only that source', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const { name, engine } of engines) {+ await reset(engine);+ const scoped = await managedSource(engine, 3600);+ const other = await managedSource(engine, 3600);+ await receipt(engine, scoped, 20);+ for (const after of [400, 500]) await receipt(engine, other, after);+ await engine.setConfig('sync.on_commit', 'true');+ for (const scope of [{ orphanRatioSourceId: scoped.id }, { sourceIds: [scoped.id] }]) {+ const check = await doctor(engine, scope);+ expect(check, name).toMatchObject({ status: 'ok' });+ expect(check.details.sources.map((s: { source_id: string }) => s.source_id)).toEqual([scoped.id]);+ expect(check.message).not.toContain(other.id);+ }+ const all = await doctor(engine, { sourceIds: [scoped.id, other.id] });+ expect(all, name).toMatchObject({ status: 'warn' });+ expect(all.message).toContain(other.id);+ }+ }), 120_000);+test('doctor grades only with sync.on_commit on or a target set: warn over the target, fail over 1 h', () => withEnv({ GBRAIN_HOME: home }, async () => {for (const { engine } of engines) {await reset(engine);