Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(skills): fail on unrunnable gbrain commands and links that leave skills/ (#6197, #6198)

garrytan8be18d244f5f
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 3287118a73..845ede79d3 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -29,3 +29,5 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).
- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.
- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.
+
+- `scripts/build-agent-protocol.ts` — generated regions of the agent operator protocol (`bun run build:agent-protocol`, `--check` in verify and `regen:all`): the protocol page's transcripts from the frozen wire goldens, the AGENTS.md quick contract, and `skills/conventions/agent-operator-protocol.md`, the whole protocol page bundled with the skills (a shared dep every copy path carries) with its relative links made absolute. Drift test: `test/agent-protocol-doc.test.ts`.
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.md
index 2c867fd291..2d7cfce0e3 100644
--- a/docs/architecture/key-files/ci-health-and-test-guards.md
+++ b/docs/architecture/key-files/ci-health-and-test-guards.md
@@ -26,3 +26,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/contributor-audit.ts` + `scripts/contributor-audit-fixture.ts` — `bun run audit:contributors <base>..<head> [--prs <manifest>] [--json]`. Per first-parent commit in the range and per pinned PR head trial-merged onto `<head>`: green baseline of the change's test files (one Bun process per file), reverse only its product hunks (non-test, non-doc) with `git apply -R` in an isolated worktree of `<head>` (falling back to the merge commit when the hunks no longer apply), classify (`discriminates`, `does_not_discriminate`, `vacuous_failure`, `setup_failed`, `conflict`, `not_audited` with a reason), restore, verify the tree is identical and green again. Untrusted install and tests run under `env -i` with `sandboxEnv()`'s allowlist (temporary `HOME`/`GBRAIN_HOME`, empty `DATABASE_URL`/`GBRAIN_DATABASE_URL` unless `--postgres` names a test-shaped database). Runs the trusted `wave-security-scan.sh` and `check-postgres-lane-coverage.ts` (`GBRAIN_GUARD_ROOT` = audited tree). State, logs and `prs.pinned.json` live in `<git-dir>/contributor-audit/<base>-<head>/`; `--resume` refuses on changed refs or pins (`preview_changed`). Human verdicts come only from the verdicts file. Exit 0 clean, 1 review, 2 refusal envelope, 130 interrupted. The fixture builds the offline demo range. Tests: `test/scripts/contributor-audit.test.ts`. Docs: `docs/TESTING.md#contributor-audit`.
- `.github/workflows/fix-wave-gate.yml` + `scripts/fix-wave-gate.ts` — the contributor gate. `pull_request_target` on master (`opened`, `edited`, `reopened`, `synchronize`, `labeled`, `unlabeled`); sparse-checks-out only the script from the default branch and never PR code. `decide()` (pure) passes a head repository equal to `TRUSTED_HEAD_REPO` with the base repository's id, or a present `maintainer-override` label whose latest `labeled` timeline event was made by a `User` on `MAINTAINERS` (no `[bot]` login); a null head repository, a missing label or any other labeler fails. Overrides print a `notice` and step-summary line naming the actor, time and event id. `--comment` (the `welcome-comment` job, `pull-requests: write`, `opened` only) posts `gateMessage()` once per PR, keyed by `COMMENT_MARKER`. The script imports only `node:` modules. Tests: `test/scripts/fix-wave-gate.test.ts` (fixture payloads in `test/fixtures/fix-wave-gate/`). Process and the required-check settings step: `docs/RELEASING.md#fix-wave-gate`.
- `.github/workflows/fix-wave-closeout.yml` + `scripts/fix-wave-closeout.ts` — closes what a merged fix wave superseded. `pull_request_target` on master (`closed`); the job runs only when the PR merged and its head repository is `garrytan/gbrain`, and sparse-checks-out only the script from the default branch. `supersededNumbers()` (pure) reads the PR numbers listed right after a line-leading `Supersedes` keyword; `runCloseout()` skips non-PRs and closed PRs, posts `closeoutMessage()` once per PR (keyed by `COMMENT_MARKER`, crediting the contributor only when the wave body says `Contributed by @handle`), closes it, caps a run at `MAX_CLOSES`, and turns a failed close into a warning. `--dry-run` reads without writing. Tests: `test/scripts/fix-wave-closeout.test.ts`. Process: `docs/RELEASING.md#fix-wave-closeout`.
+
+- `scripts/check-skill-refs.mjs` + `scripts/portable-skill-links.ts` + `scripts/skills-commit-gate.sh` — skills-tree integrity gate (`bun run check:skill-refs`, in verify and the skills commit gate). Fails on dangling backtick `skills/` refs, `./`/`../` links, `composes:` and RESOLVER dispatcher slugs; donor-workspace paths outside the shrink-only allowlist; any `gbrain <cmd>` in a fenced line or inline code span (command position only: line/span start, after a shell separator, `nohup`/env prefixes) that is not a real command (union of `--tools-json`, `CLI_FLAG_REGISTRY`, `src/cli.ts` dispatch, the command table and op `cliHints`), plus curated known-bad subcommands (`embed refresh`); and a relative link that resolves outside the skills root, in `skills/` and in the generated `plugin/skills` and `plugin-variants/*/skills` trees (`skills/migrations/**` exempt). A tools-json load failure warns and skips the CLI lane. `portable-skill-links.ts` is that rule's fix: it points `docs/protocol/AGENT_OPERATOR_v1.md` links at the bundled `skills/conventions/agent-operator-protocol.md` and other repo files at absolute blob URLs derived from `LLMS_REPO_BASE` (raw.githubusercontent base → github.com blob base; default `garrytan/gbrain/blob/master`), retargeting default-base links for forks; `--check` reports pending rewrites. Tests: `test/check-skill-refs.test.ts`, `test/skills-portable-links.test.ts` (scaffold `--all` into a tmp host: 0 broken local links).
diff --git a/docs/guides/scaling-skills.md b/docs/guides/scaling-skills.md
index 4422301d23..d5b950ffdd 100644
--- a/docs/guides/scaling-skills.md
+++ b/docs/guides/scaling-skills.md
@@ -305,6 +305,23 @@ regen + freshness check, and `check-skill-refs` in seconds — run it before
committing a skills change so the membership/closure and `plugin.version`
assertions fail locally instead of in CI.
+`check-skill-refs` fails on two things skill authors hit most:
+
+- **A `gbrain` command that cannot run.** Every `gbrain <cmd>` in a fenced
+ block or an inline code span must name a real command, and known-bad forms
+ (`gbrain embed refresh`, which parses `refresh` as a page slug) fail with
+ the replacement. Paid commands go preview first, then the user's approval,
+ then `--yes --max-usd <cap>`; never write a skill step that adds `--yes` on
+ its own.
+- **A relative link that leaves `skills/`.** Skills are copied verbatim into
+ host workspaces, harness skill dirs and the plugin trees, so a link to
+ `../../docs/...` dangles in every copy. Link the agent operator protocol
+ through its bundled copy, `skills/conventions/agent-operator-protocol.md`
+ (generated by `bun run build:agent-protocol`), and other repo docs by
+ absolute URL. `bun scripts/portable-skill-links.ts` rewrites both; it
+ derives the URL base from `LLMS_REPO_BASE` for forks. Links between skills
+ stay relative, and `skills/migrations/**` is exempt.
+
## When a skill misroutes
Treat a misroute like a failing test, because it becomes one. First
diff --git a/scripts/build-agent-protocol.ts b/scripts/build-agent-protocol.ts
index 1cd0758149..84a6ab4d88 100644
--- a/scripts/build-agent-protocol.ts
+++ b/scripts/build-agent-protocol.ts
@@ -12,6 +12,11 @@
* expected value, so a contract change cannot silently rewrite the story.
* 2. AGENTS.md "Agent operator protocol" quick contract: copied verbatim from
* the protocol page's quick-contract region.
+ * 3. skills/conventions/agent-operator-protocol.md: the whole protocol page,
+ * bundled with the skills (#6198, D13) so skill links to it resolve in
+ * every copy (skillpack scaffold, harness dirs, plugin trees). Its own
+ * relative links become absolute repo URLs (scripts/portable-skill-links.ts,
+ * which honors the LLMS_REPO_BASE fork override).
*
* Adding a transcript (Lane H journey goldens): append a TRANSCRIPTS entry
* naming its golden file, transport, expected `next` and narration. Journey
@@ -19,15 +24,17 @@
* from real runs; their placeholders render as fixed example values.
* Drift test: test/agent-protocol-doc.test.ts.
*/
-import { readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { deriveNext, type Action, type RenderContext, type Transport } from '../src/core/agent-output.ts';
import { renderConsentRefusal, type ConfirmationPayload } from '../src/core/consent.ts';
+import { BUNDLED_PROTOCOL, renderBundledProtocol, repoBlobBase } from './portable-skill-links.ts';
const ROOT = join(import.meta.dir, '..');
const GOLDENS = join(ROOT, 'test', 'fixtures', 'agent-contract', 'v1');
export const PROTOCOL_PATH = join(ROOT, 'docs', 'protocol', 'AGENT_OPERATOR_v1.md');
export const AGENTS_PATH = join(ROOT, 'AGENTS.md');
+export const BUNDLED_PROTOCOL_PATH = join(ROOT, BUNDLED_PROTOCOL);
/** Transcripts show the source-checkout base; the wire pins the installed version. */
const DOCS_BASE = 'https://github.com/garrytan/gbrain/blob/master';
@@ -258,22 +265,29 @@ export function quickContract(protocol: string): string {
return protocol.slice(m.index + m[0].length, end);
}
-/** Fresh text for both files, from the committed protocol page and goldens. */
-export function renderAgentProtocolDocs(protocol: string, agents: string): { protocol: string; agents: string } {
+/** Fresh text for every generated file, from the committed protocol page and goldens. */
+export function renderAgentProtocolDocs(protocol: string, agents: string): { protocol: string; agents: string; bundled: string } {
const transcripts = `${TRANSCRIPTS.map(renderTranscript).join('\n\n')}\n`;
+ const freshProtocol = replaceRegion(protocol, TRANSCRIPT_REGION, transcripts);
return {
- protocol: replaceRegion(protocol, TRANSCRIPT_REGION, transcripts),
+ protocol: freshProtocol,
agents: replaceRegion(agents, 'agent-protocol:quick-contract', quickContract(protocol)),
+ bundled: renderBundledProtocol(freshProtocol, repoBlobBase()),
};
}
if (import.meta.main) {
- const current = { protocol: readFileSync(PROTOCOL_PATH, 'utf8'), agents: readFileSync(AGENTS_PATH, 'utf8') };
+ const current = {
+ protocol: readFileSync(PROTOCOL_PATH, 'utf8'),
+ agents: readFileSync(AGENTS_PATH, 'utf8'),
+ bundled: existsSync(BUNDLED_PROTOCOL_PATH) ? readFileSync(BUNDLED_PROTOCOL_PATH, 'utf8') : '',
+ };
const fresh = renderAgentProtocolDocs(current.protocol, current.agents);
if (process.argv.includes('--check')) {
const stale = [
...(fresh.protocol !== current.protocol ? ['docs/protocol/AGENT_OPERATOR_v1.md'] : []),
...(fresh.agents !== current.agents ? ['AGENTS.md'] : []),
+ ...(fresh.bundled !== current.bundled ? [BUNDLED_PROTOCOL] : []),
];
if (stale.length) {
console.error(`${stale.join(', ')}: generated agent-protocol regions are stale. Run: bun run build:agent-protocol`);
@@ -283,6 +297,7 @@ if (import.meta.main) {
} else {
writeFileSync(PROTOCOL_PATH, fresh.protocol);
writeFileSync(AGENTS_PATH, fresh.agents);
- console.log('wrote docs/protocol/AGENT_OPERATOR_v1.md and AGENTS.md generated regions');
+ writeFileSync(BUNDLED_PROTOCOL_PATH, fresh.bundled);
+ console.log(`wrote docs/protocol/AGENT_OPERATOR_v1.md and AGENTS.md generated regions, and ${BUNDLED_PROTOCOL}`);
}
}
diff --git a/scripts/check-skill-refs.mjs b/scripts/check-skill-refs.mjs
index 554e721e27..8eaab3fe68 100755
--- a/scripts/check-skill-refs.mjs
+++ b/scripts/check-skill-refs.mjs
@@ -14,15 +14,26 @@
// The allowlist is a ratchet: it may shrink, never silently grow — add a
// line only with a review-visible commit. An entry whose file has no donor
// hit (cleaned or deleted) fails as stale, so the list shrinks with it.
-// 3. CLI REFS (warn only): `gbrain <cmd>` tokens inside fenced code blocks are
-// checked against the CLI's --tools-json surface. Warnings never fail the
-// build; they exist so a skill body promising a nonexistent command is
-// visible in CI logs before a user hits it.
+// 3. CLI REFS (fail): `gbrain <cmd>` tokens inside fenced code blocks AND
+// inline code spans must name a real top-level command (the CLI's
+// --tools-json surface, CLI_FLAG_REGISTRY, src/cli.ts dispatch, the
+// command table and op cliHints). A curated list of known-bad
+// subcommands (`gbrain embed refresh` parses `refresh` as a page slug)
+// fails too. Skill bodies are agent-executed instructions, so a command
+// that cannot run is a broken instruction, not a style nit. If the CLI
+// surface cannot be loaded the lane warns and skips.
+// 4. OUTSIDE-ROOT LINKS (fail): a relative markdown link whose resolved
+// target lies outside the skills root breaks the moment the skills are
+// copied into a host workspace or a plugin tree (#6198). Links inside the
+// skills tree stay relative; repo docs use absolute URLs (fix:
+// `bun scripts/portable-skill-links.ts`). skills/migrations/** is exempt.
+// The same rule runs over the generated plugin/skills and
+// plugin-variants/*/skills trees next to the skills dir.
//
// Usage: bun scripts/check-skill-refs.mjs [--skills-dir skills/] [--allowlist scripts/skill-refs-allowlist.txt] [--no-cli-refs]
import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
-import { join, relative, dirname } from 'node:path';
+import { join, relative, dirname, resolve } from 'node:path';
import { execSync } from 'node:child_process';
const args = process.argv.slice(2);
@@ -60,6 +71,20 @@ function isPlaceholderLinkTarget(target) {
return false;
}
+const SKILLS_ROOT = resolve(SKILLS_DIR);
+const PORTABLE_FIX = 'bun scripts/portable-skill-links.ts';
+
+/** A relative link that escapes `root` once resolved from `file`'s directory, or null. */
+function outsideRootLink(root, file, raw) {
+ const target = raw.split('#')[0];
+ if (!relative(root, resolve(dirname(file), target)).startsWith('..')) return null;
+ const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(`](${raw})`)) + 1;
+ return {
+ line,
+ message: `\`](${raw})\` resolves outside the skills root, so it dangles once the skills are copied into a host workspace or plugin. Fix: ${PORTABLE_FIX} (protocol links point at skills/conventions/agent-operator-protocol.md; other repo docs become absolute URLs)`,
+ };
+}
+
function walk(dir) {
const out = [];
for (const e of readdirSync(dir, { withFileTypes: true })) {
@@ -142,6 +167,11 @@ for (const file of files) {
const target = raw.split('#')[0];
if (!target) continue; // anchor-only after a ./ prefix — nothing to resolve
if (isPlaceholderLinkTarget(target)) continue;
+ const outside = outsideRootLink(SKILLS_ROOT, file, raw);
+ if (outside) {
+ failures.push(`[outside-root-link] ${rel}:${outside.line} — ${outside.message}`);
+ continue;
+ }
if (!existsSync(join(dirname(file), target))) {
const line = text.split('\n').findIndex((l) => l.includes(raw)) + 1;
failures.push(`[dangling-md-link] ${rel}:${line} — \`](${raw})\` does not resolve from ${rel}'s directory`);
@@ -191,7 +221,35 @@ if (existsSync(resolverPath)) {
}
}
-// --- 3. CLI refs (warn-only) ---
+// --- 3. CLI refs (fail) ---
+// `gbrain embed` takes flags or a page slug, so a bare word after it is read
+// as a slug: `embed refresh` runs the paid-consent gate, then "Page not found".
+const KNOWN_BAD_SUBCOMMANDS = {
+ embed: { refresh: 'gbrain embed --stale --dry-run (preview), then gbrain embed --stale --yes --max-usd <cap> after the user approves' },
+};
+// A command position: line/span start, after a shell separator or `$ ` prompt,
+// past `nohup`/`exec`/`time` and env assignments. Prose that merely mentions
+// gbrain mid-sentence ("turned off gbrain update checks") is not a command.
+const GBRAIN_CMD_RE = /(?:^|[|&;(]|\$)\s*(?:(?:nohup|exec|time)\s+|[A-Z_][A-Z0-9_]*=\S*\s+)*gbrain\s+([a-z][a-z0-9-]*)(?:\s+([a-z][a-z0-9-]*))?/g;
+
+/** `gbrain <cmd> [<sub>]` in fenced code lines and inline code spans. */
+function cliRefs(text) {
+ const refs = [];
+ let fence = null;
+ for (const line of text.split('\n')) {
+ const marker = line.match(/^\s*(`{3,}|~{3,})/);
+ if (marker && (!fence || marker[1].startsWith(fence))) {
+ fence = fence ? null : marker[1];
+ continue;
+ }
+ const snippets = fence ? [line.trim()] : [...line.matchAll(/`([^`]+)`/g)].map((m) => m[1].trim());
+ for (const snippet of snippets) {
+ for (const m of snippet.matchAll(GBRAIN_CMD_RE)) refs.push({ cmd: m[1], sub: m[2], snippet });
+ }
+ }
+ return refs;
+}
+
if (RUN_CLI_REFS) {
let known = null;
try {
@@ -208,7 +266,7 @@ if (RUN_CLI_REFS) {
warnings.push('[cli-refs] could not load --tools-json; skipping CLI-ref check');
}
if (known && known.size === 0) {
- warnings.push('[cli-refs] --tools-json parsed to an EMPTY command set; skipping CLI-ref check (the warn-only lane is not running)');
+ warnings.push('[cli-refs] --tools-json parsed to an EMPTY command set; skipping CLI-ref check (the CLI-ref lane is not running)');
}
if (known && known.size > 0) {
// top-level commands defined directly in src/cli.ts (not ops): derive from source
@@ -218,6 +276,10 @@ if (RUN_CLI_REFS) {
// Refactor wave 1: CLI-only commands are records in the command table.
const tableSrc = readFileSync('src/cli/command-table.ts', 'utf8');
for (const m of tableSrc.matchAll(/\{ name: '([a-z][a-z0-9-]*)'/g)) known.add(m[1]);
+ // Every CLI-only command has a row in the generated flag registry.
+ const registrySrc = readFileSync('src/core/cli-flag-registry.generated.ts', 'utf8');
+ const registry = registrySrc.slice(registrySrc.indexOf('CLI_FLAG_REGISTRY'), registrySrc.indexOf('CLI_ROUTING_FLAGS'));
+ for (const m of registry.matchAll(/^\s+'([a-z][a-z0-9-]*)': \[/gm)) known.add(m[1]);
} catch {}
// ops cliHints that --tools-json does not serialize: read them from source.
// operations.ts is a façade post-peel — the op declarations (and their
@@ -239,18 +301,41 @@ if (RUN_CLI_REFS) {
} catch {}
for (const file of files) {
if (file.includes('/migrations/')) continue;
- if (!file.endsWith('.md')) continue; // fenced gbrain-cmd scan is markdown-only
- const rel = relative('.', file);
- const text = readFileSync(file, 'utf8');
- for (const block of text.matchAll(/```[a-z]*\n([\s\S]*?)```/g)) {
- for (const cmd of block[1].matchAll(/(?:^|[|&;(]\s*)gbrain\s+([a-z][a-z0-9-]*)/gm)) {
- if (!known.has(cmd[1])) warnings.push(`[cli-refs] ${rel} — \`gbrain ${cmd[1]}\` not found in CLI surface (warn-only)`);
+ if (!file.endsWith('.md')) continue; // gbrain-cmd scan is markdown-only
+ const rel = join('skills', relative(SKILLS_DIR, file));
+ for (const { cmd, sub, snippet } of cliRefs(readFileSync(file, 'utf8'))) {
+ if (!known.has(cmd)) {
+ failures.push(`[cli-refs] ${rel} — \`${snippet}\`: \`gbrain ${cmd}\` is not a gbrain command, so an agent following this skill gets "unknown command". Fix: name the real command (\`gbrain --help\` lists them)`);
+ continue;
}
+ const replacement = sub && KNOWN_BAD_SUBCOMMANDS[cmd]?.[sub];
+ if (replacement) failures.push(`[cli-refs] ${rel} — \`${snippet}\`: \`gbrain ${cmd} ${sub}\` does not run as written. Fix: ${replacement}`);
}
}
}
}
+// --- 4. outside-root links in the generated plugin trees ---
+// The plugin trees ship to users verbatim; a link that escapes their skills
+// root dangles in every install. Only the link rule runs here: the variants
+// carry a subset of skills by design.
+const generatedRoots = [join(SKILLS_DIR, '..', 'plugin', 'skills')];
+const variantsDir = join(SKILLS_DIR, '..', 'plugin-variants');
+if (existsSync(variantsDir)) {
+ for (const v of readdirSync(variantsDir)) generatedRoots.push(join(variantsDir, v, 'skills'));
+}
+for (const root of generatedRoots.filter((r) => existsSync(r))) {
+ for (const file of walk(root)) {
+ const underRoot = relative(root, file);
+ if (underRoot.startsWith('migrations/') || !file.endsWith('.md')) continue;
+ for (const m of readFileSync(file, 'utf8').matchAll(/\]\((\.{1,2}\/[^)\s]+)\)/g)) {
+ if (isPlaceholderLinkTarget(m[1].split('#')[0])) continue;
+ const outside = outsideRootLink(resolve(root), file, m[1]);
+ if (outside) failures.push(`[outside-root-link] ${relative(join(SKILLS_DIR, '..'), file)}:${outside.line} — ${outside.message}, then bun run regen:all`);
+ }
+ }
+}
+
// The ratchet only shrinks if a clean file leaves the list: an entry whose
// file no longer carries a donor prefix (or no longer exists) fails.
for (const entry of allowlist) {
diff --git a/scripts/portable-skill-links.ts b/scripts/portable-skill-links.ts
new file mode 100644
index 0000000000..d14324f17f
--- /dev/null
+++ b/scripts/portable-skill-links.ts
@@ -0,0 +1,101 @@
+#!/usr/bin/env bun
+/**
+ * Portable links in the bundled skills tree (#6198, D13).
+ *
+ * bun scripts/portable-skill-links.ts rewrite skills/**\/*.md in place
+ * bun scripts/portable-skill-links.ts --check exit 1 when a rewrite is pending
+ *
+ * Skills are copied verbatim into host workspaces (`gbrain skillpack
+ * scaffold`), harness skill dirs and the generated plugin trees, so a
+ * relative link that leaves `skills/` dangles in every copy. This script
+ * rewrites each such link at the source:
+ * - `docs/protocol/AGENT_OPERATOR_v1.md` → the bundled copy at
+ * `skills/conventions/agent-operator-protocol.md` (relative, so it works
+ * offline in every copy; `bun run build:agent-protocol` keeps it fresh);
+ * - any other repo file → an absolute `<blob base>/<path>` URL.
+ * skills/migrations/** is historical record and is left alone.
+ *
+ * Blob base: derived from `LLMS_REPO_BASE`, the fork override llms.txt uses
+ * (a raw base `https://raw.githubusercontent.com/<owner>/<repo>/<ref>` maps to
+ * `https://github.com/<owner>/<repo>/blob/<ref>`; any other value is used as
+ * given). Unset → `https://github.com/garrytan/gbrain/blob/master`. A fork
+ * re-running with its override also retargets links already written with the
+ * default base. `scripts/check-skill-refs.mjs` fails on any outside-root link
+ * and names this script as the fix.
+ */
+import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { join, posix, relative } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+export const DEFAULT_BLOB_BASE = 'https://github.com/garrytan/gbrain/blob/master';
+export const PROTOCOL_SOURCE = 'docs/protocol/AGENT_OPERATOR_v1.md';
+export const BUNDLED_PROTOCOL = 'skills/conventions/agent-operator-protocol.md';
+
+export function repoBlobBase(env: Record<string, string | undefined> = process.env): string {
+ const raw = env.LLMS_REPO_BASE?.replace(/\/+$/, '');
+ if (!raw) return DEFAULT_BLOB_BASE;
+ const m = raw.match(/^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(.+)$/);
+ return m ? `https://github.com/${m[1]}/${m[2]}/blob/${m[3]}` : raw;
+}
+
+/**
+ * Rewrite every relative markdown link in `text` (a file at repo-relative
+ * `fileRel`) whose target leaves `rootRel`: the protocol page goes to the
+ * bundled copy, anything else to `base`. `rootRel: null` treats every
+ * relative link as outside (the bundled protocol copy itself). Links already
+ * on the default base move to `base`.
+ */
+export function portableLinks(text: string, fileRel: string, base: string, rootRel: string | null = 'skills'): string {
+ const dir = posix.dirname(fileRel);
+ const retargeted = base === DEFAULT_BLOB_BASE ? text : text.split(`](${DEFAULT_BLOB_BASE}/`).join(`](${base}/`);
+ return retargeted.replace(/\]\(([^)\s]+)\)/g, (whole, link: string) => {
+ if (link.startsWith('#') || link.startsWith('/') || /[<{$]/.test(link) || /^[a-z][a-z0-9+.-]*:/i.test(link)) return whole;
+ const [target, anchor = ''] = link.split(/(?=#)/);
+ const repoPath = posix.normalize(posix.join(dir, target));
+ if (repoPath.startsWith('../')) return whole;
+ if (rootRel !== null && (repoPath === rootRel || repoPath.startsWith(`${rootRel}/`))) return whole;
+ if (rootRel !== null && repoPath === PROTOCOL_SOURCE) {
+ const rel = posix.relative(dir, BUNDLED_PROTOCOL);
+ return `](${rel.startsWith('.') ? rel : `./${rel}`}${anchor})`;
+ }
+ return `](${base}/${repoPath}${anchor})`;
+ });
+}
+
+/** The bundled protocol copy: the source page with its own links made absolute. */
+export function renderBundledProtocol(protocol: string, base: string): string {
+ const [title, ...rest] = protocol.split('\n');
+ const body = portableLinks(rest.join('\n'), PROTOCOL_SOURCE, base, null);
+ return `${title}\n\n<!-- GENERATED from ${PROTOCOL_SOURCE} by \`bun run build:agent-protocol\`. Do not edit: edit the source page and regenerate. -->\n${body}`;
+}
+
+function markdownFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(e => {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) return e.name === 'migrations' ? [] : markdownFiles(p);
+ return e.name.endsWith('.md') ? [p] : [];
+ });
+}
+
+if (import.meta.main) {
+ const base = repoBlobBase();
+ const pending: string[] = [];
+ for (const file of markdownFiles(join(ROOT, 'skills'))) {
+ const rel = relative(ROOT, file).split('\\').join('/');
+ if (rel === BUNDLED_PROTOCOL) continue;
+ const text = readFileSync(file, 'utf8');
+ const fresh = portableLinks(text, rel, base);
+ if (fresh === text) continue;
+ pending.push(rel);
+ if (!process.argv.includes('--check')) writeFileSync(file, fresh);
+ }
+ if (process.argv.includes('--check')) {
+ if (pending.length) {
+ console.error(`${pending.length} skill file(s) have links that leave skills/: ${pending.join(', ')}\nFix: bun scripts/portable-skill-links.ts`);
+ process.exit(1);
+ }
+ console.log('skill links: portable');
+ } else {
+ console.log(pending.length ? `rewrote links in ${pending.length} file(s) (base ${base})` : 'skill links: already portable');
+ }
+}
diff --git a/scripts/skills-commit-gate.sh b/scripts/skills-commit-gate.sh
index a1a05eff62..1c7128e343 100755
--- a/scripts/skills-commit-gate.sh
+++ b/scripts/skills-commit-gate.sh
@@ -7,7 +7,7 @@
# 2. check-resolvable --strict (MECE overlap, DRY delegation, filing audit,
# routing-eval fixtures)
# 3. skills.lock.json regen + freshness
-# 4. check-skill-refs (dangling refs, donor remnants, CLI refs warn-only)
+# 4. check-skill-refs (dangling refs, donor remnants, CLI refs, links that leave skills/)
#
# Optional: pass changed .md file paths as arguments to also run the harvest
# privacy linter over them (the merge-lane lint — harvest can't lint merges).
diff --git a/test/agent-protocol-doc.test.ts b/test/agent-protocol-doc.test.ts
index 9f3da8287e..a501ddc256 100644
--- a/test/agent-protocol-doc.test.ts
+++ b/test/agent-protocol-doc.test.ts
@@ -5,6 +5,8 @@
* the frozen goldens in test/fixtures/agent-contract/v1/ and the quick
* contract is copied verbatim into AGENTS.md; both must match a fresh
* render (regenerate: bun run build:agent-protocol).
+ * - skills/conventions/agent-operator-protocol.md is the whole page bundled
+ * with the skills (#6198) and must match a fresh render too.
* - The quick contract stays at most 10 lines.
* - The entry points agents read first link the protocol page.
*/
@@ -12,7 +14,7 @@ import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import {
- AGENTS_PATH, PROTOCOL_PATH, TRANSCRIPTS, quickContract, renderAgentProtocolDocs,
+ AGENTS_PATH, BUNDLED_PROTOCOL_PATH, PROTOCOL_PATH, TRANSCRIPTS, quickContract, renderAgentProtocolDocs,
} from '../scripts/build-agent-protocol.ts';
const ROOT = join(import.meta.dir, '..');
@@ -31,6 +33,10 @@ describe('AGENT_OPERATOR_v1.md generated regions', () => {
expect(agents).toContain(quickContract(protocol));
});
+ test('the skills tree carries a fresh bundled copy of the page', () => {
+ expect(renderAgentProtocolDocs(protocol, agents).bundled, REGEN).toBe(readFileSync(BUNDLED_PROTOCOL_PATH, 'utf8'));
+ });
+
test('the quick contract is at most 10 lines', () => {
expect(quickContract(protocol).trimEnd().split('\n').length).toBeLessThanOrEqual(10);
});
diff --git a/test/check-skill-refs.test.ts b/test/check-skill-refs.test.ts
new file mode 100644
index 0000000000..ee80fda34a
--- /dev/null
+++ b/test/check-skill-refs.test.ts
@@ -0,0 +1,111 @@
+/**
+ * scripts/check-skill-refs.mjs — the CLI-ref lane (#6197) and the
+ * outside-root link rule (#6198), exercised on fixture skill trees.
+ *
+ * #6197: skills/maintain told agents to run `nohup gbrain embed refresh`
+ * in an inline code span; `refresh` parses as a page slug, so the command
+ * never refreshed anything. The lane scanned only fenced blocks and only
+ * warned. It now scans inline spans too and fails on an unknown top-level
+ * command or a known-bad subcommand.
+ * #6198: skills linked `../../docs/protocol/AGENT_OPERATOR_v1.md`, which
+ * dangles in every copied skill tree. A relative link that resolves outside
+ * the skills root now fails (skills/migrations/** exempt).
+ */
+import { describe, expect, it, afterAll } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+const tmpRoots: string[] = [];
+afterAll(() => { for (const d of tmpRoots) rmSync(d, { recursive: true, force: true }); });
+
+function fixture(files: Record<string, string>): string {
+ const root = mkdtempSync(join(tmpdir(), 'skill-refs-'));
+ tmpRoots.push(root);
+ for (const [rel, text] of Object.entries(files)) {
+ mkdirSync(join(root, 'skills', rel, '..'), { recursive: true });
+ writeFileSync(join(root, 'skills', rel), text);
+ }
+ return join(root, 'skills');
+}
+
+function check(skillsDir: string, ...extra: string[]): { code: number; out: string } {
+ const r = Bun.spawnSync(['bun', 'scripts/check-skill-refs.mjs', '--skills-dir', skillsDir, '--allowlist', join(skillsDir, 'no-allowlist.txt'), ...extra], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
+ return { code: r.exitCode ?? -1, out: `${r.stdout}${r.stderr}` };
+}
+
+const skill = (body: string) => `---\nname: demo\ndescription: demo\n---\n# Demo\n\n${body}\n`;
+
+describe('check-skill-refs CLI-ref lane (#6197)', () => {
+ it('fails on a known-bad subcommand inside an inline code span', () => {
+ const r = check(fixture({ 'demo/SKILL.md': skill('Refresh with `nohup gbrain embed refresh > /tmp/e.log 2>&1 &`.') }));
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('`gbrain embed refresh` does not run as written');
+ expect(r.out).toContain('gbrain embed --stale --dry-run');
+ });
+
+ it('fails on an unknown top-level command in an inline span', () => {
+ const r = check(fixture({ 'demo/SKILL.md': skill('Run `gbrain frobnicate-pages --all` first.') }));
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('`gbrain frobnicate-pages` is not a gbrain command');
+ });
+
+ it('fails on an unknown top-level command in a fenced block', () => {
+ const r = check(fixture({ 'demo/SKILL.md': skill('```bash\ngbrain sync --no-pull\ngbrain frobnicate-pages\n```') }));
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('`gbrain frobnicate-pages` is not a gbrain command');
+ });
+
+ it('passes real commands and ignores prose that only mentions gbrain', () => {
+ const r = check(fixture({
+ 'demo/SKILL.md': skill([
+ 'Preview with `gbrain embed --stale --dry-run`, then `GBRAIN_HOME=/x gbrain sync --source alpha-example --no-pull`.',
+ 'Report: `Turned off gbrain update checks (re-enable: gbrain config set self_upgrade.mode notify).`',
+ '````markdown\n```bash\ngbrain doctor --json\n```\n````',
+ '```text\n🧠 gbrain checkup — 2 things worth your attention\n# gbrain frobnicate in a comment is not a command\n```',
+ ].join('\n\n')),
+ }));
+ expect(r.out).not.toContain('FAIL');
+ expect(r.code).toBe(0);
+ });
+});
+
+describe('check-skill-refs outside-root links (#6198)', () => {
+ it('fails a relative link that leaves the skills root, naming the fix', () => {
+ const r = check(fixture({ 'demo/SKILL.md': skill('See the [protocol](../../docs/protocol/AGENT_OPERATOR_v1.md#quick-contract).') }), '--no-cli-refs');
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('[outside-root-link] skills/demo/SKILL.md:7');
+ expect(r.out).toContain('bun scripts/portable-skill-links.ts');
+ });
+
+ it('keeps links inside the skills root and exempts skills/migrations/**', () => {
+ const r = check(fixture({
+ 'demo/SKILL.md': skill('See [quality](../conventions/quality.md) and [the url](https://github.com/garrytan/gbrain/blob/master/docs/ENGINES.md).'),
+ 'conventions/quality.md': '# Quality\n',
+ 'migrations/v0.1.0.md': '# Old\n\nSee [docs](../../docs/ENGINES.md).\n',
+ }), '--no-cli-refs');
+ expect(r.out).not.toContain('FAIL');
+ expect(r.code).toBe(0);
+ });
+
+ it('checks the generated plugin trees next to the skills dir', () => {
+ const skillsDir = fixture({ 'demo/SKILL.md': skill('Clean.') });
+ const variant = join(skillsDir, '..', 'plugin-variants', 'demo-variant', 'skills', 'demo');
+ mkdirSync(variant, { recursive: true });
+ writeFileSync(join(variant, 'SKILL.md'), skill('See [protocol](../../docs/protocol/AGENT_OPERATOR_v1.md).'));
+ const r = check(skillsDir, '--no-cli-refs');
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('[outside-root-link] plugin-variants/demo-variant/skills/demo/SKILL.md:7');
+ });
+});
+
+describe('check-skill-refs on the shipped trees', () => {
+ it('passes on skills/, plugin/skills and plugin-variants/*/skills', () => {
+ const r = Bun.spawnSync(['bun', 'scripts/check-skill-refs.mjs'], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
+ const out = `${r.stdout}${r.stderr}`;
+ expect(out).not.toContain('FAIL');
+ expect(out).not.toContain('could not load --tools-json');
+ expect(r.exitCode).toBe(0);
+ });
+});
diff --git a/test/skills-conformance.test.ts b/test/skills-conformance.test.ts
index bae718fd37..1e726cbec5 100644
--- a/test/skills-conformance.test.ts
+++ b/test/skills-conformance.test.ts
@@ -92,7 +92,9 @@ describe("skills conformance", () => {
test("has a When it fails section that links the agent operator protocol", () => {
const section = content.split(/^## When it fails\s*$/m)[1]?.split(/^## /m)[0];
expect(section).toBeDefined();
- expect(section).toContain("AGENT_OPERATOR_v1.md");
+ // #6198 (D13): the link targets the protocol copy bundled with the
+ // skills, so it resolves in every installed copy of the skill.
+ expect(section).toContain("conventions/agent-operator-protocol.md)");
});
});
}
diff --git a/test/skills-portable-links.test.ts b/test/skills-portable-links.test.ts
new file mode 100644
index 0000000000..3db8158052
--- /dev/null
+++ b/test/skills-portable-links.test.ts
@@ -0,0 +1,108 @@
+/**
+ * #6198 — bundled skill links survive being copied out of the repo.
+ *
+ * Skills are copied verbatim into host workspaces (`gbrain skillpack
+ * scaffold`), harness dirs and the generated plugin trees. Links that leave
+ * `skills/` (64 of them to docs/protocol/AGENT_OPERATOR_v1.md) dangled in
+ * every copy. D13: the protocol page ships inside the skills tree as a
+ * generated copy, other repo docs use absolute URLs, and the rewrite honors
+ * the LLMS_REPO_BASE fork override.
+ */
+import { describe, expect, it, afterAll } from 'bun:test';
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative, resolve } from 'node:path';
+import { runScaffold } from '../src/core/skillpack/scaffold.ts';
+import {
+ BUNDLED_PROTOCOL, DEFAULT_BLOB_BASE, portableLinks, renderBundledProtocol, repoBlobBase,
+} from '../scripts/portable-skill-links.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const tmpRoots: string[] = [];
+afterAll(() => { for (const d of tmpRoots) rmSync(d, { recursive: true, force: true }); });
+
+function markdown(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(e => {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) return markdown(p);
+ return e.name.endsWith('.md') ? [p] : [];
+ });
+}
+
+/** `./` and `../` links (outside fenced code) that do not resolve inside the tree, as `file -> link`. */
+function brokenLinks(skillsRoot: string): string[] {
+ const broken: string[] = [];
+ for (const file of markdown(skillsRoot)) {
+ if (relative(skillsRoot, file).startsWith('migrations/')) continue;
+ const prose = readFileSync(file, 'utf8').replace(/^\s*(`{3,}|~{3,})[\s\S]*?^\s*\1/gm, '');
+ for (const m of prose.matchAll(/\]\((\.{1,2}\/[^)\s]+)\)/g)) {
+ const link = m[1];
+ if (/[<{$]/.test(link)) continue;
+ const target = link.split('#')[0];
+ const segs = target.split('/').filter(s => s && s !== '.' && s !== '..');
+ if (segs.some(s => /-example(\.|$)/.test(s)) || ['people', 'companies', 'meetings', 'concepts'].includes(segs[0] ?? '')) continue;
+ const abs = resolve(dirname(file), target);
+ if (!abs.startsWith(`${resolve(skillsRoot)}/`) || !existsSync(abs)) broken.push(`${relative(skillsRoot, file)} -> ${link}`);
+ }
+ }
+ return broken;
+}
+
+describe('scaffolded skills have no broken local links (#6198)', () => {
+ it('skillpack scaffold --all into a fresh host workspace', () => {
+ const host = mkdtempSync(join(tmpdir(), 'portable-links-host-'));
+ tmpRoots.push(host);
+ const result = runScaffold({ gbrainRoot: ROOT, targetWorkspace: host, skillSlug: null });
+ expect(result.summary.wroteNew).toBeGreaterThan(50);
+ expect(existsSync(join(host, BUNDLED_PROTOCOL))).toBe(true);
+ expect(brokenLinks(join(host, 'skills'))).toEqual([]);
+ });
+
+ it('the committed plugin trees', () => {
+ const trees = [join(ROOT, 'plugin', 'skills'), ...readdirSync(join(ROOT, 'plugin-variants')).map(v => join(ROOT, 'plugin-variants', v, 'skills'))];
+ for (const tree of trees) {
+ expect(existsSync(join(tree, 'conventions', 'agent-operator-protocol.md'))).toBe(true);
+ const escaping = brokenLinks(tree).filter(b => b.includes('../../') || b.includes('docs/'));
+ expect(escaping, tree).toEqual([]);
+ }
+ });
+});
+
+describe('portableLinks', () => {
+ it('points protocol links at the bundled copy, relative to the linking file', () => {
+ expect(portableLinks('[p](../../docs/protocol/AGENT_OPERATOR_v1.md#quick-contract)', 'skills/demo/SKILL.md', DEFAULT_BLOB_BASE))
+ .toBe('[p](../conventions/agent-operator-protocol.md#quick-contract)');
+ expect(portableLinks('[p](../docs/protocol/AGENT_OPERATOR_v1.md)', 'skills/RESOLVER.md', DEFAULT_BLOB_BASE))
+ .toBe('[p](./conventions/agent-operator-protocol.md)');
+ });
+
+ it('turns other outside links into absolute URLs and keeps inside links', () => {
+ const text = '[a](../../docs/mcp/ADMIN.md#tokens) [b](../conventions/quality.md) [c](./ref.md) [d](https://example.com/x) [e](../../people/<slug>.md)';
+ expect(portableLinks(text, 'skills/demo/SKILL.md', DEFAULT_BLOB_BASE)).toBe(
+ `[a](${DEFAULT_BLOB_BASE}/docs/mcp/ADMIN.md#tokens) [b](../conventions/quality.md) [c](./ref.md) [d](https://example.com/x) [e](../../people/<slug>.md)`,
+ );
+ });
+
+ it('derives the blob base from the LLMS_REPO_BASE fork override and retargets default-base links', () => {
+ const base = repoBlobBase({ LLMS_REPO_BASE: 'https://raw.githubusercontent.com/fork-org/gbrain/main/' });
+ expect(base).toBe('https://github.com/fork-org/gbrain/blob/main');
+ expect(repoBlobBase({})).toBe(DEFAULT_BLOB_BASE);
+ expect(repoBlobBase({ LLMS_REPO_BASE: 'https://git.example.com/gbrain/raw' })).toBe('https://git.example.com/gbrain/raw');
+ expect(portableLinks(`[a](${DEFAULT_BLOB_BASE}/docs/ENGINES.md) [b](../../INSTALL_FOR_AGENTS.md)`, 'skills/demo/SKILL.md', base))
+ .toBe(`[a](${base}/docs/ENGINES.md) [b](${base}/INSTALL_FOR_AGENTS.md)`);
+ });
+
+ it('the bundled protocol copy carries no relative link out of the skills tree', () => {
+ const protocol = readFileSync(join(ROOT, 'docs', 'protocol', 'AGENT_OPERATOR_v1.md'), 'utf8');
+ const bundled = renderBundledProtocol(protocol, DEFAULT_BLOB_BASE);
+ expect(bundled).toContain(`](${DEFAULT_BLOB_BASE}/docs/guides/error-codes.md)`);
+ expect(bundled).toContain(`](${DEFAULT_BLOB_BASE}/docs/protocol/MEMORY_VERBS_v1.md)`);
+ expect([...bundled.matchAll(/\]\((\.\.?\/[^)]*)\)/g)].map(m => m[1])).toEqual([]);
+ });
+
+ it('every skill link is already portable (bun scripts/portable-skill-links.ts --check)', () => {
+ const r = Bun.spawnSync(['bun', 'scripts/portable-skill-links.ts', '--check'], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, LLMS_REPO_BASE: '' } });
+ expect(`${r.stdout}${r.stderr}`).toContain('skill links: portable');
+ expect(r.exitCode).toBe(0);
+ });
+});