Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(skills): skill-refs lint fails closed, checks paid-consent wording and every link form (W4.7)
time-attacka42719bf94ec
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex e9940b5533..cfb160c6bd 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -27,4 +27,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `.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`; a non-https or credentialed value throws via `repoBaseOrThrow`, as in `scripts/llms-config.ts`), 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).+- `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). W4.7: a tools-json load failure FAILS the CLI lane (`--no-cli-refs` skips it deliberately); links are read in every form (`](./x)`, bare `](x.md)` unless a placeholder, `](<x>)`, titled, `[id]: x` definitions); a `[paid-consent]` lane, migrations included, fails a paid `gbrain` command carrying `--yes`/`--max-usd`/`--max-cost[-usd]` with no ask/agree/approve/consent/confirm/permission wording on its line or the 8 before. `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`; a non-https or credentialed value throws via `repoBaseOrThrow`, as in `scripts/llms-config.ts`), 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/scripts/check-skill-refs.mjs b/scripts/check-skill-refs.mjsindex 8eaab3fe68..88055dcbd8 100755--- a/scripts/check-skill-refs.mjs+++ b/scripts/check-skill-refs.mjs@@ -29,6 +29,20 @@// `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.+// W4.7: link targets are read in every Markdown form: `](./x.md)`,+// `](x.md)` (a bare `.md` target that is not a placeholder),+// `](<x.md>)`, `](x.md "title")` and reference definitions `[id]: x.md`.+// 5. PAID CONSENT (fail, W4.7): a `gbrain` command that pre-approves paid+// work (`--yes`, `--max-usd`, `--max-cost`, `--max-cost-usd` on embed,+// reindex, reindex-code, enrich, extract-conversation-facts, book-mirror,+// jobs submit, doctor --remediate, dream) needs approval wording (ask,+// agree, approve, consent, confirm, permission) on its line or in the 8+// lines before it. This lane covers skills/migrations/** too: migration+// notes are agent-executed during upgrades.+//+// The CLI-ref lane fails closed (W4.7): when the CLI surface cannot be+// loaded the check FAILS instead of warning; pass --no-cli-refs to skip it+// deliberately.//// Usage: bun scripts/check-skill-refs.mjs [--skills-dir skills/] [--allowlist scripts/skill-refs-allowlist.txt] [--no-cli-refs]@@ -78,13 +92,31 @@ const PORTABLE_FIX = 'bun scripts/portable-skill-links.ts';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;+ 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)`,};}+/** Relative link targets in `text` (W4.7): inline links (bare, `<…>`, titled) and reference definitions; URLs and anchors excluded. */+const BARE_PLACEHOLDER_SEGMENT = /^(?:path|to|type|slug|relative|page|link|url|file|name|sibling[-\w]*|[\w-]*slug[\w-]*)(?:\.md)?$/i;+function linkTargets(text) {+ const out = [];+ const add = (raw) => {+ if (!raw || /^(?:[a-z][a-z0-9+.-]*:|#|\/)/i.test(raw)) return;+ if (!raw.startsWith('./') && !raw.startsWith('../')) {+ // A bare target is a link only when it names a .md file and is not a documentation placeholder.+ const target = raw.split('#')[0];+ if (!target.endsWith('.md') || target.split('/').some((seg) => BARE_PLACEHOLDER_SEGMENT.test(seg))) return;+ }+ out.push(raw);+ };+ for (const m of text.matchAll(/\]\(\s*(?:<([^>\n]+)>|([^)\s]+))(?:\s+"[^"\n]*")?\s*\)/g)) add(m[1] ?? m[2]);+ for (const m of text.matchAll(/^\s{0,3}\[[^\]\n]+\]:\s*(?:<([^>\n]+)>|(\S+))/gm)) add(m[1] ?? m[2]);+ return out;+}+function walk(dir) {const out = [];for (const e of readdirSync(dir, { withFileTypes: true })) {@@ -162,8 +194,7 @@ for (const file of files) {// `](./x.md)` / `](../x/y.md)` targets must resolve against the linking// file's own directory. http(s) and anchor-only targets never match the// leading ./ or ../ pattern; placeholder/example targets are exempt.- for (const m of text.matchAll(/\]\((\.{1,2}\/[^)\s]+)\)/g)) {- const raw = m[1];+ for (const raw of linkTargets(text)) {const target = raw.split('#')[0];if (!target) continue; // anchor-only after a ./ prefix — nothing to resolveif (isPlaceholderLinkTarget(target)) continue;@@ -263,10 +294,10 @@ if (RUN_CLI_REFS) {for (const a of (t.cliHints && t.cliHints.aliases) || []) known.add(String(a));}} catch {- warnings.push('[cli-refs] could not load --tools-json; skipping CLI-ref check');+ failures.push('[cli-refs] could not load the CLI surface (bun src/cli.ts --tools-json), so no gbrain command in a skill was checked. Fix: make `bun src/cli.ts --tools-json` run (bun install; the Bun version in package.json engines), or pass --no-cli-refs to skip this lane deliberately');}if (known && known.size === 0) {- warnings.push('[cli-refs] --tools-json parsed to an EMPTY command set; skipping CLI-ref check (the CLI-ref lane is not running)');+ failures.push('[cli-refs] --tools-json parsed to an EMPTY command set, so no gbrain command in a skill was checked. Fix: make `bun src/cli.ts --tools-json` print the tool list, or pass --no-cli-refs to skip this lane deliberately');}if (known && known.size > 0) {// top-level commands defined directly in src/cli.ts (not ops): derive from source@@ -328,14 +359,39 @@ 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]);+ for (const raw of linkTargets(readFileSync(file, 'utf8'))) {+ if (isPlaceholderLinkTarget(raw.split('#')[0])) continue;+ const outside = outsideRootLink(resolve(root), file, raw);if (outside) failures.push(`[outside-root-link] ${relative(join(SKILLS_DIR, '..'), file)}:${outside.line} — ${outside.message}, then bun run regen:all`);}}}+// --- 5. paid consent (fail, W4.7; migrations included) ---+const PAID_COMMAND_RE = /(?:^|[|&;(]|\$)\s*(?:(?:nohup|exec|time)\s+|[A-Z_][A-Z0-9_]*=\S*\s+)*gbrain\s+(embed|reindex|reindex-code|enrich|extract-conversation-facts|book-mirror|dream|jobs\s+submit|doctor)(?![\w-])([^\n`]*)/;+const PREAPPROVAL_RE = /(?:^|\s)--(?:yes|max-usd|max-cost|max-cost-usd)(?:[=\s]|$)/;+const APPROVAL_WORDING_RE = /\b(?:ask|asks|asked|agree|agrees|agreed|approv\w*|consent\w*|confirm\w*|permission)\b/i;+for (const file of files) {+ if (!file.endsWith('.md')) continue;+ const rel = join('skills', relative(SKILLS_DIR, file));+ const lines = readFileSync(file, 'utf8').split('\n');+ let fence = null;+ lines.forEach((line, i) => {+ const marker = line.match(/^\s*(`{3,}|~{3,})/);+ if (marker && (!fence || marker[1].startsWith(fence))) { fence = fence ? null : marker[1]; return; }+ const snippets = fence ? [line.trim()] : [...line.matchAll(/`([^`]+)`/g)].map((m) => m[1].trim());+ for (const snippet of snippets) {+ const m = snippet.match(PAID_COMMAND_RE);+ if (!m || !PREAPPROVAL_RE.test(m[2])) continue;+ if (m[1] === 'doctor' && !/--remediate\b/.test(m[2])) continue;+ if (m[1] === 'dream' && !/--phase\s+(?:synthesize|patterns|chronicle)\b/.test(m[2]) && /--phase\b/.test(m[2])) continue;+ const context = lines.slice(Math.max(0, i - 8), i + 1).join('\n');+ if (APPROVAL_WORDING_RE.test(context)) continue;+ failures.push(`[paid-consent] ${rel}:${i + 1} — \`${snippet}\` pre-approves paid work with no approval step near it, so an agent following this would spend without asking. Fix: say to ask the user first (for example "only after the user agrees:" on the line above), and show the free preview (--dry-run) before it`);+ }+ });+}+// 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/skills/conversation-archive/SKILL.md b/skills/conversation-archive/SKILL.mdindex 0aff32d0a1..50741f5d63 100644--- a/skills/conversation-archive/SKILL.md+++ b/skills/conversation-archive/SKILL.md@@ -231,7 +231,8 @@ read — fix the converter and regenerate, don't hand-patch individual pages.# Preview: segmentation + counts, no DB writesgbrain extract-conversation-facts --types conversation --dry-run --limit 5-# Real run, cost-capped; use --background for large archives+# Real run (paid, cost-capped): only after the user agrees to the cap;+# use --background for large archivesgbrain extract-conversation-facts --types conversation --max-cost-usd 5```diff --git a/test/scripts/check-skill-refs.test.ts b/test/scripts/check-skill-refs.test.tsindex 22cbe348e5..1c3fa1fc2c 100644--- a/test/scripts/check-skill-refs.test.ts+++ b/test/scripts/check-skill-refs.test.ts@@ -255,4 +255,55 @@ describe('check-skill-refs', () => {expect(out).toContain('not-a-real-command');expect(code).toBe(1);}, 30_000);++ test('W4.7: the CLI-ref lane fails closed when the CLI surface cannot load', () => {+ const { code, out } = runOn((skills) => {+ mkdirSync(join(skills, 'alpha'));+ writeFileSync(join(skills, 'alpha', 'SKILL.md'), '```bash\ngbrain no-such-command\n```\n');+ }, '', { cliRefs: true });+ expect(code).toBe(1);+ expect(out).toContain('[cli-refs] could not load the CLI surface');+ });++ test('W4.7: a paid command that pre-approves spend needs approval wording near it (migrations included)', () => {+ const bad = runOn((skills) => {+ mkdirSync(join(skills, 'alpha'));+ writeFileSync(join(skills, 'alpha', 'SKILL.md'), 'Rebuild code chunks:\n\n```bash\ngbrain reindex-code --yes\n```\n');+ mkdirSync(join(skills, 'migrations'));+ writeFileSync(join(skills, 'migrations', 'v9.9.9.md'), 'Run `gbrain embed --stale --yes --max-usd 2` now.\n');+ });+ expect(bad.code).toBe(1);+ expect(bad.out).toContain('[paid-consent] skills/alpha/SKILL.md:4');+ expect(bad.out).toContain('[paid-consent] skills/migrations/v9.9.9.md:1');+ const good = runOn((skills) => {+ mkdirSync(join(skills, 'alpha'));+ writeFileSync(join(skills, 'alpha', 'SKILL.md'), 'Preview first: `gbrain reindex-code --dry-run`.\n\n```bash\n# only after the user agrees:\ngbrain reindex-code --yes\n```\n\nFree runs need nothing: `gbrain reindex --markdown --dry-run`, `gbrain apply-migrations --yes`, `gbrain reindex-frontmatter --yes`.\n');+ });+ expect(good.out).not.toContain('paid-consent');+ expect(good.code).toBe(0);+ });++ test('W4.7: titled, angle-bracket, bare .md and reference-definition links are checked; placeholders are not', () => {+ const bad = runOn((skills) => {+ mkdirSync(join(skills, 'alpha'));+ writeFileSync(join(skills, 'alpha', 'SKILL.md'), [+ 'See [a](missing-one.md) and [b](./missing-two.md "Two") and [c](<missing three.md>).',+ '',+ '[d]: ../alpha/missing-four.md',+ ].join('\n'));+ });+ expect(bad.code).toBe(1);+ for (const target of ['missing-one.md', './missing-two.md', 'missing three.md', '../alpha/missing-four.md']) expect(bad.out).toContain(target);+ const good = runOn((skills) => {+ mkdirSync(join(skills, 'alpha'));+ writeFileSync(join(skills, 'alpha', 'OTHER.md'), 'x\n');+ writeFileSync(join(skills, 'alpha', 'SKILL.md'), [+ 'See [other](OTHER.md "Other") and [page title](type/slug.md) and [p](path/to/page.md) and [s](sibling-concept.md) and [web](https://example.test/x.md).',+ '',+ '[ref]: ./OTHER.md',+ ].join('\n'));+ });+ expect(good.out).toContain('OK');+ expect(good.code).toBe(0);+ });});