Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Stop printing a stale wedged-migration notice on every command, and name each source conflict with a code and next step (#9550)
Garry Tanf739678e2f4a
diff --git a/behavior-changes.d/migration_wedge_notice_history.md b/behavior-changes.d/migration_wedge_notice_history.mdnew file mode 100644index 0000000000..28eee4bdc2--- /dev/null+++ b/behavior-changes.d/migration_wedge_notice_history.md@@ -0,0 +1,4 @@+---+kind: fix+---+Ordinary commands (remember, recall, config get and every command except apply-migrations, post-upgrade, upgrade, doctor, init and setup) no longer print a "wedged" migrations_pending notice, with a request to ask the user for a forced retry, for an upgrade migration that stopped three or more runs in a row once a newer migration has completed since. apply-migrations already treats such a wedge as history; since v0.60.725.0 the notice did not, so a brain with three old partial rows for v0.53.0 printed it on every call. A wedge with no newer migration past it still gets the notice. The v0.53.0 shared-skills migration's source conflicts stay visible where an operator looks: gbrain doctor (as a warning, when connected), gbrain apply-migrations --dry-run and --yes, and post-upgrade name each source in conflict with a code and its next step, read from the migration's read-only preview, and none of them advises --force-retry. A new code, shared_skills_unmanifested, marks a source whose skills/ folder holds skills with no skillpack.json declaring them: declare the ones to share in a skillpack.json at the source's root, or keep the source out of shared-skills adoption with gbrain sources shared-skills <id> off. Doctor stops warning once the preview finds no source in conflict. A named run of a wedged v0.53.0 still refuses, now with the read-only preview as its fix instead of a forced retry.diff --git a/changelog.d/capy-wedged-notice-history.md b/changelog.d/capy-wedged-notice-history.mdnew file mode 100644index 0000000000..e93ab69ff9--- /dev/null+++ b/changelog.d/capy-wedged-notice-history.md@@ -0,0 +1,15 @@+---+important: regression+---+**Commands no longer print a "wedged" migration notice asking for a forced retry once a newer migration has completed since; doctor and apply-migrations name each source still in conflict and its next step instead.**++### Fixed+- Since v0.60.725.0 every ordinary command (remember, recall, config get and the rest) printed `Upgrade migration(s) 0.53.0 failed several runs in a row and are wedged` with an ask-the-user `--force-retry` fix on a brain whose upgrade ledger held three old partial runs of a migration, even though a newer migration had completed since and `gbrain apply-migrations` called it history. The notice now follows apply-migrations, which treats that migration as history, so ordinary commands print nothing about it. A stuck migration with no newer migration past it still gets the notice.+- The shared-skills migration (v0.53.0) reports a source conflict where an operator looks, and never advises a forced retry: `gbrain doctor` (connected) warns with each source in conflict, its code and its next step, and goes quiet once none is left; `gbrain apply-migrations --dry-run`, `--yes` and `post-upgrade` name the same sources. They read the migration's own read-only preview, which takes under a second on a brain with five sources of 20,000 files each.+- A source conflict now carries a code. `shared_skills_unmanifested` (`gbrain errors shared_skills_unmanifested`) means a source's `skills/` folder holds skills with no `skillpack.json` declaring them: declare the ones to share in a `skillpack.json` at the source's root, or keep the source out of shared-skills adoption with `gbrain sources shared-skills <id> off`. Other conflicts carry the code of the error that stopped the inventory.+- A named run of a wedged v0.53.0 (`gbrain apply-migrations --migration 0.53.0 --yes`) still refuses, now with the read-only preview as its fix instead of a forced retry.++### Tests+- A source with no local path (a database-only source such as the conversation archive's) is pinned never to answer a path lookup, on PGLite and Postgres.++<!-- behavior-change: migration_wedge_notice_history -->diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 2b6bea7a29..4071250265 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Phase F (`v0_11_0-install.ts`) reinstalls only an existing autopilot. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history; a v0.53.0 wedge whose latest row records `apply_migrations_pending` still owes host work, `hostWorkOwedForVersion` (other migrations set that flag on ordinary partials and keep the forward-progress rule), is never superseded: it is listed as `wedged_host_work` with the read-only `--migration <v> --dry-run --json` inspect as its fix and `ask_user` `--force-retry` after it, nothing reruns it, and it fails a run only when no newer migration ran past it; tests `migration-host-work-owed.test.ts`) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; every wedged-migration message (run envelope, `--list`, stderr, `gbrain upgrade`) points at the migration's partial rows in this brain's `migrations/completed.jsonl` (`phases[].detail`, if present) through `wedgedLedgerHint` (`src/core/migration-ledger.ts`); a phase's `argv` prints as its next step. v0.11.0 Phase F (`src/commands/migrations/v0_11_0-install.ts`) installs the autopilot only for the brain's `sync.repo_path`; without one it installs nothing, is `skipped` with the exact install command (the default source's `local_path`, else `<REPO_PATH>`), records an `autopilot-install-needs-repo` pending host-work item, and the migration completes; doctor's `minions_migration` line (`src/commands/doctor/checks/autopilot-install-pending.ts`) carries that argv (`persistent_install`) until an autopilot is installed for this brain. Phase F records a `reason` code on those outcomes (`no_repo_path`, `autopilot_already_installed`, `install_failed`). `clearRepoPathWedge` writes a `retry` marker (reason `phase_f_no_repo_path`) before the plan when every partial behind a v0.11.0 wedge failed only the install phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's `sync.repo_path` is unset, so Phase F would now skip; with it set, or any other wedge, the `--force-retry` advice stands. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.+- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Phase F (`v0_11_0-install.ts`) reinstalls only an existing autopilot. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history; a v0.53.0 wedge whose latest row records `apply_migrations_pending` still owes host work, `hostWorkOwedForVersion` (other migrations set that flag on ordinary partials and keep the forward-progress rule), is never superseded: it is listed as `wedged_host_work` with the read-only `--migration <v> --dry-run --json` inspect as its fix plus each conflicting source's code and next step (`owedConflicts`), never `--force-retry`; nothing reruns it, the notice skips it once superseded, and it fails a run only when no newer migration ran past it; tests `migration-host-work-owed.test.ts`) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; every wedged-migration message (run envelope, `--list`, stderr, `gbrain upgrade`) points at the migration's partial rows in this brain's `migrations/completed.jsonl` (`phases[].detail`, if present) through `wedgedLedgerHint` (`src/core/migration-ledger.ts`); a phase's `argv` prints as its next step. v0.11.0 Phase F (`src/commands/migrations/v0_11_0-install.ts`) installs the autopilot only for the brain's `sync.repo_path`; without one it installs nothing, is `skipped` with the exact install command (the default source's `local_path`, else `<REPO_PATH>`), records an `autopilot-install-needs-repo` pending host-work item, and the migration completes; doctor's `minions_migration` line (`src/commands/doctor/checks/autopilot-install-pending.ts`) carries that argv (`persistent_install`) until an autopilot is installed for this brain. Phase F records a `reason` code on those outcomes (`no_repo_path`, `autopilot_already_installed`, `install_failed`). `clearRepoPathWedge` writes a `retry` marker (reason `phase_f_no_repo_path`) before the plan when every partial behind a v0.11.0 wedge failed only the install phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's `sync.repo_path` is unset, so Phase F would now skip; with it set, or any other wedge, the `--force-retry` advice stands. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.- `src/commands/migrations/run-engine.ts` — one PGLite engine for consecutive migrations of an apply-migrations run (each open starts an embedded Postgres, about 130 ms). `withRunEngineSession` wraps the locked run; `setRunEngineSharing` enables sharing for the opt-out read, each migration flagged `sharesRunEngine` (v0.11.0, v0.14.0, v0.22.4, v0.28.0, v0.53.0) and the post-orchestrator schema check, and disabling it (before an unflagged migration, `--list`, `--dry-run` or a consent prompt) closes the engine. `connectMigrationEngine` returns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always). `releaseRunEngine` closes it before a `gbrain` child that needs the brain (v0.11.0's `jobs smoke`). A fresh setup's migration child opens the brain three times instead of eight (counting the `jobs smoke` child); the ledger it writes is pinned by `test/fixtures/goldens/setup/fresh-setup-migration-ledger.json`. Tests: `test/migrations-run-engine.test.ts`.- `src/commands/apply-migrations-schema.ts` — #6089 schema half of the apply-migrations exit contract. `connectAtSchemaVersion` connects the configured brain and reads `config.version` (pre-flight, `--force-schema`); the post-orchestrator check opens it through `connectMigrationEngine`. `checkSchemaAfterOrchestrators` re-reads the version after the orchestrators ran: on Postgres only when the pre-flight connected; on PGLite in-process once the orchestrators released the datastore (the pre-flight stays skipped, #1100; never a child process), applying the schema migrations under `--yes`/`--non-interactive`; a busy PGLite datastore is rethrown. `schemaPendingError` builds `migrations_pending` with reason `not_applied` (fix reruns with `--yes`), `still_behind` (after an authorized run) or `schema_unreadable` (both fix `next: report` with `gbrain doctor --json` as verify, never another `--yes`), each naming the pending schema versions. `reportDatabaseUnreachable` keeps an unreachable Postgres non-fatal but prints the `GBRAIN_DB_ACCESS <reason>` marker. Tests: `test/apply-migrations-schema-exit.test.ts` (PGLite, unreachable Postgres, post-upgrade, postinstall) and `test/e2e/apply-migrations-schema-exit.test.ts` (Postgres).diff --git a/docs/contracts/public-surface.json b/docs/contracts/public-surface.jsonindex f71bcf9b29..0014ebf901 100644--- a/docs/contracts/public-surface.json+++ b/docs/contracts/public-surface.json@@ -2917,6 +2917,7 @@"setup_serves_several": 1,"setup_serves_unreadable": 1,"shared_skills_unavailable": 1,+ "shared_skills_unmanifested": 1,"shared_skills_unsupported": 1,"skill_asset_not_found": 1,"skill_bundle_required": 1,diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e32224aef4..629b08366a 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3390,7 +3390,7 @@ Reasons: `orchestrator_failed`, `orchestrator_threw`, `ledger_write_failed`, `pr| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Doctor warning: a migration stopped three or more runs in a row on a conflict in one or more sources and recorded that host work is still owed (today only v0.53.0), so it is wedged even if a newer migration has completed since. | A newer migration completing does not do the work a wedged migration owes, and nothing reruns a wedged migration by itself, so it does not clear without a person. Each source's conflict needs the user's decision before a forced retry, or the retry stops on the same conflict again. | Run the read-only inspect `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host to see each source's conflict. Once the user has reviewed each one, clear the wedge with `gbrain apply-migrations --force-retry <version>`, then run the command the inspect output names for each source, or `gbrain apply-migrations --yes`. Run: gbrain apply-migrations --list --json | user | `gbrain doctor --json` | 1 | no |+| Doctor warning: a migration stopped three or more runs in a row on a conflict in one or more sources and recorded that host work is still owed (today only v0.53.0). | Each source in conflict needs the user's decision. The migration's read-only preview names each source, its conflict code and the step that settles it, and doctor stops warning once the preview finds no source in conflict. | Run the read-only inspect `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host to see each source's conflict, its code and its next step, and settle each one with the user. For shared_skills_unmanifested, declare the skills to share in a skillpack.json at the source's root, or keep the source out with `gbrain sources shared-skills <id> off`. Run: gbrain apply-migrations --list --json | user | `gbrain doctor --json` | 1 | no |More: [docs/guides/shared-brain-skills.md#reviewed-changes-after-inventory](../../docs/guides/shared-brain-skills.md#reviewed-changes-after-inventory)@@ -5032,6 +5032,16 @@ More: [docs/guides/repair.md#setup-owner-conflict](../../docs/guides/repair.md#s|---|---|---|---|---|---|---|| The shared-skills operation was refused. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### shared_skills_unmanifested++<a id="shared_skills_unmanifested"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A conflict in the v0.53.0 shared-skills migration: a source's skills/ folder holds skills but the source has no skillpack.json declaring them, so the migration left them as they are. | Adopting skills nobody declared could publish private or half-finished ones, so the migration never adopts them and records the source as a conflict until a person decides. The conflict affects only shared-skills adoption; every other command works. | Review the skills in that source's skills/ folder with the user, then either declare the ones to share in a skillpack.json at the source's root, or keep the source out of shared-skills adoption with `gbrain sources shared-skills <id> off`. Run: gbrain apply-migrations --dry-run --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/shared-brain-skills.md#migrate-an-existing-brain](../../docs/guides/shared-brain-skills.md#migrate-an-existing-brain)+### shared_skills_unsupported<a id="shared_skills_unsupported"></a>diff --git a/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.mdindex bffcae3e06..11670e35dd 100644--- a/docs/guides/shared-brain-skills.md+++ b/docs/guides/shared-brain-skills.md@@ -538,12 +538,21 @@ before parking existed) resumes with`gbrain apply-migrations --migration 0.53.0 --yes`; the oversized source parksand the migration completes.-A 0.53.0 migration wedged on a source conflict still owes that work, even after-a newer migration completes, and it does not clear without a person. Run+A 0.53.0 migration wedged on a source conflict is reported by `gbrain doctor`,+`gbrain apply-migrations --dry-run` and `post-upgrade`, each naming the sources+in conflict, the code and the next step; ordinary commands say nothing about it+once a newer migration has completed. Run`gbrain apply-migrations --migration 0.53.0 --dry-run --json` (it changes-nothing) to see each source's conflict, resolve it with the user, and only then-run `gbrain apply-migrations --force-retry 0.53.0` and the command the output-names for that source, or `gbrain apply-migrations --yes`.+nothing) to see each source's state, then settle each conflict with the user.+For `shared_skills_unmanifested` (skills in the source's `skills/` folder that no+`skillpack.json` declares), declare the ones to share in a `skillpack.json` at+the source's root, or keep the source out with+`gbrain sources shared-skills <id> off`. Doctor stops warning once the preview+has inspected every source and finds none in conflict; a source whose policy it+could not read (a dropped database connection, for example) keeps the warning.+Don't clear the wedge with `--force-retry` for this:+the next `--yes` run would also publish each source's pending shared-skills+content.## Troubleshoot, leave, and recoverdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 0cd5deb7dc..071c8ac5f8 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -402,7 +402,7 @@ test/shared-skills-optimizer.serial.test.ts (file-level) 15 readFileSynctest/shared-skills-publication-sparse.test.ts (file-level) 4 readFileSynctest/shared-skills-setup.test.ts packaged default skills 2 readFileSynctest/shared-skills-setup.test.ts shared-skills migration recovery (#5569, #5476, A-NEW-4) 4 readFileSync-test/shared-skills-setup.test.ts staged skill migration 7 readFileSync+test/shared-skills-setup.test.ts staged skill migration 8 readFileSynctest/shared-skills-writer-boundary.test.ts (file-level) 7 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: codex project catalog 2 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: compiled binaries 1 readFileSyncdiff --git a/src/cli/migrations-notice.ts b/src/cli/migrations-notice.tsindex 55cb6a781c..60315818eb 100644--- a/src/cli/migrations-notice.ts+++ b/src/cli/migrations-notice.ts@@ -22,9 +22,13 @@ export async function pendingUpgradeMigrationsNotice(engine: BrainEngine, commanconst ledger = await import('../core/migration-ledger.ts');if (!ledger.upgradeLedgerApplies(engine)) return null;const summary = ledger.migrationLedgerSummary(version, await ledger.declinedMigrations(engine));- const history = ledger.indexCompletedEntries((await import('../core/preferences.ts')).loadCompletedMigrations());- const owed = summary.wedged.filter(v => ledger.hostWorkOwedForVersion(v, history));- const wedged = summary.wedged.filter(v => !owed.includes(v));+ const entries = (await import('../core/preferences.ts')).loadCompletedMigrations();+ const history = ledger.indexCompletedEntries(entries);+ // A wedge a newer completed migration ran past is history to apply-migrations, which then exits 0, so commands stay quiet+ // about it; doctor and apply-migrations --dry-run still report a conflict it left (its host work owed).+ const live = summary.wedged.filter(v => ledger.forwardProgressPast(v, entries) === null);+ const owed = live.filter(v => ledger.hostWorkOwedForVersion(v, history));+ const wedged = live.filter(v => !owed.includes(v));if (wedged.length > 0) {const { wedgedMigrationFix } = await import('../commands/apply-migrations.ts');return { ...migrationsNotice(`Upgrade migration(s) ${wedged.join(', ')} failed several runs in a row and are wedged; the command ran, and apply-migrations --yes will not clear them until the cause is fixed.`), fix: wedgedMigrationFix(wedged) };diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 218c327368..812e63c828 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -41,7 +41,10 @@ import {hostWorkOwedMessage,MAX_CONSECUTIVE_PARTIALS,wedgedLedgerHint,+ type OwedConflict,} from '../core/migration-ledger.ts';+import { owedConflicts } from '../core/shared-skills/migration-host-work.ts';+import type { SharedMigrationReport } from '../core/shared-skills/migration.ts';import { clearRepoPathWedge } from './migrations/v0_11_0-install.ts';import { shellQuote, type Action, type Effect } from '../core/agent-output.ts';import { writeJsonDocument } from '../core/cli-force-exit.ts';@@ -512,6 +515,8 @@ interface RunReport {wedgedHostWork?: readonly Migration[];/** Every wedged migration with host work owed, past a newer migration or not: the run never says all migrations are up to date while one is listed. */hostWorkOwed?: readonly Migration[];+ /** The sources in conflict now, from the owed migration's read-only preview; null when it was not read. */+ owedConflicts?: OwedConflict[] | null;}function unknownMigrationError(version: string): OperationError {@@ -520,12 +525,23 @@ function unknownMigrationError(version: string): OperationError {{ fix: { argv: ['gbrain', COMMAND, '--list'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists every registered migration and its status.' } });}+/** The sources a wedged migration's read-only preview finds in conflict now; null when it has no preview or the preview fails. */+async function previewOwedConflicts(migration: Migration, cli: ApplyMigrationsArgs): Promise<OwedConflict[] | null> {+ if (!migration.preview) return null;+ try { return owedConflicts(await migration.preview({ ...orchestratorOptsFrom(cli), dryRun: true }) as SharedMigrationReport | null); }+ catch { return null; }+}+/** A named run of a wedged migration: it runs by name again only after its wedge is cleared; --list and --dry-run still inspect it. */function wedgedByNameError(version: string, hostWorkOwed: boolean): OperationError {+ if (hostWorkOwed) {+ return usageError(`Migration v${version} is wedged on a source conflict (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs), so it does not run by name.`,+ `See each source's conflict and the step that settles it (read-only): ${shellQuote(hostWorkInspectArgv(version))}.`,+ { fix: hostWorkOwedFix([version]) });+ }return usageError(`Migration v${version} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs), so it does not run by name until the wedge is cleared.`,- `${hostWorkOwed ? `See each source's conflict first (read-only): ${shellQuote(hostWorkInspectArgv(version))}. ` : `Read ${wedgedLedgerHint()} for the last failure and fix its cause. `}`- + `Then clear the wedge with ${shellQuote(forceRetryArgv(version))} and run this command again.`,- { fix: hostWorkOwed ? hostWorkOwedFix([version]) : wedgedMigrationFix([version]) });+ `Read ${wedgedLedgerHint()} for the last failure and fix its cause. Then clear the wedge with ${shellQuote(forceRetryArgv(version))} and run this command again.`,+ { fix: wedgedMigrationFix([version]) });}/** The same invocation again once the underlying failure is fixed; any approval it needs is asked by the run itself. */@@ -757,7 +773,8 @@ async function runLockedMigrations(report.wedged = plan.wedged;report.hostWorkOwed = plan.wedged_host_work;report.wedgedHostWork = plan.wedged_host_work.filter(m => forwardProgressPast(m.version, completed) === null);- reportWedgedMigrations(plan.wedged, plan.wedged_superseded, plan.wedged_host_work, completed);+ report.owedConflicts = plan.wedged_host_work.length && !cli.list ? await previewOwedConflicts(plan.wedged_host_work[0]!, cli) : null;+ reportWedgedMigrations(plan.wedged, plan.wedged_superseded, plan.wedged_host_work, completed, report.owedConflicts);const namedWedged = plan.wedged.length + plan.wedged_superseded.length + plan.wedged_host_work.length;const readOnlyWedged = cli.list || cli.dryRun ? namedWedged : 0;@@ -1081,9 +1098,9 @@ function failWedged(report: RunReport): number | undefined {if (!wedged.length && owed.length) {report.doc.status = 'wedged';report.doc.wedged = owed.map(m => m.version);- report.failure = opError('migrations_pending', hostWorkOwedMessage(owed.map(m => m.version)),- 'Run the read-only inspect in the fix, show the user each source\'s conflict, and clear the wedge only after they resolve it.',- { reason: 'wedged', fix: hostWorkOwedFix(owed.map(m => m.version)) });+ report.failure = opError('migrations_pending', hostWorkOwedMessage(owed.map(m => m.version), report.owedConflicts ?? null),+ 'Run the read-only inspect in the fix and show the user each source\'s conflict and the step that settles it.',+ { reason: 'wedged', fix: hostWorkOwedFix(owed.map(m => m.version), report.owedConflicts ?? null) });return 1;}if (!wedged.length) return undefined;@@ -1107,8 +1124,9 @@ export function wedgedMigrationFix(wedged: readonly string[]): Action {}/** Bug 3 — surface wedged migrations as a loud, actionable error; the run continues (applied/partial/pending are still reported and run). */-function reportWedgedMigrations(wedged: readonly Migration[], superseded: readonly Migration[], owed: readonly Migration[], completed: readonly CompletedMigrationEntry[]): void {- if (owed.length) console.error(`\n${hostWorkOwedMessage(owed.map(m => m.version))}`);+function reportWedgedMigrations(wedged: readonly Migration[], superseded: readonly Migration[], owed: readonly Migration[], completed: readonly CompletedMigrationEntry[],+ conflicts: OwedConflict[] | null): void {+ if (owed.length) console.error(`\n${hostWorkOwedMessage(owed.map(m => m.version), conflicts)}`);for (const m of superseded) {console.error(`\nMigration v${m.version} has ${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs, but v${forwardProgressPast(m.version, completed)} completed after it, `+ 'so it is history, not outstanding work. Nothing to do.');diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex 1c62995c09..be1a83d2d2 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -13,7 +13,8 @@ import { 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 { hostWorkMigrations, readOwedConflicts } from '../../../core/shared-skills/migration-host-work.ts';+import { loadConfig } from '../../../core/config.ts';import { compareVersions } from '../../migrations/index.ts';import { bootstrapDoctorChecks } from '../bootstrap-checks.ts';import { buildMemorableRelayCheck } from './integrations-memorable.ts';@@ -242,8 +243,11 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {}const hostWork = migrationHostWorkCheck(history, declined, engine ? await hostWorkMigrations(engine).catch(() => new Set<string>()) : new Set<string>());if (hostWork) checks.push(hostWork);- if (owed.length > 0) checks.push({ name: 'minions_migration', status: 'warn', message: hostWorkOwedMessage(owed), fix: hostWorkOwedFix(owed),- details: { code: 'migration_host_work_owed', wedged_host_work: owed } });+ // Connected, doctor reads which sources are in conflict now (the read-only preview); none left means the wedge is history.+ const config = engine && owed.length > 0 ? loadConfig() : null;+ const conflicts = engine && config ? await readOwedConflicts(engine, config) : null;+ if (owed.length > 0 && conflicts?.length !== 0) checks.push({ name: 'minions_migration', status: 'warn', message: hostWorkOwedMessage(owed, conflicts), fix: hostWorkOwedFix(owed, conflicts),+ details: { code: 'migration_host_work_owed', wedged_host_work: owed, ...(conflicts ? { conflicts } : {}) } });const skippedInstall = autopilotInstallPendingCheck();if (skippedInstall) checks.push(skippedInstall);// Note: the "no preferences.json but schema is v7+" case is detecteddiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 33fab4dba9..ab95ae24c3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -547,10 +547,10 @@ export const CODES = {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 } },- migration_host_work_owed: { class: 'host_only', retryable: false, actor: 'user', summary: "Doctor warning: a migration stopped three or more runs in a row on a conflict in one or more sources and recorded that host work is still owed (today only v0.53.0), so it is wedged even if a newer migration has completed since.",- why: 'A newer migration completing does not do the work a wedged migration owes, and nothing reruns a wedged migration by itself, so it does not clear without a person. Each source\'s conflict needs the user\'s decision before a forced retry, or the retry stops on the same conflict again.',+ migration_host_work_owed: { class: 'host_only', retryable: false, actor: 'user', summary: "Doctor warning: a migration stopped three or more runs in a row on a conflict in one or more sources and recorded that host work is still owed (today only v0.53.0).",+ why: 'Each source in conflict needs the user\'s decision. The migration\'s read-only preview names each source, its conflict code and the step that settles it, and doctor stops warning once the preview finds no source in conflict.',docs: 'docs/guides/shared-brain-skills.md#reviewed-changes-after-inventory',- suggestion: 'Run the read-only inspect `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host to see each source\'s conflict. Once the user has reviewed each one, clear the wedge with `gbrain apply-migrations --force-retry <version>`, then run the command the inspect output names for each source, or `gbrain apply-migrations --yes`.',+ suggestion: 'Run the read-only inspect `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host to see each source\'s conflict, its code and its next step, and settle each one with the user. For shared_skills_unmanifested, declare the skills to share in a skillpack.json at the source\'s root, or keep the source out with `gbrain sources shared-skills <id> off`.',fix: { argv: ['gbrain', 'apply-migrations', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists each wedged migration that still owes host work (wedged_host_work) with its read-only inspect command; 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; when a migration ran out of its statement budget (#7108) the error names it and its fix depends on the case: recorded by another release (rerun), an idle-in-transaction blocker (end it once the user agrees, rerun) or nothing blocking (once the user agrees, one run with --statement-timeout). 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).',@@ -779,6 +779,11 @@ export const CODES = {hook_session_cwd: { class: 'caller', summary: "A gbrain hook or stdio MCP entry (setup, the turn-rule lane, gbrain bootstrap's lanes) starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks and stdio MCP servers in the session directory, so a cloned repository could run code on every prompt or session.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },+ shared_skills_unmanifested: { class: 'host_only', summary: "A conflict in the v0.53.0 shared-skills migration: a source's skills/ folder holds skills but the source has no skillpack.json declaring them, so the migration left them as they are.",+ why: 'Adopting skills nobody declared could publish private or half-finished ones, so the migration never adopts them and records the source as a conflict until a person decides. The conflict affects only shared-skills adoption; every other command works.',+ docs: 'docs/guides/shared-brain-skills.md#migrate-an-existing-brain',+ suggestion: 'Review the skills in that source\'s skills/ folder with the user, then either declare the ones to share in a skillpack.json at the source\'s root, or keep the source out of shared-skills adoption with `gbrain sources shared-skills <id> off`.',+ fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists each source\'s shared-skills stage and names the sources in this conflict.', requires_exclusive: false } },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },skill_bundle_required: { class: 'caller', summary: "Import cannot publish skill paths." },diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.tsindex cb65b3bb16..96522bd257 100644--- a/src/core/migration-ledger.ts+++ b/src/core/migration-ledger.ts@@ -136,39 +136,68 @@ export function hostWorkInspectArgv(version: string): string[] {return ['gbrain', 'apply-migrations', '--migration', version, '--dry-run', '--json'];}-/** The one migration whose wedge can owe host work: v0.53.0, `SHARED_SKILLS_HOST_WORK_VERSION` (not imported: its module pulls in the shared-skills graph). */-const HOST_WORK_OWED_VERSION = '0.53.0';+/**+ * Upgrade migrations whose orchestrator declares `reconcile: true` (a per-source recheck that records host work, today the+ * shared-skills content migration). Registry-free mirror of that flag, pinned against the registry by+ * test/migration-ledger.test.ts like MIGRATION_OPT_OUT_KEYS.+ */+export const RECONCILE_MIGRATION_VERSIONS: readonly string[] = ['0.53.0'];/**- * v0.53.0 wedged with its latest row recording `apply_migrations_pending`: it stopped on a conflict in one or more sources- * that a person has to settle, and that work is still owed. A newer migration never supersedes it, and apply-migrations- * never runs it again by itself, so it stays until a person resolves the conflict and clears the wedge. Other migrations- * (v0.11.0, v0.14.0) set the same flag on ordinary partial runs, so their wedges keep the forward-progress rule.+ * A reconcile migration wedged with its latest row recording `apply_migrations_pending`: its per-source recheck stopped on+ * a conflict in one or more sources that a person has to settle. Other migrations (v0.11.0, v0.14.0) set the same flag on+ * ordinary partial runs, so their wedges keep the forward-progress rule.*/export function hostWorkOwedForVersion(version: string, byVersion: Map<string, CompletedMigrationEntry[]>): boolean {- return version === HOST_WORK_OWED_VERSION && statusForVersion(version, byVersion) === 'wedged' && byVersion.get(version)?.at(-1)?.apply_migrations_pending === true;+ return RECONCILE_MIGRATION_VERSIONS.includes(version) && statusForVersion(version, byVersion) === 'wedged' && byVersion.get(version)?.at(-1)?.apply_migrations_pending === true;}-function forceRetryArgv(version: string): string[] { return ['gbrain', 'apply-migrations', '--force-retry', version]; }+/** One source in conflict, read from the migration's read-only preview: the stage's code and reason. */+export interface OwedConflict { source_id: string; code: string; reason: string }++/** The step a person takes for one source's conflict. */+export function owedConflictNextStep(conflict: OwedConflict): string {+ if (conflict.code === 'shared_skills_unmanifested') {+ return 'review the skills in its skills/ folder with the user, then either declare the ones to share in a skillpack.json at the source\'s root, or keep the source out of '+ + 'shared-skills adoption with ' + ['gbrain', 'sources', 'shared-skills', conflict.source_id, 'off'].join(' ');+ }+ return 'settle what its reason names with the user';+}-/** The one description of a wedged version with host work owed, shared by every surface that reports it. */-export function hostWorkOwedMessage(versions: readonly string[]): string {+/**+ * The one description of a wedged migration with host work owed, shared by every surface that reports it. `conflicts` is+ * the live list from the read-only preview, or null where the surface cannot read it (no database, a remote caller).+ */+export function hostWorkOwedMessage(versions: readonly string[], conflicts: readonly OwedConflict[] | null = null): string {const first = versions[0]!;- return `Migration ${versions.map(v => `v${v}`).join(', ')} stopped ${MAX_CONSECUTIVE_PARTIALS}+ runs in a row on a conflict in one or more sources that a person has to resolve, and that work is still owed; `- + `a newer migration does not replace it, and it does not clear without a person. See each source's conflict (read-only): ${hostWorkInspectArgv(first).join(' ')}. `- + `Once the user has reviewed each one, clear the wedge with ${forceRetryArgv(first).join(' ')}, then run the command that output names for each source, or gbrain apply-migrations --yes.`;+ const named = versions.map(v => `v${v}`).join(', ');+ if (conflicts === null) {+ return `Migration ${named} stopped ${MAX_CONSECUTIVE_PARTIALS}+ runs in a row on a conflict in one or more sources that a person has to settle. `+ + `See each source's conflict and its next step (read-only): ${hostWorkInspectArgv(first).join(' ')}.`;+ }+ if (conflicts.length === 0) {+ return `Migration ${named} stopped ${MAX_CONSECUTIVE_PARTIALS}+ runs in a row on a source conflict, and its preview finds no source in conflict now, so nothing waits on a person. `+ + `See each source's state (read-only): ${hostWorkInspectArgv(first).join(' ')}.`;+ }+ return `Migration ${named} is stopped on a conflict in ${conflicts.length} source(s) that a person has to settle: `+ + conflicts.map(c => `${c.source_id} (${c.code}): ${c.reason} Next: ${owedConflictNextStep(c)}.`).join(' ')+ + ` Preview every source (read-only): ${hostWorkInspectArgv(first).join(' ')}.`;}-/** The fix for a wedged version with host work owed: the read-only per-source inspect first, then ask the user to clear it once the conflict is resolved. */-export function hostWorkOwedFix(versions: readonly string[]): Action {+/** The fix for a wedged migration with host work owed: the read-only per-source inspect, then the user's decision for each source in conflict now. */+export function hostWorkOwedFix(versions: readonly string[], conflicts: readonly OwedConflict[] | null = null): Action {const first = versions[0]!;- const verify = { argv: ['gbrain', 'apply-migrations', '--list', '--json'] };- return { argv: hostWorkInspectArgv(first), consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `Lists each source's remaining step and its conflict for v${first}, with the command that settles it; changes nothing.`,- then: { ask_user: true, argv: forceRetryArgv(first), consent: [], actor: 'agent', requires_exclusive: true, verify,- why: `Writes a 'retry' marker so v${first} can run again, including the per-source command the inspect step names; a run that does not settle a conflict stops on it again.`,- user_message: `gbrain migration v${first} is stuck on a conflict in one or more sources that needs your decision; the inspect step lists each source and what conflicts there. `- + `It will not clear by itself. Once you have reviewed each conflict, clear it with ${forceRetryArgv(first).join(' ')}, then run the command the inspect step names for each source, or gbrain apply-migrations --yes. Clear it now?` } };+ const inspect: Action = { argv: hostWorkInspectArgv(first), consent: [], actor: 'agent', requires_exclusive: false,+ verify: { argv: ['gbrain', 'apply-migrations', '--list', '--json'] },+ why: `Lists each source's state and any conflict for v${first}, with the step that settles it; changes nothing.` };+ if (conflicts === null || conflicts.length === 0) return inspect;+ const unmanifested = conflicts.find(c => c.code === 'shared_skills_unmanifested');+ return { ...inspect, then: { ask_user: true, consent: [], actor: 'agent', requires_exclusive: false,+ ...(unmanifested ? { argv: ['gbrain', 'sources', 'shared-skills', unmanifested.source_id, 'off'] } : {}),+ verify: { argv: hostWorkInspectArgv(first) },+ why: 'Each conflict needs the user\'s decision; nothing changes until they make it.',+ user_message: `gbrain migration v${first} is stopped on a conflict in ${conflicts.map(c => c.source_id).join(', ')}. `+ + conflicts.map(c => `For ${c.source_id}: ${owedConflictNextStep(c)}.`).join(' ') + ' Which do you want for each?' } };}export function trailingPartialCount(entries: readonly CompletedMigrationEntry[]): number {diff --git a/src/core/shared-skills/migration-host-work.ts b/src/core/shared-skills/migration-host-work.tsindex d8a367ac9d..d97327abf4 100644--- a/src/core/shared-skills/migration-host-work.ts+++ b/src/core/shared-skills/migration-host-work.ts@@ -9,6 +9,8 @@* explicit pack). Read-only.*/import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { OwedConflict } from '../migration-ledger.ts';import type { SharedMigrationReport } from './migration.ts';import { sharedSkillSourcePolicyOrPreserve } from './setup-source-policy.ts';@@ -38,3 +40,25 @@ export async function hostWorkMigrations(engine: BrainEngine): Promise<Set<strinconst work = await sharedSkillsHostWork(engine);return new Set(work.sources.length || work.pending_actions ? [SHARED_SKILLS_HOST_WORK_VERSION] : []);}++/**+ * Every source stage a migration report marks `conflict`, with its code and reason. Null (unknown) when the report+ * could not inspect a source because its policy read failed, so an empty list always means every source was inspected.+ */+export function owedConflicts(report: Pick<SharedMigrationReport, 'sources'> | null | undefined): OwedConflict[] | null {+ if (report?.sources?.some(row => row.policy_unverified)) return null;+ return (report?.sources ?? []).flatMap(row => row.stages.filter(stage => stage.status === 'conflict')+ .map(stage => ({ source_id: row.source_id, code: stage.code ?? 'local_conflict', reason: stage.reason ?? '' })));+}++/**+ * The sources in conflict now, from the migration's read-only preview on this brain (the per-source inspect, run in+ * process: it inventories each registered pack and writes nothing). Null when the preview cannot run here.+ */+export async function readOwedConflicts(engine: BrainEngine, config: GBrainConfig): Promise<OwedConflict[] | null> {+ try {+ const { runSharedSkillsMigration } = await import('./migration.ts');+ return owedConflicts(await runSharedSkillsMigration({ engine, config, sourceId: 'default', remote: false, dryRun: true,+ logger: { info() {}, warn() {}, error() {} } }, { dryRun: true }));+ } catch { return null; }+}diff --git a/src/core/shared-skills/migration.ts b/src/core/shared-skills/migration.tsindex 8821ab0a8c..f5a6de7c6c 100644--- a/src/core/shared-skills/migration.ts+++ b/src/core/shared-skills/migration.ts@@ -18,6 +18,8 @@ export interface SharedMigrationStage {stage: 'inventory' | 'ownership' | 'projection' | 'policy' | 'members';status: 'complete' | 'action_required' | 'conflict' | 'planned';reason?: string;+ /** A conflict's stable code, for readers that must not parse `reason`. */+ code?: string;}export interface SharedSourceMigration {source_id: string;@@ -29,6 +31,8 @@ export interface SharedSourceMigration {status: 'complete' | 'action_required' | 'conflict' | 'planned';member_installations?: SharedMemberMigration[];parked?: SharedSourceParked;+ /** The source's policy could not be read, so the migration preserved its files without inspecting them. */+ policy_unverified?: true;}/*** A source whose pack exceeds an inventory bound. Later runs skip it without@@ -125,12 +129,13 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {root: source.local_path || (source.id === 'default' ? fallback : null), inventory: null, publication, stages: [], status: dryRun ? 'planned' : 'complete' };report.sources.push(row);const persist = async () => { if (!dryRun) await ctx.engine.setConfig(key, JSON.stringify(row)); };- const pending = async (stage: SharedMigrationStage['stage'], reason: string, conflict = false) => {- row.status = conflict ? 'conflict' : 'action_required';- row.stages.push({ stage, status: row.status, reason });+ const pending = async (stage: SharedMigrationStage['stage'], reason: string, conflictCode?: string) => {+ row.status = conflictCode ? 'conflict' : 'action_required';+ row.stages.push({ stage, status: row.status, reason, ...(conflictCode ? { code: conflictCode } : {}) });await persist();};if (sourcePolicy.mode === 'preserve_files') {+ if (sourcePolicy.unverified) row.policy_unverified = true;row.member_installations = await inspectSharedMemberMigration(ctx.engine, source.id, source.incarnation);await pending('projection', sourcePolicy.reason);continue;@@ -194,7 +199,8 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {await pending('inventory', parkedReason(source.id, row.parked));continue;}- await pending('inventory', error instanceof OperationError ? error.message : 'The source pack cannot be inventoried safely; inspect its manifest and declared files.', true);+ await pending('inventory', error instanceof OperationError ? error.message : 'The source pack cannot be inventoried safely; inspect its manifest and declared files.',+ error instanceof OperationError ? error.code : 'local_conflict');continue;}row.stages.push({ stage: 'inventory', status: 'complete' });@@ -216,7 +222,7 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {await persist();if (!row.inventory) {if (existsSync(join(row.root, 'skills')) && readdirSync(join(row.root, 'skills')).length) {- await pending('projection', 'Unmanifested source-local skills require reviewed adoption; no files or private markers were replaced.', true);+ await pending('projection', 'Unmanifested source-local skills require reviewed adoption; no files or private markers were replaced.', 'shared_skills_unmanifested');continue;}if (!dryRun) {diff --git a/src/core/shared-skills/setup-source-policy.ts b/src/core/shared-skills/setup-source-policy.tsindex 004f3f588e..819154c2dc 100644--- a/src/core/shared-skills/setup-source-policy.ts+++ b/src/core/shared-skills/setup-source-policy.ts@@ -7,7 +7,7 @@ export const SHARED_SKILLS_OPT_OUT_DOCS = 'docs/guides/shared-brain-skills.md#chexport type SharedSkillSourcePolicy =| { mode: 'content'; reason?: never }- | { mode: 'explicit_pack_required' | 'preserve_files'; reason: string };+ | { mode: 'explicit_pack_required' | 'preserve_files'; reason: string; unverified?: true };export async function sharedSkillSourcePolicy(engine: BrainEngine, sourceId: string): Promise<SharedSkillSourcePolicy> {const company = await getCompanyBrainProfile(engine, sourceId);@@ -34,7 +34,7 @@ export async function sharedSkillSourcePolicy(engine: BrainEngine, sourceId: str/** The policy as the migration applies it: a policy that cannot be verified preserves files. */export async function sharedSkillSourcePolicyOrPreserve(engine: BrainEngine, sourceId: string): Promise<SharedSkillSourcePolicy> {- return sharedSkillSourcePolicy(engine, sourceId).catch(error => ({ mode: 'preserve_files' as const,+ return sharedSkillSourcePolicy(engine, sourceId).catch(error => ({ mode: 'preserve_files' as const, unverified: true as const,reason: error instanceof OperationError ? `${error.code}: ${error.message}` : 'profile_incompatible: the source writeback policy could not be verified; no repository changes were attempted.' }));}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 380abba5e1..bab1af28cb 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6875,7 +6875,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_unmerged\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_command_stopped\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migration_host_work_owed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"provider_response_unparseable\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_unmerged\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_command_stopped\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migration_host_work_owed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"provider_response_unparseable\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unmanifested\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/migration-host-work-owed.test.ts b/test/migration-host-work-owed.test.tsindex c8b014bec8..2eb10837cf 100644--- a/test/migration-host-work-owed.test.ts+++ b/test/migration-host-work-owed.test.ts@@ -1,8 +1,9 @@/*** A wedged migration whose latest row records apply_migrations_pending still owes host work (for v0.53.0, a conflict- * in one or more sources). A newer migration completing after it does not make it history, and nothing clears it- * without a person. Every surface says so with the same read-only next step (the per-source inspect), offers the- * forced retry only after the conflict is resolved, and leaves the migration and every exit status as they were.+ * in one or more sources). Where an operator looks (doctor, apply-migrations, post-upgrade, upgrade) it is reported with+ * the read-only per-source inspect and, where the surface can read the preview, each source in conflict with its code+ * and next step; nothing advises a forced retry. Ordinary commands follow apply-migrations: once a newer migration ran+ * past the wedge they print nothing about it. A named run of it still refuses, with the read-only inspect as its fix.** One throwaway PGLite brain drives the CLI (HOME / GBRAIN_HOME per subprocess; process.env is never mutated); the* notice, both doctors and the upgrade message run in-process against a ledger-only home.@@ -21,12 +22,16 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { getDbUrlSource } from '../src/core/config.ts';import { VERSION } from '../src/version.ts';import { SHARED_SKILLS_HOST_WORK_VERSION } from '../src/core/shared-skills/migration-host-work.ts';+import { hostWorkOwedFix, hostWorkOwedMessage } from '../src/core/migration-ledger.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 { codeEntry } from '../src/core/error-catalogue.ts';const REPO = fileURLToPath(new URL('..', import.meta.url)).replace(/\/$/, '');const OWED = '0.53.0';const INSPECT = ['gbrain', 'apply-migrations', '--migration', OWED, '--dry-run', '--json'];-const RETRY = ['gbrain', 'apply-migrations', '--force-retry', OWED];+const FORCE_RETRY = '--force-retry';const owedRow = (n: number) => ({ ts: `2026-10-0${n}T00:00:00.000Z`, version: OWED, status: 'partial', apply_migrations_pending: true,phases: [{ name: 'content-checkpoints', status: 'complete', detail: 'Mechanical inventory is durable; publication and enrollment are NOT complete.' }] });/** v0.11.0 records apply_migrations_pending on every partial run that left host TODOs: an ordinary wedge, never a source conflict. */@@ -77,15 +82,12 @@ afterAll(async () => {try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ }});-/** The read-only inspect first, then the ask: rendered (`next`) on the wire, stored (`ask_user`) on an in-process doctor check. */-function expectOwedFix(fix: any): void {- if ('next' in fix) expect(fix).toMatchObject({ next: 'run', argv: INSPECT, then: { next: 'ask_user', argv: RETRY } });- else {- expect(fix).toMatchObject({ argv: INSPECT, then: { ask_user: true, argv: RETRY } });- expect(fix.ask_user).toBeUndefined();- }- expect(fix.then.user_message).toContain('conflict');- expect(fix.then.user_message).toContain('will not clear by itself');+/** The read-only inspect alone, with no ask: the surface could not read which sources are in conflict now. */+function expectInspectFix(fix: any): void {+ expect(fix).toMatchObject({ argv: INSPECT });+ expect(fix.ask_user).toBeUndefined();+ expect(fix.then).toBeUndefined();+ expect(JSON.stringify(fix)).not.toContain(FORCE_RETRY);}describe('apply-migrations with a wedged migration that still owes host work', () => {@@ -98,8 +100,7 @@ describe('apply-migrations with a wedged migration that still owes host work', (expect(out).not.toContain('All migrations up to date');expect(out).toMatch(new RegExp(`wedged\\s+${OWED.replace(/\./g, '\\.')}`));expect(out).toContain(INSPECT.join(' '));- expect(out.indexOf(INSPECT.join(' '))).toBeLessThan(out.indexOf(RETRY.join(' ')));- expect(out).toContain('does not clear without a person');+ expect(out).not.toContain(FORCE_RETRY);}, 120_000);test('--list --json lists it with the read-only inspect as its fix, never as superseded', async () => {@@ -131,6 +132,8 @@ describe('apply-migrations with a wedged migration that still owes host work', (expect(doc.status).toBe('up_to_date');expect(doc.wedged_host_work).toEqual([OWED]);expect(run.stderr).toContain(INSPECT.join(' '));+ expect(run.stderr).toContain('its preview finds no source in conflict now, so nothing waits on a person');+ expect(run.stderr).not.toContain(FORCE_RETRY);expect(ledger()).toBe(before);}, 120_000);@@ -141,7 +144,9 @@ describe('apply-migrations with a wedged migration that still owes host work', (expect(run.exitCode).toBe(1);const envelope = JSON.parse(run.stdout);expect(envelope).toMatchObject({ code: 'migrations_pending', reason: 'wedged' });- expectOwedFix(envelope.fix);+ expect(envelope.fix).toMatchObject({ next: 'run', argv: INSPECT });+ expect(envelope.fix.then).toBeUndefined();+ expect(run.stdout + run.stderr).not.toContain(FORCE_RETRY);expect(ledger()).toBe(before);}, 120_000);@@ -167,23 +172,18 @@ describe('apply-migrations with a wedged migration that still owes host work', (expect(ledger()).toBe(stuck);}, 240_000);- test('a named run of it refuses with the steps that clear it, and runs by name once the wedge is cleared', async () => {+ test('a named run of it refuses with the read-only inspect as its fix, never a forced retry, and changes nothing', async () => {owe(true);const before = ledger();- const named = ['apply-migrations', '--migration', OWED, '--yes', '--no-autopilot-install', '--json'];- const refused = await cli(named);- expect(refused.exitCode).toBe(2);- const envelope = JSON.parse(refused.stdout);- expect(envelope.code).toBe('invalid_params');- expect(envelope.message).toContain(`v${OWED} is wedged`);- expect(envelope.suggestion).toContain(RETRY.join(' '));- expectOwedFix(envelope.fix);+ const run = await cli(['apply-migrations', '--migration', OWED, '--yes', '--no-autopilot-install', '--json']);+ expect(run.exitCode).toBe(2);+ const envelope = JSON.parse(run.stdout);+ expect(envelope).toMatchObject({ code: 'invalid_params' });+ expect(envelope.suggestion).toContain(INSPECT.join(' '));+ expectInspectFix(envelope.fix);+ expect(run.stdout + run.stderr).not.toContain(FORCE_RETRY);expect(ledger()).toBe(before);- expect((await cli(RETRY.slice(1))).exitCode).toBe(0);- const run = await cli(named);- expect(run.exitCode).toBe(0);- expect(JSON.parse(run.stdout).code).toBeUndefined();- }, 240_000);+ }, 120_000);});describe('the other surfaces say the same thing', () => {@@ -201,12 +201,25 @@ describe('the other surfaces say the same thing', () => {.finally(() => rmSync(dir, { recursive: true, force: true }));};- test('the connect and serve notice leads with the inspect step, not the forced retry', async () => {- const notice = await scoped(true, () => pendingUpgradeMigrationsNotice({ getConfig: async () => null } as never, 'serve', VERSION));+ /** This ledger holds only the wedge and one newer run, so the other migrations still read as not run; the notice may name those, never the wedge. */+ const quietAboutWedge = (why: string) => {+ expect(why).not.toContain('wedged');+ expect(why).not.toContain('conflict');+ expect(why).not.toContain(FORCE_RETRY);+ };++ test('the connect and serve notice says nothing about it once a newer migration ran past it, as apply-migrations does', async () => {+ for (const command of ['serve', 'remember', 'recall', 'config']) {+ quietAboutWedge((await scoped(true, () => pendingUpgradeMigrationsNotice({ getConfig: async () => null } as never, command, VERSION)))?.why ?? '');+ }+ });++ test('with nothing past it the notice names the read-only inspect and asks nothing', async () => {+ const notice = await scoped(false, () => pendingUpgradeMigrationsNotice({ getConfig: async () => null } as never, 'serve', VERSION));expect(notice?.code).toBe('migrations_pending');- expect(notice!.fix).toMatchObject({ argv: INSPECT, then: { ask_user: true, argv: RETRY } });- expect(notice!.fix!.ask_user).toBeUndefined();- expect(notice!.why).toContain('does not clear without a person');+ expect(notice!.why).toContain(INSPECT.join(' '));+ expect(notice!.why).not.toContain(FORCE_RETRY);+ expectInspectFix(notice!.fix);});for (const superseded of [true, false]) {@@ -216,7 +229,8 @@ describe('the other surfaces say the same thing', () => {const row = rows.find(c => (c.details as any)?.code === 'migration_host_work_owed');expect(row?.status).toBe('warn');expect(row!.message).toContain(INSPECT.join(' '));- expectOwedFix(row!.fix);+ expect(row!.message).not.toContain(FORCE_RETRY);+ expectInspectFix(row!.fix);});}@@ -226,6 +240,7 @@ describe('the other surfaces say the same thing', () => {const row = rows.find(c => (c.details as any)?.code === 'migration_host_work_owed');expect(row?.status).toBe('warn');expect(row!.message).toContain(INSPECT.join(' '));+ expect(row!.message).not.toContain(FORCE_RETRY);}, 120_000);test('a superseded wedge of another migration that recorded host TODOs is not reported as owed host work', async () => {@@ -235,28 +250,175 @@ describe('the other surfaces say the same thing', () => {expect(rows.some(c => (c.details as any)?.code === 'migration_host_work_owed')).toBe(false);const remote = await scoped(true, async () => (await doctorReportRemote(engine, { remote: true })).checks.filter(c => c.name === 'minions_migration'), legacy);expect(remote.some(c => (c.details as any)?.code === 'migration_host_work_owed')).toBe(false);- const notice = await scoped(true, () => pendingUpgradeMigrationsNotice({ getConfig: async () => null } as never, 'serve', VERSION), legacy);- expect(notice?.why ?? '').not.toContain('does not clear without a person');+ quietAboutWedge((await scoped(true, () => pendingUpgradeMigrationsNotice({ getConfig: async () => null } as never, 'serve', VERSION), legacy))?.why ?? '');const line = await scoped(true, () => describeMigrationFailure(new Error('exit 1'), VERSION), legacy);expect(line).not.toContain(`--migration ${LEGACY}`);}, 120_000);- test('the doctor code has a registry row: gbrain errors explains it and its default fix is read-only', async () => {+ test('the doctor code has a registry row: gbrain errors explains it, its default fix is read-only and it never advises a forced retry', async () => {const entry = codeEntry('migration_host_work_owed');expect(entry?.class).toBe('host_only');expect(entry?.retryable).toBe(false);expect(entry!.fix!.argv).toEqual(['gbrain', 'apply-migrations', '--list', '--json']);expect(entry!.suggestion).toContain('--dry-run --json');- expect(entry!.suggestion).toContain('--force-retry');+ expect(entry!.suggestion).toContain('shared_skills_unmanifested');+ expect(JSON.stringify(entry)).not.toContain(FORCE_RETRY);const out = await cli(['errors', 'migration_host_work_owed']);expect(out.exitCode).toBe(0);expect(out.stdout).toContain('migration_host_work_owed (host_only');- expect(out.stdout).toContain('does not clear without a person');+ expect(out.stdout).not.toContain(FORCE_RETRY);}, 120_000);- test('upgrade\'s failure line names the inspect step, never a forced retry first', async () => {+ test('upgrade\'s failure line names the inspect step and no forced retry', async () => {const line = await scoped(true, () => describeMigrationFailure(new Error('exit 1'), VERSION));expect(line).toContain(INSPECT.join(' '));- expect(line.indexOf(INSPECT.join(' '))).toBeLessThan(line.indexOf(RETRY.join(' ')));+ expect(line).not.toContain(FORCE_RETRY);+ });+});++describe('the box ledger shape: three old partial rows for v0.53.0 and a newer migration completed', () => {+ const ordinary = [+ ['config', 'get', 'search.mode'],+ ['remember', 'Alice Example likes zebracorn tea', '--entity', 'people/alice-example', '--content-origin', 'user_said', '--provenance', 'test'],+ ['recall', 'zebracorn', '--json'],+ ];+ async function expectQuiet(): Promise<void> {+ for (const args of ordinary) {+ const run = await cli(args);+ expect({ args, exitCode: run.exitCode }).toEqual({ args, exitCode: 0 });+ expect(run.stderr).not.toContain('migrations_pending');+ expect(run.stderr).not.toContain(FORCE_RETRY);+ }+ }++ test('remember, recall and config get print nothing about it, with and without a database-only source', async () => {+ owe(true);+ await expectQuiet();+ expect((await cli(['transcripts', 'archive', 'on', '--json'])).exitCode).toBe(0);+ expect((await cli(['transcripts', 'archive', 'run', '--json'])).exitCode).toBe(0);+ const sources = JSON.parse((await cli(['sources', 'list', '--json'])).stdout);+ const rows: any[] = Array.isArray(sources) ? sources : sources.sources;+ expect(rows.find(row => row.id === 'conversations')?.local_path ?? null).toBeNull();+ expect(rows.some(row => row.id === 'conversations')).toBe(true);+ owe(true);+ await expectQuiet();+ }, 240_000);++ test('every command the advice names runs and exits 0', async () => {+ owe(true);+ for (const args of [INSPECT.slice(1), ['apply-migrations', '--dry-run', '--json'], ['sources', 'shared-skills', 'default', 'off'], ['sources', 'shared-skills', 'default', 'on']]) {+ const run = await cli(args);+ expect({ args, exitCode: run.exitCode }).toEqual({ args, exitCode: 0 });+ }+ }, 240_000);++ test('with a source in conflict, --dry-run and --yes name it with its code, never a forced retry, and ordinary commands stay quiet', async () => {+ const pack = join(home, 'source-b');+ mkdirSync(pack, { recursive: true });+ writeFileSync(join(pack, 'skillpack.json'), '[]');+ writeFileSync(join(pack, 'note.md'), '# Note\n');+ for (const args of [['init', '-q'], ['add', '-A'], ['-c', 'user.name=t', '-c', '[email protected]', 'commit', '-qm', 'init']]) {+ expect(Bun.spawnSync(['git', ...args], { cwd: pack }).exitCode).toBe(0);+ }+ expect((await cli(['sources', 'add', 'source-b', '--path', pack])).exitCode).toBe(0);+ try {+ owe(true);+ const dry = await cli(['apply-migrations', '--dry-run', '--json']);+ expect(dry.exitCode).toBe(0);+ expect(dry.stderr).toContain('source-b (local_conflict)');+ expect(dry.stderr).not.toContain(FORCE_RETRY);+ const before = ledger();+ const run = await cli(['apply-migrations', '--yes', '--no-autopilot-install']);+ expect(run.exitCode).toBe(0);+ expect(run.stderr).toContain('source-b (local_conflict)');+ expect(run.stdout + run.stderr).not.toContain(FORCE_RETRY);+ expect(ledger()).toBe(before);+ const post = await cli(['post-upgrade', '--no-autopilot-install']);+ expect(post.exitCode).toBe(0);+ expect(post.stdout + post.stderr).toContain('source-b (local_conflict)');+ expect(post.stdout + post.stderr).not.toContain(FORCE_RETRY);+ const quiet = await cli(['config', 'get', 'search.mode']);+ expect(quiet.stderr).not.toContain('migrations_pending');+ } finally {+ await cli(['sources', 'remove', 'source-b', '--confirm-destructive']);+ }+ }, 240_000);+});++describe('doctor, connected, reads which sources are in conflict now', () => {+ let live: PGLiteEngine;+ let pack: string;+ beforeAll(async () => {+ live = new PGLiteEngine();+ await live.connect({});+ await live.initSchema();+ pack = mkdtempSync(join(tmpdir(), 'gbrain-host-work-owed-pack-'));+ writeFileSync(join(pack, 'skillpack.json'), '[]');+ }, 120_000);+ afterAll(async () => {+ await live?.disconnect();+ rmSync(pack, { recursive: true, force: true });+ });++ async function owedChecks(): Promise<Check[]> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-host-work-owed-doctor-'));+ try {+ mkdirSync(join(dir, '.gbrain', 'migrations'), { recursive: true });+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));+ const rows = [...[1, 2, 3].map(owedRow), { version: '0.60.31', status: 'complete' }];+ writeFileSync(join(dir, '.gbrain', 'migrations', 'completed.jsonl'), rows.map(r => JSON.stringify(r)).join('\n') + '\n');+ const ctx = { engine: live, progress: { heartbeat() {}, finish() {} }, args: [] } as unknown as DoctorContext;+ return await withEnv({ HOME: dir, GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ async () => (await minionsMigrationEntry.run(ctx) as Check[]).filter(c => (c.details as any)?.code === 'migration_host_work_owed'));+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }++ test('names each source in conflict with its code and the user\'s decision, never a forced retry; quiet once none is left', async () => {+ await live.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', ['source-b', realpathSync(pack)]);+ const [row] = await owedChecks();+ expect(row?.status).toBe('warn');+ expect(row!.message).toContain('source-b (local_conflict)');+ expect(row!.message).toContain(INSPECT.join(' '));+ expect(row!.message).not.toContain(FORCE_RETRY);+ expect((row!.details as any).conflicts).toEqual([expect.objectContaining({ source_id: 'source-b', code: 'local_conflict' })]);+ expect(row!.fix).toMatchObject({ argv: INSPECT, then: { ask_user: true } });+ expect(row!.fix!.then!.user_message).toContain('source-b');+ expect(JSON.stringify(row!.fix)).not.toContain(FORCE_RETRY);+ await live.executeRaw("DELETE FROM sources WHERE id = 'source-b'");+ expect(await owedChecks()).toEqual([]);+ }, 120_000);++ test('a source whose policy read fails is not inspected, so doctor keeps the warning with the inspect step', async () => {+ await live.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', ['source-b', realpathSync(pack)]);+ const executeRaw = live.executeRaw.bind(live);+ live.executeRaw = (async (sql: string, params?: unknown[]) => {+ if (sql.startsWith('SELECT config FROM sources WHERE id=$1')) throw new Error('Connection terminated unexpectedly');+ return executeRaw(sql, params as any);+ }) as typeof live.executeRaw;+ try {+ const [row] = await owedChecks();+ expect(row?.status).toBe('warn');+ expect(row!.message).toContain(INSPECT.join(' '));+ expect(row!.message).not.toContain('nothing waits on a person');+ expect((row!.details as any).conflicts).toBeUndefined();+ expectInspectFix(row!.fix);+ } finally {+ live.executeRaw = executeRaw;+ await live.executeRaw("DELETE FROM sources WHERE id = 'source-b'");+ }+ }, 120_000);+});++describe('the advice for each conflict code', () => {+ test('skills nobody declared: declare them, or take the source out with sources shared-skills <id> off', () => {+ const conflicts = [{ source_id: 'source-a', code: 'shared_skills_unmanifested', reason: 'Unmanifested source-local skills require reviewed adoption; no files or private markers were replaced.' }];+ const message = hostWorkOwedMessage([OWED], conflicts);+ expect(message).toContain('source-a (shared_skills_unmanifested)');+ expect(message).toContain('skillpack.json');+ expect(message).toContain('gbrain sources shared-skills source-a off');+ expect(message).not.toContain(FORCE_RETRY);+ const fix = hostWorkOwedFix([OWED], conflicts);+ expect(fix).toMatchObject({ argv: INSPECT, then: { ask_user: true, argv: ['gbrain', 'sources', 'shared-skills', 'source-a', 'off'] } });+ expect(JSON.stringify(fix)).not.toContain(FORCE_RETRY);});});diff --git a/test/migration-ledger.test.ts b/test/migration-ledger.test.tsindex 76c9eff7c6..b564d0a444 100644--- a/test/migration-ledger.test.ts+++ b/test/migration-ledger.test.ts@@ -18,6 +18,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import {MIGRATION_VERSIONS,+ RECONCILE_MIGRATION_VERSIONS,MAX_CONSECUTIVE_PARTIALS,compareVersions,statusForVersion,@@ -36,6 +37,9 @@ describe('MIGRATION_VERSIONS registry sync (EV4)', () => {test('matches the real migration registry exactly, in order', () => {expect([...MIGRATION_VERSIONS]).toEqual(migrations.map(m => m.version));});+ test('RECONCILE_MIGRATION_VERSIONS lists exactly the migrations that declare reconcile', () => {+ expect([...RECONCILE_MIGRATION_VERSIONS]).toEqual(migrations.filter(m => m.reconcile).map(m => m.version));+ });});describe('statusForVersion (shared with apply-migrations)', () => {diff --git a/test/migrations-notice.test.ts b/test/migrations-notice.test.tsindex 7a0b6784a9..7a7e05f007 100644--- a/test/migrations-notice.test.ts+++ b/test/migrations-notice.test.ts@@ -54,6 +54,16 @@ describe('pendingUpgradeMigrationsNotice', () => {expect(notice!.why).toContain(latest);});+ test('a wedged migration a newer migration ran past is history, as apply-migrations says, so it gets no notice', async () => {+ const older = MIGRATION_VERSIONS[MIGRATION_VERSIONS.length - 3]!;+ const notice = await inHome(async () => {+ for (const version of MIGRATION_VERSIONS) if (version !== older) appendCompletedMigration({ version, status: 'complete' } as never);+ for (let i = 0; i < 3; i++) appendCompletedMigration({ version: older, status: 'partial' } as never);+ return pendingUpgradeMigrationsNotice(engine, 'query', latest);+ });+ expect(notice).toBeNull();+ });+test('no ledger yet (a fresh brain) means no notice', async () => {expect(await inHome(() => pendingUpgradeMigrationsNotice(engine, 'query', latest))).toBeNull();});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 625802d756..d4c1e7b953 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -656,6 +656,7 @@ test/shared-skills-source-opt-out.test.tstest/shared-skills-writer-boundary.test.tstest/source-lifecycle-dry-run-physical-root-6849.test.tstest/source-purge-stranded-pages-7072.test.ts+test/source-resolver-null-path.test.tstest/source-retire-missing-checkout.test.tstest/source-row-diagnostics.test.tstest/sources-git-reconcile.test.tsdiff --git a/test/shared-skills-setup.test.ts b/test/shared-skills-setup.test.tsindex 12e2d0e278..78b42d31a3 100644--- a/test/shared-skills-setup.test.ts+++ b/test/shared-skills-setup.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, test } from 'bun:test';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { randomUUID } from 'node:crypto';@@ -165,6 +165,22 @@ describe('staged skill migration', () => {writeFileSync(join(root, 'skillpack.json'), '[]');expect((await runSharedSkillsMigration(f.ctx)).status).toBe('conflict');});+ test('skills on an owned root with no skillpack.json are a conflict coded shared_skills_unmanifested, and nothing is written', async () => {+ const root = realpathSync(temp()), f = fixture(root);+ mkdirSync(join(root, 'skills/local-only'), { recursive: true });+ writeFileSync(join(root, 'skills/local-only/SKILL.md'), 'Local instructions');+ const base = f.ctx.engine.executeRaw.bind(f.ctx.engine);+ (f.ctx.engine as { executeRaw: unknown }).executeRaw = async (sql: string, params?: unknown[]) => {+ if (sql.includes('FROM persistence_brain')) return [{ brain_id: f.brainId, enabled: true, skill_bundles_enabled: true }];+ if (sql.includes('FROM persistence_source_bindings')) return [{ source_id: 'default', state: 'active', owner_host_id: 'host-a', local_path: root, relative_path: '' }];+ return base(sql, params as never);+ };+ const report = await withEnv({ GBRAIN_HOME: temp() }, () => runSharedSkillsMigration(f.ctx, { dryRun: true }));+ expect(report.status).toBe('conflict');+ expect(report.sources[0].stages.at(-1)).toMatchObject({ stage: 'projection', status: 'conflict', code: 'shared_skills_unmanifested' });+ expect(f.calls.some(sql => /INSERT|UPDATE|DELETE/.test(sql))).toBe(false);+ expect(f.config.size).toBe(0);+ });test('DB-only migration remains action-required and creates no replacement pages', async () => {const f = fixture(); f.pages();const result = await runSharedSkillsMigration(f.ctx);diff --git a/test/source-resolver-null-path.test.ts b/test/source-resolver-null-path.test.tsnew file mode 100644index 0000000000..094c6cbbda--- /dev/null+++ b/test/source-resolver-null-path.test.ts@@ -0,0 +1,66 @@+/**+ * A source with no local path (a database-only source, such as the conversation archive's) never answers a path lookup:+ * every resolver that maps a directory to a source skips it, whether its path is NULL or an empty string, on both+ * engines, so a checkout, its subfolders, an unregistered folder and / never resolve to it.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { resolveRegisteredLocalPathSource, resolveSourceForRepoPath, resolveSourceId, resolveSourceWithTier } from '../src/core/source-resolver.ts';++const work = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-null-path-')));+const checkout = join(work, 'source-a');+const outside = join(work, 'elsewhere');+const engines: Array<{ name: string; engine: BrainEngine }> = [];+let closePg: (() => Promise<void>) | undefined;++beforeAll(async () => {+ mkdirSync(join(checkout, 'notes'), { recursive: true });+ mkdirSync(outside, { recursive: true });+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engines.push({ name: 'pglite', engine: pglite });+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push({ name: 'postgres', engine: pg.engine });+ closePg = pg.close;+ }+}, 120_000);++afterAll(async () => {+ for (const { name, engine } of engines) if (name === 'pglite') await engine.disconnect();+ await closePg?.();+ rmSync(work, { recursive: true, force: true });+});++async function register(engine: BrainEngine, id: string, localPath: string | null): Promise<void> {+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2) ON CONFLICT (id) DO UPDATE SET local_path = EXCLUDED.local_path', [id, localPath]);+}++describe('a source with no local path never answers a path lookup', () => {+ for (const dbOnlyPath of [null, '']) {+ test(`local_path ${dbOnlyPath === null ? 'NULL' : "''"}: the checkout resolves to its own source, nothing resolves to the database-only one`, async () => {+ for (const { name, engine } of engines) {+ await register(engine, 'source-a', checkout);+ await register(engine, 'conversations', dbOnlyPath);+ for (const cwd of [checkout, join(checkout, 'notes')]) {+ expect({ name, cwd, id: await resolveSourceId(engine, null, cwd) }).toEqual({ name, cwd, id: 'source-a' });+ expect({ name, cwd, tier: (await resolveSourceWithTier(engine, null, cwd)).tier }).toEqual({ name, cwd, tier: 'local_path' });+ expect({ name, cwd, id: await resolveRegisteredLocalPathSource(engine, cwd) }).toEqual({ name, cwd, id: 'source-a' });+ expect({ name, cwd, id: (await resolveSourceForRepoPath(engine, cwd))?.source_id }).toEqual({ name, cwd, id: 'source-a' });+ }+ for (const cwd of [outside, work, '/']) {+ expect({ name, cwd, id: await resolveSourceId(engine, null, cwd) }).not.toEqual({ name, cwd, id: 'conversations' });+ expect({ name, cwd, id: await resolveRegisteredLocalPathSource(engine, cwd) }).toEqual({ name, cwd, id: null });+ expect({ name, cwd, hit: await resolveSourceForRepoPath(engine, cwd) }).toEqual({ name, cwd, hit: null });+ }+ await engine.executeRaw("DELETE FROM sources WHERE id IN ('source-a', 'conversations')");+ }+ });+ }+});