Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): distinguish a damaged PGLite store from a broken runtime (#2674) (#3569)
test2ae5d60b98ac
diff --git a/docs/progress-events.md b/docs/progress-events.mdindex a85c59b135..a8f5a6e63b 100644--- a/docs/progress-events.md+++ b/docs/progress-events.md@@ -135,6 +135,10 @@ sync that calls import emits `sync.import.<file>`, not `import.<file>`.Stable phase names shipped in v0.15.2:- `doctor.db_checks` (umbrella for all DB-side doctor checks)+- `doctor.pglite_probe` (the #2674 scratch-store probe; only when PGLite init+ failed with an unexplained/damage-class disk state or `--probe-pglite` was+ passed — a cold start can take 5–20s, so the heartbeat is the only sign of+ life)- `orphans.scan`- `embed.pages`- `extract.links_fs`, `extract.timeline_fs`, `extract.links_db`, `extract.timeline_db`diff --git a/src/cli.ts b/src/cli.tsindex 3e63e5c145..f75862b92f 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -3028,7 +3028,7 @@ SETUPmigrate embeddings --to <p:model> Re-embed onto another embedding providerupgrade Self-updatecheck-update [--json] Check for new versions- doctor [--json] [--fast] Health check (resolver, skills, pgvector, RLS, embeddings)+ doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)integrations [subcommand] Manage integration recipes (senses + reflexes)PAGESdiff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 89011c052e..67c784b5ee 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -782,6 +782,124 @@ export async function checkSourceConfigShape(engine: BrainEngine): Promise<Check}}+/**+ * #2674 — pglite_scratch_probe: distinguish a damaged PGLite store from a+ * broken WASM runtime.+ *+ * PGLite reports only `Aborted()` to JS (the PANIC goes to its own stderr),+ * so when init fails, the error string cannot say WHICH of the two it is.+ * The probe initializes a throwaway store in a temp dir, round-trips a row,+ * and reads the outcome:+ *+ * - scratch works, real init failed → the runtime is fine; the failure is+ * specific to YOUR store. The store-damage verdict is only ASSERTED when+ * the caller supplies positive evidence (`storeDamageEvidence`: a+ * damage-class disk diagnosis from `inspectPgliteDataDir`, or a+ * wasm-abort/corrupt classification of the real init error). engine=null+ * alone also covers locks and config refusals — blaming the store for+ * those was the original false-positive defect; without evidence the+ * message hedges and points at the `pglite_data_dir` diagnosis instead.+ * - scratch fails too → the runtime cannot start on this machine; report+ * OS + Bun versions on #223.+ *+ * COST GATE: a PGLite cold start is 5–20s on loaded machines, so this never+ * runs on a routine `gbrain doctor`. It runs only when (a) the real PGLite+ * engine actually failed to open (engine=null, not --fast, configured engine+ * is pglite) AND the disk diagnosis didn't already fully explain the failure+ * (a live lock / missing dir needs no runtime probe), or (b) the operator+ * asks with `--probe-pglite`.+ *+ * `probeFn` is a test seam so message routing can be pinned without paying+ * real cold starts.+ */+export async function checkPgliteScratchProbe(opts: {+ realInitFailed: boolean;+ /**+ * Positive evidence the REAL store is damaged: `inspectPgliteDataDir`+ * verdict wal-corruption-likely/unsupported-layout (buildChecks path) or a+ * wasm-abort/corrupt classification of the actual connect error (remote+ * path). Without it the scratch-ok arm hedges instead of asserting damage.+ */+ storeDamageEvidence?: boolean;+ realStorePath?: string;+ probeFn?: () => Promise<import('../core/pglite-engine.ts').PgliteScratchProbeResult>;+}): Promise<Check> {+ const name = 'pglite_scratch_probe';+ try {+ const probe =+ opts.probeFn ??+ (async () => {+ const { probePgliteScratchStore } = await import('../core/pglite-engine.ts');+ return probePgliteScratchStore(opts.realStorePath);+ });+ const r = await probe();+ const secs = (r.duration_ms / 1000).toFixed(1);+ if (r.ok) {+ if (opts.realInitFailed && opts.storeDamageEvidence) {+ return {+ name,+ status: 'fail',+ message:+ `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` ++ `so the runtime is healthy and YOUR STORE is damaged — not the WASM runtime. ` ++ `Your markdown is unaffected: the DB holds derived data (chunks, embeddings, links, facts) that a re-sync rebuilds. ` ++ `Recover: \`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` for in-place WAL repair (data preserved); ` ++ `if that can't fix it, restore a backup of the store directory or run \`gbrain reinit-pglite\` (wipes + re-inits + re-syncs; ` ++ `defaults embedding flags from your config file).`,+ details: { scratch_ok: true, duration_ms: r.duration_ms },+ };+ }+ if (opts.realInitFailed) {+ // Runtime proven healthy, but no independent evidence of store DAMAGE+ // — engine=null also covers locks, config refusals, and transient+ // failures. Hedge rather than convict the store (#2674 review).+ return {+ name,+ status: 'warn',+ message:+ `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` ++ `so the WASM runtime is healthy — the failure opening your brain is specific to your store, ` ++ `its lock, or its configuration. See the \`pglite_data_dir\` check for the on-disk diagnosis; ` ++ `\`gbrain pglite-repair --dry-run\` diagnoses without mutating anything.`,+ details: { scratch_ok: true, duration_ms: r.duration_ms },+ };+ }+ return {+ name,+ status: 'ok',+ message: `PGLite runtime healthy: scratch store round-trip in ${secs}s.`,+ details: { scratch_ok: true, duration_ms: r.duration_ms },+ };+ }+ const errLine = (r.error ?? 'unknown error').split('\n')[0];+ if (opts.realInitFailed) {+ return {+ name,+ status: 'fail',+ message:+ `A fresh scratch PGLite store ALSO failed to start (${secs}s), so the WASM runtime cannot run ` ++ `on this machine — your store is not necessarily damaged. Report your OS and Bun versions on ` ++ `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,+ details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },+ };+ }+ return {+ name,+ status: 'warn',+ message:+ `Your real store opened, but a fresh scratch PGLite store failed to initialize (${secs}s) — ` ++ `new stores can't be created on this machine. Report your OS and Bun versions on ` ++ `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,+ details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },+ };+ } catch (e) {+ // Includes the never-touch-the-real-store guard refusal. The probe not+ // running is a diagnostic gap, not a diagnosis — warn, don't fail.+ const msg = e instanceof Error ? e.message : String(e);+ return { name, status: 'warn', message: `scratch probe could not run: ${msg}` };+ }+}+export async function doctorReportRemote(engine: BrainEngine,opts: { sourceIds?: string[] } = {},@@ -804,6 +922,23 @@ export async function doctorReportRemote(status: 'fail',message: e instanceof Error ? e.message : String(e),});+ // #2674: on PGLite, a dead connection is exactly the ambiguous case the+ // scratch probe exists for — pay its cold start only on this failure path.+ // Unlike buildChecks (where the connect error was swallowed upstream), the+ // real error IS in hand here: classify it, and only let the probe assert+ // store damage on a damage-class verdict (wasm-abort/corrupt) — a lock or+ // config refusal classifies 'unknown' and gets the hedged message.+ if (engine.kind === 'pglite') {+ let realStorePath: string | undefined;+ try { realStorePath = loadConfig()?.database_path; } catch { /* no config */ }+ let storeDamageEvidence = false;+ try {+ const { classifyPgliteInitError, stringifyPgliteInitError } = await import('../core/pglite-engine.ts');+ const verdict = classifyPgliteInitError(stringifyPgliteInitError(e));+ storeDamageEvidence = verdict === 'wasm-abort' || verdict === 'corrupt';+ } catch { /* classifier unavailable — stay hedged (fail-closed) */ }+ checks.push(await checkPgliteScratchProbe({ realInitFailed: true, storeDamageEvidence, realStorePath }));+ }// Without a connection, every other check is meaningless — short-circuit.return computeDoctorReport(checks);}@@ -6457,24 +6592,62 @@ export async function buildChecks(// Filesystem read failure is non-fatal.}- // 3d. PGLite data-dir diagnosis (WAL-repair wave). Only meaningful when the- // connect already FAILED on a PGLite brain (engine === null): the connect- // error was swallowed by the fs-only fallback, so this check re-derives the- // dir state from disk and names the repair ladder. Skipped under --fast- // (connect wasn't attempted, so "engine === null" proves nothing there).- if (!fastMode && !engine) {- try {- const cfg = loadConfig();- if (cfg?.engine === 'pglite') {+ // 3d. PGLite data-dir diagnosis (WAL-repair wave) + scratch-store probe+ // (#2674). The data-dir check re-derives the failure state from DISK (the+ // connect error was swallowed by the fs-only fallback); the probe adds the+ // RUNTIME dimension (a throwaway store that opens fine proves the WASM+ // runtime is healthy). Both only fire when the connect already FAILED on a+ // PGLite brain (engine === null, not --fast — under --fast connect wasn't+ // attempted, so "engine === null" proves nothing there).+ //+ // Probe cost gate (a PGLite cold start is 5–20s): auto-runs ONLY when init+ // failed AND the disk diagnosis didn't already fully explain it — a live+ // lock or a missing dir needs no runtime probe (and 'locked' was exactly+ // the reviewed false-positive: blaming the store while `gbrain serve` held+ // it). Explicit --probe-pglite always runs it. A routine healthy+ // `gbrain doctor` never pays it.+ {+ const probeRequested = args.includes('--probe-pglite');+ let cfgForProbe: ReturnType<typeof loadConfig> = null;+ try { cfgForProbe = loadConfig(); } catch { /* no config — nothing to diagnose */ }+ const pgliteInitFailed = !engine && !fastMode && cfgForProbe?.engine === 'pglite';++ let dirVerdict: import('../core/pglite-repair.ts').PgliteDirDiagnosis['verdict'] | undefined;+ if (pgliteInitFailed) {+ try {const { inspectPgliteDataDir } = await import('../core/pglite-repair.ts');const { resolve } = await import('node:path');// Absolutize: a RELATIVE database_path would make the sidecar/backup// lookups resolve against doctor's cwd instead of the engine's.- const pgliteDataDir = resolve(cfg.database_path || gbrainPath('brain.pglite'));- checks.push(computePgliteDataDirCheck(pgliteDataDir, inspectPgliteDataDir(pgliteDataDir)));+ const pgliteDataDir = resolve(cfgForProbe!.database_path || gbrainPath('brain.pglite'));+ const diagnosis = inspectPgliteDataDir(pgliteDataDir);+ dirVerdict = diagnosis.verdict;+ checks.push(computePgliteDataDirCheck(pgliteDataDir, diagnosis));+ } catch {+ // Best-effort: an unreadable config or fs failure must not stop doctor.+ }+ }++ const dirExplainsFailure = dirVerdict === 'locked' || dirVerdict === 'missing';+ if (probeRequested || (pgliteInitFailed && !dirExplainsFailure)) {+ progress.start('doctor.pglite_probe');+ const stopHb = startHeartbeat(progress, 'pglite scratch-store probe (cold start, can take 5–20s)…');+ try {+ checks.push(+ await checkPgliteScratchProbe({+ // A lock/missing dir explains the failure without the store being+ // damaged — an explicit --probe-pglite there still reports on the+ // runtime, but must not treat the store as the convicted party.+ realInitFailed: pgliteInitFailed && !dirExplainsFailure,+ storeDamageEvidence:+ dirVerdict === 'wal-corruption-likely' || dirVerdict === 'unsupported-layout',+ realStorePath: cfgForProbe?.database_path,+ }),+ );+ } finally {+ stopHb();+ progress.finish();}- } catch {- // Best-effort: an unreadable config or fs failure must not stop doctor.}}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex da223f42c7..6385e07a33 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -99,6 +99,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['ocr_health','orphan_ratio','oversized_pages',+ 'pglite_scratch_probe','quarantined_pages','raw_provenance','flagged_pages',diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 59b3079048..52b3ac9b67 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1,5 +1,10 @@import { PGlite } from '@electric-sql/pglite';import type { Transaction } from '@electric-sql/pglite';+// Engine-live path: static top-level imports (scratch probe, #2674) — the+// engine-dynamic-import guard forbids lazy `import()` here.+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join as joinPath, resolve as resolvePath, sep as pathSep } from 'node:path';// Engine-live path: static top-level import (no lazy `import()`). Supplies// PGLite's WASM/fsBundle/extension assets embedded via `with { type: 'file' }`// so a `bun build --compile` binary can serve a PGLite brain (Bun vfs #1340).@@ -422,6 +427,95 @@ async function preservingProcessExitCode<T>(fn: () => Promise<T>): Promise<T> {}}+/**+ * #2674 — the scratch-store probe, the diagnostic half of the issue.+ *+ * PGLite reports only `Aborted()` to JS and prints the real PANIC (e.g.+ * `could not locate a valid checkpoint record`) to its own stderr, so from+ * the JS-visible error alone a damaged store is indistinguishable from a+ * broken WASM runtime. The one thing that CAN tell them apart is opening a+ * throwaway store on the same machine:+ *+ * - scratch store works → the runtime is healthy; the REAL store is damaged.+ * - scratch store fails too → the runtime cannot start here at all.+ *+ * Stderr capture: PGLite 0.4.3 exposes no print/printErr hook on+ * `PGliteOptions` (checked: only `debug`, which still writes to the+ * process's own stderr), so we deliberately do NOT try to intercept the+ * PANIC text — monkey-patching process.stderr.write around an async WASM+ * init is exactly the hack the classifier comments warn against. The+ * probe's ok/fail outcome carries the diagnosis instead; `verdict` is+ * populated from the JS-visible error for callers that want it.+ *+ * Runs the SAME code path as the real engine (PGlite.create with the+ * embedded WASM/extension assets) but deliberately NOT PGLiteEngine.connect():+ * connect wraps failures in buildPgliteInitErrorMessage, whose hint text+ * would then pollute re-classification of the probe error.+ *+ * Safety: the scratch dir comes from mkdtemp under os.tmpdir() and is+ * additionally checked against `realStorePath` (refuses any overlap in+ * either direction) — a bug here must never touch the brain being+ * diagnosed. The dir is removed in a finally, success or failure.+ */+export interface PgliteScratchProbeResult {+ ok: boolean;+ duration_ms: number;+ /** JS-visible error when ok=false (the PANIC itself lands on stderr, not here). */+ error?: string;+ verdict?: PgliteInitFailure;+}++export async function probePgliteScratchStore(+ realStorePath?: string,+): Promise<PgliteScratchProbeResult> {+ const scratchDir = await mkdtemp(joinPath(tmpdir(), 'gbrain-pglite-probe-'));+ if (realStorePath) {+ const real = resolvePath(realStorePath);+ const scratch = resolvePath(scratchDir);+ if (scratch === real || scratch.startsWith(real + pathSep) || real.startsWith(scratch + pathSep)) {+ await rm(scratchDir, { recursive: true, force: true }).catch(() => {});+ throw new Error(+ `refusing to probe: scratch dir ${scratch} overlaps the real store ${real}`,+ );+ }+ }++ const started = Date.now();+ let db: PGlite | null = null;+ try {+ // Same assets as the real engine's connect(): the embedded WASM/fsBundle/+ // extension options (Bun vfs #1340) — a compiled binary's probe must+ // exercise the same runtime path the real store open uses.+ const embedded = await getEmbeddedPgliteOptions();+ db = await preservingProcessExitCode(() =>+ PGlite.create({+ dataDir: joinPath(scratchDir, 'store'),+ ...embedded,+ }),+ );+ await db.query(`CREATE TABLE scratch_probe (id int PRIMARY KEY, note text)`);+ await db.query(`INSERT INTO scratch_probe VALUES (1, 'ok')`);+ const res = await db.query<{ note: string }>(`SELECT note FROM scratch_probe WHERE id = 1`);+ if (res.rows[0]?.note !== 'ok') {+ throw new Error(`scratch store read-back mismatch: ${JSON.stringify(res.rows)}`);+ }+ return { ok: true, duration_ms: Date.now() - started };+ } catch (err) {+ const message = stringifyPgliteInitError(err);+ return {+ ok: false,+ duration_ms: Date.now() - started,+ error: message,+ verdict: classifyPgliteInitError(message),+ };+ } finally {+ if (db) {+ try { await db.close(); } catch { /* probe store — nothing to save */ }+ }+ await rm(scratchDir, { recursive: true, force: true }).catch(() => {});+ }+}+export class PGLiteEngine implements BrainEngine {readonly kind = 'pglite' as const;private _db: PGLiteDB | null = null;diff --git a/test/doctor-pglite-scratch-probe.test.ts b/test/doctor-pglite-scratch-probe.test.tsnew file mode 100644index 0000000000..99df59abd6--- /dev/null+++ b/test/doctor-pglite-scratch-probe.test.ts@@ -0,0 +1,299 @@+// #2674 — pglite_scratch_probe: distinguish a damaged PGLite store from a+// broken WASM runtime.+//+// The load-bearing fact: PGLite reports only `Aborted()` to JS and prints the+// real PANIC (`could not locate a valid checkpoint record …`) to its own+// stderr, so the init-error classifier can never discriminate the two cases+// from the default path. The scratch-store probe is the only thing that can:+// a throwaway store that opens fine proves the runtime is healthy.+//+// Pinned contracts:+// - COST GATE: the probe never runs on a routine healthy doctor, and never+// when the on-disk diagnosis already fully explains the failure (a live+// lock or a missing dir). It runs when PGLite init actually failed+// (engine=null + config engine is pglite + not --fast) with an+// unexplained/damage-class dir state, or on explicit `--probe-pglite`.+// - EVIDENCE-GATED verdict (the reviewed false-positive fix): "YOUR STORE+// is damaged" is asserted ONLY with positive evidence — a damage-class+// disk diagnosis (wal-corruption-likely / unsupported-layout) or a+// wasm-abort/corrupt classification of the real connect error. Without+// evidence the scratch-ok arm hedges (warn) instead of convicting the+// store: engine=null also covers locks and config refusals.+// - Discrimination messaging: scratch-ok + evidence names the STORE+// (recovery ladder: pglite-repair first, then reinit-pglite / restore+// backup; markdown unaffected); scratch-fail names the RUNTIME (report+// OS + Bun on #223).+// - Cleanup: the scratch temp dir is removed on success AND failure.+// - Never-touch-the-real-store guard: overlap with the real store path is+// refused before any PGLite work.+// - Cross-surface parity: BOTH buildChecks() and doctorReportRemote() emit+// the check on the PGLite connection-failure path.+//+// NOTE: the buildChecks / doctorReportRemote tests import only symbols that+// exist on master, so on an unmodified master checkout they fail+// BEHAVIORALLY (the check is absent from the emitted list), not via a+// missing export.++import { describe, test, expect } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { buildChecks, doctorReportRemote, type Check } from '../src/commands/doctor.ts';+import { withEnv } from './helpers/with-env.ts';++const PROBE_TIMEOUT = 90_000; // PGLite cold start is 5–20s on loaded machines++function findCheck(checks: Check[], name: string): Check | undefined {+ return checks.find((c) => c.name === name);+}++function scratchDirsInTmp(): Set<string> {+ return new Set(readdirSync(tmpdir()).filter((d) => d.startsWith('gbrain-pglite-probe-')));+}++/** GBRAIN_HOME parent dir whose .gbrain/config.json declares a pglite engine. */+function makePgliteHome(): { home: string; storePath: string } {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-probe-home-'));+ const dotGbrain = join(home, '.gbrain');+ mkdirSync(dotGbrain, { recursive: true });+ const storePath = join(dotGbrain, 'brain.pglite');+ writeFileSync(+ join(dotGbrain, 'config.json'),+ JSON.stringify({ engine: 'pglite', database_path: storePath }),+ );+ return { home, storePath };+}++/**+ * Fabricate a PG17-pglite-shaped data dir that `inspectPgliteDataDir` reads+ * as `wal-corruption-likely`: valid layout (PG_VERSION 17, base/, 8192-byte+ * pg_control, pg_wal/) plus a STALE postmaster.pid (dead PID) — the+ * unclean-shutdown marker. Same fixture shape as doctor-pglite-datadir.test.ts.+ */+function makeDamagedStore(storePath: string): void {+ mkdirSync(join(storePath, 'global'), { recursive: true });+ mkdirSync(join(storePath, 'base'), { recursive: true });+ mkdirSync(join(storePath, 'pg_wal'), { recursive: true });+ writeFileSync(join(storePath, 'PG_VERSION'), '17\n');+ writeFileSync(join(storePath, 'global', 'pg_control'), Buffer.alloc(8192));+ writeFileSync(join(storePath, 'postmaster.pid'), '99999999\n'); // dead PID → stale marker+}++const NO_DB_ENV = { GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined };++describe('pglite_scratch_probe — buildChecks gating (#2674)', () => {+ test(+ 'damage-class disk diagnosis + healthy runtime → probe runs and blames THE STORE',+ async () => {+ const { home, storePath } = makePgliteHome();+ makeDamagedStore(storePath);+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const before = scratchDirsInTmp();+ const checks = await buildChecks(null, ['--scope=brain'], 'config-file-path');+ // The disk diagnosis fires alongside the probe (shared inspection).+ const dirCheck = findCheck(checks, 'pglite_data_dir');+ expect(dirCheck).toBeDefined();+ expect(dirCheck!.status).toBe('fail');+ const check = findCheck(checks, 'pglite_scratch_probe');+ expect(check).toBeDefined();+ // On this (healthy) machine the scratch store works, and the disk+ // shows unclean-shutdown damage, so the verdict is evidence-backed:+ // runtime fine, YOUR STORE is damaged.+ expect(check!.status).toBe('fail');+ expect(check!.message).toContain('YOUR STORE is damaged');+ expect(check!.message).toContain('pglite-repair');+ expect(check!.message).toContain('reinit-pglite');+ expect(check!.message).toContain('markdown is unaffected');+ expect(check!.message).not.toContain('cannot run');+ // Cleanup: no leaked scratch dirs.+ const after = scratchDirsInTmp();+ for (const d of after) expect(before.has(d)).toBe(true);+ });+ },+ PROBE_TIMEOUT,+ );++ test('cost gate: a MISSING store dir explains the failure — no probe, no store conviction', async () => {+ const { home } = makePgliteHome(); // config exists, store dir never created+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const checks = await buildChecks(null, ['--scope=brain'], 'config-file-path');+ // The disk diagnosis names the actual state (missing → init pointer)…+ const dirCheck = findCheck(checks, 'pglite_data_dir');+ expect(dirCheck).toBeDefined();+ expect(dirCheck!.status).toBe('warn');+ // …and the probe does NOT run: nothing ambiguous to discriminate, and+ // pre-fix this exact shape produced the "YOUR STORE is damaged" false+ // positive.+ expect(findCheck(checks, 'pglite_scratch_probe')).toBeUndefined();+ });+ });++ test('cost gate: --fast never pays the probe, even with a failed pglite engine', async () => {+ const { home } = makePgliteHome();+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const checks = await buildChecks(null, ['--fast', '--scope=brain'], 'config-file-path');+ expect(findCheck(checks, 'pglite_scratch_probe')).toBeUndefined();+ });+ });++ test('cost gate: engine=null with a NON-pglite config does not probe', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-probe-home-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(+ join(home, '.gbrain', 'config.json'),+ JSON.stringify({ engine: 'postgres', database_url: 'postgres://localhost/nope' }),+ );+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const checks = await buildChecks(null, ['--scope=brain'], 'config-file-path');+ expect(findCheck(checks, 'pglite_scratch_probe')).toBeUndefined();+ });+ });++ test(+ 'on demand: --probe-pglite with no init failure reports the runtime as healthy (ok)',+ async () => {+ const { home } = makePgliteHome();+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ // --fast keeps the walk cheap; the explicit flag still wins.+ const checks = await buildChecks(null, ['--fast', '--probe-pglite', '--scope=brain'], 'config-file-path');+ const check = findCheck(checks, 'pglite_scratch_probe');+ expect(check).toBeDefined();+ expect(check!.status).toBe('ok');+ expect(check!.message).toContain('runtime healthy');+ });+ },+ PROBE_TIMEOUT,+ );+});++describe('pglite_scratch_probe — doctorReportRemote parity (#2674)', () => {+ test(+ 'a dead PGLite connection with an abort-class error triggers the probe and blames the store',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-probe-home-'));+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const stub = {+ kind: 'pglite',+ getStats: async () => {+ throw new Error('Aborted(). Build with -sASSERTIONS for more info.');+ },+ } as unknown as BrainEngine;+ const report = await doctorReportRemote(stub);+ const check = findCheck(report.checks, 'pglite_scratch_probe');+ expect(check).toBeDefined();+ // wasm-abort classification of the REAL error = damage evidence.+ expect(check!.status).toBe('fail');+ expect(check!.message).toContain('YOUR STORE is damaged');+ });+ },+ PROBE_TIMEOUT,+ );++ test(+ 'a LOCK error on the remote surface must NOT convict the store (the reviewed false positive)',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-probe-home-'));+ await withEnv({ ...NO_DB_ENV, GBRAIN_HOME: home }, async () => {+ const stub = {+ kind: 'pglite',+ getStats: async () => {+ throw new Error('Could not acquire PGLite lock. Another gbrain process is using the database.');+ },+ } as unknown as BrainEngine;+ const report = await doctorReportRemote(stub);+ const check = findCheck(report.checks, 'pglite_scratch_probe');+ expect(check).toBeDefined();+ // Lock errors classify 'unknown' → no damage evidence → hedged warn.+ expect(check!.status).toBe('warn');+ expect(check!.message).not.toContain('YOUR STORE is damaged');+ });+ },+ PROBE_TIMEOUT,+ );++ test('a dead POSTGRES connection on the remote surface does not probe', async () => {+ const stub = {+ kind: 'postgres',+ getStats: async () => {+ throw new Error('connection refused');+ },+ } as unknown as BrainEngine;+ const report = await doctorReportRemote(stub);+ expect(findCheck(report.checks, 'pglite_scratch_probe')).toBeUndefined();+ });+});++describe('probePgliteScratchStore — probe internals (#2674)', () => {+ test('never-touch-the-real-store guard refuses overlap and leaks nothing', async () => {+ const { probePgliteScratchStore } = await import('../src/core/pglite-engine.ts');+ const before = scratchDirsInTmp();+ // The scratch dir lives under tmpdir(), so a "real store" AT tmpdir()+ // must trip the overlap guard before any PGLite work happens.+ await expect(probePgliteScratchStore(tmpdir())).rejects.toThrow(/refusing to probe/);+ const after = scratchDirsInTmp();+ for (const d of after) expect(before.has(d)).toBe(true);+ });++ test('verdict routing: probe outcomes route to the right message via the probeFn seam', async () => {+ // Message routing via the probeFn test seam — no cold start needed.+ const { checkPgliteScratchProbe } = await import('../src/commands/doctor.ts');++ // scratch ok + real init failed + DAMAGE EVIDENCE → the store is convicted.+ const storeDamaged = await checkPgliteScratchProbe({+ realInitFailed: true,+ storeDamageEvidence: true,+ probeFn: async () => ({ ok: true, duration_ms: 1234 }),+ });+ expect(storeDamaged.status).toBe('fail');+ expect(storeDamaged.message).toContain('YOUR STORE is damaged');+ expect(storeDamaged.message).toContain('pglite-repair');+ expect(storeDamaged.message).toContain('reinit-pglite');+ expect(storeDamaged.message).toContain('markdown is unaffected');++ // scratch ok + real init failed + NO evidence → hedged warn, never a+ // store conviction (engine=null also covers locks + config refusals).+ const hedged = await checkPgliteScratchProbe({+ realInitFailed: true,+ probeFn: async () => ({ ok: true, duration_ms: 1234 }),+ });+ expect(hedged.status).toBe('warn');+ expect(hedged.message).not.toContain('YOUR STORE is damaged');+ expect(hedged.message).toContain('runtime is healthy');+ expect(hedged.message).toContain('pglite_data_dir');++ // real init failed + scratch failed too → runtime is broken, ask for OS/Bun.+ const runtimeBroken = await checkPgliteScratchProbe({+ realInitFailed: true,+ probeFn: async () => ({+ ok: false,+ duration_ms: 1234,+ error: 'Aborted(). Build with -sASSERTIONS for more info.',+ verdict: 'unknown' as const,+ }),+ });+ expect(runtimeBroken.status).toBe('fail');+ expect(runtimeBroken.message).toContain('runtime cannot run');+ expect(runtimeBroken.message).toContain('issues/223');+ expect(runtimeBroken.message).toContain('OS and Bun versions');+ expect(runtimeBroken.message).not.toContain('YOUR STORE is damaged');++ // healthy real store + scratch failed → warn, still runtime-facing.+ const scratchOnly = await checkPgliteScratchProbe({+ realInitFailed: false,+ probeFn: async () => ({ ok: false, duration_ms: 10, error: 'boom' }),+ });+ expect(scratchOnly.status).toBe('warn');+ expect(scratchOnly.message).toContain('real store opened');++ // probeFn throwing (e.g. the overlap guard) → warn, not a diagnosis.+ const guardTrip = await checkPgliteScratchProbe({+ realInitFailed: true,+ probeFn: async () => {+ throw new Error('refusing to probe: overlap');+ },+ });+ expect(guardTrip.status).toBe('warn');+ expect(guardTrip.message).toContain('could not run');+ });+});