Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver: the top gate reads the skills it would show, GC no longer turns a delivered turn into a timeout, and setup treats a trailing-slash dir as the same dir
garrytanaa82dbc7580c
diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex 275e360603..c7eed2722d 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -213,10 +213,11 @@ as "do it again"), `previous_user_message` (`--previous`) is ranked instead.### top_gate: an experimental gate, off by default`top_gate` (`--top-gate`, `skills.resolver.top_gate`) empties the block-when the best-ranked skill's score divided by its catalog's maximum idf,-`ln(1 + (n - 0.5) / 1.5)` for a catalog of `n` skills, is below the+when the best skill the block would show (after `exclude`, pinned skills+and `min_match_strength`) has a score that, divided by its catalog's maximum+idf, `ln(1 + (n - 0.5) / 1.5)` for a catalog of `n` skills, is below thethreshold (0 to 100; unset or 0 is off). With merged catalogs it takes the-highest of each catalog's best. A skill named in the turn bypasses it. The+highest of those candidates. A skill named in the turn bypasses it. Thedivision keeps the number comparable across catalog sizes; it does not undomessage length, so long messages still score higher.diff --git a/docs/schemas/skill-resolver.v1.turn-input.json b/docs/schemas/skill-resolver.v1.turn-input.jsonindex e3952ca71a..6e0f52fc1f 100644--- a/docs/schemas/skill-resolver.v1.turn-input.json+++ b/docs/schemas/skill-resolver.v1.turn-input.json@@ -74,7 +74,7 @@"type": "number","minimum": 0,"maximum": 100,- "description": "Empty the block (block_reason weak_top_match) when the best-ranked skill's score divided by its catalog's maximum idf, ln(1 + (n - 0.5) / 1.5) for n skills, is below this; with merged catalogs, the highest of each catalog's best. A skill named in the turn bypasses it. Omit it or pass 0 to keep the gate off (the default)."+ "description": "Empty the block (block_reason weak_top_match) when the best skill the block would show (after exclude and min_match_strength) has a score that, divided by its catalog's maximum idf, ln(1 + (n - 0.5) / 1.5) for n skills, is below this; with merged catalogs, the highest of those candidates. A skill named in the turn bypasses it. Omit it or pass 0 to keep the gate off (the default)."},"reset_session": {"type": "boolean",diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.tsindex c5c73d0e86..06f0a25d42 100644--- a/src/commands/skill-resolver.ts+++ b/src/commands/skill-resolver.ts@@ -69,9 +69,10 @@ and no brain connection is needed.--min-match <s> drop candidates weaker than this match: named, name, triggers,routing, description or body (default: every match). It filters;stronger matches still fill the block, so it never empties it- --top-gate <x> empty the block when the best skill's score over its catalog's- maximum word weight is below x (0-100; default off); a skill- named in the turn bypasses it+ --top-gate <x> empty the block when the best skill it would show (after+ --exclude and --min-match) scores below x over its catalog's+ maximum word weight (0-100; default off); a skill named in the+ turn bypasses it--shadow compute the block without injecting it (block "" on stdout);--shadow-log <file> appends what would have been injected--expect-catalog <h> refuse with skill_catalog_mismatch unless the catalog hash is hdiff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.tsindex 3de08910f5..9a5e052a23 100644--- a/src/core/skills/resolver/config.ts+++ b/src/core/skills/resolver/config.ts@@ -17,8 +17,8 @@* skills.resolver.top_k suggestions per turn (1..8, default 5)* skills.resolver.min_match the weakest match_strength to suggest* (default: every match)- * skills.resolver.top_gate empty the block when the best skill's score- * over its catalog's maxIdf is below this (0..100; default off)+ * skills.resolver.top_gate empty the block when the best skill it would+ * show scores below this over its catalog's maxIdf (0..100; default off)* skills.resolver.per_harness.<harness>.{top_k,min_match,top_gate} overrides* for one harness; a key it leaves out falls back to the global one, and* an entry that is not an object (a hand-edited null) counts as unset@@ -29,7 +29,7 @@* never suggested (at most 1,024)*/import { readFileSync, statSync } from 'node:fs';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import { HARNESSES } from './block.ts';import { ResolverError } from './errors.ts';import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, TOP_GATE_MAX, TOP_K_MAX } from './limits.ts';@@ -94,7 +94,7 @@ export function validateTopGate(v: unknown, key: string): number {}export function validateSkillDirs(v: unknown, key: string): string[] {- if (Array.isArray(v) && v.length <= SKILL_DIRS_MAX && v.every(x => typeof x === 'string' && x.startsWith('/') && x.length <= 4096 && !x.includes('\0') && !x.split('/').includes('..'))) return v as string[];+ if (Array.isArray(v) && v.length <= SKILL_DIRS_MAX && v.every(x => typeof x === 'string' && x.startsWith('/') && x.length <= 4096 && !x.includes('\0') && !x.split('/').includes('..'))) return [...new Set((v as string[]).map(d => resolve(d)))];throw configInvalid(key, `must be a list of at most ${SKILL_DIRS_MAX} absolute directory paths`);}diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsindex 6df603a684..8e14e47da4 100644--- a/src/core/skills/resolver/hook-lane.ts+++ b/src/core/skills/resolver/hook-lane.ts@@ -29,9 +29,10 @@* that ends before the worker is needed terminates it. At the* deadline the main thread prints nothing and exits the process at once,* abandoning the worker, and commits no dedupe state: a commit starts only- * after the block was written, on the main thread, before the deadline. The- * commit's session GC pass is awaited before the lane returns, bounded by- * LANE_GC_FILES files and by the time left before the deadline.+ * after the block was written, on the main thread, before the deadline. Once+ * the turn is logged, the lane awaits the commit's session GC pass, bounded by+ * LANE_GC_FILES files and by the time left before the deadline; a deadline+ * that lands during it exits without changing the logged outcome.** One owner per event: like the harness, plugin and turn-rule lanes, it parses* the carriers the harness merges (Claude Code: managed settings, the@@ -101,7 +102,7 @@ const CONFIG_CAP_BYTES = 1024 * 1024;const SPAWN_INTERVAL_MS = 60_000;/** Time kept back from the worker's own deadline for delivery and the commit. */const COMMIT_RESERVE_MS = 10;-/** Time kept back from the deadline after the session GC pass, for the lane log and the exit. */+/** Time kept back from the deadline after the session GC pass, for the exit. */const GC_RESERVE_MS = 5;export type LaneHarness = 'claude-code' | 'codex' | 'hermes';@@ -297,9 +298,11 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,(io.exit ?? ((c: number) => process.exit(c)))(0);return 0;}- clearTimeout(timer);void ctl.worker?.terminate();if (result.outcome !== 'off' && result.outcome !== 'yield') await log(result);+ const gcDone = env.GBRAIN_TEST_SKILL_LANE_STALL === 'gc' ? new Promise<void>(() => {}) : sessionGcSettled();+ if ((await Promise.race([gcDone, deadline])) === 'deadline') (io.exit ?? ((c: number) => process.exit(c)))(0);+ clearTimeout(timer);return 0;}@@ -366,7 +369,6 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarif (posted.pending && !ctl.expired) {const gc = { files: LANE_GC_FILES, until: performance.now() + deadlineMs - elapsed() - GC_RESERVE_MS };await commitSessionAsync(home, posted.pending.key, posted.pending.delta, ctl.commit, gc);- await sessionGcSettled();}return { outcome, catalogs };}diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex ff618e7fb3..dde51d9c52 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -22,9 +22,9 @@* min_match_strength drops weaker matches before the cut to k, so a floor* never shrinks the block below what the stronger matches fill: it filters* candidates and does not gate the block. top_gate (off unless set) does:- * when the best-ranked skill's score over its catalog's maxIdf is below it,- * the block is empty (block_reason weak_top_match), unless the turn names a- * skill. A message that matches no catalog word falls back to+ * when the best skill the block would show (after exclude and+ * min_match_strength) scores below it over its catalog's maxIdf, the block is+ * empty (block_reason weak_top_match), unless the turn names a skill. A message that matches no catalog word falls back to* previous_user_message.*/import { existsSync, readFileSync, statSync } from 'node:fs';@@ -382,8 +382,8 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:const resuggested: string[] = [];const deduped: string[] = [];let paced = false;- const gated = input.top_gate !== undefined && !window.some(x => x.explicit)- && Math.max(...ranks.map((r, c) => (r.ranked[0] ? r.ranked[0].score / maxIdf(loaded[c]!.ix.n) : 0))) < input.top_gate;+ const gated = input.top_gate !== undefined && window.length > 0 && !window.some(x => x.explicit)+ && Math.max(...window.map(x => x.score / maxIdf(loaded[x.c]!.ix.n))) < input.top_gate;if (budget > 0 && window.length && spentFrac >= 0.5 && !strong(window[0]!)) paced = true;if (!paced && !gated) {window.forEach((x, i) => {diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.tsindex 74538d0903..5d146309ab 100644--- a/test/setup-skill-resolver.test.ts+++ b/test/setup-skill-resolver.test.ts@@ -310,6 +310,19 @@ describe('per_harness.<harness>.dirs: extra skill directories setup keeps', () =expect(receipt(b).catalog.source.dirs).toEqual([HARNESS['claude-code'].skills(b)]);});+ test('a hand-edited dir with a trailing or doubled slash is the same directory: one source dir, and a re-run keeps the catalog', async () => {+ const b = box();+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ const extra = join(b.root, 'shared-skills');+ skill(extra, 'citation-fixer', 'Fix broken citations across brain pages.');+ mkdirSync(gb(b), { recursive: true });+ writeFileSync(configPath(b), JSON.stringify({ skills: { resolver: { per_harness: { 'claude-code': { dirs: [`${extra}/`, extra.replace('/shared-skills', '//shared-skills')] } } } } }));+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(receipt(b).catalog.source.dirs).toEqual([HARNESS['claude-code'].skills(b), extra]);+ const again = await setup(b, 'claude-code', ['--skill-loading', 'resolve']);+ expect(again.stdout).toMatch(/keep\s+resolver catalog: 2 skills/);+ });+test('refused: a relative or .. path, more than 32 dirs, and a harness setup does not build a catalog for', async () => {const b = box();for (const [key, value, needle] of [diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsindex 423b1778d5..17823f857c 100644--- a/test/skill-resolver-hook-lane.test.ts+++ b/test/skill-resolver-hook-lane.test.ts@@ -300,6 +300,20 @@ describe('skill-resolver lane: session GC before the process exits', () => {});});+describe('skill-resolver lane: a deadline during the session GC pass', () => {+ test('the delivered turn is logged as delivered, the process still exits at the deadline, and the commit landed', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const r = await hook(b, cmd, { prompt: 'please deploy the widget to staging', session_id: 'sess-gc-stall' }, { GBRAIN_TEST_SKILL_LANE_STALL: 'gc', GBRAIN_TEST_SKILL_LANE_DEADLINE_MS: '3000' });+ expect(r.exitCode).toBe(0);+ expect(contextOf(r)).toContain('id: "deploy-widget"');+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'delivered' });+ expect(sessions(b).filter((s) => s.endsWith('.json'))).toHaveLength(1);+ });+});+describe('skill-resolver lane: a deadline during the dedupe commit', () => {for (const stall of ['commit-held', 'commit-written'] as const) {test(`${stall}: the exit releases the session lease and removes the temp file, so the next turn commits`, async () => {diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.tsindex 9a26308318..e41122d30a 100644--- a/test/skill-resolver.test.ts+++ b/test/skill-resolver.test.ts@@ -132,6 +132,20 @@ describe('turn rules', () => {expect(named.output.suggestions[0]).toMatchObject({ id: 'gbrain:deploy', match_strength: 'named' });});+ test('top_gate reads the best skill the block would show: an excluded top skill does not open it, and an empty window stays filtered', async () => {+ const home = tmp();+ await jsonCatalog(home, 'c', BASIC);+ const open = await resolveSkills({ message: 'weekly meeting notes' }, { home });+ const [top, second] = open.output.suggestions;+ expect(second!.score).toBeLessThan(top!.score);+ const gate = (top!.score + second!.score) / 2 / maxIdf(BASIC.length);+ expect((await resolveSkills({ message: 'weekly meeting notes', top_gate: gate }, { home })).output.suggestions[0]!.id).toBe(top!.id);+ const excluded = await resolveSkills({ message: 'weekly meeting notes', exclude: [top!.id], top_gate: gate }, { home });+ expect([excluded.output.suggestions, excluded.output.block_reason]).toEqual([[], 'weak_top_match']);+ const none = await resolveSkills({ message: 'weekly meeting notes', exclude: open.output.suggestions.map(s => s.id), top_gate: 0.0001 }, { home });+ expect(none.output.block_reason).toBe('filtered');+ });+test('top_gate reads the same at any catalog size: the score is divided by the maxIdf of its own catalog', async () => {const home = tmp();const pad = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `p:${word(i, 3)}`, name: word(i, 3), description: Array.from({ length: 8 }, (_, s) => word(i, 5 + s)).join(' ') }));