Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(status): managed_sync_latency grades the oldest unsynced commit (reflog, notifier first_due_at, or unknown), reports keyword-visible and embedded freshness separately, grades classic sources; source-health compares HEAD only and dates lag from when the commit landed (GBRA-133 PR 2b.5)
garrytand1af7614cfc0
diff --git a/src/commands/doctor/checks/managed-sync-latency.ts b/src/commands/doctor/checks/managed-sync-latency.tsindex 06c135021c..ed6ca3ae6a 100644--- a/src/commands/doctor/checks/managed-sync-latency.ts+++ b/src/commands/doctor/checks/managed-sync-latency.ts@@ -1,67 +1,110 @@/**- * 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, 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.+ * managed_sync_latency (#6858 ask 6, GBRA-133 PR 2b.5): how long commits take to reach search, per source, over the+ * last 24 h, and the commit that is still waiting.+ *+ * Two clocks, graded the same way:+ * - samples: the p95 commit→searchable latency of each managed source's synced commits (reader:+ * persistence/sync-freshness.ts, which also reports commit→embedded);+ * - the oldest unsynced commit of every source, managed or classic (core/sync-pending.ts): HEAD differs from the+ * synced commit, aged from the reflog entry that moved HEAD (or the commit notifier's persisted first_due_at), or+ * unknown when neither can date it (no reflog, rewritten history). A stalled source has no new samples, so this+ * is what keeps it from reading ok.+ * Keyword-visible and embedded freshness are reported separately per source (details.freshness_by_source); the+ * embedding backlog is reported, not graded (a keyless brain reads disabled).+ * It grades only a brain that asked for low latency, with `sync.on_commit` true or `sync.freshness_target_seconds` set: a+ * p95 or a waiting commit over the target (default 300 s) warns and one over max(1 h, target) fails; a waiting commit of+ * unknown age and synced commits it cannot date (not in this host's checkout) warn. Otherwise 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 remote caller's run reads no git (the notifier's first_due_at only). A+ * stopped run belongs to managed_sync_blocked (#6861) and a run that stopped moving to managed_sync_not_moving. Reads the+ * database, one read-only `git log` per sampled source, and per source one `rev-parse HEAD` and its reflog file.*/import type { Check } from '../../doctor.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';+import { loadPendingRoster, readEmbedBacklog, readPendingCommits, type EmbedBacklog, type PendingCommit } from '../../../core/sync-pending.ts';+import { parseOnCommit } from '../../../core/commit-notifier.ts';import { SYNC_ON_COMMIT_KEY } from '../../../core/sync-config-keys.ts';const DOCS = 'docs/guides/on-commit-sync.md';const p95 = (f: SourceFreshness) => f.commit_to_searchable.p95_seconds ?? 0;const line = (f: SourceFreshness) => `${f.source_id} (p95 ${formatLatency(f.commit_to_searchable.p95_seconds)}, p50 ${formatLatency(f.commit_to_searchable.p50_seconds)}, ${f.commit_to_searchable.samples} page(s))`;+const waiting = (p: PendingCommit) => p.state === 'behind'+ ? `${p.source_id} (waiting ${formatLatency(p.age_seconds)} since ${p.since}, dated from the ${p.evidence === 'reflog' ? 'reflog' : 'notifier first_due_at'})`+ : `${p.source_id} (age unknown: ${p.reason === 'history_rewritten' ? 'the synced commit is not an ancestor of HEAD' : 'no reflog entry reaches the synced commit'})`;++function embeddedState(pending: PendingCommit, backlog: EmbedBacklog | undefined): string {+ if (backlog?.state === 'disabled') return 'disabled';+ if (pending.state === 'behind' || backlog?.state === 'behind') return 'behind';+ if (pending.state === 'unknown' || backlog?.state === 'unknown') return 'unknown';+ return pending.state === 'current' ? 'current' : pending.state;+}async function runManagedSyncLatencyCheck(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];try {const engine = connectedEngine(ctx);- if (!await readManagedMode(engine)) {- checks.push({ name: 'managed_sync_latency', status: 'ok', message: 'Not a managed brain; commit→searchable latency is measured for managed sources only.' });+ const scope = doctorSourceIds(ctx);+ const managed = await readManagedMode(engine);+ const roster = (await loadPendingRoster(engine, scope)).map(s => ({ ...s, managed: managed && s.managed }));+ const pending = await readPendingCommits(engine, roster, { git: ctx.sourceIds === undefined });+ if (!managed && !pending.some(p => p.state === 'behind' || p.state === 'unknown')) {+ checks.push({ name: 'managed_sync_latency', status: 'ok', message: 'Not a managed brain; commit→searchable latency is measured for managed sources only, and no classic source has a commit known to be waiting.' });return checks;}- const onCommit = /^(1|true|on|yes)$/i.test((await engine.getConfig(SYNC_ON_COMMIT_KEY))?.trim() ?? '');+ const onCommit = parseOnCommit(await engine.getConfig(SYNC_ON_COMMIT_KEY));const target = await readFreshnessTarget(engine);const failSeconds = Math.max(FRESHNESS_FAIL_SECONDS, target.seconds);const graded = onCommit || target.explicit;- const freshness = await readSyncFreshness(engine, { sourceIds: doctorSourceIds(ctx) });+ const freshness = managed ? await readSyncFreshness(engine, { sourceIds: scope }) : [];+ const backlog = await readEmbedBacklog(engine, roster.map(s => s.id));+ const samplesBy = new Map(freshness.map(f => [f.source_id, f]));+ const freshnessBySource = roster.map((s, i) => ({ source_id: s.id, kind: s.managed ? 'managed' : 'classic',+ keyword_visible: { state: pending[i]!.state, oldest_unsynced: pending[i]!, samples: samplesBy.get(s.id)?.commit_to_searchable ?? null },+ embedded: { state: embeddedState(pending[i]!, backlog.get(s.id)), backlog: backlog.get(s.id) ?? null, samples: samplesBy.get(s.id)?.commit_to_embedded ?? null } }));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 details = { graded, on_commit: onCommit, target_seconds: target.seconds, fail_seconds: failSeconds, sources: freshness, freshness_by_source: freshnessBySource, docs: DOCS };+ const behind = pending.filter(p => p.state === 'behind');+ const undatable = pending.filter(p => p.state === 'unknown');+ const waitFail = behind.filter(p => (p.age_seconds ?? 0) > failSeconds);+ const waitSlow = behind.filter(p => (p.age_seconds ?? 0) > target.seconds);+ const waitLine = [...behind, ...undatable].map(waiting).join('; ');+ const waitPrefix = waitLine ? `Unsynced commit(s): ${waitLine}. ` : '';const failing = sampled.filter(f => p95(f) > failSeconds);const slow = sampled.filter(f => p95(f) > target.seconds);- 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;+ const firstId = failing[0]?.source_id ?? waitFail[0]?.source_id ?? slow[0]?.source_id ?? waitSlow[0]?.source_id ?? undatable[0]?.source_id;+ const fix = firstId ? agentFix(['gbrain', 'sync', 'status', '--source', firstId, '--json'],+ `Read-only: shows whether ${firstId}'s sync is behind, held or stopped, who syncs it, and the next step it names.`, 'managed_sync_latency', { docs: DOCS }) : undefined;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) {+ const window = freshness[0]?.window_hours ?? 24;+ if (graded && (failing.length || waitFail.length)) {+ checks.push({ name: 'managed_sync_latency', status: 'fail', readiness_state: 'degraded', details, fix,+ message: `${waitFail.length ? `${waitFail.map(waiting).join('; ')}: a commit has waited over ${formatLatency(failSeconds)} to reach search. ` : ''}`+ + (failing.length ? `${failing.map(line).join('; ')}: p95 commit→searchable is over ${formatLatency(failSeconds)}. New commits take that long to reach search.` : '') });+ } else if (graded && (slow.length || waitSlow.length || undatable.length)) {+ const parts = [+ waitSlow.length ? `${waitSlow.map(waiting).join('; ')}: a commit has waited over the ${formatLatency(target.seconds)} target to reach search.` : '',+ undatable.length ? `${undatable.map(waiting).join('; ')}: a commit has not reached search and its wait cannot be dated.` : '',+ slow.length ? `${slow.map(line).join('; ')}: p95 commit→searchable is over the ${formatLatency(target.seconds)} target (sync.freshness_target_seconds).` : '',+ ].filter(Boolean);+ checks.push({ name: 'managed_sync_latency', status: 'warn', readiness_state: 'degraded', details, fix, message: parts.join(' ') });+ } else 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.` });+ message: `${waitPrefix}Commit→searchable latency could not be measured for ${undatedCount} commit(s) synced in the last ${window} 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: 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.` });- } else if (graded && slow.length) {- checks.push({ name: 'managed_sync_latency', status: 'warn', readiness_state: 'degraded', details, fix,- message: `${slow.map(line).join('; ')}: p95 commit→searchable is over the ${formatLatency(target.seconds)} target (sync.freshness_target_seconds).` });+ message: waitPrefix + (undatedCount+ ? `No commit→searchable samples in the last ${window} 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 ${window} h (no managed sync imported a new commit).${waitPrefix && !graded ? ' Not graded (sync.on_commit is off and no target is set).' : ''}`) });} else {checks.push({ name: 'managed_sync_latency', status: 'ok', severity: 'info', details,- message: `Commit→searchable over the last 24 h: ${sampled.map(line).join('; ')}${graded ? `, within the ${formatLatency(target.seconds)} target` : '; not graded (sync.on_commit is off and no target is set)'}.` });+ message: `${waitPrefix}Commit→searchable over the last 24 h: ${sampled.map(line).join('; ')}${graded ? `, within the ${formatLatency(target.seconds)} target` : '; not graded (sync.on_commit is off and no target is set)'}.` });}} catch (error) {checks.push(checkError('managed_sync_latency', 'read managed sync freshness', error, { details: { health: 'unknown', docs: DOCS } }));diff --git a/src/core/source-health.ts b/src/core/source-health.tsindex 43aedf4b3d..f9672d14ca 100644--- a/src/core/source-health.ts+++ b/src/core/source-health.ts@@ -16,15 +16,22 @@* wall-clock `now - last_sync_at` (which false-flagged quiet, caught-up* repos as SEVERE). Local callers pass `probeContent: true` and lag* becomes 0 when the source is caught up by COMMIT HASH (HEAD ==- * last_commit, untracked ignored, via `isSourceUnchangedSinceSync`).+ * last_commit, via `probeSourceGitState`).* Remote callers (federation_health on the HTTP MCP path) read the stored* `newest_content_at` column instead — NO git subprocess on a DB-supplied* local_path (preserves the v0.41.27.0 trust boundary).+ *+ * GBRA-133 PR 2b.5: the local probe compares HEAD only (an uncommitted edit+ * to a tracked file is not a pending commit), and a source that is behind+ * dates its lag from when the commit landed (the reflog entry that moved+ * HEAD off last_commit) or from the commit notifier's persisted+ * first_due_at, not from the last no-op heartbeat of last_sync_at. Both+ * paths raise the lag to first_due_at's age (src/core/sync-pending.ts).*/import { execFileSync } from './spawn.ts';import type { BrainEngine } from './engine.ts';import { parseSourceConfig, type SourceRow } from './sources-load.ts';-import { isSourceUnchangedSinceSync } from './git-head.ts';+import { probeSourceGitState } from './git-head.ts';import { resolveHoursEnv } from './env-number.ts';import { isSyncDisabledConfig } from './sync-policy.ts';import { gitChildEnv } from './git-env.ts';@@ -220,7 +227,7 @@ export function resolveStalenessCeilingSeconds(): number {* fail and the surfaces escalate in order.** The LOCAL path does NOT use this — it keys off the live commit hash via- * `isSourceUnchangedSinceSync` (robust against HEAD moving to an old-dated+ * `probeSourceGitState` (robust against HEAD moving to an old-dated* commit, which a timestamp comparison would miss).*/export function lagFromContentMs(@@ -272,8 +279,11 @@ export async function computeAllSourceMetrics(// One ceiling for the whole report (hoisted out of the per-source map):// every source gets the same number, and the env read runs once.const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();+ // GBRA-133 PR 2b.5: the commit notifier's persisted first_due_at dates a pending commit on both paths (no git).+ const { readFirstDue, readGitPendingEvidence } = await import('./sync-pending.ts');+ const firstDue = await readFirstDue(engine, sources.map((src) => src.id)).catch(() => new Map<string, { firstDueAt: number | null }>());- return sources.map((src) => {+ return Promise.all(sources.map(async (src) => {const cfg = parseSourceConfig(src.config);const pages = pageCounts.get(src.id) ?? 0;const chunkStats = chunkCounts.get(src.id) ?? { total: 0, embedded: 0 };@@ -284,17 +294,22 @@ export async function computeAllSourceMetrics(: Math.round((chunkStats.embedded / chunkStats.total) * 1000) / 10;const lastMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : null;+ const dueMs = firstDue.get(src.id)?.firstDueAt ?? null;// v0.41.32.0: commit-relative lag. TWO implementations, and the split is// load-bearing rather than accidental duplication — see the diagram.//// computeAllSourceMetrics// │- // ├─ probeContent: true ──► isSourceUnchangedSinceSync (git subprocess)+ // ├─ probeContent: true ──► probeSourceGitState, HEAD only (git subprocess)// │ LOCAL only. Accurate: keys off the live// │ commit hash, so a HEAD moved to an// │ old-dated commit is correctly NOT caught- // │ up. NULL last_commit → wall-clock.- // │ Caller: `gbrain sources status`.+ // │ up, and an uncommitted edit is not a+ // │ pending commit. Behind: lag runs from the+ // │ reflog entry that moved HEAD off+ // │ last_commit, else the notifier's+ // │ first_due_at, else wall-clock since the+ // │ last sync. Caller: `gbrain sources status`.// │// └─ probeContent: false ──► lagFromContentMs (column read)// REMOTE-SAFE: no subprocess, because a@@ -308,6 +323,8 @@ export async function computeAllSourceMetrics(// doctor `sync_freshness` (via its own// clone-unavailable branch), and// `buildSyncStatusReport` (gbrain status).+ // A persisted first_due_at raises it to+ // the time the commit has been due.//// Do NOT "unify" these behind one flag: collapsing the trust boundary into a// boolean is how a remote caller eventually acquires a subprocess.@@ -315,15 +332,18 @@ export async function computeAllSourceMetrics(if (lastMs === null) {lagSeconds = null;} else if (probeContent) {- const caughtUp = isSourceUnchangedSinceSync(src.local_path, src.last_commit, {- requireCleanWorkingTree: 'ignore-untracked',- });- lagSeconds = caughtUp ? 0 : Math.max(0, Math.floor((now - lastMs) / 1000));+ const state = probeSourceGitState(src.local_path, src.last_commit);+ const evidence = state === 'changed' && src.local_path && src.last_commit+ ? await readGitPendingEvidence(src.local_path, src.last_commit).catch(() => null)+ : null;+ const sinceMs = evidence?.departedAt != null ? evidence.departedAt * 1000 : dueMs;+ lagSeconds = state === 'unchanged' ? 0 : Math.max(0, Math.floor((now - (sinceMs ?? lastMs)) / 1000));} else {const contentMs = src.newest_content_at? new Date(src.newest_content_at).getTime(): null;lagSeconds = lagFromContentMs(contentMs, lastMs, now, stalenessCeilingSeconds);+ if (lagSeconds !== null && lagSeconds >= 0 && dueMs !== null) lagSeconds = Math.max(lagSeconds, Math.floor((now - dueMs) / 1000));}return {@@ -345,7 +365,7 @@ export async function computeAllSourceMetrics(priority_label: resolvePriorityLabel(src.id, src.config),webhook_configured: typeof cfg.webhook_secret === 'string' && cfg.webhook_secret.length > 0,};- });+ }));}async function pageCountsBySource(engine: BrainEngine): Promise<Map<string, number>> {diff --git a/src/core/sync-pending.ts b/src/core/sync-pending.tsnew file mode 100644index 0000000000..6604bd32ff--- /dev/null+++ b/src/core/sync-pending.ts@@ -0,0 +1,214 @@+/**+ * GBRA-133 PR 2b.5: the oldest commit a source has not synced yet, and how long it has waited, for doctor+ * `managed_sync_latency` (managed and classic sources) and `source-health.ts` lag. A source whose sync stalled has no+ * new receipts, so a latency read from synced commits alone says nothing about it; this reads the commit that is+ * still waiting.+ *+ * A source is behind when its checkout HEAD differs from `sources.last_commit` (HEAD only: an uncommitted edit is not+ * a pending commit). The wait is dated, in order:+ * 1. the reflog: the time of the entry that first moved HEAD away from `last_commit` (`<git dir>/logs/HEAD`, read as+ * a file). That is when the commit landed in the checkout, not its committer time, so a pulled old commit does+ * not inflate the wait;+ * 2. the persisted `first_due_at` of the commit notifier (`sync_notifier_sources` while not idle, or a due freshness+ * marker in `sync_wanted_markers`), current source incarnation only. It is the only clock for a caller that runs+ * no git (a remote doctor) and for a checkout without a usable reflog;+ * 3. otherwise unknown, with the reason: `no_reflog` (no reflog entry reaches `last_commit`, which is an ancestor of+ * HEAD) or `history_rewritten` (`last_commit` is not an ancestor of HEAD, or not in the repository).+ * Without git, a source the notifier never recorded as due reads `not_observed`, never current. Nothing is written.+ */+import { closeSync, existsSync, fstatSync, openSync, readSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { execFileBounded } from './bounded-child-exec.ts';+import { gitChildEnv } from './git-env.ts';+import { readCheckoutHead } from './checkout-head.ts';+import { enclosingGitMetadata } from './persistence/root-registry.ts';+import { missingTable } from './notifier/store.ts';++export type PendingState = 'current' | 'behind' | 'unknown' | 'not_observed' | 'never_synced';+export type PendingUnknownReason = 'no_reflog' | 'history_rewritten' | 'no_checkout';++export interface PendingCommit {+ source_id: string;+ state: PendingState;+ /** The checkout HEAD (git), or the notifier's observed HEAD without git. */+ head: string | null;+ synced_commit: string | null;+ /** When the oldest unsynced commit landed or was first due; null unless behind. */+ since: string | null;+ age_seconds: number | null;+ evidence: 'reflog' | 'first_due_at' | null;+ reason: PendingUnknownReason | null;+ first_due_at: string | null;+}++export interface PendingSource { id: string; root: string | null; last_commit: string | null }++/** At most this many trailing bytes of logs/HEAD are read (about 5,000 entries). */+const REFLOG_TAIL_BYTES = 1 << 20;+const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;+const ENTRY = /^([0-9a-f]{40,64}) ([0-9a-f]{40,64}) .*? (\d+) [+-]\d{4}\t/;++function readTail(file: string): string | null {+ let fd: number;+ try { fd = openSync(file, 'r'); } catch { return null; }+ try {+ const size = fstatSync(fd).size;+ const length = Math.min(size, REFLOG_TAIL_BYTES);+ const buffer = Buffer.alloc(length);+ readSync(fd, buffer, 0, length, size - length);+ const text = buffer.toString('utf8');+ return length < size ? text.slice(text.indexOf('\n') + 1) : text;+ } catch { return null; } finally { closeSync(fd); }+}++/** Unix seconds of the reflog entry that first moved HEAD away from `synced` after its last arrival there, or null. */+export function reflogDepartureSeconds(gitDir: string, synced: string): number | null {+ const text = readTail(join(gitDir, 'logs', 'HEAD'));+ if (!text) return null;+ const entries = text.split('\n').map(line => ENTRY.exec(line)).filter((m): m is RegExpExecArray => m !== null)+ .map(m => ({ from: m[1]!, to: m[2]!, at: Number(m[3]) }));+ for (let i = entries.length - 1; i >= 0; i--) {+ if (entries[i]!.to === synced) return entries[i + 1]?.at ?? null;+ }+ return entries.find(e => e.from === synced)?.at ?? null;+}++async function isAncestor(root: string, ancestor: string): Promise<boolean> {+ const r = await execFileBounded('git', ['-C', root, 'merge-base', '--is-ancestor', ancestor, 'HEAD'], { timeout: 10_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });+ return r.error === null;+}++export interface GitPendingEvidence { head: string; behind: boolean; departedAt: number | null; reason: PendingUnknownReason | null }++/** One checkout: HEAD, whether it moved past `synced`, and when it left it (reflog). Null when no checkout can be read. */+export async function readGitPendingEvidence(root: string, synced: string): Promise<GitPendingEvidence | null> {+ const gitDir = enclosingGitMetadata(root);+ if (!gitDir || !existsSync(root)) return null;+ const checkout = await readCheckoutHead(root);+ if (!checkout) return null;+ if (checkout.head === synced) return { head: checkout.head, behind: false, departedAt: null, reason: null };+ const departedAt = reflogDepartureSeconds(gitDir, synced);+ if (departedAt !== null) return { head: checkout.head, behind: true, departedAt, reason: null };+ const reason: PendingUnknownReason = SHA.test(synced) && await isAncestor(root, synced) ? 'no_reflog' : 'history_rewritten';+ return { head: checkout.head, behind: true, departedAt: null, reason };+}++interface DueRow { source_id: string; first_due_at: unknown; observed_head: string | null }+export interface PersistedDue { firstDueAt: number | null; observedHead: string | null }++/** The notifier's persisted first_due_at per source (state not idle, or a due freshness marker), current incarnation only. */+export async function readFirstDue(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: string[]): Promise<Map<string, PersistedDue>> {+ const out = new Map<string, PersistedDue>();+ if (!sourceIds.length) return out;+ let rows: DueRow[];+ try {+ rows = await engine.executeRaw<DueRow>(+ `SELECT s.id AS source_id, n.observed_head,+ LEAST(CASE WHEN n.state <> 'idle' THEN n.first_due_at END,+ (SELECT min(m.first_due_at) FROM sync_wanted_markers m WHERE m.source_id = s.id AND m.intent = 'freshness'+ AND m.source_incarnation IS NOT DISTINCT FROM s.incarnation::text+ AND (m.wanted_head IS NULL OR m.wanted_head IS DISTINCT FROM s.last_commit))) AS first_due_at+ FROM sources s LEFT JOIN sync_notifier_sources n ON n.source_id = s.id AND n.source_incarnation IS NOT DISTINCT FROM s.incarnation::text+ WHERE s.id = ANY($1::text[])`, [sourceIds]);+ } catch (error) {+ if (missingTable(error)) return out;+ throw error;+ }+ for (const row of rows) {+ const raw = row.first_due_at;+ const at = raw === null || raw === undefined ? NaN : (raw instanceof Date ? raw : new Date(String(raw))).getTime();+ out.set(row.source_id, { firstDueAt: Number.isFinite(at) ? at : null, observedHead: row.observed_head });+ }+ return out;+}++/**+ * The oldest unsynced commit of each source. `git: false` (a remote caller) reads only the database. With git, each+ * source costs one `rev-parse HEAD`, a file read of its reflog and, only when no reflog entry reaches+ * `last_commit`, one `merge-base --is-ancestor`.+ */+export async function readPendingCommits(engine: Pick<BrainEngine, 'executeRaw'>, sources: PendingSource[], opts: { git: boolean; nowMs?: number }): Promise<PendingCommit[]> {+ const nowMs = opts.nowMs ?? Date.now();+ const due = await readFirstDue(engine, sources.map(s => s.id));+ const iso = (ms: number) => new Date(ms).toISOString();+ return Promise.all(sources.map(async (source): Promise<PendingCommit> => {+ const persisted = due.get(source.id) ?? { firstDueAt: null, observedHead: null };+ const base = { source_id: source.id, synced_commit: source.last_commit, first_due_at: persisted.firstDueAt === null ? null : iso(persisted.firstDueAt),+ head: null as string | null, since: null as string | null, age_seconds: null as number | null, evidence: null as PendingCommit['evidence'], reason: null as PendingUnknownReason | null };+ const dated = (head: string | null, sinceMs: number, evidence: 'reflog' | 'first_due_at'): PendingCommit =>+ ({ ...base, state: 'behind', head, since: iso(sinceMs), age_seconds: Math.max(0, Math.round((nowMs - sinceMs) / 1000)), evidence });+ if (!source.last_commit) return { ...base, state: 'never_synced' };+ const git = opts.git && source.root ? await readGitPendingEvidence(source.root, source.last_commit).catch(() => null) : null;+ if (git && !git.behind) return { ...base, state: 'current', head: git.head };+ if (git && git.departedAt !== null) return dated(git.head, git.departedAt * 1000, 'reflog');+ if (persisted.firstDueAt !== null) return dated(git?.head ?? persisted.observedHead, persisted.firstDueAt, 'first_due_at');+ if (git) return { ...base, state: 'unknown', head: git.head, reason: git.reason };+ return { ...base, state: 'not_observed', head: persisted.observedHead, reason: opts.git && source.root ? 'no_checkout' : null };+ }));+}++export interface EmbedBacklog {+ source_id: string;+ /** disabled: a keyless brain (nothing will embed); behind: chunks wait for a vector; unknown: a waiting chunk has no pending-since stamp. */+ state: 'current' | 'behind' | 'unknown' | 'disabled';+ pending_chunks: number;+ oldest_pending_since: string | null;+ age_seconds: number | null;+}++/**+ * The embedding backlog of each source: live chunks without a vector in the active embedding column (embed_skip pages+ * excluded, as the doctor embeddings check counts them), aged from the oldest `content_chunks.embedding_pending_since`.+ */+export async function readEmbedBacklog(engine: BrainEngine, sourceIds: string[], opts: { nowMs?: number } = {}): Promise<Map<string, EmbedBacklog>> {+ const out = new Map<string, EmbedBacklog>();+ if (!sourceIds.length) return out;+ const nowMs = opts.nowMs ?? Date.now();+ const { embeddingsDisabled } = await import('./embedding-disabled.ts');+ if (await embeddingsDisabled(engine)) {+ for (const id of sourceIds) out.set(id, { source_id: id, state: 'disabled', pending_chunks: 0, oldest_pending_since: null, age_seconds: null });+ return out;+ }+ const { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } = await import('./search/embedding-column.ts');+ const column = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name);+ const rows = await engine.executeRaw<{ source_id: string; pending: unknown; unaged: unknown; oldest: unknown }>(+ `SELECT p.source_id, count(*)::int AS pending, count(*) FILTER (WHERE cc.embedding_pending_since IS NULL)::int AS unaged,+ min(cc.embedding_pending_since) AS oldest+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.${column} IS NULL AND p.deleted_at IS NULL AND p.source_id = ANY($1::text[])+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')+ GROUP BY p.source_id`, [sourceIds]);+ const byId = new Map(rows.map(row => [row.source_id, row]));+ for (const id of sourceIds) {+ const row = byId.get(id);+ const pending = Number(row?.pending ?? 0);+ const oldestMs = row?.oldest === null || row?.oldest === undefined ? NaN : (row.oldest instanceof Date ? row.oldest : new Date(String(row.oldest))).getTime();+ if (!pending) { out.set(id, { source_id: id, state: 'current', pending_chunks: 0, oldest_pending_since: null, age_seconds: null }); continue; }+ const aged = Number(row?.unaged ?? 0) === 0 && Number.isFinite(oldestMs);+ out.set(id, { source_id: id, state: aged ? 'behind' : 'unknown', pending_chunks: pending, oldest_pending_since: aged ? new Date(oldestMs).toISOString() : null,+ age_seconds: aged ? Math.max(0, Math.round((nowMs - oldestMs) / 1000)) : null });+ }+ return out;+}++export interface RosterSource extends PendingSource { managed: boolean }++/**+ * Every source whose commits sync: managed sources (bound worktree; the root is this host's binding, else the source+ * path) and classic sources with a local path, not archived and not sync-disabled. `sourceIds` confines it in SQL.+ */+export async function loadPendingRoster(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<RosterSource[]> {+ const { existingLocalHostId } = await import('./persistence/identity.ts');+ const { isSyncDisabledConfig } = await import('./sync-policy.ts');+ const rows = await engine.executeRaw<{ id: string; last_commit: string | null; root: string | null; managed: unknown; config: unknown }>(+ `SELECT s.id, s.last_commit, s.config, (b.source_id IS NOT NULL) AS managed, COALESCE(h.local_path, s.local_path) AS root+ FROM sources s+ LEFT JOIN persistence_source_bindings b ON b.source_id = s.id AND b.source_incarnation = s.incarnation+ LEFT JOIN persistence_host_bindings h ON h.worktree_id = b.worktree_id AND h.host_id::text = $2+ WHERE s.archived IS NOT TRUE AND (b.source_id IS NOT NULL OR s.local_path IS NOT NULL)+ AND ($1::text[] IS NULL OR s.id = ANY($1::text[]))+ ORDER BY s.id`, [sourceIds ?? null, existingLocalHostId()]);+ return rows.filter(row => !isSyncDisabledConfig(row.config))+ .map(row => ({ id: row.id, last_commit: row.last_commit, root: row.root, managed: row.managed === true || row.managed === 't' }));+}diff --git a/test/e2e/s-truthful-sync-status-postgres.test.ts b/test/e2e/s-truthful-sync-status-postgres.test.tsnew file mode 100644index 0000000000..24f42cfa8f--- /dev/null+++ b/test/e2e/s-truthful-sync-status-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-truthful-sync-status.test.ts'));diff --git a/test/pathological/s-truthful-sync-status.test.ts b/test/pathological/s-truthful-sync-status.test.tsnew file mode 100644index 0000000000..9b7236b67b--- /dev/null+++ b/test/pathological/s-truthful-sync-status.test.ts@@ -0,0 +1,184 @@+/**+ * GBRA-133 PR 2b.5: status tells the truth about a commit that has not synced.+ *+ * Protects:+ * - doctor managed_sync_latency grades the oldest unsynced commit, not only the commits that did sync: a managed+ * source with an unsynced commit 10 minutes old warns (v0.60.316.0 said "No commit→searchable samples", ok), one+ * the commit notifier has had due for 2 h fails, dated from its persisted first_due_at when there is no reflog;+ * - with neither a reflog nor a first_due_at the wait reads unknown (no_reflog, or history_rewritten when the synced+ * commit is not an ancestor of HEAD) and warns, never ok;+ * - keyword-visible and embedded freshness are reported separately per source (an embedding backlog is reported,+ * not graded);+ * - the classic equivalent: a non-managed brain grades its classic sources' unsynced commits;+ * - source-health compares HEAD only (a dirty tracked file is not lag) and dates lag from when the commit landed+ * (reflog) or the notifier's first_due_at, not from the last no-op heartbeat of last_sync_at.+ * Every timing assertion reads a recorded timestamp (reflog entry, first_due_at, embedding_pending_since), never a+ * measured duration. PGLite always, Postgres when DATABASE_URL is set (twin: test/e2e/s-truthful-sync-status-postgres.test.ts).+ */+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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { managedSyncLatencyEntry } from '../../src/commands/doctor/checks/managed-sync-latency.ts';+import { computeAllSourceMetrics } from '../../src/core/source-health.ts';+import { loadAllSources } from '../../src/core/sources-load.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const SOURCE = 'acme-example';+const MINUTE = 60;++function git(root: string, args: string[], atSeconds?: number): string {+ const env = { ...process.env, GIT_DIR: undefined, GIT_WORK_TREE: undefined, GIT_INDEX_FILE: undefined,+ ...(atSeconds === undefined ? {} : { GIT_COMMITTER_DATE: `@${atSeconds} +0000`, GIT_AUTHOR_DATE: `@${atSeconds} +0000` }) };+ return execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', ...args], { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+const nowS = () => Math.floor(Date.now() / 1000);+/** Commit a change to the checkout with the reflog and committer time `ageSeconds` ago; returns the new HEAD. */+function commit(root: string, file: string, body: string, ageSeconds: number): string {+ writeFileSync(join(root, file), body);+ git(root, ['add', '-A'], nowS() - ageSeconds);+ git(root, ['commit', '-qm', file], nowS() - ageSeconds);+ return git(root, ['rev-parse', 'HEAD']);+}++interface Brain { engine: BrainEngine; home: string; root: string; synced: string }++async function withBrain(databaseUrl: string | undefined, opts: { managed: boolean }, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-truthful-status-'));+ await withEnv({ GBRAIN_HOME: home, GBRAIN_NOTIFIER: '0' }, async () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ try {+ const root = join(home, SOURCE);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, ['init', '-q']);+ const synced = commit(root, 'notes/alice-example.md', '# Alice Example\n', 60 * MINUTE);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,last_commit,last_sync_at,config) VALUES($1,$1,$2,$3,now(),'{}')", [SOURCE, root, synced]);+ if (opts.managed) {+ await claimWorktree(engine, SOURCE, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }+ await engine.setConfig('sync.on_commit', 'true');+ await run({ engine, home, root, synced });+ } finally {+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1').catch(() => undefined);+ await close();+ rmSync(home, { recursive: true, force: true });+ }+ });+}++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 bySource = (check: Record<string, any>) => (check.details?.freshness_by_source ?? []).find((f: { source_id: string }) => f.source_id === SOURCE);+async function markDue(engine: BrainEngine, ageSeconds: number): Promise<void> {+ await engine.executeRaw(`INSERT INTO sync_notifier_sources (source_id, source_incarnation, state, reason, first_due_at, attempts)+ SELECT id, incarnation::text, 'retry', 'notifier_stalled', now() - ($2::int * interval '1 second'), 4 FROM sources WHERE id = $1`, [SOURCE, ageSeconds]);+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`truthful sync status (GBRA-133 PR 2b.5) [${backend}]`, () => {+ test('a managed source with an unsynced commit 10 minutes old warns; master read "no samples", ok', () => withBrain(databaseUrl, { managed: true }, async ({ engine, root }) => {+ const head = commit(root, 'notes/bob-example.md', '# Bob Example\n', 10 * MINUTE);+ const check = await doctor(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`${SOURCE} (waiting 10m`);+ expect(check.message).toContain('dated from the reflog');+ const pending = bySource(check).keyword_visible.oldest_unsynced;+ expect(pending).toMatchObject({ state: 'behind', head, evidence: 'reflog' });+ expect(pending.age_seconds).toBeGreaterThanOrEqual(10 * MINUTE);+ expect(pending.age_seconds).toBeLessThan(11 * MINUTE);+ expect(check.fix?.argv).toEqual(['gbrain', 'sync', 'status', '--source', SOURCE, '--json']);+ }), 120_000);++ test('without a reflog the notifier\'s persisted first_due_at dates the wait: 2 h due fails', () => withBrain(databaseUrl, { managed: true }, async ({ engine, root }) => {+ commit(root, 'notes/bob-example.md', '# Bob Example\n', 5 * MINUTE);+ rmSync(join(root, '.git', 'logs'), { recursive: true, force: true });+ await markDue(engine, 120 * MINUTE);+ const check = await doctor(engine);+ expect(check.status).toBe('fail');+ const pending = bySource(check).keyword_visible.oldest_unsynced;+ expect(pending).toMatchObject({ state: 'behind', evidence: 'first_due_at' });+ expect(pending.age_seconds).toBeGreaterThanOrEqual(120 * MINUTE);+ expect(pending.age_seconds).toBeLessThan(121 * MINUTE);+ expect(check.message).toContain('notifier first_due_at');+ }), 120_000);++ test('with no reflog and no first_due_at the wait reads unknown and warns; a rewritten history says so', () => withBrain(databaseUrl, { managed: true }, async ({ engine, root, synced }) => {+ commit(root, 'notes/bob-example.md', '# Bob Example\n', 5 * MINUTE);+ rmSync(join(root, '.git', 'logs'), { recursive: true, force: true });+ let check = await doctor(engine);+ expect(check.status).toBe('warn');+ expect(bySource(check).keyword_visible.oldest_unsynced).toMatchObject({ state: 'unknown', reason: 'no_reflog', age_seconds: null });+ expect(check.message).toContain('its wait cannot be dated');++ git(root, ['checkout', '-q', '--orphan', 'rewritten']);+ const rewritten = commit(root, 'notes/carol-example.md', '# Carol Example\n', 5 * MINUTE);+ rmSync(join(root, '.git', 'logs'), { recursive: true, force: true });+ expect(rewritten).not.toBe(synced);+ check = await doctor(engine);+ expect(check.status).toBe('warn');+ expect(bySource(check).keyword_visible.oldest_unsynced).toMatchObject({ state: 'unknown', reason: 'history_rewritten' });+ }), 120_000);++ test('keyword-visible and embedded freshness are reported separately; an embedding backlog is reported, not graded', () => withBrain(databaseUrl, { managed: true }, async ({ engine }) => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const [page] = await engine.executeRaw<{ id: number }>("INSERT INTO pages(source_id,slug,type,title) VALUES($1,'notes/alice-example','note','Alice Example') RETURNING id", [SOURCE]);+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [page!.id]);+ await engine.executeRaw("INSERT INTO content_chunks(page_id,chunk_index,chunk_text,embedding_pending_since) VALUES($1,0,'Alice Example',now() - interval '20 minutes')", [page!.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const check = await doctor(engine);+ expect(check.status).toBe('ok');+ const fresh = bySource(check);+ expect(fresh.keyword_visible.state).toBe('current');+ expect(fresh.embedded.state).toBe('behind');+ expect(fresh.embedded.backlog).toMatchObject({ state: 'behind', pending_chunks: 1 });+ expect(fresh.embedded.backlog.age_seconds).toBeGreaterThanOrEqual(20 * MINUTE);+ expect(fresh.embedded.backlog.age_seconds).toBeLessThan(21 * MINUTE);+ }), 120_000);++ test('classic equivalent: a non-managed brain grades its classic source\'s unsynced commit', () => withBrain(databaseUrl, { managed: false }, async ({ engine, root }) => {+ commit(root, 'notes/bob-example.md', '# Bob Example\n', 10 * MINUTE);+ const check = await doctor(engine);+ expect(check.status).toBe('warn');+ expect(check.message).not.toContain('Not a managed brain');+ expect(bySource(check)).toMatchObject({ kind: 'classic', keyword_visible: { state: 'behind', oldest_unsynced: { evidence: 'reflog' } } });+ }), 120_000);++ const lag = async (engine: BrainEngine, probeContent: boolean) => (await computeAllSourceMetrics(engine, await loadAllSources(engine), { probeContent }))+ .find(m => m.source_id === SOURCE)!.lag_seconds!;++ test('source-health compares HEAD only: an uncommitted edit to a tracked file is not lag', () => withBrain(databaseUrl, { managed: false }, async ({ engine, root }) => {+ writeFileSync(join(root, 'notes/alice-example.md'), '# Alice Example\nan edit not committed yet\n');+ await engine.executeRaw("UPDATE sources SET last_sync_at = now() - interval '1 hour' WHERE id = $1", [SOURCE]);+ expect(await lag(engine, true)).toBe(0);+ }), 120_000);++ test('source-health dates a pending commit from when it landed (reflog), not from the last no-op heartbeat', () => withBrain(databaseUrl, { managed: false }, async ({ engine, root }) => {+ commit(root, 'notes/bob-example.md', '# Bob Example\n', 10 * MINUTE);+ await engine.executeRaw('UPDATE sources SET last_sync_at = now() WHERE id = $1', [SOURCE]);+ const local = await lag(engine, true);+ expect(local).toBeGreaterThanOrEqual(10 * MINUTE);+ expect(local).toBeLessThan(11 * MINUTE);+ }), 120_000);++ test('source-health without git (remote) dates lag from the notifier\'s first_due_at', () => withBrain(databaseUrl, { managed: false }, async ({ engine }) => {+ await engine.executeRaw("UPDATE sources SET newest_content_at = now() - interval '3 hours' WHERE id = $1", [SOURCE]);+ await markDue(engine, 120 * MINUTE);+ const remote = await lag(engine, false);+ expect(remote).toBeGreaterThanOrEqual(120 * MINUTE);+ expect(remote).toBeLessThan(121 * MINUTE);+ }), 120_000);+ });+}