Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(shared-skills): canonical skills without tools inherit brain tools; refuse an empty SKILL.md (#5150, A-NEW-5)
time-attack9cc874d1b798
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.mdindex ef38de6bea..eaa12e39d8 100644--- a/docs/architecture/key-files/shared-skills.md+++ b/docs/architecture/key-files/shared-skills.md@@ -1,11 +1,11 @@# Shared brain skills-- `src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts` defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned.+- `src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts` defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned. `skillMetadata` refuses an empty or whitespace-only SKILL.md (A-NEW-5) and records `tools_declared` (#5150): a canonical skill published without `tools` inherits the caller's `sharedSkillToolAccess` as `usable_tools` in v2 list/detail and the v1 compatibility projection (which now reuses the catalog's computed lists), `tools: []` permits none, and revisions published before the flag re-read their SKILL.md on detail (`skillToolsDeclared`) while the list fails closed. `SHARED_SKILL_LIMITS.packFiles` (128, equal to the persistence `BUNDLE_FILE_LIMITS.files`) bounds one canonical publication; `files` (64) bounds one skill (#5476).- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths. A relative or host-only `file://` alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with `invalid_source_uri` (not `skill_bundle_required`).- `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. `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.+- `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/{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/docs/wave9/sg.md b/docs/wave9/sg.mdindex f38ce27145..2ae2bb6c64 100644--- a/docs/wave9/sg.md+++ b/docs/wave9/sg.md@@ -8,6 +8,8 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md- **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.+- **Portable canonical skills list their usable tools (#5150).** A shared skill published without `tools:` now inherits the caller's available brain tools as `usable_tools` (list, detail, and the v1 compatibility catalog), matching host-repository skills; `tools: []` still permits none. Revisions published before this release re-read their SKILL.md on `get_skill`; `list_skills` keeps them empty until republished.+- **`put_skill` refuses an empty SKILL.md (A-NEW-5).** An empty or whitespace-only entry point is `invalid_params` instead of publishing a blank skill.## Upgrade-note rows@@ -17,3 +19,5 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md| 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 |+| Canonical skills without `tools:` inherit brain tools (#5150) | Clients reading `usable_tools` for shared skills | `gbrain call get_skill '{"name":"<skill>"}'` | Declare `tools:` in the skill to narrow it |+| Empty SKILL.md refused (A-NEW-5) | Editors publishing placeholder skills | none | Write a non-empty SKILL.md |diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 5f246d9356..e5d0c5fba0 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -167,7 +167,7 @@ export const SKILL_CATALOG_INSTRUCTIONS = {"are not callable by you on this server.","For host-repository skills, declared `tools` narrow the usable tools. Valid " +"frontmatter without `tools` inherits your available brain tools; `tools: []` permits none. " +- "Canonical shared skills use their approved requirements instead.",+ "Canonical shared skills follow the same rule; their other requirements gate `usable`.",],} as const;@@ -185,7 +185,7 @@ export const SKILL_CLIENT_GUIDANCE = {"Do not invent tools — only the tools in `usable_tools` are callable by you.","For host-repository skills, declared `tools` narrow this list. Valid frontmatter " +"without `tools` inherits your available brain tools; `tools: []` permits none. " +- "Canonical shared skills use their approved requirements instead.",+ "Canonical shared skills follow the same rule; their other requirements gate `usable`.","If `mutating` is true, this skill writes to the brain; confirm before doing so " +"if the user hasn't clearly asked for a write.",],diff --git a/src/core/shared-skills/catalog.ts b/src/core/shared-skills/catalog.tsindex 46dd323c77..2e0807068f 100644--- a/src/core/shared-skills/catalog.ts+++ b/src/core/shared-skills/catalog.ts@@ -5,7 +5,7 @@ import { catalogFix, skillHeadFix } from './fixes.ts';import { sourceScopeOpts } from '../ops/context.ts';import { stableJson } from '../persistence/digest.ts';import { approvedFiles, authorizeSkillRead, legacySharedSkillPolicy, normalizePolicy, publicationEnabled, readSharedSkillPolicy, skillPrincipal } from './policy.ts';-import { skillName, skillPath } from './manifest.ts';+import { skillName, skillPath, skillToolsDeclared } from './manifest.ts';import { SHARED_SKILL_LIMITS, type SharedSkillDetail, type SharedSkillKey, type SharedSkillList, type SharedSkillSelector,type SharedSkillSummary, type SharedSkillPolicy, type StoredSkillRevision } from './model.ts';@@ -80,7 +80,8 @@ async function readSnapshot(ctx: OperationContext, selector: SharedSkillSelectorif (!policy.policy.enabled || ctx.remote !== false && row.metadata.private ||!row.metadata.audience.some(a => (a === 'readers' || a === principal) && policy!.policy.audiences.includes(a))) continue;const skillKey = { brain_id: brain.brain_id, source_id: row.source_id, source_incarnation: row.source_incarnation, pack_id: row.pack_id, name: row.name };- const { file_policy, ...metadata } = row.metadata;+ const { file_policy, tools_declared: _toolsDeclared, ...metadata } = row.metadata;+ const inherits = !skillToolsDeclared(row.metadata, null);const complete = file_policy.every(f => policy!.policy.classes.includes(f.file_class) && f.audience.some(a => (a === 'readers' || a === principal) && policy!.policy.audiences.includes(a)));const tools = metadata.requirements.filter(r => r.startsWith('tool:')).map(r => r.slice(5));const unavailable = metadata.requirements.filter(r => !r.startsWith('tool:') || !availableTools.has(r.slice(5)) ||@@ -88,7 +89,7 @@ async function readSnapshot(ctx: OperationContext, selector: SharedSkillSelectorskills.push({ ...skillKey, ...metadata, audience: metadata.audience.filter(a => a === 'readers' || a === principal), qualified_id: qualifiedSkillId(skillKey), revision: row.revision,policy_epoch: policy.epoch, allow_follow: policy.policy.allow_follow,delivery: complete ? 'complete' : 'prose_only', usable: complete && unavailable.length === 0,- usable_tools: tools.filter(t => availableTools.has(t)), unavailable_tools: tools.filter(t => !availableTools.has(t)), unavailable_requirements: unavailable });+ usable_tools: inherits ? [...availableTools] : tools.filter(t => availableTools.has(t)), unavailable_tools: inherits ? [] : tools.filter(t => !availableTools.has(t)), unavailable_requirements: unavailable });}const auth = opaque(brain.token_secret, { principal, sources: sourceIds, scopes: ctx.auth?.scopes,operations: ctx.auth?.allowedOperations, surface: ctx.auth?.effectiveSurface, grant_revision: ctx.auth?.grantRevision, serving_epoch: brain.serving_epoch });@@ -174,15 +175,18 @@ async function detail(active: OperationContext, params: SharedSkillSelector) {}const visible = new Set(files.map(f => f.path));const complete = files.length === row.files.length && files.every(f => f.depends_on.every(d => visible.has(d)));- const { file_policy: _filePolicy, ...metadata } = row.metadata;+ const { file_policy: _filePolicy, tools_declared: _toolsDeclared, ...metadata } = row.metadata;const { sharedSkillToolAccess } = await import('./tool-access.ts');- const tools = new Set(await sharedSkillToolAccess(active));+ const access = await sharedSkillToolAccess(active);+ const tools = new Set(access);+ const body = Buffer.from(main.content, 'base64').toString('utf8');+ const inherits = !skillToolsDeclared(row.metadata, body);const declaredTools = metadata.requirements.filter(r => r.startsWith('tool:')).map(r => r.slice(5));const unavailable = metadata.requirements.filter(r => !r.startsWith('tool:') || !tools.has(r.slice(5)) ||!['legacy-prose', 'consent-required'].includes(epoch) && !policy.requirements.includes(r));const result: SharedSkillDetail = { ...selected, ...metadata, audience: metadata.audience.filter(a => a === 'readers' || a === snapshot.principal), revision: row.revision, schema_version: 2,- delivery: complete ? 'complete' : 'prose_only', body: Buffer.from(main.content, 'base64').toString('utf8'),- usable_tools: declaredTools.filter(t => tools.has(t)), unavailable_tools: declaredTools.filter(t => !tools.has(t)),+ delivery: complete ? 'complete' : 'prose_only', body,+ usable_tools: inherits ? access : declaredTools.filter(t => tools.has(t)), unavailable_tools: inherits ? [] : declaredTools.filter(t => !tools.has(t)),unavailable_requirements: unavailable, usable: complete && unavailable.length === 0,files: files.map(({ content: _content, ...file }) => ({ ...file, audience: file.audience.filter(a => a === 'readers' || a === snapshot.principal), depends_on: file.depends_on.filter(d => visible.has(d)) })) };return { result, files };diff --git a/src/core/shared-skills/compatibility.ts b/src/core/shared-skills/compatibility.tsindex c1db8d9e4c..5bc1a0c537 100644--- a/src/core/shared-skills/compatibility.ts+++ b/src/core/shared-skills/compatibility.ts@@ -25,7 +25,7 @@ export async function listLegacySharedSkills(ctx: OperationContext, section?: stconst skills = (await allSkills(ctx)).filter(() => !section || section === 'Published skills').map(skill => {const tools = skill.requirements.filter(r => r.startsWith('tool:')).map(r => r.slice(5));return { name: skill.name, description: skill.description, section: 'Published skills', triggers: skill.triggers, tools,- usable_tools: tools.filter(t => access.includes(t)), unavailable_tools: tools.filter(t => !access.includes(t)), writes_pages: skill.writes_pages, mutating: skill.mutating };+ usable_tools: skill.usable_tools, unavailable_tools: skill.unavailable_tools, writes_pages: skill.writes_pages, mutating: skill.mutating };});return { schema_version: 1, skills_dir_source: 'config', count: skills.length, skills,instructions: { summary: SKILL_CATALOG_INSTRUCTIONS.summary, how_to_use: [...SKILL_CATALOG_INSTRUCTIONS.how_to_use], available_brain_tools: access, fetch_op: 'get_skill' } };@@ -42,7 +42,7 @@ export async function getLegacySharedSkill(ctx: OperationContext, name: unknown,const access = await sharedSkillToolAccess(ctx);return { schema_version: 1, name: skill.name, frontmatter: { name: skill.name, description: skill.description, triggers: skill.triggers,tools, writes_pages: fm?.writes_pages ?? false, mutating: fm?.mutating ?? false }, body: skill.body,- usable_tools: tools.filter(t => access.includes(t)), unavailable_tools: tools.filter(t => !access.includes(t)),+ usable_tools: skill.usable_tools, unavailable_tools: skill.unavailable_tools,client_guidance: { nature: SKILL_CLIENT_GUIDANCE.nature, protocol: [...SKILL_CLIENT_GUIDANCE.protocol], available_brain_tools: access, mutating: fm?.mutating ?? false } };}export async function listLegacySharedPacks(ctx: OperationContext): Promise<ResidentPackResult> {diff --git a/src/core/shared-skills/manifest.ts b/src/core/shared-skills/manifest.tsindex d3a990a027..05629eb323 100644--- a/src/core/shared-skills/manifest.ts+++ b/src/core/shared-skills/manifest.ts@@ -127,6 +127,22 @@ export function normalizeSkillFiles(name: string, input: unknown): StoredSkillFi}return files;}+/**+ * #5150: whether a stored skill declared its tools. Revisions published before+ * `tools_declared` was recorded are re-read from their SKILL.md; unreadable+ * frontmatter counts as declared, so the reader fails closed.+ */+export function skillToolsDeclared(metadata: Pick<SkillMetadata, 'tools_declared' | 'requirements'>, body: string | null): boolean {+ if (metadata.tools_declared !== undefined) return metadata.tools_declared;+ if (body === null || metadata.requirements.some(requirement => requirement.startsWith('tool:'))) return true;+ const normalized = body.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');+ if (!/^---[ \t]*\n/.test(normalized)) return false;+ const match = normalized.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n|$)/);+ try {+ const parsed: unknown = match ? safeLoad(match[1], { schema: FAILSAFE_SCHEMA }) : undefined;+ return !(parsed && typeof parsed === 'object' && !Array.isArray(parsed)) || Object.hasOwn(parsed, 'tools');+ } catch { return true; }+}export function skillMetadata(name: string, files: StoredSkillFile[], params: Record<string, unknown>): SkillMetadata {const body = Buffer.from(files.find(f => f.path === `skills/${name}/SKILL.md`)!.content, 'base64').toString('utf8');const normalized = body.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');@@ -154,6 +170,10 @@ export function skillMetadata(name: string, files: StoredSkillFile[], params: Rethrow opError('invalid_params', 'Frontmatter name must match the skill key.',`Set name: ${name} in skills/${name}/SKILL.md's frontmatter (or remove the name key), then resubmit.`);}+ if (!normalized.trim()) {+ throw opError('invalid_params', 'SKILL.md is empty.',+ `Write skills/${name}/SKILL.md with frontmatter (name, description) and the instructions, then resubmit.`);+ }const description = params.description ?? (typeof fm.description === 'string' ? fm.description.replace(/\s+/g, ' ').trim() : fm.description) ?? '';if (typeof description !== 'string' || description.length > 2048 || /[\x00-\x1f\x7f]/.test(description)) {throw opError('invalid_params', 'Invalid skill description.',@@ -172,8 +192,9 @@ export function skillMetadata(name: string, files: StoredSkillFile[], params: Re}markers.set(canonical, ['true', 'yes'].includes(value.toLowerCase()));}- return { description, triggers: stringList(params.triggers ?? fm.triggers, 'triggers'),- requirements: stringList([...stringList(params.requirements, 'requirements'), ...stringList(fm.requires, 'requires'), ...stringList(fm.tools, 'tools').map(t => `tool:${t}`)], 'requirements'),+ const requirements = stringList([...stringList(params.requirements, 'requirements'), ...stringList(fm.requires, 'requires'), ...stringList(fm.tools, 'tools').map(t => `tool:${t}`)], 'requirements');+ return { description, triggers: stringList(params.triggers ?? fm.triggers, 'triggers'), requirements,+ tools_declared: Object.hasOwn(fm, 'tools') || requirements.some(requirement => requirement.startsWith('tool:')),private: params.private === true || markers.get('private') === true || markers.get('publish') === false || markers.get('mcp_publish') === false,audience: files.find(f => f.path === `skills/${name}/SKILL.md`)!.audience,writes_pages: markers.get('writes_pages') ?? false, mutating: markers.get('mutating') ?? false,diff --git a/src/core/shared-skills/model.ts b/src/core/shared-skills/model.tsindex f1e8f2a1ce..46b152099a 100644--- a/src/core/shared-skills/model.ts+++ b/src/core/shared-skills/model.ts@@ -55,8 +55,10 @@ export interface SkillMetadata {writes_pages: boolean;mutating: boolean;file_policy: Array<Pick<SharedSkillFile, 'file_class' | 'audience'>>;+ /** #5150: false when the SKILL.md declared no `tools`, so readers inherit the caller's brain tools; absent on revisions published before it was recorded. */+ tools_declared?: boolean;}-export interface SharedSkillSummary extends SharedSkillKey, Omit<SkillMetadata, 'file_policy'> {+export interface SharedSkillSummary extends SharedSkillKey, Omit<SkillMetadata, 'file_policy' | 'tools_declared'> {qualified_id: string;revision: string;policy_epoch: string;diff --git a/test/shared-skills-tools-5150.test.ts b/test/shared-skills-tools-5150.test.tsnew file mode 100644index 0000000000..e64824c8b1--- /dev/null+++ b/test/shared-skills-tools-5150.test.ts@@ -0,0 +1,77 @@+/**+ * #5150 residual: a canonical shared skill published without `tools:` inherits+ * the caller's available brain tools, like a host-repository skill; `tools: []`+ * still permits none. A-NEW-5: an empty or whitespace-only SKILL.md is refused+ * at publication instead of listing as a blank skill.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } 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 { submitSharedSkillMutation } from '../src/core/shared-skills/publication.ts';+import { getSharedSkill, listSharedSkills } from '../src/core/shared-skills/catalog.ts';+import { getLegacySharedSkill, listLegacySharedSkills } from '../src/core/shared-skills/compatibility.ts';+import { sharedSkillToolAccess } from '../src/core/shared-skills/tool-access.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';++async function fixture(run: (local: OperationContext) => Promise<void>) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-skill-tools-'));+ 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() {} } });+ } finally { await disposePersistenceConsumer(engine); await isolated.close(); }+ });+ rmSync(dir, { recursive: true, force: true });+}+async function put(ctx: OperationContext, name: string, body: string) {+ const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', ['default']);+ return submitSharedSkillMutation(ctx, 'put_skill', { request_id: randomUUID(), expected_revision: null, source_id: 'default',+ source_incarnation: source.incarnation, pack_id: 'example-pack', name, files: [{ path: `skills/${name}/SKILL.md`, content: body, file_class: 'prose' }] });+}++test('a canonical skill without tools inherits the available brain tools; tools: [] permits none; declared tools narrow (#5150)', () => fixture(async local => {+ await put(local, 'notools', '---\nname: notools\ndescription: Portable fixture skill\n---\n\nUse search.\n');+ await put(local, 'emptytools', '---\nname: emptytools\ndescription: Locked fixture skill\ntools: []\n---\n\nNo tools.\n');+ await put(local, 'onetool', '---\nname: onetool\ndescription: Narrow fixture skill\ntools: [search]\n---\n\nUse search.\n');+ const available = await sharedSkillToolAccess(local);+ expect(available).toContain('search');+ const listed = new Map((await listSharedSkills(local, { limit: 100 })).skills.map(skill => [skill.name, skill]));+ expect(listed.get('notools')!.usable_tools).toEqual(available);+ expect(listed.get('emptytools')!.usable_tools).toEqual([]);+ expect(listed.get('onetool')!.usable_tools).toEqual(['search']);+ expect((await getSharedSkill(local, { name: 'notools' })).usable_tools).toEqual(available);+ expect((await getSharedSkill(local, { name: 'emptytools' })).usable_tools).toEqual([]);+ const legacy = new Map((await listLegacySharedSkills(local)).skills.map(skill => [skill.name, skill]));+ expect(legacy.get('notools')!.usable_tools).toEqual(available);+ expect(legacy.get('emptytools')!.usable_tools).toEqual([]);+ expect(((await getLegacySharedSkill(local, 'notools')) as { usable_tools: string[] }).usable_tools).toEqual(available);+}), 120_000);++test('an empty or whitespace-only SKILL.md is refused at publication (A-NEW-5)', () => fixture(async local => {+ await expect(put(local, 'blank', '')).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(put(local, 'spaces', ' \n\t\n')).rejects.toMatchObject({ code: 'invalid_params' });+ expect((await listSharedSkills(local, { limit: 100 })).skills.map(skill => skill.name)).toEqual([]);+}), 120_000);++test('revisions published before tools_declared re-read their SKILL.md; unreadable frontmatter fails closed (#5150)', async () => {+ const { skillToolsDeclared } = await import('../src/core/shared-skills/manifest.ts');+ expect(skillToolsDeclared({ requirements: [] }, '---\nname: a\ndescription: x\n---\nBody\n')).toBe(false);+ expect(skillToolsDeclared({ requirements: [] }, '---\nname: a\ntools: []\n---\nBody\n')).toBe(true);+ expect(skillToolsDeclared({ requirements: ['tool:search'] }, '---\nname: a\n---\nBody\n')).toBe(true);+ expect(skillToolsDeclared({ requirements: [] }, '---\nname: [unclosed\n---\nBody\n')).toBe(true);+ expect(skillToolsDeclared({ requirements: [] }, null)).toBe(true);+ expect(skillToolsDeclared({ requirements: [], tools_declared: false }, null)).toBe(false);+});