Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): apply-migrations --list and doctor report applied_pending_host_work (#6796)
time-attack891d015df8dd
diff --git a/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.mdindex 6dbe9a2d0c..a5a25ec922 100644--- a/docs/guides/shared-brain-skills.md+++ b/docs/guides/shared-brain-skills.md@@ -385,6 +385,23 @@ does not expose them to every source. Do not count `pending_host_work` orper-source `action_required` as completion even if the migration ledger saysthe mechanical checkpoint completed.+While a source's inventory, ownership (writer), projection or policy stage, or+a brain-level pending action, is still open, `gbrain apply-migrations --list` shows 0.53.0 as+`applied_pending_host_work` (not `applied`), `--list --json` adds an+`applied_pending_host_work` array whose `fix.argv` is the read-only+inventory, and `gbrain doctor` warns on `minions_migration` with+`details.code: migration_host_work_pending`:++```bash+gbrain apply-migrations --migration 0.53.0 --dry-run --json # each source's next step; changes nothing+gbrain apply-migrations --yes # after the work: the re-check records it done+```++The `members` stage alone (no installation enrolled yet, as on every new+brain) is not host work, and neither is a source that opted out with+`gbrain sources shared-skills <id> off`; a brain that declines the migration+(below) never reports it.+The host report's `member_installations` inventories known members per source,with `joined`, `refresh_pending`, `delivery_reported`, `source_changed`, or`left` and a `next_action`. `delivery_reported` means client-reported artifactdiff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 746eb12ddc..3941d207e0 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -26,7 +26,7 @@ import {import { loadCompletedMigrations, appendCompletedMigration, type CompletedMigrationEntry } from '../core/preferences.ts';import { migrations, compareVersions, type Migration, type OrchestratorOpts } from './migrations/index.ts';import { setRunEngineSharing, withRunEngineSession } from './migrations/run-engine.ts';-import { migrationDeclinedError, readDeclinedMigrations } from './migrations/opt-out.ts';+import { migrationDeclinedError, readDeclinedMigrations, readHostWorkMigrations } from './migrations/opt-out.ts';import {indexCompletedEntries,statusForVersion as ledgerStatusForVersion,@@ -34,6 +34,8 @@ import {isFreshInstallStamp,forwardProgressPast,isPendingFreshInstall,+ hostWorkInspectArgv,+ hostWorkPendingForVersion,MAX_CONSECUTIVE_PARTIALS,wedgedLedgerHint,} from '../core/migration-ledger.ts';@@ -155,6 +157,14 @@ Usage:pending_fresh_install = setup work abrain created by gbrain init has notrun yet (expected; apply with --yes).+ applied_pending_host_work = the+ checkpoint is recorded but host work+ (publication, client activation) is+ not done; inspect it with --migration+ <v> --dry-run --json, then --yes+ records it (doctor minions_migration).+ Unenrolled members and opted-out+ sources are not host work.gbrain apply-migrations --migration vX.Y.ZForce-run a specific migration by version.gbrain apply-migrations --force-retry vX.Y.Z@@ -224,6 +234,8 @@ function statusForVersion(interface Plan {applied: Migration[];+ /** #6796: applied migrations whose ledger row records host work and whose stored report still names some (a subset of applied). */+ applied_pending_host_work: Migration[];partial: Migration[];pending: Migration[];/** Never run on a brain gbrain init created at or after its version: expected setup work, not an interrupted upgrade. */@@ -253,8 +265,8 @@ interface Plan {* 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, declined: ReadonlySet<string> = new Set()): Plan {- const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [], wedged_superseded: [], declined: [] };+function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: string, declined: ReadonlySet<string> = new Set(), hostWork: ReadonlySet<string> = new Set()): Plan {+ const plan: Plan = { applied: [], applied_pending_host_work: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [], wedged_superseded: [], declined: [] };const ledger = [...idx.byVersion.values()].flat();for (const m of migrations) {if (filterVersion && m.version !== filterVersion) continue;@@ -264,8 +276,10 @@ function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: strin}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);+ if (status === 'complete') {+ plan.applied.push(m);+ if (hostWork.has(m.version) && hostWorkPendingForVersion(m.version, idx.byVersion)) plan.applied_pending_host_work.push(m);+ } else if (status === 'partial') plan.partial.push(m);else if (status === 'wedged') (forwardProgressPast(m.version, ledger) === null ? plan.wedged : plan.wedged_superseded).push(m);else if (isPendingFreshInstall(m.version, idx.freshVersion)) plan.pending_fresh_install.push(m);else plan.pending.push(m);@@ -297,7 +311,7 @@ const FINISH_SETUP_ARGV = ['gbrain', 'apply-migrations', '--yes', '--no-autopilofunction listRows(plan: Plan): Array<{ status: string; m: Migration }> {return [- ...plan.applied.map(m => ({ status: 'applied', m })),+ ...plan.applied.map(m => ({ status: plan.applied_pending_host_work.includes(m) ? 'applied_pending_host_work' : 'applied', m })),...plan.partial.map(m => ({ status: 'partial', m })),...[...plan.wedged, ...plan.wedged_superseded].map(m => ({ status: 'wedged', m })),...plan.pending.map(m => ({ status: 'pending', m })),@@ -324,8 +338,12 @@ function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): voidconst 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`);for (const m of plan.wedged) console.log(`v${m.version} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs). Read ${wedgedLedgerHint()}, fix the cause, then: ${shellQuote(forceRetryArgv(m.version))}`);+ for (const m of plan.applied_pending_host_work) {+ console.log(`v${m.version} is applied_pending_host_work: its mechanical checkpoint is recorded, but host publication or client activation is not done. `+ + `Inspect each source's next step: ${shellQuote(hostWorkInspectArgv(m.version))}; once that work is done, \`gbrain apply-migrations --yes\` records it in the migration's report.`);+ }if (needsWork === 0 && setup === 0 && plan.wedged.length === 0) {- console.log('All migrations up to date.');+ if (plan.applied_pending_host_work.length === 0) console.log('All migrations up to date.');return;}if (needsWork > 0) console.log(`${needsWork} migration(s) need action. Run \`gbrain apply-migrations --yes\` to apply.`);@@ -352,6 +370,8 @@ function listJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: Dneeds_action: plan.pending.length + plan.partial.length,...(plan.wedged.length ? { wedged: plan.wedged.map(m => ({ version: m.version, fix: { argv: forceRetryArgv(m.version), command: shellQuote(forceRetryArgv(m.version)) } })) } : {}),pending_fresh_install: plan.pending_fresh_install.length,+ ...(plan.applied_pending_host_work.length ? { applied_pending_host_work: plan.applied_pending_host_work.map(m => ({ version: m.version,+ fix: { argv: hostWorkInspectArgv(m.version), command: shellQuote(hostWorkInspectArgv(m.version)) } })) } : {}),...(outstanding > 0 ? { next: { argv: FINISH_SETUP_ARGV, command: shellQuote(FINISH_SETUP_ARGV) } } : {}),};}@@ -680,7 +700,9 @@ async function runLockedMigrations(const idx = indexCompleted(completed);await setRunEngineSharing(true);const declined = await readDeclinedMigrations(loadConfig()!);- const plan = buildPlan(idx, installed, cli.specificMigration, declined);+ const hostWork = cli.list && [...idx.byVersion.keys()].some(v => hostWorkPendingForVersion(v, idx.byVersion))+ ? await readHostWorkMigrations(loadConfig()!) : new Set<string>();+ const plan = buildPlan(idx, installed, cli.specificMigration, declined, hostWork);doc.database = dbProbe;doc.plan = Object.fromEntries(Object.entries(plan).map(([state, entries]) => [state, entries.map((migration: Migration) => migration.version)]));diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex 7a20d72781..e44914d7d5 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -12,6 +12,8 @@ import { MIGRATION_OPT_OUT_KEYS, declinedMigrations, indexCompletedEntries, isFrimport { VERSION } from '../../../version.ts';import { pendingFreshInstallCheck } from './pending-fresh-install.ts';import { autopilotInstallPendingCheck } from './autopilot-install-pending.ts';+import { migrationHostWorkCheck } from './migration-host-work.ts';+import { hostWorkMigrations } from '../../../core/shared-skills/migration-host-work.ts';import { compareVersions } from '../../migrations/index.ts';import { bootstrapDoctorChecks } from '../bootstrap-checks.ts';import { buildMemorableRelayCheck } from './integrations-memorable.ts';@@ -221,6 +223,8 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {const setup = pendingFreshInstallCheck();if (setup) checks.push(setup);}+ const hostWork = migrationHostWorkCheck(history, declined, engine ? await hostWorkMigrations(engine).catch(() => new Set<string>()) : new Set<string>());+ if (hostWork) checks.push(hostWork);const skippedInstall = autopilotInstallPendingCheck();if (skippedInstall) checks.push(skippedInstall);// Note: the "no preferences.json but schema is v7+" case is detecteddiff --git a/src/commands/doctor/checks/migration-host-work.ts b/src/commands/doctor/checks/migration-host-work.tsnew file mode 100644index 0000000000..36ec634985--- /dev/null+++ b/src/commands/doctor/checks/migration-host-work.ts@@ -0,0 +1,26 @@+/**+ * #6796: `minions_migration` line for an applied migration whose ledger row+ * records `apply_migrations_pending` and whose stored report still names host+ * work (`apply-migrations --list` status `applied_pending_host_work`): the+ * checkpoint landed, but publication or a source's writer setup is not done.+ * Unenrolled members and opted-out sources are not host work, and a declined+ * migration is never reported. Read-only.+ */+import { compareVersions, hostWorkInspectArgv, hostWorkPendingForVersion } from '../../../core/migration-ledger.ts';+import type { CompletedMigrationEntry } from '../../../core/preferences.ts';+import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';++export function migrationHostWorkCheck(history: Map<string, CompletedMigrationEntry[]>, declined: ReadonlySet<string>, hostWork: ReadonlySet<string>): Check | null {+ const versions = [...history.keys()].filter(v => !declined.has(v) && hostWork.has(v) && hostWorkPendingForVersion(v, history)).sort(compareVersions);+ if (versions.length === 0) return null;+ const argv = hostWorkInspectArgv(versions[0]);+ return {+ name: 'minions_migration',+ status: 'warn',+ message: `Migration(s) ${versions.join(', ')} applied_pending_host_work: the checkpoint is recorded, but host publication or source setup is not done. `+ + `Inspect each source's next step: ${argv.join(' ')}; once that work is done, \`gbrain apply-migrations --yes\` records it.`,+ fix: agentFix(argv, "Lists each source's pending host step (writer setup, publication) and its command; changes nothing.", 'minions_migration'),+ details: { code: 'migration_host_work_pending', applied_pending_host_work: versions },+ };+}diff --git a/src/commands/migrations/opt-out.ts b/src/commands/migrations/opt-out.tsindex 68eedd61d1..fc2c2ce39a 100644--- a/src/commands/migrations/opt-out.ts+++ b/src/commands/migrations/opt-out.ts@@ -15,6 +15,8 @@ import { declinedMigrations } from '../../core/migration-ledger.ts';import { opError, type OperationError } from '../../core/ops/contract.ts';import type { Migration } from './types.ts';import { connectMigrationEngine } from './run-engine.ts';+import { hostWorkMigrations } from '../../core/shared-skills/migration-host-work.ts';+import type { BrainEngine } from '../../core/engine.ts';export { declinedMigrations, isMigrationDeclinedValue } from '../../core/migration-ledger.ts';@@ -33,6 +35,17 @@ export async function readDeclinedMigrations(config: GBrainConfig): Promise<Set<}}+/** #6796: the applied migrations whose stored report still names host work; an unreachable brain reads as none. */+export async function readHostWorkMigrations(config: GBrainConfig): Promise<Set<string>> {+ if (isThinClient(config)) return new Set();+ try {+ const { engine, close } = await connectMigrationEngine(config);+ try { return await hostWorkMigrations(engine as BrainEngine); } finally { await close(); }+ } catch {+ return new Set();+ }+}+export function migrationDeclinedError(m: Migration): OperationError {const key = m.optOut?.key ?? '';return opError('migration_declined',diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 13b64a40b4..dad16c5a90 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -912,6 +912,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: 'A worker registry directory that exists but cannot be listed (permission denied, or a file where the directory should be) now reads as unknown worker liveness instead of no workers. Doctor `queue_health` reports `worker_alive: null` with a liveness-unknown message and no start-a-worker fix, `legacy_job_authority` reports `live_workers: null`, `gbrain jobs supervisor status --json` reports `workers: null`, a submitted job\'s `queue_state` omits `worker_alive` and warns that liveness is unknown, `gbrain jobs stats` reports a wedge instead of `no_worker`, and the `migrate-embeddings` plan warns about an unknown worker count. Each names the errno and path in `worker_registry_errno` and `worker_registry_path`. A missing registry directory still means no workers.' },{ since: '0.60.307.0', text: '`gbrain sources attach` with an invalid source id now refuses with `invalid_params` (a caller error) and a fix that lists the existing ids (`gbrain sources list --json`), instead of an `internal_error`. Nothing is written in either case.' },{ since: '0.60.307.0', text: 'On a managed brain, a dream synthesis output or summary whose publish is refused because the principal or brain outstanding-request cap (`persistence.limits.principal_outstanding`, `persistence.limits.brain_outstanding`) is full is now deferred like a pending publish: the phase warns with `publish_pending`, leaves the cooldown unstamped and the next cycle retries the same request, instead of failing the phase. A zero cap and cumulative quotas still fail it.' },+ // #6796 (apply-migrations applied_pending_host_work).+ { since: '0.60.307.0', text: '`gbrain apply-migrations --list` now shows v0.53.0 as `applied_pending_host_work` instead of `applied` while its stored shared-skills report still names host work (a source\'s inventory, writer, projection or publication-policy stage, or a brain-level pending action), and no longer prints "All migrations up to date" for it; `--list --json` rows carry that status and an `applied_pending_host_work` array whose fix is the read-only `gbrain apply-migrations --migration 0.53.0 --dry-run --json` inventory. Scripts that match `applied` should accept both. `gbrain doctor` warns on `minions_migration` (`details.code: migration_host_work_pending`) until a later `gbrain apply-migrations --yes` re-check finds the work done. Unenrolled members (every new brain), sources that opted out and a declined migration are never reported.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a5436d9dc..4d928ac8b0 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -403,6 +403,11 @@ export const CODES = {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'] },+ migration_host_work_pending: { class: 'host_only', summary: "A migration's mechanical checkpoint is recorded, but its stored report still names host work (for v0.53.0 a source's inventory, writer, projection or publication-policy stage, or a brain-level pending action); apply-migrations --list shows it applied_pending_host_work.",+ why: 'The ledger row is complete so the schema work never reruns, and v0.53.0 records apply_migrations_pending on every run because member enrollment is never verified, so the stored report decides (#6796): unenrolled members and sources that opted out are not host work. The next apply-migrations --yes re-check rewrites the report once the work is done.',+ docs: 'docs/guides/shared-brain-skills.md#migrate-an-existing-brain',+ suggestion: 'Run the read-only inventory `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host, do each source\'s next step it names (ask the user before publishing or activating), then run `gbrain apply-migrations --yes`.',+ fix: { argv: ['gbrain', 'apply-migrations', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists each migration\'s status and the read-only inventory command for host work still pending; changes nothing.', requires_exclusive: false } },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. 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`.',diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.tsindex 826dd0a153..4d0614764b 100644--- a/src/core/migration-ledger.ts+++ b/src/core/migration-ledger.ts@@ -107,6 +107,21 @@ export function statusForVersion(}/** Consecutive `partial` entries at the end of one version's ledger history: the wedge counter. A `retry` or `complete` entry resets it. */+/**+ * #6796: the latest ledger row for the version is `complete` but recorded+ * `apply_migrations_pending`: the mechanical checkpoint landed and host work+ * (publication, client activation) is still outstanding.+ */+export function hostWorkPendingForVersion(version: string, byVersion: Map<string, CompletedMigrationEntry[]>): boolean {+ const latest = byVersion.get(version)?.at(-1);+ return latest?.status === 'complete' && latest.apply_migrations_pending === true;+}++/** Read-only next step for host work a migration left pending: its per-source inventory. */+export function hostWorkInspectArgv(version: string): string[] {+ return ['gbrain', 'apply-migrations', '--migration', version, '--dry-run', '--json'];+}+export function trailingPartialCount(entries: readonly CompletedMigrationEntry[]): number {let consecutive = 0;for (let i = entries.length - 1; i >= 0 && entries[i].status === 'partial'; i--) consecutive++;diff --git a/src/core/shared-skills/migration-host-work.ts b/src/core/shared-skills/migration-host-work.tsnew file mode 100644index 0000000000..d8a367ac9d--- /dev/null+++ b/src/core/shared-skills/migration-host-work.ts@@ -0,0 +1,40 @@+/**+ * #6796: whether the v0.53.0 shared-skills migration still has host work a+ * person must do, read from its stored report (`shared_skills.migration.v1`).+ * The orchestrator records every run `apply_migrations_pending` because member+ * enrollment and native activation are never verified (a fresh brain reports+ * "No installation has enrolled"), so the `members` stage alone is not host+ * work, and neither is a projection the source's own policy blocks (opted out+ * with `sources shared-skills <id> off`, or a remote clone that needs an+ * explicit pack). Read-only.+ */+import type { BrainEngine } from '../engine.ts';+import type { SharedMigrationReport } from './migration.ts';+import { sharedSkillSourcePolicyOrPreserve } from './setup-source-policy.ts';++export const SHARED_SKILLS_HOST_WORK_VERSION = '0.53.0';++/** Sources whose stored migration stages still need host work, and the count of brain-level pending actions. */+export async function sharedSkillsHostWork(engine: BrainEngine): Promise<{ sources: string[]; pending_actions: number }> {+ let report: SharedMigrationReport;+ try {+ report = JSON.parse((await engine.getConfig('shared_skills.migration.v1')) ?? 'null');+ } catch {+ return { sources: [], pending_actions: 0 };+ }+ const sources: string[] = [];+ for (const row of report?.sources ?? []) {+ const open = row.stages.filter(s => s.stage !== 'members' && (s.status === 'action_required' || s.status === 'conflict'));+ if (open.length === 0) continue;+ const policyBlocked = open.every(s => s.stage === 'projection' && s.status === 'action_required')+ && (await sharedSkillSourcePolicyOrPreserve(engine, row.source_id)).mode !== 'content';+ if (!policyBlocked) sources.push(row.source_id);+ }+ return { sources, pending_actions: report?.pending_actions?.length ?? 0 };+}++/** The applied migrations whose recorded host work is still open (today only v0.53.0). */+export async function hostWorkMigrations(engine: BrainEngine): Promise<Set<string>> {+ const work = await sharedSkillsHostWork(engine);+ return new Set(work.sources.length || work.pending_actions ? [SHARED_SKILLS_HOST_WORK_VERSION] : []);+}diff --git a/test/apply-migrations-host-work-6796.test.ts b/test/apply-migrations-host-work-6796.test.tsnew file mode 100644index 0000000000..1cebb5a2e3--- /dev/null+++ b/test/apply-migrations-host-work-6796.test.ts@@ -0,0 +1,127 @@+/**+ * #6796: v0.53.0 records its checkpoint `complete` with+ * `apply_migrations_pending` on every run, because member enrollment and+ * native activation are never verified. `apply-migrations --list` and doctor+ * must report `applied_pending_host_work` only when the stored report+ * (`shared_skills.migration.v1`) names real host work (a source's writer or+ * publication stage, or a brain-level pending action), never for the+ * "no installation has enrolled" state a fresh brain is in, nor for a source+ * that opted out. Runner cases drive the real apply-migrations in a child+ * process against a stubbed registry (test/helpers/apply-migrations-schema-driver.ts,+ * kind `host_work`) on a PGLite brain whose config carries the report.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.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 } from './helpers/apply-migrations-schema-driver.ts';+import { withEnv } from './helpers/with-env.ts';++const INSPECT = ['gbrain', 'apply-migrations', '--migration', '0.53.0', '--dry-run', '--json'];+const REPORT_KEY = 'shared_skills.migration.v1';+const stage = (name: string, status: string) => ({ stage: name, status, reason: 'fixture' });+const report = (stages: object[], pendingActions: string[] = []) => JSON.stringify({ version: 1, status: 'action_required', pending_actions: pendingActions,+ permission_changes: [], sources: [{ source_id: 'default', stages, status: 'action_required' }] });+const UNENROLLED = report([stage('inventory', 'complete'), stage('ownership', 'complete'), stage('projection', 'complete'), stage('policy', 'complete'), stage('members', 'action_required')]);+const WRITER_NOT_QUIESCED = report([stage('inventory', 'complete'), stage('ownership', 'action_required')]);+const OPTED_OUT = report([stage('projection', 'action_required')]);+const work = mkdtempSync(join(tmpdir(), 'gbrain-host-work-6796-'));+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(stored: string): Promise<string> {+ const home = makeHome({ engine: 'pglite' });+ homes.push(home);+ const datastore = join(home, 'brain.pglite');+ cpSync(TEMPLATE, datastore, { recursive: true });+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: datastore });+ await engine.setConfig(REPORT_KEY, stored);+ await engine.disconnect();+ return home;+}++async function list(home: string, json: boolean) {+ const result = await collect(spawnDriver(home, writeSchemaDriver(home, { migrations: ['host_work'], args: json ? ['--list', '--json'] : ['--list'] })));+ expect(result.code, result.stderr + result.stdout).toBe(0);+ return result.stdout;+}++describe('#6796 apply-migrations --list', () => {+ test('a writer stage still open: applied_pending_host_work with the read-only inventory as its fix', async () => {+ const home = await pgliteHome(WRITER_NOT_QUIESCED);+ const doc = parseDocument(await list(home, true));+ expect(doc.migrations).toEqual([{ version: '0.53.0', status: 'applied_pending_host_work', headline: 'schema exit probe host_work' }]);+ expect(doc.applied_pending_host_work).toEqual([{ version: '0.53.0', fix: { argv: INSPECT, command: INSPECT.join(' ') } }]);+ const human = await list(home, false);+ expect(human).toMatch(/applied_pending_host_work\s+0\.53\.0/);+ expect(human).toContain(INSPECT.join(' '));+ expect(human).not.toContain('All migrations up to date');+ }, 180_000);++ test('only unenrolled members (a fresh brain) is applied and up to date', async () => {+ const home = await pgliteHome(UNENROLLED);+ const doc = parseDocument(await list(home, true));+ expect(doc.migrations).toEqual([{ version: '0.53.0', status: 'applied', headline: 'schema exit probe host_work' }]);+ expect(doc.applied_pending_host_work).toBeUndefined();+ expect(await list(home, false)).toContain('All migrations up to date');+ }, 180_000);+});++describe('#6796 doctor minions_migration', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ afterAll(async () => { await engine.disconnect(); });++ async function hostWorkChecks(stored: string): Promise<Check[]> {+ await engine.setConfig(REPORT_KEY, stored);+ const home = mkdtempSync(join(work, 'doctor-'));+ const ledgerDir = join(home, '.gbrain', 'migrations');+ mkdirSync(ledgerDir, { recursive: true });+ writeFileSync(join(ledgerDir, 'completed.jsonl'), JSON.stringify({ version: '0.53.0', status: 'complete', apply_migrations_pending: true }) + '\n');+ const ctx = { engine, progress: { heartbeat() {}, finish() {} }, args: [] } as unknown as DoctorContext;+ return withEnv({ GBRAIN_HOME: home }, async () => (await minionsMigrationEntry.run(ctx) as Check[])+ .filter(c => (c.details as { code?: string } | undefined)?.code === 'migration_host_work_pending'));+ }++ test('warns with the inventory fix while a writer stage or a pending action is open', async () => {+ const [check] = await hostWorkChecks(WRITER_NOT_QUIESCED);+ expect(check).toBeDefined();+ expect(check.name).toBe('minions_migration');+ expect(check.status).toBe('warn');+ expect(check.fix?.argv).toEqual(INSPECT);+ expect((check.details as { applied_pending_host_work: string[] }).applied_pending_host_work).toEqual(['0.53.0']);+ expect(await hostWorkChecks(report([stage('members', 'action_required')], ['Host-global catalog assignment is pending.']))).toHaveLength(1);+ });++ test('quiet for unenrolled members, an opted-out source and a declined migration', async () => {+ expect(await hostWorkChecks(UNENROLLED)).toEqual([]);+ await engine.executeRaw(`UPDATE sources SET config = config || '{"shared_skills": false}'::jsonb WHERE id = 'default'`);+ expect(await hostWorkChecks(OPTED_OUT)).toEqual([]);+ await engine.executeRaw(`UPDATE sources SET config = config - 'shared_skills' WHERE id = 'default'`);+ expect(await hostWorkChecks(OPTED_OUT)).toHaveLength(1);+ await engine.setConfig('shared_skills.migration.enabled', 'false');+ expect(await hostWorkChecks(WRITER_NOT_QUIESCED)).toEqual([]);+ });+});diff --git a/test/helpers/apply-migrations-schema-driver.ts b/test/helpers/apply-migrations-schema-driver.tsindex 3086768881..0cf47584f0 100644--- a/test/helpers/apply-migrations-schema-driver.ts+++ b/test/helpers/apply-migrations-schema-driver.ts@@ -3,7 +3,7 @@* stubbed orchestrator registry, so a test controls which orchestrator work is* pending while the schema-version check runs for real (PGLite or Postgres).*/-import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';+import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';import { join, resolve } from 'node:path';const REPO = resolve(import.meta.dir, '..', '..');@@ -15,8 +15,10 @@ const REPO = resolve(import.meta.dir, '..', '..');* 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.+ * `host_work` is that same applied 0.53.0 re-check whose ledger row records+ * `apply_migrations_pending` (#6796; seeded once per home).*/-export type StubMigration = 'reconcile' | 'noop' | 'migrate_schema' | 'hide_version' | 'fail' | 'declinable';+export type StubMigration = 'reconcile' | 'noop' | 'migrate_schema' | 'hide_version' | 'fail' | 'declinable' | 'host_work';export interface SchemaDriverOpts {args: string[];@@ -42,7 +44,10 @@ export function writeSchemaDriver(home: string, opts: SchemaDriverOpts): stringif (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}` }));+ if (opts.migrations.includes('host_work') && !existsSync(join(ledgerDir, 'completed.jsonl'))) {+ appendFileSync(join(ledgerDir, 'completed.jsonl'), `${JSON.stringify({ version: '0.53.0', status: 'complete', apply_migrations_pending: true })}\n`);+ }+ const stubs = opts.migrations.map((kind, i) => ({ kind, version: kind === 'reconcile' ? '0.0.1' : kind === 'declinable' || kind === 'host_work' ? '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';@@ -67,13 +72,14 @@ const actions = {hide_version: () => withEngine(engine => engine.executeRaw('ALTER TABLE config RENAME TO config_hidden_6089')),fail: async () => {},declinable: async () => {},+ host_work: 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' } } : {}),+ ...(kind === 'declinable' || kind === 'host_work' ? { 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/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.tsindex fe8efedc31..91a9a97f5d 100644--- a/test/helpers/config-reader-registry.ts+++ b/test/helpers/config-reader-registry.ts@@ -52,6 +52,7 @@ export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [{ key: 'shared_skills.export.v1.', prefix: true, reason: 'shared-skills migration export receipts' },{ key: 'shared_skills.content.v1.', prefix: true, reason: 'shared-skills content setup state per source incarnation' },{ key: 'shared_skills.migration.v1.', prefix: true, reason: 'shared-skills migration checkpoints per source incarnation' },+ { key: 'shared_skills.migration.v1', reason: 'the shared-skills migration report the 0.53.0 migration writes and apply-migrations --list / doctor read for host work (#6796)' },{ key: 'shared_skills.bridge_owner.v1.', prefix: true, reason: 'shared-brain bridge ownership claims' },];