Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): name the missing column or table before reading it as pre-migration (#6599 follow-up, wave 18b 1.1)
garrytan20eebf2da476
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex d928201d53..9f4f3ac3f8 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -904,6 +904,20 @@ entry fails. Fixtures: `test/fixtures/guards/check-durable-flush.ts/`. Thetest.yml `security-regressions` job; `test/helpers/win32-flush-semantics.ts`makes them discriminate on POSIX.+#### Schema-error predicate guard++`scripts/check-schema-error-predicates.ts` (`bun run check:schema-error-predicates`,+in `bun run verify`) fails on a call to `isUndefinedColumnError` or+`isUndefinedTableError`, or a comparison against the SQLSTATE string `'42703'`,+anywhere in `src/` outside `src/core/utils.ts`. The column helper matches any+42703 and the table helper also matches `column "x" of relation "y" does not+exist`, so a handler that reads them as "pre-migration" reports ok or skipped+for an unrelated missing object. Fix: name the objects the old schema lacks+with `isMissingSchemaObject(e, 'column' | 'table', [names])`. A reviewed degrade+that can never read as ok goes in the guard's `ALLOWLIST` with a reason; a stale+entry fails. Fixtures: `test/fixtures/guards/check-schema-error-predicates.ts/`;+test: `test/scripts/check-schema-error-predicates.test.ts`.+#### Windows hidden-console guard`scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`;diff --git a/package.json b/package.jsonindex 42c3043779..ae7fcf4521 100644--- a/package.json+++ b/package.json@@ -156,6 +156,7 @@"check:layering": "bun scripts/check-layering.ts","check:ai-sdk-importers": "bun scripts/check-ai-sdk-importers.ts","check:durable-flush": "bun scripts/check-durable-flush.ts",+ "check:schema-error-predicates": "bun scripts/check-schema-error-predicates.ts","check:windows-hide": "bun scripts/check-windows-hide.ts","check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts","check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts",diff --git a/scripts/check-schema-error-predicates.ts b/scripts/check-schema-error-predicates.tsnew file mode 100644index 0000000000..0b8429994f--- /dev/null+++ b/scripts/check-schema-error-predicates.ts@@ -0,0 +1,104 @@+#!/usr/bin/env bun+/**+ * Schema-error predicate guard (wave 18b, docs/TESTING.md#schema-error-predicate-guard).+ *+ * `isUndefinedColumnError(e, col)` returns true for ANY SQLSTATE 42703 (the+ * column argument only matters when the driver drops the code), and+ * `isUndefinedTableError(e)` also matches `column "x" of relation "y" does not+ * exist`. A handler that uses either to mean "this brain predates migration N"+ * reports ok / skipped for every missing column or table, including the one+ * that is a real bug. A raw `'42703'` comparison has the same hole.+ *+ * This guard fails on a new call to either broad helper, or a comparison+ * against the string '42703' (`===`, `!==`, `==`, `!=`, `case`), anywhere in+ * src/ outside src/core/utils.ts unless the file is in ALLOWLIST below. Files+ * already allowlisted are the reviewed degrade ladders that still use the+ * broad helpers; an entry that no longer needs it fails as stale.+ *+ * Fix: name the objects the old schema lacks with the strict predicate,+ * `isMissingSchemaObject(e, "column", [names])` (or `"table"`), from+ * src/core/utils.ts.+ *+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).+ */+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const ANCHOR = 'docs/TESTING.md#schema-error-predicate-guard';+const HELPER = 'src/core/utils.ts';+const BROAD = new Set(['isUndefinedColumnError', 'isUndefinedTableError']);++/** Files allowed to keep a broad schema-error predicate. Each entry names its reason; a stale entry fails. */+const ALLOWLIST: Record<string, string> = {+ 'src/core/oauth-provider.ts': 'OAuth token/client degrade ladders retry narrower projections on any 42703; per-column audit is a follow-up',+ 'src/core/grants/legacy-token.ts': 'maps a missing grant column to grant_schema_required (a refusal, never a silent ok)',+ 'src/core/grants/rescope.ts': 'rescope degrade ladder over optional oauth_clients columns; per-column audit is a follow-up',+ 'src/core/ops/request-tools.ts': 'surface-column degrade on the request-tools op; per-column audit is a follow-up',+ 'src/core/token-mint.ts': 'maps a missing grant column to a schema refusal (never a silent ok)',+ 'src/core/trust/min-trust.ts': 'maps a missing min_trust column to migrations_pending (a refusal, never a silent ok)',+ 'src/core/sources-load.ts': 'local code-only 42703 helper behind the sources projection ladder; per-column audit is a follow-up',+ 'src/core/migration-orchestration-lock.ts': 'lock probe treats a pre-lock schema as "no lock held" before migrations run',+};++function tsFiles(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...tsFiles(full));+ else if (entry.endsWith('.ts') && !entry.endsWith('.d.ts')) out.push(full);+ }+ return out;+}++const is42703 = (node: ts.Node | undefined): boolean => !!node && ts.isStringLiteralLike(node) && node.text === '42703';+const EQUALITY = new Set([+ ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,+ ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken,+]);++const violations: string[] = [];+const flagged = new Set<string>();+for (const abs of tsFiles(join(ROOT, 'src'))) {+ const rel = relative(ROOT, abs).replace(/\\/g, '/');+ if (rel === HELPER) continue;+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const line = (node: ts.Node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;+ const report = (node: ts.Node, what: string) => {+ flagged.add(rel);+ if (ALLOWLIST[rel]) return;+ violations.push(`FAIL [schema_error_predicate_broad]: ${rel}:${line(node)} ${what}\n`+ + ` Fix: use isMissingSchemaObject(e, "column", [names]) (or "table") from ${HELPER}, naming the objects the old schema lacks\n`+ + ` Allowlist: only for a reviewed degrade that can never read as ok, add '${rel}': '<reason>' to ALLOWLIST in scripts/check-schema-error-predicates.ts`);+ };+ const visit = (node: ts.Node): void => {+ if (ts.isCallExpression(node)) {+ const callee = node.expression;+ const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : null;+ if (name && BROAD.has(name)) report(node, `calls ${name}, which matches any missing column or table`);+ } else if (ts.isBinaryExpression(node) && EQUALITY.has(node.operatorToken.kind) && (is42703(node.left) || is42703(node.right))) {+ report(node, "compares a SQLSTATE against '42703', which matches any missing column");+ } else if (ts.isCaseClause(node) && is42703(node.expression)) {+ report(node, "switches on SQLSTATE '42703', which matches any missing column");+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+}+for (const [rel, reason] of Object.entries(ALLOWLIST)) {+ if (existsSync(join(ROOT, rel)) && !flagged.has(rel)) {+ violations.push(`FAIL [schema_error_predicate_stale_allowlist]: ${rel} no longer uses a broad schema-error predicate (allowlisted: ${reason})\n`+ + ' Fix: delete its ALLOWLIST entry in scripts/check-schema-error-predicates.ts');+ }+}++if (violations.length) {+ for (const v of violations) console.error(v);+ console.error('Why: a broad predicate reads ANY missing column or table as "pre-migration", so a real schema bug reports ok or skipped.');+ console.error(`See: ${ANCHOR}`);+ console.error(`check-schema-error-predicates: ${violations.length} violation(s)`);+ process.exit(1);+}+console.log(`check-schema-error-predicates: ok (src/, helper ${HELPER}, ${Object.keys(ALLOWLIST).length} allowlisted)`);diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex dddac25f35..cb000b0481 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -71,6 +71,7 @@ check-sync-run-state.ts scanner yes A17 (W4 sync): SyncRun mutable fields (non-rcheck-layering.ts scanner yes EO10 layering (TS AST, every import form): src/core/engine-sql/** imports no engine façade; src/core/schema-migrations/** imports no migrate.ts; src/core/persistence/** imports no ai/gateway.ts (P8 write-inference contract)check-ai-sdk-importers.ts scanner yes P8: provider SDKs (ai, @ai-sdk/*, @anthropic-ai/sdk, openai) imported as runtime values only by scripts/ai-sdk-importers.allowlist (shrink-only), so every model call is observable through invokeAIcheck-durable-flush.ts scanner yes #5595/#5475 Windows durability (TS AST, scope-resolved): fsyncSync of a descriptor from a read-only or unreadable-flags openSync in src/ outside src/core/fs-durable.ts fails, file or directory; write-fd flushes pass; reasoned ALLOWLIST, stale entries fail; bad-directory fixture covers an O_RDONLY directory flush+check-schema-error-predicates.ts scanner yes wave 18b doctor truth (TS AST): a call to isUndefinedColumnError/isUndefinedTableError or a '42703' comparison in src/ outside src/core/utils.ts fails unless the file is in ALLOWLIST (reasoned; stale entries fail); bad-raw-code fixture covers a raw SQLSTATE comparisoncheck-windows-hide.ts scanner yes #4992 Windows hidden consoles (TS AST): runtime child_process import or Bun.spawn* outside src/core/spawn.ts fails unless the file is in NOT_YET_MIGRATED (ratchet: a listed file that stops launching directly fails as stale); explicit windowsHide: false outside ALLOWLIST fails, stale entries failcheck-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex fff9ce6e21..52caee0dbf 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -171,6 +171,9 @@ CHECKS=(# #5595/#5475: no fsync of a read-only descriptor outside src/core/fs-durable.ts# (Windows refuses it with EPERM)."check:durable-flush"+ # Wave 18b: a missing column/table reads as "pre-migration" only when the+ # handler names it (isMissingSchemaObject); broad predicates are allowlisted.+ "check:schema-error-predicates"# #4992: subprocess launches go through src/core/spawn.ts (windowsHide# default); NOT_YET_MIGRATED is a ratchet that only shrinks."check:windows-hide"diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex eccf9f106e..06e1f6f9bb 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -26,7 +26,7 @@ import type { BrainEngine } from '../core/engine.ts';import { assertAllowedScopes } from '../core/scope.ts';import { isTrustTier, TRUST_TIERS, type TrustTier } from '../core/trust/tier.ts';import { setMinTrust, setTokenMinTrust } from '../core/trust/min-trust.ts';-import { generateToken, isUndefinedColumnError, isUndefinedTableError } from '../core/utils.ts';+import { generateToken, isMissingSchemaObject } from '../core/utils.ts';import { TOKEN_ID_RE, insertUnifiedToken } from '../core/token-mint.ts';import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';@@ -1026,12 +1026,10 @@ export function clientOperationsLines(row: ClientRow): string[] {* for the unit suite.*/export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]> {- // The columns each degrade tier drops. isUndefinedColumnError matches any- // 42703 by code; the column list covers message-only (code-less) variants.+ // The columns each degrade tier drops; any other missing object rethrows.const isSchemaShapeError = (e: unknown): boolean =>- isUndefinedTableError(e) ||- ['allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']- .some(col => isUndefinedColumnError(e, col));+ isMissingSchemaObject(e, 'table', 'oauth_clients') ||+ isMissingSchemaObject(e, 'column', ['allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']);try {return await engine.executeRaw<ClientRow>(`SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at@@ -1074,7 +1072,7 @@ export async function tokenLifetimeClampedClients(engine: BrainEngine): Promise<);return new Set(rows.map(r => r.client_id));} catch (e) {- if (isUndefinedTableError(e)) return new Set();+ if (isMissingSchemaObject(e, 'table', 'oauth_grant_audit')) return new Set();throw e;}}diff --git a/src/commands/doctor/checks/canonical-content.ts b/src/commands/doctor/checks/canonical-content.tsindex 9ced0da774..110c4e2f65 100644--- a/src/commands/doctor/checks/canonical-content.ts+++ b/src/commands/doctor/checks/canonical-content.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../../../core/engine.ts';-import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';+import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';import type { Check } from '../../doctor.ts';export async function checkCanonicalContentWrites(engine: BrainEngine, sourceIds?: string[]): Promise<Check | null> {@@ -14,7 +14,7 @@ export async function checkCanonicalContentWrites(engine: BrainEngine, sourceIds: `${sources.length} writer-owned content source(s); no pending canonical publication or recovery.`,details: { writer_owned_count: sources.length, pending_count: pending, recovering_count: recovering } };} catch (error) {- if (/does not exist|no such table/i.test(String(error))) return null;+ if (isOwnedContentSchemaMissing(error)) return null;return { name: 'canonical_content_writes', status: 'warn', message: 'Canonical content publication status could not be verified; inspect sources writer status on the designated owner.' };}}diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.tsindex 883221a200..a43bc9eb46 100644--- a/src/commands/doctor/checks/core-health.ts+++ b/src/commands/doctor/checks/core-health.ts@@ -15,6 +15,7 @@ import type { ProgressReporter } from '../../../core/progress.ts';import type { Check } from '../../doctor.ts';import { PAGE_CHILD_FK_TARGETS, orphanPredicate } from '../../../core/repair/orphan-children.ts';import { checkError } from '../check-fix.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';/*** Doctor check: takes.weight grid integrity (v0.32 — EXP-2).@@ -394,7 +395,7 @@ export async function checkVolunteerChannels(// a connection blip on a fully-migrated brain must not be misreported// as an old schema. Info-only either way; never block doctor.const msg = e instanceof Error ? e.message : String(e);- const tableAbsent = /does not exist|undefined table|no such table|42P01/i.test(msg);+ const tableAbsent = isMissingSchemaObject(e, 'table', 'context_volunteer_events');return {name,status: 'ok',diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex f7d740683e..bcfa6b0651 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -15,7 +15,7 @@ import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../coreimport { chunkerStamp } from '../../../core/chunkers/code.ts';import { effectiveLinkExtractorWatermark, smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';import { previewMentionPass } from '../../../core/mentions/stale.ts';-import { isMissingSchemaObject, isUndefinedColumnError } from '../../../core/utils.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';import {loadStorageConfig,effectiveDbOnlyDirs,@@ -94,7 +94,8 @@ export const EXTRACTION_LAG_MIN_PAGES = 100;* would break a CI/cron pipeline gating on `gbrain doctor`.** Vacuous-skip on tiny brains (<100 pages, no --source) like orphan_ratio.- * Pre-v112 brains (column missing) degrade to OK via isUndefinedColumnError.+ * Pre-v112 brains (links_extracted_at missing) degrade to OK; any other missing+ * column is a real failure.* Strictly SQL — no filesystem/git access — so it's safe to wire into the* thin-client doctorReportRemote path (CDX-5 trust boundary).*@@ -135,7 +136,7 @@ export async function checkLinksExtractionLag(stale = await engine.countStalePagesForExtraction({ sourceId, versionTs, attendance: 'exclude' });attendanceBlocked = await engine.countStalePagesForExtraction({ sourceId, versionTs, attendance: 'blocked' });} catch (e) {- if (!isUndefinedColumnError(e, 'links_attendance_blocked_revision')) throw e;+ if (!isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) throw e;stale = await engine.countStalePagesForExtraction({ sourceId, versionTs });}const pct = (stale / total) * 100;@@ -177,7 +178,7 @@ export async function checkLinksExtractionLag(} catch (e) {// Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK// (migration/bootstrap adds it; nothing to assess until then).- if (isUndefinedColumnError(e, 'links_extracted_at')) {+ if (isMissingSchemaObject(e, 'column', 'links_extracted_at')) {return { name, status: 'ok', message: 'links_extracted_at not present (pre-v112 brain)' };}return checkError(name, 'check links_extraction_lag', e);diff --git a/src/commands/doctor/checks/knowledge-health.ts b/src/commands/doctor/checks/knowledge-health.tsindex 69a706ee29..744d24c8ba 100644--- a/src/commands/doctor/checks/knowledge-health.ts+++ b/src/commands/doctor/checks/knowledge-health.ts@@ -13,6 +13,7 @@ import { zeroTotalContradictionsCheck } from '../../../core/eval-contradictions/import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { agentFix, checkError, doctorVerify } from '../check-fix.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';async function runEvalCapture(ctx: DoctorContext): Promise<Check[]> {const { progress } = ctx;@@ -284,7 +285,7 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {}} catch (err) {const code = (err as { code?: string } | null)?.code;- if (code === '42P01' || code === '42703') {+ if (isMissingSchemaObject(err, 'table', 'ingest_log') || isMissingSchemaObject(err, 'column', 'source_id')) {// ingest_log missing entirely (extreme legacy) or source_id column// missing (pre-v50 brain that hasn't run apply-migrations yet).checks.push({@@ -459,8 +460,7 @@ async function runEffectiveDate(ctx: DoctorContext): Promise<Check[]> {});}} catch (err) {- const code = (err as { code?: string } | null)?.code;- if (code === '42703') {+ if (isMissingSchemaObject(err, 'column', ['effective_date', 'effective_date_source'])) {// column doesn't exist — pre-v0.29.1 brainchecks.push({ name: 'effective_date_health', status: 'ok', message: 'Skipped (effective_date column unavailable — run gbrain apply-migrations)' });} else {@@ -519,8 +519,7 @@ async function runSalience(ctx: DoctorContext): Promise<Check[]> {});}} catch (err) {- const code = (err as { code?: string } | null)?.code;- if (code === '42703' || code === '42P01') {+ if (isMissingSchemaObject(err, 'column', 'emotional_weight') || isMissingSchemaObject(err, 'table', 'takes')) {checks.push({ name: 'salience_health', status: 'ok', message: 'Skipped (emotional_weight or takes table unavailable — pre-v0.29 brain)' });} else {checks.push(checkError('salience_health', 'read pages', err));diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.tsindex 88ff20d050..d023c76271 100644--- a/src/commands/doctor/checks/routing-federation.ts+++ b/src/commands/doctor/checks/routing-federation.ts@@ -8,7 +8,7 @@ import { existsSync, readFileSync } from 'fs';import type { BrainEngine } from '../../../core/engine.ts';import { gbrainPath } from '../../../core/config.ts';import { embedBackfillWorkerSurface } from '../../../core/minions/embed-backfill-admission.ts';-import { isUndefinedTableError, isUndefinedColumnError } from '../../../core/utils.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../../../core/scope.ts';import type { Check } from '../../doctor.ts';@@ -104,7 +104,7 @@ async function adoptedSkillPackSourceIds(engine: BrainEngine): Promise<Set<strin);return new Set(rows.map((r) => r.id));} catch (e) {- if (isUndefinedTableError(e) || isUndefinedColumnError(e, 'incarnation')) return new Set();+ if (isMissingSchemaObject(e, 'table', ['shared_skill_packs', 'shared_skill_heads']) || isMissingSchemaObject(e, 'column', 'incarnation')) return new Set();throw e;}}@@ -232,7 +232,7 @@ export async function checkOauthConfidentialHealth(engine: BrainEngine): Promise} catch (e) {const msg = e instanceof Error ? e.message : String(e);// Pre-OAuth schema (oauth_clients table missing) → ok.- if (msg.toLowerCase().includes('relation') && msg.toLowerCase().includes('does not exist')) {+ if (isMissingSchemaObject(e, 'table', 'oauth_clients')) {return { name: 'oauth_confidential_client_health', status: 'ok', message: 'OAuth not configured (skipping)' };}return { name: 'oauth_confidential_client_health', status: 'warn', message: `Check failed: ${msg}` };@@ -299,11 +299,9 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<orphaned = await engine.executeRaw<{ id: string }>(orphanSql(true), [WORKSPACE_SUFFIX]);} catch (e) {// Pre-v0.31 brain without the facts table: a source can't hold facts it- // has no table for — retry without the exclusion. Scoped here (code-first- // classification + the message must name `facts`) so the dangling-grant- // arm's findings above aren't lost to the outer catch's schema-degrade.- const msg = e instanceof Error ? e.message : String(e);- if (!(isUndefinedTableError(e) && /facts/i.test(msg))) throw e;+ // has no table for — retry without the exclusion. Scoped here so the+ // dangling-grant arm's findings above aren't lost to the outer catch.+ if (!isMissingSchemaObject(e, 'table', 'facts')) throw e;orphaned = await engine.executeRaw<{ id: string }>(orphanSql(false), [WORKSPACE_SUFFIX]);}// (c) PRIVILEGED SELF-REGISTERED CLIENTS — an active row whose scope@@ -337,7 +335,7 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<[privilegedScopeRegex],);} catch (e) {- if (!(isUndefinedTableError(e) || isUndefinedColumnError(e, 'grant_revision'))) throw e;+ if (!(isMissingSchemaObject(e, 'table', 'oauth_grant_audit') || isMissingSchemaObject(e, 'column', 'grant_revision'))) throw e;privilegedDcrNote = 'self-registered-client scope audit skipped: grant audit schema not present (run `gbrain apply-migrations --yes`), so privileged self-registered clients are unknown';}const problems: string[] = [];@@ -390,16 +388,13 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<};} catch (e) {const msg = e instanceof Error ? e.message : String(e);- // Pre-OAuth schema (table missing) or pre-migration schema (column- // missing) → ok, matching the confidential-client check's posture.- // CODE-FIRST classification (42P01/42703 via core/utils): a bare message- // regex would classify e.g. `function unnest(jsonb) does not exist` — a- // type-drift failure this check exists to catch — as "schema not present"- // and lie green. Column candidates are the optional oauth-scoping columns- // this check's queries touch.- const missingColumn = ['federated_read', 'source_id', 'deleted_at', 'archived', 'local_path']- .some((c) => isUndefinedColumnError(e, c));- if (isUndefinedTableError(e) || missingColumn) {+ // Pre-OAuth schema (oauth_clients missing) or pre-migration schema (one+ // of the optional oauth-scoping columns missing) → ok, matching the+ // confidential-client check's posture. Any other missing object, or a+ // type-drift failure like `function unnest(jsonb) does not exist`, is a+ // real failure this check exists to catch.+ if (isMissingSchemaObject(e, 'table', 'oauth_clients')+ || isMissingSchemaObject(e, 'column', ['federated_read', 'source_id', 'deleted_at', 'archived', 'local_path'])) {return { name: 'oauth_client_scope_health', status: 'ok', message: 'OAuth scoping schema not present (skipping)' };}return { name: 'oauth_client_scope_health', status: 'warn', message: `Check failed: ${msg}` };@@ -534,7 +529,7 @@ export async function checkStaleLocks(} catch (e) {const msg = e instanceof Error ? e.message : String(e);// Pre-v0.30 brains may not have the gbrain_cycle_locks table yet.- if (/relation .* does not exist|no such table/i.test(msg)) {+ if (isMissingSchemaObject(e, 'table', 'gbrain_cycle_locks')) {return { name: 'stale_locks', status: 'ok', message: 'gbrain_cycle_locks table not yet provisioned (skipping)' };}return { name: 'stale_locks', status: 'warn', message: `Check failed: ${msg}` };diff --git a/src/commands/doctor/checks/shared-skills.ts b/src/commands/doctor/checks/shared-skills.tsindex b213059313..1d1fe5ca66 100644--- a/src/commands/doctor/checks/shared-skills.ts+++ b/src/commands/doctor/checks/shared-skills.ts@@ -3,6 +3,7 @@ import { readSharedSkillsSourceView } from '../../../core/shared-skills/source-oimport { SHARED_SKILLS_OPT_OUT_DOCS } from '../../../core/shared-skills/setup-source-policy.ts';import type { Check } from '../../doctor.ts';import { agentFix } from '../check-fix.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';/*** Sources opted out of shared-skills adoption (`config.shared_skills=false`)@@ -28,7 +29,7 @@ export async function checkSharedSkillsSources(engine: BrainEngine): Promise<Che'Shows the parked bound and the three ways to resume (raise the bound, opt out, or shrink and release); it changes nothing.', 'shared_skills_sources', { docs: SHARED_SKILLS_OPT_OUT_DOCS }),};} catch (error) {- if (/does not exist|no such table/i.test(String(error))) return null;+ if (isMissingSchemaObject(error, 'column', ['archived', 'incarnation'])) return null;return { name: 'shared_skills_sources', status: 'warn', fix_unavailable_reason: 'check_errored',message: `Shared-skills source settings could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };}diff --git a/src/commands/doctor/checks/trust-scan.ts b/src/commands/doctor/checks/trust-scan.tsindex c1203635b8..6e190e8d3c 100644--- a/src/commands/doctor/checks/trust-scan.ts+++ b/src/commands/doctor/checks/trust-scan.ts@@ -15,7 +15,7 @@ import type { Check } from '../../doctor.ts';import { checkError, doctorVerify } from '../check-fix.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { readTrustScanState } from '../../../core/eligibility/scan.ts';-import { isUndefinedColumnError, isUndefinedTableError } from '../../../core/utils.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';const SCAN_USER_MESSAGE = 'gbrain can check your memory written before its write gate for text that reads like instructions to an AI '+ '(for example "from now on always say..."). Anything it flags stays in your brain, in search and in what agents get automatically, '@@ -41,7 +41,7 @@ async function runTrustScan(ctx: DoctorContext): Promise<Check[]> {why: 'Scans legacy agent-written and unverified rows with the deterministic detector and records flag receipts; it moves, deletes or rewrites nothing, but flagged rows read as flagged (and leave proactive context under trust.agent_activation suppress) until the owner confirms them, so the user runs it after reading user_message; no agent starts it.',user_message: SCAN_USER_MESSAGE } });} catch (err) {- if (isUndefinedColumnError(err, 'trust_tier') || isUndefinedTableError(err)) {+ if (isMissingSchemaObject(err, 'column', 'trust_tier') || isMissingSchemaObject(err, 'table', ['facts', 'takes', 'timeline_entries'])) {checks.push({ name: 'trust_scan', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates the write gate; the scan arrives with its migration.' });} else {checks.push(checkError('trust_scan', 'read the trust scan state', err));diff --git a/src/commands/doctor/checks/trust-sources-unclaimed.ts b/src/commands/doctor/checks/trust-sources-unclaimed.tsindex eb8609e37d..4b129c1b08 100644--- a/src/commands/doctor/checks/trust-sources-unclaimed.ts+++ b/src/commands/doctor/checks/trust-sources-unclaimed.ts@@ -16,7 +16,7 @@ import { connectedEngine, type DoctorContext, type DoctorEntry } from '../conteximport { claimSourcesFix, readUnclaimedLegacySources } from '../../../core/trust/claim.ts';import { TRUST_CLAIM_RESUME_COMMAND } from '../../../core/trust/claim-state.ts';import { relowerClaimedRows, TRUST_RELOWER_COMMAND, type TrustRelowerReport } from '../../../core/trust/backfill.ts';-import { isUndefinedColumnError } from '../../../core/utils.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';const VERIFY = { argv: ['gbrain', 'doctor', '--only', 'trust_sources_unclaimed', '--json'] };@@ -49,7 +49,7 @@ async function runTrustSourcesUnclaimed(ctx: DoctorContext): Promise<Check[]> {fix: claimSourcesFix('trust_sources_unclaimed') });}} catch (err) {- if (isUndefinedColumnError(err, 'trust_tier')) {+ if (isMissingSchemaObject(err, 'column', 'trust_tier')) {checks.push({ name: 'trust_sources_unclaimed', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates trust tiers; claiming arrives with the migration that adds them.' });} else {checks.push(checkError('trust_sources_unclaimed', 'read unclaimed sources', err));diff --git a/src/commands/doctor/checks/trust-tiers.ts b/src/commands/doctor/checks/trust-tiers.tsindex 108c71a6ca..6844d67ffe 100644--- a/src/commands/doctor/checks/trust-tiers.ts+++ b/src/commands/doctor/checks/trust-tiers.ts@@ -16,7 +16,7 @@ import { connectedEngine, type DoctorContext, type DoctorEntry } from '../conteximport { readTrustBackfillState, readTrustTierCounts } from '../../../core/trust/backfill.ts';import { TRUST_TIERS } from '../../../core/trust/tier.ts';import { readDerivedTaintShare } from '../../../core/trust/taint.ts';-import { isUndefinedColumnError } from '../../../core/utils.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';async function runTrustTiers(ctx: DoctorContext): Promise<Check[]> {@@ -46,7 +46,7 @@ async function runTrustTiers(ctx: DoctorContext): Promise<Check[]> {fix: agentFix(argv, 'Classifies legacy rows from deterministic signals in resumable batches; it never raises a row to confirmed and changes no content.', 'trust_tiers',{ preview_argv: ['gbrain', 'trust', 'backfill', '--dry-run', '--json'] }) });} catch (err) {- if (isUndefinedColumnError(err, 'trust_tier')) {+ if (isMissingSchemaObject(err, 'column', 'trust_tier')) {checks.push({ name: 'trust_tiers', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates trust tiers; they arrive with the migration that adds them.' });} else {checks.push(checkError('trust_tiers', 'read trust tier counts', err));diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 039f394151..36eecca6e8 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -43,7 +43,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { ATTENDANCE_REPAIR_HELP, isAttendanceRepairRequest } from './extract-attendance-repair.ts';import { join, relative, dirname } from 'path';import type { BrainEngine, LinkBatchInput, TimelineBatchInput } from '../core/engine.ts';-import { isUndefinedTableError } from '../core/utils.ts';+import { isMissingSchemaObject } from '../core/utils.ts';import type { PageType } from '../core/types.ts';import { parseMarkdown } from '../core/markdown.ts';import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';@@ -509,7 +509,7 @@ async function loadSlugAliasTargets(engine: BrainEngine, sourceId: string, allSltry {rows = await engine.executeRaw('SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id = $1', [sourceId]);} catch (error) {- if (!isUndefinedTableError(error)) throw error;+ if (!isMissingSchemaObject(error, 'table', 'slug_aliases')) throw error;}const aliases = new Map(rows.filter(row => !allSlugs.has(row.alias_slug) && allSlugs.has(row.canonical_slug)).map(row => [row.alias_slug, row.canonical_slug]));diff --git a/src/commands/reconcile-links.ts b/src/commands/reconcile-links.tsindex d94d2bcb6d..b85cba6095 100644--- a/src/commands/reconcile-links.ts+++ b/src/commands/reconcile-links.ts@@ -23,6 +23,7 @@*/import type { BrainEngine } from '../core/engine.ts';+import { PageMissingError } from '../core/engine-errors.ts';import { extractCodeRefs } from '../core/link-extraction.ts';import { slugifyCodePath } from '../core/sync.ts';import { createProgress } from '../core/progress.ts';@@ -129,12 +130,11 @@ export async function runReconcileLinks(await engine.addLink(codeSlug, mdSlug, ref.path, 'documented_by', 'markdown', mdSlug, 'compiled_truth', linkOpts); // gbrain-allow-direct-insert: gbrain reconcile-links command — reverse documented_by edge} catch (e: unknown) {// Per-link errors don't abort the batch. Track them for the summary.- const msg = e instanceof Error ? e.message : String(e);- if (/not found|does not exist/i.test(msg)) {+ if (e instanceof PageMissingError) {edgesTargetsMissing++;} else {// Real error — log but keep going. Agents can inspect progress events.- console.warn(`[reconcile-links] ${mdSlug} → ${codeSlug}: ${msg}`);+ console.warn(`[reconcile-links] ${mdSlug} → ${codeSlug}: ${e instanceof Error ? e.message : String(e)}`);}}}diff --git a/src/commands/think.ts b/src/commands/think.tsindex d3e9650f21..78933f45a9 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -177,7 +177,7 @@ prints what would have been the input (exit 0).let allowedSources: string[] | undefined;const { resolveSourceWithTier, localFederatedSourceIds, ALL_SOURCES } =await import('../core/source-resolver.ts');- const { isUndefinedTableError } = await import('../core/utils.ts');+ const { isMissingSchemaObject } = await import('../core/utils.ts');try {const resolved = await resolveSourceWithTier(engine, source ?? null);// __all__ spans the brain; runThink has no sentinel handling of its@@ -188,7 +188,7 @@ prints what would have been the input (exit 0).// Only the structural pre-init failure (no sources table) keeps the// legacy unscoped gather; every other resolver error — an unknown// ambient source, a connection failure, a genuine bug — propagates.- if (source !== undefined || !isUndefinedTableError(err)) throw err;+ if (source !== undefined || !isMissingSchemaObject(err, 'table', 'sources')) throw err;}result = await runThink(engine, {question, anchor, rounds, save, take, model, since, until,diff --git a/src/core/by-mention.ts b/src/core/by-mention.tsindex d2bf9c4bf7..fb75b1d13f 100644--- a/src/core/by-mention.ts+++ b/src/core/by-mention.ts@@ -32,7 +32,7 @@import { createHash } from 'crypto';import type { BrainEngine } from './engine.ts';-import { isUndefinedTableError } from './utils.ts';+import { isMissingSchemaObject } from './utils.ts';import { CJK_SLUG_CHARS } from './cjk.ts';import { stripCodeBlocks, isCrossSourceLinksEnabled } from './link-extraction.ts';// #4222: shared generic-token reject list — same list gates enrichEntity@@ -593,7 +593,7 @@ export async function buildGazetteer(// (mention-pass) build throws instead, so nothing is reconciled against// a partial gazetteer.if (opts.strict) throw err;- if (!isUndefinedTableError(err) && !aliasGazetteerWarned) {+ if (!isMissingSchemaObject(err, 'table', 'page_aliases') && !aliasGazetteerWarned) {aliasGazetteerWarned = true;console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);}diff --git a/src/core/chronicle/ledger-stats.ts b/src/core/chronicle/ledger-stats.tsindex 44f70dbe9c..9ab8739a52 100644--- a/src/core/chronicle/ledger-stats.ts+++ b/src/core/chronicle/ledger-stats.ts@@ -1,7 +1,7 @@// Life Chronicle (#5876): read-only rollups of the `chronicle_page_state` ledger for doctor and// the advisor. One query module so the surfaces cannot drift from the ledger's columns.import type { BrainEngine } from '../engine.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';export interface ChronicleLedgerStats {/** False when the ledger table is absent (migration not applied yet). */@@ -71,7 +71,7 @@ export async function readChronicleLedgerStats(engine: BrainEngine): Promise<ChrincompleteRecords: Number(counts?.incomplete ?? 0) },};} catch (error) {- if (isUndefinedTableError(error)) return EMPTY;+ if (isMissingSchemaObject(error, 'table', ['chronicle_page_state', 'chronicle_judge_reservations'])) return EMPTY;throw error;}}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 65bc902066..4f61f08521 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -83,7 +83,7 @@ import { throwIfAborted } from '../abort-check.ts';import { createHash } from 'crypto';import { slugifySegment } from '../sync.ts';import { resolveAlias, resolveTierDefault } from '../model-config.ts';-import { isUndefinedTableError, warnOncePerProcess } from '../utils.ts';+import { isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';import { utcDate } from './cycle-date.ts';import { normalizeForGrounding } from './synthesize-verify.ts';import type { TranscriptPageIndex } from '../transcripts/discover.ts';@@ -635,7 +635,7 @@ export async function tombstonedTranscriptsForHashes();return new Set(rows.map(r => transcriptStateKey(r.file_path, r.content_hash)));} catch (err) {- if (isUndefinedTableError(err)) {+ if (isMissingSchemaObject(err, 'table', 'extract_atoms_transcript_state')) {// Un-migrated brain: the table lands with v146. Once per process, not a// full error line on every cycle until the operator migrates.warnOncePerProcess('extract_atoms.transcript_state_missing',@@ -1034,7 +1034,7 @@ export async function runPhaseExtractAtoms(// A strike that never lands means this transcript never tombstones and// re-spends budget forever (#4916's class) — say so. A missing table// was already warned once by the tombstone check above.- if (!isUndefinedTableError(err)) {+ if (!isMissingSchemaObject(err, 'table', 'extract_atoms_transcript_state')) {console.error(`[extract_atoms] transcript failure-count write failed for ${item.filePath}: ${err instanceof Error ? err.message : String(err)}`);}return null;diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.tsindex dc62dccc1b..593073ddd5 100644--- a/src/core/destructive-guard.ts+++ b/src/core/destructive-guard.ts@@ -22,7 +22,7 @@ import { resolve as resolvePath } from 'node:path';import { isPathContained } from './path-confine.ts';import { defaultCloneDir } from './sources-ops.ts';import { gbrainPath } from './config.ts';-import { isUndefinedColumnError, isUndefinedTableError } from './utils.ts';+import { isMissingSchemaObject } from './utils.ts';import { deleteSourceRow, EXPIRED_ARCHIVE_SQL, UNVERIFIED_ARCHIVE_SQL, unverifiedArchiveReason } from './source-delete.ts';// ── Types ───────────────────────────────────────────────────@@ -107,13 +107,11 @@ export async function clientsReferencingSource();return rows.map((r) => ({ clientId: r.client_id, clientName: r.client_name, deleted: r.deleted === true }));} catch (e) {- if (isUndefinedTableError(e)) return [];- // isUndefinedColumnError is code-first (any 42703 matches), and the- // primary query references BOTH optional columns — disambiguate on the- // message, which names the missing column.- const msg = e instanceof Error ? e.message : String(e);- if (isUndefinedColumnError(e, 'source_id') && msg.includes('source_id')) return [];- if (!(isUndefinedColumnError(e, 'deleted_at') && msg.includes('deleted_at'))) throw e;+ if (isMissingSchemaObject(e, 'table', 'oauth_clients')) return [];+ // The primary query references BOTH optional columns; the strict+ // predicate tells them apart by the column the error names.+ if (isMissingSchemaObject(e, 'column', 'source_id')) return [];+ if (!isMissingSchemaObject(e, 'column', 'deleted_at')) throw e;try {const rows = await engine.executeRaw<{ client_id: string; client_name: string }>(`SELECT client_id, client_name FROM oauth_clients@@ -124,7 +122,7 @@ export async function clientsReferencingSource(return rows.map((r) => ({ clientId: r.client_id, clientName: r.client_name, deleted: false }));} catch (e2) {// The fallback's only optional column is source_id — no column ⇒ no FK.- if (isUndefinedColumnError(e2, 'source_id')) return [];+ if (isMissingSchemaObject(e2, 'column', 'source_id')) return [];throw e2;}}@@ -242,7 +240,7 @@ export async function assessDestructiveImpact();factCount = factRows[0]?.n ?? 0;} catch (e) {- if (!isUndefinedTableError(e)) throw e;+ if (!isMissingSchemaObject(e, 'table', 'facts')) throw e;}// PR6 D5b: fold the FK-RESTRICT referent count into the preview so thediff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 9a24d03904..b27ca6f6e3 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -23,7 +23,7 @@ import { sanitizeText } from '../batch-rows.ts';import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';import { quarantineFilterFragment } from '../quarantine.ts';-import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isUndefinedTableError, warnOncePerProcess } from '../utils.ts';+import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';import { DELETE_BATCH_SIZE } from '../engine-constants.ts';import { jsonbParam, type SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';@@ -1027,7 +1027,7 @@ export async function resolveSlugWithAliasDetailed(} catch (e) {// Pre-v105 brain: slug_aliases table doesn't exist yet. Defense-in-depth// per the engine interface contract.- if (isUndefinedTableError(e)) return null;+ if (isMissingSchemaObject(e, 'table', 'slug_aliases')) return null;throw e;}}diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex 44d70bbb8c..d899119586 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -29,7 +29,7 @@ import { slugifySegment } from '../sync.ts';/** Lazy: the mentions graph stays out of the OpenClaw plugin's static import graph. */const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonical = async (...args) =>(await import('../mentions/siblings.ts')).siblingCanonical(...args);-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { rankingLinkSql } from '../link-ranking-policy.ts';@@ -189,7 +189,7 @@ async function tryAliasExact(engine: BrainEngine, source_id: string, raw: stringconst live = [...new Set(rows.map((r) => r.slug))];return live.length === 1 ? live[0] : await siblingCanonical(engine, source_id, live);} catch (err) {- if (!isUndefinedTableError(err) && !aliasExactWarned) {+ if (!isMissingSchemaObject(err, 'table', 'page_aliases') && !aliasExactWarned) {aliasExactWarned = true;console.error(`[gbrain] alias-exact resolution degraded (falling through to fuzzy): ${err instanceof Error ? err.message : String(err)}`);}@@ -384,7 +384,7 @@ export async function resolveStrictEntityReference(const aliased = await pick(await live(hits.map(h => h.slug)), 'alias_exact');if (aliased) return aliased;} catch (err) {- if (!isUndefinedTableError(err)) throw err;+ if (!isMissingSchemaObject(err, 'table', 'page_aliases')) throw err;}}if (opts.sameName && !isBareName(trimmed)) {diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.tsindex f976af92f3..e68db901ec 100644--- a/src/core/entity-identity.ts+++ b/src/core/entity-identity.ts@@ -28,7 +28,7 @@import type { BrainEngine } from './engine.ts';import type { Link } from './types.ts';-import { isUndefinedTableError } from './utils.ts';+import { isMissingSchemaObject } from './utils.ts';import { privatePagesFilterFragment } from './search/private-visibility.ts';/** Config key for the flag-gated retrieval union. Default OFF. */@@ -245,7 +245,7 @@ export async function listEntityIdentities(}));} catch (e) {// Pre-v137 brain (table missing): identity is simply "not set up yet".- if (isUndefinedTableError(e)) return [];+ if (isMissingSchemaObject(e, 'table', 'entity_identities')) return [];throw e;}}@@ -270,7 +270,7 @@ export async function identityIdsForPages();return new Map(rows.map((r): [string, string] => [`${r.source_id}:${r.slug}`, r.entity_id]).filter(([k]) => wanted.has(k)));} catch (e) {- if (isUndefinedTableError(e)) return new Map();+ if (isMissingSchemaObject(e, 'table', 'entity_identities')) return new Map();throw e;}}diff --git a/src/core/google/counterparty.ts b/src/core/google/counterparty.tsindex 6facee0a0b..0e5bb75895 100644--- a/src/core/google/counterparty.ts+++ b/src/core/google/counterparty.ts@@ -20,7 +20,7 @@*/import type { BrainEngine } from '../engine.ts';import { normalizeAlias } from '../search/alias-normalize.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';export interface ResolvedCounterparty {slug: string;@@ -42,7 +42,7 @@ async function canonicalTwin(engine: BrainEngine, sourceId: string, slug: string);return rows.length === 1 ? { slug: rows[0]!.slug, sourceId: rows[0]!.source_id } : null;} catch (err) {- if (isUndefinedTableError(err)) return null;+ if (isMissingSchemaObject(err, 'table', 'entity_identities')) return null;throw err;}}@@ -62,7 +62,7 @@ async function emailAliasElsewhere(engine: BrainEngine, sourceId: string, email:);return rows.length === 1 ? { slug: rows[0]!.slug, sourceId: rows[0]!.source_id } : null;} catch (err) {- if (isUndefinedTableError(err)) return null;+ if (isMissingSchemaObject(err, 'table', 'page_aliases')) return null;throw err;}}diff --git a/src/core/import-contextual-mode.ts b/src/core/import-contextual-mode.tsindex 638814744f..65be12fc92 100644--- a/src/core/import-contextual-mode.ts+++ b/src/core/import-contextual-mode.ts@@ -14,7 +14,7 @@import type { BrainEngine } from './engine.ts';import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';-import { isUndefinedTableError } from './utils.ts';+import { isMissingSchemaObject } from './utils.ts';import { computeCorpusGeneration, loadSourceRow, SourceRowNotFoundError } from './contextual-retrieval-service.ts';import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';@@ -27,7 +27,7 @@ export async function resolveImportContextualMode(engine: BrainEngine, sourceId:const row = await loadSourceRow(engine, sourceId);source = { id: row.id, contextual_retrieval_mode: row.contextual_retrieval_mode ?? null, trust_frontmatter_overrides: row.trust_frontmatter_overrides === true };} catch (error) {- if (strict || !(error instanceof SourceRowNotFoundError || isUndefinedTableError(error))) throw error;+ if (strict || !(error instanceof SourceRowNotFoundError || isMissingSchemaObject(error, 'table', 'sources'))) throw error;}const resolution = resolveContextualRetrievalMode({ pageFrontmatter: frontmatter ?? {}, source,globalMode: knobs.contextual_retrieval, killSwitchDisabled: knobs.contextual_retrieval_disabled });diff --git a/src/core/last-retrieved.ts b/src/core/last-retrieved.tsindex 2e92fcd212..b2e83f317e 100644--- a/src/core/last-retrieved.ts+++ b/src/core/last-retrieved.ts@@ -46,7 +46,7 @@*/import type { BrainEngine } from './engine.ts';-import { isUndefinedTableError } from './utils.ts';+import { isMissingSchemaObject } from './utils.ts';import { registerBackgroundWorkDrainer } from './background-work.ts';let _trackRetrievalCache: { ts: number; enabled: boolean } | null = null;@@ -212,7 +212,7 @@ export function bumpLastRetrievedAt(engine: BrainEngine, pageIds: number[]): voi} catch (err) {// Pre-v224 brain (table missing) falls through silently — the search// op already returned, the LSD signal just stays NULL until upgrade.- if (isUndefinedTableError(err)) return;+ if (isMissingSchemaObject(err, 'table', 'page_retrievals')) return;// Other errors: stderr-warn but don't break the op response.const msg = err instanceof Error ? err.message : String(err);console.warn(`[last-retrieved] write-back failed (best-effort): ${msg}`);diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.tsindex fdb8f95bac..9b59b45410 100644--- a/src/core/ops/schema-packs.ts+++ b/src/core/ops/schema-packs.ts@@ -237,12 +237,12 @@ const schema_review_orphans: Operation = {const limit = Math.max(1, Math.min(10000, (p.limit as number) ?? 100));const { loadActivePackBestEffort } = await import('../schema-pack/best-effort.ts');const { findTypeOrphans } = await import('../schema-pack/review.ts');- const { isUndefinedTableError } = await import('../utils.ts');+ const { isMissingSchemaObject } = await import('../utils.ts');const pack = await loadActivePackBestEffort(ctx);try {return { schema_version: 1, ...await findTypeOrphans(ctx.engine, pack?.manifest ?? null, sourceScopeOpts(ctx), limit) };} catch (err) {- if (isUndefinedTableError(err)) return { schema_version: 1, orphan_count: 0, orphans: [], undeclared_types: [], pack: pack?.manifest.name ?? null, truncated: false };+ if (isMissingSchemaObject(err, 'table', 'pages')) return { schema_version: 1, orphan_count: 0, orphans: [], undeclared_types: [], pack: pack?.manifest.name ?? null, truncated: false };throw err;}},diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.tsindex 768d43615d..8de4998cc5 100644--- a/src/core/page-state/rename-alias.ts+++ b/src/core/page-state/rename-alias.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';/**@@ -28,7 +28,7 @@ export async function recordRenameAlias([sourceId, oldSlug, newSlug]);});} catch (error) {- if (!isUndefinedTableError(error)) throw error;+ if (!isMissingSchemaObject(error, 'table', 'slug_aliases')) throw error;}}@@ -63,7 +63,7 @@ export async function moveSlugBindings(try {await tx.transaction(savepoint => savepoint.executeRaw(sql, [sourceId, oldSlug, newSlug]));} catch (error) {- if (!isUndefinedTableError(error)) throw error;+ if (!isMissingSchemaObject(error, 'table', ['facts', 'page_aliases'])) throw error;}}}diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex a1b0085db4..fa18a7d9cf 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';import type { ParsedPage } from '../import-file.ts';import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver } from '../link-extraction.ts';import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';@@ -19,7 +19,7 @@ async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: sAND EXISTS (SELECT 1 FROM pages c WHERE c.source_id=a.source_id AND c.slug=a.canonical_slug AND c.deleted_at IS NULL)`, [sourceId, [...new Set(targets)]]);return new Map(rows.map(row => [row.alias_slug, row.canonical_slug]));} catch (error) {- if (isUndefinedTableError(error)) return new Map();+ if (isMissingSchemaObject(error, 'table', 'slug_aliases')) return new Map();throw error;}}diff --git a/src/core/schema-pack/stats.ts b/src/core/schema-pack/stats.tsindex b10d7f2a82..eab260e146 100644--- a/src/core/schema-pack/stats.ts+++ b/src/core/schema-pack/stats.ts@@ -18,7 +18,7 @@import type { BrainEngine } from '../engine.ts';import { loadActivePackBestEffort } from './best-effort.ts';import type { OperationContext } from '../operations.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';import { storedTypeMissesPack, type TypeUsagePack } from './type-usage.ts';export interface StatsOpts {@@ -185,7 +185,7 @@ async function fetchCountRows(engine: BrainEngine, opts: StatsOpts): Promise<Raw// false "100% coverage" + a starved `schema suggest`. Surface// everything that is not a missing-table error so the real failure// is visible instead of hidden behind a fake zero.- if (isUndefinedTableError(err)) return [];+ if (isMissingSchemaObject(err, 'table', 'pages')) return [];throw err;}}@@ -227,7 +227,7 @@ async function detectDeadPrefixes(} catch (err) {// #2466: only skip on the genuine "no pages table yet" case;// rethrow any other engine error so it isn't silently masked.- if (isUndefinedTableError(err)) continue;+ if (isMissingSchemaObject(err, 'table', 'pages')) continue;throw err;}}diff --git a/src/core/skillpack/shared-brain-bridge.ts b/src/core/skillpack/shared-brain-bridge.tsindex 242afca812..6f8d7a81c0 100644--- a/src/core/skillpack/shared-brain-bridge.ts+++ b/src/core/skillpack/shared-brain-bridge.ts@@ -5,7 +5,7 @@ import type { BrainEngine } from '../engine.ts';import { configDir, type GBrainConfig } from '../config.ts';import { checkedRoot, confinedPath, sha256, privateWrite, readFileConfigState } from '../agent-install/state.ts';import { findBridgeEntry, loadBridgeState } from './bridge-state.ts';-import { isUndefinedTableError } from '../utils.ts';+import { isMissingSchemaObject } from '../utils.ts';import { createSharedSkillsAdapter, type SharedSkillsToolCaller } from '../shared-skills/adapter.ts';import { verifyLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../persistence/identity.ts';import { renderAgentLauncher } from '../agent-install/launcher.ts';@@ -95,7 +95,7 @@ export async function sharedBrainBridgePlan(options: {const [brain] = await options.engine.executeRaw<{ skill_bundles_enabled: boolean }>('SELECT skill_bundles_enabled FROM persistence_brain WHERE singleton=1');active = brain?.skill_bundles_enabled === true;} catch (error) {- if (!isUndefinedTableError(error)) unavailable = true;+ if (!isMissingSchemaObject(error, 'table', 'persistence_brain')) unavailable = true;}} else if (!active && (options.config?.database_url || options.config?.database_path || options.config?.engine === 'pglite')) unavailable = true;if (!active && !unavailable) return null;diff --git a/test/doctor-schema-error-predicates.test.ts b/test/doctor-schema-error-predicates.test.tsnew file mode 100644index 0000000000..df42b5707e--- /dev/null+++ b/test/doctor-schema-error-predicates.test.ts@@ -0,0 +1,115 @@+/**+ * Wave 18b (1.1): doctor handlers read a missing column or table as+ * "pre-migration" only when the error names the object that migration adds.+ * Before, `isUndefinedColumnError(e, col)` ignored `col` whenever a SQLSTATE+ * was present and `isUndefinedTableError(e)` also matched+ * `column "x" of relation "y" does not exist`, so each check below reported+ * ok / skipped for an UNRELATED missing column or table.+ *+ * Each check runs against a real PGLite engine whose SQL reads throw the+ * fixture error; the "named" arm proves the genuine pre-migration degrade+ * still reads ok.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { Check } from '../src/commands/doctor.ts';+import type { DoctorContext, DoctorEntry } from '../src/commands/doctor/context.ts';+import { checkLinksExtractionLag } from '../src/commands/doctor/checks/extraction-sync.ts';+import { effectiveDateEntry, factsExtractionEntry, salienceEntry } from '../src/commands/doctor/checks/knowledge-health.ts';+import { checkOauthClientScopeHealth, checkOauthConfidentialHealth, checkStaleLocks } from '../src/commands/doctor/checks/routing-federation.ts';+import { trustScanEntry } from '../src/commands/doctor/checks/trust-scan.ts';+import { trustSourcesUnclaimedEntry } from '../src/commands/doctor/checks/trust-sources-unclaimed.ts';+import { trustTiersEntry } from '../src/commands/doctor/checks/trust-tiers.ts';+import { checkCanonicalContentWrites } from '../src/commands/doctor/checks/canonical-content.ts';+import { checkSharedSkillsSources } from '../src/commands/doctor/checks/shared-skills.ts';+import { checkVolunteerChannels } from '../src/commands/doctor/checks/core-health.ts';++let real: PGLiteEngine;+beforeAll(async () => {+ real = new PGLiteEngine();+ await real.connect({});+ await real.initSchema();+}, 60_000);+afterAll(async () => { await real.disconnect(); }, 60_000);++const missingColumn = (column: string, relation = 'pages') =>+ Object.assign(new Error(`column "${column}" of relation "${relation}" does not exist`), { code: '42703' });+const missingBareColumn = (column: string) => Object.assign(new Error(`column "${column}" does not exist`), { code: '42703' });+const missingTable = (table: string) => Object.assign(new Error(`relation "${table}" does not exist`), { code: '42P01' });++/** The real engine, except every SQL read (executeRaw, the raw PGLite handle, the stale-page counter) throws `error`. */+function failingEngine(error: Error): BrainEngine {+ return new Proxy(real, {+ get(target, prop, receiver) {+ if (prop === 'executeRaw' || prop === 'countStalePagesForExtraction') return async () => { throw error; };+ if (prop === 'db') return { query: async () => { throw error; } };+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;+}++const viaEntry = (entry: DoctorEntry) => async (engine: BrainEngine): Promise<Check> => {+ const checks = await entry.run({ engine, args: [], progress: { heartbeat() {}, finish() {} } } as unknown as DoctorContext) as Check[];+ return checks[0]!;+};++type Case = { check: string; run: (engine: BrainEngine) => Promise<Check | null>; named: Error[] };+const CASES: Case[] = [+ { check: 'links_extraction_lag', run: engine => checkLinksExtractionLag(engine), named: [missingBareColumn('links_extracted_at')] },+ { check: 'facts_extraction_health', run: viaEntry(factsExtractionEntry), named: [missingTable('ingest_log'), missingBareColumn('source_id')] },+ { check: 'effective_date_health', run: viaEntry(effectiveDateEntry), named: [missingBareColumn('effective_date_source')] },+ { check: 'salience_health', run: viaEntry(salienceEntry), named: [missingBareColumn('emotional_weight'), missingTable('takes')] },+ { check: 'oauth_client_scope_health', run: checkOauthClientScopeHealth, named: [missingTable('oauth_clients'), missingBareColumn('federated_read')] },+ { check: 'oauth_confidential_client_health', run: checkOauthConfidentialHealth, named: [missingTable('oauth_clients')] },+ { check: 'stale_locks', run: engine => checkStaleLocks(engine), named: [missingTable('gbrain_cycle_locks')] },+ { check: 'trust_scan', run: viaEntry(trustScanEntry), named: [missingBareColumn('trust_tier'), missingTable('takes')] },+ { check: 'trust_sources_unclaimed', run: viaEntry(trustSourcesUnclaimedEntry), named: [missingBareColumn('trust_tier')] },+ { check: 'trust_tiers', run: viaEntry(trustTiersEntry), named: [missingBareColumn('trust_tier')] },+];++describe('doctor checks fed an unrelated missing column or table report the real error (1.1)', () => {+ for (const c of CASES) {+ test(`${c.check}: an unrelated 42703 is not ok`, async () => {+ const result = await c.run(failingEngine(missingColumn('zz_unrelated')));+ expect(result?.status).not.toBe('ok');+ expect(result?.message).toContain('zz_unrelated');+ });++ test(`${c.check}: an unrelated 42P01 is not ok`, async () => {+ const result = await c.run(failingEngine(missingTable('zz_unrelated_table')));+ expect(result?.status).not.toBe('ok');+ expect(result?.message).toContain('zz_unrelated_table');+ });++ for (const named of c.named) {+ test(`${c.check}: the named pre-migration object (${named.message}) still degrades to ok`, async () => {+ const result = await c.run(failingEngine(named));+ expect(result?.status).toBe('ok');+ });+ }+ }+});++describe('message-only swallows name their objects (1.1)', () => {+ test('canonical_content_writes: an unrelated missing column is reported, a missing persistence table is not', async () => {+ const unrelated = await checkCanonicalContentWrites(failingEngine(missingColumn('zz_unrelated')));+ expect(unrelated?.status).toBe('warn');+ expect(await checkCanonicalContentWrites(failingEngine(missingTable('persistence_brain')))).toBeNull();+ });++ test('shared_skills_sources: an unrelated missing column is reported, a pre-archived sources table is not', async () => {+ const unrelated = await checkSharedSkillsSources(failingEngine(missingColumn('zz_unrelated')));+ expect(unrelated?.status).toBe('warn');+ expect(unrelated?.message).toContain('zz_unrelated');+ expect(await checkSharedSkillsSources(failingEngine(missingBareColumn('archived')))).toBeNull();+ });++ test('volunteer_channels: only a missing context_volunteer_events table reads as a pre-v117 brain', async () => {+ const unrelated = await checkVolunteerChannels(failingEngine(missingColumn('zz_unrelated', 'context_volunteer_events')));+ expect(unrelated.message).toContain('volunteer_channels query failed');+ const absent = await checkVolunteerChannels(failingEngine(missingTable('context_volunteer_events')));+ expect(absent.message).toContain('pre-v117 brain');+ });+});diff --git a/test/fixtures/guards/check-schema-error-predicates.ts/bad-raw-code/src/core/example.ts b/test/fixtures/guards/check-schema-error-predicates.ts/bad-raw-code/src/core/example.tsnew file mode 100644index 0000000000..eb4b167300--- /dev/null+++ b/test/fixtures/guards/check-schema-error-predicates.ts/bad-raw-code/src/core/example.ts@@ -0,0 +1,3 @@+export function degraded(e: unknown): boolean {+ return (e as { code?: string }).code === '42703';+}diff --git a/test/fixtures/guards/check-schema-error-predicates.ts/bad/src/commands/doctor/checks/example.ts b/test/fixtures/guards/check-schema-error-predicates.ts/bad/src/commands/doctor/checks/example.tsnew file mode 100644index 0000000000..5008c9cf4d--- /dev/null+++ b/test/fixtures/guards/check-schema-error-predicates.ts/bad/src/commands/doctor/checks/example.ts@@ -0,0 +1,5 @@+declare function isUndefinedColumnError(error: unknown, column: string): boolean;++export function degraded(e: unknown): boolean {+ return isUndefinedColumnError(e, 'example_column');+}diff --git a/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/example.ts b/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/example.tsnew file mode 100644index 0000000000..0964255ee4--- /dev/null+++ b/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/example.ts@@ -0,0 +1,6 @@+import { isMissingSchemaObject } from './utils.ts';++// isUndefinedColumnError in a comment is not a call.+export function degraded(e: unknown): boolean {+ return isMissingSchemaObject(e, 'column', ['example_column']) || isMissingSchemaObject(e, 'table', 'example_table');+}diff --git a/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/utils.ts b/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/utils.tsnew file mode 100644index 0000000000..27158ef72e--- /dev/null+++ b/test/fixtures/guards/check-schema-error-predicates.ts/good/src/core/utils.ts@@ -0,0 +1,6 @@+export function isUndefinedColumnError(error: unknown, column: string): boolean {+ return (error as { code?: string }).code === '42703' || String(error).includes(column);+}+export function isMissingSchemaObject(_e: unknown, _kind: 'table' | 'column', _names: string | readonly string[]): boolean {+ return false;+}diff --git a/test/schema-error-write-paths.test.ts b/test/schema-error-write-paths.test.tsnew file mode 100644index 0000000000..6869920bc2--- /dev/null+++ b/test/schema-error-write-paths.test.ts@@ -0,0 +1,47 @@+/**+ * Wave 18b (1.1): write paths that skip a statement on an old schema skip it+ * only when the error names the table that schema lacks. Before,+ * `isUndefinedTableError` also matched `column "x" of relation "y" does not+ * exist` (and any other missing relation), so a rename silently dropped its+ * alias or slug-binding moves on an unrelated schema error.+ */+import { describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { moveSlugBindings, recordRenameAlias } from '../src/core/page-state/rename-alias.ts';+import { resolveSlugWithAliasDetailed } from '../src/core/engine-sql/pages.ts';++const unrelatedColumn = (relation: string) =>+ Object.assign(new Error(`column "zz_unrelated" of relation "${relation}" does not exist`), { code: '42703' });+const missingTable = (table: string) => Object.assign(new Error(`relation "${table}" does not exist`), { code: '42P01' });++/** A transaction handle whose statements throw `error` (the withdrawal-subject move, which runs outside a savepoint, succeeds). */+function tx(error: Error): Pick<BrainEngine, 'transaction' | 'executeRaw'> {+ const savepoint = { executeRaw: async () => { throw error; } } as unknown as BrainEngine;+ return {+ transaction: (async <T>(fn: (t: BrainEngine) => Promise<T>) => fn(savepoint)) as BrainEngine['transaction'],+ executeRaw: (async () => []) as BrainEngine['executeRaw'],+ };+}++describe('rename write paths rethrow an unrelated schema error (1.1)', () => {+ test('recordRenameAlias: a missing column on slug_aliases throws; a missing slug_aliases table is skipped', async () => {+ await expect(recordRenameAlias(tx(unrelatedColumn('slug_aliases')), 'default', 'old', 'new')).rejects.toThrow('zz_unrelated');+ await expect(recordRenameAlias(tx(missingTable('zz_other')), 'default', 'old', 'new')).rejects.toThrow('zz_other');+ await expect(recordRenameAlias(tx(missingTable('slug_aliases')), 'default', 'old', 'new')).resolves.toBeUndefined();+ });++ test('moveSlugBindings: a missing column on facts throws; missing facts / page_aliases tables are skipped', async () => {+ await expect(moveSlugBindings(tx(unrelatedColumn('facts')), 'default', 'old', 'new')).rejects.toThrow('zz_unrelated');+ await expect(moveSlugBindings(tx(missingTable('facts')), 'default', 'old', 'new')).resolves.toBeUndefined();+ await expect(moveSlugBindings(tx(missingTable('page_aliases')), 'default', 'old', 'new')).resolves.toBeUndefined();+ });+});++describe('alias resolution rethrows an unrelated schema error (1.1)', () => {+ const exec = (error: Error) => ({ run: async () => { throw error; } }) as unknown as Parameters<typeof resolveSlugWithAliasDetailed>[0];++ test('a missing column under slug_aliases throws; a missing slug_aliases table reads as no alias', async () => {+ await expect(resolveSlugWithAliasDetailed(exec(unrelatedColumn('pages')), 'old', 'default')).rejects.toThrow('zz_unrelated');+ await expect(resolveSlugWithAliasDetailed(exec(missingTable('slug_aliases')), 'old', 'default')).resolves.toBeNull();+ });+});diff --git a/test/scripts/check-schema-error-predicates.test.ts b/test/scripts/check-schema-error-predicates.test.tsnew file mode 100644index 0000000000..26017f2871--- /dev/null+++ b/test/scripts/check-schema-error-predicates.test.ts@@ -0,0 +1,71 @@+/**+ * Wave 18b (1.1): scripts/check-schema-error-predicates.ts fails on a call to+ * a broad schema-error predicate or a raw '42703' comparison in src/ outside+ * src/core/utils.ts, names the strict replacement and how to allowlist, and+ * passes the strict predicate and the real tree.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-schema-error-predicates.ts');+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function run(files: Record<string, string> | null) {+ let env: NodeJS.ProcessEnv = { ...process.env };+ delete env.GBRAIN_GUARD_ROOT;+ if (files) {+ const tree = mkdtempSync(join(tmpdir(), 'gbrain-schema-predicates-'));+ dirs.push(tree);+ for (const [rel, body] of Object.entries(files)) {+ mkdirSync(join(tree, rel, '..'), { recursive: true });+ writeFileSync(join(tree, rel), body);+ }+ env = { ...env, GBRAIN_GUARD_ROOT: tree };+ }+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}++describe('check-schema-error-predicates.ts', () => {+ test.each([+ ['isUndefinedColumnError', "import { isUndefinedColumnError } from '../utils.ts';\nexport const f = (e: unknown) => isUndefinedColumnError(e, 'x');\n"],+ ['isUndefinedTableError', "import { isUndefinedTableError } from '../utils.ts';\nexport const f = (e: unknown) => isUndefinedTableError(e);\n"],+ ['a dynamic-import destructure', "export async function f(e: unknown) { const { isUndefinedTableError } = await import('../utils.ts'); return isUndefinedTableError(e); }\n"],+ ['a raw === comparison', "export const f = (e: { code?: string }) => e.code === '42703';\n"],+ ['a raw !== comparison', "export const f = (e: { code?: string }) => '42703' !== e.code;\n"],+ ['a switch case', "export function f(code: string) { switch (code) { case '42703': return true; default: return false; } }\n"],+ ])('%s fails with location, the strict replacement and the allowlist recipe', (_label, body) => {+ const r = run({ 'src/core/doctor-thing/example.ts': body });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL [schema_error_predicate_broad]: src/core/doctor-thing/example.ts:');+ expect(r.out).toContain('use isMissingSchemaObject(e, "column", [names])');+ expect(r.out).toContain('to ALLOWLIST in scripts/check-schema-error-predicates.ts');+ expect(r.out).toContain('See: docs/TESTING.md#schema-error-predicate-guard');+ });++ test('the strict predicate, comments, other SQLSTATEs and utils.ts itself pass', () => {+ const r = run({+ 'src/core/utils.ts': "export function isUndefinedColumnError(e: unknown, c: string) { return (e as { code?: string }).code === '42703' || String(e).includes(c); }\n",+ 'src/core/ok.ts': [+ "import { isMissingSchemaObject } from './utils.ts';",+ '// isUndefinedColumnError(e) in a comment is not a call.',+ "export const f = (e: unknown) => isMissingSchemaObject(e, 'column', ['a', 'b']);",+ "export const g = (e: { code?: string }) => e.code === '42P01' || e.code === '42501';",+ "export const h = { codes: ['42703'] };",+ ].join('\n') + '\n',+ });+ expect(r.out).toContain('check-schema-error-predicates: ok');+ expect(r.code).toBe(0);+ });++ test('the real tree passes (every remaining broad use is allowlisted with a reason)', () => {+ const r = run(null);+ expect(r.out).toContain('check-schema-error-predicates: ok');+ expect(r.code).toBe(0);+ });+});