Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): let an unbound 0.53.0 export checkpoint move to another root (#8528)

garrytana57a6a7ba277
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.md
index 1b82996640..f4a49c4d26 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. 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), 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. 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-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.tsv
index 399892acc2..1cd4f26776 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 def
test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync
test/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSync
test/shared-skills-catalog.test.ts (file-level) 22 readFileSync
-test/shared-skills-export.serial.test.ts (file-level) 7 readFileSync
+test/shared-skills-export.serial.test.ts (file-level) 13 readFileSync
test/shared-skills-init.serial.test.ts real combined brain initialization 4 readFileSync
test/shared-skills-migration-cli.serial.test.ts (file-level) 1 readFileSync
test/shared-skills-optimizer.serial.test.ts (file-level) 15 readFileSync
diff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.ts
index da3334b047..bf5fbf72de 100644
--- a/src/core/shared-skills/migration-export.ts
+++ b/src/core/shared-skills/migration-export.ts
@@ -198,6 +198,16 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
`The saved export checkpoint for source ${options.sourceId} (config key ${key}) is not valid JSON, so nothing was exported. Show it to the user and ask how to proceed before changing it.`,
{ 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;
+ 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 (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.',
`An earlier export of source ${options.sourceId} is checkpointed for another root or source incarnation; resume it with its own --content-root, or ask the user to settle it before starting a new one.`,
@@ -212,7 +222,7 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
throw opError('local_conflict', 'The source already has a canonical root; this export never moves it.',
`Source ${options.sourceId} already has a canonical checkout, so it needs no database-only export; the export only creates a root for sources that have none.`);
}
- if (existsSync(root) && !prior) {
+ if (existsSync(root) && (!prior || moved)) {
throw opError('local_conflict', 'Choose an absent export destination; existing directories are never overwritten.',
`${root} already exists; pass --content-root a path that does not exist yet (the export creates it).`);
}
@@ -242,6 +252,12 @@ 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)) {
+ 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.`,
+ { fix: exportPreviewFix(root, options.sourceId, `Shows the checkpointed export state of source ${options.sourceId} without writing.`) });
+ }
try {
await ctx.engine.setConfig(key, JSON.stringify(receipt));
if (!existsSync(root)) {
diff --git a/test/shared-skills-export.serial.test.ts b/test/shared-skills-export.serial.test.ts
index 8220b29619..a495c62832 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -141,3 +142,98 @@ test('a source schema change during export refuses binding and remains a checkpo
expect(resumed.status).toBe('conflict');
expect(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) => {
+ 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);
+ const root = join(home, 'content');
+ expect((await exportDatabaseContent(ctx, { ...options, root, dryRun: true })).status).toBe('planned');
+ const result = await exportDatabaseContent(ctx, { ...options, root });
+ expect(result.status).toBe('complete');
+ expect(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);
+}), 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) => {
+ const first = join(home, 'first'), 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 bytes = readFileSync(join(first, 'notes/example.md'), 'utf8');
+ const root = join(home, 'second');
+ const result = await exportDatabaseContent(ctx, { ...options, root });
+ expect(result.status).toBe('complete');
+ 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);
+}), 120_000);
+
+test('#8528: a moved export rechecks the inventory and still needs an absent destination', () => fixture(async (ctx, home) => {
+ const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };
+ const repo = join(home, 'repo'); mkdirSync(repo);
+ execFileSync('git', ['init', '-q', repo]);
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(repo, 'content') })).rejects.toMatchObject({ code: 'local_conflict' });
+ mkdirSync(join(home, 'taken'));
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'taken'), dryRun: true })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('absent export destination') });
+ await ctx.engine.putPage('notes/example', { type: 'note', title: 'Example', compiled_truth: 'Changed after the checkpoint.', timeline: '', frontmatter: { visibility: 'private', custom: { retained: true } } }, { sourceId: 'default' });
+ const changed = await exportDatabaseContent(ctx, { ...options, root: join(home, 'content') });
+ expect(changed.status).toBe('conflict');
+ expect(changed.conflicts.map(conflict => conflict.reason).join(' ')).toContain('Database content changed since the export checkpoint');
+ expect(existsSync(join(home, 'content'))).toBe(false);
+ expect((await ctx.engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'"))[0].local_path).toBeNull();
+}), 120_000);
+
+test('#8528: a bound export never moves to another root', () => fixture(async (ctx, home) => {
+ const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };
+ expect((await exportDatabaseContent(ctx, { ...options, root: join(home, 'content') })).status).toBe('complete');
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'elsewhere'), dryRun: true })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('different root') });
+ expect(existsSync(join(home, 'elsewhere'))).toBe(false);
+}), 120_000);
+
+test('#8528: a move refuses when another run updated the checkpoint before this run took its lock', () => fixture(async (ctx, home) => {
+ const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };
+ const repo = join(home, 'repo'); mkdirSync(repo);
+ execFileSync('git', ['init', '-q', repo]);
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(repo, 'content') })).rejects.toMatchObject({ code: 'local_conflict' });
+ 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 ctx.engine.setConfig(key, JSON.stringify({ ...JSON.parse(value), pending_actions: ['another run'] }));
+ }
+ return value;
+ };
+ try {
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(home, 'content') })).rejects.toMatchObject({ code: 'local_conflict', message: expect.stringContaining('changed while this export waited') });
+ } finally { ctx.engine.getConfig = getConfig; }
+ expect(existsSync(join(home, 'content'))).toBe(false);
+ expect(JSON.parse((await getConfig('shared_skills.export.v1.default.' + (await ctx.engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'"))[0].incarnation))!).root).toBe(join(repo, 'content'));
+}), 120_000);
+
+test('#8528: an export whose source claim already started keeps its root', () => fixture(async (ctx, home) => {
+ const options = { sourceId: 'default', confirmQuiesced: true, backup: 'operator_verified' as const };
+ const repo = join(home, 'repo'); mkdirSync(repo);
+ execFileSync('git', ['init', '-q', repo]);
+ await expect(exportDatabaseContent(ctx, { ...options, root: join(repo, 'content') })).rejects.toMatchObject({ code: 'local_conflict' });
+ const [{ incarnation }] = await ctx.engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const checkpoint = JSON.parse((await ctx.engine.getConfig(`shared_skills.export.v1.default.${incarnation}`))!);
+ await ctx.engine.executeRaw(`INSERT INTO persistence_topology_changes(principal_id,request_id,digest,operation,source_id,state)
+ 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);