Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
26.3 KB
Raw Blame
/**
 * skill-catalog.ts — host-repo skill catalog for the MCP `list_skills` /
 * `get_skill` ops (PR1).
 *
 * WHAT THIS IS: the agent repo (OpenClaw/Hermes) ships fat-markdown "skills" —
 * prose instruction sets, NOT executable code. This module reads them off the
 * server host's filesystem and shapes them for a thin MCP client (Codex desktop,
 * Claude Code, Perplexity) to discover and FOLLOW. "Using" a skill = fetching its
 * prose and then calling the gbrain MCP tools the same server already exposes.
 *
 * TRUST-BOUNDARY MEMO (read before changing scope/localOnly on the ops):
 * These ops read the server-host filesystem and return file CONTENTS over HTTP.
 * gbrain treats `file_list`/`file_url` as `admin + localOnly` for exactly this
 * reason. `read` + non-localOnly is defensible HERE, but ONLY because of the full
 * mitigation stack — do not weaken one piece without re-reading the rest:
 *   1. Explicit owner opt-in — the publish gate (`mcp.publish_skills`) defaults
 *      OFF at runtime; new installs turn it on at `gbrain init`, existing installs
 *      via a consenting migration. Unlike `file_list`, this is content the owner
 *      deliberately published.
 *   2. Confinement — only the resolved skills dir is reachable. The client `name`
 *      is a manifest LOOKUP KEY, never a raw path segment; the manifest-derived
 *      path is realpath + relative-contained on every call (defeats symlink/`..`
 *      escape, including a poisoned manifest.json `path`); resolved path must be a
 *      regular file named `SKILL.md`.
 *   3. Field allowlist — frontmatter is projected to a safe subset; `writes_to`
 *      (private brain taxonomy) and `sources` (absolute paths) are dropped.
 *   4. Prose-only + size-capped — no source code (PR2 ships tarballs); `get_skill`
 *      caps the file size so a huge/binary file can't OOM the server.
 *   5. No install_path serve for remote — a hosted gbrain with no agent repo
 *      returns `storage_error`, never gbrain's own bundled dev skills.
 *   6. Bounded — the MCP rate limiter caps call rate; per-call memory is bounded
 *      by the size cap.
 *
 * Skills live on the HOST FILESYSTEM and are repo-global: `sourceScopeOpts(ctx)` /
 * `ctx.sourceId` (in-DB tenancy) and `ctx.brainId` (mounts) deliberately do NOT
 * apply. One server host = one skills dir = one catalog for all callers.
 */

import { existsSync, readFileSync, realpathSync, statSync } from 'fs';
import { basename, join, relative, resolve } from 'path';
import { FAILSAFE_SCHEMA } from 'js-yaml';
import { loadBoundedYaml as load } from './data-frontmatter.ts';
import {
  autoDetectSkillsDir,
  autoDetectSkillsDirReadOnly,
  AUTO_DETECT_HINT,
  AUTO_DETECT_HINT_READ_ONLY,
  type SkillsDirSource,
} from './repo-root.ts';
import { loadOrDeriveManifest, type ManifestEntry } from './skill-manifest.ts';
import { relativeEscapesRoot } from './path-confine.ts';
import { loadSkillTriggerIndex, FRONTMATTER_SECTION } from './skill-trigger-index.ts';
import { parseSkillFrontmatter } from './skill-frontmatter.ts';
import { oneLineDescription } from './skill-description.ts';
import { splitWords } from './skills/resolver/tokenize.ts';
import { operationScopesAllowed } from './scope.ts';
import { currentVerifiedLocalWriter } from './persistence/identity.ts';
import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';
import { filterOpsForSurface } from '../mcp/surface.ts';
import { operations, OperationError, opAllowedForBoundClient, type Operation, type OperationContext } from './operations.ts';
import {
  SKILL_CATALOG_INSTRUCTIONS,
  SKILL_CLIENT_GUIDANCE,
} from './operations-descriptions.ts';

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/** Max SKILL.md size `get_skill` will read/return. Env-overridable. Default
 *  256 KB — generous for prose, small enough that a stray binary/generated file
 *  can't balloon the server's RSS (codex P1-c). */
