Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): git_convergence check; push health never ok while ahead (#5063)
time-attack476b1399a801
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 1dc9d94be0..87d5b31ebc 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -38,6 +38,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport).- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.+- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig`; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 05c404fe9d..edf9928d51 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -68,6 +68,8 @@`bootstrap_push_health` and `gbrain bootstrap status` report only the push record of the workspace named by this machine's bootstrap receipt; another workspace's stale or failed push is listed as such (a warn naming that workspace), never as this workspace's state. `reranker_health` auth warnings are audit-log history (`details.live_probe_performed: false`), not a live check of the key. These warns can appear while every other check reads green; each one names a check that did not run.+<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace, `git push` otherwise). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.+**`brain_score` shows a low "timeline density (entity and event pages)"?** The 15-point timeline component grades only linkable pages whose type's active-pack primitive is `entity` or `temporal` (people, companies, meetings, emails, events…); reference documents such as notes, writing and guides have no events and are not graded, so do not stamp "page created" rows onto them. Types the pack does not declare are still graded. Raise the score by giving those entity and event pages real timeline entries (`gbrain extract timeline`).**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.diff --git a/docs/wave9/sg.md b/docs/wave9/sg.mdindex 886586988f..6ce0f93432 100644--- a/docs/wave9/sg.md+++ b/docs/wave9/sg.md@@ -12,6 +12,7 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md- **`put_skill` refuses an empty SKILL.md (A-NEW-5).** An empty or whitespace-only entry point is `invalid_params` instead of publishing a blank skill.- **`gbrain reindex --markdown` works on managed brains (#5377, C-NEW-5).** It used to fail every page with "cannot mutate a managed brain through the legacy writer", while doctor, upgrade and post-upgrade kept prescribing it. On a managed brain it now runs the projection repairs (`gbrain repair safe-chunks`, then `contextual-mode` unless `--no-embed`): no page revision, journal request or canonical file changes. `--type` is refused on managed brains with the repair commands.- **`gbrain sources writer status` no longer reports a CLI's own consumer as the brain's ingress (C-NEW-4).** The `ingress` field (always `not_running` from a one-shot CLI) is replaced by `local_process_ingress`, which says it describes only the process that answered; ownership stays under `worktrees` and `bindings`.+- **Doctor sees unpushed source checkouts (#5063).** New `git_convergence` check: a source checkout or `sync.repo_path` with commits not on its upstream warns after 6 hours and fails after 24; uncommitted changes older than 6 hours warn. It compares with the last fetched upstream and never fetches. `bootstrap_push_health` no longer says `ok` on a recent push while the workspace is still ahead of origin, and `scripts/smoke-test.sh` accepts a configured database URL and a keyless embedding provider that doctor accepts.## Upgrade-note rows@@ -25,3 +26,4 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md| Empty SKILL.md refused (A-NEW-5) | Editors publishing placeholder skills | none | Write a non-empty SKILL.md || Managed `reindex --markdown` delegates to projection repairs (#5377) | Managed brains with chunker or contextual-mode drift | doctor calibration hint (`gbrain reindex --markdown`) now works | Run `gbrain repair safe-chunks` / `contextual-mode` directly for per-kind control || `writer status`: `ingress` → `local_process_ingress` with a `scope` note (C-NEW-4) | Scripts reading `ingress` from `gbrain sources writer status --json` | none | Read `local_process_ingress.state`; for ownership read `worktrees`/`bindings` |+| New doctor `git_convergence`; `bootstrap_push_health` warns when ahead (#5063) | Brains syncing from Git checkouts with an upstream | `gbrain doctor --only git_convergence` | Push the checkout; checkouts without an upstream are skipped |diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex d67e7043a2..51618eca15 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -104,8 +104,9 @@ if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; thenENGINE_KIND=$(printf '%s\n' "$ENGINE_JSON" | sed -n 's/.*"effective_engine": *"\([a-z]*\)".*/\1/p' | head -1)ENGINE_SRC=$(printf '%s\n' "$ENGINE_JSON" | sed -n 's/.*"db_url_source": *"\([^"]*\)".*/\1/p' | head -1)[ -n "$ENGINE_KIND" ] && echo " engine: $ENGINE_KIND (${ENGINE_SRC:-no url})"- if [ -z "$DB_URL" ] && [ "$ENGINE_KIND" != "pglite" ]; then- fail "GBrain database — no DATABASE_URL or GBRAIN_DATABASE_URL (and the engine is not pglite)"+ # #5063: a URL from the config file (engine status db_url_source) is as valid as one from the environment.+ if [ -z "$DB_URL" ] && [ "$ENGINE_KIND" != "pglite" ] && [ -z "$ENGINE_SRC" ]; then+ fail "GBrain database — no DATABASE_URL, GBRAIN_DATABASE_URL or configured database URL (and the engine is not pglite)"elserun_doctor_json() { DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" timeout 30 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" doctor --json 2>/dev/null; }DOCTOR_JSON=$(run_doctor_json)@@ -187,12 +188,20 @@ elseskip "OpenClaw gateway — not responding (may not be running yet)"fi-# ── 7. Embedding API key ─────────────────────────────────+# ── 7. Embedding provider ────────────────────────────────+# #5063: the configured provider decides (ollama and other keyless providers+# need no OPENAI/VOYAGE key), so trust doctor's embedding_provider verdict when+# section 3 read it; fall back to the raw keys only without a doctor report.+EMBED_STATUS=$(printf '%s\n' "${DOCTOR_JSON:-}" | sed -n 's/.*"name": *"embedding_provider", *"status": *"\([a-z]*\)".*/\1/p' | head -1)EMBED_KEY="${OPENAI_API_KEY:-${VOYAGE_API_KEY:-}}"-if [ -n "$EMBED_KEY" ]; then+if [ "$EMBED_STATUS" = "fail" ]; then+ fail "Embedding provider — doctor embedding_provider failed (run: gbrain doctor --only embedding_provider)"+elif [ -n "$EMBED_STATUS" ]; then+ pass "Embedding provider (doctor embedding_provider: $EMBED_STATUS)"+elif [ -n "$EMBED_KEY" ]; thenpass "Embedding API key set"else- fail "Embedding API key — neither OPENAI_API_KEY nor VOYAGE_API_KEY is set"+ fail "Embedding provider — no doctor report and neither OPENAI_API_KEY nor VOYAGE_API_KEY is set"fi# ── 8. Brain repo (if configured) ────────────────────────diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.tsindex 0524e14f23..7d82b02e96 100644--- a/src/commands/doctor/bootstrap-checks.ts+++ b/src/commands/doctor/bootstrap-checks.ts@@ -279,18 +279,28 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise// itself failed): unverified must NOT be treated as clean below.let dirty = false;let known = false;+ // #5063: commits on a NAMED branch not yet on origin, counted whatever the push age.+ let ahead = 0;if (ws) {try {const statusOut = execFileSync('git', ['-C', ws, 'status', '--porcelain'], {stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,}).toString();+ const branch = execFileSync('git', ['-C', ws, 'branch', '--show-current'], {+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,+ }).toString().trim();+ if (branch) {+ try {+ ahead = parseInt(execFileSync('git', ['-C', ws, 'rev-list', '--count', `origin/${branch}..HEAD`], {+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,+ }).toString().trim(), 10) || 0;+ } catch { ahead = 0; }+ }if (statusOut.trim() !== '') {dirty = true;known = true;} else {- const branchOut = execFileSync('git', ['-C', ws, 'branch', '--show-current'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,- }).toString().trim();+ const branchOut = branch;if (branchOut) {try {const aheadOut = execFileSync(@@ -367,6 +377,13 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise? `last successful push ${staleIso} (>48h ago); workspace tree state unverified (the git probe failed) — check ${ws} manually, or run \`gbrain sources push --path ${ws}\` to be safe`: `last successful push ${staleIso} (>48h ago); workspace tree state unverified (no bootstrap receipt on this machine names a workspace to check) — check the workspace manually`,});+ } else if (ahead > 0) {+ // #5063: a recent successful push of something never certifies a tree that is still ahead.+ checks.push({+ name: 'bootstrap_push_health',+ status: 'warn',+ message: `last push ok (${staleIso}), but ${ws} has ${ahead} commit(s) not on origin — recent agent memory is unpushed. Run \`gbrain sources push --path ${ws}\`.`,+ });} else {checks.push({ name: 'bootstrap_push_health', status: 'ok', message: `last push ok (${staleIso})` });}diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.tsnew file mode 100644index 0000000000..866b701866--- /dev/null+++ b/src/commands/doctor/checks/git-convergence.ts@@ -0,0 +1,108 @@+/**+ * #5063: `git_convergence`, whether each Git checkout the brain syncs from has+ * reached its upstream. Probes every non-archived filesystem source root plus+ * `sync.repo_path` (connector sources and roots without an upstream are+ * skipped and listed; with no upstream anywhere the check emits nothing) with `git status --porcelain` and ahead/behind against+ * the local `@{u}` ref. It never fetches, so it is only as fresh as the last+ * fetch, and every git call is time-bounded so doctor stays fast and offline.+ *+ * Commits not on the upstream warn once the oldest is older than 6 hours and+ * fail past 24 hours. Uncommitted changes warn once the oldest changed file is+ * older than 6 hours, never fail (they may be deliberate work in progress).+ * Being behind is reported, not judged: sync pulls.+ */+import { execFileSync } from 'node:child_process';+import { statSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { parseSourceConfig } from '../../../core/sources-load.ts';+import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export const GIT_CONVERGENCE_WARN_MS = 6 * 3_600_000;+export const GIT_CONVERGENCE_FAIL_MS = 24 * 3_600_000;+const GIT_TIMEOUT_MS = 5_000;+const MAX_ROOTS = 50;+const MAX_DIRTY_PATHS = 200;++interface RootReport { root: string; source_ids: string[]; branch: string | null; ahead: number; behind: number; dirty: number;+ oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail' }++function git(root: string, args: string[]): string | null {+ try { return execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: GIT_TIMEOUT_MS }).toString(); }+ catch { return null; }+}++function probe(root: string, sourceIds: string[], now: number): RootReport | { root: string; source_ids: string[]; skipped: string } {+ const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();+ if (!top) return { root, source_ids: sourceIds, skipped: 'not a git checkout' };+ const counts = git(top, ['rev-list', '--left-right', '--count', '@{u}...HEAD'])?.trim().split(/\s+/).map(Number);+ if (!counts || counts.length !== 2 || counts.some(n => !Number.isFinite(n))) return { root: top, source_ids: sourceIds, skipped: 'no upstream branch' };+ const [behind, ahead] = counts as [number, number];+ const oldestUnpushed = ahead > 0 ? Number(git(top, ['log', '@{u}..HEAD', '--reverse', '--format=%ct'])?.split('\n')[0]) * 1000 : NaN;+ const changed: string[] = [];+ const entries = (git(top, ['status', '--porcelain', '-z']) ?? '').split('\0');+ for (let i = 0; i < entries.length; i++) {+ if (entries[i].length < 4) continue;+ changed.push(entries[i].slice(3));+ if (/^[RC]/.test(entries[i])) i++;+ }+ const mtimes = changed.slice(0, MAX_DIRTY_PATHS).flatMap(path => { try { return [statSync(join(top, path)).mtimeMs]; } catch { return []; } });+ const oldestDirty = mtimes.length ? Math.min(...mtimes) : NaN;+ const unpushedAge = Number.isFinite(oldestUnpushed) ? now - oldestUnpushed : 0;+ const dirtyAge = Number.isFinite(oldestDirty) ? now - oldestDirty : 0;+ const status = unpushedAge > GIT_CONVERGENCE_FAIL_MS ? 'fail'+ : unpushedAge > GIT_CONVERGENCE_WARN_MS || dirtyAge > GIT_CONVERGENCE_WARN_MS ? 'warn' : 'ok';+ return { root: top, source_ids: sourceIds, branch: git(top, ['branch', '--show-current'])?.trim() || null, ahead, behind, dirty: changed.length,+ oldest_unpushed_at: Number.isFinite(oldestUnpushed) ? new Date(oldestUnpushed).toISOString() : null,+ oldest_dirty_at: Number.isFinite(oldestDirty) ? new Date(oldestDirty).toISOString() : null, status };+}++export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now()): Promise<Check | null> {+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: unknown }>(+ 'SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id');+ const roots = new Map<string, string[]>();+ for (const source of sources) {+ if (!source.local_path || isConnectorSourceKind(parseSourceConfig(source.config).kind)) continue;+ roots.set(source.local_path, [...(roots.get(source.local_path) ?? []), source.id]);+ }+ const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);+ if (repoPath && !roots.has(repoPath)) roots.set(repoPath, []);+ if (!roots.size) return null;+ const byTop = new Map<string, RootReport | { root: string; source_ids: string[]; skipped: string }>();+ for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {+ const report = probe(root, ids, now);+ const prior = byTop.get(report.root);+ byTop.set(report.root, prior ? { ...prior, source_ids: [...prior.source_ids, ...ids] } : report);+ }+ const reports = [...byTop.values()].filter((r): r is RootReport => !('skipped' in r));+ const skipped = [...byTop.values()].filter((r): r is { root: string; source_ids: string[]; skipped: string } => 'skipped' in r);+ const details = { roots: reports, skipped, ...(roots.size > MAX_ROOTS ? { not_probed: roots.size - MAX_ROOTS } : {}),+ warn_after_hours: GIT_CONVERGENCE_WARN_MS / 3_600_000, fail_after_hours: GIT_CONVERGENCE_FAIL_MS / 3_600_000, fetched: false };+ if (!reports.length) return null;+ const bad = reports.filter(r => r.status !== 'ok');+ if (!bad.length) {+ return { name: 'git_convergence', status: 'ok', details,+ message: `${reports.length} Git checkout(s) have no unpushed commits or stale uncommitted changes (compared with the last fetched upstream).` };+ }+ const lines = bad.map(r => `${r.root}${r.source_ids.length ? ` (${r.source_ids.join(', ')})` : ''}: `+ + [r.ahead ? `${r.ahead} commit(s) not on the upstream since ${r.oldest_unpushed_at}` : '', r.dirty && r.oldest_dirty_at ? `${r.dirty} uncommitted change(s), oldest from ${r.oldest_dirty_at}` : '']+ .filter(Boolean).join('; '));+ return { name: 'git_convergence', status: bad.some(r => r.status === 'fail') ? 'fail' : 'warn', details,+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout); this compares with the last fetched upstream and does not fetch.` };+}++async function runGitConvergence(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('git_convergence');+ const check = await gitConvergenceCheck(connectedEngine(ctx));+ if (check) checks.push(check);+ return checks;+}++export const gitConvergenceEntry: DoctorEntry = {+ name: 'git_convergence',+ emits: ['git_convergence'],+ run: runGitConvergence,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 1e54ec8fef..91e3504b12 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -82,6 +82,7 @@ import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeimport { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';+import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { autoChronicleEntry } from './checks/auto-chronicle.ts';import { factsDrainEntry } from './checks/facts-drain.ts';@@ -157,6 +158,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [indexAuditEntry,imageAssetsEntry,syncFreshnessEntry,+ gitConvergenceEntry,decideHealthEntry,unlinkedFactsEntry,edgeValidityEntry,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 47bd973088..a871ed5255 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -148,6 +148,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([// #5984: unfinished managed sync cursors, their remaining entries and indexing ETA.'managed_sync_backlog','sync_freshness',+ // #5063: source checkouts with commits not on their upstream or stale uncommitted changes.+ 'git_convergence','takes_count','takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).diff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.tsindex 9d2fc51b71..adb9e91658 100644--- a/test/bootstrap-doctor-checks.test.ts+++ b/test/bootstrap-doctor-checks.test.ts@@ -354,6 +354,17 @@ describe('bootstrap_push_health', () => {expect(c?.message).toContain('last push ok');}, T);+ test('fresh successful push but the workspace is AHEAD of origin → warn, never ok (#5063)', async () => {+ const { parent, home } = makeHome();+ const ws = makeWorkspace({ ahead: true });+ writeReceipt(home, ws);+ writePushStatus(home, JSON.stringify({ ts: new Date().toISOString(), ok: true }));+ const c = byName(await run(parent), 'bootstrap_push_health');+ expect(c?.status).toBe('warn');+ expect(c?.message).toContain('1 commit(s) not on origin');+ expect(c?.message).toContain(ws);+ }, T);+test('last push FAILED → warn naming the reason (regardless of age)', async () => {const { parent, home } = makeHome();writePushStatus(home, JSON.stringify({ ts: new Date().toISOString(), ok: false, reason: 'push_failed' }));diff --git a/test/doctor-git-convergence-5063.test.ts b/test/doctor-git-convergence-5063.test.tsnew file mode 100644index 0000000000..663945728f--- /dev/null+++ b/test/doctor-git-convergence-5063.test.ts@@ -0,0 +1,83 @@+/**+ * #5063: `git_convergence` compares each source checkout (and sync.repo_path)+ * with its last fetched upstream: commits not pushed warn past 6 hours and fail+ * past 24; stale uncommitted changes warn; roots without an upstream are skipped.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { gitConvergenceCheck } from '../src/commands/doctor/checks/git-convergence.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-git-convergence-'));+const HOUR = 3_600_000;++function git(cwd: string, args: string[], env: Record<string, string> = {}): string {+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } }).toString().trim();+}+function checkout(name: string): string {+ const bare = join(dir, `${name}.git`), work = join(dir, name);+ git(dir, ['init', '-q', '--bare', bare]);+ git(dir, ['clone', '-q', bare, work]);+ git(work, ['config', 'user.email', '[email protected]']);+ git(work, ['config', 'user.name', 'Example']);+ writeFileSync(join(work, 'note.md'), 'first\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'first']); git(work, ['push', '-q', 'origin', 'HEAD']);+ git(work, ['branch', '--set-upstream-to', `origin/${git(work, ['branch', '--show-current'])}`]);+ return work;+}+function commitAt(work: string, file: string, ageMs: number) {+ writeFileSync(join(work, file), `${file}\n`);+ git(work, ['add', '-A']);+ const date = new Date(Date.now() - ageMs).toISOString();+ git(work, ['commit', '-q', '-m', file], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date });+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++test('git_convergence is registered and categorized', () => {+ expect(DOCTOR_CHECK_REGISTRY.some(entry => entry.emits.includes('git_convergence'))).toBe(true);+ expect(categorizeCheck('git_convergence')).toBe('brain');+});++test('converged, ahead (6-24h warn, >24h fail), dirty and upstream-less checkouts', async () => {+ const synced = checkout('synced'), recent = checkout('recent'), old = checkout('old'), dirty = checkout('dirty');+ const noUpstream = join(dir, 'plain'); git(dir, ['init', '-q', noUpstream]);+ for (const [id, path] of [['synced', synced], ['recent', recent], ['old', old], ['dirty', dirty], ['plain', noUpstream]]) {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);+ }+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('mail','mail',$1,'{\"kind\":\"google\"}'::jsonb)", [old]);++ let check = await gitConvergenceCheck(engine);+ expect(check?.status).toBe('ok');++ commitAt(recent, 'recent.md', 8 * HOUR);+ writeFileSync(join(dirty, 'draft.md'), 'work in progress\n');+ const stale = (Date.now() - 10 * HOUR) / 1000; utimesSync(join(dirty, 'draft.md'), stale, stale);+ check = await gitConvergenceCheck(engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('1 commit(s) not on the upstream');+ expect(check?.message).toContain('1 uncommitted change(s)');++ commitAt(old, 'old.md', 30 * HOUR);+ check = await gitConvergenceCheck(engine);+ expect(check?.status).toBe('fail');+ const details = check!.details as { roots: Array<{ source_ids: string[]; ahead: number; status: string }>; skipped: Array<{ source_ids: string[]; skipped: string }>; fetched: boolean };+ expect(details.roots.find(root => root.source_ids.includes('old'))).toMatchObject({ ahead: 1, status: 'fail' });+ expect(details.roots.find(root => root.source_ids.includes('old'))!.source_ids).not.toContain('mail');+ expect(details.skipped).toEqual([expect.objectContaining({ source_ids: ['plain'], skipped: 'no upstream branch' })]);+ expect(details.fetched).toBe(false);+});diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c17732c488..22f54f10fb 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -621,6 +621,10 @@"category": "ops","name": "db_only_collector_collision"},+ {+ "category": "brain",+ "name": "git_convergence"+ },{"category": "ops","name": "decide_health"diff --git a/test/smoke-test-worker.test.ts b/test/smoke-test-worker.test.tsindex ac6fd81478..ae8632e510 100644--- a/test/smoke-test-worker.test.ts+++ b/test/smoke-test-worker.test.ts@@ -8,7 +8,7 @@ const REPO = resolve(import.meta.dir, '..');const SCRIPT = join(REPO, 'scripts', 'smoke-test.sh');const tempDirs: string[] = [];-function runSmoke(opts: { supervisorRunning: boolean; legacyPid?: number }) {+function runSmoke(opts: { supervisorRunning: boolean; legacyPid?: number; configUrlOnly?: boolean; embeddingStatus?: string }) {const dir = mkdtempSync(join(tmpdir(), 'gbrain-smoke-worker-'));tempDirs.push(dir);const fakeBun = join(dir, 'bun');@@ -21,10 +21,10 @@ printf '%s\\n' "$*" >> "$SMOKE_BUN_CALLS"case " $* " in*" --help "*) exit 0 ;;*" engine status --json "*)- printf '%s\\n' '{"schema_version":1,"effective_engine":"postgres","db_url_source":"env:GBRAIN_DATABASE_URL"}'+ printf '%s\\n' "{\\"schema_version\\":1,\\"effective_engine\\":\\"postgres\\",\\"db_url_source\\":\\"$SMOKE_DB_URL_SOURCE\\"}"exit 0 ;;*" doctor --json "*)- printf '%s\\n' '{"checks":[{"name":"connection","status":"ok"}],"health_score":97}'+ printf '%s\\n' "{\\"checks\\":[{\\"name\\":\\"connection\\",\\"status\\":\\"ok\\"}$SMOKE_EMBEDDING_CHECK],\\"health_score\\":97}"exit 0 ;;*" doctor "*) printf '%s\\n' 'GBrain Health Check' 'Health score: 97'; exit 0 ;;*" jobs supervisor status --json "*)@@ -49,11 +49,15 @@ exit 0HOME: dir,GBRAIN_BUN_PATH: fakeBun,GBRAIN_DIR_OVERRIDE: REPO,- GBRAIN_DATABASE_URL: 'postgres://smoke.invalid/brain',+ GBRAIN_DATABASE_URL: opts.configUrlOnly ? '' : 'postgres://smoke.invalid/brain',+ DATABASE_URL: '',+ SMOKE_DB_URL_SOURCE: opts.configUrlOnly ? 'config-file' : 'env:GBRAIN_DATABASE_URL',+ SMOKE_EMBEDDING_CHECK: opts.embeddingStatus ? `,{"name":"embedding_provider","status":"${opts.embeddingStatus}"}` : '',GBRAIN_SMOKE_LOG: join(dir, 'smoke.log'),GBRAIN_SMOKE_WORKER_PID_FILE: workerPid,GBRAIN_BRAIN_PATH: dir,- OPENAI_API_KEY: 'test-only-placeholder',+ OPENAI_API_KEY: opts.embeddingStatus ? '' : 'test-only-placeholder',+ VOYAGE_API_KEY: '',SMOKE_BUN_CALLS: calls,SMOKE_WORKER_STARTED: workerStarted,SMOKE_SUPERVISOR_RUNNING: opts.supervisorRunning ? '1' : '0',@@ -94,3 +98,18 @@ describe('smoke-test worker health (#4175)', () => {expect(existsSync(result.workerStarted)).toBe(false);}, 30_000);});++describe('smoke-test database and embedding sources (#5063)', () => {+ test('a configured database URL and a keyless embedding provider doctor accepts both pass', () => {+ const result = runSmoke({ supervisorRunning: true, configUrlOnly: true, embeddingStatus: 'ok' });+ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);+ expect(result.stdout).toContain('health score: 97/100');+ expect(result.stdout).toContain('Embedding provider (doctor embedding_provider: ok)');+ }, 30_000);++ test('a failing doctor embedding_provider check still fails the smoke test', () => {+ const result = runSmoke({ supervisorRunning: true, embeddingStatus: 'fail' });+ expect(result.status).toBe(1);+ expect(result.stdout).toContain('doctor embedding_provider failed');+ }, 30_000);+});