Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): refuse writes migrations_pending/schema_behind while the schema is behind, before the request id is admitted (#6904)
garrytan2577603f3c80
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4067ce61a1..62fad52a51 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2234,9 +2234,9 @@ Reasons: `orchestrator_failed`, `orchestrator_threw`, `ledger_write_failed`, `pr| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. | not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration's partial rows in the brain home's migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`. | agent | `repeat the read that failed` | 1 | no |+| Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles). | schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration's partial rows in the brain home's migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`. | agent | `repeat the read that failed` | 1 | no |-Reasons: `not_applied`, `still_behind`, `schema_unreadable`, `wedged`.+Reasons: `not_applied`, `still_behind`, `schema_unreadable`, `wedged`, `schema_behind`.### migrations_runningdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 13d3766342..0f57277401 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -83,6 +83,7 @@ of making a duplicate.| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. || <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. || <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |+| <a id="schema_behind"></a>`schema_behind` | `migrations_pending` (reason `schema_behind`) | A managed write (`put_page` and every write admitted the same way) was refused before admission because the brain schema is at a lower version than this gbrain build needs: an upgrade installed the new binary but `gbrain apply-migrations` did not finish, often because the database role gbrain connects as does not own the tables. The write path reads tables or columns only the pending migrations add, so publishing now would fail. It is not retryable as is (class `caller`): the same write refuses until the schema is migrated. Nothing was admitted and the request id was not used. A replay of a request id accepted earlier still reconciles, and the `apply-migrations` orchestrators are not refused while they hold the migration lock. | Run `gbrain apply-migrations --yes` on the brain host as the database role that owns the gbrain tables (the fix renders `tell_user_to_run` when this connection's role does not own them), confirm with `gbrain doctor --json` (`schema_version` at head), then resubmit the same write: the same request id commits. A write that already failed on a missing column or table is classified `schema_missing` by `gbrain write-request <request_id> --json`. || <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). || <a id="extract-timeline-refused"></a>timeline extract refused | the printed code, usually `writer_coordinator_required` | `gbrain extract timeline --source db` (or a timeline-only `gbrain extract timeline` on a managed brain) could not write a page's timeline rows. It prints `refused: <code>; nothing written; existing timeline rows are untouched` per page, a summary of written versus refused, and exits 1. The rows import already stored for each page stay as they were. | `gbrain extract --stale` (add `--source-id <id>` when you scoped the run) publishes links and missing timeline rows on the managed path. If it refuses too, follow the row for the printed code. || unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, preview with `gbrain doctor --remediation-plan --json` and, after the user agrees, run `gbrain doctor --remediate --yes --include-repairs --expect <plan_hash> --max-usd <n>`. |diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a75873ca38..0a0e76a3e0 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -392,9 +392,9 @@ export const CODES = {migration_failed: { class: 'server', summary: "A migration orchestrator failed, so the migration chain stopped; finished migrations stay recorded.",reasons: ['orchestrator_failed', 'orchestrator_threw', 'ledger_write_failed', 'preview_failed', 'schema_failed'] },migrations_pending: { class: 'caller', summary: "Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success.",- why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending.',- suggestion: 'not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration\'s partial rows in the brain home\'s migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',- reasons: ['not_applied', 'still_behind', 'schema_unreadable', 'wedged'] },+ why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles).',+ suggestion: 'schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration\'s partial rows in the brain home\'s migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',+ reasons: ['not_applied', 'still_behind', 'schema_unreadable', 'wedged', 'schema_behind'] },migrations_running: { class: 'retryable', summary: "Another apply-migrations run holds the migration orchestration lock.", exit: 75 },missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },missing_source_value: { class: 'caller', summary: "A source flag was given without a value." },diff --git a/src/core/migration-orchestration-lock.ts b/src/core/migration-orchestration-lock.tsindex 0c45dff6fb..da442cf208 100644--- a/src/core/migration-orchestration-lock.ts+++ b/src/core/migration-orchestration-lock.ts@@ -178,6 +178,17 @@ async function acquirePostgres(config: GBrainConfig): Promise<MigrationOrchestra};}+/** #6904: orchestration locks this process holds right now; only acquire/release change it. */+let heldHere = 0;++/**+ * #6904: whether this process holds the orchestration lock. Write admission refuses while the schema is behind this build,+ * except for this process's orchestrators, which may write mid-upgrade while it holds the lock. No caller can set it.+ */+export function migrationOrchestrationHeldHere(): boolean {+ return heldHere > 0;+}+/*** Acquire the orchestration lock or throw MigrationsRunningError. Returns* null only on Postgres when the database is unreachable or@@ -185,11 +196,13 @@ async function acquirePostgres(config: GBrainConfig): Promise<MigrationOrchestra* starts orchestrators.*/export async function acquireMigrationOrchestrationLock(config: GBrainConfig): Promise<MigrationOrchestrationLock | null> {- if (config.engine === 'pglite') {- if (!config.database_path) return { assertHeld: async () => {}, release: async () => {} };- return acquirePglite(config.database_path);- }- return acquirePostgres(config);+ const lock = config.engine === 'pglite'+ ? config.database_path ? await acquirePglite(config.database_path) : { assertHeld: async () => {}, release: async () => {} }+ : await acquirePostgres(config);+ if (!lock) return null;+ heldHere++;+ let released = false;+ return { ...lock, release: async () => { if (!released) { released = true; heldHere--; } await lock.release(); } };}/** Best-effort holder lookup for callers that only saw the runner's exit status. */diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 4f8137ddd1..c6758b0a91 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -27,6 +27,7 @@ import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertGraduationAdmission } from './graduation-custody.ts';+import { schemaAdmissionRefusal } from './schema-admission.ts';import { CAPACITY_VERIFY } from './capacity-verify.ts';import { readManagedMode } from './managed-mode.ts';import { localHostId } from './identity.ts';@@ -294,6 +295,9 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over}return assertReplayIntent(prior, fingerprint);}+ // #6904: only after a replay returned, so an accepted request id reconciles whatever the schema reads.+ const schemaRefusal = await schemaAdmissionRefusal(tx);+ if (schemaRefusal) throw schemaRefusal;if (input.targetKind === 'skill_bundle') await assertSharedSkillPersistence(tx, input.sourceId);for (const row of counters) {const brain = row.key === 'brain';diff --git a/src/core/persistence/schema-admission.ts b/src/core/persistence/schema-admission.tsnew file mode 100644index 0000000000..a46b20c200--- /dev/null+++ b/src/core/persistence/schema-admission.ts@@ -0,0 +1,56 @@+/**+ * #6904: write admission while the brain's schema is behind this build.+ *+ * A build whose write path reads a table or column from a migration the brain has not applied+ * fails at publication with a Postgres 42703/42P01 after spending the caller's request id. So+ * admission reads the schema version (`config.version`) after its guard batch and, when it is+ * below `LATEST_SCHEMA_VERSION`, refuses `migrations_pending` (reason `schema_behind`) before+ * any request row exists: the request id is not consumed and the same id commits once the+ * schema is migrated. A replay of an already accepted id is judged first and still reconciles.+ * The `apply-migrations` orchestrators that write mid-upgrade run while this process holds the+ * orchestration lock and are never refused. A missing or unparsable version is not judged here.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';+import { LATEST_SCHEMA_VERSION } from '../schema-migrations/latest.generated.ts';++export const SCHEMA_BEHIND_REASON = 'schema_behind';++/** Whether the brain's schema version is below this build's; null when it cannot be read. A terminal-receipt reader's input. */+export async function readSchemaBehind(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean | null> {+ try {+ const [row] = await engine.executeRaw<{ value: string | null }>(`SELECT value FROM config WHERE key='version'`);+ const current = Number.parseInt(row?.value ?? '', 10);+ return Number.isSafeInteger(current) ? current < LATEST_SCHEMA_VERSION : null;+ } catch {+ return null;+ }+}++/** The fix of a schema-behind refusal: apply-migrations as the schema owner, verified read-only with doctor. */+export function schemaBehindFix(ownsSchema: boolean): Action {+ return { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: ownsSchema ? 'agent' : 'host_admin', requires_exclusive: true,+ why: 'Applies the pending schema migrations. It needs a database role that owns the gbrain tables; then resubmit the write (the same request_id works, nothing was admitted).',+ ...(ownsSchema ? {} : { user_message: 'The brain schema is behind this gbrain build and this connection\'s database role does not own the gbrain tables. Run gbrain apply-migrations --yes on the brain host as the role that owns them, then I will resubmit the write.' }),+ verify: { argv: ['gbrain', 'doctor', '--json'] }, docs: 'docs/guides/write-refusals.md#schema_behind' };+}++/**+ * Called by admission after the guard batch and after an accepted request id's replay has returned: the refusal to+ * raise for a new request, or null.+ */+export async function schemaAdmissionRefusal(tx: BrainEngine): Promise<OperationError | null> {+ const [row] = await tx.executeRaw<{ value: string | null }>(`SELECT value FROM config WHERE key='version'`);+ const current = Number.parseInt(row?.value ?? '', 10);+ if (!Number.isSafeInteger(current) || current >= LATEST_SCHEMA_VERSION) return null;+ // Loaded only when behind: the lock module pulls in the engine factory.+ if ((await import('../migration-orchestration-lock.ts')).migrationOrchestrationHeldHere()) return null;+ const [owner] = await tx.executeRaw<{ owns: boolean | null }>(+ `SELECT pg_has_role(current_user, c.relowner, 'USAGE') AS owns FROM pg_class c WHERE c.oid = to_regclass('sources')`);+ const ownsSchema = owner?.owns !== false;+ return opError('migrations_pending', `The brain schema is at v${current} and this gbrain build needs v${LATEST_SCHEMA_VERSION}, so the write was not admitted.`,+ `Not retryable as is: the same write refuses until the schema is migrated. Apply the pending migrations with \`gbrain apply-migrations --yes\`${ownsSchema ? '' : ' as the database role that owns the gbrain tables (this connection\'s role does not)'}, then resubmit; nothing was admitted, so the same request_id commits.`,+ { reason: SCHEMA_BEHIND_REASON, why: 'The write path of this build reads tables or columns that only the pending migrations add, so publishing now would fail on the missing schema and spend the request id.',+ fix: schemaBehindFix(ownsSchema) });+}diff --git a/test/admission-schema-behind-6904.test.ts b/test/admission-schema-behind-6904.test.tsnew file mode 100644index 0000000000..89493112de--- /dev/null+++ b/test/admission-schema-behind-6904.test.ts@@ -0,0 +1,111 @@+/**+ * #6904: a managed write is refused `migrations_pending` (reason `schema_behind`) while the brain's schema is behind+ * this build, before a request id is admitted.+ *+ * Protects: with `config.version` one step behind `LATEST_SCHEMA_VERSION`, put_page refuses with the protocol fix+ * (`gbrain apply-migrations --yes`, verify `gbrain doctor --json`) and admits nothing; the same request id commits once+ * the schema is at head again; a replay of an id accepted before the schema fell behind still reconciles; and a write+ * made while this process holds the apply-migrations orchestration lock is admitted. A real PGLite brain with a managed,+ * claimed canonical worktree.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';+import { acquireMigrationOrchestrationLock } from '../src/core/migration-orchestration-lock.ts';+import { withEnv } from './helpers/with-env.ts';++const logger = { info() {}, warn() {}, error() {} };+let engine: BrainEngine;+let dir: string;+let ctx: OperationContext;+const SOURCE = 'schema-behind';++const page = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${title} body.\n`;+const put = (slug: string, requestId: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: page(slug), request_id: requestId } });+const requests = async (requestId: string) => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1', [requestId])).map(row => row.state);+const live = async (slug: string) => (await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [SOURCE, slug]))[0]!.n === 1;+const behind = () => engine.setConfig('version', String(LATEST_SCHEMA_VERSION - 1));+const atHead = () => engine.setConfig('version', String(LATEST_SCHEMA_VERSION));++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: join(dir, 'home') }, fn);++async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++describe('#6904 writes refused while the schema is behind', () => {+ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-schema-behind-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ execFileSync('git', ['init', '-q'], { cwd: root });+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, root]);+ await engine.setConfig('sync.write_through', 'true');+ await inHome(() => claimWorktree(engine, SOURCE, root));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ ctx = { engine, sourceId: SOURCE, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ test('put_page refuses migrations_pending/schema_behind with the apply-migrations fix, admits nothing, and the same request id commits after migrating', () => inHome(async () => {+ await atHead();+ const requestId = randomUUID();+ await behind();+ try {+ const error = await refusal(() => put('notes/behind', requestId));+ expect(error.code).toBe('migrations_pending');+ expect(error.reason).toBe('schema_behind');+ expect(error.message).toContain(`v${LATEST_SCHEMA_VERSION - 1}`);+ expect(error.suggestion).toContain('the same request_id commits');+ expect(error.fix).toMatchObject({ argv: ['gbrain', 'apply-migrations', '--yes'], actor: 'agent', requires_exclusive: true, verify: { argv: ['gbrain', 'doctor', '--json'] } });+ expect(await requests(requestId)).toEqual([]);+ expect(await live('notes/behind')).toBe(false);+ } finally { await atHead(); }+ await put('notes/behind', requestId);+ expect(await requests(requestId)).toEqual(['committed']);+ expect(await live('notes/behind')).toBe(true);+ }), 60_000);++ test('a replay of a request id accepted before the schema fell behind still reconciles', () => inHome(async () => {+ await atHead();+ const requestId = randomUUID();+ await put('notes/replayed', requestId);+ await behind();+ try {+ await put('notes/replayed', requestId);+ expect(await requests(requestId)).toEqual(['committed']);+ expect((await refusal(() => put('notes/fresh', randomUUID()))).code).toBe('migrations_pending');+ } finally { await atHead(); }+ }), 60_000);++ test('a write made while this process holds the apply-migrations orchestration lock is admitted', () => inHome(async () => {+ await behind();+ try {+ const lock = (await acquireMigrationOrchestrationLock({ engine: 'pglite' } as never))!;+ const requestId = randomUUID();+ try {+ await put('notes/orchestrator', requestId);+ } finally { await lock.release(); }+ expect(await requests(requestId)).toEqual(['committed']);+ expect((await refusal(() => put('notes/after-release', randomUUID()))).code).toBe('migrations_pending');+ } finally { await atHead(); }+ }), 60_000);+});diff --git a/test/facts-absorb-put-page-session-6333.test.ts b/test/facts-absorb-put-page-session-6333.test.tsindex 022f6c5a0d..bab67d87cf 100644--- a/test/facts-absorb-put-page-session-6333.test.ts+++ b/test/facts-absorb-put-page-session-6333.test.ts@@ -29,6 +29,7 @@ import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorimport { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';const DIMS = 1536;const ENTITY = 'people/alice-example';@@ -80,7 +81,7 @@ async function scenario(managed: boolean) {try {await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: 'test' }, async () => {await resetPgliteState(engine);- await engine.setConfig('version', '156');+ await engine.setConfig('version', String(LATEST_SCHEMA_VERSION));await engine.setConfig('embedding_model', 'openai:text-embedding-3-small');await engine.setConfig('embedding_dimensions', String(DIMS));await registerLocalWriter(engine, 'cli');diff --git a/test/persistence-facts-backstop.test.ts b/test/persistence-facts-backstop.test.tsindex 9a7cb9f716..40bfaa4283 100644--- a/test/persistence-facts-backstop.test.ts+++ b/test/persistence-facts-backstop.test.ts@@ -16,6 +16,7 @@ import type { WriteRequest } from '../src/core/persistence/model.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';let engine: PGLiteEngine;const config = { engine: 'pglite' as const, embedding_disabled: true };@@ -25,7 +26,7 @@ afterAll(async () => { await engine.disconnect(); });async function fixture(run: () => Promise<void>) {const home = mkdtempSync(join(tmpdir(), 'gbrain-facts-effect-'));- try { await withEnv({ GBRAIN_HOME: home }, async () => { await resetPgliteState(engine); await engine.setConfig('version', '156'); await registerLocalWriter(engine, 'cli'); await run(); }); }+ try { await withEnv({ GBRAIN_HOME: home }, async () => { await resetPgliteState(engine); await engine.setConfig('version', String(LATEST_SCHEMA_VERSION)); await registerLocalWriter(engine, 'cli'); await run(); }); }finally { rmSync(home, { force: true, recursive: true }); }}async function prepare(overrides: Partial<OperationContext> = {}, params: Record<string, unknown> = {}) {