Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): migration ledger row counts only real wedges, honors retry markers, reports skipped host migrations (C-NEW-2, C-NEW-3)
time-attackd4a482b0199e
diff --git a/docs/guides/minions-fix.md b/docs/guides/minions-fix.mdindex 44e00697d5..d49e335078 100644--- a/docs/guides/minions-fix.md+++ b/docs/guides/minions-fix.md@@ -446,6 +446,16 @@ fail:[FAIL] minions_migration: MINIONS HALF-INSTALLED (partial migration: 0.11.0). Run: gbrain apply-migrations --yes```+Three or more partial records in a row read as `WEDGED MIGRATION(s)` and name+`gbrain apply-migrations --force-retry <version>`. After that retry the version+is pending again, and doctor warns that it has not run yet with the plain+`gbrain apply-migrations --yes` command. Doctor also warns when the ledger shows+a host migration that a newer one already ran past, so it never ran:++```+[WARN] minions_migration: 1 host migration(s) not run yet: 0.53.0. Run: gbrain apply-migrations --yes+```+(Missing `~/.gbrain/preferences.json` on a fresh install is a validpre-`apply-migrations` state — doctor deliberately does NOT fail on thatalone; the partial-migration record is the canonical half-migration signal.)diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex 6c55d3b707..681ee3a21e 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -8,7 +8,8 @@*/import { loadCompletedMigrations } from '../../../core/preferences.ts';-import { isFreshInstallStamp } from '../../../core/migration-ledger.ts';+import { indexCompletedEntries, isFreshInstallStamp, migrationLedgerSummary, trailingPartialCount } from '../../../core/migration-ledger.ts';+import { VERSION } from '../../../version.ts';import { pendingFreshInstallCheck } from './pending-fresh-install.ts';import { compareVersions } from '../../migrations/index.ts';import { bootstrapDoctorChecks } from '../bootstrap-checks.ts';@@ -140,9 +141,14 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {const completedVersions = Array.from(byVersion.entries()).filter(([, s]) => s.ran).map(([v]) => v);+ // A trailing `retry` marker (apply-migrations --force-retry) makes the+ // version pending again, as statusForVersion and get_health read it: it+ // is reported below as not run yet, never as still wedged.+ const history = indexCompletedEntries(completed);const stuck = Array.from(byVersion.entries()).filter(([v, s]) => {if (!s.partial || s.complete) return false;+ if (history.get(v)?.at(-1)?.status === 'retry') return false;// Forward-progress override: if any version >= v has completed, the// partial is stale. compareVersions returns 1 when first arg is newer.const supersededBy = completedVersions.find(cv => compareVersions(cv, v) >= 0);@@ -161,11 +167,16 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {// that won't unstick them.const wedged: string[] = [];for (const v of stuck) {- const partialCount = completed.filter(- e => e.version === v && e.status === 'partial',- ).length;+ const partialCount = trailingPartialCount(history.get(v) ?? []);if (partialCount >= 3) wedged.push(v);}+ // Registered host migrations get_health lists as `pending` (no ledger+ // entry, or reset by a retry marker) that a NEWER migration already ran+ // past were skipped, not merely not reached yet. Versions above the newest+ // run are the next apply-migrations' ordinary work and stay quiet here.+ const newestRun = completedVersions.reduce<string | null>((a, v) => (a === null || compareVersions(v, a) > 0 ? v : a), null);+ const pending = completed.length === 0 ? [] : migrationLedgerSummary(VERSION).pending.filter(v =>+ (newestRun !== null && compareVersions(v, newestRun) < 0) || history.get(v)?.at(-1)?.status === 'retry');if (wedged.length > 0) {// The wedged set is a STRICT subset of the stuck set, so a wedged@@ -184,6 +195,13 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {status: 'fail',message: `MINIONS HALF-INSTALLED (partial migration: ${stuck.join(', ')}). Run: gbrain apply-migrations --yes`,});+ } else if (pending.length > 0) {+ checks.push({+ name: 'minions_migration',+ status: 'warn',+ message: `${pending.length} host migration(s) not run yet: ${pending.join(', ')}. Run: gbrain apply-migrations --yes`,+ details: { pending },+ });} else {const setup = pendingFreshInstallCheck();if (setup) checks.push(setup);diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex f2de89a2df..0349f7839f 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -13,7 +13,8 @@ import type { BrainEngine } from '../../core/engine.ts';import { LATEST_VERSION } from '../../core/migrate.ts';import { loadConfig } from '../../core/config.ts';import { loadCompletedMigrations } from '../../core/preferences.ts';-import { isFreshInstallStamp } from '../../core/migration-ledger.ts';+import { indexCompletedEntries, isFreshInstallStamp, migrationLedgerSummary, trailingPartialCount } from '../../core/migration-ledger.ts';+import { VERSION } from '../../version.ts';import { pendingFreshInstallCheck } from './checks/pending-fresh-install.ts';import { compareVersions } from '../migrations/index.ts';import { resolveHoursEnv } from '../../core/env-number.ts';@@ -229,18 +230,24 @@ export async function doctorReportRemote(}// Fresh-install stamps are not forward progress (same rule as the local doctor).const completedVersions = Array.from(byVersion.entries()).filter(([, s]) => s.ran).map(([v]) => v);+ // A trailing retry marker makes the version pending (same rule as the local doctor and get_health).+ const history = indexCompletedEntries(completed);const stuck = Array.from(byVersion.entries()).filter(([v, s]) => {if (!s.partial || s.complete) return false;+ if (history.get(v)?.at(-1)?.status === 'retry') return false;const supersededBy = completedVersions.find(cv => compareVersions(cv, v) >= 0);return supersededBy === undefined;}).map(([v]) => v);const wedged: string[] = [];for (const v of stuck) {- const partialCount = completed.filter(e => e.version === v && e.status === 'partial').length;+ const partialCount = trailingPartialCount(history.get(v) ?? []);if (partialCount >= 3) wedged.push(v);}+ const newestRun = completedVersions.reduce<string | null>((a, v) => (a === null || compareVersions(v, a) > 0 ? v : a), null);+ const pending = completed.length === 0 ? [] : migrationLedgerSummary(VERSION).pending.filter(v =>+ (newestRun !== null && compareVersions(v, newestRun) < 0) || history.get(v)?.at(-1)?.status === 'retry');if (wedged.length > 0) {const cmd = wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ');checks.push({@@ -254,6 +261,13 @@ export async function doctorReportRemote(status: 'fail',message: `MINIONS HALF-INSTALLED on brain host: ${stuck.join(', ')}. Run on the host: gbrain apply-migrations --yes`,});+ } else if (pending.length > 0) {+ checks.push({+ name: 'minions_migration',+ status: 'warn',+ message: `${pending.length} host migration(s) not run yet on brain host: ${pending.join(', ')}. Run on the host: gbrain apply-migrations --yes`,+ details: { pending },+ });} else {const setup = pendingFreshInstallCheck();if (setup) checks.push(setup);diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.tsindex 4b273a777c..c926dbf649 100644--- a/src/core/migration-ledger.ts+++ b/src/core/migration-ledger.ts@@ -71,17 +71,18 @@ export function statusForVersion(const latest = entries[entries.length - 1];if (latest.status === 'retry') return 'pending';if (entries.some(e => e.status === 'complete')) return 'complete';- let consecutive = 0;- for (let i = entries.length - 1; i >= 0; i--) {- const e = entries[i];- if (e.status === 'partial') consecutive++;- else break;- }- if (consecutive >= MAX_CONSECUTIVE_PARTIALS) return 'wedged';+ if (trailingPartialCount(entries) >= MAX_CONSECUTIVE_PARTIALS) return 'wedged';if (entries.some(e => e.status === 'partial')) return 'partial';return 'pending';}+/** Consecutive `partial` entries at the end of one version's ledger history: the wedge counter. A `retry` or `complete` entry resets it. */+export function trailingPartialCount(entries: readonly CompletedMigrationEntry[]): number {+ let consecutive = 0;+ for (let i = entries.length - 1; i >= 0 && entries[i].status === 'partial'; i--) consecutive++;+ return consecutive;+}+/** A ledger entry `gbrain init` wrote for a `fresh_install_noop` migration (src/commands/migrations/fresh-install.ts). */export function isFreshInstallStamp(entry: CompletedMigrationEntry): boolean {return entry.fresh_install === true;diff --git a/test/doctor-minions-check.test.ts b/test/doctor-minions-check.test.tsindex cfd72012e3..256f3a2d61 100644--- a/test/doctor-minions-check.test.ts+++ b/test/doctor-minions-check.test.ts@@ -30,6 +30,7 @@ import { withEnv } from './helpers/with-env.ts';import { runCli } from './helpers/cli-spawn.ts';import { buildChecks, computeDoctorReport, type Check } from '../src/commands/doctor.ts';import { getDbUrlSource } from '../src/core/config.ts';+import { MIGRATION_VERSIONS } from '../src/core/migration-ledger.ts';let tmp: string;@@ -236,6 +237,37 @@ describe('gbrain doctor — half-migrated Minions detection', () => {expect(minions!.message).toContain('0.16.0');});+ function seedLedger(entries: Array<Record<string, unknown>>): void {+ const migrationsDir = join(tmp, '.gbrain', 'migrations');+ mkdirSync(migrationsDir, { recursive: true });+ writeFileSync(join(migrationsDir, 'completed.jsonl'), entries.map(e => JSON.stringify(e)).join('\n') + '\n');+ }++ test('C-NEW-2: a retry marker resets the wedge counter; only trailing partials count', async () => {+ seedLedger(['partial', 'partial', 'partial', 'retry', 'partial'].map(status => ({ version: '0.53.0', status })));+ const minions = (await runFastChecks()).checks.find(c => c.name === 'minions_migration');+ expect(minions!.status).toBe('fail');+ expect(minions!.message).toContain('MINIONS HALF-INSTALLED (partial migration: 0.53.0)');+ expect(minions!.message).not.toContain('--force-retry');+ });++ test('C-NEW-2: after --force-retry the version is pending, not still wedged', async () => {+ seedLedger(['partial', 'partial', 'partial', 'retry'].map(status => ({ version: '0.53.0', status })));+ const result = await runFastChecks();+ const minions = result.checks.find(c => c.name === 'minions_migration');+ expect(minions!.status).toBe('warn');+ expect(minions!.message).toBe('1 host migration(s) not run yet: 0.53.0. Run: gbrain apply-migrations --yes');+ expect(result.exitCode).toBe(0);+ });++ test('C-NEW-3: a host migration a newer one skipped past is reported as never run', async () => {+ seedLedger(MIGRATION_VERSIONS.filter(v => v !== '0.53.0').map(version => ({ version, status: 'complete' })));+ const minions = (await runFastChecks()).checks.find(c => c.name === 'minions_migration');+ expect(minions!.status).toBe('warn');+ expect(minions!.message).toBe('1 host migration(s) not run yet: 0.53.0. Run: gbrain apply-migrations --yes');+ expect((minions!.details as { pending: string[] }).pending).toEqual(['0.53.0']);+ });+test('human output: prints MINIONS HALF-INSTALLED loud banner', async () => {// Same fixture as the first test, but check the human-readable output// includes the exact banner phrase an OpenClaw host's cron scriptdiff --git a/test/doctor-remote-migration-ledger.test.ts b/test/doctor-remote-migration-ledger.test.tsnew file mode 100644index 0000000000..a4700e7d0d--- /dev/null+++ b/test/doctor-remote-migration-ledger.test.ts@@ -0,0 +1,48 @@+/**+ * C-NEW-2/C-NEW-3 on the remote doctor report: the brain host's+ * minions_migration row reads the ledger the way get_health and+ * apply-migrations do. Authoring gate: (1) protects the retry-marker reset+ * and the never-run report on doctorReportRemote; (2) fails when a forced+ * retry still reads as wedged or a skipped host migration stays silent;+ * (3) test/doctor-minions-check.test.ts covers only the local doctor;+ * (4) no production seam (real PGLite engine, isolated GBRAIN_HOME).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { doctorReportRemote } from '../src/commands/doctor/report-remote.ts';+import { MIGRATION_VERSIONS } from '../src/core/migration-ledger.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });++function homeWithLedger(entries: Array<Record<string, unknown>>): string {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-remote-ledger-'));+ mkdirSync(join(home, '.gbrain', 'migrations'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));+ writeFileSync(join(home, '.gbrain', 'migrations', 'completed.jsonl'), entries.map(e => JSON.stringify(e)).join('\n') + '\n');+ return home;+}++async function ledgerRow(entries: Array<Record<string, unknown>>) {+ return withEnv({ GBRAIN_HOME: homeWithLedger(entries), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () =>+ (await doctorReportRemote(engine, { remote: true })).checks.find(c => c.name === 'minions_migration'));+}++describe('remote doctor migration ledger row', () => {+ test('after --force-retry the version is pending, not wedged', async () => {+ const row = await ledgerRow(['partial', 'partial', 'partial', 'retry'].map(status => ({ version: '0.53.0', status })));+ expect(row?.status).toBe('warn');+ expect(row?.message).toBe('1 host migration(s) not run yet on brain host: 0.53.0. Run on the host: gbrain apply-migrations --yes');+ }, 60_000);++ test('a host migration a newer one skipped past is reported as never run', async () => {+ const row = await ledgerRow(MIGRATION_VERSIONS.filter(v => v !== '0.53.0').map(version => ({ version, status: 'complete' })));+ expect(row?.status).toBe('warn');+ expect(row?.message).toContain('not run yet on brain host: 0.53.0');+ }, 60_000);+});