Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): v0.53.0 content checkpoint after a host move names the repair, and the repair lists unfinished checkpoints that name another root (#7900)
garrytan1ad8b893207b
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 291aac9748..f890080a38 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -834,7 +834,11 @@ names the source's root and that root's device and inode. A writer transferaccept and `gbrain sources set-path` rebind the receipt of every moved source(nested sources by their relative path) in their own transaction, and report itas `content_receipts`. A receipt an older release left on the old root makes-doctor report `content_receipt_stale` with this repair as its fix.+doctor report `content_receipt_stale` with this repair as its fix. The repair+also lists an unfinished setup checkpoint that names another root: after a host+move, the 0.53.0 migration refuses `The canonical root changed after setup+began` with this repair as its fix (#7900). Follow the class it prints, then+run `gbrain apply-migrations --force-retry 0.53.0`.```bashgbrain repair content-receipt-root --source default # preview, on the owner host@@ -848,7 +852,7 @@ Classes in the preview:|---|---|---|| `rebind` | The owner binding's root is the source's `local_path` and the owner's tree hashes to the worktree manifest the last transfer or rebind verified. | The apply rewrites the receipt's `root` and `root_identity`. || `source_path_mismatch` | The source's `local_path` still names the old root (a transfer was accepted, `set-path` not yet run). | `gbrain sources set-path <source> <owner root>`, which also rebinds the receipt. |-| `tree_mismatch` | The owner's tree no longer hashes to the recorded manifest (pages were written since), so it is not proven to be the transferred content; the detail prints both digests. | A self-transfer on the owner host (`gbrain sources writer transfer prepare <source> --self-transfer ...`, then the accept it prints) re-verifies the tree and rebinds the receipt. |+| `tree_mismatch` | The owner's tree no longer hashes to the recorded manifest (pages were written since, or a claim on a new host recorded none), so it is not proven to be the transferred content; the detail prints both digests. | A self-transfer on the owner host (`gbrain sources writer transfer prepare <source> --self-transfer ...`, then the accept it prints) re-verifies the tree and rebinds the receipt. With shared skills on, the fix then repeats `gbrain sources writer activate --confirm-quiesced --shared-skills` for the new owner epoch. || `not_owner_host`, `root_missing` | This host does not own the checkout, or the owner's root cannot be read. | `gbrain sources writer status --source <source> --json`. |The apply recomputes the preview and refuses `preview_changed` unless it isdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 5f57c32597..93f29107af 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)-src/core/behavior-change-notice.ts 1535 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row+src/core/behavior-change-notice.ts 1537 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); +2 the #7900 content checkpoint host-move row (master 1535 + 2); the behavior-change table split (#7607) retires this rowdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex aaf7bc8b2d..5ea5cdbf96 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1337,6 +1337,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.483.0', id: 'visibility_noncanonical_hold_7848', text: 'Git sync (classic and managed) and `gbrain import` (with or without a Git checkout) hold a file whose frontmatter asks for `visibility: private` in a spelling page privacy does not read (`Visibility: private`, `visibility: Private`, a block scalar, a list, a flow mapping or a merge key) as `visibility_noncanonical` instead of storing a world-readable page; the rest of the source syncs and an existing page keeps its last imported version. Write `visibility: private` on its own frontmatter line (lowercase) and commit, or import the file again. Doctor `git_held_files` counts the held files and the stored pages that already ask for private this way (`details.visibility_noncanonical`); nothing rewrites them. On a brain without managed persistence, `gbrain put --file` and `gbrain capture --file` of a page over the single-string ceiling refuse such a request with `visibility_not_applied`, as a smaller write does.' },// #7880 ingest_capture and company-brain imports on a brain without managed persistence. `since` is stamped at the merge slot.{ since: '0.60.485.0', id: 'ingest_capture_private_hold_7880', text: 'On a brain without managed persistence, an `ingest_capture` job (the webhook `POST /ingest` route and the ingestion daemon) whose content asks for `visibility: private` in a spelling page privacy does not read (`Visibility: private`, `visibility: Private`, a block scalar, a list, a flow mapping or a merge key) is refused `visibility_not_applied` and dead-letters on its first attempt instead of storing a world-readable page, as a managed brain already refused it. A legacy company-brain connect or sync holds such a file as `visibility_noncanonical` instead of importing it world-readable, and the GitHub and Google connectors hold it on a database-only source as they do with a checkout. Write `visibility: private` on its own frontmatter line (lowercase) and send it again. Nothing rewrites pages already stored (#7880).' },+ // #7900 v0.53.0 content checkpoint after a host move. `since` is stamped at the merge slot.+ { since: 'TBD', id: 'content_checkpoint_host_move_7900', text: 'After a brain moves hosts, `gbrain apply-migrations` at v0.53.0 (`content-checkpoints`) still refuses `The canonical root changed after setup began` when an unfinished shared-skills content setup checkpoint names the old host\'s root, but its fix is now `gbrain repair content-receipt-root --source <source>` (before, it told you to resume at the old root). That repair, and doctor `sync_freshness` (`content_receipt_stale`), now list unfinished checkpoints that name another root as well as complete receipts (before, the repair found nothing). The preview names the step that proves the new root; for a source claimed on the new host that is a self-transfer on the owner host, which rebinds the checkpoint, followed by `gbrain sources writer activate --confirm-quiesced --shared-skills` when shared skills are on. Then `gbrain apply-migrations --force-retry 0.53.0` completes. Nothing is rewritten without those explicit steps.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/repair/content-receipt-root.ts b/src/core/repair/content-receipt-root.tsindex 4ab165b8c6..fe02a6d317 100644--- a/src/core/repair/content-receipt-root.ts+++ b/src/core/repair/content-receipt-root.ts@@ -33,18 +33,24 @@ const previewCommand = (scope: RepairScope) => `gbrain repair content-receipt-roconst statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s owner host, binding root and worktree state, read-only.`,{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });-function selfTransferFix(sourceId: string): Action {+/** #7900: a self-transfer moves the owner epoch, so where shared skills are on, their activation is repeated for the new epoch. */+function selfTransferFix(sourceId: string, sharedSkills: boolean): Action {const intent = (phase: string) => ['--admin-intent', `writer_transfer_${phase}`, '--expected-state', '<admin_state>'];const inputs = [{ name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host (read it again before the accept)` }];+ const reactivate: Action = { argv: ['gbrain', 'sources', 'writer', 'activate', '--confirm-quiesced', '--shared-skills', '--admin-intent', 'writer_activate', '--expected-state', '<admin_state>'],+ inputs: [{ name: 'admin_state', how: 'admin_state from gbrain sources writer status --json, read again after the accept' }], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Registers shared-skill publication for the owner epoch the self-transfer moved to; until then shared skill writes refuse writer_not_quiesced.' };return { argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, '--self-transfer', ...intent('prepare')], inputs, consent: [], actor: 'host_admin', requires_exclusive: false,why: `Records the manifest of source ${sourceId}'s current tree on the owner host; the self-transfer accept then re-verifies the tree and rebinds the content receipt in the same transaction.`,then: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', sourceId, '--path', '<owner root>', '--expected-epoch', '<owner_epoch>', '--manifest', '<manifest digest printed by prepare>', '--self-transfer', ...intent('accept')],inputs: [...inputs, { name: 'owner root', how: 'the binding root writer status prints' }, { name: 'owner_epoch', how: 'the owner_epoch prepare printed' }],- consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Accepts the self-transfer: ownership stays on this host and the content receipt follows the verified root.' } };+ consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Accepts the self-transfer: ownership stays on this host and the content receipt follows the verified root.',+ ...(sharedSkills ? { then: reactivate } : {}) } };}async function verdicts(engine: Parameters<RepairHandler['plan']>[0], scope: RepairScope): Promise<Verdict[]> {const out: Verdict[] = [];+ const [brain] = await engine.executeRaw<{ skill_bundles_enabled: boolean }>('SELECT skill_bundles_enabled FROM persistence_brain WHERE singleton=1');for (const stale of await staleOwnedContent(engine, scope.source_ids)) {const [row] = await engine.executeRaw<{ incarnation: string; brain_id: string; key: string; value: string; owner_host_id: string; manifest: StoredWorktreeManifest | null; worktree_root: string; relative_path: string }>(`SELECT s.incarnation::text AS incarnation,p.brain_id,c.key,c.value,w.owner_host_id::text AS owner_host_id,w.manifest,h.local_path AS worktree_root,b.relative_path@@ -69,7 +75,7 @@ async function verdicts(engine: Parameters<RepairHandler['plan']>[0], scope: Repconst recorded = row.manifest?.digest ?? null;const actual = worktreeManifest(row.worktree_root, { scope: storedManifestScope(row.manifest) }).digest;if (recorded !== actual) {- out.push({ ...base, class: 'tree_mismatch', fix: selfTransferFix(stale.sourceId),+ out.push({ ...base, class: 'tree_mismatch', fix: selfTransferFix(stale.sourceId, brain?.skill_bundles_enabled === true),detail: `${was}; the owner's tree at ${row.worktree_root} hashes to ${actual} but the recorded worktree manifest is ${recorded ?? 'missing'}, so it is not proven to be the transferred content` });continue;}diff --git a/src/core/shared-skills/content-freshness.ts b/src/core/shared-skills/content-freshness.tsindex fe0228514b..0adef197f3 100644--- a/src/core/shared-skills/content-freshness.ts+++ b/src/core/shared-skills/content-freshness.ts@@ -55,8 +55,11 @@ async function ownedContentRows(engine: BrainEngine, sourceIds?: string[]): PromAND NOT EXISTS (SELECT 1 FROM source_ingestion_receipts r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.profile='company-brain')`, [sourceIds ?? null, await graduationVerifyInheritsPersistence(engine)]);}-/** The row's complete, ready, owned receipt of a plain content source (no connector, clone or company brain), else null. */-function completeOwnedReceipt(row: OwnedContentRow, sourceIds?: string[]): Record<string, unknown> | null {+/**+ * The row's owned receipt of a plain content source (no connector, clone or company brain), else null; complete and+ * ready unless `anyStage` (#7900: a setup checkpoint the migration resumes is stale too when it names another root).+ */+function ownedReceipt(row: OwnedContentRow, sourceIds?: string[], anyStage = false): Record<string, unknown> | null {if (sourceIds && !sourceIds.includes(row.id)) return null;if (!row.config || typeof row.config !== 'object' || Array.isArray(row.config) || row.last_commit !== null) return null;const config = row.config as Record<string, unknown>;@@ -64,8 +67,8 @@ function completeOwnedReceipt(row: OwnedContentRow, sourceIds?: string[]): Recorlet receipt: Record<string, unknown>;try { receipt = JSON.parse(row.receipt); } catch { return null; }return receipt && receipt.version === 1 && receipt.brain_id === row.brain_id && receipt.source_id === row.id- && receipt.source_incarnation === row.incarnation && receipt.owned_root === true && receipt.stage === 'complete'- && receipt.status === 'ready' && ['content_directory', 'git'].includes(String(receipt.repository_kind)) ? receipt : null;+ && receipt.source_incarnation === row.incarnation && receipt.owned_root === true && (anyStage || receipt.stage === 'complete' && receipt.status === 'ready')+ && ['content_directory', 'git'].includes(String(receipt.repository_kind)) ? receipt : null;}const ownerRootOf = (row: OwnedContentRow) => typeof row.owner_root === 'string' && typeof row.relative_path === 'string' ? resolve(row.owner_root, row.relative_path) : null;@@ -78,7 +81,7 @@ function rootsAgree(row: OwnedContentRow, receipt: Record<string, unknown>): booexport async function ownedContentFreshness(engine: BrainEngine, sourceIds?: string[]): Promise<OwnedContentFreshness[]> {const result: OwnedContentFreshness[] = [];for (const row of await ownedContentRows(engine, sourceIds)) {- const receipt = completeOwnedReceipt(row, sourceIds);+ const receipt = ownedReceipt(row, sourceIds);if (receipt && rootsAgree(row, receipt)) result.push({ sourceId: row.id, pending: Number(row.pending), recovering: Number(row.recovering) });}return result;@@ -91,7 +94,7 @@ export async function ownedContentFreshness(engine: BrainEngine, sourceIds?: strexport async function staleOwnedContent(engine: BrainEngine, sourceIds?: string[]): Promise<StaleOwnedContent[]> {const result: StaleOwnedContent[] = [];for (const row of await ownedContentRows(engine, sourceIds)) {- const receipt = completeOwnedReceipt(row, sourceIds);+ const receipt = ownedReceipt(row, sourceIds, true);if (receipt && !rootsAgree(row, receipt)) result.push({ sourceId: row.id, receiptRoot: typeof receipt.root === 'string' ? receipt.root : null, ownerRoot: ownerRootOf(row), localPath: row.local_path });}return result;diff --git a/src/core/shared-skills/setup.ts b/src/core/shared-skills/setup.tsindex 6bb673804b..8798e6247d 100644--- a/src/core/shared-skills/setup.ts+++ b/src/core/shared-skills/setup.ts@@ -132,6 +132,11 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Shreceipt.repository_kind = gitProbe?.status === 0 && resolve(gitProbe.stdout.trim()) === root ? 'git' : 'content_directory';const existed = existsSync(root);if (prior?.root && prior.root !== root) {+ if (existingRoot) {+ throw opError('local_conflict', 'The canonical root changed after setup began.',+ `Content setup for source ${sourceId} began at ${prior.root}, but the source is now registered at ${root} (a host move, transfer or relocation). Preview gbrain repair content-receipt-root --source ${sourceId}: it lists what proves the new root and the step that rebinds the checkpoint; then run the migration again.`,+ { fix: readFix(`Lists source ${sourceId}'s content checkpoint that names another root, with the step that rebinds it, read-only.`, { argv: ['gbrain', 'repair', 'content-receipt-root', '--source', sourceId] }) });+ }throw opError('local_conflict', 'The canonical root changed after setup began.',`Content setup for source ${sourceId} began at ${prior.root}; resume it with --content-root ${prior.root}, or ask the user before abandoning that setup.`);}diff --git a/test/migration-0-53-host-move-7900.test.ts b/test/migration-0-53-host-move-7900.test.tsnew file mode 100644index 0000000000..8de2a8db8e--- /dev/null+++ b/test/migration-0-53-host-move-7900.test.ts@@ -0,0 +1,115 @@+/**+ * #7900: after a host move, apply-migrations stopped at v0.53.0 content-checkpoints with "The canonical root changed+ * after setup began", forever, and `gbrain repair content-receipt-root` found nothing to repair.+ *+ * Shape: content setup on the old host created an owned root and stopped at stage `owner` (an existing brain waits+ * for the writer to be claimed and shared-skill persistence activated). The brain then moved: the content was copied+ * to the new host's root, the source pointed there, claimed and activated on the new host identity. The setup+ * checkpoint still named the old host's root. The migration resumes that setup and refused, and the repair only read+ * complete receipts, so the operator had no supported way through.+ *+ * Now the refusal names the repair, the repair lists the stale checkpoint with its exit (a self-transfer on the owner+ * host re-verifies the tree and rebinds the checkpoint), and after it the migration completes and the source reads+ * fresh. Nothing is rewritten without that explicit, verified step.+ */+import { describe, expect, test } from 'bun:test';+import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { ownedContentFreshness, staleOwnedContent } from '../src/core/shared-skills/content-freshness.ts';+import { runSharedSkillsMigration } from '../src/core/shared-skills/migration.ts';+import { contentSetupKey, setupSharedBrainContent } from '../src/core/shared-skills/setup.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { withEnv } from './helpers/with-env.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';++const ctxOf = (engine: BrainEngine): OperationContext => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default',+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } });++async function checkpoint(engine: BrainEngine) {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ return JSON.parse((await engine.getConfig(contentSetupKey('default', incarnation)))!) as { root: string; stage: string; status: string };+}++async function repairPreview(engine: BrainEngine) {+ const { contentReceiptRootRepair } = await import('../src/core/repair/content-receipt-root.ts');+ const { repairSpec } = await import('../src/core/repair/registry.ts');+ return runRepair(ctxOf(engine) as never, contentReceiptRootRepair, await resolveRepairScope(engine, 'default'),+ { apply: false, explicit: true, spec: repairSpec('content-receipt-root' as never), sourceFlag: 'default' });+}++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const arms = [{ backend: 'pglite', databaseUrl: undefined as string | undefined },+ ...(process.env.DATABASE_URL ? [{ backend: 'postgres', databaseUrl: process.env.DATABASE_URL }] : [])];++for (const { backend, databaseUrl } of arms) for (const git of [false, true]) {+ describe(`#7900 v0.53.0 content checkpoint after a host move (${backend}, ${git ? 'Git repository' : 'content directory'})`, () => {+ test('the refusal and the repair name a way through; after the verified self-transfer the migration completes and the source reads fresh', async () => {+ const base = mkdtempSync(join(tmpdir(), 'gbrain-7900-'));+ const oldHome = join(base, 'old-host-home'), newHome = join(base, 'new-host-home');+ const oldRoot = join(base, 'old-host', 'content'), newRoot = join(base, 'new-host', 'content');+ mkdirSync(join(base, 'old-host')); mkdirSync(join(base, 'new-host'));+ const { engine, close } = await withEnv({ GBRAIN_HOME: oldHome, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => isolatedSharedSkillsEngine(databaseUrl));+ try {+ const oldHost = await withEnv({ GBRAIN_HOME: oldHome }, async () => {+ const receipt = await setupSharedBrainContent(ctxOf(engine), { sourceId: 'default', root: oldRoot, ...(git ? { git: 'init' as const } : {}) });+ expect(receipt).toMatchObject({ root: oldRoot, owned_root: true, stage: 'owner', repository_kind: git ? 'git' : 'content_directory' });+ writeFileSync(join(oldRoot, 'notes.md'), '# notes\n');+ return localHostId();+ });+ cpSync(oldRoot, newRoot, { recursive: true });+ await withEnv({ GBRAIN_HOME: newHome, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ try {+ expect(localHostId()).not.toBe(oldHost);+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [newRoot]);+ await claimWorktree(engine, 'default', newRoot);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });++ const refused = await refusal(() => runSharedSkillsMigration(ctxOf(engine)));+ expect(refused.message).toBe('The canonical root changed after setup began.');+ expect(refused.suggestion).toContain('gbrain repair content-receipt-root --source default');+ expect((refused as { fix?: { argv?: string[] } }).fix?.argv).toEqual(['gbrain', 'repair', 'content-receipt-root', '--source', 'default']);+ expect(await checkpoint(engine)).toMatchObject({ root: oldRoot, stage: 'owner' });++ expect((await staleOwnedContent(engine, ['default'])).map(row => row.sourceId)).toEqual(['default']);+ const preview = await repairPreview(engine);+ expect(preview.listing).toEqual([expect.objectContaining({ item: 'default', class: 'tree_mismatch' })]);+ const fix = (preview.details?.refused as Array<{ fix: { argv: string[]; then: { argv: string[]; then?: { argv: string[] } } } }>)[0].fix;+ expect([fix.argv.slice(0, 7), fix.then.argv.slice(0, 5), fix.then.then?.argv.slice(0, 6)]).toEqual([+ ['gbrain', 'sources', 'writer', 'transfer', 'prepare', 'default', '--self-transfer'],+ ['gbrain', 'sources', 'writer', 'transfer', 'accept'],+ ['gbrain', 'sources', 'writer', 'activate', '--confirm-quiesced', '--shared-skills']]);+ expect(await checkpoint(engine)).toMatchObject({ root: oldRoot, stage: 'owner' });++ const prepared = await runPersistenceAdministration(engine, 'writer_transfer_prepare',+ { source_id: 'default', self_transfer: true, ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }) as { owner_epoch: string; manifest: { digest: string } };+ const accepted = await runPersistenceAdministration(engine, 'writer_transfer_accept', { source_id: 'default', path: newRoot, expected_epoch: prepared.owner_epoch,+ manifest: prepared.manifest.digest, self_transfer: true, ...await reviewedWriterIntent(engine, 'writer_transfer_accept') }) as { content_receipts: unknown[] };+ expect(accepted.content_receipts).toEqual([expect.objectContaining({ source_id: 'default', from: oldRoot, to: newRoot })]);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });++ const report = await runSharedSkillsMigration(ctxOf(engine));+ expect(report.status).not.toBe('conflict');+ expect(await checkpoint(engine)).toMatchObject({ root: newRoot, stage: 'complete', status: 'ready' });+ expect(await staleOwnedContent(engine, ['default'])).toEqual([]);+ expect((await ownedContentFreshness(engine, ['default'])).map(row => row.sourceId)).toEqual(['default']);+ expect((await repairPreview(engine)).listing).toEqual([]);+ } finally { await disposePersistenceConsumer(engine); }+ });+ } finally { await close(); rmSync(base, { recursive: true, force: true }); }+ }, 240_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 54f20be971..624fc3a137 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -259,6 +259,7 @@ test/managed-sync-preparation-stalled-holds.test.tstest/managed-sync-row-parity.test.tstest/managed-sync-stale-group-head.test.tstest/mcp-unreadable-sources-notice.test.ts+test/migration-0-53-host-move-7900.test.tstest/migration-persistence-foreground-committed-index.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.ts