Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): copy every live page, not the first listPages batch (#5539)
garrytan9d0afb21eb0b
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 21d6a09fa6..dd72ef5278 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -22,7 +22,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), 2 non-TTY without `--yes`. 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` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). 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, 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). 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` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). 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/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. `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). 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/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex 6684cce01e..383c28dfab 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -15,7 +15,7 @@ import type { EngineConfig, Page } from '../core/types.ts';import { writeFileSync, readFileSync, existsSync, unlinkSync, statSync, mkdirSync, renameSync } from 'fs';import { createHash } from 'crypto';import { resolve, dirname } from 'path';-import { createProgress } from '../core/progress.ts';+import { createProgress, type ProgressReporter } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { registerCleanup } from '../core/process-cleanup.ts';@@ -405,7 +405,7 @@ export async function copyMigrationConfig(export async function copyPageLinksToTarget(source: BrainEngine,target: BrainEngine,- page: Page,+ page: MigratePageRef,failedKeys: ReadonlySet<string> = new Set(),): Promise<number> {const links = await source.getLinks(page.slug, { sourceId: page.source_id });@@ -550,6 +550,9 @@ export async function copyPageToTarget(};}+/** A page's identity: what the copy lists before it reads each page body. */+export type MigratePageRef = Pick<Page, 'slug' | 'source_id'>;+/** A page that failed to copy during migrate — tracked so the run's final* summary reports it honestly instead of letting the "N copied" counter* imply every page landed (#3194). */@@ -559,6 +562,49 @@ export interface MigratePageFailure {reason: string;}+/**+ * Copy each listed page, reading its body by (source_id, slug) at copy time so+ * memory holds refs, not the whole brain. v0.32.8 F8: source_id is threaded+ * end-to-end so non-default-source tags / timeline / raw / links land on the+ * right row. A page soft-deleted after the listing reads null and is returned+ * in `vanished` (not copied, not a failure). #3194: a per-page write failure is+ * never swallowed into the success count; it stays OUT of completed_slugs (a+ * resume retries it; every write is an upsert) and is returned in `failures`.+ */+export async function copyMigrationPages(+ sourceEngine: BrainEngine,+ targetEngine: BrainEngine,+ refs: MigratePageRef[],+ manifest: MigrateManifest,+ rowCounts: PageCopyCounts,+ progress: ProgressReporter,+): Promise<{ migrated: number; failures: MigratePageFailure[]; vanished: MigratePageRef[] }> {+ let migrated = 0;+ const failures: MigratePageFailure[] = [];+ const vanished: MigratePageRef[] = [];+ for (const ref of refs) {+ try {+ const page = await sourceEngine.getPage(ref.slug, { sourceId: ref.source_id });+ if (!page) {+ vanished.push(ref);+ } else {+ const counts = await copyPageToTarget(sourceEngine, targetEngine, page);+ rowCounts.chunks += counts.chunks;+ rowCounts.tags += counts.tags;+ rowCounts.timeline_entries += counts.timeline_entries;+ rowCounts.raw_data += counts.raw_data;+ manifest.completed_slugs.push(makeManifestKey(page.source_id, page.slug));+ saveManifest(manifest);+ migrated++;+ }+ } catch (e) {+ failures.push({ source_id: ref.source_id, slug: ref.slug, reason: e instanceof Error ? e.message : String(e) });+ }+ progress.tick(1, ref.slug);+ }+ return { migrated, failures, vanished };+}+/*** Quiesce a running autopilot daemon for the duration of the copy.*@@ -944,9 +990,11 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]// (`autopilotEngineIdentity`) and exits cleanly for supervisor relaunch on// the new config — that check, not reconnect(), is what converges it.let sourceStats!: Awaited<ReturnType<BrainEngine['getStats']>>;- let pagesToMigrate: Page[] = [];+ let pagesToMigrate: MigratePageRef[] = [];let migrated = 0;- const failures: MigratePageFailure[] = [];+ let failures: MigratePageFailure[] = [];+ // Pages soft-deleted on the source after the listing: not copied, not failures.+ let vanished: MigratePageRef[] = [];// Per-table copy counts for the end-of-run summary (#4350): every table// the migration touches reports what actually landed, so an omitted table// is visible instead of silent.@@ -960,9 +1008,10 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]try {sourcesCopied = await copyMigrationSources(sourceEngine, targetEngine);- // Get all source pages+ // Every live page's (source_id, slug) from one uncapped query; each body+ // is read in the copy loop, so memory holds refs, not the whole brain.sourceStats = await sourceEngine.getStats();- const allPages = await sourceEngine.listPages({ limit: 100000 });+ const allPages = await sourceEngine.listAllPageRefs();pagesToMigrate = allPages.filter(p => !completedSet.has(makeManifestKey(p.source_id, p.slug)));console.log(`Migrating ${pagesToMigrate.length} pages (${allPages.length} total, ${completedSet.size} already done)...`);@@ -970,38 +1019,13 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));progress.start('migrate.copy_pages', pagesToMigrate.length);- // v0.32.8 F8: thread source_id end-to-end so multi-source pages migrate- // intact. Pre-fix: putPage / getTags / getTimeline / getRawData / getLinks- // all silently defaulted to source_id='default', so non-default-source- // tags / timeline / raw / links were either dropped or attached to the- // wrong row.- for (const page of pagesToMigrate) {- try {- const counts = await copyPageToTarget(sourceEngine, targetEngine, page);- rowCounts.chunks += counts.chunks;- rowCounts.tags += counts.tags;- rowCounts.timeline_entries += counts.timeline_entries;- rowCounts.raw_data += counts.raw_data;- // Track progress with composite key so multi-source resume is correct.- manifest!.completed_slugs.push(makeManifestKey(page.source_id, page.slug));- saveManifest(manifest!);- migrated++;- } catch (e) {- // #3194: a per-page write failure must never be swallowed into the- // success count. Leave it OUT of completed_slugs (a resume retries- // it — putPage/upsertChunks/etc. are all upserts, so re-running the- // whole page copy is safe) and surface it in the final summary below- // instead of letting "N pages copied" imply everything landed.- failures.push({- source_id: page.source_id,- slug: page.slug,- reason: e instanceof Error ? e.message : String(e),- });- }- progress.tick(1, page.slug);- }+ ({ migrated, failures, vanished } = await copyMigrationPages(sourceEngine, targetEngine, pagesToMigrate, manifest!, rowCounts, progress));progress.finish();+ if (vanished.length > 0) {+ console.log(`${vanished.length} page(s) were deleted on the source during the copy and were not migrated.`);+ }+if (failures.length > 0) {console.error(`\n${failures.length} of ${pagesToMigrate.length} page(s) FAILED to copy and were NOT migrated:`);for (const f of failures) {@@ -1022,7 +1046,8 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]// whole phase (the exact "addLink failed: page ... not found" crash from// the original report). Skip links on either end of a known-failed page —// a retry that successfully copies the page also re-copies its links.- const failedKeys = new Set(failures.map(f => makeManifestKey(f.source_id, f.slug)));+ // A page deleted mid-copy is absent on the target the same way.+ const failedKeys = new Set([...failures, ...vanished].map(f => makeManifestKey(f.source_id, f.slug)));console.log('Copying links...');progress.start('migrate.copy_links', allPages.length);for (const page of allPages) {diff --git a/test/migrate-engine-pagination.serial.test.ts b/test/migrate-engine-pagination.serial.test.tsnew file mode 100644index 0000000000..ddd33c95da--- /dev/null+++ b/test/migrate-engine-pagination.serial.test.ts@@ -0,0 +1,141 @@+/**+ * #5532 -- `gbrain migrate` must copy every live page. The copy used one+ * `listPages({ limit: 100000 })` read, so the engine's LIMIT silently dropped+ * every page past it. Here the source engine caps each listPages read at 2+ * rows (standing in for that LIMIT without inserting 100k rows); the+ * migration must still land all pages, same-slug pages from two sources+ * included. A page soft-deleted after the listing is skipped without+ * failing the run and without costing any live page.+ *+ * Serial: mutates GBRAIN_HOME / DATABASE_URL for the migration's config reads.+ */++import { describe, test, expect, afterEach } from 'bun:test';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runMigrateEngine } from '../src/commands/migrate-engine.ts';+import { saveConfig } from '../src/core/config.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import type { PageFilters } from '../src/core/types.ts';++const PAGES = [+ 'connector-a:notes/p1',+ 'connector-a:people/alice-example',+ 'default:notes/p2',+ 'default:notes/p3',+ 'default:people/alice-example',+];++/**+ * Migrate a seeded PGLite brain into a fresh PGLite target. `afterListing`+ * runs once, after the listing began and before the first page is read:+ * on the second capped listPages call or the first getPage call, whichever+ * comes first.+ */+async function migrate(afterListing?: (source: PGLiteEngine) => Promise<void>) {+ const gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-migrate-home-'));+ const targetDbPath = join(mkdtempSync(join(tmpdir(), 'gbrain-migrate-target-')), 'brain.pglite');+ const prev = {+ home: process.env.GBRAIN_HOME,+ url: process.env.DATABASE_URL,+ gbrainUrl: process.env.GBRAIN_DATABASE_URL,+ exitCode: process.exitCode,+ log: console.log,+ };+ let source: PGLiteEngine | null = null;+ let target: PGLiteEngine | null = null;+ try {+ delete process.env.DATABASE_URL;+ delete process.env.GBRAIN_DATABASE_URL;+ process.env.GBRAIN_HOME = gbrainHome;+ saveConfig({ engine: 'postgres', database_url: 'postgresql://unused/guard-only' });++ source = new PGLiteEngine();+ await source.connect({});+ await source.initSchema();+ await source.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('connector-a', 'Connector A') ON CONFLICT DO NOTHING`,+ );+ for (const key of PAGES) {+ const [sourceId, slug] = key.split(':');+ await source.putPage(+ slug,+ { type: 'note', title: slug, compiled_truth: `body ${key}`, timeline: '' },+ { sourceId },+ );+ }++ const seeded = source;+ let hookRan = !afterListing;+ const runHook = async () => {+ if (hookRan) return;+ hookRan = true;+ await afterListing!(seeded);+ };+ const realList = PGLiteEngine.prototype.listPages;+ const realGet = PGLiteEngine.prototype.getPage;+ let listCalls = 0;+ (seeded as unknown as { listPages: unknown }).listPages = async (filters?: PageFilters) => {+ if (++listCalls === 2) await runHook();+ return realList.call(seeded, { ...filters, limit: Math.min(filters?.limit ?? 100, 2) });+ };+ (seeded as unknown as { getPage: unknown }).getPage = async (...args: Parameters<PGLiteEngine['getPage']>) => {+ await runHook();+ return realGet.apply(seeded, args);+ };++ const logLines: string[] = [];+ console.log = (...args: unknown[]) => { logLines.push(args.join(' ')); };+ try {+ await runMigrateEngine(seeded, ['--to', 'pglite', '--path', targetDbPath]);+ } finally {+ console.log = prev.log;+ }+ const exitCode = currentExitCode();++ target = new PGLiteEngine();+ await target.connect({ database_path: targetDbPath });+ const rows = await target.executeRaw<{ source_id: string; slug: string; compiled_truth: string }>(+ `SELECT source_id, slug, compiled_truth FROM pages ORDER BY source_id, slug`,+ );+ return { exitCode, log: logLines.join('\n'), rows };+ } finally {+ console.log = prev.log;+ if (source) await source.disconnect();+ if (target) await target.disconnect();+ _resetCliExitVerdictForTests();+ process.exitCode = prev.exitCode;+ if (prev.home !== undefined) process.env.GBRAIN_HOME = prev.home; else delete process.env.GBRAIN_HOME;+ if (prev.url !== undefined) process.env.DATABASE_URL = prev.url;+ if (prev.gbrainUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prev.gbrainUrl;+ rmSync(gbrainHome, { recursive: true, force: true });+ rmSync(join(targetDbPath, '..'), { recursive: true, force: true });+ }+}++describe('runMigrateEngine reads the whole page set (#5532)', () => {+ afterEach(() => {+ _resetCliExitVerdictForTests();+ });++ test('pages past a capped listPages read reach the target', async () => {+ const { exitCode, log, rows } = await migrate();+ expect(exitCode).toBe(0);+ expect(log).toContain('Migrating 5 pages (5 total, 0 already done)');+ expect(rows.map((r) => `${r.source_id}:${r.slug}`)).toEqual(PAGES);+ for (const r of rows) expect(r.compiled_truth).toContain(`body ${r.source_id}:${r.slug}`);+ }, 60000);++ test('a page soft-deleted after the listing is skipped and every live page lands', async () => {+ const { exitCode, log, rows } = await migrate(async (source) => {+ await source.executeRaw(+ `UPDATE pages SET deleted_at = now() WHERE source_id = 'connector-a' AND slug = 'notes/p1'`,+ );+ });+ expect(exitCode).toBe(0);+ expect(log).toContain('1 page(s) were deleted on the source during the copy and were not migrated.');+ expect(rows.map((r) => `${r.source_id}:${r.slug}`)).toEqual(PAGES.filter((k) => k !== 'connector-a:notes/p1'));+ }, 60000);+});