Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation G2b: target routes/probes, request-only drain, in-process copier

garrytan4344d8e57eb3
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index a9e3e56a23..e462b2b2a7 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -46,6 +46,8 @@ export async function runResidentProjectionInvocation(engine: BrainEngine, hostI
{ deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now, retryCooldown: true });
}
+const PARKED_WORKER: Promise<void> = Promise.resolve();
+
export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;
export class PersistenceConsumer {
private stopping = false;
@@ -88,14 +90,20 @@ export class PersistenceConsumer {
readonly hostId: string;
constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,
private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void;
- onSettled?: (row: WriteRequest) => void } = {}) {
+ onSettled?: (row: WriteRequest) => void;
+ /** Engine graduation drain: claim, recover and publish requests only; effect, projection, topology and maintenance workers never start. */
+ requestsOnly?: boolean } = {}) {
this.hostId = opts.hostId ?? localHostId();
}
private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {
const engine = this.engine as { onCheckout?: unknown };
return typeof engine.onCheckout === 'function' ? (engine.onCheckout as (listener: () => void) => () => void).bind(this.engine) : undefined;
}
- start(): void { this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs; this.schedule(0); }
+ start(): void {
+ this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs;
+ if (this.opts.requestsOnly) this.projectionWorker = this.effectsWorker = this.topologyWorker = this.maintenanceWorker = PARKED_WORKER;
+ this.schedule(0);
+ }
/**
* Work admitted by this process: tick now instead of waiting out the idle
* backoff. Like a completed publication, it claims at once and leaves scans
diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.ts
index bf90114460..cc337b5a00 100644
--- a/src/core/persistence/engine-graduation.types.ts
+++ b/src/core/persistence/engine-graduation.types.ts
@@ -94,6 +94,8 @@ export interface InventoryEntry {
lossKind: LossKind;
/** The only differences verify tolerates between source snapshot and target. */
transforms: readonly ColumnTransform[];
+ /** Columns the per-column copy contract tolerates differing between source and target (name -> reason). */
+ columnAllowlist?: Readonly<Record<string, string>>;
reason: string;
}
@@ -119,6 +121,39 @@ export interface TargetRoutes {
urlEnv?: string;
}
+export interface EmbeddingColumn {
+ relation: string;
+ column: string;
+ /** format_type rendering, e.g. "vector(1536)" or "halfvec(1024)". */
+ type: string;
+ dims: number | null;
+}
+
+export interface TargetProbe {
+ reachable: boolean;
+ auth: boolean;
+ /** Redacted; never carries the URL or password. */
+ error?: { code: string; message: string };
+ ddl: { reachable: boolean; auth: boolean; error?: { code: string; message: string } };
+ serverVersion: string | null;
+ serverVersionNum: number | null;
+ vector: { installed: string | null; available: string | null; halfvec: boolean };
+ createPrivilege: { database: boolean; schema: boolean };
+ /** BEGIN; SET LOCAL session_replication_role = replica; ROLLBACK succeeded. */
+ replicaRole: boolean;
+ /** Every existing public table is owned by a role the current user can act as. */
+ ownsTables: boolean;
+ triggerBypass: TriggerBypass | null;
+ /** A gbrain schema exists (the config table is present). */
+ gbrainSchema: boolean;
+ /** No public tables, or a gbrain schema holding only the initSchema seed rows. */
+ empty: boolean;
+ nonEmptyTables: readonly string[];
+ embeddingColumns: readonly EmbeddingColumn[];
+ /** Other sessions on the target database (informational). */
+ otherSessions: number;
+}
+
export interface SourceIdentity {
dataDir: string;
brainId: string;
diff --git a/src/core/persistence/graduation-copy.ts b/src/core/persistence/graduation-copy.ts
new file mode 100644
index 0000000000..33be18a958
--- /dev/null
+++ b/src/core/persistence/graduation-copy.ts
@@ -0,0 +1,426 @@
+/**
+ * Engine graduation copier (Route B, in process): copies each carried table
+ * from the PGLite source into the fenced Postgres target verbatim, primary
+ * keys and every column preserved.
+ *
+ * - Per-column contract: source and target columns must match by name, type
+ * and typmod (`format_type`) and generation expression, outside the
+ * inventory entry's `columnAllowlist`; generated columns are never inserted.
+ * - Each table copies in one target transaction that carries the run's fence
+ * identity (`gbrain.graduation_run`), bypasses user triggers
+ * (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name
+ * inside the same transaction, never the fence), deletes the target's rows
+ * for that table (initSchema seed rows included; config keeps its
+ * target-owned keys) and inserts the source rows.
+ * - Values travel as canonical text and are cast back with the column's own
+ * type, one jsonb parameter per batch (far below the 65,535 bind-parameter
+ * limit), batches sized by bytes. Source batches are keyset-ordered by
+ * primary key with `COLLATE "C"` under UTC/ISO rendering settings.
+ * - Self-referencing FKs copy in one pass under replica mode (no FK triggers)
+ * and in two passes (insert with NULL, then update) under DISABLE TRIGGER,
+ * where FK checks stay active.
+ * - Inventory transforms (lease and claim resets) are applied from
+ * `COPY_TRANSFORMS`; the digest applies the same expressions to the source.
+ * - Sequences are set to the source's exact position, raised to the target
+ * column maximum when that is higher.
+ * - HNSW and GIN indexes are dropped before the copy and rebuilt after it; the
+ * pending list lives in a target-owned config row so a crash resumes it.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { ANN_BUILD_MESSAGE, buildDeferredAnnIndexes, type DeferredAnnIndex } from '../embedding-ann-build.ts';
+import type { GraduationEngines, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';
+import { graduationError } from './graduation-target.ts';
+
+export const GRADUATION_DEFERRED_INDEXES_KEY = 'graduation.deferred_indexes';
+/** Config keys each engine owns: the target keeps its own values and the copy never writes them. */
+export const TARGET_OWNED_CONFIG_KEYS: readonly string[] = ['engine', 'version', GRADUATION_DEFERRED_INDEXES_KEY];
+/** Default copy batch size in bytes of canonical text. */
+export const DEFAULT_COPY_BATCH_BYTES = 4 * 1024 * 1024;
+const MAX_BATCH_ROWS = 5000;
+const FENCE_TRIGGER_PREFIX = 'gbrain_graduation_fence';
+const RENDER_SETTINGS = ["SET LOCAL TimeZone = 'UTC'", "SET LOCAL DateStyle = 'ISO'", 'SET LOCAL extra_float_digits = 3', "SET LOCAL IntervalStyle = 'postgres'", "SET LOCAL bytea_output = 'hex'"];
+
+/** Rows of a carried table that are not copied (and not digested): the target-owned config keys. */
+export function carryRowFilter(relation: string): string | null {
+ if (relation !== 'config') return null;
+ return `NOT (key = ANY (ARRAY[${TARGET_OWNED_CONFIG_KEYS.map(k => `'${k.replace(/'/g, "''")}'`).join(', ')}]::text[]))`;
+}
+
+export interface CopyTransform {
+ rule: string;
+ /** SQL over the typed source values; `col(name)` renders another column of the same row. */
+ sql: (col: (name: string) => string) => string;
+}
+
+const activeJob = (col: (name: string) => string, column: string) => `CASE WHEN ${col('status')} = 'active' THEN NULL ELSE ${col(column)} END`;
+const claimedEffect = (col: (name: string) => string, column: string) => `CASE WHEN ${col('state')} IN ('running', 'queued') THEN NULL ELSE ${col(column)} END`;
+
+/**
+ * Every column transform graduation may apply, keyed `relation.column`. An
+ * inventory entry lists the ones it uses; verify applies the same SQL to the
+ * source snapshot, so nothing else may differ.
+ */
+export const COPY_TRANSFORMS: Readonly<Record<string, CopyTransform>> = {
+ 'minion_jobs.status': { rule: 'active -> waiting', sql: col => `CASE WHEN ${col('status')} = 'active' THEN 'waiting' ELSE ${col('status')} END` },
+ 'minion_jobs.lock_token': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'lock_token') },
+ 'minion_jobs.lock_until': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'lock_until') },
+ 'minion_jobs.timeout_at': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'timeout_at') },
+ 'minion_jobs.started_at': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'started_at') },
+ 'persistence_worktrees.heartbeat_at': { rule: 'reset', sql: () => 'NULL' },
+ 'persistence_effects.state': { rule: 'running -> queued', sql: col => `CASE WHEN ${col('state')} = 'running' THEN 'queued' ELSE ${col('state')} END` },
+ 'persistence_effects.execution_token': { rule: 'cleared on running and queued effects', sql: col => claimedEffect(col, 'execution_token') },
+ 'persistence_effects.claim_expires_at': { rule: 'cleared on running and queued effects', sql: col => claimedEffect(col, 'claim_expires_at') },
+ 'persistence_brain.enabled': { rule: 'false until cutover', sql: () => 'false' },
+};
+
+export function transformFor(relation: string, column: string): CopyTransform {
+ const transform = COPY_TRANSFORMS[`${relation}.${column}`];
+ if (!transform) throw new Error(`graduation inventory lists a transform for ${relation}.${column} that the copier does not implement`);
+ return transform;
+}
+
+export interface ColumnMeta {
+ name: string;
+ ident: string;
+ type: string;
+ generated: boolean;
+ generationExpr: string | null;
+ collatable: boolean;
+}
+
+type Sql = Pick<BrainEngine, 'executeRaw'>;
+
+async function relationIdent(engine: Sql, relation: string): Promise<string> {
+ const [row] = await engine.executeRaw<{ ident: string; exists: boolean }>(
+ "SELECT format('%I', $1::text) AS ident, to_regclass(format('public.%I', $1::text)) IS NOT NULL AS exists", [relation]);
+ if (!row?.exists) throw new Error(`relation ${relation} does not exist`);
+ return row.ident;
+}
+
+export async function tableColumns(engine: Sql, relation: string): Promise<ColumnMeta[]> {
+ const rows = await engine.executeRaw<{ name: string; ident: string; type: string; generated: boolean; generation_expr: string | null; collatable: boolean }>(
+ `SELECT a.attname AS name, format('%I', a.attname) AS ident, format_type(a.atttypid, a.atttypmod) AS type,
+ a.attgenerated <> '' AS generated, CASE WHEN a.attgenerated <> '' THEN pg_get_expr(d.adbin, d.adrelid) END AS generation_expr,
+ t.typcollation <> 0 AS collatable
+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
+ WHERE a.attrelid = to_regclass(format('public.%I', $1::text)) AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, [relation]);
+ return rows.map(r => ({ name: r.name, ident: r.ident, type: r.type, generated: r.generated === true, generationExpr: r.generation_expr, collatable: r.collatable === true }));
+}
+
+async function constraintColumns(engine: Sql, relation: string, kind: 'p' | 'f-self'): Promise<string[]> {
+ const rows = await engine.executeRaw<{ name: string }>(kind === 'p'
+ ? `SELECT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) WITH ORDINALITY AS u(attnum, ord)
+ JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum
+ WHERE k.contype = 'p' AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY u.ord`
+ : `SELECT DISTINCT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) AS u(attnum)
+ JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum
+ WHERE k.contype = 'f' AND k.conrelid = k.confrelid AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY 1`, [relation]);
+ return rows.map(r => r.name);
+}
+
+const normalizeExpr = (expr: string | null) => (expr ?? '').replace(/\s+/g, ' ').trim();
+
+/**
+ * The per-column contract: every non-allowlisted column must exist on both
+ * sides with the same type and typmod, and generated columns must carry the
+ * same expression. Returns the columns the copy inserts (source order).
+ */
+export function columnContract(entry: Pick<InventoryEntry, 'relation' | 'columnAllowlist'>, source: readonly ColumnMeta[], target: readonly ColumnMeta[]): ColumnMeta[] {
+ const allow = entry.columnAllowlist ?? {};
+ const targetByName = new Map(target.map(c => [c.name, c]));
+ const sourceNames = new Set(source.map(c => c.name));
+ const problems: string[] = [];
+ const copied: ColumnMeta[] = [];
+ for (const column of source) {
+ const other = targetByName.get(column.name);
+ if (column.name in allow) { if (other && !other.generated && !column.generated && other.type === column.type) copied.push(column); continue; }
+ if (!other) { problems.push(`${column.name} (${column.type}) is missing on the target`); continue; }
+ if (other.type !== column.type) { problems.push(`${column.name} is ${column.type} on the source but ${other.type} on the target`); continue; }
+ if (other.generated !== column.generated || normalizeExpr(other.generationExpr) !== normalizeExpr(column.generationExpr)) {
+ problems.push(`${column.name} generation differs (source ${column.generationExpr ?? 'not generated'}, target ${other.generationExpr ?? 'not generated'})`);
+ continue;
+ }
+ if (!column.generated) copied.push(column);
+ }
+ for (const column of target) {
+ if (!sourceNames.has(column.name) && !(column.name in allow)) problems.push(`${column.name} (${column.type}) exists only on the target`);
+ }
+ if (problems.length) {
+ throw graduationError('graduation_target_unsupported', `The target's ${entry.relation} columns do not match the source.`,
+ 'Use an empty target database created by this gbrain version; the column contract never copies into a different shape.',
+ { why: `Graduation copies every column verbatim; ${entry.relation}: ${problems.join('; ')}.`, detail: problems.join('; '),
+ fix: { argv: ['gbrain', 'migrate', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Re-plans after the target is replaced or its schema is upgraded.', verify: { argv: ['gbrain', 'migrate', '--plan', '--json'] } } });
+ }
+ return copied;
+}
+
+export async function detectTriggerBypass(target: BrainEngine): Promise<TriggerBypass | null> {
+ const rollback = Symbol('rollback');
+ try {
+ await target.transaction(async tx => { await tx.executeRaw('SET LOCAL session_replication_role = replica'); throw rollback; });
+ } catch (error) {
+ if (error === rollback) return 'session_replication_role';
+ }
+ const [row] = await target.executeRaw<{ owns: boolean }>(`SELECT COALESCE(bool_and(pg_has_role(current_user, c.relowner, 'USAGE')), true) AS owns
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')`);
+ return row?.owns ? 'disable_trigger' : null;
+}
+
+async function setFence(tx: Sql, runId: string): Promise<void> {
+ await tx.executeRaw("SELECT set_config('gbrain.graduation_run', $1::text, true)", [runId]);
+}
+
+/** The run id the target fence admits: explicit, else the target's `persistence_graduation` row. */
+async function fenceRunId(target: Sql, explicit?: string): Promise<string | null> {
+ if (explicit) return explicit;
+ const [table] = await target.executeRaw<{ present: boolean }>("SELECT to_regclass('public.persistence_graduation') IS NOT NULL AS present");
+ if (!table?.present) return null;
+ const [row] = await target.executeRaw<{ run_id: string }>('SELECT run_id::text AS run_id FROM persistence_graduation LIMIT 1');
+ return row?.run_id ?? null;
+}
+
+type TriggerState = { ident: string; enabled: string };
+
+async function userTriggers(tx: Sql, relation: string, enabledOnly: boolean): Promise<TriggerState[]> {
+ return tx.executeRaw<TriggerState>(`SELECT format('%I', tgname) AS ident, tgenabled::text AS enabled FROM pg_trigger
+ WHERE tgrelid = to_regclass(format('public.%I', $1::text)) AND NOT tgisinternal AND tgname NOT LIKE '${FENCE_TRIGGER_PREFIX}%'
+ ${enabledOnly ? "AND tgenabled <> 'D'" : "AND tgenabled = 'D'"} ORDER BY tgname`, [relation]);
+}
+
+const ENABLE_BY_MODE: Readonly<Record<string, string>> = { O: 'ENABLE TRIGGER', A: 'ENABLE ALWAYS TRIGGER', R: 'ENABLE REPLICA TRIGGER' };
+
+/**
+ * Copies one carried (or rebind) table into the fenced target in a single
+ * transaction and returns the number of source rows copied.
+ */
+export async function copyTable(e: GraduationEngines, entry: InventoryEntry,
+ opts: { bypass: TriggerBypass; batchBytes?: number; onBatch?: (rows: number) => void; runId: string }): Promise<{ rows: number }> {
+ if (entry.class !== 'carry' && entry.class !== 'rebind') throw new Error(`copyTable: ${entry.relation} is ${entry.class}, not carried`);
+ const relation = entry.relation;
+ const sourceColumns = await tableColumns(e.source, relation);
+ const targetColumns = await tableColumns(e.target, relation);
+ if (!sourceColumns.length) throw new Error(`copyTable: ${relation} does not exist on the source`);
+ const columns = columnContract(entry, sourceColumns, targetColumns);
+ const pk = await constraintColumns(e.source, relation, 'p');
+ if (!pk.length) throw new Error(`copyTable: ${relation} has no primary key; the keyset copy needs one`);
+ const transforms = new Map(entry.transforms.map(t => [t.column, transformFor(relation, t.column)]));
+ const selfFk = opts.bypass === 'disable_trigger' ? (await constraintColumns(e.target, relation, 'f-self')).filter(c => columns.some(col => col.name === c)) : [];
+ const sourceIdent = await relationIdent(e.source, relation);
+ const targetIdent = await relationIdent(e.target, relation);
+ const filter = carryRowFilter(relation);
+ const index = new Map(columns.map((c, i) => [c.name, i]));
+ const pkColumns = pk.map(name => {
+ const column = columns.find(c => c.name === name);
+ if (!column) throw new Error(`copyTable: primary key column ${relation}.${name} is not copied`);
+ return column;
+ });
+ const typed = (name: string) => {
+ const i = index.get(name);
+ if (i === undefined) throw new Error(`copyTable: ${relation}.${name} is not a copied column`);
+ return `((r.v->>${i})::${columns[i]!.type})`;
+ };
+ const insertExprs = columns.map(c => selfFk.includes(c.name) ? 'NULL' : transforms.get(c.name)?.sql(typed) ?? typed(c.name));
+ const insertSql = `INSERT INTO ${targetIdent} (${columns.map(c => c.ident).join(', ')}) SELECT ${insertExprs.join(', ')} FROM jsonb_array_elements($1::jsonb) AS r(v)`;
+ const orderBy = pkColumns.map(c => c.collatable ? `${c.ident} COLLATE "C"` : c.ident).join(', ');
+ const keyset = `(${orderBy}) > (${pkColumns.map((c, j) => `$${j + 1}::${c.type}${c.collatable ? ' COLLATE "C"' : ''}`).join(', ')})`;
+ const batchBytes = opts.batchBytes ?? DEFAULT_COPY_BATCH_BYTES;
+
+ const selectList = columns.map((c, i) => `${c.ident}::text AS c${i}`).join(', ');
+ const scan = async (extraWhere: string | null, visit: (rows: Array<Array<string | null>>) => Promise<void>) => {
+ let limit = 100;
+ let last: Array<string | null> | null = null;
+ for (;;) {
+ const where: string[] = [filter, extraWhere, last ? keyset : null].filter((w): w is string => !!w);
+ const sql: string = `SELECT ${selectList} FROM ${sourceIdent}${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY ${orderBy} LIMIT ${limit}`;
+ const params: Array<string | null> = last ? pkColumns.map(c => last![index.get(c.name)!]!) : [];
+ const rows: Array<Record<string, string | null>> = await e.source.transaction(async tx => {
+ for (const setting of RENDER_SETTINGS) await tx.executeRaw(setting);
+ return tx.executeRaw<Record<string, string | null>>(sql, params);
+ });
+ if (!rows.length) return;
+ const values: Array<Array<string | null>> = rows.map(row => columns.map((_, i) => row[`c${i}`] ?? null));
+ await visit(values);
+ if (rows.length < limit) return;
+ last = values[values.length - 1]!;
+ const bytes = values.reduce((sum, row) => sum + row.reduce((s, v) => s + (v?.length ?? 4) + 3, 2), 0);
+ limit = Math.max(1, Math.min(MAX_BATCH_ROWS, Math.floor(batchBytes * rows.length / Math.max(1, bytes))));
+ }
+ };
+
+ return e.target.transaction(async tx => {
+ await setFence(tx, opts.runId);
+ const disabled = opts.bypass === 'disable_trigger' ? await userTriggers(tx, relation, true) : [];
+ if (opts.bypass === 'session_replication_role') await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${targetIdent} DISABLE TRIGGER ${trigger.ident}`);
+ await tx.executeRaw(`DELETE FROM ${targetIdent}${filter ? ` WHERE ${filter}` : ''}`);
+ let copied = 0;
+ await scan(null, async rows => {
+ await tx.executeRaw(insertSql, [JSON.stringify(rows)]);
+ copied += rows.length;
+ opts.onBatch?.(rows.length);
+ });
+ if (selfFk.length) {
+ const fkColumns = selfFk.map(name => columns[index.get(name)!]!);
+ const updateSql = `UPDATE ${targetIdent} AS t SET ${fkColumns.map((c, j) => `${c.ident} = (r.v->>${pkColumns.length + j})::${c.type}`).join(', ')}
+ FROM jsonb_array_elements($1::jsonb) AS r(v) WHERE ${pkColumns.map((c, j) => `t.${c.ident} = (r.v->>${j})::${c.type}`).join(' AND ')}`;
+ await scan(`(${fkColumns.map(c => `${c.ident} IS NOT NULL`).join(' OR ')})`, async rows => {
+ const payload = rows.map(row => [...pkColumns.map(c => row[index.get(c.name)!]), ...fkColumns.map(c => row[index.get(c.name)!] ?? null)]);
+ await tx.executeRaw(updateSql, [JSON.stringify(payload)]);
+ });
+ }
+ for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${targetIdent} ${ENABLE_BY_MODE[trigger.enabled] ?? 'ENABLE TRIGGER'} ${trigger.ident}`);
+ return { rows: copied };
+ });
+}
+
+export interface SequencePosition { sequence: string; value: string; isCalled: boolean; raisedToColumnMax: boolean }
+
+/**
+ * Sets every source sequence present on the target to the source's exact
+ * position (`last_value`, `is_called`), raised to the maximum of every target
+ * column it feeds when that is higher, so a value consumed by an aborted source
+ * transaction is never reissued. Sequences absent on the target are skipped.
+ */
+export async function copySequences(e: GraduationEngines, opts: { runId?: string } = {}): Promise<readonly SequencePosition[]> {
+ const sequences = await e.source.executeRaw<{ name: string; ident: string }>(`SELECT c.relname AS name, format('%I', c.relname) AS ident
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind = 'S' ORDER BY c.relname`);
+ const runId = await fenceRunId(e.target, opts.runId);
+ const positions: SequencePosition[] = [];
+ await e.target.transaction(async tx => {
+ if (runId) await setFence(tx, runId);
+ for (const seq of sequences) {
+ const [present] = await tx.executeRaw<{ present: boolean }>("SELECT to_regclass(format('public.%I', $1::text)) IS NOT NULL AS present", [seq.name]);
+ if (!present?.present) continue;
+ const [position] = await e.source.executeRaw<{ last_value: string; is_called: boolean }>(`SELECT last_value::text AS last_value, is_called FROM ${seq.ident}`);
+ const feeds = await tx.executeRaw<{ table_ident: string; column_ident: string }>(`SELECT DISTINCT format('%I', t.relname) AS table_ident, format('%I', a.attname) AS column_ident
+ FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
+ WHERE d.classid = 'pg_class'::regclass AND d.objid = to_regclass(format('public.%I', $1::text)) AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i')
+ UNION
+ SELECT DISTINCT format('%I', t.relname), format('%I', a.attname)
+ FROM pg_depend d JOIN pg_attrdef ad ON ad.oid = d.objid JOIN pg_class t ON t.oid = ad.adrelid JOIN pg_attribute a ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
+ WHERE d.classid = 'pg_attrdef'::regclass AND d.refobjid = to_regclass(format('public.%I', $1::text))`, [seq.name]);
+ let value = BigInt(position!.last_value);
+ let isCalled = position!.is_called === true;
+ let raised = false;
+ for (const feed of feeds) {
+ const [max] = await tx.executeRaw<{ max: string | null }>(`SELECT max(${feed.column_ident})::text AS max FROM ${feed.table_ident}`);
+ if (max?.max && /^-?\d+$/.test(max.max) && BigInt(max.max) > value - (isCalled ? 0n : 1n)) {
+ value = BigInt(max.max); isCalled = true; raised = true;
+ }
+ }
+ await tx.executeRaw(`SELECT setval(to_regclass(format('public.%I', $1::text)), $2::bigint, $3::boolean)`, [seq.name, value.toString(), isCalled]);
+ positions.push({ sequence: seq.name, value: value.toString(), isCalled, raisedToColumnMax: raised });
+ }
+ });
+ return positions;
+}
+
+export interface DeferredIndex { name: string; relation: string; method: 'hnsw' | 'gin'; def: string }
+
+async function readDeferred(engine: Sql): Promise<DeferredIndex[]> {
+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1', [GRADUATION_DEFERRED_INDEXES_KEY]);
+ if (!row?.value) return [];
+ const parsed = JSON.parse(row.value) as unknown;
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((d): d is DeferredIndex => !!d && typeof d.name === 'string' && typeof d.def === 'string' && typeof d.relation === 'string'
+ && (d.method === 'hnsw' || d.method === 'gin') && /^CREATE INDEX [a-z_][a-z0-9_]* ON public\.[a-z_][a-z0-9_]* USING (hnsw|gin) \(/.test(d.def) && !d.def.includes(';'));
+}
+
+async function writeDeferred(engine: BrainEngine, pending: readonly DeferredIndex[], runId: string | null): Promise<void> {
+ await engine.transaction(async tx => {
+ if (runId) await setFence(tx, runId);
+ if (pending.length) {
+ await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
+ [GRADUATION_DEFERRED_INDEXES_KEY, JSON.stringify(pending)]);
+ } else {
+ await tx.executeRaw('DELETE FROM config WHERE key = $1', [GRADUATION_DEFERRED_INDEXES_KEY]);
+ }
+ });
+}
+
+/**
+ * Drops every non-unique HNSW and GIN index on the target's public tables and
+ * records their definitions in the target-owned `graduation.deferred_indexes`
+ * config row, in one transaction. Re-running merges with an existing list.
+ */
+export async function deferIndexes(target: BrainEngine, opts: { runId?: string } = {}): Promise<readonly DeferredIndex[]> {
+ const runId = await fenceRunId(target, opts.runId);
+ return target.transaction(async tx => {
+ if (runId) await setFence(tx, runId);
+ const found = await tx.executeRaw<{ name: string; ident: string; relation: string; method: 'hnsw' | 'gin'; def: string }>(`SELECT i.relname AS name,
+ format('%I', i.relname) AS ident, t.relname AS relation, am.amname AS method, pg_get_indexdef(i.oid) AS def
+ FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid
+ JOIN pg_namespace n ON n.oid = t.relnamespace JOIN pg_am am ON am.oid = i.relam
+ WHERE n.nspname = 'public' AND am.amname IN ('hnsw', 'gin') AND NOT x.indisunique
+ AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conindid = i.oid) ORDER BY t.relname, i.relname`);
+ const byName = new Map((await readDeferred(tx)).map(d => [d.name, d]));
+ for (const index of found) byName.set(index.name, { name: index.name, relation: index.relation, method: index.method, def: index.def });
+ const pending = [...byName.values()];
+ if (pending.length) {
+ await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
+ [GRADUATION_DEFERRED_INDEXES_KEY, JSON.stringify(pending)]);
+ }
+ for (const index of found) await tx.executeRaw(`DROP INDEX ${index.ident}`);
+ return pending;
+ });
+}
+
+/**
+ * Builds the deferred indexes one at a time, removing each from the pending
+ * row once valid, so a killed run resumes where it stopped. HNSW indexes go
+ * through the deferred-ANN build of `gbrain migrate embeddings` (invalid
+ * remnant cleanup, CONCURRENTLY on Postgres, per-type dimension caps); GIN
+ * indexes build plainly without a statement timeout.
+ */
+export async function buildDeferredIndexes(target: BrainEngine, opts: { runId?: string; log?: (line: string) => void } = {}): Promise<{ built: readonly string[] }> {
+ const runId = await fenceRunId(target, opts.runId);
+ const built: string[] = [];
+ for (const index of await readDeferred(target)) {
+ if (index.method === 'hnsw') {
+ const column = /USING hnsw \(([a-z_][a-z0-9_]*) /.exec(index.def)?.[1];
+ const [dims] = await target.executeRaw<{ dims: number }>(`SELECT a.atttypmod AS dims FROM pg_attribute a
+ WHERE a.attrelid = to_regclass(format('public.%I', $1::text)) AND a.attname = $2`, [index.relation, column ?? '']);
+ const targetDims = Number(dims?.dims ?? 0);
+ if (!(targetDims > 0)) throw new Error(`deferred index ${index.name}: ${index.relation}.${column} has no vector dimension on the target`);
+ const ann: DeferredAnnIndex = { name: index.name, def: index.def };
+ const result = await buildDeferredAnnIndexes(target, {
+ targetDims, readPending: async () => [ann], writePending: async () => {},
+ log: opts.log ?? (line => process.stderr.write(`${line.replace(`[migrate] ${ANN_BUILD_MESSAGE}`, '[graduation] building deferred vector index')}\n`)),
+ });
+ if (result.skipped_over_cap.length) throw new Error(`deferred index ${index.name} exceeds the HNSW dimension cap on the target`);
+ } else {
+ await target.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL statement_timeout = 0');
+ await tx.executeRaw(index.def.replace(/^CREATE INDEX /, 'CREATE INDEX IF NOT EXISTS '));
+ });
+ }
+ built.push(index.name);
+ await writeDeferred(target, (await readDeferred(target)).filter(d => d.name !== index.name), runId);
+ }
+ return { built };
+}
+
+/**
+ * Re-enables user triggers left disabled on the given relations (never the
+ * graduation fence). The copier disables and re-enables inside each table's
+ * transaction, so this only repairs a target someone else left disabled.
+ */
+export async function reenableTriggers(target: BrainEngine, relations: readonly string[], opts: { runId?: string } = {}): Promise<readonly string[]> {
+ const runId = await fenceRunId(target, opts.runId);
+ const enabled: string[] = [];
+ await target.transaction(async tx => {
+ if (runId) await setFence(tx, runId);
+ for (const relation of relations) {
+ const [present] = await tx.executeRaw<{ present: boolean }>("SELECT to_regclass(format('public.%I', $1::text)) IS NOT NULL AS present", [relation]);
+ if (!present?.present) continue;
+ const ident = await relationIdent(tx, relation);
+ for (const trigger of await userTriggers(tx, relation, false)) {
+ await tx.executeRaw(`ALTER TABLE ${ident} ENABLE TRIGGER ${trigger.ident}`);
+ enabled.push(`${relation}.${trigger.ident}`);
+ }
+ }
+ });
+ return enabled;
+}
diff --git a/src/core/persistence/graduation-drain.ts b/src/core/persistence/graduation-drain.ts
new file mode 100644
index 0000000000..b5970fa18e
--- /dev/null
+++ b/src/core/persistence/graduation-drain.ts
@@ -0,0 +1,164 @@
+/**
+ * Engine graduation drain: under the PGLite kernel lock, queued, running and
+ * recovering requests this host owns are published to terminal states by a
+ * request-only consumer (no effect, projection, topology or maintenance
+ * workers), bounded by `--drain-timeout`, behind the consumer's stop barrier.
+ * Effects, connector holds and leases are carried or classified, never waited
+ * on. After the drain the source is frozen read-only for the copy.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { PersistenceConsumer } from './consumer.ts';
+import { disposePersistenceConsumer, preparePersistedMutation } from './service.ts';
+import { readWriterAdminLock } from './admin-lock.ts';
+import type { GraduationBlocker } from './engine-graduation.types.ts';
+import { graduationError } from './graduation-target.ts';
+import type { OperationError } from '../ops/contract.ts';
+
+const PENDING_REQUESTS_SQL = `SELECT r.request_id::text AS request_id, r.source_id, r.operation, r.state,
+ r.recovery IS NOT NULL AS recovering, w.owner_host_id::text AS owner_host_id
+ FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id = r.worktree_id
+ WHERE r.state IN ('queued', 'running', 'recovering') OR r.recovery IS NOT NULL
+ ORDER BY r.sequence`;
+
+type PendingRequest = { request_id: string; source_id: string; operation: string; state: string; recovering: boolean; owner_host_id: string | null };
+
+/**
+ * Everything that keeps graduation from copying, each with its graduation
+ * action. Read-only. Queued, running and recovering requests owned by this
+ * host are `request` blockers the drain itself clears (recovering ones carry
+ * the retry command for when the drain cannot finish them); requests and host
+ * bindings owned by another host, recovering topology changes, recovering
+ * effects and the writer admin lock need someone else to act first.
+ */
+export async function graduationBlockers(source: BrainEngine, hostId: string): Promise<readonly GraduationBlocker[]> {
+ const blockers: GraduationBlocker[] = [];
+ const lock = await readWriterAdminLock(source);
+ if (lock.locked) {
+ blockers.push({ kind: 'writer_admin_lock', id: 'persistence.writer_admin_lock', detail: `writer administration locked at ${lock.set_at ?? 'unknown time'}`,
+ argv: ['gbrain', 'sources', 'writer', 'unlock'], needsUser: true });
+ }
+ for (const r of await source.executeRaw<PendingRequest>(PENDING_REQUESTS_SQL)) {
+ const detail = `${r.operation} ${r.state}${r.recovering ? ', recovering' : ''} (source ${r.source_id})`;
+ if (r.owner_host_id && r.owner_host_id !== hostId) {
+ blockers.push({ kind: 'foreign_host_binding', id: r.request_id, detail: `${detail} is bound to a worktree owned by host ${r.owner_host_id}`,
+ argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', r.source_id], needsUser: true });
+ } else if (r.recovering || r.state === 'recovering') {
+ blockers.push({ kind: 'request', id: r.request_id, detail, argv: ['gbrain', 'sync', '--source', r.source_id, '--no-pull', '--retry-failed'], needsUser: false });
+ } else {
+ blockers.push({ kind: 'request', id: r.request_id, detail, needsUser: false });
+ }
+ }
+ const topology = await source.executeRaw<{ id: string; operation: string; source_id: string }>(
+ "SELECT id::text AS id, operation, source_id FROM persistence_topology_changes WHERE state = 'recovering' OR recovery IS NOT NULL ORDER BY created_at");
+ for (const t of topology) {
+ blockers.push({ kind: 'topology_recovery', id: t.id, detail: `${t.operation} for ${t.source_id} is recovering`,
+ argv: ['gbrain', 'sources', 'writer', 'status', t.source_id, '--json'], needsUser: false });
+ }
+ const effects = await source.executeRaw<{ id: string; kind: string; state: string; source_id: string | null; request_id: string }>(
+ `SELECT e.id::text AS id, e.kind, e.state, COALESCE(e.source_id, r.source_id) AS source_id, r.request_id::text AS request_id
+ FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id WHERE e.recovery IS NOT NULL ORDER BY e.id`);
+ for (const e of effects) {
+ const sourceId = e.source_id ?? 'default';
+ blockers.push({ kind: 'effect_recovery', id: e.id, detail: `${e.kind} effect ${e.state} for request ${e.request_id} is recovering`,
+ argv: e.kind === 'embedding' ? ['gbrain', 'repair', 'embedding-effects', '--source', sourceId]
+ : ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'], needsUser: false });
+ }
+ const bindings = await source.executeRaw<{ worktree_id: string; host_id: string; source_id: string | null }>(
+ `SELECT b.worktree_id::text AS worktree_id, b.host_id::text AS host_id,
+ (SELECT s.source_id FROM persistence_source_bindings s WHERE s.worktree_id = b.worktree_id ORDER BY s.source_id LIMIT 1) AS source_id
+ FROM persistence_host_bindings b WHERE b.host_id <> $1::uuid ORDER BY b.worktree_id, b.host_id`, [hostId]);
+ for (const b of bindings) {
+ blockers.push({ kind: 'foreign_host_binding', id: `${b.worktree_id}:${b.host_id}`, detail: `worktree ${b.worktree_id} has a binding on host ${b.host_id}`,
+ argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', b.source_id ?? b.worktree_id], needsUser: true });
+ }
+ return blockers;
+}
+
+/** Blockers the request-only drain can clear by itself. */
+function drainable(blocker: GraduationBlocker): boolean {
+ return blocker.kind === 'request';
+}
+
+/**
+ * Drains this host's requests with a request-only consumer. Any blocker the
+ * drain cannot clear is returned before anything starts. The consumer's stop
+ * barrier always runs before return, so no publication is in flight when the
+ * caller freezes and copies the source. `drained` lists the request ids that
+ * reached a terminal state; `blockers` is the re-read blocker list (empty on
+ * success).
+ */
+export async function drainForGraduation(source: BrainEngine, opts: { timeoutMs: number; hostId: string; config: GBrainConfig; pollMs?: number }):
+ Promise<{ drained: readonly string[]; blockers: readonly GraduationBlocker[] }> {
+ const initial = await graduationBlockers(source, opts.hostId);
+ if (initial.some(b => !drainable(b))) return { drained: [], blockers: initial };
+ const pending = initial.map(b => b.id);
+ if (!pending.length) return { drained: [], blockers: [] };
+ await disposePersistenceConsumer(source);
+ const pollMs = opts.pollMs ?? 100;
+ let lastError: string | undefined;
+ const consumer = new PersistenceConsumer(source, opts.config, preparePersistedMutation, {
+ hostId: opts.hostId, requestsOnly: true, pollMs, idleMaxMs: pollMs * 5,
+ onError: error => { lastError = String((error as { code?: unknown } | null)?.code ?? 'storage_error'); },
+ });
+ const deadline = Date.now() + opts.timeoutMs;
+ consumer.start();
+ try {
+ while (Date.now() < deadline) {
+ const [row] = await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests
+ WHERE request_id::text = ANY($1::text[]) AND (state IN ('queued', 'running', 'recovering') OR recovery IS NOT NULL)`, [pending]);
+ if (Number(row?.n ?? 0) === 0) break;
+ consumer.wake();
+ await new Promise(resolve => setTimeout(resolve, pollMs));
+ }
+ } finally {
+ await consumer.stop();
+ }
+ const terminal = await source.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests
+ WHERE request_id::text = ANY($1::text[]) AND state NOT IN ('queued', 'running', 'recovering') AND recovery IS NULL ORDER BY sequence`, [pending]);
+ const blockers = (await graduationBlockers(source, opts.hostId))
+ .map(b => lastError && b.kind === 'request' ? { ...b, detail: `${b.detail}; last drain error ${lastError}` } : b);
+ return { drained: terminal.map(r => r.request_id), blockers };
+}
+
+/** The `--drain-timeout` refusal: resumable when every blocker is still progressing, otherwise the first person-needed action. */
+export function drainTimeoutError(blockers: readonly GraduationBlocker[], timeoutMs: number): OperationError {
+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000));
+ const needsPerson = blockers.find(b => b.needsUser || b.argv);
+ const resume = ['gbrain', 'migrate', '--resume', '--drain-timeout', String(seconds * 2), '--json'];
+ const listed = blockers.slice(0, 10).map(b => `${b.kind} ${b.id} (${b.detail})${b.argv ? `: ${b.argv.join(' ')}` : ''}`).join(' | ');
+ return graduationError('graduation_drain_timeout', `The drain did not finish within ${seconds}s; ${blockers.length} item(s) remain.`,
+ needsPerson ? `Clear ${needsPerson.kind} ${needsPerson.id} first (${needsPerson.argv?.join(' ') ?? 'see detail'}), then resume.` : `Resume with a longer drain: ${resume.join(' ')}.`,
+ { why: `Graduation copies only a drained brain; the source is unchanged and still writable. Remaining: ${listed}`,
+ detail: listed,
+ fix: needsPerson?.argv
+ ? { argv: [...needsPerson.argv], consent: [], actor: needsPerson.needsUser ? 'user' : 'agent', requires_exclusive: false,
+ why: `Clears ${needsPerson.kind} ${needsPerson.id}, which the request-only drain cannot finish.`,
+ verify: { argv: ['gbrain', 'migrate', '--status', '--json'] } }
+ : { argv: resume, consent: [], actor: 'agent', requires_exclusive: true, why: 'Every remaining request is still progressing; a longer drain finishes it.',
+ verify: { argv: ['gbrain', 'migrate', '--status', '--json'] } } });
+}
+
+/**
+ * Freezes the PGLite source after the drain: the resident consumer is stopped
+ * and the single connection defaults to read-only transactions, so any
+ * in-process background writer fails instead of changing the snapshot being
+ * copied. Source-row custody writes go through `withSourceWritable`.
+ */
+export async function freezeSource(source: BrainEngine): Promise<void> {
+ if (source.kind !== 'pglite') throw new Error('freezeSource applies to the PGLite source of a graduation');
+ await disposePersistenceConsumer(source);
+ await source.executeRaw('SET default_transaction_read_only = on');
+}
+
+export async function unfreezeSource(source: BrainEngine): Promise<void> {
+ await source.executeRaw('SET default_transaction_read_only = off');
+}
+
+/** One read-write transaction on a frozen source (the source-row `quiesced`/`cutover` writes). */
+export async function withSourceWritable<T>(source: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return source.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ WRITE');
+ return fn(tx);
+ });
+}
diff --git a/src/core/persistence/graduation-target.ts b/src/core/persistence/graduation-target.ts
new file mode 100644
index 0000000000..7275819969
--- /dev/null
+++ b/src/core/persistence/graduation-target.ts
@@ -0,0 +1,377 @@
+/**
+ * Engine graduation target side: the two routes to the target database (main
+ * and DDL/direct), the password-free target identity, the read-only target
+ * probes `--plan` reports, and the nonce cross-check that proves both routes
+ * reach the same database before any DDL.
+ *
+ * Secrets: a target URL is read from `--url` or the variable named by
+ * `--url-env`; every display form and every emitted command carries the
+ * redacted URL or `--url-env <VAR>`, never the password. Only the 0600
+ * manifest (written by the orchestrator) stores the full URLs.
+ *
+ * The DDL route is resolved here once (explicit `GBRAIN_DIRECT_DATABASE_URL`,
+ * otherwise the Supabase derivation, otherwise the main URL) and handed to
+ * the connection manager as an explicit override, which disables its
+ * automatic session-pooler fallback for this operation.
+ */
+import postgres from '#postgres';
+import { createHash, randomInt } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { PostgresEngine } from '../postgres-engine.ts';
+import { normalizeDirectUrl, isNetworkUnreachableError } from '../connection-manager.ts';
+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
+import { opError, type OpErrorOpts, type OperationError } from '../ops/contract.ts';
+import type { RegistryCode } from '../error-registry.ts';
+import type { EmbeddingColumn, GraduationBlocker, GraduationErrorCode, TargetIdentity, TargetProbe, TargetRoutes, TriggerBypass } from './engine-graduation.types.ts';
+
+export type ResolvedTargetRoutes = TargetRoutes & { mainUrl: string; ddlUrl: string };
+
+/** The env var every emitted command names instead of a literal URL. */
+export const DEFAULT_TARGET_URL_ENV = 'GBRAIN_TARGET_URL';
+/** Oldest server the copy and the schema are tested against. */
+export const MIN_TARGET_SERVER_VERSION_NUM = 140000;
+/** pgvector release that added halfvec (facts.embedding, query_cache.embedding). */
+export const MIN_VECTOR_HALFVEC_VERSION = '0.7.0';
+
+/** Graduation codes are registered by the agent-contract batch; until then they are typed by the shared list. */
+export function graduationError(code: GraduationErrorCode, message: string, suggestion: string, opts: OpErrorOpts = {}): OperationError {
+ return opError(code as RegistryCode, message, suggestion, opts);
+}
+
+export function targetPlanArgv(routes: Pick<TargetRoutes, 'urlEnv'>, to: 'postgres' | 'supabase' = 'postgres'): string[] {
+ return ['gbrain', 'migrate', '--to', to, '--url-env', routes.urlEnv ?? DEFAULT_TARGET_URL_ENV, '--plan', '--json'];
+}
+
+function parsePostgresUrl(url: string): URL {
+ if (!/^postgres(?:ql)?:\/\//i.test(url)) {
+ throw graduationError('graduation_target_unsupported', 'The target is not a Postgres URL.',
+ 'Pass a postgres:// or postgresql:// URL through --url-env, then rerun the plan.',
+ { why: 'Graduation moves a PGLite brain into a Postgres database; the given value is not a Postgres connection URL.',
+ fix: { argv: targetPlanArgv({}), consent: ['credentials'], actor: 'agent', requires_exclusive: false,
+ why: 'Re-plans against a URL held in an environment variable, so the password never appears in argv.',
+ user_message: `Set ${DEFAULT_TARGET_URL_ENV} to the Postgres URL of the target database (postgres://user:password@host:5432/db).`,
+ verify: { argv: targetPlanArgv({}) } } });
+ }
+ return new URL(url.replace(/^postgres(?:ql)?:\/\//i, 'http://'));
+}
+
+/** Display form: scheme, user, host, port and database; never the password or query parameters. */
+export function redactTargetUrl(url: string): string {
+ try {
+ const parsed = parsePostgresUrl(url);
+ const user = parsed.username ? `${decodeURIComponent(parsed.username)}@` : '';
+ return `postgres://${user}${parsed.hostname}:${parsed.port || '5432'}${parsed.pathname || '/'}`;
+ } catch {
+ return redactConnectionInfo(url);
+ }
+}
+
+export function targetIdentity(url: string): TargetIdentity {
+ const parsed = parsePostgresUrl(url);
+ const host = parsed.hostname.toLowerCase();
+ const port = Number(parsed.port || '5432');
+ const user = decodeURIComponent(parsed.username || '');
+ const database = decodeURIComponent((parsed.pathname || '/').replace(/^\//, '')) || user;
+ const id = createHash('sha256').update(JSON.stringify([host, port, database, user])).digest('hex');
+ return { id, host, port, database, user };
+}
+
+export function resolveTargetRoutes(opts: { url?: string; urlEnv?: string; env?: NodeJS.ProcessEnv }): ResolvedTargetRoutes {
+ const env = opts.env ?? process.env;
+ if (opts.url && opts.urlEnv) {
+ throw graduationError('graduation_target_unsupported', 'Both --url and --url-env were given.',
+ 'Pass the target once, preferably as --url-env <VAR>.',
+ { why: 'Two target sources could name different databases.',
+ fix: { argv: targetPlanArgv({ urlEnv: opts.urlEnv }), consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Re-plans with the target named only by its environment variable.', verify: { argv: targetPlanArgv({ urlEnv: opts.urlEnv }) } } });
+ }
+ const mainUrl = opts.urlEnv ? env[opts.urlEnv] : opts.url;
+ if (!mainUrl) {
+ const urlEnv = opts.urlEnv ?? DEFAULT_TARGET_URL_ENV;
+ throw graduationError('graduation_target_unsupported', opts.urlEnv ? `${opts.urlEnv} is not set.` : 'No target URL was given.',
+ `Set ${urlEnv} to the target Postgres URL and rerun with --url-env ${urlEnv}.`,
+ { why: 'Graduation needs the target database URL; it is read from an environment variable so the password never reaches argv or logs.',
+ fix: { argv: targetPlanArgv({ urlEnv }), consent: ['credentials'], actor: 'agent', requires_exclusive: false,
+ why: 'Plans the move once the variable holds the target URL.',
+ user_message: `Set ${urlEnv} to the Postgres URL of the empty target database.`, verify: { argv: targetPlanArgv({ urlEnv }) } } });
+ }
+ parsePostgresUrl(mainUrl);
+ const ddlUrl = normalizeDirectUrl(mainUrl, env.GBRAIN_DIRECT_DATABASE_URL || null) ?? mainUrl;
+ parsePostgresUrl(ddlUrl);
+ return { main: redactTargetUrl(mainUrl), ddl: redactTargetUrl(ddlUrl), ...(opts.urlEnv ? { urlEnv: opts.urlEnv } : {}), mainUrl, ddlUrl };
+}
+
+function classifyConnectError(error: unknown): { reachable: boolean; auth: boolean; error: { code: string; message: string } } {
+ const code = String((error as { code?: unknown } | null)?.code ?? 'connect_failed');
+ const message = redactConnectionInfo(error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, 200);
+ if (code === '28P01' || code === '28000') return { reachable: true, auth: false, error: { code, message } };
+ if (isNetworkUnreachableError(error) || code === 'connect_failed') return { reachable: false, auth: false, error: { code, message } };
+ return { reachable: true, auth: true, error: { code, message } };
+}
+
+function probeClient(url: string, timeoutSeconds: number) {
+ return postgres(url, { max: 1, prepare: false, connect_timeout: timeoutSeconds, idle_timeout: 1, onnotice: () => {} });
+}
+
+function versionAtLeast(version: string | null, min: string): boolean {
+ if (!version) return false;
+ const a = version.split('.').map(n => Number.parseInt(n, 10) || 0);
+ const b = min.split('.').map(n => Number.parseInt(n, 10) || 0);
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
+ }
+ return true;
+}
+
+type Query = <T>(sql: string, params?: unknown[]) => Promise<T[]>;
+
+/** Tables a fresh initSchema seeds, and the most rows the seed leaves in each. */
+const SEED_ROW_LIMITS: Readonly<Record<string, number>> = {
+ op_checkpoints: 1, page_generation_clock: 1, persistence_brain: 1, shared_skill_state: 1, sources: 1,
+};
+/** Each engine's own schema writes these; they never count against emptiness. */
+const SCHEMA_OWNED_TABLES = new Set(['config', 'file_migration_ledger', 'persistence_graduation']);
+
+/**
+ * A target counts as empty when it has no public tables, or a gbrain schema whose
+ * tables hold only the initSchema seed rows (config, the `default` source, the
+ * disabled persistence identity and the singleton clocks). Read-only.
+ */
+export async function targetEmptiness(query: Query): Promise<{ empty: boolean; nonEmptyTables: string[]; gbrainSchema: boolean }> {
+ const tables = await query<{ name: string; ident: string }>(`SELECT c.relname AS name, quote_ident(c.relname) AS ident
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') ORDER BY c.relname`);
+ const nonEmptyTables: string[] = [];
+ for (const table of tables) {
+ if (SCHEMA_OWNED_TABLES.has(table.name)) continue;
+ const limit = SEED_ROW_LIMITS[table.name] ?? 0;
+ const [row] = await query<{ n: number }>(`SELECT count(*)::int AS n FROM (SELECT 1 FROM ${table.ident} LIMIT ${limit + 1}) s`);
+ if (Number(row?.n ?? 0) > limit) { nonEmptyTables.push(table.name); continue; }
+ if (table.name === 'sources' && Number(row?.n) === 1) {
+ const [seed] = await query<{ ok: boolean }>(`SELECT bool_and(id = 'default') AS ok FROM sources`);
+ if (!seed?.ok) nonEmptyTables.push(table.name);
+ }
+ if (table.name === 'persistence_brain' && Number(row?.n) === 1) {
+ const [seed] = await query<{ ok: boolean }>('SELECT bool_and(NOT enabled) AS ok FROM persistence_brain');
+ if (!seed?.ok) nonEmptyTables.push(table.name);
+ }
+ }
+ return { empty: nonEmptyTables.length === 0, nonEmptyTables, gbrainSchema: tables.some(t => t.name === 'config') };
+}
+
+/** Every vector/halfvec column in the public schema with its dimension. Read-only; works on both engines. */
+export async function embeddingColumns(query: Query): Promise<EmbeddingColumn[]> {
+ const rows = await query<{ relation: string; column: string; type: string; dims: number | null }>(`SELECT c.relname AS relation, a.attname AS column,
+ format_type(a.atttypid, a.atttypmod) AS type, CASE WHEN a.atttypmod > 0 THEN a.atttypmod ELSE NULL END AS dims
+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_type t ON t.oid = a.atttypid
+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND t.typname IN ('vector', 'halfvec')
+ ORDER BY c.relname, a.attname`);
+ return rows.map(r => ({ relation: r.relation, column: r.column, type: r.type, dims: r.dims === null ? null : Number(r.dims) }));
+}
+
+/**
+ * The source's effective embedding layout, which sizes the target schema:
+ * every vector/halfvec column with its typmod plus the embedding config rows
+ * (model, dimensions and the embedding-column registry).
+ */
+export async function sourceEmbeddingLayout(source: BrainEngine): Promise<{ columns: EmbeddingColumn[]; config: Record<string, string> }> {
+ const query: Query = (sql, params) => source.executeRaw(sql, params);
+ const rows = await source.executeRaw<{ key: string; value: string }>(
+ `SELECT key, value FROM config WHERE key IN ('embedding_model', 'embedding_dimensions', 'embedding_columns', 'search_embedding_column') ORDER BY key`);
+ return { columns: await embeddingColumns(query), config: Object.fromEntries(rows.map(r => [r.key, r.value])) };
+}
+
+/** Columns whose type differs between the source layout and an existing target schema. */
+export function embeddingLayoutMismatches(source: readonly EmbeddingColumn[], target: readonly EmbeddingColumn[]): Array<{ relation: string; column: string; source: string; target: string }> {
+ const byKey = new Map(target.map(c => [`${c.relation}.${c.column}`, c]));
+ return source.flatMap(c => {
+ const other = byKey.get(`${c.relation}.${c.column}`);
+ return other && other.type !== c.type ? [{ relation: c.relation, column: c.column, source: c.type, target: other.type }] : [];
+ });
+}
+
+/**
+ * Read-only probes of the target, through one session per route: reachability
+ * and authentication on both routes, server version, the `vector` extension
+ * (installed or available, with halfvec), CREATE privilege, whether
+ * `session_replication_role = replica` is permitted (otherwise the copy needs
+ * table ownership for DISABLE TRIGGER), emptiness and existing embedding
+ * columns. Every query runs inside a READ ONLY transaction; nothing is created.
+ */
+export async function probeTarget(routes: ResolvedTargetRoutes, opts: { timeoutSeconds?: number } = {}): Promise<TargetProbe> {
+ const timeout = opts.timeoutSeconds ?? 10;
+ const probe: TargetProbe = {
+ reachable: false, auth: false, ddl: { reachable: false, auth: false }, serverVersion: null, serverVersionNum: null,
+ vector: { installed: null, available: null, halfvec: false }, createPrivilege: { database: false, schema: false },
+ replicaRole: false, ownsTables: false, triggerBypass: null, gbrainSchema: false, empty: false, nonEmptyTables: [],
+ embeddingColumns: [], otherSessions: 0,
+ };
+ const main = probeClient(routes.mainUrl, timeout);
+ try {
+ await main.begin('read only', async tx => {
+ const query: Query = async <T>(sql: string, params: unknown[] = []) => await tx.unsafe(sql, params as never[]) as unknown as T[];
+ probe.reachable = true; probe.auth = true;
+ const [server] = await query<{ version: string; num: string; db_create: boolean; schema_create: boolean; sessions: number }>(`SELECT
+ current_setting('server_version') AS version, current_setting('server_version_num') AS num,
+ has_database_privilege(current_user, current_database(), 'CREATE') AS db_create,
+ has_schema_privilege(current_user, 'public', 'CREATE') AS schema_create,
+ (SELECT count(*)::int FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()) AS sessions`);
+ probe.serverVersion = server!.version;
+ probe.serverVersionNum = Number(server!.num);
+ probe.createPrivilege = { database: server!.db_create === true, schema: server!.schema_create === true };
+ probe.otherSessions = Number(server!.sessions);
+ const [vector] = await query<{ installed: string | null; available: string | null }>(`SELECT
+ (SELECT extversion FROM pg_extension WHERE extname = 'vector') AS installed,
+ (SELECT default_version FROM pg_available_extensions WHERE name = 'vector') AS available`);
+ probe.vector = { installed: vector?.installed ?? null, available: vector?.available ?? null,
+ halfvec: versionAtLeast(vector?.installed ?? vector?.available ?? null, MIN_VECTOR_HALFVEC_VERSION) };
+ const [owned] = await query<{ ok: boolean }>(`SELECT COALESCE(bool_and(pg_has_role(current_user, c.relowner, 'USAGE')), true) AS ok
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')`);
+ probe.ownsTables = owned?.ok === true;
+ Object.assign(probe, await targetEmptiness(query));
+ probe.embeddingColumns = await embeddingColumns(query);
+ await query('SAVEPOINT gbrain_replica_probe');
+ try { await query('SET LOCAL session_replication_role = replica'); probe.replicaRole = true; }
+ catch { probe.replicaRole = false; }
+ await query('ROLLBACK TO SAVEPOINT gbrain_replica_probe');
+ });
+ } catch (error) {
+ if (!probe.reachable) Object.assign(probe, classifyConnectError(error));
+ else probe.error = classifyConnectError(error).error;
+ } finally {
+ await main.end({ timeout: 1 }).catch(() => {});
+ }
+ probe.triggerBypass = probe.replicaRole ? 'session_replication_role' : probe.ownsTables && probe.createPrivilege.schema ? 'disable_trigger' : null;
+ if (routes.ddlUrl === routes.mainUrl) {
+ probe.ddl = { reachable: probe.reachable, auth: probe.auth, ...(probe.error ? { error: probe.error } : {}) };
+ return probe;
+ }
+ const ddl = probeClient(routes.ddlUrl, timeout);
+ try {
+ await ddl.begin('read only', async tx => { await tx.unsafe('SELECT 1'); });
+ probe.ddl = { reachable: true, auth: true };
+ } catch (error) {
+ probe.ddl = classifyConnectError(error);
+ } finally {
+ await ddl.end({ timeout: 1 }).catch(() => {});
+ }
+ return probe;
+}
+
+/**
+ * Plan blockers from a probe: every unmet target prerequisite, a non-empty
+ * target, and embedding columns whose existing type differs from the source
+ * layout. Unreachable routes and failed authentication are raised by
+ * `assertTargetReachable` instead, because nothing else can be measured then.
+ */
+export function targetProbeBlockers(probe: TargetProbe, routes: Pick<TargetRoutes, 'urlEnv' | 'main'>, sourceColumns: readonly EmbeddingColumn[] = []): GraduationBlocker[] {
+ const argv = targetPlanArgv(routes);
+ const unsupported = (id: string, detail: string): GraduationBlocker => ({ kind: 'target_unsupported', id, detail, argv, needsUser: true });
+ const blockers: GraduationBlocker[] = [];
+ if (probe.serverVersionNum !== null && probe.serverVersionNum < MIN_TARGET_SERVER_VERSION_NUM) {
+ blockers.push(unsupported('server_version', `server ${probe.serverVersion} is older than PostgreSQL 14`));
+ }
+ if (!probe.vector.installed && !probe.vector.available) blockers.push(unsupported('vector_extension', 'the vector extension is neither installed nor available'));
+ else if (!probe.vector.halfvec) blockers.push(unsupported('vector_halfvec', `vector ${probe.vector.installed ?? probe.vector.available} predates halfvec (needs ${MIN_VECTOR_HALFVEC_VERSION} or newer)`));
+ if (!probe.createPrivilege.schema) blockers.push(unsupported('create_privilege', `role cannot CREATE in schema public on ${routes.main}`));
+ if (!probe.vector.installed && !probe.createPrivilege.database) blockers.push(unsupported('create_extension', 'vector is not installed and the role lacks CREATE on the database to install it'));
+ if (!probe.triggerBypass) blockers.push(unsupported('trigger_bypass', 'the role may neither set session_replication_role = replica nor owns the existing tables (needed for DISABLE TRIGGER)'));
+ if (!probe.empty) blockers.push({ kind: 'target_not_empty', id: 'target', detail: `target already holds rows in ${probe.nonEmptyTables.slice(0, 10).join(', ')}`, argv, needsUser: true });
+ for (const m of embeddingLayoutMismatches(sourceColumns, probe.embeddingColumns)) {
+ blockers.push({ kind: 'embedding_dimension', id: `${m.relation}.${m.column}`, detail: `source ${m.source}, target ${m.target}`, argv, needsUser: true });
+ }
+ return blockers;
+}
+
+/** Throws the typed refusal when either route is unreachable or refuses authentication. */
+export function assertTargetReachable(probe: TargetProbe, routes: Pick<TargetRoutes, 'urlEnv' | 'main' | 'ddl'>): void {
+ const urlEnv = routes.urlEnv ?? DEFAULT_TARGET_URL_ENV;
+ const argv = targetPlanArgv(routes);
+ if (probe.reachable && !probe.auth) {
+ throw graduationError('graduation_target_auth_failed', `The target ${routes.main} refused authentication.`,
+ `Ask the user for the current URL of the same database, put it in ${urlEnv} and rerun with --url-env ${urlEnv}.`,
+ { why: `The server answered but rejected the credentials (${probe.error?.code ?? 'auth'}); a rotated password is the usual cause.`,
+ fix: { argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with the corrected URL for the same target identity.',
+ user_message: `The Postgres server at ${routes.main} rejected the password. Set ${urlEnv} to the current URL for this database.`, verify: { argv } } });
+ }
+ if (!probe.reachable) {
+ throw graduationError('graduation_target_unsupported', `The target ${routes.main} is unreachable.`,
+ 'Check that the database is running and reachable from this machine, then rerun the plan.',
+ { why: `Connecting failed before authentication (${probe.error?.code ?? 'unreachable'}: ${probe.error?.message ?? 'no detail'}).`,
+ fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-probes the target once it is reachable.', verify: { argv } } });
+ }
+ if (probe.serverVersion === null) {
+ throw graduationError('graduation_target_unsupported', `The target ${routes.main} could not be probed.`,
+ 'Fix the named connection problem (for example create the database), then rerun the plan.',
+ { why: `The server answered but the probe session failed (${probe.error?.code ?? 'unknown'}: ${probe.error?.message ?? 'no detail'}).`,
+ fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-probes the target after the fix.', verify: { argv } } });
+ }
+ if (!probe.ddl.reachable || !probe.ddl.auth) {
+ throw graduationError('graduation_target_ddl_unreachable', `The DDL connection ${routes.ddl} is unreachable.`,
+ 'Ask the user for a session-mode connection (Supabase: the session pooler on port 5432), set GBRAIN_DIRECT_DATABASE_URL to it and rerun the plan.',
+ { why: `gbrain runs schema changes and the copy on a direct/session connection; it failed (${probe.ddl.error?.code ?? 'unreachable'}). Graduation never falls back to another route on its own.`,
+ fix: { argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with the DDL route the user provides.',
+ user_message: `Set GBRAIN_DIRECT_DATABASE_URL to the session-mode connection URL of ${routes.main}.`, verify: { argv } } });
+ }
+}
+
+/**
+ * Proves the main and DDL engines reach the same database before any DDL: the
+ * DDL route takes a transaction-scoped advisory lock keyed by a fresh nonce
+ * for this run, and the main route must read that exact lock row (same
+ * backend pid, same database) from pg_locks while it is held. A transaction
+ * lock works through any pooler mode and leaves nothing behind.
+ */
+export async function crossCheckRoutes(main: BrainEngine, ddl: BrainEngine, runId: string): Promise<void> {
+ const keys = [randomInt(1, 2 ** 31 - 1), randomInt(1, 2 ** 31 - 1)];
+ const refuse = (detail: string) => graduationError('graduation_target_ddl_unreachable',
+ 'The DDL connection does not reach the same database as the main connection.',
+ 'Ask the user for the session-mode URL of the same database, set GBRAIN_DIRECT_DATABASE_URL to it and rerun the plan.',
+ { why: `Run ${runId}: ${detail}. Schema changes through a different database would leave the target incomplete, so nothing was changed.`,
+ fix: { argv: targetPlanArgv({}), consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with a DDL route that names the target database.',
+ user_message: 'Set GBRAIN_DIRECT_DATABASE_URL to the session-mode connection URL of the target database.', verify: { argv: targetPlanArgv({}) } } });
+ let seen: boolean;
+ try {
+ seen = await ddl.transaction(async tx => {
+ await tx.executeRaw('SELECT 1 FROM (SELECT pg_advisory_xact_lock($1::int4, $2::int4)) AS nonce', keys);
+ const [held] = await tx.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ const [row] = await main.executeRaw<{ seen: boolean }>(`SELECT EXISTS (SELECT 1 FROM pg_locks l
+ WHERE l.locktype = 'advisory' AND l.granted AND l.pid = $1::int AND l.classid = $2::oid AND l.objid = $3::oid AND l.objsubid = 2
+ AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())) AS seen`, [held!.pid, keys[0], keys[1]]);
+ return row?.seen === true;
+ });
+ } catch (error) {
+ throw refuse(`the cross-check failed (${redactConnectionInfo(error instanceof Error ? error.message : String(error)).slice(0, 160)})`);
+ }
+ if (!seen) throw refuse('the nonce lock taken through the DDL route is not visible through the main route');
+}
+
+/**
+ * Connects the main and DDL target engines with the DDL route as an explicit
+ * override, so the connection manager never derives another route or falls
+ * back to the session pooler on its own. The override is read when each
+ * engine's connection manager is built inside `connect()`.
+ */
+export async function connectTargetEngines(routes: ResolvedTargetRoutes, opts: { poolSize?: number } = {}): Promise<{ main: PostgresEngine; ddl: PostgresEngine; close(): Promise<void> }> {
+ const prior = process.env.GBRAIN_DIRECT_DATABASE_URL;
+ const main = new PostgresEngine();
+ const ddl = new PostgresEngine();
+ process.env.GBRAIN_DIRECT_DATABASE_URL = routes.ddlUrl;
+ try {
+ await main.connect({ database_url: routes.mainUrl, poolSize: opts.poolSize ?? 4 });
+ await ddl.connect({ database_url: routes.ddlUrl, poolSize: 2 });
+ } catch (error) {
+ await Promise.allSettled([main.disconnect(), ddl.disconnect()]);
+ throw error;
+ } finally {
+ if (prior === undefined) delete process.env.GBRAIN_DIRECT_DATABASE_URL; else process.env.GBRAIN_DIRECT_DATABASE_URL = prior;
+ }
+ return { main, ddl, close: async () => { await Promise.allSettled([main.disconnect(), ddl.disconnect()]); } };
+}
+
+/** Which bypass a probe allows; `forced` is the `--trigger-bypass` escape hatch and must be permitted. */
+export function chooseTriggerBypass(probe: Pick<TargetProbe, 'replicaRole' | 'triggerBypass'>, forced?: TriggerBypass): TriggerBypass | null {
+ if (forced === 'session_replication_role') return probe.replicaRole ? forced : null;
+ if (forced === 'disable_trigger') return forced;
+ return probe.triggerBypass;
+}