Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(shared-skills): 0.53 migration retakes unfinished inventories, adopts 75-skill packs, accepts reviewed changes (#5569, #5476, A-NEW-4)
time-attack8b129c5fa6f0
diff --git a/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.mdindex a15ef5a471..9519671dcd 100644--- a/docs/guides/shared-brain-skills.md+++ b/docs/guides/shared-brain-skills.md@@ -460,6 +460,27 @@ without re-reading the pack. Resume it in one of three ways, then run`gbrain doctor` warns `shared_skills_sources` while a source is parked.+A pack whose adoption could never publish is refused at inventory instead of+after it: one canonical adoption writes one `SKILL.md` per declared skill plus+`skillpack.json`, at most 128 files (the persistence bundle bound), so a pack+declaring 128 or more skills reports `payload_too_large` as an action (not a+conflict) until it is split across sources or trimmed (#5476). This is separate+from the per-skill bound of 64 declared files.++### Reviewed changes after inventory++When skill files change after the migration inventory, the inventory stage+reports a conflict that lists the changed paths and the exact acceptance+command with a digest of the current files. Review the changes with the user;+only after they agree run+`gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory <source>=<digest> --yes`.+A later edit changes the digest, so the old command is refused again. Hashes+are byte-exact, so a checkout that rewrites line endings (CRLF on Windows)+counts as a change: pin `*.md text eol=lf` in `.gitattributes` before+inventorying. An inventory that never completed (for example, the root was+missing or wrong when it ran) is simply taken again at the corrected root; a+completed inventory whose root moved still refuses (#5569).+An install whose 0.53.0 migration already shows as wedged (three partial runsbefore parking existed) resumes with`gbrain apply-migrations --force-retry 0.53.0`, thendiff --git a/docs/wave9/sg.md b/docs/wave9/sg.mdindex 6082054c89..f38ce27145 100644--- a/docs/wave9/sg.md+++ b/docs/wave9/sg.md@@ -6,6 +6,8 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md- **Long page filenames publish again (#5861).** Atomic and journaled writes stage through a short hidden sibling (`.<sha256 of the target path>.tmp.<uuid>`) instead of appending a suffix to the full basename, so a valid basename near the 255-byte limit no longer fails with ENAMETOOLONG or leaves a write request recovering. Recovery still accepts historical stage names and, under the owner lock, durably swaps in a short name only for a recorded stage the filesystem cannot name. Timeline write-through uses the same allocator (D-NEW-3).- **One image no longer stops managed sync (#5493).** With multimodal embedding on, managed sync holds each image import as `managed_image_sync_unsupported` instead of refusing the whole run, so Markdown and code beside it import and the checkpoint advances. The image is recorded as incomplete coverage (a durable hold in `gbrain sources status`, doctor `git_held_files`, and the `held_files` read notice), re-screened when it changes, leaves the source, or on `gbrain sources retry-held`; deleting or renaming an image still reconciles its page. Image holds never escalate. Reworked from a contribution by @andreineacsu (#5975).+- **`gbrain sources set-path` repairs a stale `local_path` (#5569).** Pointing set-path at the checkout the source is already bound to used to no-op even when `sources.local_path` still named an old directory; it now updates the path. The 0.53.0 shared-skills migration retakes an inventory that never completed at the corrected root instead of recording a conflict on every run; a completed inventory whose root moved still refuses.+- **Bundled-size skill packs adopt in one publication (#5476, A-NEW-4).** One canonical adoption may now write up to 128 files (one SKILL.md per skill plus skillpack.json, the persistence bundle bound) instead of 64, so the 75-skill bundled set adopts. A pack declaring 128 or more skills is refused at inventory as an action instead of failing after it. When skill files change after inventory, the conflict lists the changed paths and an exact `gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory <source>=<digest> --yes` acceptance command.## Upgrade-note rows@@ -13,3 +15,5 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md|---|---|---|---|| Staging files are now hidden `.<hash>.tmp.<uuid>` siblings (#5861) | Anyone with page basenames over ~214 bytes; operators who glob for `*.tmp.*` leftovers (the new names still contain `.tmp.`) | `gbrain sources writer status --json` shows any recovery that still holds a stage | None needed; historical journals keep working || Managed sync holds images instead of refusing the run (#5493) | Managed brains with `embedding_multimodal` on whose sources contain images | doctor `git_held_files` warns with `managed_image_sync_unsupported` paths (never fails for them) | Exclude images with `sync.exclude`, or turn multimodal embedding off; either clears the holds on the next sync |+| set-path updates a stale `sources.local_path` (#5569) | Sources whose DB path drifted from their writer binding | `gbrain sources list --json` shows the corrected path | None |+| 0.53.0 migration: re-inventory, 128-file pack adoption, reviewed acceptance (#5476) | Brains adopting shared skills with >63 skills or edited packs | `gbrain apply-migrations --migration 0.53.0 --dry-run --json` shows per-source stages | Don't pass `--accept-reviewed-inventory`; the conflict stays until reviewed |diff --git a/skills/migrations/v0.53.0.0.md b/skills/migrations/v0.53.0.0.mdindex 29abd444f0..fd238d3a23 100644--- a/skills/migrations/v0.53.0.0.md+++ b/skills/migrations/v0.53.0.0.md@@ -27,6 +27,12 @@ withdrawals, or durable receipts. Keep credentials and backups private andverify recovery before declaring them protected. Do not open a running PGLiteowner's database from a second process or remove its live lock.+If a source reports `Files changed since migration inventory`, show the user+the listed paths. Accept them only with their agreement, using the+`--accept-reviewed-inventory <source>=<digest>` command printed in that+reason; never delete the checkpoint by hand. Line-ending rewrites (CRLF+checkouts) count as changes, so pin `*.md text eol=lf` first.+## 2. Stop old writers and activate the host protocolStop old servers, workers, sync jobs, optimizers, and direct filesystem writersdiff --git a/src/cli/help/apply-migrations.ts b/src/cli/help/apply-migrations.tsindex 9922dc30a5..bce2c4d515 100644--- a/src/cli/help/apply-migrations.ts+++ b/src/cli/help/apply-migrations.ts@@ -31,6 +31,7 @@ export const help: CliHelpSpec = {{ name: '--confirm-quiesced', type: 'boolean', desc: 'Attest old writers and skill servers are stopped.' },{ name: '--backup-confirmed', type: 'boolean', desc: 'Attest an operational backup was verified.' },{ name: '--acknowledge-no-backup', type: 'boolean', desc: 'Proceed without a verified backup (explicit choice).', consent: ['destructive'] },+ { name: '--accept-reviewed-inventory', type: 'string', desc: 'With --migration 0.53.0: accept a skill-pack change the user reviewed, as <source>=<digest> from the conflict message (repeatable; a later edit changes the digest).' },],examples: ['gbrain apply-migrations --dry-run --json',diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 381e358977..4fc05e8ae6 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -43,6 +43,7 @@ interface ApplyMigrationsArgs {dryRun: boolean;json: boolean;dbOnlyExport?: OrchestratorOpts['dbOnlyExport'];+ acceptReviewedInventory?: OrchestratorOpts['acceptReviewedInventory'];yes: boolean;nonInteractive: boolean;mode?: 'always' | 'pain_triggered' | 'off';@@ -79,6 +80,14 @@ function parseArgs(args: string[]): ApplyMigrationsArgs {exitCliError(usageError('DB-only export requires --content-root and exactly one explicit backup choice for a non-dry run.','Example: gbrain apply-migrations --migration <version> --export-db-only --content-root <path> --backup-confirmed --dry-run --json'), COMMAND);}+ const accepted: Record<string, string> = {};+ args.forEach((arg, i) => {+ if (arg !== '--accept-reviewed-inventory') return;+ const match = /^([^=\s]+)=([a-f0-9]{64})$/.exec(args[i + 1] ?? '');+ if (!match) exitCliError(usageError('--accept-reviewed-inventory takes <source-id>=<64-hex inventory digest>, copied from the migration\'s conflict message.',+ 'Example: gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory default=<digest> --yes'), COMMAND);+ accepted[match![1]] = match![2];+ });if (mode && !['always', 'pain_triggered', 'off'].includes(mode)) {exitCliError(usageError(`Invalid --mode "${mode}". Allowed: always, pain_triggered, off.`,'Example: gbrain apply-migrations --yes --mode pain_triggered'), COMMAND);@@ -90,6 +99,7 @@ function parseArgs(args: string[]): ApplyMigrationsArgs {dbOnlyExport: exporting ? { root: val('--content-root')!, sourceId: val('--export-source') ?? 'default',confirmQuiesced: has('--confirm-quiesced'),backup: has('--backup-confirmed') ? 'operator_verified' : has('--acknowledge-no-backup') ? 'acknowledged_unprotected' : undefined } : undefined,+ ...(Object.keys(accepted).length ? { acceptReviewedInventory: accepted } : {}),yes: has('--yes'),nonInteractive: has('--non-interactive'),mode,@@ -121,6 +131,10 @@ Usage:--confirm-quiesced Attest old writers and skill servers are stopped.--backup-confirmed Attest an operational backup was verified by you.--acknowledge-no-backup Explicitly proceed without a verified backup.+ gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory <source>=<digest> --yes+ Accept a skill-pack change the user reviewed; the+ digest comes from the conflict message and stops+ matching if the files change again. Repeatable.gbrain apply-migrations --list [--json]Show applied + pending migrations.pending_fresh_install = setup work a@@ -387,6 +401,7 @@ function orchestratorOptsFrom(cli: ApplyMigrationsArgs, ownLeaseToken?: string):hostDir: cli.hostDir,noAutopilotInstall: cli.noAutopilotInstall,dbOnlyExport: cli.dbOnlyExport && { ...cli.dbOnlyExport, ownLeaseToken },+ ...(cli.acceptReviewedInventory ? { acceptReviewedInventory: cli.acceptReviewedInventory } : {}),};}diff --git a/src/commands/migrations/shared-content.ts b/src/commands/migrations/shared-content.tsindex c5be6f4696..50ec0ecbe5 100644--- a/src/commands/migrations/shared-content.ts+++ b/src/commands/migrations/shared-content.ts@@ -12,7 +12,8 @@ export const SHARED_CONTENT_MIGRATION_VERSION = '0.53.0';/** Read-only: prints every source's remaining stage, its reason and the command for it (`pending_actions`). */export const SHARED_CONTENT_INSPECT_ARGV = ['gbrain', 'apply-migrations', '--migration', SHARED_CONTENT_MIGRATION_VERSION, '--dry-run', '--json'];-export async function inspectSharedContentMigration(dryRun: boolean, exportOptions?: OrchestratorOpts['dbOnlyExport']): Promise<SharedMigrationReport | null> {+export async function inspectSharedContentMigration(dryRun: boolean, exportOptions?: OrchestratorOpts['dbOnlyExport'],+ acceptReviewedInventory?: OrchestratorOpts['acceptReviewedInventory']): Promise<SharedMigrationReport | null> {const config = loadConfig();if (!config) return null;if (isThinClient(config)) return {@@ -25,7 +26,7 @@ export async function inspectSharedContentMigration(dryRun: boolean, exportOptioconst ctx = { engine, config, sourceId: exportOptions?.sourceId ?? 'default', remote: false, dryRun,logger: { info: console.error, warn: console.error, error: console.error } };const exported = exportOptions ? await exportDatabaseContent(ctx, { ...exportOptions, dryRun }) : undefined;- const report = await runSharedSkillsMigration(ctx, { dryRun });+ const report = await runSharedSkillsMigration(ctx, { dryRun, acceptReviewedInventory });if (exported) {report.content_export = exported;if (exported.status !== 'complete') report.status = exported.status === 'conflict' ? 'conflict' : 'action_required';@@ -41,11 +42,11 @@ export const sharedContentMigration: Migration = {headline: 'Knowledge and shared skills belong to the same source-scoped content repository.',description: 'Inventories and checkpoints existing packs without moving knowledge or changing grants. Existing true publishing remains prose-only, false stays disabled, and DB-only/export, old writers and client activation remain explicit pending actions.',},- preview: options => inspectSharedContentMigration(true, options.dbOnlyExport),+ preview: options => inspectSharedContentMigration(true, options.dbOnlyExport, options.acceptReviewedInventory),reconcile: true,orchestrator: async options => {try {- const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport);+ const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport, options.acceptReviewedInventory);if (!report) return { version: SHARED_CONTENT_MIGRATION_VERSION, status: 'complete', phases: [{ name: 'inventory', status: 'skipped', detail: 'No brain configured.' }] };const pending = report.status === 'action_required' || report.status === 'conflict';console.error(`[shared-skills] ${report.status}. ${report.sources.filter(source => source.status !== 'complete').length} source(s) need host action; no grants or bundle consent changed.`diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.tsindex 08c5db18de..c59d46d7f9 100644--- a/src/commands/migrations/types.ts+++ b/src/commands/migrations/types.ts@@ -42,6 +42,8 @@ export interface OrchestratorOpts {/** The runner's own orchestration lease, which the quiescence check ignores. */ownLeaseToken?: string;};+ /** #5476: `--accept-reviewed-inventory <source>=<digest>`: the reviewed shared-skills inventory change to accept, per source. */+ acceptReviewedInventory?: Record<string, string>;}export interface OrchestratorPhaseResult {diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 14164c2b1c..efdb2ee9d0 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],- 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],+ 'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],@@ -89,7 +89,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--url', '--yes'],@@ -128,7 +128,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--url', '--yes'],diff --git a/src/core/shared-skills/migration.ts b/src/core/shared-skills/migration.tsindex 6bb8ba90f9..520d4c06db 100644--- a/src/core/shared-skills/migration.ts+++ b/src/core/shared-skills/migration.ts@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import { existsSync, readdirSync } from 'node:fs';import { join, resolve } from 'node:path';import { isThinClient } from '../config.ts';@@ -10,6 +11,7 @@ import type { DatabaseContentExportReceipt } from './migration-export.ts';import { inspectSharedMemberMigration, type SharedMemberMigration } from './migration-members.ts';import { sharedSkillSourcePolicyOrPreserve } from './setup-source-policy.ts';import { INVENTORY_LIMIT_CEILINGS, readInventoryLimits, type InventoryLimits } from './inventory-limits.ts';+import { SHARED_SKILL_LIMITS } from './model.ts';export type MigrationPublication = 'disabled' | 'prose_only' | 'consent_required';export interface SharedMigrationStage {@@ -66,6 +68,15 @@ export function parkedReason(sourceId: string, parked: SharedSourceParked): stri+ 'See docs/guides/shared-brain-skills.md#oversized-skill-packs.';}+/** The digest an operator echoes to accept a reviewed inventory change (#5476): the sorted path/hash list. */+export function inventoryDigest(hashes: Record<string, string>): string {+ return createHash('sha256').update(JSON.stringify(Object.keys(hashes).sort().map(path => [path, hashes[path]]))).digest('hex');+}++function changedInventoryPaths(before: Record<string, string>, after: Record<string, string>): string[] {+ return [...new Set([...Object.keys(before), ...Object.keys(after)])].filter(path => before[path] !== after[path]).sort();+}+export async function legacyPublication(ctx: OperationContext): Promise<MigrationPublication> {const dbValue = await ctx.engine.getConfig('mcp.publish_skills');const value = dbValue === null ? ctx.config.mcp?.publish_skills : dbValue;@@ -74,7 +85,7 @@ export async function legacyPublication(ctx: OperationContext): Promise<Migratioreturn 'consent_required';}-export async function runSharedSkillsMigration(ctx: OperationContext, options: { dryRun?: boolean } = {}): Promise<SharedMigrationReport> {+export async function runSharedSkillsMigration(ctx: OperationContext, options: { dryRun?: boolean; acceptReviewedInventory?: Record<string, string> } = {}): Promise<SharedMigrationReport> {if (ctx.remote !== false) {throw opError('permission_denied', 'Shared-skills migration requires the trusted local host.','The shared-skills migration runs only from gbrain apply-migrations on the brain host; a remote connection cannot run it.');@@ -154,19 +165,33 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {}row.inventory = inventorySkillpack(row.root, limits);if (prior && (prior.source_incarnation !== source.incarnation || prior.root !== row.root)) {- throw opError('local_conflict', 'The source root changed since migration inventory.',- `Source ${source.id} was recreated or moved since its migration inventory was taken; review the checkpoint with the user before continuing the migration.`);+ // #5569: an inventory that never completed has nothing to preserve, so it is taken again at the current root.+ if (prior.stages?.some(stage => stage.stage === 'inventory' && stage.status === 'complete')) {+ throw opError('local_conflict', 'The source root changed since migration inventory.',+ `Source ${source.id} was recreated or moved since its migration inventory was taken; review the checkpoint with the user before continuing the migration.`);+ }+ prior = null;}if (prior?.inventory && (!row.inventory || !sameInventory(prior.inventory.hashes, row.inventory.hashes))) {const original = { ...prior.inventory.hashes }, current = { ...row.inventory?.hashes };delete original['skillpack.json']; delete current['skillpack.json'];const [sealed] = await ctx.engine.executeRaw<{ manifest_hash: string }>('SELECT manifest_hash FROM shared_skill_packs WHERE source_id=$1 AND source_incarnation=$2::uuid', [source.id, source.incarnation]);- if (!row.inventory || !sameInventory(original, current) || sealed?.manifest_hash !== row.inventory.hashes['skillpack.json']) {+ const digest = row.inventory ? inventoryDigest(row.inventory.hashes) : null;+ if ((!row.inventory || !sameInventory(original, current) || sealed?.manifest_hash !== row.inventory.hashes['skillpack.json'])+ && (digest === null || options.acceptReviewedInventory?.[source.id] !== digest)) {+ const changed = changedInventoryPaths(prior.inventory.hashes, row.inventory?.hashes ?? {});row.inventory = prior.inventory;- throw opError('local_conflict', 'Files changed since migration inventory; preserve edits and review the checkpoint before retrying.',- `Skill files under ${row.root} changed since the migration inventory. Keep the edits, review them with the user, then run the migration again.`);+ throw opError('local_conflict', `Files changed since migration inventory; preserve edits and review the checkpoint before retrying. Changed: ${changed.slice(0, 20).join(', ')}${changed.length > 20 ? ` and ${changed.length - 20} more` : ''}.`+ + (digest ? ` After the user reviews these changes, accept exactly this inventory with gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory ${source.id}=${digest} --yes.` : ''),+ `Skill files under ${row.root} changed since the migration inventory. Keep the edits and review them with the user; only after they agree, accept the reviewed inventory with the command in the message (a later edit changes the digest and is refused again).`);}}+ // A-NEW-4: one canonical adoption writes one SKILL.md per declared skill plus skillpack.json.+ if (row.inventory && row.inventory.names.length + 1 > SHARED_SKILL_LIMITS.packFiles) {+ await pending('inventory', `payload_too_large: source ${source.id} declares ${row.inventory.names.length} skills, but one canonical adoption publishes at most ${SHARED_SKILL_LIMITS.packFiles} files (one SKILL.md per skill plus skillpack.json). `+ + `Split the pack across sources or remove skills from skillpack.json, then run gbrain apply-migrations --migration 0.53.0 --yes. See docs/guides/shared-brain-skills.md#oversized-skill-packs.`);+ continue;+ }} catch (error) {if (error instanceof OperationError && error.code === 'payload_too_large' && error.detail) {row.inventory = prior?.inventory ?? null;diff --git a/src/core/shared-skills/model.ts b/src/core/shared-skills/model.tsindex 5825b18a05..f1e8f2a1ce 100644--- a/src/core/shared-skills/model.ts+++ b/src/core/shared-skills/model.ts@@ -99,6 +99,12 @@ export interface StoredSkillRevision {deleted: boolean;policy_epoch: string;}-export const SHARED_SKILL_LIMITS = Object.freeze({ files: 64, fileBytes: 1024 * 1024,+/**+ * `files` bounds one skill's declared files. `packFiles` bounds one canonical+ * publication (adoption writes one SKILL.md per declared skill plus+ * skillpack.json); it equals the persistence bundle bound+ * (`BUNDLE_FILE_LIMITS.files`) that the journal enforces on every bundle (#5476).+ */+export const SHARED_SKILL_LIMITS = Object.freeze({ files: 64, packFiles: 128, fileBytes: 1024 * 1024,skillMdBytes: 256 * 1024, bundleBytes: 4 * 1024 * 1024, closureDepth: 12,pageSize: 100, catalogSkills: 10_000 });diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.tsindex 62abb551af..59351af109 100644--- a/src/core/shared-skills/publication.ts+++ b/src/core/shared-skills/publication.ts@@ -466,9 +466,9 @@ export async function prepareSharedSkillMutation(engine: BrainEngine, row: Writeconst packRevision = randomUUID();let prunedRevisions = 0;const totalBytes = Buffer.byteLength(manifestContent) + [...changedFiles.values()].reduce((sum, file) => sum + (file?.size ?? 0), 0) + Object.values(intent.extra_files).reduce((sum, content) => sum + Buffer.byteLength(content), 0);- if (totalBytes > SHARED_SKILL_LIMITS.bundleBytes || changedFiles.size + Object.keys(intent.extra_files).length + 1 > SHARED_SKILL_LIMITS.files) {+ if (totalBytes > SHARED_SKILL_LIMITS.bundleBytes || changedFiles.size + Object.keys(intent.extra_files).length + 1 > SHARED_SKILL_LIMITS.packFiles) {throw opError('invalid_params', 'The complete canonical publication exceeds the file-set bound.',- `Request ${row.request_id} would write ${changedFiles.size + Object.keys(intent.extra_files).length + 1} files and ${totalBytes} bytes; one publication may write at most ${SHARED_SKILL_LIMITS.files} files and ${SHARED_SKILL_LIMITS.bundleBytes} bytes. Split the shared-conventions edit into smaller changes and resubmit each with a new request_id.`);+ `Request ${row.request_id} would write ${changedFiles.size + Object.keys(intent.extra_files).length + 1} files and ${totalBytes} bytes; one publication may write at most ${SHARED_SKILL_LIMITS.packFiles} files and ${SHARED_SKILL_LIMITS.bundleBytes} bytes. Split the shared-conventions edit into smaller changes and resubmit each with a new request_id.`);}return {target: 'skill_bundle', sourceExclusive: true, observedRevision: intent.expected_revision,diff --git a/test/shared-skills-pack-bounds-5476.test.ts b/test/shared-skills-pack-bounds-5476.test.tsnew file mode 100644index 0000000000..f10d8b8dbd--- /dev/null+++ b/test/shared-skills-pack-bounds-5476.test.ts@@ -0,0 +1,59 @@+/**+ * #5476 item 2 / A-NEW-4: one canonical adoption publishes one SKILL.md per+ * declared skill plus skillpack.json, so the pack-level publication bound is+ * separate from the per-skill file bound (64). The bundled pack (75 skills)+ * must fit; a pack beyond the persistence bundle bound is refused by name.+ */+import { expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { BUNDLE_FILE_LIMITS } from '../src/core/persistence/bundle-files.ts';+import { adoptSharedSkillpack } from '../src/core/shared-skills/publication.ts';+import { listSharedSkills } from '../src/core/shared-skills/catalog.ts';+import { SHARED_SKILL_LIMITS } from '../src/core/shared-skills/model.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';++async function fixture(run: (local: OperationContext, root: string) => Promise<void>) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-pack-bounds-'));+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined }, async () => {+ const isolated = await isolatedSharedSkillsEngine();+ const engine = isolated.engine;+ try {+ const root = join(dir, 'default'); mkdirSync(root);+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, 'default']);+ await claimWorktree(engine, 'default', root);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await engine.setConfig('mcp.publish_skills', 'true');+ await run({ engine, config: { engine: 'pglite' }, remote: false, sourceId: 'default', dryRun: false, logger: { info() {}, warn() {}, error() {} } }, root);+ } finally { await disposePersistenceConsumer(engine); await isolated.close(); }+ });+ rmSync(dir, { recursive: true, force: true });+}+function writePack(root: string, count: number) {+ const names = Array.from({ length: count }, (_, i) => `skill-${String(i).padStart(3, '0')}`);+ for (const name of names) {+ mkdirSync(join(root, 'skills', name), { recursive: true });+ writeFileSync(join(root, 'skills', name, 'SKILL.md'), `---\nname: ${name}\ndescription: A synthetic fixture skill\n---\n\nInstructions for ${name}.\n`);+ }+ writeFileSync(join(root, 'skillpack.json'), JSON.stringify({ name: 'example-pack', brain_resident: true, skills: names.map(name => `skills/${name}`) }));+ return names;+}++test('the pack publication bound is the persistence bundle bound, not the per-skill file bound', () => {+ expect(SHARED_SKILL_LIMITS.packFiles).toBe(BUNDLE_FILE_LIMITS.files);+ expect(SHARED_SKILL_LIMITS.packFiles).toBeGreaterThan(SHARED_SKILL_LIMITS.files);+});++test('a 75-skill pack (the bundled set size) adopts in one canonical publication', () => fixture(async (local, root) => {+ const names = writePack(root, 75);+ const adopted = await adoptSharedSkillpack(local, 'default');+ expect(adopted.receipts.map(receipt => (receipt.write_request as { state?: string } | undefined)?.state)).toEqual(['committed']);+ const listed = await listSharedSkills(local, { limit: 100 });+ expect(listed.skills.map(skill => skill.name).sort()).toEqual(names);+}), 180_000);diff --git a/test/shared-skills-setup.test.ts b/test/shared-skills-setup.test.tsindex 192d9f3397..12e2d0e278 100644--- a/test/shared-skills-setup.test.ts+++ b/test/shared-skills-setup.test.ts@@ -212,3 +212,53 @@ describe('packaged default skills', () => {expect(JSON.parse(output)).toEqual(packagedSharedSkills());}, 60_000);});++describe('shared-skills migration recovery (#5569, #5476, A-NEW-4)', () => {+ test('an inventory that never completed is retaken at the corrected root instead of conflicting (#5569)', async () => {+ const stale = join(temp(), 'missing'), fixed = temp(), f = fixture(stale); writePack(fixed);+ const first = await runSharedSkillsMigration(f.ctx);+ expect(first.sources[0].stages[0]).toMatchObject({ stage: 'inventory', status: 'conflict' });+ f.source.local_path = fixed;+ const second = await runSharedSkillsMigration(f.ctx);+ expect(second.status).not.toBe('conflict');+ expect(second.sources[0].stages[0]).toEqual({ stage: 'inventory', status: 'complete' });+ expect(second.sources[0].root).toBe(fixed);+ });+ test('a completed inventory still refuses a moved root (#5569)', async () => {+ const first = temp(), moved = temp(), f = fixture(first); writePack(first); writePack(moved);+ expect((await runSharedSkillsMigration(f.ctx)).sources[0].stages[0]).toEqual({ stage: 'inventory', status: 'complete' });+ f.source.local_path = moved;+ const report = await runSharedSkillsMigration(f.ctx);+ expect(report.status).toBe('conflict');+ expect(report.sources[0].stages[0].reason).toContain('root changed');+ });+ test('a reviewed inventory change is accepted only by its exact digest (#5476)', async () => {+ const root = temp(), f = fixture(root); writePack(root);+ expect((await runSharedSkillsMigration(f.ctx)).status).toBe('action_required');+ writeFileSync(join(root, 'skills/memory-care/SKILL.md'), '---\nname: memory-care\ndescription: Reviewed local edit\n---\nLocal instructions\n');+ const edited = await runSharedSkillsMigration(f.ctx);+ expect(edited.status).toBe('conflict');+ const reason = edited.sources[0].stages[0].reason!;+ expect(reason).toContain('Changed: skills/memory-care/SKILL.md.');+ const digest = /--accept-reviewed-inventory default=([a-f0-9]{64})/.exec(reason)![1];+ expect((await runSharedSkillsMigration(f.ctx, { acceptReviewedInventory: { default: '0'.repeat(64) } })).status).toBe('conflict');+ const accepted = await runSharedSkillsMigration(f.ctx, { acceptReviewedInventory: { default: digest } });+ expect(accepted.status).toBe('action_required');+ expect(accepted.sources[0].stages[0]).toEqual({ stage: 'inventory', status: 'complete' });+ expect(accepted.sources[0].inventory?.hashes['skills/memory-care/SKILL.md']).toBe(setupHash(readFileSync(join(root, 'skills/memory-care/SKILL.md'))));+ expect((await runSharedSkillsMigration(f.ctx)).status).toBe('action_required');+ });+ test('a pack one adoption cannot publish is refused at inventory, not after it (A-NEW-4)', async () => {+ const root = temp(), f = fixture(root);+ const names = Array.from({ length: 128 }, (_, i) => `skill-${String(i).padStart(3, '0')}`);+ for (const name of names) {+ mkdirSync(join(root, 'skills', name), { recursive: true });+ writeFileSync(join(root, 'skills', name, 'SKILL.md'), `---\nname: ${name}\ndescription: Synthetic\n---\nBody\n`);+ }+ writeFileSync(join(root, 'skillpack.json'), JSON.stringify({ name: 'example-pack', brain_resident: true, skills: names.map(name => `skills/${name}`) }));+ const report = await runSharedSkillsMigration(f.ctx);+ expect(report.status).toBe('action_required');+ expect(report.sources[0].stages[0]).toMatchObject({ stage: 'inventory', status: 'action_required' });+ expect(report.sources[0].stages[0].reason).toContain('declares 128 skills');+ });+});