export const MAX_SKILL_MD_BYTES = (() => {
  const raw = process.env.GBRAIN_MAX_SKILL_MD_BYTES;
  if (raw) {
    const n = parseInt(raw, 10);
    if (Number.isFinite(n) && n > 0) return n;
  }
  return 256 * 1024;
})();

/** Max client-supplied skill name length before we even hit the manifest. */
const MAX_SKILL_NAME_LEN = 128;

/** Where auto-detect found the dir, plus the explicit-config variant. */
export type ResolvedSkillsDirSource = SkillsDirSource | 'config';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface SkillCatalogEntry {
  name: string;
  description: string;
  section: string;
  triggers: string[];
  tools: string[];
  /** declared tools ∩ (exposed by this server AND permitted to this caller). */
  usable_tools: string[];
  /** declared tools − usable (not on this server, or beyond caller scope). */
  unavailable_tools: string[];
  writes_pages: boolean;
  mutating: boolean;
  /** #6471: present only when the call carried `query`; see `scoreSkillMatch`. */
  match?: SkillMatch;
}

/** #6471: lexical relevance of a skill to a task. `matched_on` names the strongest contributor. */
export interface SkillMatch {
  score: number;
  matched_on: 'trigger' | 'name' | 'description';
}

export interface ListSkillsResult {
  schema_version: 1;
  skills_dir_source: ResolvedSkillsDirSource;
  count: number;
  skills: SkillCatalogEntry[];
  instructions: {
    summary: string;
    how_to_use: string[];
    available_brain_tools: string[];
    fetch_op: 'get_skill';
  };
}

export interface GetSkillResult {
  schema_version: 1;
  name: string;
  /** Allowlisted projection — never the raw frontmatter object. */
  frontmatter: {
    name?: string;
    description?: string;
    triggers?: string[];
    tools?: string[];
    writes_pages?: boolean;
    mutating?: boolean;
  };
  body: string;
  usable_tools: string[];
  unavailable_tools: string[];
  client_guidance: {
    nature: string;
    protocol: string[];
    available_brain_tools: string[];
    mutating: boolean;
  };
}

// ---------------------------------------------------------------------------
// Skills-dir resolution
// ---------------------------------------------------------------------------

/**
 * Read `mcp.publish_skills` honoring BOTH config planes. `gbrain config set`
 * writes the DB plane (engine.setConfig) — so the DB value wins; `gbrain init`
 * also writes the DB plane. The file plane (`config.json` → `ctx.config.mcp`) is
 * a fallback for hand-edited configs. Absent in both → false (fail-safe).
 */
export async function readMcpPublishSkills(ctx: OperationContext): Promise<boolean> {
  let dbVal: string | null = null;
  try {
    dbVal = await ctx.engine.getConfig('mcp.publish_skills');
  } catch {
    // Engine without a config table / transient error → fall back to file plane.
  }
  if (dbVal != null) return dbVal === 'true';
  return ctx.config?.mcp?.publish_skills === true;
}

/**
 * Read `mcp.skills_dir` from the DB plane (what `gbrain config set` writes),
 * falling back to the file plane. Returns undefined when unset on both.
 */
export async function readMcpSkillsDir(ctx: OperationContext): Promise<string | undefined> {
  let dbVal: string | null = null;
  try {
    dbVal = await ctx.engine.getConfig('mcp.skills_dir');
  } catch {
    // ignore — fall through to file plane
  }
  if (dbVal && dbVal.trim().length > 0) return dbVal;
  const fileVal = ctx.config?.mcp?.skills_dir;
  return fileVal && fileVal.trim().length > 0 ? fileVal : undefined;
}

