Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(migrations): shared_skills.migration.enabled=false declines the v0.53.0 migration (#6466)

garrytan554889e02495
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index e455b50ef8..6a38888e69 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/migrate-engine.ts` — Legacy engine copier (`gbrain migrate --to pglite`, and PGLite → Postgres when `migrate.graduation` is `false`). A PGLite → Postgres move routes to `src/commands/migrate-graduation.ts` (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286: `copyPageToTarget` forwards the full page row (`page_kind`, `source_path`, effective date and its source, `import_filename`, `source_kind`/`source_uri`/`ingested_via`, `ingested_at` restored in the timestamp UPDATE), the frontmatter aliases (`setPageAliases`) and each chunk's code metadata (`carryChunkMetadata`). A page sealed on the source is queued `engine_migration`; one the source had not sealed is queued `engine_migration_source_unsealed` and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, `runMigrateEngine` runs `drainProjections` (moved to `src/core/page-state/projections.ts`; `commands/projections.ts` re-exports it) on the target for the `engine_migration` and `rebuild_failed` reasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned by `test/migrate-full-row-projections.serial.test.ts`, `test/e2e/migrate-full-row-projections-postgres.test.ts` and a D2 case in `test/e2e/migrate-engine-pglite-to-postgres.test.ts`. Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.
-- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains; the config check reads `auto_link` in-process (file/env plane, then the database), never through a `gbrain config get` child. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md; raises `minion_jobs.max_stalled`'s default to 3 only when it is below 3, so it never lowers schema v15's 5). Fresh installs (E8): `Migration.fresh_install_noop: true` marks an orchestrator that changes nothing on a brain `gbrain init` just created; `fresh-install.ts:recordFreshInstallMigrations` (one call in each init engine path, only when init created the database) appends a `complete` ledger entry with `fresh_install: true` + `installed_version` for each, and every other migration lists as `pending_fresh_install` (`src/core/migration-ledger.ts:freshInstallVersion`/`isPendingFreshInstall`) in `apply-migrations --list [--json]`/`--dry-run`, `get_health.migrations` and doctor's `minions_migration` (an `ok`/`info` row with `gbrain apply-migrations --yes --no-autopilot-install`); stamps never count as forward progress over a real partial. Each flag is proven by `test/migrations-fresh-install-audit.serial.test.ts` (schema, row counts, config table and GBRAIN_HOME file tree unchanged by the real orchestrator on a keyless `init --pglite --no-embedding` brain); unit coverage `test/migrations-fresh-install.test.ts`. `shared-content.ts` names its read-only next step as phase `argv` (`SHARED_CONTENT_INSPECT_ARGV`), which the runner prints and the ledger keeps. All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in `src/core/schema-migrations/v014-pages-updated-at-index.ts` and `v015-minion-jobs-max-stalled-default-5.ts` (one file per schema migration; `migrate.ts` is the runner). `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
+- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains; the config check reads `auto_link` in-process (file/env plane, then the database), never through a `gbrain config get` child. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md; raises `minion_jobs.max_stalled`'s default to 3 only when it is below 3, so it never lowers schema v15's 5). Fresh installs (E8): `Migration.fresh_install_noop: true` marks an orchestrator that changes nothing on a brain `gbrain init` just created; `fresh-install.ts:recordFreshInstallMigrations` (one call in each init engine path, only when init created the database) appends a `complete` ledger entry with `fresh_install: true` + `installed_version` for each, and every other migration lists as `pending_fresh_install` (`src/core/migration-ledger.ts:freshInstallVersion`/`isPendingFreshInstall`) in `apply-migrations --list [--json]`/`--dry-run`, `get_health.migrations` and doctor's `minions_migration` (an `ok`/`info` row with `gbrain apply-migrations --yes --no-autopilot-install`); stamps never count as forward progress over a real partial. Each flag is proven by `test/migrations-fresh-install-audit.serial.test.ts` (schema, row counts, config table and GBRAIN_HOME file tree unchanged by the real orchestrator on a keyless `init --pglite --no-embedding` brain); unit coverage `test/migrations-fresh-install.test.ts`. `shared-content.ts` names its read-only next step as phase `argv` (`SHARED_CONTENT_INSPECT_ARGV`), which the runner prints and the ledger keeps. #6466 opt-out: `Migration.optOut: { key }` names a brain-level DB config key (`shared-content.ts`: `shared_skills.migration.enabled`, the registry-free table `MIGRATION_OPT_OUT_KEYS` in `src/core/migration-ledger.ts`, pinned to every module's `optOut`); an explicit off value (`false`/`0`/`off`/`no`, `isMigrationDeclinedValue`) puts the migration in the plan's `declined` bucket (`opt-out.ts:readDeclinedMigrations`, read before `buildPlan`; an unreachable brain declines nothing), so the runner never calls its orchestrator, reconcile included, `--list [--json]` and `--dry-run` show it `declined` with `opt_out.key`, and an explicit `--migration <v>` refuses `migration_declined` (exit 3, `fix.next: ask_user`, `gbrain config set <key> true`, verify `--list --json`). `migrationLedgerSummary(VERSION, declined)` gives `get_health.migrations.declined` and doctor's `minions_migration` an `ok` row with `details.declined`. Tests: `test/shared-skills-migration-decline-6466.test.ts`. All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in `src/core/schema-migrations/v014-pages-updated-at-index.ts` and `v015-minion-jobs-max-stalled-default-5.ts` (one file per schema migration; `migrate.ts` is the runner). `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
- `src/commands/migrations/v0_46_3.ts` — idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.
- `src/commands/migrations/v0_60_31.ts` — the security fix wave orchestrated migration (ledger `0.60.31`), two phases. `credential_projection`: runs `runMigrateOnlyCore` first (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), then `resealCredentialProjections`, provider-free and never embedding; a dry run reports the count; any failed page makes the run `partial`, so `gbrain apply-migrations --yes --no-autopilot-install` retries it, and re-sealed pages are no longer pending, so a rerun resumes. `google_file_modes_notice`: `googleFileModesNoticePhase` from `v0_60_31-google-file-modes.ts`. A brain without config completes with the phase skipped. Agent instructions: `skills/migrations/v0.60.31.0.md`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 94d3c5537d..c42296c8f6 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -26,7 +26,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
-- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_health` adds `embedding_column`, the registry-active vector column its coverage counts were measured on (legacy `embedding` when the registry is unreadable), on both engines (`test/get-health-embedding-column.test.ts` + its Postgres arm). `get_versions` reads an explicit column list (`PAGE_VERSION_COLUMNS` in `engine-sql/pages.ts`), so the write attribution columns never reach a plain `read` caller; trusted local callers and `admin` holders (`canReadWriteAttribution`) also get `written_by` and `archived_by` from `attributeVersions`. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. Optional `limit` (a positive safe integer; any other explicit value is `invalid_params` without echoing it) returns the newest N versions, and `include_body: false` returns metadata only; both run in `engine-sql/pages.ts` `getVersions` (one query, scope and privacy predicates in WHERE before `LIMIT`, `ORDER BY pv.snapshot_at DESC, pv.id DESC`, metadata mode selects no body columns, typed `PageVersionRows`), so hidden versions never shift the prefix; trusted and admin callers keep `written_by`/`archived_by` (`test/get-versions-response-bounds.test.ts`). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, pending_fresh_install, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read). `get_health` serves repeat calls from `src/core/health-memo.ts` and returns `computed_at`, the time its counters were read.
+- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_health` adds `embedding_column`, the registry-active vector column its coverage counts were measured on (legacy `embedding` when the registry is unreadable), on both engines (`test/get-health-embedding-column.test.ts` + its Postgres arm). `get_versions` reads an explicit column list (`PAGE_VERSION_COLUMNS` in `engine-sql/pages.ts`), so the write attribution columns never reach a plain `read` caller; trusted local callers and `admin` holders (`canReadWriteAttribution`) also get `written_by` and `archived_by` from `attributeVersions`. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. Optional `limit` (a positive safe integer; any other explicit value is `invalid_params` without echoing it) returns the newest N versions, and `include_body: false` returns metadata only; both run in `engine-sql/pages.ts` `getVersions` (one query, scope and privacy predicates in WHERE before `LIMIT`, `ORDER BY pv.snapshot_at DESC, pv.id DESC`, metadata mode selects no body columns, typed `PageVersionRows`), so hidden versions never shift the prefix; trusted and admin callers keep `written_by`/`archived_by` (`test/get-versions-response-bounds.test.ts`). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, pending_fresh_install, partial, wedged, declined, skipped_future}` block (`declined` since #6466: versions the brain's config turns off, read through `declinedMigrations(engine)`) stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read). `get_health` serves repeat calls from `src/core/health-memo.ts` and returns `computed_at`, the time its counters were read.
- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query per table; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).
- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a20918744e..3df7e1a5b7 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1760,6 +1760,14 @@ More: [docs/guides/write-refusals.md#merge_recommended](../../docs/guides/write-
|---|---|---|---|---|---|---|
| The HTTP method is not allowed on this endpoint. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### migration_declined
+
+<a id="migration_declined"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An explicit apply-migrations --migration named a migration the brain's config declines, so nothing was run or written. | The migration's opt-out key (for v0.53.0: shared_skills.migration.enabled=false) is brain-level config shared by every machine on that database; an explicit run from one machine would rewrite config for all of them, so the runner refuses instead of overriding the owner's choice. Ordinary runs skip a declined migration and list it as declined. | Do not retry. Tell the user the migration is declined on this brain and give them the fix command (gbrain config set <key> true) if they want it to run; --list --json shows it declined. | user | `repeat the read that failed` | 3 | no |
+
### migration_failed
<a id="migration_failed"></a>
diff --git a/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.md
index 9519671dcd..a2f45991cc 100644
--- a/docs/guides/shared-brain-skills.md
+++ b/docs/guides/shared-brain-skills.md
@@ -386,6 +386,34 @@ with `joined`, `refresh_pending`, `delivery_reported`, `source_changed`, or
delivery only; every row remains native-unverified. Unknown or disconnected
installations are not proven migrated by that inventory.
+### Decline the migration for the whole brain
+
+**Say to your agent:** *"We are not adopting shared skills on this brain; stop
+the v0.53.0 migration from running on every upgrade."* The agent runs
+
+```bash
+gbrain config set shared_skills.migration.enabled false
+```
+
+The key is brain-level database config, so it applies to every machine that
+uses that database. From then on `gbrain apply-migrations` (including the
+`bun install` postinstall, `gbrain upgrade` and `gbrain post-upgrade`) skips
+v0.53.0 entirely: no inventory, no `shared_skills.migration.v1*` config
+writes, and the applied-migration re-check does not run. `gbrain
+apply-migrations --list` and `--dry-run` show it as `declined` with the key,
+`gbrain doctor` reports `minions_migration` ok with `declined: ['0.53.0']`,
+and `get_health.migrations.declined` lists it. An explicit `gbrain
+apply-migrations --migration 0.53.0` refuses with `migration_declined` (exit
+3) and the command that turns it back on instead of overriding the owner's
+choice from one machine. To adopt shared skills later:
+
+```bash
+gbrain config set shared_skills.migration.enabled true
+gbrain apply-migrations --yes
+```
+
+Per-source opt-outs (next section) still apply once the migration runs.
+
## Choose which sources adopt shared skills
**Say to your agent:** *"Stop the shared-skills migration from touching the
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 869f9f53bd..58a79b175f 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -25,6 +25,7 @@ import {
} from '../core/migration-orchestration-lock.ts';
import { loadCompletedMigrations, appendCompletedMigration, type CompletedMigrationEntry } from '../core/preferences.ts';
import { migrations, compareVersions, type Migration, type OrchestratorOpts } from './migrations/index.ts';
+import { migrationDeclinedError, readDeclinedMigrations } from './migrations/opt-out.ts';
import {
indexCompletedEntries,
statusForVersion as ledgerStatusForVersion,
@@ -223,6 +224,8 @@ interface Plan {
pending_fresh_install: Migration[];
skippedFuture: Migration[];
wedged: Migration[];
+ /** #6466: declined by the brain's config (`Migration.optOut`); never run, listed as `declined`. */
+ declined: Migration[];
}
/**
@@ -236,18 +239,21 @@ interface Plan {
* after this version (fresh-install stamps). Runs like pending.
* - skippedFuture: migration.version > installed VERSION (binary is older
* than the migration; wait for a newer install).
+ * - declined: the brain's config turns the migration off (#6466); not
+ * applied, partial or pending whatever the ledger says.
*
* Codex H9: we never compare against `current VERSION >` — that rule would
* skip v0.11.0 when running v0.11.1. Compare against completed.jsonl.
*/
-function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: string): Plan {
- const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [] };
+function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: string, declined: ReadonlySet<string> = new Set()): Plan {
+ const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [], declined: [] };
for (const m of migrations) {
if (filterVersion && m.version !== filterVersion) continue;
if (compareVersions(m.version, installed) > 0) {
plan.skippedFuture.push(m);
continue;
}
+ if (declined.has(m.version)) { plan.declined.push(m); continue; }
const status = statusForVersion(m.version, idx);
if (status === 'complete') plan.applied.push(m);
else if (status === 'partial') plan.partial.push(m);
@@ -287,6 +293,7 @@ function listRows(plan: Plan): Array<{ status: string; m: Migration }> {
...plan.wedged.map(m => ({ status: 'wedged', m })),
...plan.pending.map(m => ({ status: 'pending', m })),
...plan.pending_fresh_install.map(m => ({ status: 'pending_fresh_install', m })),
+ ...plan.declined.map(m => ({ status: 'declined', m })),
...plan.skippedFuture.map(m => ({ status: 'future', m })),
];
}
@@ -306,6 +313,7 @@ function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void
console.log('');
const needsWork = plan.pending.length + plan.partial.length;
const setup = plan.pending_fresh_install.length;
+ for (const m of plan.declined) console.log(`v${m.version} is declined by config (${m.optOut?.key} is false); turn it back on: gbrain config set ${m.optOut?.key} true`);
if (needsWork === 0 && setup === 0) {
console.log('All migrations up to date.');
return;
@@ -329,6 +337,7 @@ function listJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: D
status: r.status,
headline: r.m.featurePitch.headline,
...(r.status === 'applied' && (idx.byVersion.get(r.m.version) ?? []).some(isFreshInstallStamp) ? { fresh_install: true } : {}),
+ ...(r.status === 'declined' && r.m.optOut ? { opt_out: { key: r.m.optOut.key } } : {}),
})),
needs_action: plan.pending.length + plan.partial.length,
pending_fresh_install: plan.pending_fresh_install.length,
@@ -360,6 +369,11 @@ function printDryRun(plan: Plan, installed: string, dbProbe: DbProbeOutcome): vo
for (const m of plan.pending_fresh_install) console.log(` → v${m.version} — ${m.featurePitch.headline}`);
console.log('');
}
+ if (plan.declined.length) {
+ console.log('Declined by config (not run; turn one back on with gbrain config set <key> true):');
+ for (const m of plan.declined) console.log(` ⊘ v${m.version} — ${m.optOut?.key} is false`);
+ console.log('');
+ }
if (plan.skippedFuture.length) {
console.log('Skipped (newer than installed binary):');
for (const m of plan.skippedFuture) console.log(` ⧗ v${m.version}`);
@@ -650,7 +664,8 @@ async function runLockedMigrations(
const completed = loadCompletedMigrations();
const idx = indexCompleted(completed);
- const plan = buildPlan(idx, installed, cli.specificMigration);
+ const declined = await readDeclinedMigrations(loadConfig()!);
+ const plan = buildPlan(idx, installed, cli.specificMigration, declined);
doc.database = dbProbe;
doc.plan = Object.fromEntries(Object.entries(plan).map(([state, entries]) => [state, entries.map((migration: Migration) => migration.version)]));
@@ -667,11 +682,17 @@ async function runLockedMigrations(
// Don't exit — applied/partial/pending are still worth reporting and running.
}
- if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.pending_fresh_install.length + plan.skippedFuture.length === 0) {
+ if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.pending_fresh_install.length + plan.skippedFuture.length + plan.declined.length === 0) {
console.error(`No migration registered with version "${cli.specificMigration}". Run \`gbrain apply-migrations --list\` to see registered versions.`);
fail('invalid', unknownMigrationError(cli.specificMigration));
return 2;
}
+ // #6466: an explicit run of a declined migration refuses (T1) instead of
+ // overriding brain-level config every machine on the database shares.
+ if (cli.specificMigration && plan.declined.length > 0 && !cli.list && !cli.dryRun) {
+ fail('declined', migrationDeclinedError(plan.declined[0]!));
+ return writeCliError(report.failure, COMMAND, { json: cli.json });
+ }
// #4364: --require-db turns an unreachable DB into a hard failure instead
// of a filesystem-only plan that renders identically to a clean database.
diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.ts
index 23cc715f97..02d097c41a 100644
--- a/src/commands/doctor/checks/local-runtime.ts
+++ b/src/commands/doctor/checks/local-runtime.ts
@@ -8,7 +8,7 @@
*/
import { loadCompletedMigrations } from '../../../core/preferences.ts';
-import { indexCompletedEntries, isFreshInstallStamp, migrationLedgerSummary, trailingPartialCount } from '../../../core/migration-ledger.ts';
+import { MIGRATION_OPT_OUT_KEYS, declinedMigrations, indexCompletedEntries, isFreshInstallStamp, migrationLedgerSummary, trailingPartialCount } from '../../../core/migration-ledger.ts';
import { VERSION } from '../../../version.ts';
import { pendingFreshInstallCheck } from './pending-fresh-install.ts';
import { compareVersions } from '../../migrations/index.ts';
@@ -127,10 +127,14 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {
// schema clearly advanced. Without this, every install that went through
// a v0.11.0 stopgap and then upgraded carries the "MINIONS HALF-INSTALLED"
// flag forever, even on installs that have been at v0.22+ for months.
+ // #6466: a migration the brain's config declines is reported as such,
+ // never as pending, partial or wedged.
+ const declined = engine ? await declinedMigrations(engine).catch(() => new Set<string>()) : new Set<string>();
try {
const completed = loadCompletedMigrations();
const byVersion = new Map<string, { complete: boolean; partial: boolean; ran: boolean }>();
for (const entry of completed) {
+ if (declined.has(entry.version)) continue;
const seen = byVersion.get(entry.version) ?? { complete: false, partial: false, ran: false };
if (entry.status === 'complete') seen.complete = true;
if (entry.status === 'complete' && !isFreshInstallStamp(entry)) seen.ran = true;
@@ -176,9 +180,18 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {
// past were skipped, not merely not reached yet. Versions above the newest
// run are the next apply-migrations' ordinary work and stay quiet here.
const newestRun = completedVersions.reduce<string | null>((a, v) => (a === null || compareVersions(v, a) > 0 ? v : a), null);
- const pending = completed.length === 0 ? [] : migrationLedgerSummary(VERSION).pending.filter(v =>
+ const pending = completed.length === 0 ? [] : migrationLedgerSummary(VERSION, declined).pending.filter(v =>
(newestRun !== null && compareVersions(v, newestRun) < 0) || history.get(v)?.at(-1)?.status === 'retry');
+ if (declined.size > 0) {
+ const keys = [...declined].map(v => `${MIGRATION_OPT_OUT_KEYS[v]}=false`);
+ checks.push({
+ name: 'minions_migration',
+ status: 'ok',
+ message: `Declined by config: ${[...declined].join(', ')} (${keys.join(', ')}); apply-migrations skips it on every machine using this brain. Turn one back on: gbrain config set <key> true`,
+ details: { declined: [...declined] },
+ });
+ }
if (wedged.length > 0) {
// The wedged set is a STRICT subset of the stuck set, so a wedged
// version is also stuck. Surface the force-retry hint instead of the
diff --git a/src/commands/migrations/opt-out.ts b/src/commands/migrations/opt-out.ts
new file mode 100644
index 0000000000..c1d8d0e217
--- /dev/null
+++ b/src/commands/migrations/opt-out.ts
@@ -0,0 +1,47 @@
+/**
+ * #6466: a brain owner can decline a host migration. A `Migration` with
+ * `optOut: { key }` is `declined` while the brain's DB config holds an
+ * explicit off value under that key (`gbrain config set <key> false`); the
+ * runner then never calls its orchestrator, not even the reconcile re-check
+ * an applied ledger entry would rerun, and an explicit `--migration <v>`
+ * refuses with `migration_declined` (exit 3). The keys live in
+ * `core/migration-ledger.ts` (MIGRATION_OPT_OUT_KEYS, registry-free so doctor
+ * and get_health read them without the registry). The key is brain-level config
+ * shared by every machine on that database, so one machine's explicit run
+ * does not override what the owner set for all of them.
+ */
+import { createEngine } from '../../core/engine-factory.ts';
+import { isThinClient, toEngineConfig, type GBrainConfig } from '../../core/config.ts';
+import { declinedMigrations } from '../../core/migration-ledger.ts';
+import { opError, type OperationError } from '../../core/ops/contract.ts';
+import type { Migration } from './types.ts';
+
+export { declinedMigrations, isMigrationDeclinedValue } from '../../core/migration-ledger.ts';
+
+/**
+ * The runner's read: opens the brain to read the opt-out keys, and treats an
+ * unreachable brain (or a thin client) as "nothing declined"; the
+ * orchestrator then reports the same failure it would have anyway.
+ */
+export async function readDeclinedMigrations(config: GBrainConfig): Promise<Set<string>> {
+ if (isThinClient(config)) return new Set();
+ try {
+ const engine = await createEngine(toEngineConfig(config));
+ await engine.connect(toEngineConfig(config));
+ try { return await declinedMigrations(engine); } finally { await engine.disconnect(); }
+ } catch {
+ return new Set();
+ }
+}
+
+export function migrationDeclinedError(m: Migration): OperationError {
+ const key = m.optOut?.key ?? '';
+ return opError('migration_declined',
+ `Migration v${m.version} is declined on this brain: ${key} is false, so apply-migrations skips it (its headline: ${m.featurePitch.headline}). Nothing was run or written.`,
+ `Leave it declined, or ask the user to turn it back on with \`gbrain config set ${key} true\` and run apply-migrations again.`,
+ { why: `${key} is brain-level config shared by every machine on this database; an explicit run from one machine would rewrite config for all of them, so it refuses instead of overriding the owner's choice.`,
+ fix: { ask_user: true, argv: ['gbrain', 'config', 'set', key, 'true'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Re-enables the declined migration for every machine on this brain; the next apply-migrations runs it.',
+ user_message: `Migration v${m.version} is turned off on this brain (${key}=false). Turn it back on and run it?`,
+ verify: { argv: ['gbrain', 'apply-migrations', '--list', '--json'] } } });
+}
diff --git a/src/commands/migrations/shared-content.ts b/src/commands/migrations/shared-content.ts
index 50ec0ecbe5..b0f372b6df 100644
--- a/src/commands/migrations/shared-content.ts
+++ b/src/commands/migrations/shared-content.ts
@@ -6,8 +6,11 @@ import type { OrchestratorOpts } from './types.ts';
import { exportDatabaseContent } from '../../core/shared-skills/migration-export.ts';
import { PgliteBusyError } from '../../core/pglite-lock.ts';
import { shellQuote } from '../../core/agent-output.ts';
+import { MIGRATION_OPT_OUT_KEYS } from '../../core/migration-ledger.ts';
export const SHARED_CONTENT_MIGRATION_VERSION = '0.53.0';
+/** #6466: `gbrain config set shared_skills.migration.enabled false` declines this migration (brain-level, every machine). */
+export const SHARED_CONTENT_MIGRATION_OPT_OUT_KEY = MIGRATION_OPT_OUT_KEYS[SHARED_CONTENT_MIGRATION_VERSION]!;
/** Read-only: prints every source's remaining stage, its reason and the command for it (`pending_actions`). */
export const SHARED_CONTENT_INSPECT_ARGV = ['gbrain', 'apply-migrations', '--migration', SHARED_CONTENT_MIGRATION_VERSION, '--dry-run', '--json'];
@@ -44,6 +47,7 @@ export const sharedContentMigration: Migration = {
},
preview: options => inspectSharedContentMigration(true, options.dbOnlyExport, options.acceptReviewedInventory),
reconcile: true,
+ optOut: { key: SHARED_CONTENT_MIGRATION_OPT_OUT_KEY },
orchestrator: async options => {
try {
const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport, options.acceptReviewedInventory);
diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.ts
index c59d46d7f9..bcf538a1cf 100644
--- a/src/commands/migrations/types.ts
+++ b/src/commands/migrations/types.ts
@@ -73,6 +73,12 @@ export interface Migration {
orchestrator: (opts: OrchestratorOpts) => Promise<OrchestratorResult>;
preview?: (opts: OrchestratorOpts) => Promise<unknown>;
reconcile?: boolean;
+ /**
+ * #6466: brain-level DB config key whose explicit off value declines this
+ * migration (`./opt-out.ts`): the runner skips it, reconcile included,
+ * lists it `declined`, and refuses an explicit `--migration <v>`.
+ */
+ optOut?: { key: string };
/**
* Consent effects the orchestrator performs (agent operator contract A4);
* apply-migrations asks for them before running it. `persistent_install`
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 081bffb525..09a3a18241 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -440,6 +440,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Fix wave 15 (GBRA-79), doctor / repair / migrations group.
{ since: '0.60.176.0', text: '`gbrain doctor --only harness_wiring` on a Postgres, `database_url` or `remote_mcp` brain now probes an HTTP registration\'s `/health` without any credential instead of reporting `http_serve_missing` unseen: a healthy gbrain answer is `wired_running` with `mcp_access: unverified` (a listener is proven, this registration\'s token and tool access are not; confirm tools in a new session), a refused local `http:` port keeps `http_serve_missing` with the `serve --http` fix, and anything else (`https:` refused, DNS or TLS errors, a timeout, a redirect, a 503 or a non-gbrain answer) is `http_serve_unreachable` / `http_serve_unhealthy` with no fix. Registered URLs are printed without userinfo, query or fragment in every doctor message and JSON (#6453).' },
{ since: '0.60.176.0', text: '`gbrain repair <kind> --apply` no longer stops the whole run when one item is refused with `invalid_params` (a slug the grammar no longer accepts) or `source_changed` (file and database copies disagree): the item is listed in `failed[]` with its reason and left exactly as it was, the remaining items are repaired, and the command exits 1. A failed item is not retried by a resumed run; the next full scan (the printed apply command once the run has completed) retries it. `gbrain doctor --remediate` reports a repair step with failed items as `failed`, never `completed`, and the content lane and maintenance phases warn on them.' },
+ { since: '0.60.176.0', text: '`gbrain config set shared_skills.migration.enabled false` declines the v0.53.0 shared-skills migration for every machine on the brain: `gbrain apply-migrations` (the install postinstall, `gbrain upgrade` and `gbrain post-upgrade` included) skips it with no inventory and no config writes, `--list` and `--dry-run` show it `declined`, doctor and `get_health.migrations.declined` report it, and an explicit `--migration 0.53.0` refuses with `migration_declined` (exit 3) naming the command that turns it back on (#6466).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index e3bb4e6752..e6d7262fa1 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1754,7 +1754,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.publication_ceiling_ms', // #6405: persistence/sync-drain.ts (in-pass publication ceiling)
'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
- 'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries',
+ 'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
'migrate.graduation', // file plane, src/commands/migrate-graduation.ts (engine graduation opt-out)
'consent.preapprove.paid.max_usd_per_run', 'consent.preapprove.persistent_install', // A4: file plane, core/consent.ts
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index ca91d28e6a..13ec79f5c4 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -277,6 +277,9 @@ export const CODES = {
method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },
migration_lease_lost: { class: 'server', summary: "This apply-migrations run's own migration lease no longer matched its fence, so it stopped before the next migration.",
why: 'The lease row still names this process (pid and host), but the fenced refresh matched no row: the direct and main database connections may reach different databases, or the row was rewritten. The details say whether the acquisition token and acquisition time still match (never the token itself). Run `gbrain doctor --json` and report it (#6028).' },
+ migration_declined: { class: 'consent', exit: 3, actor: 'user', summary: "An explicit apply-migrations --migration named a migration the brain's config declines, so nothing was run or written.",
+ why: "The migration's opt-out key (for v0.53.0: shared_skills.migration.enabled=false) is brain-level config shared by every machine on that database; an explicit run from one machine would rewrite config for all of them, so the runner refuses instead of overriding the owner's choice. Ordinary runs skip a declined migration and list it as declined.",
+ suggestion: 'Do not retry. Tell the user the migration is declined on this brain and give them the fix command (gbrain config set <key> true) if they want it to run; --list --json shows it declined.' },
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), so the command did not report success.",
diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.ts
index c926dbf649..7d0b356517 100644
--- a/src/core/migration-ledger.ts
+++ b/src/core/migration-ledger.ts
@@ -13,6 +13,7 @@
* test/migration-ledger.test.ts so it cannot drift silently.
*/
+import type { BrainEngine } from './engine.ts';
import { loadCompletedMigrations, type CompletedMigrationEntry } from './preferences.ts';
/**
@@ -26,6 +27,30 @@ export const MIGRATION_VERSIONS: readonly string[] = [
'0.32.2', '0.43.0', '0.46.3', '0.53.0', '0.60.31',
];
+/**
+ * #6466: migrations a brain owner can decline, by version → the brain-level
+ * DB config key whose explicit off value declines it. Registry-free (version
+ * strings and keys only, like MIGRATION_VERSIONS); pinned against each
+ * module's `optOut` by test/migration-ledger.test.ts.
+ */
+export const MIGRATION_OPT_OUT_KEYS: Readonly<Record<string, string>> = {
+ '0.53.0': 'shared_skills.migration.enabled',
+};
+
+/** True for an explicit off value; absent, empty or anything else keeps the migration enabled. */
+export function isMigrationDeclinedValue(raw: string | null | undefined): boolean {
+ return typeof raw === 'string' && ['false', '0', 'off', 'no'].includes(raw.trim().toLowerCase());
+}
+
+/** Versions MIGRATION_OPT_OUT_KEYS declines on this brain, in version order; an unreadable key counts as enabled. */
+export async function declinedMigrations(engine: Pick<BrainEngine, 'getConfig'>): Promise<Set<string>> {
+ const declined = new Set<string>();
+ for (const [version, key] of Object.entries(MIGRATION_OPT_OUT_KEYS)) {
+ if (isMigrationDeclinedValue(await engine.getConfig(key).catch(() => null))) declined.add(version);
+ }
+ return declined;
+}
+
/** Bug 3 attempt cap — consecutive partials before a version counts wedged. */
export const MAX_CONSECUTIVE_PARTIALS = 3;
@@ -131,6 +156,8 @@ export interface MigrationLedgerSummary {
partial: string[];
/** Hit the consecutive-partial cap — needs an explicit forced retry. */
wedged: string[];
+ /** #6466: declined by the brain's config (a migration's `optOut` key is off); never pending, partial or wedged. */
+ declined: string[];
/**
* Migrations newer than the installed binary (count only). Future-versioned
* migrations are excluded from ALL status buckets regardless of ledger
@@ -147,16 +174,17 @@ export interface MigrationLedgerSummary {
* BrainEngine.getHealth() in both engines. Version strings only; never
* migration internals.
*/
-export function migrationLedgerSummary(installedVersion: string): MigrationLedgerSummary {
+export function migrationLedgerSummary(installedVersion: string, declined: ReadonlySet<string> = new Set()): MigrationLedgerSummary {
const entries = loadCompletedMigrations();
const byVersion = indexCompletedEntries(entries);
const freshVersion = freshInstallVersion(entries);
- const summary: MigrationLedgerSummary = { pending: [], pending_fresh_install: [], partial: [], wedged: [], skipped_future: 0 };
+ const summary: MigrationLedgerSummary = { pending: [], pending_fresh_install: [], partial: [], wedged: [], declined: [], skipped_future: 0 };
for (const version of MIGRATION_VERSIONS) {
if (compareVersions(version, installedVersion) > 0) {
summary.skipped_future += 1;
continue;
}
+ if (declined.has(version)) { summary.declined.push(version); continue; }
const status = statusForVersion(version, byVersion);
if (status === 'pending') (isPendingFreshInstall(version, freshVersion) ? summary.pending_fresh_install : summary.pending).push(version);
else if (status === 'partial') summary.partial.push(version);
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index e4edbaa08b..4ab493f970 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -77,9 +77,9 @@ const get_health: Operation = {
// degrades the field, never the health call.
let migrations: unknown;
try {
- const { migrationLedgerSummary } = await import('../migration-ledger.ts');
+ const { declinedMigrations, migrationLedgerSummary } = await import('../migration-ledger.ts');
const { VERSION } = await import('../../version.ts');
- migrations = migrationLedgerSummary(VERSION);
+ migrations = migrationLedgerSummary(VERSION, await declinedMigrations(ctx.engine));
} catch {
migrations = { error: 'ledger_unreadable' };
}
diff --git a/test/helpers/apply-migrations-schema-driver.ts b/test/helpers/apply-migrations-schema-driver.ts
index a808e37386..3086768881 100644
--- a/test/helpers/apply-migrations-schema-driver.ts
+++ b/test/helpers/apply-migrations-schema-driver.ts
@@ -12,9 +12,11 @@ const REPO = resolve(import.meta.dir, '..', '..');
* `reconcile` is an applied re-check that runs on every pass (like the
* shared-content migration); the others are pending. `migrate_schema` stamps
* the schema at head; `hide_version` renames the config table so the version
- * cannot be read back; `fail` reports a failed orchestrator.
+ * cannot be read back; `fail` reports a failed orchestrator; `declinable` is
+ * an applied reconcile re-check at version 0.53.0 with the shared-skills
+ * opt-out key (#6466), so `shared_skills.migration.enabled=false` declines it.
*/
-export type StubMigration = 'reconcile' | 'noop' | 'migrate_schema' | 'hide_version' | 'fail';
+export type StubMigration = 'reconcile' | 'noop' | 'migrate_schema' | 'hide_version' | 'fail' | 'declinable';
export interface SchemaDriverOpts {
args: string[];
@@ -37,7 +39,10 @@ export function writeSchemaDriver(home: string, opts: SchemaDriverOpts): string
if (opts.migrations.includes('reconcile')) {
appendFileSync(join(ledgerDir, 'completed.jsonl'), `${JSON.stringify({ version: '0.0.1', status: 'complete' })}\n`);
}
- const stubs = opts.migrations.map((kind, i) => ({ kind, version: kind === 'reconcile' ? '0.0.1' : `0.0.${i + 2}` }));
+ if (opts.migrations.includes('declinable')) {
+ appendFileSync(join(ledgerDir, 'completed.jsonl'), `${JSON.stringify({ version: '0.53.0', status: 'complete' })}\n`);
+ }
+ const stubs = opts.migrations.map((kind, i) => ({ kind, version: kind === 'reconcile' ? '0.0.1' : kind === 'declinable' ? '0.53.0' : `0.0.${i + 2}` }));
const driver = join(home, `schema-driver-${Math.random().toString(36).slice(2)}.ts`);
writeFileSync(driver, `import { mock } from 'bun:test';
import { appendFileSync, readFileSync } from 'node:fs';
@@ -61,12 +66,14 @@ const actions = {
migrate_schema: () => withEngine(engine => engine.setConfig('version', String(realMigrate.LATEST_VERSION))),
hide_version: () => withEngine(engine => engine.executeRaw('ALTER TABLE config RENAME TO config_hidden_6089')),
fail: async () => {},
+ declinable: async () => {},
};
mock.module(${JSON.stringify(join(REPO, 'src/commands/migrations/index.ts'))}, () => ({
compareVersions: (a, b) => a.localeCompare(b, undefined, { numeric: true }),
migrations: ${JSON.stringify(stubs)}.map(({ kind, version }) => ({
version,
...(kind === 'reconcile' ? { reconcile: true } : {}),
+ ...(kind === 'declinable' ? { reconcile: true, optOut: { key: 'shared_skills.migration.enabled' } } : {}),
featurePitch: { headline: 'schema exit probe ' + kind },
orchestrator: async () => {
appendFileSync(log, 'ran ' + kind + '\\n');
diff --git a/test/migration-ledger.test.ts b/test/migration-ledger.test.ts
index 72315de517..76c9eff7c6 100644
--- a/test/migration-ledger.test.ts
+++ b/test/migration-ledger.test.ts
@@ -126,7 +126,7 @@ describe('get_health op layer (dispatchToolCall, real PGLiteEngine)', () => {
const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
- test('migrations block carries the five ledger keys', async () => {
+ test('migrations block carries the six ledger keys (declined since #6466)', async () => {
const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
// GBRAIN_HOME is a PARENT dir — configDir() appends '.gbrain' itself.
const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-op-'));
@@ -136,9 +136,10 @@ describe('get_health op layer (dispatchToolCall, real PGLiteEngine)', () => {
expect(res.isError ?? false).toBe(false);
const body = JSON.parse(res.content[0].text) as {
page_count: number;
- migrations: { pending: string[]; pending_fresh_install: string[]; partial: string[]; wedged: string[]; skipped_future: number };
+ migrations: { pending: string[]; pending_fresh_install: string[]; partial: string[]; wedged: string[]; declined: string[]; skipped_future: number };
};
- expect(Object.keys(body.migrations).sort()).toEqual(['partial', 'pending', 'pending_fresh_install', 'skipped_future', 'wedged'].sort());
+ expect(Object.keys(body.migrations).sort()).toEqual(['declined', 'partial', 'pending', 'pending_fresh_install', 'skipped_future', 'wedged'].sort());
+ expect(body.migrations.declined).toEqual([]);
expect(Array.isArray(body.migrations.pending_fresh_install)).toBe(true);
expect(Array.isArray(body.migrations.pending)).toBe(true);
expect(Array.isArray(body.migrations.partial)).toBe(true);
diff --git a/test/shared-skills-migration-decline-6466.test.ts b/test/shared-skills-migration-decline-6466.test.ts
new file mode 100644
index 0000000000..5630a27a0c
--- /dev/null
+++ b/test/shared-skills-migration-decline-6466.test.ts
@@ -0,0 +1,176 @@
+/**
+ * #6466: a brain owner can decline the v0.53.0 shared-skills migration.
+ * `shared_skills.migration.enabled=false` (brain-level DB config, shared by
+ * every machine on that database) makes the runner skip the migration on
+ * every apply-migrations path, including the reconcile re-check an applied
+ * ledger entry would otherwise rerun: no orchestrator call, no inventory, no
+ * config writes. `--list` reports it `declined`; an explicit
+ * `--migration 0.53.0` refuses with exit 3 `migration_declined` and the
+ * command that turns it back on (T1: refuse, because one machine's explicit
+ * run would rewrite config for all of them); doctor and get_health report
+ * `declined` instead of pending.
+ *
+ * Runner cases drive the real apply-migrations in a child process against a
+ * stubbed registry (test/helpers/apply-migrations-schema-driver.ts, kind
+ * `declinable`) on a PGLite brain whose config carries the key.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { VERSION } from '../src/version.ts';
+import * as ledger from '../src/core/migration-ledger.ts';
+import { migrations } from '../src/commands/migrations/index.ts';
+import { sharedContentMigration } from '../src/commands/migrations/shared-content.ts';
+import { minionsMigrationEntry } from '../src/commands/doctor/checks/local-runtime.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { collect, makeHome, spawnDriver } from './helpers/apply-migrations-lock-driver.ts';
+import { parseDocument, writeSchemaDriver, type SchemaDriverOpts } from './helpers/apply-migrations-schema-driver.ts';
+
+const KEY = 'shared_skills.migration.enabled';
+// Read through the namespace so the fail-first run on a tree without them reports the missing behaviour, not an import error.
+const { migrationLedgerSummary } = ledger;
+const MIGRATION_OPT_OUT_KEYS = ledger.MIGRATION_OPT_OUT_KEYS;
+const optOut = ledger as Pick<typeof ledger, 'isMigrationDeclinedValue' | 'declinedMigrations'>;
+const work = mkdtempSync(join(tmpdir(), 'gbrain-decline-6466-'));
+const TEMPLATE = join(work, 'template.pglite');
+const homes: string[] = [];
+
+beforeAll(async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: TEMPLATE });
+ await engine.initSchema();
+ await engine.disconnect();
+}, 180_000);
+
+afterAll(() => {
+ for (const home of homes) rmSync(home, { recursive: true, force: true });
+ rmSync(work, { recursive: true, force: true });
+});
+
+async function pgliteHome(configValue: string | null): Promise<string> {
+ const home = makeHome({ engine: 'pglite' });
+ homes.push(home);
+ const datastore = join(home, 'brain.pglite');
+ cpSync(TEMPLATE, datastore, { recursive: true });
+ if (configValue !== null) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: datastore });
+ await engine.setConfig(KEY, configValue);
+ await engine.disconnect();
+ }
+ return home;
+}
+
+async function run(home: string, opts: SchemaDriverOpts) {
+ const result = await collect(spawnDriver(home, writeSchemaDriver(home, opts)));
+ const logPath = join(home, 'orchestrator.log');
+ return { ...result, log: existsSync(logPath) ? readFileSync(logPath, 'utf8') : '', out: result.stderr + result.stdout };
+}
+
+describe('#6466 shared-skills migration opt-out', () => {
+ test('the shared-content migration declares the opt-out key and the registry-free table matches every optOut', () => {
+ expect(sharedContentMigration.optOut).toEqual({ key: KEY });
+ const fromRegistry = Object.fromEntries(migrations.filter((m) => m.optOut).map((m) => [m.version, m.optOut!.key]));
+ expect(MIGRATION_OPT_OUT_KEYS).toEqual(fromRegistry);
+ });
+
+ test('apply-migrations --yes skips the declined reconcile re-check and runs the rest', async () => {
+ const home = await pgliteHome('false');
+ const r = await run(home, { migrations: ['declinable', 'noop'], args: ['--yes', '--non-interactive', '--no-autopilot-install', '--json'] });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran noop\n');
+ const doc = parseDocument(r.stdout);
+ expect(doc.plan.declined).toEqual(['0.53.0']);
+ expect(doc.plan.applied).toEqual([]);
+ }, 180_000);
+
+ test('with the key true or absent the re-check runs as before', async () => {
+ for (const value of ['true', null]) {
+ const home = await pgliteHome(value);
+ const r = await run(home, { migrations: ['declinable'], args: ['--yes', '--non-interactive', '--no-autopilot-install'] });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran declinable\n');
+ }
+ }, 180_000);
+
+ test('--list --json reports the migration declined with its key, not as needing action', async () => {
+ const home = await pgliteHome('false');
+ const r = await run(home, { migrations: ['declinable'], args: ['--list', '--json'] });
+ expect(r.code, r.out).toBe(0);
+ const doc = parseDocument(r.stdout);
+ expect(doc.migrations).toEqual([{ version: '0.53.0', status: 'declined', headline: 'schema exit probe declinable', opt_out: { key: KEY } }]);
+ expect(doc.needs_action).toBe(0);
+ expect(r.log).toBe('');
+ const human = await run(home, { migrations: ['declinable'], args: ['--list'] });
+ expect(human.code, human.out).toBe(0);
+ expect(human.stdout).toMatch(/declined\s+0\.53\.0/);
+ expect(human.stdout).toContain(KEY);
+ }, 180_000);
+
+ test('an explicit --migration 0.53.0 refuses with exit 3 migration_declined and writes nothing', async () => {
+ const home = await pgliteHome('false');
+ const r = await run(home, { migrations: ['declinable'], args: ['--migration', '0.53.0', '--yes', '--json'] });
+ expect(r.code, r.out).toBe(3);
+ expect(r.log).toBe('');
+ const doc = JSON.parse(r.stdout);
+ expect(doc.code).toBe('migration_declined');
+ expect(doc.class).toBe('consent');
+ expect(doc.fix.next).toBe('ask_user');
+ expect(doc.fix.argv).toEqual(['gbrain', 'config', 'set', KEY, 'true']);
+ expect(doc.fix.verify.argv).toEqual(['gbrain', 'apply-migrations', '--list', '--json']);
+ expect(doc.message).toContain(KEY);
+ const dry = await run(home, { migrations: ['declinable'], args: ['--migration', '0.53.0', '--dry-run'] });
+ expect(dry.code, dry.out).toBe(0);
+ expect(dry.stdout).toContain('Declined');
+ expect(dry.log).toBe('');
+ }, 180_000);
+});
+
+describe('#6466 declined migrations in doctor and the ledger summary', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('isMigrationDeclinedValue accepts only explicit off values', () => {
+ for (const v of ['false', '0', 'off', 'no', ' False ']) expect(optOut.isMigrationDeclinedValue(v)).toBe(true);
+ for (const v of ['true', '1', 'on', '', 'maybe', null, undefined]) expect(optOut.isMigrationDeclinedValue(v)).toBe(false);
+ });
+
+ test('declinedMigrations reads the real registry from the brain config', async () => {
+ expect([...await optOut.declinedMigrations(engine)]).toEqual([]);
+ await engine.setConfig(KEY, 'false');
+ expect([...await optOut.declinedMigrations(engine)]).toEqual(['0.53.0']);
+ await engine.setConfig(KEY, 'true');
+ expect([...await optOut.declinedMigrations(engine)]).toEqual([]);
+ });
+
+ test('migrationLedgerSummary lists a declined version as declined, never pending', () => {
+ const plain = migrationLedgerSummary(VERSION);
+ const declined = migrationLedgerSummary(VERSION, new Set(['0.53.0']));
+ expect(declined.declined).toEqual(['0.53.0']);
+ expect(declined.pending).not.toContain('0.53.0');
+ expect(declined.pending_fresh_install).not.toContain('0.53.0');
+ expect(declined.partial).not.toContain('0.53.0');
+ expect(plain.declined).toEqual([]);
+ });
+
+ test('doctor minions_migration reports the declined migration as ok with its key', async () => {
+ await engine.setConfig(KEY, 'false');
+ const ctx = { engine, progress: { heartbeat() {}, finish() {} }, args: [] } as unknown as DoctorContext;
+ const checks = await minionsMigrationEntry.run(ctx) as Check[];
+ const declined = checks.find((c) => c.name === 'minions_migration' && c.details && 'declined' in (c.details as object));
+ expect(declined).toBeDefined();
+ expect(declined!.status).toBe('ok');
+ expect(declined!.message).toContain('0.53.0');
+ expect(declined!.message).toContain(KEY);
+ expect((declined!.details as { declined: string[] }).declined).toEqual(['0.53.0']);
+ expect(checks.filter((c) => c.name === 'minions_migration' && c.status !== 'ok')).toEqual([]);
+ });
+});