Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

migrate: refusals carry why and a filled fix naming the refusing side

garrytan4b14b8039ea8
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index f639adb721..b93fabe463 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -19,7 +19,7 @@ Different users have different constraints:
| Researcher | Analytics, bulk exports, embeddings | DuckDBEngine (someday) |
| Edge/mobile | Offline-first, sync later | PGLiteEngine + sync (someday) |
-The engine interface means we don't have to choose. PGLite is the zero-friction default. Supabase is the production scale path. `gbrain migrate --to supabase/pglite` moves between them.
+The engine interface means we don't have to choose. PGLite is the zero-friction default. Supabase is the production scale path. `gbrain migrate --to postgres|pglite` moves between them (`supabase` is an alias of `postgres`).
## The interface
@@ -293,7 +293,16 @@ Details in INSTALL_FOR_AGENTS.md ("Engine preference for harness installs").
| Concurrency | Single process | Connection pooling |
| Backups | Manual (file copy) | Managed by Supabase |
-**Migration:** `gbrain migrate --to supabase` exports everything (pages, chunks, embeddings, links, tags, timeline, facts) and imports into Supabase. Config rows copy in full minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. `gbrain migrate --to pglite` goes the other direction. The copy is lossless for what it carries, but it refuses two kinds of brain: a managed brain (`writer_coordinator_required`, "cannot mutate a managed brain through the legacy writer") and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`), because the copier cannot carry request IDs, withdrawals or ownership. A brain that has saved memory through the write coordinator (`remember`, `put_page` from an agent or a resident `gbrain serve`) has that history, so in practice `migrate --to` works only for brains that never used it. For those brains, keep the datastore and repair forward (`gbrain doctor`, `gbrain repair`) instead of migrating, and choose Postgres up front if you expect 1000+ files or several machines. An engine move that preserves request IDs, withdrawals, attribution, grants and ownership is planned, not shipped.
+**Migration:** `gbrain migrate --to postgres` (alias `--to supabase`) exports everything (pages, chunks, embeddings, links, tags, timeline, facts) and imports into Postgres. Config rows copy in full minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. `gbrain migrate --to pglite` goes the other direction. The copy is lossless for what it carries, but it refuses two kinds of brain: a managed brain and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`), because the copier cannot carry request IDs, withdrawals or ownership. A brain that has saved memory through the write coordinator (`remember`, `put_page` from an agent or a resident `gbrain serve`) has that history, so in practice `migrate --to` works only for brains that never used it. Choose Postgres up front if you expect 1000+ files or several machines.
+
+<a id="engine-migration-refused"></a>**Engine migration refused (`writer_coordinator_required`).** The refusal is an agent-contract envelope whose `fix` names the refusing side; every branch verifies with the read-only `gbrain doctor --no-migrate --json`, and nothing has changed in either datastore:
+
+| Refusing side | `fix.next` | Next step |
+|---|---|---|
+| A PGLite brain moving to Postgres (history or managed) | `ask_user` | Relay `user_message`: keep the brain on PGLite and share it with other machines through `gbrain mcp expose` (effects `persistent_install`, `egress`), or leave it as it is. A verified PGLite-to-Postgres graduation that carries this history is not available yet. |
+| A Postgres brain moving to PGLite | `report` | The brain stays on Postgres; moving down would drop its history. |
+| A target that already holds persistence history | `tell_user_to_run` | `gbrain migrate --to <engine> --url <empty_database_url>` with an empty database the user provides (`--path` for a PGLite target). |
+
The migration and the autopilot daemon do not race: `migrate --to` claims a
cooperative pause marker before touching the target. The marker doubles as a
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 4641dbd794..d6f1a35b42 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -81,10 +81,12 @@ gbrain init --prefer-postgres # env URL → Supabase token discovery → loca
To switch later:
```bash
-gbrain migrate --to supabase # PGLite → Postgres
+gbrain migrate --to postgres # PGLite → Postgres (alias: --to supabase)
gbrain migrate --to pglite # Postgres → PGLite (rare)
```
+The move works for brains with no write history. A brain that has saved memory through the write coordinator stays on its engine; the refusal explains the choices ([engine migration refused](ENGINES.md#engine-migration-refused)).
+
If Postgres access ever breaks at runtime, `gbrain engine status --probe` diagnoses it and `gbrain db-repair` fixes it — see the "Engine detection and access repair" section of [`docs/ENGINES.md`](ENGINES.md).
For shared / large / multi-machine deployments (a team or company brain with multiple users hitting one server over HTTP MCP with OAuth scoping per user), follow the dedicated walkthrough: **[Tutorial: set up GBrain as your company brain](tutorials/company-brain.md)**.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 481549773a..1b0fd7c95e 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -22,6 +22,7 @@
| Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` |
| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |
| [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |
+| [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` |
| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |
| [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` |
diff --git a/src/cli.ts b/src/cli.ts
index ad39bb129f..fe6c148187 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -2960,7 +2960,7 @@ SETUP
engine status [--json] [--probe] Which engine + URL source, engine-free
db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free
(--yes --apply-rewrites for config rewrites)
- migrate --to <supabase|pglite> Transfer brain between engines
+ migrate --to <postgres|pglite> Transfer brain between engines (supabase = postgres)
migrate embeddings --to <p:model> Re-embed onto another embedding provider
embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)
upgrade Self-update
diff --git a/src/cli/commands/migrate.ts b/src/cli/commands/migrate.ts
index 9d6821cd49..640e5c0b40 100644
--- a/src/cli/commands/migrate.ts
+++ b/src/cli/commands/migrate.ts
@@ -10,14 +10,14 @@ import type { BrainEngine } from '../../core/engine.ts';
export async function run(engine: BrainEngine, args: string[]): Promise<void> {
// #3390: `gbrain migrate embeddings --to <provider:model>` — the
// provider-agnostic embedding migration. Everything else stays the
- // engine-transfer path (`migrate --to <supabase|pglite>`).
+ // engine-transfer path (`migrate --to <postgres|supabase|pglite>`).
if (args[0] === 'embeddings') {
const { runMigrateEmbeddings } = await import('../../commands/migrate-embeddings.ts');
await runMigrateEmbeddings(engine, args.slice(1));
return;
}
if (args.includes('--help') || args.includes('-h')) {
- console.log('Usage: gbrain migrate --to <supabase|pglite> [--url <url>] [--path <path>] [--force]');
+ console.log('Usage: gbrain migrate --to <postgres|supabase|pglite> [--url <url>] [--path <path>] [--force]');
console.log(' gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes]');
console.log('');
console.log('The first form transfers the brain between engines; the second re-embeds');
diff --git a/src/commands/config.ts b/src/commands/config.ts
index c761e7aaa1..393747518a 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -220,7 +220,7 @@ const CONFIG_SET_KNOWN_FLAGS = ['--force', '--coverage-override', '--yes'];
export async function handleDbPlaneRoutedKeys(key: string, value: string): Promise<boolean> {
if (key === 'engine') {
console.error('[config] engine is INFERRED from database_url / database_path — it is never set directly.');
- console.error('[config] To move your data between engines: gbrain migrate --to <supabase|pglite>');
+ console.error('[config] To move your data between engines: gbrain migrate --to <postgres|pglite>');
console.error('[config] To point at a different database: gbrain config set database_url <conn> (or gbrain init --url <conn>)');
console.error('[config] No --force escape: an engine flip without a data migration splits the brain across two stores.');
process.exit(1);
diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.ts
index 1166d64828..7ecb6291a1 100644
--- a/src/commands/migrate-engine.ts
+++ b/src/commands/migrate-engine.ts
@@ -38,14 +38,19 @@ interface MigrateOpts {
function parseArgs(args: string[]): MigrateOpts {
const toIdx = args.indexOf('--to');
if (toIdx === -1 || !args[toIdx + 1]) {
- throw opError('invalid_params', 'gbrain migrate needs --to <supabase|pglite>.',
- 'Usage: gbrain migrate --to <supabase|pglite> [--url <url>] [--path <path>] [--force]. Example: gbrain migrate --to pglite --path ~/.gbrain/brain.pglite');
+ throw opError('invalid_params', 'gbrain migrate needs --to <postgres|supabase|pglite>.',
+ 'Usage: gbrain migrate --to <postgres|supabase|pglite> [--url <url>] [--path <path>] [--force]. Example: gbrain migrate --to pglite --path ~/.gbrain/brain.pglite');
}
const targetRaw = args[toIdx + 1];
const targetEngine = targetRaw === 'supabase' ? 'postgres' : targetRaw as 'postgres' | 'pglite';
if (targetEngine !== 'postgres' && targetEngine !== 'pglite') {
- throw new Error(`Unknown target engine: "${targetRaw}". Use: supabase or pglite`);
+ throw opError('invalid_params', `Unknown target engine: "${targetRaw}". Use postgres (alias supabase) or pglite.`,
+ 'Usage: gbrain migrate --to <postgres|supabase|pglite> [--url <url>] [--path <path>] [--force].',
+ { why: `gbrain migrate moves a brain between its two engines, postgres and pglite; "${targetRaw}" is neither.`,
+ fix: { argv: ['gbrain', 'migrate', '--to', '<engine>'], inputs: [{ name: 'engine', how: 'postgres (alias supabase) or pglite, whichever engine the user wants to move to.' }],
+ consent: [], actor: 'agent', requires_exclusive: true, verify: { argv: ['gbrain', 'engine', 'status', '--json'] },
+ why: 'Names an engine gbrain supports.' } });
}
const urlIdx = args.indexOf('--url');
@@ -828,8 +833,9 @@ export async function quiesceAutopilot(engine?: BrainEngine): Promise<(() => voi
export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]): Promise<void> {
const opts = parseArgs(args);
- await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration');
- await assertLegacyEngineMigration(sourceEngine);
+ const migration = { from: sourceEngine.kind, to: opts.targetEngine };
+ await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration', { migration: { side: 'source', ...migration } });
+ await assertLegacyEngineMigration(sourceEngine, { side: 'source', ...migration });
const config = loadConfig();
if (!config) {
console.error('No brain configured. Run: gbrain init');
@@ -880,8 +886,8 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]
await targetEngine.connect(targetConfig);
await targetEngine.initSchema();
try {
- await assertUnmanagedCanonicalWriter(targetEngine, 'engine migration');
- await assertLegacyEngineMigration(targetEngine);
+ await assertUnmanagedCanonicalWriter(targetEngine, 'engine migration', { migration: { side: 'target', ...migration } });
+ await assertLegacyEngineMigration(targetEngine, { side: 'target', ...migration });
} catch (error) {
try { await targetEngine.disconnect(); } finally { resumeAutopilot(); }
throw error;
diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.ts
index 79467e646d..6f16fecb7e 100644
--- a/src/core/persistence/maintenance.ts
+++ b/src/core/persistence/maintenance.ts
@@ -2,23 +2,69 @@ import { existsSync, renameSync } from 'node:fs';
import { join } from 'node:path';
import { acquireLock, releaseLock } from '../pglite-lock.ts';
import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
import type { SqlEngine } from './model.ts';
// Every facts-family bulk writer now publishes through the coordinator on a
// managed brain (#5280); status and activation keep reporting the (empty) list.
export const UNSUPPORTED_MANAGED_BULK_WRITERS: readonly string[] = [];
+export const ENGINE_MIGRATION_DOCS = 'docs/ENGINES.md#engine-migration-refused';
+const DOCTOR_VERIFY = { argv: ['gbrain', 'doctor', '--no-migrate', '--json'] };
+type EngineKind = 'pglite' | 'postgres';
+/** Which side of `gbrain migrate --to` a refusal names: the brain being moved, or the datastore it would land in. */
+export interface EngineMigrationSide { side: 'source' | 'target'; from: EngineKind; to: EngineKind }
+
+/**
+ * The refusal's next step, by side. A PGLite brain moving up gets the user's
+ * choice: wait for verified graduation, or stay on PGLite and share it over
+ * MCP. A Postgres brain moving down keeps its datastore. A target that
+ * already holds persistence state needs an empty database.
+ */
+function engineMigrationFix(m: EngineMigrationSide, why: string): Action {
+ if (m.side === 'target') {
+ return { argv: ['gbrain', 'migrate', '--to', m.to, ...(m.to === 'postgres' ? ['--url', '<empty_database_url>'] : ['--path', '<empty_brain_path>'])],
+ inputs: [m.to === 'postgres'
+ ? { name: 'empty_database_url', how: 'Ask the user for the connection string of an empty Postgres database (a new database or project).' }
+ : { name: 'empty_brain_path', how: 'Ask the user for a path where no PGLite brain exists yet.' }],
+ consent: [], actor: 'user', requires_exclusive: true, docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
+ why: `${why} The migration target already holds another brain's write history, so gbrain will not copy into it; the source brain is untouched.`,
+ user_message: 'The database you chose to migrate into already holds another gbrain brain. Do you have an empty database to use instead? Nothing has changed in your current brain.' };
+ }
+ if (m.from === 'postgres') {
+ return { consent: [], actor: 'agent', requires_exclusive: false, docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
+ why: `${why} Moving a Postgres brain with this history to PGLite would drop it, so the brain stays on Postgres; nothing changed.`,
+ user_message: 'Your brain stays on Postgres: moving it to PGLite would lose its write history and withdrawn facts. Nothing changed.' };
+ }
+ return { argv: ['gbrain', 'mcp', 'expose'], consent: ['persistent_install', 'egress'], actor: 'agent', requires_exclusive: false,
+ docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
+ why: `${why} A verified PGLite-to-Postgres graduation that carries this history is not available yet. Until it is, the brain stays on PGLite; `
+ + '`gbrain mcp expose` shares it with agents on other machines without moving it.',
+ user_message: 'Your brain cannot move to Postgres yet without losing its write history and withdrawn facts. '
+ + 'Should I keep it on PGLite and share it with your other machines over MCP (gbrain mcp expose), or leave it as it is until graduation to Postgres is available? Nothing has changed.' };
+}
+
/** Refuse unsupported multi-stage writers before providers, files or git change. */
-export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string): Promise<void> {
+export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string, opts: { migration?: EngineMigrationSide } = {}): Promise<void> {
const rows = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (rows?.[0]?.enabled) throw new OperationError('writer_coordinator_required',
- `${operation} cannot mutate a managed brain through the legacy writer.`,
- 'Use supported persistence operations. Source topology and maintenance require a verified drain before migration.');
+ if (!rows?.[0]?.enabled) return;
+ const message = `${operation} cannot mutate a managed brain through the legacy writer.`;
+ const why = 'This brain is managed: every write goes through its writer coordinator, which the legacy writer bypasses.';
+ if (opts.migration) {
+ throw opError('writer_coordinator_required', message,
+ 'Keep this datastore; the engine copier cannot carry a managed brain. Ask the user how to proceed.',
+ { why, reason: 'managed_brain', docs: ENGINE_MIGRATION_DOCS, fix: engineMigrationFix(opts.migration, why) });
+ }
+ throw opError('writer_coordinator_required', message,
+ `Run the same gbrain command again: it routes a managed brain through the coordinator, and the brain became managed while ${operation} ran.`,
+ { why, reason: 'managed_brain', fix: { consent: [], actor: 'agent', requires_exclusive: false, verify: DOCTOR_VERIFY,
+ why: `${why} Each gbrain command that changes sources or imports content takes the coordinated path on a managed brain, so the same command run again uses it; nothing was written.`,
+ user_message: `gbrain stopped ${operation} because your brain switched to managed writes while it ran. Nothing was written; running the same command again uses the managed path.` } });
}
/** The legacy engine copier cannot transfer permanent IDs, withdrawals or ownership. */
-export async function assertLegacyEngineMigration(engine: SqlEngine): Promise<void> {
+export async function assertLegacyEngineMigration(engine: SqlEngine, migration: EngineMigrationSide = { side: 'source', from: 'pglite', to: 'postgres' }): Promise<void> {
const tables = ['persistence_requests', 'fact_withdrawals', 'persistence_worktrees'] as const;
// Older migration sources can predate these tables. Do not interpret any
// other database failure as an empty history.
@@ -27,9 +73,13 @@ export async function assertLegacyEngineMigration(engine: SqlEngine): Promise<vo
for (const table of tables) {
if (!present.some(row => row.name === table)) continue;
const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS(SELECT 1 FROM ${table}) AS present`);
- if (row?.present) throw new OperationError('writer_coordinator_required',
+ if (!row?.present) continue;
+ const why = `The ${migration.side === 'source' ? 'brain' : 'target datastore'} has rows in ${table}, and the engine copier cannot carry request IDs, withdrawals or canonical ownership.`;
+ throw opError('writer_coordinator_required',
'Engine migration cannot discard durable write history, withdrawal protection, or canonical ownership.',
- 'Keep this datastore. Use forward repair or a verified migration that preserves the complete persistence state.');
+ migration.side === 'target' ? 'Choose an empty target database; the source brain is unchanged.'
+ : 'Keep this datastore; nothing changed. Ask the user how to proceed.',
+ { why, reason: 'persistence_history', docs: ENGINE_MIGRATION_DOCS, fix: engineMigrationFix(migration, why) });
}
}
diff --git a/test/engine-migration-refusal.test.ts b/test/engine-migration-refusal.test.ts
new file mode 100644
index 0000000000..53c5e99414
--- /dev/null
+++ b/test/engine-migration-refusal.test.ts
@@ -0,0 +1,128 @@
+/**
+ * `gbrain migrate --to` refusals carry the agent contract (Foundations 2,
+ * "Lane B: refusal now", refusal envelopes and refusal branches).
+ *
+ * Protects: the envelope an agent reads when the legacy engine copier refuses
+ * a brain. The history refusal and the managed-brain refusal are `opError`s
+ * with `why` and a filled `fix` that names the refusing side: a PGLite brain
+ * gets the user's choice (stay on PGLite and share it with `gbrain mcp
+ * expose`, or wait for graduation, which is not available yet), a Postgres
+ * brain moving down keeps its datastore, and a target that already holds
+ * history needs an empty database. Every branch verifies read-only with
+ * `gbrain doctor --no-migrate --json`. The unknown-engine error is an
+ * `invalid_params` opError, and the usage text names every accepted engine.
+ * Fails when: a refusal goes back to a prose-only OperationError (no `fix`),
+ * a branch loses its side, or the usage text drops `postgres`.
+ * Why new: test/persistence-migration-preservation.test.ts pins only the code.
+ * Seam: none (real PGLite brains; toAgentError renders the CLI and MCP wire).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { assertLegacyEngineMigration, assertUnmanagedCanonicalWriter } from '../src/core/persistence/maintenance.ts';
+import { runMigrateEngine } from '../src/commands/migrate-engine.ts';
+import { toAgentError, type RenderContext } from '../src/core/agent-output.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+const routing = { brain: 'host', source: 'default' };
+const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false, routing };
+const stdio: RenderContext = { transport: 'stdio', surface: 'full', isCallable: () => true, preapproved: () => false, routing };
+const VERIFY = ['gbrain', 'doctor', '--no-migrate', '--json'];
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES('default','world','refusal-example')");
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ const error = await run().then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ return error as OperationError;
+}
+const envelope = (e: unknown, render: RenderContext) => toAgentError(e, { transport: render.transport, render });
+
+describe('history refusal names the refusing side', () => {
+ test('a PGLite brain moving to Postgres: ask the user, stay on PGLite and expose it, graduation not available yet', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'source', from: 'pglite', to: 'postgres' }));
+ expect(e.code).toBe('writer_coordinator_required');
+ expect(e.why).toContain('fact_withdrawals');
+ const env = envelope(e, cli);
+ expect(env.code).toBe('writer_coordinator_required');
+ expect(env.fix).toMatchObject({ next: 'ask_user', consent: ['persistent_install', 'egress'], verify: { argv: expect.arrayContaining(VERIFY) } });
+ expect(env.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
+ expect(env.fix?.user_message).toContain('gbrain mcp expose');
+ expect(env.fix?.user_message).toContain('until graduation to Postgres is available');
+ expect(env.fix?.why).toContain('not available yet');
+ expect(JSON.stringify(env)).not.toContain('--plan');
+ // Over MCP the CLI command is the user's to run; the choice they are asked about is unchanged.
+ expect(envelope(e, stdio).fix).toMatchObject({ next: 'tell_user_to_run', user_message: env.fix?.user_message });
+ });
+
+ test('the default side is the PGLite source moving up', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine));
+ expect(envelope(e, cli).fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
+ });
+
+ test('a Postgres brain moving to PGLite keeps its datastore', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'source', from: 'postgres', to: 'pglite' }));
+ const env = envelope(e, cli);
+ expect(env.fix?.next).toBe('report');
+ expect(env.fix?.argv).toBeUndefined();
+ expect(env.fix?.user_message).toContain('stays on Postgres');
+ expect(env.fix?.verify?.argv).toEqual(expect.arrayContaining(VERIFY));
+ });
+
+ test('a target that already holds history needs an empty database from the user', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'target', from: 'pglite', to: 'postgres' }));
+ const env = envelope(e, cli);
+ expect(e.why).toContain('target datastore');
+ expect(env.fix).toMatchObject({ next: 'tell_user_to_run', inputs: [{ name: 'empty_database_url' }] });
+ expect(env.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'migrate', '--to', 'postgres']);
+ expect(env.fix?.user_message).toContain('empty database');
+ });
+
+ test('runMigrateEngine refuses a PGLite brain with history before touching a target, with the filled fix', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, ['--to', 'postgres', '--url', 'postgresql://user@localhost:1/never']));
+ expect(envelope(e, cli).fix?.next).toBe('ask_user');
+ });
+});
+
+describe('managed-brain refusal', () => {
+ beforeAll(async () => { await engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1'); });
+ afterAll(async () => { await engine.executeRaw('UPDATE persistence_brain SET enabled = false WHERE singleton = 1'); });
+
+ test('engine migration of a managed brain gets the same graduate-or-expose choice', async () => {
+ const e = await refusal(() => assertUnmanagedCanonicalWriter(engine, 'engine migration', { migration: { side: 'source', from: 'pglite', to: 'postgres' } }));
+ expect(e.code).toBe('writer_coordinator_required');
+ expect(e.why).toContain('managed');
+ expect(envelope(e, cli).fix?.next).toBe('ask_user');
+ expect(envelope(e, cli).fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
+ });
+
+ test('another legacy writer names the coordinated path and verifies read-only', async () => {
+ const e = await refusal(() => assertUnmanagedCanonicalWriter(engine, 'sources archive'));
+ const env = envelope(e, cli);
+ expect(env.fix?.next).toBe('report');
+ expect(env.fix?.why).toContain('coordinated path');
+ expect(env.fix?.user_message).toContain('sources archive');
+ expect(env.fix?.verify?.argv).toEqual(expect.arrayContaining(VERIFY));
+ });
+});
+
+describe('gbrain migrate argument errors', () => {
+ test('an unknown engine is an invalid_params opError whose fix names the accepted engines', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, ['--to', 'duckdb']));
+ expect(e.code).toBe('invalid_params');
+ expect(e.why).toContain('postgres and pglite');
+ const env = envelope(e, cli);
+ expect(env.fix?.inputs?.[0]?.how).toContain('postgres (alias supabase) or pglite');
+ });
+
+ test('the usage text lists every accepted --to value', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, []));
+ for (const value of ['postgres', 'supabase', 'pglite']) expect(e.suggestion).toContain(value);
+ });
+});
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 2dd82bd490..1a42aa2574 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -20,7 +20,7 @@
" engine status [--json] [--probe] Which engine + URL source, engine-free",
" db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free",
" (--yes --apply-rewrites for config rewrites)",
- " migrate --to <supabase|pglite> Transfer brain between engines",
+ " migrate --to <postgres|pglite> Transfer brain between engines (supabase = postgres)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
" upgrade Self-update",
@@ -230,7 +230,7 @@
" engine status [--json] [--probe] Which engine + URL source, engine-free",
" db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free",
" (--yes --apply-rewrites for config rewrites)",
- " migrate --to <supabase|pglite> Transfer brain between engines",
+ " migrate --to <postgres|pglite> Transfer brain between engines (supabase = postgres)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
" upgrade Self-update",
@@ -440,7 +440,7 @@
" engine status [--json] [--probe] Which engine + URL source, engine-free",
" db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free",
" (--yes --apply-rewrites for config rewrites)",
- " migrate --to <supabase|pglite> Transfer brain between engines",
+ " migrate --to <postgres|pglite> Transfer brain between engines (supabase = postgres)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
" upgrade Self-update",