Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

shared-skills: config-backed capped inventory bounds; an oversized pack parks its source instead of wedging 0.53.0

garrytan25e9784695d5
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 9da71f6759..ea52887179 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1060,6 +1060,13 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }
}
+ // The shared-skills migration reads these bounds on every run; refuse a malformed or over-ceiling value.
+ const { INVENTORY_LIMIT_KEYS, parseInventoryLimitValue } = await import('../core/shared-skills/inventory-limits.ts');
+ if (INVENTORY_LIMIT_KEYS.includes(key)) {
+ try { parseInventoryLimitValue(key, value); }
+ catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
+ }
+
// #5254: an unknown value would silently keep refusing unbound writes.
const { UNBOUND_WRITE_KEY, parseUnboundWriteValue } = await import('../core/persistence/unbound-source.ts');
if (key === UNBOUND_WRITE_KEY) {
diff --git a/src/core/config.ts b/src/core/config.ts
index 10c5140a1b..2a7b06c4af 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1661,6 +1661,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.principal_terminal_bytes', 'persistence.limits.brain_terminal_bytes',
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts
+ // shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
+ 'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries',
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
'migrate.graduation', // file plane, src/commands/migrate-graduation.ts (engine graduation opt-out)
'consent.preapprove.paid.max_usd_per_run', 'consent.preapprove.persistent_install', // A4: file plane, core/consent.ts
diff --git a/src/core/shared-skills/inventory-limits.ts b/src/core/shared-skills/inventory-limits.ts
new file mode 100644
index 0000000000..924d1debf0
--- /dev/null
+++ b/src/core/shared-skills/inventory-limits.ts
@@ -0,0 +1,48 @@
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+
+/**
+ * Size bounds for the shared-skills migration inventory (`inventorySkillpack`).
+ * Database config, written only through the trusted local `gbrain config set`
+ * (no MCP operation writes config). Each value is capped by
+ * INVENTORY_LIMIT_CEILINGS; confinement checks (symlinks, hard links, unsafe
+ * paths, directory depth) are not configurable.
+ */
+export interface InventoryLimits {
+ max_files: number;
+ max_total_bytes: number;
+ max_file_bytes: number;
+ max_entries: number;
+}
+
+export const DEFAULT_INVENTORY_LIMITS: Readonly<InventoryLimits> = {
+ max_files: 256, max_total_bytes: 4 * 1024 * 1024, max_file_bytes: 262_144, max_entries: 1024,
+};
+
+export const INVENTORY_LIMIT_CEILINGS: Readonly<InventoryLimits> = {
+ max_files: 4096, max_total_bytes: 64 * 1024 * 1024, max_file_bytes: 8 * 1024 * 1024, max_entries: 16_384,
+};
+
+const PREFIX = 'shared_skills.inventory.';
+export const inventoryLimitKey = (name: keyof InventoryLimits): string => `${PREFIX}${name}`;
+export const INVENTORY_LIMIT_KEYS: readonly string[] = (Object.keys(DEFAULT_INVENTORY_LIMITS) as Array<keyof InventoryLimits>).map(inventoryLimitKey);
+
+export function parseInventoryLimitValue(key: string, value: string): number {
+ const name = key.slice(PREFIX.length) as keyof InventoryLimits;
+ const ceiling = INVENTORY_LIMIT_CEILINGS[name];
+ if (!/^[1-9]\d*$/.test(value) || Number(value) > ceiling) {
+ throw opError('invalid_params', `Invalid ${key}: expected a whole number from 1 to ${ceiling}.`,
+ `Set ${key} to a whole number from 1 to ${ceiling} (default ${DEFAULT_INVENTORY_LIMITS[name]}), or unset it to use the default.`,
+ { fix: readFix('Removes the override so the default bound applies.', { argv: ['gbrain', 'config', 'unset', key] }) });
+ }
+ return Number(value);
+}
+
+export async function readInventoryLimits(engine: { getConfig(key: string): Promise<string | null> }): Promise<InventoryLimits> {
+ const limits = { ...DEFAULT_INVENTORY_LIMITS };
+ for (const name of Object.keys(limits) as Array<keyof InventoryLimits>) {
+ const value = await engine.getConfig(inventoryLimitKey(name));
+ if (value !== null) limits[name] = parseInventoryLimitValue(inventoryLimitKey(name), value);
+ }
+ return limits;
+}
diff --git a/src/core/shared-skills/migration.ts b/src/core/shared-skills/migration.ts
index 3511769317..6bb8ba90f9 100644
--- a/src/core/shared-skills/migration.ts
+++ b/src/core/shared-skills/migration.ts
@@ -8,7 +8,8 @@ import { checkedContentRoot, inventorySkillpack, sameInventory, type PackInvento
import { contentSetupKey, installPackagedSharedSkills, setupSharedBrainContent, type SharedContentReceipt } from './setup.ts';
import type { DatabaseContentExportReceipt } from './migration-export.ts';
import { inspectSharedMemberMigration, type SharedMemberMigration } from './migration-members.ts';
-import { sharedSkillSourcePolicy } from './setup-source-policy.ts';
+import { sharedSkillSourcePolicyOrPreserve } from './setup-source-policy.ts';
+import { INVENTORY_LIMIT_CEILINGS, readInventoryLimits, type InventoryLimits } from './inventory-limits.ts';
export type MigrationPublication = 'disabled' | 'prose_only' | 'consent_required';
export interface SharedMigrationStage {
@@ -25,6 +26,19 @@ export interface SharedSourceMigration {
stages: SharedMigrationStage[];
status: 'complete' | 'action_required' | 'conflict' | 'planned';
member_installations?: SharedMemberMigration[];
+ parked?: SharedSourceParked;
+}
+/**
+ * A source whose pack exceeds an inventory bound. Later runs skip it without
+ * re-inventorying (the migration completes instead of going partial) until the
+ * configured bounds change, the source opts out, or
+ * `gbrain sources shared-skills <id> on` releases it.
+ */
+export interface SharedSourceParked {
+ limit: string;
+ limits: InventoryLimits;
+ reason: string;
+ parked_at: string;
}
export interface SharedMigrationReport {
version: 1;
@@ -41,6 +55,17 @@ export function migrationCheckpointKey(sourceId: string, incarnation: string): s
return `shared_skills.migration.v1.${sourceId}.${incarnation}`;
}
+const sameLimits = (a: InventoryLimits, b: InventoryLimits): boolean =>
+ (Object.keys(INVENTORY_LIMIT_CEILINGS) as Array<keyof InventoryLimits>).every(name => a[name] === b[name]);
+
+export function parkedReason(sourceId: string, parked: SharedSourceParked): string {
+ const ceiling = INVENTORY_LIMIT_CEILINGS[parked.limit.split('.').pop() as keyof InventoryLimits];
+ return `payload_too_large: ${parked.reason} Parked: this source is skipped, not retried, and the rest of the migration completes. `
+ + `Raise the bound (gbrain config set ${parked.limit} <n>, at most ${ceiling}), opt the source out (gbrain sources shared-skills ${sourceId} off), `
+ + `or shrink the pack and release it (gbrain sources shared-skills ${sourceId} on); then run gbrain apply-migrations --migration 0.53.0 --yes. `
+ + 'See docs/guides/shared-brain-skills.md#oversized-skill-packs.';
+}
+
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;
@@ -70,11 +95,11 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
}
report.brain_id = brain.brain_id;
const publication = await legacyPublication(ctx);
+ const limits = await readInventoryLimits(ctx.engine);
const roots = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>('SELECT id,incarnation,local_path FROM sources WHERE NOT archived ORDER BY id');
const fallback = await ctx.engine.getConfig('sync.repo_path');
for (const source of roots) {
- const sourcePolicy = await sharedSkillSourcePolicy(ctx.engine, source.id).catch(error => ({ mode: 'preserve_files' as const,
- reason: error instanceof OperationError ? `${error.code}: ${error.message}` : 'profile_incompatible: the source writeback policy could not be verified; no repository changes were attempted.' }));
+ const sourcePolicy = await sharedSkillSourcePolicyOrPreserve(ctx.engine, source.id);
const contentCheckpoint = await ctx.engine.getConfig(contentSetupKey(source.id, source.incarnation));
if (contentCheckpoint && !dryRun && sourcePolicy.mode === 'content') {
let content: SharedContentReceipt;
@@ -121,7 +146,13 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
throw opError('local_conflict', 'The registered canonical root is missing.',
`Source ${source.id}'s registered root ${row.root} does not exist. Restore it (from its Git remote or backup), then run the migration again.`);
}
- row.inventory = inventorySkillpack(row.root);
+ if (prior?.parked && prior.root === row.root && sameLimits(prior.parked.limits, limits)) {
+ row.inventory = prior.inventory;
+ row.parked = prior.parked;
+ await pending('inventory', parkedReason(source.id, row.parked));
+ continue;
+ }
+ 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.`);
@@ -137,6 +168,12 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
}
}
} catch (error) {
+ if (error instanceof OperationError && error.code === 'payload_too_large' && error.detail) {
+ row.inventory = prior?.inventory ?? null;
+ row.parked = { limit: error.detail, limits, reason: error.message, parked_at: prior?.parked?.parked_at ?? new Date().toISOString() };
+ await pending('inventory', parkedReason(source.id, row.parked));
+ continue;
+ }
await pending('inventory', error instanceof OperationError ? error.message : 'The source pack cannot be inventoried safely; inspect its manifest and declared files.', true);
continue;
}
@@ -165,7 +202,7 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
if (!dryRun) {
try {
await installPackagedSharedSkills(ctx, source.id, ['README.md', 'LICENSE'].filter(path => existsSync(join(row.root!, path))));
- row.inventory = inventorySkillpack(row.root);
+ row.inventory = inventorySkillpack(row.root, limits);
} catch (error) {
await pending('projection', error instanceof OperationError ? `${error.code}: ${error.message}` : 'Pack initialization failed; inspect the canonical receipt before retrying.');
continue;
@@ -197,7 +234,7 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
`Inspect request ${open.request_id ?? 'receipts'} first; rerunning the migration resumes the same durable request (same request_id), never a second adoption.`);
}
}
- row.inventory = inventorySkillpack(row.root);
+ row.inventory = inventorySkillpack(row.root, limits);
} catch (error) {
await pending('projection', error instanceof OperationError ? `${error.code}: ${error.message}` : 'Catalog adoption failed; retry after inspecting the canonical publication receipt.');
continue;
@@ -220,7 +257,7 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
try {
checkedContentRoot(hostDir);
const entries = readdirSync(hostDir);
- complete = entries.length <= 256 && entries.every(name => !existsSync(join(hostDir, name, 'SKILL.md')) || declared.has(name));
+ complete = entries.length <= limits.max_files && entries.every(name => !existsSync(join(hostDir, name, 'SKILL.md')) || declared.has(name));
} catch { complete = false; }
}
if (!complete) report.pending_actions.push('Host-global catalog assignment is pending. Review a dedicated content pack root with skillpack.json (brain_resident:true) and declared skills; never register the application checkout. After approval, register it with `gbrain sources add shared-skills --path <reviewed-pack-root> --force --no-federated`. Inspect `gbrain sources writer status --json` before deliberate ownership changes; follow skills/migrations/v0.53.0.0.md for action-specific --admin-intent and reviewed --expected-state claim/activation steps. Quiescence is a separate prerequisite, not administration authority. Preview `gbrain apply-migrations --migration 0.53.0 --dry-run --json`, then apply with --yes only when those stages are approved. Original files and grants are unchanged; unmanifested or undeclared skills require explicit review.');
diff --git a/src/core/shared-skills/setup-files.ts b/src/core/shared-skills/setup-files.ts
index 740fe42492..0f8ec16b36 100644
--- a/src/core/shared-skills/setup-files.ts
+++ b/src/core/shared-skills/setup-files.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { opError, OperationError } from '../ops/contract.ts';
+import { DEFAULT_INVENTORY_LIMITS, inventoryLimitKey, type InventoryLimits } from './inventory-limits.ts';
export const setupHash = (content: string | Uint8Array): string => createHash('sha256').update(content).digest('hex');
@@ -29,7 +30,15 @@ export interface PackInventory {
excluded_from_install: string[];
}
-export function inventorySkillpack(root: string): PackInventory | null {
+/** The pack exceeds a configured inventory bound; `detail` names the config key. The migration parks the source instead of retrying. */
+function inventoryOverflow(root: string, limit: keyof InventoryLimits, value: number, what: string) {
+ const key = inventoryLimitKey(limit);
+ return opError('payload_too_large', `The skillpack in ${root} exceeds the migration inventory bound ${key}=${value}: ${what}.`,
+ `Raise ${key} with gbrain config set, opt the source out with gbrain sources shared-skills <source-id> off, or move large assets out of the declared skills and shared_deps; then run gbrain apply-migrations --migration 0.53.0 --yes.`,
+ { detail: key, docs: 'docs/guides/shared-brain-skills.md#oversized-skill-packs' });
+}
+
+export function inventorySkillpack(root: string, limits: InventoryLimits = DEFAULT_INVENTORY_LIMITS): PackInventory | null {
checkedContentRoot(root);
const manifestPath = join(root, 'skillpack.json');
if (!existsSync(manifestPath)) return null;
@@ -44,16 +53,15 @@ export function inventorySkillpack(root: string): PackInventory | null {
`${path} resolves outside ${root}. Replace the link with the real files inside the pack (or drop the entry from skillpack.json), then run the migration again.`);
}
const stat = lstatSync(absolute);
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 262144) {
- throw opError('local_conflict', 'A skillpack file is unsafe or exceeds the migration limit.',
- `${path} in ${root} must be a regular, singly linked file of at most 262144 bytes; shrink, split or remove it, then run the migration again.`);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) {
+ throw opError('local_conflict', 'A skillpack file is unsafe.',
+ `${path} in ${root} must be a regular, singly linked file; replace it with a real file or remove it, then run the migration again.`);
}
+ if (stat.size > limits.max_file_bytes) throw inventoryOverflow(root, 'max_file_bytes', limits.max_file_bytes, `${path} is ${stat.size} bytes`);
+ if (Object.keys(hashes).length >= limits.max_files) throw inventoryOverflow(root, 'max_files', limits.max_files, `it declares more than ${limits.max_files} files`);
const data = readFileSync(absolute);
bytes += data.length;
- if (Object.keys(hashes).length >= 256 || bytes > 4 * 1024 * 1024) {
- throw opError('local_conflict', 'The skillpack exceeds the bounded migration inventory.',
- `The pack in ${root} holds more than 255 files or 4 MiB; move large assets out of the declared skills and shared_deps, then run the migration again.`);
- }
+ if (bytes > limits.max_total_bytes) throw inventoryOverflow(root, 'max_total_bytes', limits.max_total_bytes, `its declared files exceed ${limits.max_total_bytes} bytes`);
hashes[path] = setupHash(data);
return data.toString('utf8');
};
@@ -74,10 +82,11 @@ export function inventorySkillpack(root: string): PackInventory | null {
`List each skill once in "skills" of ${manifestPath}, then run the migration again.`);
}
const visit = (path: string, depth: number): void => {
- if (++entries > 1024 || depth > 8 || path.includes('\\') || path.split('/').some(part => !part || part === '.' || part === '..') || isAbsolute(path)) {
+ if (depth > 8 || path.includes('\\') || path.split('/').some(part => !part || part === '.' || part === '..') || isAbsolute(path)) {
throw opError('local_conflict', 'The skillpack contains an unsafe dependency path.',
- `Declared skill and shared_deps paths in ${manifestPath} must be relative forward-slash paths without empty, . or .. segments, at most 8 directories deep and 1024 entries in total; fix the manifest, then run the migration again.`);
+ `Declared skill and shared_deps paths in ${manifestPath} must be relative forward-slash paths without empty, . or .. segments and at most 8 directories deep; fix the manifest, then run the migration again.`);
}
+ if (++entries > limits.max_entries) throw inventoryOverflow(root, 'max_entries', limits.max_entries, `its declared paths hold more than ${limits.max_entries} entries`);
const stat = lstatSync(join(root, path));
if (stat.isSymbolicLink()) {
throw opError('local_conflict', 'Skillpack migration does not follow symlinks.',