Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): stage nothing inside a repository and settle a moved export's copies (#8528)
garrytan52d8fdb8fa05
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.mdindex 49ca318bf2..88cb2979d7 100644--- a/docs/architecture/key-files/shared-skills.md+++ b/docs/architecture/key-files/shared-skills.md@@ -5,7 +5,7 @@- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects; the request and effect guards refuse `writer_coordinator_required` when the writing role cannot see the `persistence_brain` floor, and activation refuses any role that row-level security filters on `sources` or the request, effect, worktree and binding tables. Their function bodies are exported alone so a migration replaces them without re-creating triggers. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server `membership_inactive` (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (`remote_membership_reason: superseded`), so harness rotation converges; `gbrain bootstrap harness --refresh-skills` re-runs `join` to adopt the current epoch.- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.-- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. `installPackagedSharedSkills` resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's `gbrain-memory` pack before admitting one, since the adoption key binds the release-stamped `skillpack.json` and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner. The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage `inventory` or `exported`, no started claim) to another absent `--content-root`, leaving the old root and staging as they are and rechecking the checkpoint's inventory (#8528), refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).+- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. `installPackagedSharedSkills` resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's `gbrain-memory` pack before admitting one, since the adoption key binds the release-stamped `skillpack.json` and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner. The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage `inventory` or `exported`, no started claim) to another absent `--content-root` and rechecks the checkpoint's inventory (#8528): a root inside a Git worktree is refused before any page is staged, the old staging directory is removed under the lock only when it holds nothing but the export's own bytes (else the move is refused, naming it), a filled earlier root is kept and named in `earlier_roots` and `pending_actions`, and every run refuses if the checkpoint changed while it waited for its lock, refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).- `src/core/shared-skills/{setup-source-policy,content-freshness}.ts` excludes external, connector, company and opted-out (`config.shared_skills=false`) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. `src/commands/doctor/checks/canonical-content.ts` reports pending publication and recovery separately; it never invents an upstream sync timestamp. `src/core/shared-skills/adopted-packs.ts` names the sources holding an adopted pack (`source_routing_health` skips their zero-page warning) and, of those, the read-only catalogs (no commit, no `.git` when the checkout is readable) that `sync_freshness` exempts; a failing read exempts nothing and is a note. `staleOwnedContent` names a receipt, or an unfinished setup checkpoint, left on an old root (doctor `content_receipt_stale`); `setup.ts` refuses a resumed setup whose checkpoint names another root with `gbrain repair content-receipt-root --source <id>` as the fix. `src/core/shared-skills/receipt-root.ts` (`rebindContentReceipts`) rebinds the receipt root and `root_identity` of every current incarnation on the moved worktrees (nested by `relative_path`) inside the writer transfer accept and `sources set-path` transactions. `src/core/repair/content-receipt-root.ts` (`gbrain repair content-receipt-root`, explicit-only, preview-bound, owner host) rebinds a stale receipt when the source path is the owner root and the owner tree hashes to the recorded manifest, else lists `source_path_mismatch` / `tree_mismatch` (both digests) / `not_owner_host` / `root_missing`; it keeps `<key>.backup`. Test: `test/pathological/c7-content-receipt-root.test.ts`.- `src/core/shared-skills/{source-opt-out,inventory-limits}.ts` and `src/commands/sources-shared-skills.ts` implement `gbrain sources shared-skills <id> on|off|status`: `off` writes `config.shared_skills=false`, `on` deletes it and releases a parked inventory, and every form reports the configured value and the effective policy mode with its reason. Trusted local only; a remote attempt gets `trusted_local_only` with a `host_admin` fix and a read-only verify. `inventorySkillpack` reads its file-count, total-byte, per-file and entry bounds from the capped `shared_skills.inventory.*` keys; confinement checks are fixed. An overflow (`payload_too_large`) parks the source in its per-source migration record, so the 0.53.0 orchestrator completes and later runs skip it until the bounds change, it opts out, or it is released. `src/commands/doctor/checks/shared-skills.ts` (`shared_skills_sources`) lists opted-out and parked sources. Operator recipe: `docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills`.- `src/core/shared-skills/optimizer.ts` stages opt-in optimization outside canonical roots with the original grants, immutable approved closure and protected metadata. Publication rechecks authority and the original revision through the coordinator; provider evaluation cannot write canonical skill files directly.diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 1cd4f26776..190391db8f 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -375,7 +375,7 @@ test/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two deftest/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSynctest/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSynctest/shared-skills-catalog.test.ts (file-level) 22 readFileSync-test/shared-skills-export.serial.test.ts (file-level) 13 readFileSync+test/shared-skills-export.serial.test.ts (file-level) 15 readFileSynctest/shared-skills-init.serial.test.ts real combined brain initialization 4 readFileSynctest/shared-skills-migration-cli.serial.test.ts (file-level) 1 readFileSynctest/shared-skills-optimizer.serial.test.ts (file-level) 15 readFileSyncdiff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.tsindex bf5fbf72de..30cf7b8659 100644--- a/src/core/shared-skills/migration-export.ts+++ b/src/core/shared-skills/migration-export.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto';-import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync } from 'node:fs';+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';import { dirname, isAbsolute, join, resolve } from 'node:path';import { spawnSync } from '../spawn.ts';import { opError, OperationError, type OperationContext } from '../ops/contract.ts';@@ -53,6 +53,8 @@ export interface DatabaseContentExportReceipt {pending_actions: string[];root_identity?: { device: number; inode: number };schema_policy?: { schema: ApprovedSchemaIdentity; source_config_sha256: string };+ /** #8528: roots an earlier attempt of this checkpoint filled before it moved; gbrain no longer manages them. */+ earlier_roots?: string[];}function exportPreviewFix(root: string, sourceId: string, why: string): Action {@@ -138,6 +140,14 @@ async function exportInventory(engine: BrainEngine, sourceId: string) {return { files, conflicts, pages: pages.length, schemaPolicy };}+/** #8528: a moving checkpoint's staging directory holds only bytes this export wrote, or the move is refused. */+function assertOwnedStaging(staging: string, hashes: Record<string, string>): void {+ try { verifyFiles(staging, Object.fromEntries(Object.entries(hashes).filter(([path]) => existsSync(join(staging, path)))), true); } catch {+ throw opError('local_conflict', 'The earlier export staging directory holds files this export did not write, so the export was not moved.',+ `${staging} holds a staged copy of every page (private ones included) next to a file the export did not write or an edited one. Ask the user to review that directory and remove it, then run the export again.`);+ }+}+function verifyFiles(root: string, hashes: Record<string, string>, exact = false): void {checkedContentRoot(root);for (const [path, hash] of Object.entries(hashes)) {@@ -199,14 +209,17 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data{ fix: readFix('Prints the saved export checkpoint.', { argv: ['gbrain', 'config', 'get', key] }) });}// #8528: an export that stopped before its source was bound (a destination the Git worktree or privacy checks refused,- // or an interruption) moves to another absent root. The old root and its staging directory are left as they are; the- // checkpoint's file hashes and schema policy are still checked against the database below, and a started claim keeps it.- let moved = false;+ // or an interruption) moves to another absent root. Its staging directory is removed under the lock once it is proven+ // to hold only the export's own bytes; a filled earlier root stays and is named in pending_actions. The checkpoint's+ // file hashes and schema policy are still checked against the database below, and a started claim keeps it.+ let moved: DatabaseContentExportReceipt | null = null;if (prior?.version === 1 && prior.root !== root && prior.brain_id === brain.brain_id && prior.source_incarnation === source.incarnation&& (prior.stage === 'inventory' || prior.stage === 'exported') && !source.local_path&& !(await ctx.engine.executeRaw("SELECT 1 FROM persistence_topology_changes WHERE request_id=$1::uuid AND state<>'failed'", [prior.request_id])).length) {- prior = { ...prior, root, staging_root: `${root}.gbrain-export-${randomUUID()}`, request_id: randomUUID(), stage: 'inventory', root_identity: undefined };- moved = true;+ if (existsSync(prior.staging_root)) assertOwnedStaging(prior.staging_root, prior.files);+ moved = prior;+ prior = { ...prior, root, staging_root: `${root}.gbrain-export-${randomUUID()}`, request_id: randomUUID(), stage: 'inventory', root_identity: undefined,+ ...(existsSync(prior.root) ? { earlier_roots: [...(prior.earlier_roots ?? []), prior.root] } : {}) };}if (prior && (prior.version !== 1 || prior.root !== root || prior.brain_id !== brain.brain_id || prior.source_incarnation !== source.incarnation)) {throw opError('local_conflict', 'The export checkpoint targets a different root or identity.',@@ -242,8 +255,10 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Dataif (!options.confirmQuiesced) receipt.pending_actions.push('Stop all memory/file writers and old skill servers, then pass --confirm-quiesced.');if (!options.backup) receipt.pending_actions.push('Verify an operational backup and pass --backup-confirmed, or explicitly choose --acknowledge-no-backup. Markdown is not a full database backup.');receipt.backup = options.backup ?? receipt.backup;+ const earlier = receipt.earlier_roots?.length ? [`An earlier export of every page, private ones included, remains at ${receipt.earlier_roots.join(', ')}; gbrain no longer manages it. Ask the user whether to keep or delete it.`] : [];if (receipt.conflicts.length || options.dryRun || receipt.pending_actions.length) {receipt.status = receipt.conflicts.length ? 'conflict' : options.dryRun ? 'planned' : 'action_required';+ receipt.pending_actions.push(...earlier);return receipt;}const lock = await acquireNativeLock(gbrainPath('persistence', 'locks', `export-${brain.brain_id}-${source.incarnation}.lock`), { timeoutMs: 1000 });@@ -252,15 +267,26 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data`Another export of source ${options.sourceId} holds its checkpoint lock. Wait for it to finish and preview the checkpoint before starting again; nothing was written by this run.`,{ fix: exportPreviewFix(root, options.sourceId, `Shows the checkpointed export state of source ${options.sourceId} without writing.`) });}- if (moved && !await ctx.engine.getConfig(key).then(value => value === saved, () => false)) {+ if (!await ctx.engine.getConfig(key).then(value => value === saved, () => false)) {await lock.release();throw opError('local_conflict', 'The export checkpoint changed while this export waited for its lock.',- `Another run updated the export checkpoint of source ${options.sourceId}, so it was not moved to ${root}. Preview the checkpoint before starting again.`,+ `Another run updated the export checkpoint of source ${options.sourceId}, so this run wrote nothing. Preview the checkpoint before starting again.`,{ fix: exportPreviewFix(root, options.sourceId, `Shows the checkpointed export state of source ${options.sourceId} without writing.`) });}+ if (moved && existsSync(moved.staging_root)) {+ try { assertOwnedStaging(moved.staging_root, moved.files); rmSync(moved.staging_root, { recursive: true, force: true }); }+ catch (error) { await lock.release(); throw error; }+ }try {await ctx.engine.setConfig(key, JSON.stringify(receipt));if (!existsSync(root)) {+ // The staging directory is a sibling of the root, so a destination inside a repository is refused before any page is written.+ let parent = dirname(root);+ while (!existsSync(parent) && dirname(parent) !== parent) parent = dirname(parent);+ if (spawnSync('git', ['-C', parent, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 }).status === 0) {+ throw opError('local_conflict', 'The export would claim an enclosing Git worktree. Choose a destination outside existing repositories.',+ `${root} lies inside an existing Git worktree; pass --content-root a path outside any repository.`);+ }if (!existsSync(receipt.staging_root)) mkdirSync(receipt.staging_root, { recursive: true, mode: 0o700 });checkedContentRoot(receipt.staging_root);for (const [path, content] of Object.entries(inventory.files)) {@@ -274,11 +300,6 @@ export async function exportDatabaseContent(ctx: OperationContext, options: DataprivateWrite(target, content);}verifyFiles(receipt.staging_root, hashes, true);- const enclosing = spawnSync('git', ['-C', receipt.staging_root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 });- if (enclosing.status === 0) {- throw opError('local_conflict', 'The export would claim an enclosing Git worktree. Choose a destination outside existing repositories.',- `${root} lies inside an existing Git worktree; pass --content-root a path outside any repository.`);- }const current = await exportInventory(ctx.engine, options.sourceId);if (current.conflicts.length || stableJson(current.schemaPolicy) !== stableJson(receipt.schema_policy) || !sameInventory(hashes, Object.fromEntries(Object.entries(current.files).map(([path, content]) => [path, setupHash(content)])))) {throw opError('local_conflict', 'The database content, source schema or ingestion policy changed while exporting; writers were not quiesced.',@@ -313,12 +334,12 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Dataif (!protocol.skill_bundles_enabled) await activateSharedSkillPersistence(ctx.engine, { confirmQuiesced: true });await installPackagedSharedSkills(ctx, options.sourceId, Object.keys(hashes));receipt.stage = 'complete'; receipt.status = 'complete';- receipt.pending_actions = ['Operational database state is retained and still needs backup. Publication consent, grants and client-native activation are unchanged.'];+ receipt.pending_actions = ['Operational database state is retained and still needs backup. Publication consent, grants and client-native activation are unchanged.', ...earlier];await ctx.engine.setConfig(key, JSON.stringify(receipt));return receipt;} catch (error) {receipt.status = error instanceof OperationError && error.code === 'local_conflict' ? 'conflict' : 'action_required';- receipt.pending_actions = [error instanceof OperationError ? `${error.code}: ${error.message}` : 'Export was interrupted; preserve staged files and rerun with the same root and source.'];+ receipt.pending_actions = [error instanceof OperationError ? `${error.code}: ${error.message}` : 'Export was interrupted; preserve staged files and rerun with the same root and source.', ...earlier];await ctx.engine.setConfig(key, JSON.stringify(receipt));throw error;} finally { await lock.release(); }diff --git a/test/shared-skills-export.serial.test.ts b/test/shared-skills-export.serial.test.tsindex a495c62832..36b837568b 100644--- a/test/shared-skills-export.serial.test.ts+++ b/test/shared-skills-export.serial.test.ts@@ -1,5 +1,6 @@import { expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';@@ -143,13 +144,12 @@ test('a source schema change during export refuses binding and remains a checkpoexpect(resumed.conflicts[0].reason).toContain('source schema or ingestion policy changed');}), 120_000);-test('#8528: an export refused at a root inside a Git worktree completes at another root, leaving the first staging untouched', () => fixture(async (ctx, home) => {+test('#8528: an export refused at a root inside a Git worktree writes nothing there and completes at another root', () => fixture(async (ctx, home) => {const repo = join(home, 'repo'); mkdirSync(repo);execFileSync('git', ['init', '-q', repo]);const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };await expect(exportDatabaseContent(ctx, { ...options, root: join(repo, 'content') })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('enclosing Git worktree') });- const staged = readdirSync(repo).filter(name => name.startsWith('content.gbrain-export-'));- expect(staged).toHaveLength(1);+ expect(readdirSync(repo)).toEqual(['.git']);const root = join(home, 'content');expect((await exportDatabaseContent(ctx, { ...options, root, dryRun: true })).status).toBe('planned');const result = await exportDatabaseContent(ctx, { ...options, root });@@ -157,8 +157,8 @@ test('#8528: an export refused at a root inside a Git worktree completes at anotexpect(result.root).toBe(root);expect(readFileSync(join(root, 'notes/example.md'), 'utf8')).toContain('A saved observation.');expect((await ctx.engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'"))[0].local_path).toBe(root);- expect(readdirSync(repo).filter(name => name.startsWith('content.gbrain-export-'))).toEqual(staged);- expect(existsSync(join(repo, staged[0]!, 'notes/example.md'))).toBe(true);+ expect(readdirSync(repo)).toEqual(['.git']);+ expect(result.earlier_roots).toBeUndefined();}), 120_000);test('#8528: an export interrupted before source binding moves to another root; the first root is kept as it was', () => fixture(async (ctx, home) => {@@ -180,6 +180,8 @@ test('#8528: an export interrupted before source binding moves to another root;expect(readFileSync(join(root, 'notes/example.md'), 'utf8')).toBe(bytes);expect(readFileSync(join(first, 'notes/example.md'), 'utf8')).toBe(bytes);expect((await ctx.engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'"))[0].local_path).toBe(root);+ expect(result.earlier_roots).toEqual([first]);+ expect(result.pending_actions.join(' ')).toContain(`An earlier export of every page, private ones included, remains at ${first}`);}), 120_000);test('#8528: a moved export rechecks the inventory and still needs an absent destination', () => fixture(async (ctx, home) => {@@ -237,3 +239,60 @@ test('#8528: an export whose source claim already started keeps its root', () =>VALUES(gen_random_uuid(),$1::uuid,'example','claim','default','recovering')`, [checkpoint.request_id]);await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'content'), dryRun: true })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('different root') });}), 120_000);++test('#8528: a move removes the earlier staging directory only once it holds nothing but the export\'s own bytes', () => fixture(async (ctx, home) => {+ await ctx.engine.setConfig('schema_pack.source.default', 'company-brain');+ const original = ctx.engine.setConfig.bind(ctx.engine);+ let changed = false;+ ctx.engine.setConfig = async (key, value) => {+ await original(key, value);+ if (!changed && key.startsWith('shared_skills.export.')) { changed = true; await original('schema_pack.source.default', 'gbrain-base-v2'); }+ };+ const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'first') })).rejects.toMatchObject({ code: 'local_conflict' });+ ctx.engine.setConfig = original;+ await original('schema_pack.source.default', 'company-brain');+ const staged = readdirSync(home).filter(name => name.startsWith('first.gbrain-export-'));+ expect(staged).toHaveLength(1);+ expect(existsSync(join(home, staged[0]!, 'notes/example.md'))).toBe(true);+ writeFileSync(join(home, staged[0]!, 'notes/unowned.md'), 'A file the export did not write.');+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'second'), dryRun: true })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('staging directory holds files this export did not write') });+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'second') })).rejects.toMatchObject({ code: 'local_conflict' });+ expect(readFileSync(join(home, staged[0]!, 'notes/unowned.md'), 'utf8')).toBe('A file the export did not write.');+ expect(existsSync(join(home, 'second'))).toBe(false);+ rmSync(join(home, staged[0]!, 'notes/unowned.md'));+ const result = await exportDatabaseContent(ctx, { ...options, root: join(home, 'second') });+ expect(result.status).toBe('complete');+ expect(readdirSync(home).filter(name => name.includes('.gbrain-export-'))).toEqual([]);+ expect(result.earlier_roots).toBeUndefined();+}), 120_000);++test('#8528: a resumed export refuses when another run moved its checkpoint before this run took its lock', () => fixture(async (ctx, home) => {+ const first = join(home, 'first'), second = join(home, 'second'), options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };+ const setConfig = ctx.engine.setConfig.bind(ctx.engine);+ let interrupted = false;+ ctx.engine.setConfig = async (key, value) => {+ if (!interrupted && key.startsWith('shared_skills.export.') && JSON.parse(value).stage === 'exported') {+ interrupted = true; throw new Error('injected interruption before source binding');+ }+ return setConfig(key, value);+ };+ await expect(exportDatabaseContent(ctx, { ...options, root: first })).rejects.toThrow('injected interruption before source binding');+ ctx.engine.setConfig = setConfig;+ const getConfig = ctx.engine.getConfig.bind(ctx.engine);+ let raced = false;+ ctx.engine.getConfig = async key => {+ const value = await getConfig(key);+ if (!raced && value && key.startsWith('shared_skills.export.')) {+ raced = true;+ await setConfig(key, JSON.stringify({ ...JSON.parse(value), root: second, staging_root: `${second}.gbrain-export-${randomUUID()}`, request_id: randomUUID(), stage: 'inventory', root_identity: undefined }));+ }+ return value;+ };+ try {+ await expect(exportDatabaseContent(ctx, { ...options, root: first })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('changed while this export waited') });+ } finally { ctx.engine.getConfig = getConfig; }+ const [{ incarnation }] = await ctx.engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");+ expect(JSON.parse((await getConfig(`shared_skills.export.v1.default.${incarnation}`))!).root).toBe(second);+ expect((await ctx.engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'"))[0].local_path).toBeNull();+}), 120_000);