/**
 * Resolve the skills dir for this call. An explicit `mcp.skills_dir` override
 * (resolved from either config plane by the caller) wins; otherwise autodetect.
 * REMOTE callers use `autoDetectSkillsDir` (no install_path tier — a hosted
 * gbrain must never serve its own bundled dev skills); LOCAL callers
 * (`ctx.remote === false`) use the read-only variant with the install_path
 * fallback. Throws `storage_error` (with the search-path hint) when nothing
 * resolves. Pure modulo filesystem state — `skillsDirOverride` keeps it testable
 * without an engine.
 */
export function resolveSkillsDir(
  ctx: OperationContext,
  skillsDirOverride?: string,
): {
  dir: string;
  source: ResolvedSkillsDirSource;
} {
  if (skillsDirOverride && skillsDirOverride.trim().length > 0) {
    if (!existsSync(skillsDirOverride)) {
      throw new OperationError(
        'storage_error',
        `Configured mcp.skills_dir does not exist: ${skillsDirOverride}`,
        'Fix it with `gbrain config set mcp.skills_dir <path>` or unset it to autodetect.',
      );
    }
    return { dir: skillsDirOverride, source: 'config' };
  }

  const det =
    ctx.remote === false ? autoDetectSkillsDirReadOnly() : autoDetectSkillsDir();
  if (!det.dir || !det.source) {
    const hint = ctx.remote === false ? AUTO_DETECT_HINT_READ_ONLY : AUTO_DETECT_HINT;
    throw new OperationError(
      'storage_error',
      'No skills directory found on the server host.',
      `Set it explicitly: \`gbrain config set mcp.skills_dir <path>\` (or $GBRAIN_SKILLS_DIR). Search order:\n${hint}`,
    );
  }
  return { dir: det.dir, source: det.source };
}

// ---------------------------------------------------------------------------
// Path confinement (the security boundary)
// ---------------------------------------------------------------------------

const SKILL_NAME_HINT = `Pass name exactly as list_skills returned it: a lookup key of at most ${MAX_SKILL_NAME_LEN} characters with no slashes, spaces or "..", never a path.`;

/** Validate the client-supplied skill name BEFORE any filesystem access. */
function assertSkillNameShape(name: unknown): asserts name is string {
  if (typeof name !== 'string' || name.length === 0) {
    throw new OperationError('invalid_params', 'skill name must be a non-empty string', SKILL_NAME_HINT);
  }
  if (name.length > MAX_SKILL_NAME_LEN) {
    throw new OperationError('invalid_params', `skill name exceeds ${MAX_SKILL_NAME_LEN} characters`, SKILL_NAME_HINT);
  }
  // No path separators, no traversal, no null byte. The name is a manifest
  // LOOKUP KEY — it must never look like a path component.
  if (/[/\\]|\.\.|/.test(name)) {
    throw new OperationError('invalid_params', `Invalid skill name: ${name}`, SKILL_NAME_HINT);
  }
}

/**
 * Resolve `name` → the absolute, confined `SKILL.md` path. The name is resolved
 * THROUGH the vetted manifest (never used as a raw path segment); the
 * manifest-derived path is realpath + relative-contained on every call; the
 * resolved target must be a regular file named `SKILL.md`. Throws on any miss.
 */
export function resolveSkillMdPath(skillsDir: string, name: string): string {
  assertSkillNameShape(name);
  const { skills } = loadOrDeriveManifest(skillsDir);
  const entry = skills.find(s => s.name === name);
  if (!entry) {
    throw new OperationError(
      'page_not_found',
      `Skill not found: ${name}`,
      'Call list_skills to see available skills.',
    );
  }
  return confineManifestPath(skillsDir, entry);
}

/**
 * Realpath + containment + file-type check for a manifest entry's `path`. Used
 * by both `get_skill` (one entry) and `list_skills` (every entry — manifest.json
 * `path` is taken verbatim, so a poisoned entry must not escape). Throws on
 * escape / missing / non-`SKILL.md` / non-regular-file.
 */
