Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

skill resolver: Node library from the installed gbrain, release sha256, OpenClaw load line, async commit export, match_strength

garrytanbfe3878b7ab2
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 084061882a..7b5721a088 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -63,7 +63,7 @@ jobs:
# can repair it.
assets="$(gh release view "v$version" --repo "$GITHUB_REPOSITORY" \
--json assets --jq '[.assets[].name] | sort | join(",")' 2>/dev/null || true)"
- if [ "$assets" = "gbrain-darwin-arm64,gbrain-linux-x64,gbrain-skill-resolver.mjs" ]; then
+ if [ "$assets" = "gbrain-darwin-arm64,gbrain-linux-x64,gbrain-skill-resolver.mjs,gbrain-skill-resolver.mjs.sha256" ]; then
echo "exists=true" >> "$GITHUB_OUTPUT"
echo "Release v$version already published with all assets — nothing to do."
else
@@ -180,7 +180,7 @@ jobs:
skill-resolver-bundle:
# GBRA-377: the skill resolver library as one dependency-free ES module for
# Node adapters (docs/guides/skill-resolver.md#library). Built from the gated
- # SHA and smoke-tested under Node before it is attached.
+ # SHA and smoke-tested under Node before it is attached with its sha256.
needs: [version, ci-gate]
if: needs.version.outputs.exists == 'false' && needs.ci-gate.outputs.publish == 'true'
runs-on: ubuntu-latest
@@ -202,7 +202,9 @@ jobs:
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: gbrain-skill-resolver.mjs
- path: bundle/gbrain-skill-resolver.mjs
+ path: |
+ bundle/gbrain-skill-resolver.mjs
+ bundle/gbrain-skill-resolver.mjs.sha256
release:
needs: [version, ci-gate, build, skill-resolver-bundle]
@@ -218,6 +220,9 @@ jobs:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
path: artifacts
+ - name: Check the skill resolver bundle against its sha256
+ working-directory: artifacts/gbrain-skill-resolver.mjs
+ run: sha256sum -c gbrain-skill-resolver.mjs.sha256
- name: Extract CHANGELOG entry for release notes
# env-bound, not inlined into the script: VERSION comes from master so
# it isn't attacker-reachable today, but a `${{ }}` inside `run:` is
@@ -241,6 +246,7 @@ jobs:
artifacts/gbrain-darwin-arm64/gbrain-darwin-arm64
artifacts/gbrain-linux-x64/gbrain-linux-x64
artifacts/gbrain-skill-resolver.mjs/gbrain-skill-resolver.mjs
+ artifacts/gbrain-skill-resolver.mjs/gbrain-skill-resolver.mjs.sha256
# [C1 = D6-A] `latest-stable` is the alpha channel's ref: the alpha
# update check follows it, and so does anyone who pins it by hand. The
# install surfaces (the README paste block, the BOOTSTRAP_FOR_AGENTS.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d2e3e7b91b..89ee34952a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,8 +14,8 @@ identifiers and attribution are available in the pre-removal Git revision
### Added
-- `gbrain skills index build|status|remove` and `gbrain skills resolve`: an engine-free skill resolver that ranks a harness's skill catalog against one user turn and prints a short `<relevant_skills>` block (at most 5 suggestions, at most 400 tokens), so an agent with hundreds of skills sees the few that fit. Off by default; nothing changes until you build a catalog and call it. Works with no brain, on thin clients and while `gbrain serve` holds the PGLite lock. Word matching only (the BM25F ranker frozen by the Step 1 offline eval); nothing leaves the machine. Sessions never repeat a suggestion and share a 2,000-token budget (`skills.resolver.session_token_budget`). JSON contract in `docs/schemas/skill-resolver.v1.*.json`; library as `gbrain/skill-resolver` and, for Node, the `gbrain-skill-resolver.mjs` release asset. Guide: `docs/guides/skill-resolver.md`.
-- `gbrain setup claude-code|codex --skill-loading resolve`: a per-turn hook lane (`GBRAIN_HOOK_LANE=skill-resolver`) that adds the resolver's block to every prompt, with the harness's own load line. Setup builds the user catalog first and writes the `skills.resolver.*` keys and the hook only when it found at least one skill (`skill_resolver_setup_incomplete` otherwise); `--skill-loading off` and `setup --remove` undo all of it. The lane runs in the hook process with no brain and no serve, exits within 50 ms with nothing printed when it cannot deliver, drops a block over `skills.resolver.lane_payload_chars` whole, and lets exactly one wiring deliver. Claude Code project skills get their own catalog, built in the background. `gbrain doctor` reports it as `skill_resolver`. Off by default; with it off, hook output and setup's files are unchanged. A `config.json` that holds only file-plane settings no longer reads as a Postgres brain. Release binaries are now built with the lane's worker as a second entrypoint.
+- `gbrain skills index build|status|remove` and `gbrain skills resolve`: an engine-free skill resolver that ranks a harness's skill catalog against one user turn and prints a short `<relevant_skills>` block (at most 5 suggestions, at most 400 tokens), so an agent with hundreds of skills sees the few that fit. Off by default; nothing changes until you build a catalog and call it. Works with no brain, on thin clients and while `gbrain serve` holds the PGLite lock. Word matching only (the BM25F ranker frozen by the Step 1 offline eval); nothing leaves the machine. Sessions never repeat a suggestion and share a 2,000-token budget (`skills.resolver.session_token_budget`). JSON contract in `docs/schemas/skill-resolver.v1.*.json`; library as `gbrain/skill-resolver` and, for Node, one dependency-free module built from the same source: `gbrain skills library` writes it to `GBRAIN_HOME/lib/gbrain-skill-resolver.mjs` and prints its sha256, and each release attaches `gbrain-skill-resolver.mjs` with a `.sha256`. Each suggestion carries `match_strength` (`named`, `name`, `triggers`, `routing`, `description` or `body`) so an adapter can drop weak matches. Guide: `docs/guides/skill-resolver.md`.
+- `gbrain setup claude-code|codex --skill-loading resolve`: a per-turn hook lane (`GBRAIN_HOOK_LANE=skill-resolver`) that adds the resolver's block to every prompt, with the harness's own load line. Setup builds the user catalog first and writes the `skills.resolver.*` keys and the hook only when it found at least one skill (`skill_resolver_setup_incomplete` otherwise); `--skill-loading off` and `setup --remove` undo all of it. The lane runs in the hook process with no brain and no serve, exits within 50 ms with nothing printed when it cannot deliver, drops a block over `skills.resolver.lane_payload_chars` whole, and lets exactly one wiring deliver. Claude Code project skills get their own catalog, built in the background. `gbrain doctor` reports it as `skill_resolver`. Off by default; with it off, hook output and setup's files are unchanged. A `config.json` that holds only `skills.resolver` settings no longer reads as a Postgres brain. Release binaries are now built with the lane's worker as a second entrypoint.
## [0.60.632.0] - 2026-11-09
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6a1082a40b..e963974813 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4702,7 +4702,7 @@ More: [docs/guides/skill-resolver.md#skill_source_invalid](../../docs/guides/ski
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A --dir or --routing path does not exist or cannot be read, so nothing was built. | The request itself was wrong or no longer matches the brain; nothing was changed. | Pass an existing directory (or file) you can read. | agent | `repeat the read that failed` | 1 | no |
+| A --dir or --routing path (or, for `gbrain skills library`, gbrain's own source in a compiled binary) does not exist or cannot be read, so nothing was built. | The request itself was wrong or no longer matches the brain; nothing was changed. | Pass an existing directory (or file) you can read; for the Node library from a compiled binary, download the release asset. | agent | `repeat the read that failed` | 1 | no |
More: [docs/guides/skill-resolver.md#skill_source_unreadable](../../docs/guides/skill-resolver.md#skill_source_unreadable)
diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.md
index 82b4ebe00c..be7d310e12 100644
--- a/docs/guides/skill-resolver.md
+++ b/docs/guides/skill-resolver.md
@@ -133,7 +133,10 @@ Within v1, changes are additive only.
`no_skill` is true only for an acknowledgement from a small multilingual list
(`no_skill_reason: "ack"`) or when no word of the turn is in the catalog
(`"no_match"`). There is no score threshold: a weak match is still
-suggested. A skill named in the turn (`$name`, `@name`, a leading `/name`,
+suggested, and each suggestion's `match_strength` says how it matched
+(`named` in the turn, else the first of `name`, `triggers`, `routing`,
+`description`, `body`) so an adapter can set its own floor, for example
+dropping body-only matches. A skill named in the turn (`$name`, `@name`, a leading `/name`,
"the name skill", or its full id) ranks first.
### Exit codes and fail-open
@@ -234,17 +237,31 @@ pull requests that touch the resolver.
## Library
`import { buildSkillIndex, resolveSkills } from 'gbrain/skill-resolver'` for
-Bun. Node adapters use `gbrain-skill-resolver.mjs` from the release assets: one
-dependency-free ES module (build it locally with
-`bun scripts/build-skill-resolver-bundle.ts --out <file.mjs>`). The CLI JSON
-contract stays the primary interface.
+Bun. Node adapters load one dependency-free ES module built from the same
+source as the CLI:
+
+- `gbrain skills library --json` writes it from the installed gbrain to
+ `GBRAIN_HOME/lib/gbrain-skill-resolver.mjs` (`--out <file.mjs>` for another
+ path) and prints `{path, sha256, bytes, gbrain_version}`. Run it again
+ after each upgrade; the module exports `GBRAIN_VERSION` so an adapter can
+ see a skew. A compiled binary has no source to build from and refuses with
+ `skill_source_unreadable`.
+- Each release attaches `gbrain-skill-resolver.mjs` and
+ `gbrain-skill-resolver.mjs.sha256` (`sha256sum -c` format), smoke-tested
+ under Node before publishing.
+
+The CLI JSON contract stays the primary interface.
```ts
const r = await resolveSkills({ message, session_id, harness: 'codex' }, { catalogs: ['codex-user'], failOpen: true });
-inject(r.output.block);
+inject(r.output.suggestions.filter(s => s.match_strength !== 'body').length ? r.output.block : '');
await r.commit();
```
+On an event loop that must not block, commit with async I/O instead:
+`if (r.pending) await commitSessionAsync(home, r.pending.key, r.pending.delta)`
+(same file, lease and rules as `commit()`).
+
## Error codes
### skill_index_missing
@@ -286,7 +303,10 @@ several catalogs and pass them together.
### skill_source_unreadable
-A `--dir` or `--routing` path does not exist or cannot be read.
+A `--dir` or `--routing` path does not exist or cannot be read, or
+`gbrain skills library` ran from a compiled binary, which carries no source to
+build the Node library from: download the release's `gbrain-skill-resolver.mjs`
+and its `.sha256` instead.
### skill_source_invalid
diff --git a/docs/schemas/skill-resolver.v1.turn-output.json b/docs/schemas/skill-resolver.v1.turn-output.json
index dfa40b32a1..a0b243b302 100644
--- a/docs/schemas/skill-resolver.v1.turn-output.json
+++ b/docs/schemas/skill-resolver.v1.turn-output.json
@@ -48,6 +48,7 @@
"score",
"summary",
"reason",
+ "match_strength",
"catalog"
],
"properties": {
@@ -72,6 +73,17 @@
"type": "string",
"description": "The matched fields and terms."
},
+ "match_strength": {
+ "enum": [
+ "named",
+ "name",
+ "triggers",
+ "routing",
+ "description",
+ "body"
+ ],
+ "description": "The strongest way it matched: named in the turn, else the first matched field of name, triggers, routing, description, body. An adapter that wants a floor drops body-only (or description-only) suggestions."
+ },
"path": {
"type": "string",
"description": "The SKILL.md path, when the catalog knows it."
diff --git a/scripts/build-skill-resolver-bundle.ts b/scripts/build-skill-resolver-bundle.ts
index 8ec5d80e36..5ad01c1891 100644
--- a/scripts/build-skill-resolver-bundle.ts
+++ b/scripts/build-skill-resolver-bundle.ts
@@ -2,24 +2,27 @@
/**
* Build the skill resolver library (src/core/skills/resolver/index.ts) as
* one dependency-free ES module for Node adapters: the release asset
- * gbrain-skill-resolver.mjs (docs/guides/skill-resolver.md#library).
+ * gbrain-skill-resolver.mjs and its .sha256 (docs/guides/skill-resolver.md#library).
+ * Same builder as `gbrain skills library` (src/commands/skill-resolver-library.ts).
*
* Usage: bun scripts/build-skill-resolver-bundle.ts --out <file.mjs> [--smoke]
- * --smoke imports the bundle with node, builds a catalog from JSON and the
- * bundled catalog in a scratch home, resolves one turn, and exits 1 on any
- * failure.
+ * Writes <file.mjs>.sha256 beside it (sha256sum format). --smoke imports the
+ * bundle with node, builds a catalog from JSON and the bundled catalog in a
+ * scratch home, resolves one turn, and exits 1 on any failure.
*/
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { basename, dirname, join, resolve } from 'node:path';
+import { basename, join, resolve } from 'node:path';
+import { buildResolverLibrary } from '../src/commands/skill-resolver-library.ts';
+import { VERSION } from '../src/version.ts';
const args = process.argv.slice(2);
const at = args.indexOf('--out');
if (at < 0 || !args[at + 1]) { console.error('Usage: bun scripts/build-skill-resolver-bundle.ts --out <file.mjs> [--smoke]'); process.exit(2); }
const out = resolve(args[at + 1]!);
-const result = await Bun.build({ entrypoints: [join(import.meta.dir, '..', 'src/core/skills/resolver/index.ts')], target: 'node', format: 'esm', outdir: dirname(out), naming: basename(out) });
-if (!result.success) { for (const l of result.logs) console.error(l); process.exit(1); }
-console.log(`built ${out}`);
+const built = await buildResolverLibrary(out);
+writeFileSync(`${out}.sha256`, `${built.sha256} ${basename(out)}\n`);
+console.log(`built ${out} sha256 ${built.sha256}`);
if (args.includes('--smoke')) {
const home = mkdtempSync(join(tmpdir(), 'skres-bundle-'));
try {
@@ -29,9 +32,11 @@ if (args.includes('--smoke')) {
`const home = ${JSON.stringify(join(home, 'home'))};`,
"await m.buildSkillIndex({ catalog: 'c', fromJson: JSON.stringify([{ id: 'x:deploy', name: 'deploy', description: 'Ship a service to production' }]), fromJsonStdin: true }, { home });",
"const b = await m.buildSkillIndex({ catalog: 'gb', bundled: true }, { home });",
- "const t = await m.resolveSkills({ message: 'deploy the service' }, { home, catalogs: ['c'] });",
- "if (t.output.suggestions[0]?.id !== 'x:deploy' || b.catalog.skill_count < 1) { console.error(JSON.stringify(t.output)); process.exit(1); }",
- "console.log(JSON.stringify({ node: process.version, bundled_skills: b.catalog.skill_count, top: t.output.suggestions[0].id }));",
+ "const t = await m.resolveSkills({ message: 'deploy the service', session_id: 's1' }, { home, catalogs: ['c'] });",
+ "if (t.output.suggestions[0]?.id !== 'x:deploy' || t.output.suggestions[0]?.match_strength !== 'name' || b.catalog.skill_count < 1) { console.error(JSON.stringify(t.output)); process.exit(1); }",
+ "if (!(await m.commitSessionAsync(home, t.pending.key, t.pending.delta))) { console.error('commitSessionAsync did not commit'); process.exit(1); }",
+ `if (m.GBRAIN_VERSION !== ${JSON.stringify(VERSION)}) { console.error('GBRAIN_VERSION ' + m.GBRAIN_VERSION); process.exit(1); }`,
+ "console.log(JSON.stringify({ node: process.version, gbrain_version: m.GBRAIN_VERSION, bundled_skills: b.catalog.skill_count, top: t.output.suggestions[0].id }));",
].join('\n'));
const run = Bun.spawnSync(['node', probe], { stdout: 'pipe', stderr: 'pipe', cwd: home });
process.stdout.write(run.stdout.toString());
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index afd8136687..305e1d4d8b 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -389,7 +389,7 @@ test/skill-resolver-hook-lane.test.ts skill-resolver lane: compiled binaries 1 r
test/skill-resolver-hook-lane.test.ts skill-resolver lane: delivery per harness 3 readFileSync
test/skill-resolver-hook-lane.test.ts skill-resolver lane: fail open 6 readFileSync
test/skill-resolver-off-pin.test.ts (file-level) 1 readFileSync
-test/skill-resolver-packaging.test.ts skill resolver packaging 1 bun-file
+test/skill-resolver-packaging.test.ts skill resolver packaging 2 bun-file,readFileSync
test/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSync
test/skillify-scaffold.test.ts applyScaffold 3 readFileSync
test/skillify-scaffold.test.ts planScaffold 13 readFileSync
diff --git a/src/cli/command-route.ts b/src/cli/command-route.ts
index 19b81a4ec0..87e771f3ab 100644
--- a/src/cli/command-route.ts
+++ b/src/cli/command-route.ts
@@ -6,12 +6,12 @@
* command. The `ask` alias stays inline in main.ts, where the dispatch-shape
* analyzer reads it.
*
- * GBRA-377: `skills index ...` and `skills resolve ...` route to the
+ * GBRA-377: `skills index ...`, `skills resolve ...` and `skills library` route to the
* engine-free skill resolver (`skill-resolver`) before help, prewarming or
* any engine work; plain `skills` stays the `list_skills` listing.
*/
export function routeCommand(command: string, subArgs: string[]): { command: string; subArgs: string[] } {
- if (command === 'skills' && (subArgs[0] === 'index' || subArgs[0] === 'resolve')) return { command: 'skill-resolver', subArgs };
+ if (command === 'skills' && (subArgs[0] === 'index' || subArgs[0] === 'resolve' || subArgs[0] === 'library')) return { command: 'skill-resolver', subArgs };
if (command !== 'search') return { command, subArgs };
const at = subArgs.indexOf('--exact');
const end = subArgs.indexOf('--');
diff --git a/src/commands/skill-resolver-library.ts b/src/commands/skill-resolver-library.ts
new file mode 100644
index 0000000000..9970e9d6d5
--- /dev/null
+++ b/src/commands/skill-resolver-library.ts
@@ -0,0 +1,34 @@
+/**
+ * The skill resolver library as one dependency-free ES module for Node
+ * adapters, built from this gbrain's own source so an adapter runs the same
+ * code as the CLI. Used by `gbrain skills library` (written under the gbrain
+ * home) and scripts/build-skill-resolver-bundle.ts (the release asset).
+ */
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
+import { basename, dirname, join, resolve } from 'node:path';
+import { ResolverError } from '../core/skills/resolver/errors.ts';
+
+export const LIBRARY_FILE = 'gbrain-skill-resolver.mjs';
+const ENTRY = resolve(import.meta.dir, '../core/skills/resolver/index.ts');
+
+export interface LibraryBuild { path: string; sha256: string; bytes: number }
+
+/** Build the bundle to `out` (atomically: a reader never sees half a file). */
+export async function buildResolverLibrary(out: string): Promise<LibraryBuild> {
+ if (!existsSync(ENTRY)) {
+ throw new ResolverError('skill_source_unreadable', 'This gbrain is a compiled binary without its source, so it cannot build the Node library.',
+ { suggestion: `Download ${LIBRARY_FILE} and ${LIBRARY_FILE}.sha256 from this version's GitHub release, or run gbrain skills library from a source install (bun install -g github:garrytan/gbrain).` });
+ }
+ const dir = dirname(out);
+ mkdirSync(dir, { recursive: true });
+ const tmp = `.${basename(out)}.tmp-${process.pid}`;
+ const result = await Bun.build({ entrypoints: [ENTRY], target: 'node', format: 'esm', outdir: dir, naming: tmp });
+ if (!result.success) {
+ rmSync(join(dir, tmp), { force: true });
+ throw new Error(`the skill resolver library did not build: ${result.logs.map(String).join('; ')}`);
+ }
+ renameSync(join(dir, tmp), out);
+ const bytes = readFileSync(out);
+ return { path: out, sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.length };
+}
diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.ts
index 7ed8fff1d5..68266c7477 100644
--- a/src/commands/skill-resolver.ts
+++ b/src/commands/skill-resolver.ts
@@ -1,7 +1,7 @@
/**
- * `gbrain skills index build|status|remove` and `gbrain skills resolve`:
- * the skill resolver's CLI (library: src/core/skills/resolver/). The router
- * (src/cli/command-route.ts) sends these two `skills` subcommands here
+ * `gbrain skills index build|status|remove`, `gbrain skills resolve` and
+ * `gbrain skills library`: the skill resolver's CLI (library:
+ * src/core/skills/resolver/). The router (src/cli/command-route.ts) sends these `skills` subcommands here
* before any engine or brain is touched; plain `gbrain skills` keeps
* listing skills through `list_skills`.
*
@@ -13,13 +13,14 @@
* an unknown flag or catalog name), with the agent-protocol refusal.
*/
import { appendFileSync } from 'node:fs';
+import { join, resolve as resolvePath } from 'node:path';
import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';
import { readStdinBounded } from '../core/interaction.ts';
import { opError } from '../core/ops/contract.ts';
import type { RegistryCode } from '../core/error-registry.ts';
import {
buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, resolveSkills, resolverHome, sessionStatus,
- ResolverError, HARNESSES, errorTurnOutput, type BuildInput, type TurnInput,
+ ResolverError, HARNESSES, errorTurnOutput, GBRAIN_VERSION, type BuildInput, type TurnInput,
} from '../core/skills/resolver/index.ts';
const HELP_INDEX = `Usage: gbrain skills index <build|status|remove> [options]
@@ -71,6 +72,18 @@ and no brain connection is needed.
Guide: docs/guides/skill-resolver.md
`;
+const HELP_LIBRARY = `Usage: gbrain skills library [--out <file.mjs>] [--json]
+
+Write the skill resolver library, built from this gbrain's own source, as one
+dependency-free ES module that Node imports (default: GBRAIN_HOME/lib/gbrain-skill-resolver.mjs),
+and print its path, sha256 and gbrain version. Run it again after each upgrade.
+
+ --out <file.mjs> write it here instead
+ --json {path, sha256, bytes, gbrain_version}
+
+Guide: docs/guides/skill-resolver.md#library
+`;
+
const CMD = 'skills';
function toOpError(e: ResolverError) {
@@ -251,9 +264,27 @@ async function runResolve(args: string[]): Promise<void> {
if (out.error && !failOpen) process.exit(1);
}
+async function runLibrary(args: string[]): Promise<void> {
+ const p = parseFlags(args, ['--out'], ['--json'], HELP_LIBRARY);
+ if (p.positionals.length) usage(`Unexpected argument "${p.positionals[0]}".`, 'Pass the file with --out <file.mjs>.');
+ const json = p.bools.has('--json');
+ const out = one(p, '--out');
+ if (out !== undefined && !out.endsWith('.mjs')) usage('--out must name a .mjs file.', 'Example: gbrain skills library --out ./gbrain-skill-resolver.mjs');
+ try {
+ const { buildResolverLibrary, LIBRARY_FILE } = await import('./skill-resolver-library.ts');
+ const built = await buildResolverLibrary(out ? resolvePath(out) : join(resolverHome(), 'lib', LIBRARY_FILE));
+ const doc = { ...built, gbrain_version: GBRAIN_VERSION };
+ await write(json ? `${JSON.stringify(doc)}\n` : `Wrote ${doc.path} (gbrain ${doc.gbrain_version}, ${doc.bytes} bytes)\nsha256 ${doc.sha256}\n`);
+ } catch (e) {
+ if (!(e instanceof ResolverError)) throw e;
+ runtimeFailure(e, json);
+ }
+}
+
export async function runSkillResolver(args: string[]): Promise<void> {
const [sub, ...rest] = args;
if (sub === 'index') return runIndex(rest);
if (sub === 'resolve') return runResolve(rest);
- process.stdout.write(`${HELP_RESOLVE}\n${HELP_INDEX}`);
+ if (sub === 'library') return runLibrary(rest);
+ process.stdout.write(`${HELP_RESOLVE}\n${HELP_INDEX}\n${HELP_LIBRARY}`);
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index a3ab4602ff..2894ef13e8 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -124,7 +124,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],
- 'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--names-only', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--top-k'],
+ 'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--names-only', '--out', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--top-k'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
diff --git a/src/core/config.ts b/src/core/config.ts
index 71338af045..13459f1a8e 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -730,8 +730,8 @@ export function loadConfig(): GBrainConfig | null {
const dbUrl = effectiveEnvDatabaseUrl();
if (!fileConfig && !dbUrl) return null;
- // GBRA-377: a brain is an engine, a database or a remote endpoint; a file of file-plane settings alone (skills.resolver) is none.
- if (!dbUrl && fileConfig && !fileConfig.engine && !fileConfig.database_url && !fileConfig.database_path && !fileConfig.remote_mcp) return null;
+ // GBRA-377: a file holding only skills.resolver settings is no brain; every other file keeps its file-plane reads.
+ if (!dbUrl && fileConfig && Object.keys(fileConfig).every((k) => k === 'skills')) return null;
// Infer engine type. A DATABASE_URL-style env var is always a Postgres
// connection target and must override a file-backed PGLite engine
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 12949da14c..bf077a3753 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -743,7 +743,7 @@ export const CODES = {
skill_resolver_setup_incomplete: { class: 'caller', summary: 'gbrain setup --skill-loading resolve found no skill to index (or could not build the catalog or wire the hook), so it wrote no config keys and no hook.', docs: 'docs/guides/skill-resolver.md#skill_resolver_setup_incomplete', suggestion: 'Add a skill to one of the scanned directories (the message names them), then run setup again.' },
skill_resolver_internal: { class: 'server', summary: 'The skill resolver failed unexpectedly; a scrubbed trace (no turn text) was written under skill-index/logs/.', docs: 'docs/guides/skill-resolver.md#skill_resolver_internal', suggestion: 'Run gbrain skills index status and report the trace if it repeats.', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog and its last build error; changes nothing.' } },
skill_source_invalid: { class: 'caller', exit: 2, summary: 'The --from-json catalog or --routing file is not valid (not JSON, a malformed entry, over 10,000 skills or 8 MB, or a routing file over 1 MB), so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_invalid', suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects.' },
- skill_source_unreadable: { class: 'caller', summary: 'A --dir or --routing path does not exist or cannot be read, so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_unreadable', suggestion: 'Pass an existing directory (or file) you can read.' },
+ skill_source_unreadable: { class: 'caller', summary: 'A --dir or --routing path (or, for `gbrain skills library`, gbrain\'s own source in a compiled binary) does not exist or cannot be read, so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_unreadable', suggestion: 'Pass an existing directory (or file) you can read; for the Node library from a compiled binary, download the release asset.' },
skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },
skill_unavailable: { class: 'caller', summary: "The qualified shared skill is not in this installation's current authorized view.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
slug_page_mismatch: { class: 'caller', retryable: false, actor: 'agent',
diff --git a/src/core/skills/resolver/block.ts b/src/core/skills/resolver/block.ts
index 39351547c3..68ed2d5817 100644
--- a/src/core/skills/resolver/block.ts
+++ b/src/core/skills/resolver/block.ts
@@ -17,7 +17,7 @@ export type Harness = (typeof HARNESSES)[number];
export const BLOCK_TOKENIZER = 'gbrain-estimate-tokens-v1';
const LOAD_LINES: Record<Harness | 'default', string> = {
- 'openclaw': 'To use one, read it with skills_read (by its path, or its id) before acting.',
+ 'openclaw': 'To use one, read it with skills_read({name}) using its name before acting.',
'claude-code': 'To use one, load it with the Skill tool (by its id) before acting.',
'codex': 'To use one, open the SKILL.md at its path and follow it.',
'hermes': 'To use one, load it with skill_view(name) using its id before acting.',
diff --git a/src/core/skills/resolver/index.ts b/src/core/skills/resolver/index.ts
index 61436734d3..a49c0a88c3 100644
--- a/src/core/skills/resolver/index.ts
+++ b/src/core/skills/resolver/index.ts
@@ -11,7 +11,9 @@
* docs/schemas/skill-resolver.v1.*.json.
*/
export { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, sessionStatus, type BuildInput, type BuildReceipt, type CatalogStatus } from './build.ts';
-export { resolveSkills, normalizeTurnInput, errorTurnOutput, SCHEMA_VERSION, type Explain, type ResolveOptions, type ResolveResult, type Suggestion, type TurnInput, type TurnOutput } from './resolve.ts';
+export { resolveSkills, normalizeTurnInput, errorTurnOutput, SCHEMA_VERSION, type Explain, type MatchStrength, type ResolveOptions, type ResolveResult, type Suggestion, type TurnInput, type TurnOutput } from './resolve.ts';
+export { commitSessionAsync, type TurnDelta } from './session.ts';
+export { VERSION as GBRAIN_VERSION } from '../../../version.ts';
export { ResolverError, type ResolverErrorCode } from './errors.ts';
export { HARNESSES, BLOCK_TOKEN_CAP } from './block.ts';
export { resolverHome } from './paths.ts';
diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.ts
index e1fbe0c5be..287e6e92e1 100644
--- a/src/core/skills/resolver/resolve.ts
+++ b/src/core/skills/resolver/resolve.ts
@@ -54,7 +54,10 @@ export interface TurnInput {
reset_session?: boolean;
}
-export interface Suggestion { id: string; name: string; score: number; summary: string; reason: string; path?: string; catalog: string }
+/** The strongest way a suggestion matched the turn: named in it, then by field. A body-only match is the weakest. */
+export type MatchStrength = 'named' | 'name' | 'triggers' | 'routing' | 'description' | 'body';
+const STRENGTH_FIELDS = ['name', 'triggers', 'routing', 'description', 'body'] as const;
+export interface Suggestion { id: string; name: string; score: number; summary: string; reason: string; match_strength: MatchStrength; path?: string; catalog: string }
export interface TurnError { code: string; message: string; fix: { suggestion: string; command?: string } }
export interface TurnOutput {
schema_version: 1;
@@ -344,7 +347,9 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:
const suggestions: Suggestion[] = kept.map(x => {
const m = metaOf(x.c, x.doc);
const namesOnly = lines.find(l => l.id === m.id)!.namesOnly;
- return { id: m.id, name: m.name, score: round4(x.score), summary: namesOnly ? '' : m.summary, reason: x.explicit ? `named in the turn; ${reasonText(ranks[x.c]!.matchedFields(x.doc).fields)}` : reasonText(ranks[x.c]!.matchedFields(x.doc).fields), ...(m.path ? { path: m.path } : {}), catalog: loaded[x.c]!.name };
+ const fields = ranks[x.c]!.matchedFields(x.doc).fields;
+ const match_strength: MatchStrength = x.explicit ? 'named' : STRENGTH_FIELDS.find(f => fields[f]?.length) ?? 'body';
+ return { id: m.id, name: m.name, score: round4(x.score), summary: namesOnly ? '' : m.summary, reason: x.explicit ? `named in the turn; ${reasonText(fields)}` : reasonText(fields), match_strength, ...(m.path ? { path: m.path } : {}), catalog: loaded[x.c]!.name };
});
const out: TurnOutput = { ...base, budget_exhausted: exhausted, suggestions, block: r.block, block_tokens: r.tokens, deduped };
let explain: Explain | undefined;
diff --git a/src/version.ts b/src/version.ts
index ec56aa1fab..3a30f0b86b 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1,2 +1,2 @@
-import pkg from '../package.json';
+import pkg from '../package.json' with { type: 'json' };
export const VERSION = pkg.version;
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index a318e46f30..05f3dee335 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -997,11 +997,13 @@
],
"./skill-resolver": [
"BLOCK_TOKEN_CAP",
+ "GBRAIN_VERSION",
"HARNESSES",
"ResolverError",
"SCHEMA_VERSION",
"buildSkillIndex",
"catalogStatus",
+ "commitSessionAsync",
"errorTurnOutput",
"listCatalogs",
"normalizeTurnInput",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index e3d0db0f4c..5216e93a68 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -8770,6 +8770,13 @@
],
"name": "Explain"
},
+ {
+ "kind": "variable",
+ "name": "GBRAIN_VERSION",
+ "signature": [
+ "string"
+ ]
+ },
{
"kind": "variable",
"name": "HARNESSES",
@@ -8777,6 +8784,13 @@
"readonly [\"openclaw\", \"claude-code\", \"codex\", \"hermes\", \"qm\"]"
]
},
+ {
+ "kind": "type",
+ "name": "MatchStrength",
+ "signature": [
+ "\"body\" | \"name\" | \"description\" | \"named\" | \"triggers\" | \"routing\""
+ ]
+ },
{
"kind": "interface",
"members": [
@@ -8848,6 +8862,7 @@
"members": [
"catalog: string",
"id: string",
+ "match_strength: MatchStrength",
"name: string",
"path?: string | undefined",
"reason: string",
@@ -8856,6 +8871,16 @@
],
"name": "Suggestion"
},
+ {
+ "kind": "interface",
+ "members": [
+ "reset: boolean",
+ "resuggested: string[]",
+ "suggested: string[]",
+ "tokens: number"
+ ],
+ "name": "TurnDelta"
+ },
{
"kind": "interface",
"members": [
@@ -8908,6 +8933,13 @@
"(name: string, opts?: { home?: string; }) => Promise<CatalogStatus>"
]
},
+ {
+ "kind": "function",
+ "name": "commitSessionAsync",
+ "signature": [
+ "(home: string, key: string, delta: TurnDelta) => Promise<boolean>"
+ ]
+ },
{
"kind": "function",
"name": "errorTurnOutput",
diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.ts
index a28df84ecf..9a78e024bb 100644
--- a/test/setup-skill-resolver.test.ts
+++ b/test/setup-skill-resolver.test.ts
@@ -204,6 +204,8 @@ describe('the engine boundary with resolver-only settings', () => {
const load = () => withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => loadConfig());
write({ skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } });
expect(await load()).toBeNull();
+ write({ autopilot: { incremental_extract_include_frontmatter: true }, skills: { resolver: { enabled: true } } });
+ expect((await load())?.autopilot?.incremental_extract_include_frontmatter).toBe(true);
write({ engine: 'pglite', database_path: join(dir, '.gbrain', 'brain.pglite'), skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } });
expect((await load())?.engine).toBe('pglite');
write({ remote_mcp: { issuer_url: 'https://brain.example.invalid', mcp_url: 'https://brain.example.invalid/mcp', oauth_client_id: 'client-a' }, skills: { resolver: { enabled: true } } });
diff --git a/test/skill-resolver-cli.test.ts b/test/skill-resolver-cli.test.ts
index 20d187def3..e588bce08e 100644
--- a/test/skill-resolver-cli.test.ts
+++ b/test/skill-resolver-cli.test.ts
@@ -34,9 +34,10 @@ const SKILLS = JSON.stringify([
]);
describe('routing', () => {
- test('only skills index and skills resolve route to the resolver', () => {
+ test('only skills index, skills resolve and skills library route to the resolver', () => {
expect(routeCommand('skills', ['index', 'build']).command).toBe('skill-resolver');
expect(routeCommand('skills', ['resolve', '--text', 'x']).command).toBe('skill-resolver');
+ expect(routeCommand('skills', ['library', '--json']).command).toBe('skill-resolver');
expect(routeCommand('skills', []).command).toBe('skills');
expect(routeCommand('skills', ['--json']).command).toBe('skills');
expect(routeCommand('skills', ['list']).command).toBe('skills');
diff --git a/test/skill-resolver-packaging.test.ts b/test/skill-resolver-packaging.test.ts
index cddeeac577..b68263b86f 100644
--- a/test/skill-resolver-packaging.test.ts
+++ b/test/skill-resolver-packaging.test.ts
@@ -1,19 +1,27 @@
/**
- * GBRA-377 PR A: the skill resolver library's two published forms.
+ * GBRA-377 PR A: the skill resolver library's published forms.
*
* 1. Protects: `gbrain/skill-resolver` (the package export Bun consumers
- * import) and the dependency-free Node bundle the release attaches
- * (scripts/build-skill-resolver-bundle.ts, gbrain-skill-resolver.mjs),
- * which must import and resolve under Node with no node_modules.
- * 2. Fails when: the export path moves, or the bundle stops building or
- * running under Node (a Bun-only API, an unbundled dependency).
+ * import), the dependency-free Node bundle the release attaches with its
+ * sha256 (scripts/build-skill-resolver-bundle.ts, gbrain-skill-resolver.mjs)
+ * and `gbrain skills library`, which writes the same bundle from the
+ * installed source to a fixed path; each must import and resolve under
+ * Node with no node_modules. In CI a missing node fails instead of skipping.
+ * 2. Fails when: the export path moves, the bundle stops building or running
+ * under Node (a Bun-only API, an unbundled dependency, a JSON import
+ * without its attribute), the CLI and the release build differ, or the
+ * release stops attaching or checking the sha256.
*/
import { describe, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { createHash } from 'node:crypto';
+import { VERSION } from '../src/version.ts';
const ROOT = resolve(import.meta.dir, '..');
+const NODE = Bun.which('node');
+const needNode = !NODE && !process.env.CI;
describe('skill resolver packaging', () => {
test('the package export names the library entry point', async () => {
@@ -22,19 +30,51 @@ describe('skill resolver packaging', () => {
const viaExport = await import('gbrain/skill-resolver');
const direct = await import('../src/core/skills/resolver/index.ts');
expect(viaExport.resolveSkills).toBe(direct.resolveSkills);
+ expect(viaExport.commitSessionAsync).toBeFunction();
+ expect(viaExport.GBRAIN_VERSION).toBe(VERSION);
});
- test.skipIf(!Bun.which('node'))('the Node bundle builds, imports under node from an empty directory and resolves', () => {
+ test.skipIf(needNode)('the Node bundle builds, imports under node from an empty directory, resolves and commits', () => {
+ expect(NODE, 'node is required in CI').toBeTruthy();
const dir = mkdtempSync(join(tmpdir(), 'skres-node-'));
try {
const out = join(dir, 'gbrain-skill-resolver.mjs');
const run = Bun.spawnSync([process.execPath, 'scripts/build-skill-resolver-bundle.ts', '--out', out, '--smoke'], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
expect(run.exitCode, run.stderr.toString()).toBe(0);
- const smoke = JSON.parse(run.stdout.toString().trim().split('\n').at(-1)!) as { node: string; bundled_skills: number; top: string };
+ const smoke = JSON.parse(run.stdout.toString().trim().split('\n').at(-1)!) as { node: string; gbrain_version: string; bundled_skills: number; top: string };
expect(smoke.top).toBe('x:deploy');
+ expect(smoke.gbrain_version).toBe(VERSION);
expect(smoke.bundled_skills).toBeGreaterThan(20);
+ const sum = createHash('sha256').update(readFileSync(out)).digest('hex');
+ expect(readFileSync(`${out}.sha256`, 'utf8')).toBe(`${sum} gbrain-skill-resolver.mjs\n`);
+ const home = join(dir, 'home');
+ const cli = Bun.spawnSync([process.execPath, 'src/cli.ts', 'skills', 'library', '--json'], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, GBRAIN_HOME: home } });
+ expect(cli.exitCode, cli.stderr.toString()).toBe(0);
+ const lib = JSON.parse(cli.stdout.toString()) as { path: string; sha256: string; bytes: number; gbrain_version: string };
+ expect(lib.path).toBe(join(home, '.gbrain', 'lib', 'gbrain-skill-resolver.mjs'));
+ expect(lib.sha256).toBe(sum);
+ expect(lib.gbrain_version).toBe(VERSION);
+ const probe = Bun.spawnSync([NODE!, '--input-type=module', '-e', `const m = await import(${JSON.stringify(lib.path)}); console.log(m.GBRAIN_VERSION, typeof m.resolveSkills, typeof m.commitSessionAsync);`], { cwd: dir, stdout: 'pipe', stderr: 'pipe' });
+ expect(probe.exitCode, probe.stderr.toString()).toBe(0);
+ expect(probe.stdout.toString().trim()).toBe(`${VERSION} function function`);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}, 120_000);
+
+ test.skipIf(needNode)('the version module imports under node (JSON import attribute)', () => {
+ const run = Bun.spawnSync([NODE!, '--input-type=module', '-e', `const m = await import(${JSON.stringify(join(ROOT, 'src/version.ts'))}); console.log(m.VERSION);`], { cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
+ expect(run.exitCode, run.stderr.toString()).toBe(0);
+ expect(run.stdout.toString().trim()).toBe(VERSION);
+ });
+
+ test('the release attaches the bundle with its sha256 and checks it before publishing', () => {
+ const wf = readFileSync(join(ROOT, '.github/workflows/release.yml'), 'utf8');
+ expect(wf).toContain('gbrain-darwin-arm64,gbrain-linux-x64,gbrain-skill-resolver.mjs,gbrain-skill-resolver.mjs.sha256');
+ expect(wf).toContain('bun scripts/build-skill-resolver-bundle.ts --out bundle/gbrain-skill-resolver.mjs --smoke');
+ expect(wf).toContain('artifacts/gbrain-skill-resolver.mjs/gbrain-skill-resolver.mjs.sha256');
+ const check = wf.indexOf('sha256sum -c gbrain-skill-resolver.mjs.sha256');
+ expect(check).toBeGreaterThan(0);
+ expect(check).toBeLessThan(wf.indexOf('uses: softprops/action-gh-release'));
+ });
});
diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.ts
index 9847ded5f9..b325c2b8ab 100644
--- a/test/skill-resolver.test.ts
+++ b/test/skill-resolver.test.ts
@@ -83,6 +83,22 @@ describe('tokenizer', () => {
});
describe('turn rules', () => {
+ test('each suggestion carries its match strength: named, then the strongest matched field, body-only last', async () => {
+ const home = tmp();
+ await jsonCatalog(home, 'c', [
+ { id: 'x:alpha', name: 'alpha', description: 'Rotate the zorvek keys' },
+ { id: 'x:beta', name: 'beta', description: 'Other work', triggers: ['zorvek rollout'] },
+ { id: 'x:gamma', name: 'gamma', description: 'Other work', routing: ['zorvek audit'] },
+ { id: 'x:delta', name: 'delta', description: 'Other work', body: 'Step one: check the zorvek dashboard.' },
+ { id: 'x:zorvek', name: 'zorvek', description: 'Other work' },
+ ]);
+ const r = await resolveSkills({ message: 'zorvek', top_k: 8 }, { home });
+ const by = Object.fromEntries(r.output.suggestions.map(s => [s.id, s.match_strength]));
+ expect(by).toEqual({ 'x:zorvek': 'name', 'x:beta': 'triggers', 'x:gamma': 'routing', 'x:alpha': 'description', 'x:delta': 'body' });
+ const named = await resolveSkills({ message: 'use the delta skill for zorvek' }, { home });
+ expect(named.output.suggestions[0]).toMatchObject({ id: 'x:delta', match_strength: 'named' });
+ });
+
test('ack and no_match are the only no_skill results; short imperatives and CJK turns are ranked', async () => {
const home = tmp();
await jsonCatalog(home, 'c', [...BASIC, { id: 'x:minutes', name: 'minutes', description: '会议纪要 整理' }]);
@@ -355,7 +371,7 @@ describe('block', () => {
const root = tmp('skres-dir-');
const p = skillDir(root, 'deploy', { name: 'deploy', description: 'Ship a service to production' });
await buildSkillIndex({ catalog: 'c', dirs: [root] }, { home });
- const lines: Record<string, string> = { 'claude-code': 'Skill tool', 'codex': 'open the SKILL.md at its path', 'hermes': 'skill_view(name)', 'openclaw': 'skills_read', 'qm': 'action read' };
+ const lines: Record<string, string> = { 'claude-code': 'Skill tool', 'codex': 'open the SKILL.md at its path', 'hermes': 'skill_view(name)', 'openclaw': 'skills_read({name}) using its name', 'qm': 'action read' };
for (const [h, needle] of Object.entries(lines)) {
const r = await resolveSkills({ message: 'deploy acme-example-secret-words', harness: h }, { home });
expect(r.output.block).toContain(needle);