Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): GBRA-130 A-31 report failed open-loop rows, block the engine switch and exit 1
garrytanb9edcb2e160b
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex eb0fa0c3f9..b4f67be708 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/maintain.ts` — `gbrain maintain [--safe] [--dry-run] [--json]`: stale extraction, then one source-scoped `runCycle` per source doctor's `cycle_freshness` names. A source whose cycle throws an item-scoped error is a `blocked` action with `details.code` and `fix` (`gbrain dream --source <id>`) and later sources still cycle (ItemRun site `maintain.cycle_sources`); run-scoped errors and `item_failures_systemic` stop maintain; any blocked action sets exit 1. Tests: `test/maintain.test.ts`, `test/pathological/a41-maintain-sources.test.ts`.- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.-- `src/commands/migrate-engine.ts` — Legacy engine copier (`gbrain migrate --to pglite`, and PGLite → Postgres when `migrate.graduation` is `false`). A PGLite → Postgres move routes to `src/commands/migrate-graduation.ts` (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286: `copyPageToTarget` forwards the full page row (`page_kind`, `source_path`, effective date and its source, `import_filename`, `source_kind`/`source_uri`/`ingested_via`, `ingested_at` restored in the timestamp UPDATE), the frontmatter aliases (`setPageAliases`) and each chunk's code metadata (`carryChunkMetadata`). A page sealed on the source is queued `engine_migration`; one the source had not sealed is queued `engine_migration_source_unsealed` and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, `runMigrateEngine` runs `drainProjections` (moved to `src/core/page-state/projections.ts`; `commands/projections.ts` re-exports it) on the target for the `engine_migration` and `rebuild_failed` reasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned by `test/migrate-full-row-projections.serial.test.ts`, `test/e2e/migrate-full-row-projections-postgres.test.ts` and a D2 case in `test/e2e/migrate-engine-pglite-to-postgres.test.ts`. Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.+- `src/commands/migrate-engine.ts` — Legacy engine copier (`gbrain migrate --to pglite`, and PGLite → Postgres when `migrate.graduation` is `false`). A PGLite → Postgres move routes to `src/commands/migrate-graduation.ts` (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286: `copyPageToTarget` forwards the full page row (`page_kind`, `source_path`, effective date and its source, `import_filename`, `source_kind`/`source_uri`/`ingested_via`, `ingested_at` restored in the timestamp UPDATE), the frontmatter aliases (`setPageAliases`) and each chunk's code metadata (`carryChunkMetadata`). A page sealed on the source is queued `engine_migration`; one the source had not sealed is queued `engine_migration_source_unsealed` and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, `runMigrateEngine` runs `drainProjections` (moved to `src/core/page-state/projections.ts`; `commands/projections.ts` re-exports it) on the target for the `engine_migration` and `rebuild_failed` reasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned by `test/migrate-full-row-projections.serial.test.ts`, `test/e2e/migrate-full-row-projections-postgres.test.ts` and a D2 case in `test/e2e/migrate-engine-pglite-to-postgres.test.ts`. Open-loop and loop-suppression rows the target refuses (`copyMigrationSimpleTable`, per-row `ItemRun` site `migrate_engine.loop_rows`) are printed with their id and reason, block the config flip and set exit 1; a run-scoped failure stops the copy (`test/pathological/a31-migrate-loop-rows.serial.test.ts`). Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains; the config check reads `auto_link` in-process (file/env plane, then the database), never through a `gbrain config get` child. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md; raises `minion_jobs.max_stalled`'s default to 3 only when it is below 3, so it never lowers schema v15's 5). Fresh installs (E8): `Migration.fresh_install_noop: true` marks an orchestrator that changes nothing on a brain `gbrain init` just created; `fresh-install.ts:recordFreshInstallMigrations` (one call in each init engine path, only when init created the database) appends a `complete` ledger entry with `fresh_install: true` + `installed_version` for each, and every other migration lists as `pending_fresh_install` (`src/core/migration-ledger.ts:freshInstallVersion`/`isPendingFreshInstall`) in `apply-migrations --list [--json]`/`--dry-run`, `get_health.migrations` and doctor's `minions_migration` (an `ok`/`info` row with `gbrain apply-migrations --yes --no-autopilot-install`); stamps never count as forward progress over a real partial. Each flag is proven by `test/migrations-fresh-install-audit.serial.test.ts` (schema, row counts, config table and GBRAIN_HOME file tree unchanged by the real orchestrator on a keyless `init --pglite --no-embedding` brain); unit coverage `test/migrations-fresh-install.test.ts`. `shared-content.ts` names its read-only next step as phase `argv` (`SHARED_CONTENT_INSPECT_ARGV`), which the runner prints and the ledger keeps. #6466 opt-out: `Migration.optOut: { key }` names a brain-level DB config key (`shared-content.ts`: `shared_skills.migration.enabled`, the registry-free table `MIGRATION_OPT_OUT_KEYS` in `src/core/migration-ledger.ts`, pinned to every module's `optOut`); an explicit off value (`false`/`0`/`off`/`no`, `isMigrationDeclinedValue`) puts the migration in the plan's `declined` bucket (`opt-out.ts:readDeclinedMigrations`, read before `buildPlan`; an unreachable brain declines nothing), so the runner never calls its orchestrator, reconcile included, `--list [--json]` and `--dry-run` show it `declined` with `opt_out.key`, and an explicit `--migration <v>` refuses `migration_declined` (exit 3, `fix.next: ask_user`, `gbrain config set <key> true`, verify `--list --json`). `migrationLedgerSummary(VERSION, declined)` gives `get_health.migrations.declined` and doctor's `minions_migration` an `ok` row with `details.declined`. Tests: `test/shared-skills-migration-decline-6466.test.ts`. All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in `src/core/schema-migrations/v014-pages-updated-at-index.ts` and `v015-minion-jobs-max-stalled-default-5.ts` (one file per schema migration; `migrate.ts` is the runner). `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 7022e187f5..8c2e7fc89e 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -301,6 +301,7 @@ test/openclaw-context-engine-native.serial.test.ts global-state global-state: bitest/ops-run-onboard-scope-gate.serial.test.ts R2 R2: mock.module(../src/core/onboard/checks.ts, ../src/core/remediation/index.ts, ../src/core/onboard/render.ts) replaces modules for every file in the processtest/oversized-backfill.serial.test.ts global-state global-state: installs the process-global embedding transport seam (__setEmbedTransportForTests) and gateway config (configureGateway); swaps GBRAIN_HOME through withEnvtest/page-summary-length.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)+test/pathological/a31-migrate-loop-rows.serial.test.ts global-state global-state: runMigrateEngine sets the process-wide CLI exit verdict and writes the config under a withEnv-scoped GBRAIN_HOMEtest/pending-write-exit.serial.test.ts global-state global-state: binds local servers/portstest/persistence-drain-latency.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console; times event-loop gaps against a bound, so a parallel neighbour would distort the measurementtest/persistence-image-import.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the processdiff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex 7a3ab3a612..24ed92a787 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -9,6 +9,7 @@ import { assertLegacyEngineMigration, assertUnmanagedCanonicalWriter } from '../*/import { opError } from '../core/ops/contract.ts';+import { ItemRun } from '../core/item-failure.ts';import { createEngine } from '../core/engine-factory.ts';import { loadConfig, saveConfig, toEngineConfig, gbrainPath, effectiveEnvDatabaseUrl, type GBrainConfig } from '../core/config.ts';import type { BrainEngine } from '../core/engine.ts';@@ -247,7 +248,8 @@ async function factsColumns(engine: BrainEngine): Promise<string[]> {*/export interface MigrateSimpleTableResult {copied: number;- failed: number;+ /** Rows the target refused, with the classified code and the database's reason; any of them blocks the engine switch. */+ failed: Array<{ id: string; code: string; reason: string }>;table_missing: boolean;}@@ -270,9 +272,9 @@ export async function copyMigrationSimpleTable(}};const sourceCols = await colsOf(source);- if (sourceCols.length === 0) return { copied: 0, failed: 0, table_missing: true };+ if (sourceCols.length === 0) return { copied: 0, failed: [], table_missing: true };const targetColSet = new Set(await colsOf(target));- if (targetColSet.size === 0) return { copied: 0, failed: 0, table_missing: true };+ if (targetColSet.size === 0) return { copied: 0, failed: [], table_missing: true };const cols = sourceCols.filter((c) => targetColSet.has(c));const rows = await source.executeRaw<Record<string, unknown>>(@@ -281,14 +283,19 @@ export async function copyMigrationSimpleTable(await target.executeRaw(`DELETE FROM ${table}`);const insertSql = `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(', ')})VALUES (${cols.map((c, i) => (c === 'evidence' ? `$${i + 1}::text::jsonb` : `$${i + 1}`)).join(', ')})`;- const result: MigrateSimpleTableResult = { copied: 0, failed: 0, table_missing: false };+ const result: MigrateSimpleTableResult = { copied: 0, failed: [], table_missing: false };+ // GBRA-130 A-31: a refused row is recorded with its reason (it blocks the switch); a run-scoped failure (lost+ // connection, failed transaction) or a systemic run (most rows refused) stops the copy instead.+ const run = new ItemRun('migrate_engine.loop_rows');for (const raw of rows) {const row = nullifyUndefinedColumns(raw);try {await target.executeRaw(insertSql, cols.map((c) => row[c]));result.copied++;- } catch {- result.failed++;+ run.succeed();+ } catch (error) {+ const failure = run.fail(`${table}:${String(row.id)}`, error);+ result.failed.push({ id: String(row.id), code: failure.code, reason: failure.message });}onRow?.();}@@ -888,6 +895,19 @@ export async function assertWindowsGraduationPlatform(sourceEngine: BrainEngine,}}+/** GBRA-130 A-31: prints the open-loop rows the target refused (each blocks the engine switch), sets the exit verdict, and returns how many. */+function reportLoopRowFailures(tables: Record<string, MigrateSimpleTableResult>, opts: Pick<MigrateOpts, 'targetEngine' | 'targetPath' | 'targetUrl'>): number {+ const failures = Object.entries(tables).flatMap(([table, r]) => r.failed.map(f => ({ table, ...f })));+ if (failures.length === 0) return 0;+ console.error(`\n${failures.length} open-loop row(s) FAILED to copy:`);+ for (const f of failures.slice(0, 20)) console.error(` - ${f.table} id ${f.id} (${f.code}): ${f.reason}`);+ if (failures.length > 20) console.error(` ... and ${failures.length - 20} more`);+ const retry = ['gbrain', 'migrate', '--to', opts.targetEngine, ...(opts.targetPath ? ['--path', opts.targetPath] : []), ...(opts.targetUrl ? ['--url', '<the same connection string>'] : [])];+ console.error(`The active engine was NOT switched. Fix the cause each reason names on the target, then re-run: ${retry.join(' ')}`);+ setCliExitVerdict(1);+ return failures.length;+}+export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]): Promise<void> {const opts = parseArgs(args);await assertWindowsGraduationPlatform(sourceEngine, opts);@@ -1068,8 +1088,9 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]const rowCounts: PageCopyCounts = { chunks: 0, tags: 0, timeline_entries: 0, raw_data: 0 };let linksCopied = 0;let factsResult: MigrateFactsResult = { copied: 0, failed: [], embeddings_dropped: 0, table_missing: false };- let openLoopsResult: MigrateSimpleTableResult = { copied: 0, failed: 0, table_missing: true };- let loopSuppressionsResult: MigrateSimpleTableResult = { copied: 0, failed: 0, table_missing: true };+ let openLoopsResult: MigrateSimpleTableResult = { copied: 0, failed: [], table_missing: true };+ let loopSuppressionsResult: MigrateSimpleTableResult = { copied: 0, failed: [], table_missing: true };+ let loopRowsFailed = 0;let configResult: { copied: number; skipped: string[] } = { copied: 0, skipped: [] };try {sourcesCopied = await copyMigrationSources(sourceEngine, targetEngine);@@ -1134,6 +1155,7 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]openLoopsResult = await copyMigrationSimpleTable(sourceEngine, targetEngine, 'open_loops', () => progress.tick(1));loopSuppressionsResult = await copyMigrationSimpleTable(sourceEngine, targetEngine, 'loop_suppressions', () => progress.tick(1));progress.finish();+ loopRowsFailed = reportLoopRowFailures({ open_loops: openLoopsResult, loop_suppressions: loopSuppressionsResult }, opts);if (factsResult.failed.length > 0) {console.error(`\n${factsResult.failed.length} fact row(s) FAILED to copy:`);for (const f of factsResult.failed.slice(0, 10)) {@@ -1176,7 +1198,7 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]// calls), before the flip and while autopilot is paused, so the new active brain starts sealed and its first sync// does not replace chunks. A page whose rebuild fails blocks the flip like a page that failed to copy.let projectionsFailed = 0;- if (failures.length === 0 && factsResult.failed.length === 0) {+ if (failures.length === 0 && factsResult.failed.length === 0 && loopRowsFailed === 0) {console.log('Rebuilding text projections on the target...');const drained = await drainProjections(targetEngine, { reasons: MIGRATION_PROJECTION_REASONS });projectionsFailed = drained.failed.length;@@ -1187,7 +1209,7 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]setCliExitVerdict(1);}}- if (failures.length === 0 && factsResult.failed.length === 0 && projectionsFailed === 0) {+ if (failures.length === 0 && factsResult.failed.length === 0 && loopRowsFailed === 0 && projectionsFailed === 0) {const existingFile = (await import('../core/config.ts')).loadConfigFileOnly() ?? ({} as GBrainConfig);const newConfig: GBrainConfig = {...existingFile,@@ -1239,18 +1261,19 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]const loopsRow = (label: string, r: MigrateSimpleTableResult) =>summaryRow(label, r.table_missing? '0 (source schema predates the open-loop tables)'- : r.failed > 0 ? `${r.copied} (${r.failed} FAILED)` : String(r.copied));+ : r.failed.length > 0 ? `${r.copied} (${r.failed.length} FAILED)` : String(r.copied));loopsRow('open loops', openLoopsResult);loopsRow('loop suppressions', loopSuppressionsResult);summaryRow('config rows', configResult.skipped.length > 0? `${configResult.copied} (skipped engine-local: ${configResult.skipped.join(', ')})`: String(configResult.copied));- const cleanRun = failures.length === 0 && factsResult.failed.length === 0;+ const cleanRun = failures.length === 0 && factsResult.failed.length === 0 && loopRowsFailed === 0;if (!cleanRun) {const parts = [failures.length > 0 ? `${migrated} of ${pagesToMigrate.length} pages copied, ${failures.length} failed (${completedSet.size} already done from a prior run)` : '',factsResult.failed.length > 0 ? `${factsResult.failed.length} fact row(s) failed` : '',+ loopRowsFailed > 0 ? `${loopRowsFailed} open-loop row(s) failed` : '',].filter(Boolean).join('; ');console.log(`\nMigration completed with errors. ${parts}. See failure list above.`);console.log(`Config NOT switched — still using engine: ${config.engine}. Re-run \`gbrain migrate --to ${opts.targetEngine}\` to retry; already-copied pages resume via the manifest.`);diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex d5cff083c8..38b4bea11f 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -43,6 +43,7 @@ export const ISOLATE_SITES = {'repair.all_kinds': 'A-45','repair.content_lane_kinds': 'A-46','migration.credential_reseal': 'A-27',+ 'migrate_engine.loop_rows': 'A-31',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/test/pathological/a31-migrate-loop-rows.serial.test.ts b/test/pathological/a31-migrate-loop-rows.serial.test.tsnew file mode 100644index 0000000000..e927c6c4b0--- /dev/null+++ b/test/pathological/a31-migrate-loop-rows.serial.test.ts@@ -0,0 +1,161 @@+/**+ * A-31 (GBRA-130): `gbrain migrate --to …` never switches the active engine+ * over open-loop rows the target refused.+ *+ * Protects: an open_loops/loop_suppressions row whose insert the target+ * refuses (type or constraint drift) is recorded with its id, typed code and+ * the database's reason, printed, and blocks the engine switch with exit 1+ * while every other row, fact and page still copies; after the cause clears a+ * re-run copies the row and switches. A run where most rows fail is systemic+ * (item_failures_systemic) and a run-scoped failure (a lost connection, a+ * failed transaction) stops the copy instead of being counted as a refused row.+ * Fails when: the per-row catch counts the failure and discards it, or the+ * cutover gate and the clean-run verdict ignore the loop tables (the config+ * switches and the rows are gone on the active brain).+ * Seams: none in production; the run case wraps the target engine in a Proxy.+ * Serial: runMigrateEngine reads and writes the process-wide config under+ * GBRAIN_HOME and the CLI exit verdict. PGLite source; PGLite target always,+ * Postgres target when DATABASE_URL is set.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { copyMigrationSimpleTable, runMigrateEngine } from '../../src/commands/migrate-engine.ts';+import { loadConfigFileOnly, saveConfig } from '../../src/core/config.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const LOOP_SUMMARIES = ['reply to alice-example', 'send deck to acme-example', 'poison', 'follow up on contract', 'book the review', 'renew the domain'];++async function seedSource(): Promise<PGLiteEngine> {+ const source = new PGLiteEngine();+ await source.connect({});+ await source.initSchema();+ for (const slug of ['notes/one', 'notes/two']) await source.putPage(slug, { type: 'note', title: slug, compiled_truth: `body of ${slug}`, timeline: '', frontmatter: {} });+ for (const [i, summary] of LOOP_SUMMARIES.entries()) {+ await source.executeRaw(`INSERT INTO open_loops (source_id, dedup_key, loop_type, summary, detector) VALUES ('default', $1, 'commitment_owed_by_me', $2, 'manual')`, [`k${i}`, summary]);+ }+ await source.executeRaw(`INSERT INTO loop_suppressions (source_id, kind, value) VALUES ('default', 'sender', '[email protected]')`);+ return source;+}++interface Target { args: string[]; open: () => Promise<BrainEngine>; configEngine: 'pglite' | 'postgres'; close: () => Promise<void> }++/** The migration target, prepared with `prepare` (a constraint) before the migration connects to it. */+async function makeTarget(databaseUrl: string | undefined, dir: string, prepare: (engine: BrainEngine) => Promise<void>): Promise<Target> {+ if (databaseUrl) {+ const isolated = await isolatedPersistencePostgres(databaseUrl);+ await prepare(isolated.engine);+ await isolated.engine.disconnect();+ return { args: ['--to', 'postgres', '--url', isolated.databaseUrl], configEngine: 'postgres', close: isolated.close,+ open: async () => { const e = new PostgresEngine(); await e.connect({ database_url: isolated.databaseUrl, poolSize: 2 }); return e; } };+ }+ const path = join(dir, 'target.pglite');+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: path });+ await engine.initSchema();+ await prepare(engine);+ await engine.disconnect();+ return { args: ['--to', 'pglite', '--path', path], configEngine: 'pglite', close: async () => {},+ open: async () => { const e = new PGLiteEngine(); await e.connect({ database_path: path }); return e; } };+}++async function migrate(source: BrainEngine, target: Target): Promise<{ out: string; err: string }> {+ const out: string[] = [];+ const err: string[] = [];+ const [log, error, warn] = [console.log, console.error, console.warn];+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };+ console.error = (...a: unknown[]) => { err.push(a.join(' ')); };+ console.warn = () => {};+ try { await runMigrateEngine(source, target.args); } finally { console.log = log; console.error = error; console.warn = warn; }+ return { out: out.join('\n'), err: err.join('\n') };+}++const loopRows = async (engine: BrainEngine) => (await engine.executeRaw<{ id: string | number; summary: string }>('SELECT id, summary FROM open_loops ORDER BY id'))+ .map(r => ({ id: Number(r.id), summary: r.summary }));++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-31 migrate open-loop rows (${backend} target)`, () => {+ afterEach(() => _resetCliExitVerdictForTests());++ async function scenario(prepare: (engine: BrainEngine) => Promise<void>, run: (ctx: { source: PGLiteEngine; target: Target; dir: string }) => Promise<void>) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-a31-'));+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const source = await seedSource();+ const target = await makeTarget(databaseUrl, dir, prepare);+ saveConfig(target.configEngine === 'pglite' ? { engine: 'postgres', database_url: 'postgresql://unused/guard-only' } : { engine: 'pglite', database_path: join(dir, 'source.pglite') });+ try { await run({ source, target, dir }); } finally { await source.disconnect(); await target.close(); }+ });+ rmSync(dir, { recursive: true, force: true });+ }++ test('A-31 item: a refused open_loops row is printed with its id and code and blocks the switch; the rest copies; a re-run after the fix switches', async () => {+ await scenario(e => e.executeRaw("ALTER TABLE open_loops ADD CONSTRAINT patho_no_poison CHECK (summary <> 'poison')").then(() => undefined), async ({ source, target }) => {+ const poison = (await loopRows(source)).find(r => r.summary === 'poison')!;+ const before = await snapshotItems(source, 'default');+ const { err } = await expectUnitNotAborted(() => migrate(source, target));+ expect(currentExitCode()).toBe(1);+ expect(loadConfigFileOnly()?.engine).not.toBe(target.configEngine);+ const line = err.split('\n').find(l => l.startsWith(' - open_loops id '));+ const parsed = /^ {2}- (open_loops) id (\d+) \((\w+)\): (.+)$/.exec(line ?? '');+ expect(parsed).not.toBeNull();+ const fix = /then re-run: (gbrain migrate .+)$/m.exec(err)?.[1];+ expectItemFailure({ key: `${parsed![1]}:${parsed![2]}`, code: parsed![3], fix }, { key: `open_loops:${poison.id}`, code: 'invalid_data', fix: new RegExp(`^gbrain migrate --to ${target.configEngine}`) });+ expect(parsed![4]).toContain('patho_no_poison');+ expectOthersUnchanged(before, await snapshotItems(source, 'default'));+ const copied = await target.open();+ try {+ expect((await loopRows(copied)).map(r => r.summary)).toEqual(LOOP_SUMMARIES.filter(s => s !== 'poison'));+ expect(await copied.executeRaw('SELECT count(*)::int AS n FROM loop_suppressions')).toEqual([{ n: 1 }]);+ expect((await copied.executeRaw<{ slug: string }>('SELECT slug FROM pages ORDER BY slug')).map(r => r.slug)).toEqual(['notes/one', 'notes/two']);+ await copied.executeRaw('ALTER TABLE open_loops DROP CONSTRAINT patho_no_poison');+ } finally { await copied.disconnect(); }++ _resetCliExitVerdictForTests();+ await expectUnitNotAborted(() => migrate(source, target));+ expect(currentExitCode()).toBe(0);+ expect(loadConfigFileOnly()?.engine).toBe(target.configEngine);+ const after = await target.open();+ try { expect((await loopRows(after)).map(r => r.summary)).toEqual(LOOP_SUMMARIES); } finally { await after.disconnect(); }+ });+ }, 180_000);++ test('A-31 breaker: when most rows are refused the copy stops item_failures_systemic and the engine is not switched', async () => {+ await scenario(e => e.executeRaw("ALTER TABLE open_loops ADD CONSTRAINT patho_none CHECK (summary = 'never')").then(() => undefined), async ({ source, target }) => {+ let thrown: unknown;+ try { await migrate(source, target); } catch (error) { thrown = error; }+ expect(thrown).toBeInstanceOf(OperationError);+ expect((thrown as OperationError).code).toBe('item_failures_systemic');+ expect(loadConfigFileOnly()?.engine).not.toBe(target.configEngine);+ });+ }, 180_000);++ for (const injected of runScopedErrors().filter(e => e.name === 'connection lost' || e.name === 'failed transaction (25P02)')) {+ test(`A-31 run: a run-scoped error (${injected.name}) inserting a row stops the copy and records no refused row`, async () => {+ await scenario(async () => {}, async ({ source, target }) => {+ const real = await target.open();+ try {+ const error = injected.error();+ let inserts = 0;+ const failing = new Proxy(real, { get(t, prop) {+ const value = Reflect.get(t, prop, t);+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => sql.startsWith('INSERT INTO open_loops') && ++inserts === 3 ? Promise.reject(error) : (value as Function).call(t, sql, params);+ return typeof value === 'function' ? value.bind(t) : value;+ } }) as BrainEngine;+ let thrown: unknown;+ try { await copyMigrationSimpleTable(source, failing, 'open_loops'); } catch (e) { thrown = e; }+ expect(thrown).toBe(error);+ expect(inserts).toBe(3);+ } finally { await real.disconnect(); }+ });+ }, 180_000);+ }+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 57423125e6..f374cd4b0e 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -63,4 +63,6 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {'repair.all_kinds': { file: 'test/pathological/a45-repair-all-kinds.test.ts', item: 'item case: a kind whose plan throws', run: 'run case: a run-scoped' },'repair.content_lane_kinds': { file: 'test/pathological/a46-content-lane-kinds.test.ts', item: 'item case: fences throwing is recorded', run: 'run case: a run-scoped' },'migration.credential_reseal': { file: 'test/pathological/a27-credential-reseal.test.ts', item: 'item case: the unbuildable page is held', run: 'run case: a run-scoped' },+ 'migrate_engine.loop_rows': { file: 'test/pathological/a31-migrate-loop-rows.serial.test.ts',+ item: 'A-31 item: a refused open_loops row is printed with its id and code and blocks the switch', run: 'A-31 run: a run-scoped error' },};