export function confineManifestPath(skillsDir: string, entry: ManifestEntry): string {
  let realRoot: string;
  let realCandidate: string;
  try {
    realRoot = realpathSync(skillsDir);
  } catch {
    throw new OperationError('storage_error', `Cannot resolve skills dir: ${skillsDir}`,
      'The skills directory on the brain host is missing or unreadable. The host\'s operator checks mcp.skills_dir (gbrain config get mcp.skills_dir) or unsets it so gbrain autodetects the directory.');
  }
  const candidate = join(realRoot, entry.path);
  try {
    realCandidate = realpathSync(candidate);
  } catch {
    throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`, `The skills manifest lists ${entry.name} but its SKILL.md is missing on the brain host. Call list_skills for the skills that are available; the host's operator restores the file or regenerates the manifest.`);
  }
  const rel = relative(realRoot, realCandidate);
  if (relativeEscapesRoot(rel) || resolve(realRoot, rel) !== realCandidate) { // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rel comes from relative() of two realpaths; resolve only re-joins it to confirm containment, no file is opened here
    throw new OperationError('invalid_params', `Skill path escapes skills dir: ${entry.name}`,
      `The manifest entry for ${entry.name} points outside the skills directory, so it is refused. Pick another skill from list_skills; the brain host's operator fixes the manifest.`);
  }
  let st;
  try {
    st = statSync(realCandidate);
  } catch {
    throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`, `The skills manifest lists ${entry.name} but its SKILL.md is missing on the brain host. Call list_skills for the skills that are available; the host's operator restores the file or regenerates the manifest.`);
  }
  if (!st.isFile() || basename(realCandidate) !== 'SKILL.md') {
    throw new OperationError(
      'invalid_params',
      `Skill target is not a SKILL.md regular file: ${entry.name}`,
      `The manifest entry for ${entry.name} does not point at a regular SKILL.md file, so it is refused. Pick another skill from list_skills; the brain host's operator fixes the manifest.`,
    );
  }
  return realCandidate;
}

// ---------------------------------------------------------------------------
// Tool honesty (D7)
// ---------------------------------------------------------------------------

/** Can THIS caller call THIS op on THIS server? Local owns everything. */
function opCallableByCaller(op: Operation, ctx: OperationContext, gateDisabled?: ReadonlySet<string>): boolean {
  if (ctx.remote === false) return true; // local CLI — OS is the trust boundary
  if (op.localOnly) return false; // not reachable over a remote transport
  if (!opAllowedForBoundClient(ctx.auth, op)) return false;
  if (filterOpsForSurface([op], ctx.auth?.effectiveSurface ?? ctx.surfaceCeiling ?? 'full').length === 0) return false;
  if (op.publishGateKey && (!gateDisabled || gateDisabled.has(op.name))) return false;
  if (ctx.transport === 'stdio') {
    const writer = currentVerifiedLocalWriter();
    if (!ctx.auth && writer?.remote && !opAllowedForBoundClient({
      allowedOperations: writer.grant.operations ?? undefined,
      boundSlugPrefixes: writer.grant.slugPrefixes ?? undefined,
    }, op)) return false;
    const scopes = ctx.auth?.scopes ?? (writer?.remote ? writer.grant.scopes : undefined);
    return scopes ? operationScopesAllowed(scopes, op) : !op.requiredScopes?.length;
  }
  return operationScopesAllowed(ctx.auth?.scopes ?? [], op);
}

/**
 * Split a skill's declared `tools:` into what the caller can vs cannot actually
 * use, cross-referenced against this server's op set AND the caller's scope.
 * A declared tool not in the op set is unavailable (not on this server).
 */
export function crossReferenceTools(
  declared: string[],
  ctx: OperationContext,
  gateDisabled?: ReadonlySet<string>,
): { usable_tools: string[]; unavailable_tools: string[] } {
  const usable: string[] = [];
  const unavailable: string[] = [];
  for (const tool of declared) {
    const op = operations.find(o => o.name === tool);
    if (op && opCallableByCaller(op, ctx, gateDisabled)) usable.push(tool);
    else unavailable.push(tool);
  }
  return { usable_tools: usable, unavailable_tools: unavailable };
}

