Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(shared-skills): resumed-setup refusal names the claim and activation for a moved source the repair cannot list (#7915)

garrytand2be186fe1c9
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.md
index 1b82996640..c655b6b2c5 100644
--- a/docs/architecture/key-files/shared-skills.md
+++ b/docs/architecture/key-files/shared-skills.md
@@ -6,7 +6,7 @@
- `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-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/{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, or, for a source with no canonical owner (which the repair cannot list), with the `gbrain sources writer claim <id> --path <root> --dry-run --json` preview as the first step (#7915). `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.
- `src/core/persistence/{import-mutations,import-prepare}.ts` routes managed Markdown, code and image import through prepared canonical publication. Source, input, target, owner and revision checks run before apply; derived content retains the source-scoped skill-path guard. `importManagedFiles` takes a batch (at most `IMPORT_BATCH_MAX_PAGES` files and `IMPORT_BATCH_MAX_BYTES`, cut by `nextImportBatch`): each file keeps its own durable intent (`op_checkpoints` `managed-file-import`, written and cleared in one statement per batch), request id, receipt and result; the new requests are admitted in one transaction (`page-batch.ts` `admitBatch`, with its connection-loss re-run and `write_outcome_unknown`) and carry one `intent.import_batch`, so the owner publishes them as independent groups. A file refused before admission settles only that file; a slug the batch already holds ends the batch there, and that file and the rest import after it, as they would one by one. GBRA-75 wave 7: the no-op screen (`unchangedManagedImport`) calls `prepareManagedImportMutation` with `screen: { snapshot }`, the snapshot it just read: the preparer then skips its first path check, the input re-normalization and the snapshot re-read, because the screen just made them, `validate` re-runs every path and byte check last and the no-op kernel re-checks the page revision; a skipped file reads its snapshot once. A canonical input reuses its input hash as the target hash. The plan and screen loops run inside `withScreeningPaths` (`screening-paths.ts`). The preparer imports with `coordinated: true`: publication proves the base revision under its page guard, and the apply reads the page once after its write for the read-back check, the projection target, the text seal and the receipt's postimage. Pinned by `test/persistence-import-batch.test.ts` (row-by-row state against one-by-one imports on PGLite and Postgres, resume, lost commit acknowledgment). A Markdown file over the single-string ceiling imported from outside its source root refuses (`outsideRootTooLarge`) with a message that itself names the move into the root and the target path, and a user fix (`gbrain import <target> --source <id>`; `test/large-pages/managed-import-outside-root.test.ts`).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index fbfc157404..2ead618b82 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -890,8 +890,11 @@ as `content_receipts`. A receipt an older release left on the old root makes
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`.
+began` with this repair as its fix (#7900). The repair lists only sources claimed
+under activated writer persistence, so for a moved source that is not, the
+refusal names the `gbrain sources writer claim` and `activate` previews to run
+first (#7915). Follow the class it prints, then run
+`gbrain apply-migrations --force-retry 0.53.0`.
```bash
gbrain repair content-receipt-root --source default # preview, on the owner host
diff --git a/src/core/shared-skills/setup.ts b/src/core/shared-skills/setup.ts
index 8798e6247d..471d9c62a7 100644
--- a/src/core/shared-skills/setup.ts
+++ b/src/core/shared-skills/setup.ts
@@ -5,6 +5,7 @@ import { gbrainPath, isThinClient } from '../config.ts';
import { opError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { claimWorktree, getWorktreeBinding, readPersistenceBrain } from '../persistence/ownership.ts';
+import { unboundBindCommand } from '../persistence/unbound-source.ts';
import { activateSharedSkillPersistence } from '../persistence/skill-activation.ts';
import { checkedContentRoot } from './setup-files.ts';
import { DEFAULT_SHARED_PACK_ID, packagedSharedSkillPolicy, packagedSharedSkills } from './setup-bundle.ts';
@@ -132,6 +133,15 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
receipt.repository_kind = gitProbe?.status === 0 && resolve(gitProbe.stdout.trim()) === root ? 'git' : 'content_directory';
const existed = existsSync(root);
if (prior?.root && prior.root !== root) {
+ const bound = existingRoot ? await getWorktreeBinding(ctx.engine, sourceId) !== null : true;
+ if (existingRoot && (!bound || !brain.enabled)) {
+ const claim = ['gbrain', 'sources', 'writer', 'claim', sourceId, '--path', root, '--dry-run', '--json'];
+ const activate = ['gbrain', 'sources', 'writer', 'activate', '--confirm-quiesced', '--shared-skills', '--dry-run', '--json'];
+ const activateStep = `activate writer persistence (preview with ${activate.join(' ')}, then run it without --dry-run with --admin-intent writer_activate --expected-state <admin_state>)`;
+ 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). gbrain repair content-receipt-root lists only sources claimed under activated writer persistence, and this source ${bound ? 'is claimed but persistence is not activated' : 'has no canonical owner'}, so the repair has nothing to list yet. Ask the user, then ${bound ? activateStep : `claim it on this host (preview with ${claim.join(' ')}, then ${unboundBindCommand(sourceId, root)})${brain.enabled ? '' : ` and ${activateStep}`}`}. Then preview gbrain repair content-receipt-root --source ${sourceId}, which lists the step that rebinds the checkpoint, and run the migration again.`,
+ { fix: readFix(bound ? 'Previews activating writer persistence with shared skills, read-only.' : `Previews claiming source ${sourceId}'s registered root on this host, read-only.`, { argv: bound ? activate : claim }) });
+ }
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.`,
diff --git a/test/migration-0-53-host-move-7900.test.ts b/test/migration-0-53-host-move-7900.test.ts
index fee366439e..f419ca2aa6 100644
--- a/test/migration-0-53-host-move-7900.test.ts
+++ b/test/migration-0-53-host-move-7900.test.ts
@@ -163,6 +163,51 @@ describe('#7900 branches the host-move walk-through does not reach (pglite)', ()
});
} finally { await close(); rmSync(base, { recursive: true, force: true }); }
}, 120_000);
+
+ // Value: protects=a resumed setup for a moved source that no host has claimed names the claim as its first step, since the repair lists only bound sources; fails_when=the refusal points only at gbrain repair content-receipt-root, whose preview is empty for an unclaimed source, so apply-migrations stops with a fix that does nothing; why_new=#7915; seam=none; no_claim=Postgres arm, the claim's own preview output
+ test('#7915: an unclaimed moved source refuses naming the claim, then the activation; once both ran, the repair lists it', async () => {
+ const base = mkdtempSync(join(tmpdir(), 'gbrain-7915-'));
+ 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: join(base, 'old-home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => isolatedSharedSkillsEngine(undefined));
+ try {
+ await withEnv({ GBRAIN_HOME: join(base, 'old-home') }, async () => {
+ await setupSharedBrainContent(ctxOf(engine), { sourceId: 'default', root: oldRoot });
+ writeFileSync(join(oldRoot, 'notes.md'), '# notes\n');
+ });
+ cpSync(oldRoot, newRoot, { recursive: true });
+ await withEnv({ GBRAIN_HOME: join(base, 'new-home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ try {
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [newRoot]);
+ expect(await getWorktreeBinding(engine, 'default')).toBeNull();
+ expect((await repairPreview(engine)).listing).toEqual([]);
+ for (const run of [() => runSharedSkillsMigration(ctxOf(engine)), () => setupSharedBrainContent(ctxOf(engine), { sourceId: 'default' })]) {
+ const refused = await refusal(run);
+ expect(refused.message).toBe('The canonical root changed after setup began.');
+ expect(refused.suggestion).toContain('has no canonical owner, so the repair has nothing to list yet');
+ expect(refused.suggestion).toContain(`gbrain sources writer claim default --path ${newRoot} --dry-run --json`);
+ expect(refused.suggestion).toContain(`gbrain sources writer claim default --path ${newRoot} --admin-intent writer_claim --expected-state <admin_state>`);
+ expect(refused.suggestion).toContain('gbrain sources writer activate --confirm-quiesced --shared-skills --dry-run --json');
+ expect(refused.suggestion).toContain('Then preview gbrain repair content-receipt-root --source default');
+ expect((refused as { fix?: { argv?: string[] } }).fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'claim', 'default', '--path', newRoot, '--dry-run', '--json']);
+ }
+ expect(await checkpoint(engine)).toMatchObject({ root: oldRoot, stage: 'owner' });
+
+ await claimWorktree(engine, 'default', newRoot);
+ expect((await repairPreview(engine)).listing).toEqual([]);
+ const claimed = await refusal(() => setupSharedBrainContent(ctxOf(engine), { sourceId: 'default' }));
+ expect(claimed.suggestion).toContain('is claimed but persistence is not activated');
+ expect(claimed.suggestion).not.toContain('gbrain sources writer claim');
+ expect((claimed as { fix?: { argv?: string[] } }).fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'activate', '--confirm-quiesced', '--shared-skills', '--dry-run', '--json']);
+
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ const refused = await refusal(() => setupSharedBrainContent(ctxOf(engine), { sourceId: 'default' }));
+ expect((refused as { fix?: { argv?: string[] } }).fix?.argv).toEqual(['gbrain', 'repair', 'content-receipt-root', '--source', 'default']);
+ expect((await repairPreview(engine)).listing).toEqual([expect.objectContaining({ item: 'default', class: 'tree_mismatch' })]);
+ } finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally { await close(); rmSync(base, { recursive: true, force: true }); }
+ }, 120_000);
});
/*