Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(remediate): planner-stats is not part of the remediation approval's plan_hash

garrytan83deba1d8e08
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19cfcc7233..53acde2c0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,23 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.260.0] - 2026-10-16
+
+**An approved `doctor --remediate --include-repairs` run no longer fails with `preview_changed` because autovacuum analyzed a table between the preview and the run.** Hotfix for LHF wave 2 item 6 (GBRA-107, reported by GBRA-101).
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| Postgres autoanalyzes a table (or collects an expression index's statistics) between `doctor --remediation-plan` and the approved `--remediate --include-repairs --expect <plan_hash>` | refused with `preview_changed`; the approval had to be repeated | runs; planner-stats applies whatever is pending at run time |
+| A new pending repair appears between preview and run | `preview_changed` | `preview_changed` (unchanged) |
+
+### Itemized changes
+
+- `RepairKindSpec.approval: 'unbound'` leaves a kind out of the remediation approval's plan_hash. planner-stats is the one such kind: it plans from live server statistics that autovacuum changes on its own schedule, and its ANALYZE changes no stored record. Every other repair kind stays bound by its pending count.
+- `test/e2e/remediate-planner-stats-approval.test.ts`: an ANALYZE between approval and run fails on v0.60.259.0 with `preview_changed` and passes here; a new orphan connector checkpoint between approval and run still refuses.
+- No schema change.
+
## [0.60.259.0] - 2026-10-16
**Remote Postgres searches take about half the time, typed searches stop paying for JIT compilation, `tokenmax` `query` stops expanding by default, and a new harness proves a performance change leaves every answer the same.** This is LHF wave 2 (GBRA-107), the second low-hanging-fruit wave on search latency, retrieval and cost. Every performance item below was checked against master with the new contract-parity harness: on PGLite and Postgres, every remote response block, `_meta` field and database write is identical; only timings differ.
diff --git a/src/commands/doctor/remediate-consent.ts b/src/commands/doctor/remediate-consent.ts
index dc4645cd80..b2d62a7539 100644
--- a/src/commands/doctor/remediate-consent.ts
+++ b/src/commands/doctor/remediate-consent.ts
@@ -13,6 +13,9 @@
* - `destructive` (repairs): `--yes --expect <plan_hash>`, where plan_hash
* binds the brain, the repair kinds and their pending counts, the job
* steps and the parameters. A changed plan re-asks (`preview_changed`).
+ * Kinds marked `approval: 'unbound'` (planner-stats: live server
+ * statistics, no stored record changed) are left out, so an autoanalyze
+ * between preview and run does not void the approval.
*
* A resume reuses the checkpoint's manifest (brain, cap, steps), so it binds
* no new plan hash; it still needs `--yes` for the effects it continues.
@@ -24,6 +27,7 @@ import type { Effect } from '../../core/agent-output.ts';
import { brainRoutingArgs } from '../../core/brain-resolver.ts';
import type { BrainEngine } from '../../core/engine.ts';
import type { RemediationPlan } from '../../core/remediation/types.ts';
+import { repairSpec } from '../../core/repair/registry.ts';
export interface RemediateFlags {
targetScore: number;
@@ -72,7 +76,7 @@ export function remediationSelection(brainId: string, plan: RemediationPlan | nu
operation: 'doctor --remediate',
records: [
...(plan?.plan ?? []).map(step => ({ id: `job:${step.id}` })),
- ...(plan?.repair_steps ?? []).map(step => ({ id: step.id, revision: step.affected })),
+ ...(plan?.repair_steps ?? []).filter(step => repairSpec(step.kind).approval !== 'unbound').map(step => ({ id: step.id, revision: step.affected })),
],
parameters: { target_score: flags.targetScore, include_repairs: true, no_embed: flags.noEmbed, plan_computed: plan !== null },
effects: ['paid', 'destructive'],
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 2fc2738214..dbe0d066c0 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -90,6 +90,12 @@ export interface RepairKindSpec {
consentText?: { what: string; why: string; risk: string; user_message: string };
/** `llm`: the kind may call a paid chat model; its spend is metered by the daily USD ledger and reported in `cost.llm_usd`. */
spends?: 'llm';
+ /**
+ * `unbound`: the remediation approval (`--expect <plan_hash>`) leaves this kind out. Its plan follows live server
+ * statistics that autovacuum changes between preview and run, and its apply changes no stored record; the run
+ * still applies what is pending then.
+ */
+ approval?: 'unbound';
}
const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
@@ -271,7 +277,7 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Preview-bound: --apply --expect <hash> applies exactly the previewed set. gbrain repair content runs fences, then this kind.',
},
'planner-stats': {
- handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],
+ handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'], approval: 'unbound',
summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '
+ 'so search and graph reads stop planning as slow nested loops. PGLite also resets each table\'s pending row count; Postgres runs each '
+ 'ANALYZE with a 60 s statement and 2 s lock timeout. No journal admission and no user data changes. Brain-wide.',
diff --git a/test/e2e/remediate-planner-stats-approval.test.ts b/test/e2e/remediate-planner-stats-approval.test.ts
new file mode 100644
index 0000000000..a673075364
--- /dev/null
+++ b/test/e2e/remediate-planner-stats-approval.test.ts
@@ -0,0 +1,84 @@
+/**
+ * An approved `doctor --remediate --include-repairs` run survives a server
+ * ANALYZE between preview and run (GBRA-101, after LHF wave 2 item 6).
+ *
+ * Contract protected: the plan_hash an operator approves binds the repair
+ * steps that rewrite stored records. planner-stats plans from live server
+ * statistics (pg_stat counters, pg_stats rows for expression indexes) that
+ * autovacuum changes on its own schedule, and its ANALYZE changes no stored
+ * record, so it is not part of the approval: an autoanalyze landing between
+ * `--remediation-plan` and the run must not refuse it with preview_changed.
+ * A real plan change (a new pending repair) still refuses. Regression that
+ * fails it: the selection carried planner-stats with its table count as the
+ * revision, so the approved hash went stale the moment the table was analyzed.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { PAGES_NAME_LOOKUP_INDEXES } from '../../src/core/schema-migrations/v240-pages-name-lookup-indexes.ts';
+import { readExpressionIndexesWithoutStats } from '../../src/core/planner-stats.ts';
+import { planRepairSteps } from '../../src/core/remediation/repairs.ts';
+import { runRemediate } from '../../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from '../helpers/remediate-approval.ts';
+
+const RUN = hasDatabase();
+const d = RUN ? describe : describe.skip;
+const TITLE_INDEX = PAGES_NAME_LOOKUP_INDEXES[0];
+const ARGS = ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'];
+
+async function quiet(fn: () => Promise<void>): Promise<string | null> {
+ const log = console.log, error = console.error;
+ console.log = () => {};
+ console.error = () => {};
+ try {
+ await fn();
+ return null;
+ } catch (err) {
+ return String((err as { code?: unknown }).code ?? (err as Error).message);
+ } finally {
+ console.log = log;
+ console.error = error;
+ }
+}
+
+d('remediation approval and planner statistics (Postgres)', () => {
+ beforeAll(async () => {
+ const engine = await setupDB();
+ await engine.executeRaw('ALTER TABLE pages SET (autovacuum_enabled = false)');
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title) SELECT 'default', 'people/approval-' || g, 'person', 'Person Example ' || g FROM generate_series(1, 600) g`);
+ });
+ afterAll(async () => {
+ const engine = getEngine();
+ await engine.executeRaw('ALTER TABLE pages RESET (autovacuum_enabled)');
+ await teardownDB();
+ });
+
+ /** The state an upgrade leaves before autoanalyze: pages analyzed, then the expression index built with no ANALYZE after it. */
+ async function unanalyzedIndex(): Promise<void> {
+ const engine = getEngine();
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw(TITLE_INDEX.sql);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+ expect((await planRepairSteps(engine, { noEmbed: true })).map(step => step.kind)).toContain('planner-stats');
+ }
+
+ test('an ANALYZE between the approval and the run does not invalidate the approved plan', async () => {
+ const engine = getEngine();
+ await unanalyzedIndex();
+ const approved = await approvedRemediateArgs(engine, ARGS);
+ await engine.executeRaw('ANALYZE pages');
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([]);
+ expect(await quiet(() => runRemediate(engine, approved))).toBeNull();
+ });
+
+ test('a new pending repair between the approval and the run still refuses with preview_changed', async () => {
+ const engine = getEngine();
+ await unanalyzedIndex();
+ const approved = await approvedRemediateArgs(engine, ARGS);
+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);
+ expect((await planRepairSteps(engine, { noEmbed: true })).map(step => step.kind)).toContain('connector-checkpoints');
+ expect(await quiet(() => runRemediate(engine, approved))).toBe('preview_changed');
+ });
+});