/** Every server tool this caller can call — the envelope's "what you can use". */
function availableBrainTools(ctx: OperationContext, gateDisabled?: ReadonlySet<string>): string[] {
  return operations.filter(op => opCallableByCaller(op, ctx, gateDisabled)).map(op => op.name).sort();
}

export async function readSkillToolGates(ctx: OperationContext): Promise<ReadonlySet<string> | undefined> {
  return ctx.remote === false ? undefined : disabledOpsForPublishGates(ctx.engine, ctx.config);
}

function resolveSkillTools(
  parsed: ReturnType<typeof parseSkillFrontmatter>,
  ctx: OperationContext,
  gateDisabled?: ReadonlySet<string>,
): { usable_tools: string[]; unavailable_tools: string[] } {
  if (parsed?.tools !== undefined) return crossReferenceTools(parsed.tools, ctx, gateDisabled);
  if (parsed) {
    try {
      const data = load(parsed.raw, { schema: FAILSAFE_SCHEMA });
      if (data && typeof data === 'object' && !Array.isArray(data) && !Object.hasOwn(data, 'tools')) {
        return { usable_tools: availableBrainTools(ctx, gateDisabled), unavailable_tools: [] };
      }
    } catch {}
  }
  return { usable_tools: [], unavailable_tools: [] };
}

// ---------------------------------------------------------------------------
// Frontmatter projection + description
// ---------------------------------------------------------------------------

/** Strip the leading `---\n...\n---` fence; return the prose body. */
function stripFrontmatterFence(content: string): string {
  const m = content.match(/^---\n[\s\S]*?\n---\n?/);
  return m ? content.slice(m[0].length) : content;
}

export { oneLineDescription };

// ---------------------------------------------------------------------------
// Catalog assembly
// ---------------------------------------------------------------------------

interface TriggerInfo {
  triggers: Set<string>;
  section: string;
}

