Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): legacy copier forwards the full page row and seals projections before the flip (#6286)
time-attack0a7b5316e3b9
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 0573208a6d..10858e2c82 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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. 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`. 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. 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 223dc235ce..a44d9c1f4f 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -247,6 +247,7 @@ test/migrate-embeddings-recovery-cli.serial.test.ts global-state global-state: Rtest/migrate-engine-completeness.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)test/migrate-engine-page-copy-failure.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)test/migrate-engine-pagination.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)+test/migrate-full-row-projections.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL) through withEnv; writes config.json (saveConfig)test/migrate-graduation-cli.serial.test.ts global-state global-state: withEnv holds GBRAIN_HOME at a temp dir (withEnv) across awaited runMigrateGraduation calls that read the file-plane opt-outtest/migrate-quiet-replay.serial.test.ts R1 R1: mutates process.env (GBRAIN_MIGRATE_VERBOSE, GBRAIN_PGLITE_SNAPSHOT)test/migration-in-process.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnectdiff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex e828598b37..8776a290b1 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -12,7 +12,7 @@ import { opError } from '../core/ops/contract.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';-import type { EngineConfig, Page } from '../core/types.ts';+import type { EffectiveDateSource, EngineConfig, Page, PageKind } from '../core/types.ts';import { writeFileSync, readFileSync, existsSync, unlinkSync, statSync, mkdirSync, renameSync } from 'fs';import { createHash } from 'crypto';import { resolve, dirname } from 'path';@@ -26,7 +26,9 @@ import { registerCleanup } from '../core/process-cleanup.ts';import { autopilotPausedMarkerPath, autopilotLockPath, markerHolderAlive, MIGRATE_PAUSE_MARKER_PREFIX } from '../core/autopilot-paths.ts';export { MIGRATE_PAUSE_MARKER_PREFIX };import { listLiveLocks } from '../core/db-lock.ts';-import { queuePageProjection } from '../core/page-state/projections.ts';+import { drainProjections, queuePageProjection } from '../core/page-state/projections.ts';+import { carryChunkMetadata } from '../core/embed-stale.ts';+import { normalizeAliasList } from '../core/search/alias-normalize.ts';interface MigrateOpts {targetEngine: 'postgres' | 'pglite';@@ -484,6 +486,9 @@ export interface PageCopyCounts {raw_data: number;}+/** Queue reasons the migration rebuilds before its flip: pages it copied sealed, and earlier attempts that failed. */+const MIGRATION_PROJECTION_REASONS = ['engine_migration', 'rebuild_failed'] as const;+export async function copyPageToTarget(source: BrainEngine,target: BrainEngine,@@ -496,6 +501,13 @@ export async function copyPageToTarget(// Verbatim copy — the source engine's row is authoritative, so a// legitimately blank body (image page, deliberate clear) must land even// when a re-run's target row already holds an older non-empty body.+ // #6286: the full row travels: origin, kind and provenance columns `Page` does not carry are read from the source row.+ const [row] = await source.executeRaw<{ page_kind: PageKind | null; source_path: string | null; effective_date: Date | string | null; effective_date_source: EffectiveDateSource | null;+ import_filename: string | null; source_kind: string | null; source_uri: string | null; ingested_via: string | null; ingested_at: Date | string | null; sealed: boolean }>(+ `SELECT page_kind,source_path,effective_date,effective_date_source,import_filename,source_kind,source_uri,ingested_via,ingested_at,+ text_projection_revision IS NOT DISTINCT FROM knowledge_revision AS sealed+ FROM pages WHERE slug=$1 AND source_id=$2`, [page.slug, page.source_id ?? 'default']);+ const asDate = (value: Date | string | null | undefined) => value == null ? null : value instanceof Date ? value : new Date(value);await target.putPage(page.slug, nullifyUndefinedColumns({type: page.type,title: page.title,@@ -503,7 +515,10 @@ export async function copyPageToTarget(timeline: page.timeline,frontmatter: page.frontmatter,content_hash: page.content_hash,+ ...(row ? { page_kind: row.page_kind ?? undefined, source_path: row.source_path, effective_date: asDate(row.effective_date), effective_date_source: row.effective_date_source,+ import_filename: row.import_filename, source_kind: row.source_kind, source_uri: row.source_uri, ingested_via: row.ingested_via } : {}),}), { ...sourceOpts, allowEmptyOverwrite: true });+ await target.setPageAliases(page.slug, page.source_id ?? 'default', normalizeAliasList(page.frontmatter?.aliases));// #4527: putPage stamps created_at/updated_at with now() (PageInput has no// timestamp fields), so without this every migrated page loses its@@ -512,13 +527,14 @@ export async function copyPageToTarget(// timestamps directly; COALESCE keeps the putPage-stamped value if the// source engine ever hands back a NULL (never expected, but a copy must// not null out a NOT NULL column).- if (page.created_at != null || page.updated_at != null) {+ if (page.created_at != null || page.updated_at != null || row?.ingested_at != null) {await target.executeRaw(`UPDATE pagesSET created_at = COALESCE($1, created_at),- updated_at = COALESCE($2, updated_at)+ updated_at = COALESCE($2, updated_at),+ ingested_at = COALESCE($5::timestamptz, ingested_at)WHERE slug = $3 AND source_id = $4`,- [page.created_at ?? null, page.updated_at ?? null, page.slug, page.source_id ?? 'default'],+ [page.created_at ?? null, page.updated_at ?? null, page.slug, page.source_id ?? 'default', asDate(row?.ingested_at)],);}@@ -526,7 +542,7 @@ export async function copyPageToTarget(// projection. The target rebuilds sanitized text under its new revision.const chunks = await source.getChunksWithEmbeddings(page.slug, { ...sourceOpts, includeUnsealed: true });if (chunks.length > 0) {- await target.upsertChunks(page.slug, chunks.map(c => ({+ await target.upsertChunks(page.slug, chunks.map(c => carryChunkMetadata(c, {chunk_index: c.chunk_index,chunk_text: c.chunk_text,chunk_source: c.chunk_source,@@ -563,7 +579,9 @@ export async function copyPageToTarget(await target.putRawData(page.slug, rd.source, rd.data, sourceOpts);}- await queuePageProjection(target, page.source_id ?? 'default', page.slug, 'engine_migration');+ // #6286: a page sealed on the source is rebuilt on the target before the flip (MIGRATION_PROJECTION_REASONS); one+ // the source itself had not sealed stays queued as it was, so the copy keeps its verbatim chunks and vectors.+ await queuePageProjection(target, page.source_id ?? 'default', page.slug, row?.sealed === false ? 'engine_migration_source_unsealed' : 'engine_migration');return {chunks: chunks.length,@@ -1153,7 +1171,22 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]// finished. Leaving the file-plane config untouched keeps the source the// active engine, so a retry (which resumes via the still-intact manifest)// is a same-shaped command, not a special case.+ // #6286: every copied page was queued for a projection rebuild; rebuild them on the target now (keyless, no provider+ // 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) {+ console.log('Rebuilding text projections on the target...');+ const drained = await drainProjections(targetEngine, { reasons: MIGRATION_PROJECTION_REASONS });+ projectionsFailed = drained.failed.length;+ console.log(`Projections: ${drained.rebuilt} rebuilt, ${drained.superseded} superseded, ${drained.failed.length} failed, ${drained.remaining} still queued.`);+ if (projectionsFailed) {+ for (const f of drained.failed.slice(0, 10)) console.error(` - ${f.source_id}/${f.slug}: ${f.reason}`);+ console.error('The active engine was NOT switched: the target has pages whose text projection did not rebuild. Fix them (`gbrain projections drain` on the target names each next step), then re-run `gbrain migrate` to resume.');+ setCliExitVerdict(1);+ }+ }+ if (failures.length === 0 && factsResult.failed.length === 0 && projectionsFailed === 0) {const existingFile = (await import('../core/config.ts')).loadConfigFileOnly() ?? ({} as GBrainConfig);const newConfig: GBrainConfig = {...existingFile,diff --git a/src/commands/projections.ts b/src/commands/projections.tsindex e3674cdf8c..359147b8af 100644--- a/src/commands/projections.ts+++ b/src/commands/projections.ts@@ -14,15 +14,14 @@ import type { OperationError } from '../core/ops/contract.ts';import { catalogueError } from '../core/error-catalogue.ts';import type { LockHolderInfo } from '../core/pglite-lock.ts';import type { ProgressReporter } from '../core/progress.ts';-import {- projectionBacklog, rebuildPendingPageProjections, type ProjectionRebuildFailure,-} from '../core/page-state/projections.ts';+import { type ProjectionRebuildFailure } from '../core/page-state/projections.ts';+// #6286: the drain lives in core so `migrate` can run it on its target before the config flip.+export { drainProjections, type ProjectionDrainResult } from '../core/page-state/projections.ts';import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';import { resolveAutopilotJob } from '../core/autopilot-paths.ts';import { detectInstalledJob } from './autopilot/jobs.ts';export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';-const BATCH = 100;export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--limit <n>] [--json]@@ -40,46 +39,6 @@ On Postgres the drain is safe while \`gbrain serve\` runs. Progress goes to stdeDocs: ${PROJECTION_DRAIN_DOCS}`;-export interface ProjectionDrainResult {- rebuilt: number;- superseded: number;- failed: ProjectionRebuildFailure[];- remaining: number;- limited: boolean;-}--export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter } = {}): Promise<ProjectionDrainResult> {- const [{ runStart }] = await engine.executeRaw<{ runStart: string }>('SELECT now()::text AS "runStart"');- // PGLite's clock can be coarse: wait until it passes the run start, so a page- // that fails in this run is stamped after it and is not tried again.- while (!(await engine.executeRaw<{ passed: boolean }>('SELECT now()>$1::text::timestamptz AS passed', [runStart]))[0]?.passed) {- await new Promise(resolve => setTimeout(resolve, 1));- }- const total = (await projectionBacklog(engine)).pending;- opts.progress?.start('projections.drain', opts.limit === undefined ? total : Math.min(total, opts.limit));- const failed: ProjectionRebuildFailure[] = [];- let rebuilt = 0;- let superseded = 0;- let tried = 0;- try {- while (opts.limit === undefined || tried < opts.limit) {- const failuresBefore = failed.length;- const batch = await rebuildPendingPageProjections(engine, Math.min(BATCH, (opts.limit ?? Infinity) - tried),- { notAfter: runStart, onFailure: failure => failed.push(failure) });- const attempted = batch.rebuilt + batch.superseded + failed.length - failuresBefore;- if (attempted === 0) break;- rebuilt += batch.rebuilt;- superseded += batch.superseded;- tried += attempted;- opts.progress?.tick(attempted, `${rebuilt} rebuilt, ${failed.length} failed`);- }- } finally {- opts.progress?.finish();- }- const remaining = (await projectionBacklog(engine)).pending;- return { rebuilt, superseded, failed, remaining, limited: opts.limit !== undefined && tried >= opts.limit && remaining > 0 };-}-/** The next step for one failed page, from the preparation error it reported. */export function projectionFailureNextAction(failure: ProjectionRebuildFailure): string {if (failure.reason.startsWith('Code projection requires a recorded source path')) {diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 2434b84852..26dfa6bc7b 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../engine.ts';+import type { ProgressReporter } from '../progress.ts';import type { Chunk, ChunkInput, ResolvedColumn, PageKind } from '../types.ts';import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';import { CHUNKER_VERSION } from '../chunkers/code.ts';@@ -369,6 +370,8 @@ export interface ProjectionRebuildOptions {notAfter?: string;/** Skip failed rows inside their retry window (PROJECTION_RETRY_READY_SQL). */retryCooldown?: boolean;+ /** Only rows whose queue reason is one of these. */+ reasons?: readonly string[];/** Only these pages of one source. */pages?: { sourceId: string; slugs: readonly string[] };/** Receives each failed page; without it a generic stderr line is printed. */@@ -393,6 +396,7 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =const filters: string[] = [];if (opts.retryCooldown) filters.push(PROJECTION_RETRY_READY_SQL);if (opts.notAfter !== undefined) { params.push(opts.notAfter); filters.push(`j.updated_at<=$${params.length}::text::timestamptz`); }+ if (opts.reasons) { params.push(opts.reasons); filters.push(`j.reason=ANY($${params.length}::text[])`); }if (opts.pages) { params.push(opts.pages.slugs); filters.push(`j.slug=ANY($${params.length}::text[])`); }const sourceFilter = opts.pages ? `WHERE s.id=$${params.push(opts.pages.sourceId)}` : '';const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind@@ -444,3 +448,47 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =}return { rebuilt, superseded };}++/** #6286: queued projections are rebuilt in batches of this many pages. */+const DRAIN_BATCH = 100;++export interface ProjectionDrainResult {+ rebuilt: number;+ superseded: number;+ failed: ProjectionRebuildFailure[];+ remaining: number;+ limited: boolean;+}++export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter; reasons?: readonly string[] } = {}): Promise<ProjectionDrainResult> {+ const [{ runStart }] = await engine.executeRaw<{ runStart: string }>('SELECT now()::text AS "runStart"');+ // PGLite's clock can be coarse: wait until it passes the run start, so a page+ // that fails in this run is stamped after it and is not tried again.+ while (!(await engine.executeRaw<{ passed: boolean }>('SELECT now()>$1::text::timestamptz AS passed', [runStart]))[0]?.passed) {+ await new Promise(resolve => setTimeout(resolve, 1));+ }+ const total = (await projectionBacklog(engine)).pending;+ opts.progress?.start('projections.drain', opts.limit === undefined ? total : Math.min(total, opts.limit));+ const failed: ProjectionRebuildFailure[] = [];+ let rebuilt = 0;+ let superseded = 0;+ let tried = 0;+ try {+ while (opts.limit === undefined || tried < opts.limit) {+ const failuresBefore = failed.length;+ const batch = await rebuildPendingPageProjections(engine, Math.min(DRAIN_BATCH, (opts.limit ?? Infinity) - tried),+ { notAfter: runStart, reasons: opts.reasons, onFailure: failure => failed.push(failure) });+ const attempted = batch.rebuilt + batch.superseded + failed.length - failuresBefore;+ if (attempted === 0) break;+ rebuilt += batch.rebuilt;+ superseded += batch.superseded;+ tried += attempted;+ opts.progress?.tick(attempted, `${rebuilt} rebuilt, ${failed.length} failed`);+ }+ } finally {+ opts.progress?.finish();+ }+ const remaining = (await projectionBacklog(engine)).pending;+ return { rebuilt, superseded, failed, remaining, limited: opts.limit !== undefined && tried >= opts.limit && remaining > 0 };+}+diff --git a/test/e2e/migrate-engine-pglite-to-postgres.test.ts b/test/e2e/migrate-engine-pglite-to-postgres.test.tsindex 5bf9ae5c3d..9857f5d01e 100644--- a/test/e2e/migrate-engine-pglite-to-postgres.test.ts+++ b/test/e2e/migrate-engine-pglite-to-postgres.test.ts@@ -378,6 +378,13 @@ describePg('migrate-engine whole-brain PGLite to Postgres (D2)', () => {expect(fresh.id).toBeGreaterThan(factMaxId);});+ test('pages the source had not sealed arrive queued with their verbatim chunks, and do not block the flip (#6286)', async () => {+ const target = getEngine();+ const jobs = await target.executeRaw<{ reason: string; n: number | string }>(+ 'SELECT reason, count(*)::int AS n FROM page_projection_jobs GROUP BY reason ORDER BY reason');+ expect(jobs.map(j => [j.reason, Number(j.n)])).toEqual([['engine_migration_source_unsealed', seeded.pages]]);+ });+test('DB-plane config rows migrated; engine-local keys did not', async () => {const target = getEngine();const get = async (key: string): Promise<string | null> => {diff --git a/test/e2e/migrate-full-row-projections-postgres.test.ts b/test/e2e/migrate-full-row-projections-postgres.test.tsnew file mode 100644index 0000000000..aaf76a0730--- /dev/null+++ b/test/e2e/migrate-full-row-projections-postgres.test.ts@@ -0,0 +1,55 @@+/**+ * #6286 (P2.12, R9), Postgres arm: a sealed PGLite page copied by the legacy migrate copier reaches Postgres with its+ * origin, kind, provenance, ingested_at and aliases, and the migration's projection drain seals it there without+ * replacing its chunks, so an identical re-import skips. Synthetic content.+ */+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 { copyPageToTarget } from '../../src/commands/migrate-engine.ts';+import { drainProjections } from '../../src/core/page-state/projections.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const describePg = hasDatabase() ? describe : describe.skip;+const DB_URL = process.env.DATABASE_URL ?? '';+const body = '---\ntitle: Full Row\naliases: [Example Alias, EA]\n---\n\nA synthetic note about a full row.\n';+const rowOf = async (e: BrainEngine) => (await e.executeRaw<Record<string, unknown>>(+ `SELECT page_kind,source_path,effective_date_source,import_filename,source_kind,source_uri,ingested_via,ingested_at,+ (text_projection_revision IS NOT DISTINCT FROM knowledge_revision) AS sealed FROM pages WHERE slug='notes/full-row' AND source_id='default'`))[0]!;+const chunkIds = async (e: BrainEngine) => (await e.executeRaw<{ id: number }>(+ "SELECT id FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE slug='notes/full-row') ORDER BY id")).map(r => Number(r.id));++describePg('legacy migrate copier, PGLite to Postgres (#6286)', () => {+ let source: PGLiteEngine;+ let target: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;+ beforeAll(async () => {+ source = new PGLiteEngine(); await source.connect({}); await source.initSchema();+ target = await isolatedPersistencePostgres(DB_URL);+ }, 120_000);+ afterAll(async () => { await source?.disconnect(); await target?.close(); });++ test('the full row travels, the drain seals the page and keeps its chunks, and a re-import skips', async () => {+ await importFromContent(source, 'notes/full-row', body, { sourcePath: 'notes/full-row.md', noEmbed: true });+ await source.executeRaw(`UPDATE pages SET source_kind='file',source_uri='file:///example/notes/full-row.md',ingested_via='sync',ingested_at='2022-01-02T03:04:05Z'+ WHERE slug='notes/full-row'`);+ const before = await rowOf(source);+ expect(before.sealed).toBe(true);+ await copyPageToTarget(source, target.engine, (await source.getPage('notes/full-row'))!);+ const after = await rowOf(target.engine);+ for (const key of ['page_kind', 'source_path', 'effective_date_source', 'import_filename', 'source_kind', 'source_uri', 'ingested_via']) expect(after[key]).toEqual(before[key]);+ expect(new Date(String(after.ingested_at)).toISOString()).toBe('2022-01-02T03:04:05.000Z');+ const [aliases] = await target.engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM page_aliases WHERE slug='notes/full-row' AND origin='frontmatter'");+ expect(Number(aliases!.n)).toBeGreaterThan(0);+ const [job] = await target.engine.executeRaw<{ reason: string }>("SELECT reason FROM page_projection_jobs WHERE slug='notes/full-row'");+ expect(job?.reason).toBe('engine_migration');+ const copied = await chunkIds(target.engine);+ expect(await drainProjections(target.engine, { reasons: ['engine_migration', 'rebuild_failed'] })).toMatchObject({ rebuilt: 1, failed: [], remaining: 0 });+ expect((await rowOf(target.engine)).sealed).toBe(true);+ expect(await chunkIds(target.engine)).toEqual(copied);+ const again = await importFromContent(target.engine, 'notes/full-row', body, { sourcePath: 'notes/full-row.md', noEmbed: true });+ expect(again.status).toBe('skipped');+ expect(await chunkIds(target.engine)).toEqual(copied);+ }, 120_000);+});diff --git a/test/migrate-engine-page-copy-failure.serial.test.ts b/test/migrate-engine-page-copy-failure.serial.test.tsindex d8dbe5d897..d514993e17 100644--- a/test/migrate-engine-page-copy-failure.serial.test.ts+++ b/test/migrate-engine-page-copy-failure.serial.test.ts@@ -56,9 +56,11 @@ describe('copyPageToTarget — undefined-column normalization (#3194)', () => {// #4527: copyPageToTarget restores the source row's timestamps via a// raw UPDATE right after putPage.executeRaw: async () => [],+ setPageAliases: async () => {}, // #6286: frontmatter aliases travel with the page} as unknown as BrainEngine;const source = {getChunksWithEmbeddings: async () => [],+ executeRaw: async () => [], // #6286: the copier reads the source row's origin and provenance columnsgetTags: async () => [],getTimeline: async () => [],getRawData: async () => [],@@ -101,9 +103,11 @@ describe('copyPageToTarget — undefined-column normalization (#3194)', () => {// #4527: copyPageToTarget restores the source row's timestamps via a// raw UPDATE right after putPage.executeRaw: async () => [],+ setPageAliases: async () => {}, // #6286: frontmatter aliases travel with the page} as unknown as BrainEngine;const source = {getChunksWithEmbeddings: async () => [],+ executeRaw: async () => [], // #6286: the copier reads the source row's origin and provenance columnsgetTags: async () => [],getTimeline: async () => [],getRawData: async () => [],diff --git a/test/migrate-engine-raw-include-deleted.test.ts b/test/migrate-engine-raw-include-deleted.test.tsindex bd0b168d6f..7da601afd8 100644--- a/test/migrate-engine-raw-include-deleted.test.ts+++ b/test/migrate-engine-raw-include-deleted.test.ts@@ -36,6 +36,7 @@ describe('copyPageToTarget — raw_data read opts', () => {];const source = {getChunksWithEmbeddings: async () => [],+ executeRaw: async () => [], // #6286: the copier reads the source row's origin and provenance columnsgetTags: async () => [],getTimeline: async () => [],getRawData: async (slug: string, rawSource: unknown, opts: unknown) => {@@ -46,6 +47,7 @@ describe('copyPageToTarget — raw_data read opts', () => {const target = {putPage: async () => fakePage(),executeRaw: async () => [],+ setPageAliases: async () => {}, // #6286: frontmatter aliases travel with the pageputRawData: async (slug: string, rawSource: string, data: unknown, opts: unknown) => {putRawDataCalls.push({ slug, rawSource, data, opts });},diff --git a/test/migrate-full-row-projections.serial.test.ts b/test/migrate-full-row-projections.serial.test.tsnew file mode 100644index 0000000000..c389b97c3d--- /dev/null+++ b/test/migrate-full-row-projections.serial.test.ts@@ -0,0 +1,82 @@+/**+ * #6286 (P2.12, R9): the legacy migrate copier forwarded six page fields, so the new active brain lost each page's+ * origin (`source_path`), kind, provenance, `ingested_at`, frontmatter aliases and code-chunk metadata at the config+ * flip, and every copied page stayed queued for a projection rebuild: the first sync replaced its chunks (re-embedding+ * them, or losing the vectors under `--no-embed`). The copier now forwards the full row, and `runMigrateEngine` drains+ * the target's projections before it flips the config; a page whose rebuild fails blocks the flip. Synthetic content.+ */+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 { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { copyPageToTarget, runMigrateEngine } from '../src/commands/migrate-engine.ts';+import { drainProjections } from '../src/core/page-state/projections.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { loadConfigFileOnly, saveConfig } from '../src/core/config.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';++const body = (title: string) => `---\ntitle: ${title}\naliases: [Example Alias, EA]\n---\n\nA synthetic note about ${title}.\n`;+afterEach(() => _resetCliExitVerdictForTests());++async function fresh(path?: string) { const e = new PGLiteEngine(); await e.connect(path ? { database_path: path } : {}); await e.initSchema(); return e; }+const rowOf = async (e: PGLiteEngine, slug: string) => (await e.executeRaw<Record<string, unknown>>(+ `SELECT page_kind,source_path,effective_date_source,import_filename,source_kind,source_uri,ingested_via,ingested_at::text AS ingested_at,+ (text_projection_revision IS NOT DISTINCT FROM knowledge_revision) AS sealed FROM pages WHERE slug=$1 AND source_id='default'`, [slug]))[0];+const aliasesOf = async (e: PGLiteEngine, slug: string) => (await e.executeRaw<{ alias_norm: string }>(+ "SELECT alias_norm FROM page_aliases WHERE slug=$1 AND source_id='default' AND origin='frontmatter' ORDER BY alias_norm", [slug])).map(r => r.alias_norm);++describe('copyPageToTarget forwards the full row (#6286)', () => {+ test('origin, kind, provenance, ingested_at, aliases and chunk metadata survive; after the drain an identical re-import skips and keeps chunk ids', async () => {+ const source = await fresh(), target = await fresh();+ try {+ await importFromContent(source, 'notes/full-row', body('Full Row'), { sourcePath: 'notes/full-row.md', noEmbed: true });+ await source.executeRaw(`UPDATE pages SET source_kind='file',source_uri='file:///example/notes/full-row.md',ingested_via='sync',ingested_at='2022-01-02T03:04:05Z'+ WHERE slug='notes/full-row'`);+ await source.executeRaw("UPDATE content_chunks SET language='markdown',symbol_name='Example',start_line=1,end_line=4 WHERE page_id=(SELECT id FROM pages WHERE slug='notes/full-row')");+ const before = await rowOf(source, 'notes/full-row');+ expect(before!.source_path).toBe('notes/full-row.md');+ await copyPageToTarget(source, target, (await source.getPage('notes/full-row'))!);+ const after = await rowOf(target, 'notes/full-row');+ for (const key of ['page_kind', 'source_path', 'effective_date_source', 'import_filename', 'source_kind', 'source_uri', 'ingested_via']) expect(after![key]).toEqual(before![key]);+ expect(new Date(String(after!.ingested_at)).toISOString()).toBe('2022-01-02T03:04:05.000Z');+ expect(await aliasesOf(target, 'notes/full-row')).toEqual(await aliasesOf(source, 'notes/full-row'));+ expect((await aliasesOf(target, 'notes/full-row')).length).toBeGreaterThan(0);+ const [chunk] = await target.executeRaw<{ language: string | null; symbol_name: string | null; start_line: number | null }>(+ "SELECT language,symbol_name,start_line FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE slug='notes/full-row') ORDER BY chunk_index LIMIT 1");+ expect(chunk).toMatchObject({ language: 'markdown', symbol_name: 'Example', start_line: 1 });+ expect(after!.sealed).toBe(false);+ const drained = await drainProjections(target);+ expect(drained).toMatchObject({ failed: [], remaining: 0 });+ expect((await rowOf(target, 'notes/full-row'))!.sealed).toBe(true);+ const ids = async () => (await target.executeRaw<{ id: number }>("SELECT id FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE slug='notes/full-row') ORDER BY id")).map(r => r.id);+ const idsBefore = await ids();+ const again = await importFromContent(target, 'notes/full-row', body('Full Row'), { sourcePath: 'notes/full-row.md', noEmbed: true });+ expect(again.status).toBe('skipped');+ expect(await ids()).toEqual(idsBefore);+ } finally { await source.disconnect(); await target.disconnect(); }+ }, 120_000);+});++describe('runMigrateEngine drains the target before the flip (#6286)', () => {+ test('a clean legacy migration leaves the target sealed with nothing queued, and flips the config', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6286-home-'));+ const targetPath = join(mkdtempSync(join(tmpdir(), 'gbrain-6286-target-')), 'brain.pglite');+ const source = await fresh();+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ saveConfig({ engine: 'postgres', database_url: 'postgresql://unused/guard-only' });+ for (const n of ['a', 'b', 'c']) await importFromContent(source, `notes/${n}`, body(n.toUpperCase()), { sourcePath: `notes/${n}.md`, noEmbed: true });+ await runMigrateEngine(source, ['--to', 'pglite', '--path', targetPath]);+ expect(loadConfigFileOnly()).toMatchObject({ engine: 'pglite', database_path: targetPath });+ });+ const target = await fresh(targetPath);+ try {+ const [queue] = await target.executeRaw<{ n: number | string }>('SELECT count(*) AS n FROM page_projection_jobs');+ expect(Number(queue!.n)).toBe(0);+ for (const n of ['a', 'b', 'c']) expect(await rowOf(target, `notes/${n}`)).toMatchObject({ sealed: true, source_path: `notes/${n}.md` });+ } finally { await target.disconnect(); }+ } finally { await source.disconnect(); rmSync(home, { recursive: true, force: true }); }+ }, 180_000);+});