/** Group the unified trigger index by skill directory name. */
function buildTriggerMap(skillsDir: string): Map<string, TriggerInfo> {
  const map = new Map<string, TriggerInfo>();
  for (const e of loadSkillTriggerIndex(skillsDir)) {
    if (e.isGStack) continue; // external refs aren't fetchable skills
    const m = e.skillPath.match(/^skills\/([^/]+)\//);
    if (!m) continue;
    const dir = m[1];
    let info = map.get(dir);
    if (!info) {
      info = { triggers: new Set(), section: e.section };
      map.set(dir, info);
    }
    info.triggers.add(e.trigger);
    // Prefer a real RESOLVER.md section label over the synthesized
    // frontmatter section when both exist.
    if (info.section === FRONTMATTER_SECTION && e.section !== FRONTMATTER_SECTION) {
      info.section = e.section;
    }
  }
  return map;
}

/** First path segment of a manifest entry path (the skill dir name). */
function dirNameOf(entry: ManifestEntry): string {
  return entry.path.split('/')[0] ?? entry.name;
}

const QUERY_STOPWORDS = new Set(['a', 'an', 'the', 'and', 'or', 'of', 'to', 'for', 'in', 'on', 'at', 'by', 'with', 'my', 'me', 'is', 'it', 'be', 'this', 'that', 'from', 'as']);
const QUERY_RESULT_LIMIT_DEFAULT = 10;
const QUERY_RESULT_LIMIT_MAX = 100;

/** Lowercased word tokens; hyphens and punctuation split, so `meeting-prep` is `meeting` + `prep`. */
function queryTokens(text: string): string[] {
  return splitWords(text).filter(t => t.length >= 2 && !QUERY_STOPWORDS.has(t));
}

/**
 * #6471: lexical token overlap between a task and one catalog entry. Trigger
 * tokens count 2 each and a whole trigger phrase inside the query counts
 * double again; name tokens count 3; description tokens count 1. Null when
 * nothing overlaps (the entry is dropped from a ranked list). No model call:
 * the catalog is ~100 entries and `list_skills` must stay keyless and fast.
 */
export function scoreSkillMatch(entry: Pick<SkillCatalogEntry, 'name' | 'description' | 'triggers'>, query: string): SkillMatch | null {
  const queryWords = queryTokens(query);
  if (queryWords.length === 0) return null;
  const inQuery = new Set(queryWords);
  const queryText = ` ${queryWords.join(' ')} `;
  const overlap = (text: string): number => new Set(queryTokens(text).filter(t => inQuery.has(t))).size;
  let trigger = 0;
  for (const phrase of entry.triggers) {
    const words = queryTokens(phrase);
    if (words.length === 0) continue;
    trigger += queryText.includes(` ${words.join(' ')} `) ? 4 * words.length : 2 * overlap(phrase);
  }
  const name = 3 * overlap(entry.name);
  const description = overlap(entry.description);
  const score = trigger + name + description;
  if (score === 0) return null;
  const matched_on = trigger >= name && trigger >= description ? 'trigger' : name >= description ? 'name' : 'description';
  return { score, matched_on };
}

/**
 * Build the flat host-repo skill catalog + the instructional envelope. Resilient:
 * a single malformed/escaping skill is skipped, never throws the whole call.
 * With `opts.query` (#6471) the section-filtered catalog is ranked by
 * `scoreSkillMatch`, zero-score entries are dropped, ties break by name and
 * `opts.limit` (default 10, max 100) caps the list; without it the output is
 * unchanged.
 */
export function buildSkillCatalog(
  ctx: OperationContext,
  skillsDir: string,
  source: ResolvedSkillsDirSource,
  opts: { section?: string; gateDisabled?: ReadonlySet<string>; query?: string; limit?: number } = {},
): ListSkillsResult {
  const { skills: manifest } = loadOrDeriveManifest(skillsDir);
  const triggerMap = buildTriggerMap(skillsDir);
  const sectionFilter = opts.section?.trim();
  const query = opts.query?.trim();

  let skills: SkillCatalogEntry[] = [];
  for (const entry of manifest) {
    let path: string;
    try {
      path = confineManifestPath(skillsDir, entry);
    } catch {
      continue; // skip escaping / non-SKILL.md / missing entries in the listing
    }
    let content: string;
    try {
      content = readFileSync(path, 'utf-8');
    } catch {
      continue;
    }
    const parsed = parseSkillFrontmatter(content);
    const raw = parsed?.raw ?? '';
    const body = stripFrontmatterFence(content);
    const dir = dirNameOf(entry);
    const trig = triggerMap.get(dir);
    const triggers = trig
      ? Array.from(trig.triggers)
      : parsed?.triggers ?? [];
    const section = trig?.section ?? FRONTMATTER_SECTION;

    if (sectionFilter && section !== sectionFilter) continue;

    const tools = parsed?.tools ?? [];
    const { usable_tools, unavailable_tools } = resolveSkillTools(parsed, ctx, opts.gateDisabled);
    skills.push({
      name: entry.name,
      description: oneLineDescription(raw, body),
      section,
      triggers,
      tools,
      usable_tools,
      unavailable_tools,
      writes_pages: parsed?.writes_pages ?? false,
      mutating: parsed?.mutating ?? false,
    });
  }

  skills.sort((a, b) => a.name.localeCompare(b.name));
  if (query) {
    const limit = Math.min(QUERY_RESULT_LIMIT_MAX, Math.max(1, Math.floor(opts.limit ?? QUERY_RESULT_LIMIT_DEFAULT)));
    skills = skills
      .flatMap(entry => { const match = scoreSkillMatch(entry, query); return match ? [{ ...entry, match }] : []; })
      .sort((a, b) => b.match!.score - a.match!.score || a.name.localeCompare(b.name))
      .slice(0, limit);
  }

  return {
    schema_version: 1,
    skills_dir_source: source,
    count: skills.length,
    skills,
    instructions: {
      summary: SKILL_CATALOG_INSTRUCTIONS.summary,
      how_to_use: [...SKILL_CATALOG_INSTRUCTIONS.how_to_use],
      available_brain_tools: availableBrainTools(ctx, opts.gateDisabled),
      fetch_op: 'get_skill',
    },
  };
}

/** Fetch one skill's full instructions (prose only, size-capped, sanitized). */
export function getSkillDetail(
  ctx: OperationContext,
  skillsDir: string,
  name: string,
  opts: { gateDisabled?: ReadonlySet<string> } = {},
): GetSkillResult {
  const path = resolveSkillMdPath(skillsDir, name);

  const size = statSync(path).size;
  if (size > MAX_SKILL_MD_BYTES) {
    throw new OperationError(
      'payload_too_large',
      `Skill ${name} is ${size} bytes (cap ${MAX_SKILL_MD_BYTES}).`,
      'Raise GBRAIN_MAX_SKILL_MD_BYTES if this is a legitimately large skill.',
    );
  }
  const content = readFileSync(path, 'utf-8');
  if (Buffer.byteLength(content, 'utf8') > MAX_SKILL_MD_BYTES) {
    throw new OperationError('payload_too_large', `Skill ${name} exceeds the size cap.`,
      `Skill ${name} is over ${MAX_SKILL_MD_BYTES} bytes, so it is not served. The brain host's operator can raise GBRAIN_MAX_SKILL_MD_BYTES if it is legitimately large.`);
  }

  const parsed = parseSkillFrontmatter(content);
  const raw = parsed?.raw ?? '';
  const body = stripFrontmatterFence(content);
  const { usable_tools, unavailable_tools } = resolveSkillTools(parsed, ctx, opts.gateDisabled);
  const mutating = parsed?.mutating ?? false;

  return {
    schema_version: 1,
    name,
    frontmatter: {
      name: parsed?.name,
      description: oneLineDescription(raw, body) || undefined,
      triggers: parsed?.triggers,
      tools: parsed?.tools,
      writes_pages: parsed?.writes_pages,
      mutating: parsed?.mutating,
    },
    body,
    usable_tools,
    unavailable_tools,
    client_guidance: {
      nature: SKILL_CLIENT_GUIDANCE.nature,
      protocol: [...SKILL_CLIENT_GUIDANCE.protocol],
      available_brain_tools: availableBrainTools(ctx, opts.gateDisabled),
      mutating,
    },
  };
}

// ---------------------------------------------------------------------------
// Publish gate
// ---------------------------------------------------------------------------

/**
 * Enforce the publish gate. Local callers (`ctx.remote === false`) always pass —
 * the owner running the CLI owns the machine. Remote callers require
 * `publishSkills === true` (resolved from either config plane by the caller;
 * absent → false → OFF, fail-safe: no silent capability grant to existing tokens
 * on upgrade). Throws `permission_denied` otherwise. Pure (boolean in) so tests
 * drive both branches without an engine.
 */
export function assertPublishEnabled(ctx: OperationContext, publishSkills: boolean): void {
  if (ctx.remote === false) return;
  if (publishSkills) return;
  // Caller-facing wording + machine-readable detail (WP1). The k=v `detail`
  // grammar (`config_key=<key>`) is THE machine-parseable denial format —
  // future denial classes reuse it rather than inventing new string shapes.
  // Honest catalogs hide this op at list time; reaching this throw means a
  // caller guessed the name or the gate flipped between list and call.
  const err = new OperationError(
    'permission_denied',
    'This tool is not published by the brain owner, so it is hidden from your tool catalog. ' +
      'Ask the owner to enable skill publishing if you need it.',
    'The owner can enable it with `gbrain config set mcp.publish_skills true`.',
  );
  err.detail = 'config_key=mcp.publish_skills';
  throw err;
}