Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Hermes: setup turns on the skill resolver, with compaction reset and owner senders

garrytan8889b264be46
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 927b2836bc..86da4d739c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+### Hermes can turn on the skill resolver with one setup command
+
+**`gbrain setup hermes --skill-loading resolve` now wires the skill resolver into Hermes the way it already does for Claude Code and Codex.** Before, Hermes users built the catalog, edited `config.json` and pasted the hook by hand.
+
+- Setup builds the `hermes-user` catalog from `$HERMES_HOME/skills` (nested category folders included) and adds the resolver's `pre_llm_call` entry to gbrain's marked `hooks:` block in `$HERMES_HOME/config.yaml`, approving it in Hermes's `shell-hooks-allowlist.json`. The block also carries the brain-first turn rule. Each feature adds and removes only its own entry: `--no-instructions` keeps the resolver, `--skill-loading off` keeps the turn rule, and the block goes when its last entry does. An existing install's turn-rule block is left byte for byte as it was.
+- The command runs without a shell, the way Hermes runs hooks: `/usr/bin/env GBRAIN_HOOK_LANE=skill-resolver <launcher> <gbrain> hook user-prompt --harness hermes`.
+- If your config.yaml already has its own `hooks:` section, setup refuses and prints the entry to paste under it. Once you paste it, the next run approves and keeps it. A Hermes with no SOUL.md still gets the resolver.
+- Hermes compacts conversations in place and tells hooks nothing about it. The lane now starts a session's dedupe fresh on a first turn, or when the conversation history is shorter than it was on the last turn, so skills offered before a compaction can be offered again. It reads the history's length in the same streaming pass, so a large history still costs about one JSON parse.
+- `gbrain config set skills.resolver.per_harness.hermes.owner_sender_ids <id>,<id>` limits suggestions to turns from those senders, using the same rule as the OpenClaw plugin: a turn from anyone else, or with no sender, gets no block.
+- Pinned skills for Hermes (`gbrain skills pin add <id> --catalog hermes-user`) go in a marked block in `$HERMES_HOME/SOUL.md` while the resolver is on. With no pins there is no block, and SOUL.md is never created.
+- `gbrain doctor`'s `skill_resolver` check now covers Hermes, and warns when Hermes's allowlist no longer approves the hook.
+
## [0.60.699.0] - 2026-11-12
### The Ubicloud gate VMs run a current git
diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.md
index fbb893ee4b..08261c0fd7 100644
--- a/docs/guides/skill-resolver.md
+++ b/docs/guides/skill-resolver.md
@@ -9,7 +9,7 @@ model.
- **Off by default.** Nothing changes until you build a catalog and wire a
harness to call `gbrain skills resolve`, or turn on the hook lane with
- `gbrain setup <claude-code|codex> --skill-loading resolve` (OpenClaw: the
+ `gbrain setup <claude-code|codex|hermes> --skill-loading resolve` (OpenClaw: the
plugin below). Setup writes nothing for it otherwise.
- **Local and deterministic.** Word matching (BM25F) over the catalog's names,
descriptions, triggers, routing rows and the first 4 KB of each body. No
@@ -94,21 +94,37 @@ per-turn hook that puts the block in front of the model on every prompt:
`--dry-run` lists every write, and re-running changes nothing. A bare
`gbrain setup <harness>` refreshes a lane that is on.
-**Hermes** runs the same lane as a `pre_llm_call` shell hook. Hermes splits
-the command without a shell and needs its first word to be a path that
-exists, so pass the environment through `/usr/bin/env` and name gbrain by its
-absolute path:
-`/usr/bin/env GBRAIN_HOOK_LANE=skill-resolver /abs/path/to/gbrain hook user-prompt --harness hermes`.
-Setup does not wire it yet, so build `hermes-user` yourself
-(`gbrain skills index build --catalog hermes-user --dir ~/.hermes/skills
---harness hermes`), add `hermes` to `skills.resolver.harnesses` in
-`~/.gbrain/config.json` by hand (`gbrain config set` refuses that key, which
-setup owns) and set `skills.resolver.enabled` to `true` there; the lane is
-off without it. Doctor's `skill_resolver` check does not cover Hermes yet. The lane
-reads `extra.user_message`, `session_id` and `cwd` from the hook's stdin and
-answers `{"context": "<block>"}`. Hermes sends the whole conversation history
-on every turn, so the lane streams stdin and keeps only those three strings
-(each capped at 8 KB): a history of any size is read, never refused.
+**Hermes**: `gbrain setup hermes --skill-loading resolve` builds `hermes-user`
+from `$HERMES_HOME/skills` (nested category folders included) and adds the
+lane's `pre_llm_call` entry to gbrain's marked `hooks:` block in
+`$HERMES_HOME/config.yaml`, the same block that carries the brain-first turn
+rule, approving it in `shell-hooks-allowlist.json`. Each lane owns only its
+own entry: `--no-instructions` drops the turn rule and keeps the resolver,
+`--skill-loading off` the reverse, and the block goes with its last entry.
+Hermes splits the command like a shell would but runs no shell, so it starts
+with `/usr/bin/env`:
+`/usr/bin/env GBRAIN_HOOK_LANE=skill-resolver <launcher> /abs/path/to/gbrain hook user-prompt --harness hermes`.
+When config.yaml already has a `hooks:` section of yours, setup refuses with
+the entry to paste under it; once pasted, the next run approves and keeps it.
+A Hermes with no SOUL.md still gets the resolver. `hermes hooks doctor` checks
+the entry on the Hermes host, and gbrain's doctor `skill_resolver` check
+covers Hermes.
+
+The lane reads `extra.user_message`, `session_id`, `cwd`, `extra.sender_id`,
+`extra.is_first_turn` and the length of `extra.conversation_history` from
+the hook's stdin and answers `{"context": "<block>"}`. Hermes sends the whole
+conversation history on every turn, so the lane streams stdin and keeps only
+those fields (each string capped at 8 KB): a history of any size is read,
+never refused. Hermes compacts in place, keeping the session id, and tells
+hooks nothing, so a first turn, or a history shorter than the last turn saw,
+starts the session's dedupe fresh. To show suggestions only on turns from
+some senders (a group chat), list them:
+`gbrain config set skills.resolver.per_harness.hermes.owner_sender_ids <id>,<id>`;
+a turn from anyone else, or with no sender, then gets no block.
+
+Pinned skills for Hermes (`gbrain skills pin add <id> --catalog hermes-user`)
+go in a marked block in `$HERMES_HOME/SOUL.md` while the lane is on, so every
+turn sees them; with no pins there is no block, and SOUL.md is never created.
The lane runs the resolver in the hook process (never through `gbrain serve`),
so it works with serve down and with no brain. Each block names the skill ids
@@ -146,7 +162,7 @@ The lane always exits 0 and prints nothing when it cannot deliver:
- **Compaction:** a SessionStart with `source: compact` (Claude Code, and Codex
0.165 and later) resets the session, so skills can be offered again. A Codex
install from before gets the SessionStart group on its next setup run.
- Hermes has no compaction event yet.
+ Hermes sends no compaction event; the lane resets a session when its history shrinks or on a first turn.
Each turn appends one line (outcome, error code, duration, catalogs; never
turn text) to `skill-index/logs/lane-<UTC date>.jsonl`, one file per day,
diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.ts
index 4298d1b98e..d8c4d96796 100644
--- a/src/commands/doctor/checks/skill-resolver.ts
+++ b/src/commands/doctor/checks/skill-resolver.ts
@@ -1,8 +1,8 @@
/**
* `skill_resolver` (GBRA-377 PR B): the skill-resolver hook lane that
- * `gbrain setup <claude-code|codex> --skill-loading resolve` turns on
+ * `gbrain setup <claude-code|codex|hermes> --skill-loading resolve` turns on
* (src/core/skills/resolver/hook-lane.ts). Per harness it reports the lane's
- * hook (wired, untrusted in Codex, outdated when it predates the SessionStart
+ * hook (wired, untrusted in Codex or unapproved in Hermes, outdated when it predates the SessionStart
* compaction reset, or missing), each catalog's freshness
* (the content tier: source re-read, index re-hashed) and the recent
* outcomes and error codes from the lane log. It emits nothing when the
@@ -24,7 +24,7 @@ import { inspectSkillResolverHook, type ResolverHarness, type ResolverHookState
import { describeOpenclawSkill, openclawSkillView, type OpenclawSkillView } from './skill-resolver-openclaw.ts';
const name = 'skill_resolver';
-const HARNESSES: ResolverHarness[] = ['claude-code', 'codex'];
+const HARNESSES: ResolverHarness[] = ['claude-code', 'codex', 'hermes'];
/** Lane-log lines doctor reads (the newest), and the tail it reads them from. */
const RECENT_LINES = 200;
const LOG_TAIL_BYTES = 64 * 1024;
@@ -105,12 +105,12 @@ export function skillResolverCheck(v: SkillResolverView | null): Check | null {
return { name, status: 'warn', message: `${describeSkillResolver(v)} The hook lane prints nothing until it can read it.`, details: { ...details, code: 'skill_resolver_config_unreadable' },
fix: { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(name), docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable',
why: 'gbrain never rewrites a config file it cannot parse; the lane and setup leave it alone.',
- user_message: `gbrain's config file (${join(configDir(), 'config.json')}) is not valid JSON, so the skill resolver is paused. Fix or move it, then run: gbrain setup <claude-code|codex> --skill-loading resolve` } };
+ user_message: `gbrain's config file (${join(configDir(), 'config.json')}) is not valid JSON, so the skill resolver is paused. Fix or move it, then run: gbrain setup <claude-code|codex|hermes> --skill-loading resolve` } };
}
const broken = v.harnesses.find((h) => h.on && (h.hook !== 'wired' || !h.catalogs.some((c) => isTurnCatalog(h.harness, c.name))));
if (broken) {
const what = broken.hook === 'outdated' ? `its hook has no SessionStart entry (installed before the compaction reset), so skills offered before a compaction are not offered again; ${setupArgv(broken.harness).join(' ')} adds it`
- : `${broken.hook === 'untrusted' ? 'its Codex hook is not trusted' : broken.hook === 'absent' ? 'its hook entry is missing' : 'its user catalog is missing'}, so no skills block is added`;
+ : `${broken.hook === 'untrusted' ? (broken.harness === 'hermes' ? 'its Hermes hook is not approved in shell-hooks-allowlist.json (hermes hooks doctor shows it)' : 'its Codex hook is not trusted') : broken.hook === 'absent' ? 'its hook entry is missing' : 'its user catalog is missing'}, so no skills block is added`;
return { name, status: 'warn', message: `${describeSkillResolver(v)} ${broken.harness}: the resolver is on but ${what}.`, details,
fix: { argv: setupArgv(broken.harness), consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(name),
why: `Rebuilds the ${broken.harness} user catalog and rewrites only the skill-resolver hook entry; --skill-loading off removes it instead.` } };
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index af350b6636..9f31fbc8bd 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -43,6 +43,7 @@ import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE, registrationA
import { hookLauncherPath } from '../core/setup/hook-launcher.ts';
import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';
import { describeResolverSetup, removeSkillResolverSetup, syncSkillResolverSetup, type ResolverSetupResult } from '../core/setup/skill-resolver-setup.ts';
+import type { ResolverHarness } from '../core/setup/skill-resolver-hook.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { peekLock } from '../core/pglite-lock.ts';
import { claudePluginProvidesName, codexPluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';
@@ -181,10 +182,11 @@ Flags:
gbrain's bundled skills beside the brain-first block (about
1.5k tokens) and loads a skill's full text only when a task
matches (gbrain bundled-skill <name>, from this gbrain).
- resolve (claude-code, codex) indexes the harness's own skills
- (~/.claude/skills; Codex: ~/.agents/skills, CODEX_HOME/skills)
- and adds a separate per-turn hook that names the few skills
- that fit each prompt (word match; nothing leaves the machine).
+ resolve (claude-code, codex, hermes) indexes the harness's own
+ skills (~/.claude/skills; Codex: ~/.agents/skills,
+ CODEX_HOME/skills; Hermes: $HERMES_HOME/skills) and adds a
+ separate per-turn hook that names the few skills that fit
+ each prompt (word match; nothing leaves the machine).
off removes what an earlier run wrote. The
choice is remembered; GBRAIN_SKILL_LOADING sets it too.
--skills-index-only Refresh every skills index recorded for this harness (its
@@ -300,8 +302,8 @@ function parseFlags(args: string[]): SetupFlags | string {
const envLoading = process.env[SKILL_LOADING_ENV]?.trim();
if (flagLoading === undefined && envLoading && envLoading !== 'resolve' && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;
const openclaw = positionals[0] === 'openclaw';
- const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || openclaw;
- if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex and OpenClaw (claude-code, codex, openclaw); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';
+ const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || positionals[0] === 'hermes' || openclaw;
+ if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex, Hermes and OpenClaw (claude-code, codex, hermes, openclaw); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';
if (flagLoading === 'shadow' && !openclaw) return '--skill-loading shadow is for openclaw only (it resolves and logs each turn without showing the model anything)';
const agentFlags = args.flatMap((a, i) => (a === '--agent' ? [args[i + 1] ?? ''] : []));
if (agentFlags.some((a) => !/^[\w.@:-]{1,128}$/.test(a))) return '--agent needs an OpenClaw agent id';
@@ -902,12 +904,12 @@ function removeSkillsFor(harness: BrainFirstHarness, where: { scope?: WiringScop
}
/**
- * The skill-resolver lane for this run (claude-code, codex): --skill-loading
+ * The skill-resolver lane for this run (claude-code, codex, hermes): --skill-loading
* resolve turns it on, off or spring turns it off, and with no choice a lane
* that is on is refreshed. Null when there is nothing to do, so an install
* that never turned it on gets no new output.
*/
-async function resolverFor(harness: SetupHarnessId, flags: SetupFlags, launcher: string): Promise<ResolverSetupResult | null> {
+async function resolverFor(harness: ResolverHarness, flags: SetupFlags, launcher: string): Promise<ResolverSetupResult | null> {
const home = configDir();
if (flags.skillResolver === 'off' || (flags.remove && flags.skillResolver !== 'on')) return removeSkillResolverSetup({ harness, home, dryRun: flags.dryRun });
const cfg = readResolverConfig(home);
@@ -1025,7 +1027,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
// Loud failure: an accepted install whose per-turn hook does not load exits non-zero and names the harness's own check.
// A 'print' outcome installed nothing and already names the step that does, so it is reported, not verified.
const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;
- const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;
+ const resolver = harness === 'claude-code' || harness === 'codex' || harness === 'hermes' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;
const skillPlugin = harness === 'openclaw' ? await openclawSkillFor(flags) : null;
const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) || resolver?.error ? 1 : 0;
if (out.json) {
@@ -1054,7 +1056,7 @@ async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number>
return refuse(opError('invalid_params', `--skills-index-only needs a harness with an instruction file: ${BRAIN_FIRST_HARNESSES.join(', ')}`, 'Pass the harness whose skills index to refresh, e.g. gbrain setup claude-code --skills-index-only.'), out);
}
const outcomes = refreshSkillsIndexes(harness, { mode: flags.skillLoading, launcher: flags.gbrainBin, dryRun: flags.dryRun });
- const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;
+ const resolver = harness === 'claude-code' || harness === 'codex' || harness === 'hermes' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;
const skillPlugin = harness === 'openclaw' ? await openclawSkillFor(flags, true) : null;
const code = outcomes.some((o) => o.action === 'preserve') || resolver?.error ? 1 : 0;
if (out.json) {
diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.ts
index 934d081703..c9e538f4ae 100644
--- a/src/commands/skill-resolver.ts
+++ b/src/commands/skill-resolver.ts
@@ -24,9 +24,11 @@ import {
ResolverError, HARNESSES, errorTurnOutput, GBRAIN_VERSION, type BuildInput, type TurnInput,
} from '../core/skills/resolver/index.ts';
import { validCatalogName } from '../core/skills/resolver/paths.ts';
-import { readResolverConfig } from '../core/setup/skill-resolver-config.ts';
+import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';
import { catalogSkillIds, pinProblem, PINS_MAX, readPins, renderPinnedBlock, writePins } from '../core/setup/skill-pins.ts';
import { refreshOpenclawPins } from '../core/setup/openclaw-skill-plugin.ts';
+import { HERMES_PINS_CATALOG, syncHermesPins } from '../core/setup/hermes-skill-pins.ts';
+import { hermesHomeDir } from '../core/setup/skill-resolver-hook.ts';
const HELP_INDEX = `Usage: gbrain skills index <build|status|remove> [options]
@@ -345,14 +347,17 @@ async function runPin(args: string[]): Promise<void> {
}
writePins(read, catalog, pins);
}
- const rendered = renderPinnedBlock(pins, { harness: catalog.startsWith('openclaw-') ? 'openclaw' : undefined, known: catalogSkillIds(home, catalog) });
+ const rendered = renderPinnedBlock(pins, { harness: catalog.startsWith('openclaw-') ? 'openclaw' : catalog === HERMES_PINS_CATALOG ? 'hermes' : undefined, known: catalogSkillIds(home, catalog) });
const agents = sub === 'list' ? [] : refreshOpenclawPins(home);
- const doc = { catalog, pins, rendered: rendered.ids, unknown: rendered.unknown, cut: rendered.cut, block_tokens: rendered.tokens, ...(agents.length ? { openclaw_agents_updated: agents } : {}) };
+ const hermesOn = catalog === HERMES_PINS_CATALOG && sub !== 'list' && resolverHarnesses(read.state === 'ok' ? read.doc : null).includes('hermes');
+ const soul = hermesOn ? syncHermesPins({ home, hermesHome: hermesHomeDir(), dryRun: false }) : null;
+ const doc = { catalog, pins, rendered: rendered.ids, unknown: rendered.unknown, cut: rendered.cut, block_tokens: rendered.tokens, ...(agents.length ? { openclaw_agents_updated: agents } : {}), ...(soul ? { hermes_soul: soul } : {}) };
if (json) { await write(`${JSON.stringify(doc)}\n`); return; }
await write([
pins.length ? `${catalog}: ${pins.length} pin(s)` : `${catalog}: no pins`,
...pins.map((x) => ` ${x.name}${x.line ? ` — ${x.line}` : ''}${rendered.unknown.includes(x.name) ? ' (not in the catalog: left out, skill_resolver_pin_unknown)' : rendered.cut.includes(x.name) ? ' (over the token cap: left out)' : ''}`),
agents.length ? `OpenClaw agent(s) ${agents.join(', ')} use the new pins from their next turn.` : '',
+ soul ? `Hermes: ${soul.action} ${soul.detail}${soul.action === 'skip' ? '' : '; Hermes reads SOUL.md at session start'}.` : '',
].filter(Boolean).join('\n') + '\n');
}
diff --git a/src/core/setup/hermes-skill-pins.ts b/src/core/setup/hermes-skill-pins.ts
new file mode 100644
index 0000000000..23bbf1e252
--- /dev/null
+++ b/src/core/setup/hermes-skill-pins.ts
@@ -0,0 +1,46 @@
+/**
+ * hermes-skill-pins.ts — the operator's pinned skills for Hermes (catalog
+ * hermes-user, `gbrain skills pin --catalog hermes-user`) as a marked block
+ * in $HERMES_HOME/SOUL.md, Hermes's system prompt. The resolver's per-turn
+ * hook adds only suggestions for that turn, so the pins go where every turn
+ * sees them. gbrain ships no pins: with none the block is absent.
+ *
+ * SOUL.md is Hermes's file and is never created here; text outside the
+ * markers is never touched, and damaged markers leave the file as it is.
+ * Written by `gbrain setup hermes --skill-loading resolve` and by
+ * `gbrain skills pin` while the lane is on for Hermes; removed with the lane.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
+import { writeUnlessChanged } from './brain-first.ts';
+import { pinnedBlockFor } from './skill-pins.ts';
+
+const MARKERS: BlockMarkers = { begin: '<!-- gbrain:skill-pins:begin -->', end: '<!-- gbrain:skill-pins:end -->', label: 'skill-pins', rerun: 'gbrain setup hermes --skill-loading resolve' };
+export const HERMES_PINS_CATALOG = 'hermes-user';
+
+export interface HermesPinsOutcome { action: 'write' | 'keep' | 'remove' | 'skip'; path: string; detail: string; ids: string[] }
+
+/** Make SOUL.md's pinned block match the pins (or, with off, strip it). Null when there is nothing either way. Never throws. */
+export function syncHermesPins(opts: { home: string; hermesHome: string; off?: boolean; dryRun: boolean }): HermesPinsOutcome | null {
+ const path = join(opts.hermesHome, 'SOUL.md');
+ const pins = opts.off ? { block: '', ids: [] as string[] } : pinnedBlockFor(opts.home, HERMES_PINS_CATALOG, 'hermes');
+ try {
+ if (!existsSync(path)) return pins.block ? { action: 'skip', path, detail: `${path} does not exist, so the ${pins.ids.length} pinned skill(s) were not placed; start Hermes once (it writes SOUL.md) and run setup again`, ids: [] } : null;
+ const text = readFileSync(path, 'utf8');
+ const probe = probeBlock(MARKERS, text);
+ if (probe.state === 'damaged') return { action: 'skip', path, detail: `the gbrain skill-pins markers in ${path} are damaged; fix or delete them and run setup again`, ids: [] };
+ if (!pins.block) {
+ if (probe.state !== 'present') return null;
+ if (!opts.dryRun) writeUnlessChanged(path, text, false, removeBlock(MARKERS, text).text);
+ return { action: 'remove', path, detail: `pinned skills block from ${path}`, ids: [] };
+ }
+ const next = spliceBlock(MARKERS, text, pins.block);
+ const detail = `${pins.ids.length} pinned skill(s) (${pins.ids.join(', ')}) in ${path}`;
+ if (next === text) return { action: 'keep', path, detail, ids: pins.ids };
+ if (!opts.dryRun) writeUnlessChanged(path, text, false, next);
+ return { action: 'write', path, detail, ids: pins.ids };
+ } catch (e) {
+ return { action: 'skip', path, detail: `pinned skills in ${path} left as they are (${(e as Error).message})`, ids: [] };
+ }
+}
diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.ts
index a230c35045..2502c39500 100644
--- a/src/core/setup/hermes-turn-hook.ts
+++ b/src/core/setup/hermes-turn-hook.ts
@@ -14,6 +14,13 @@
* records the approval for this exact command in Hermes's own allowlist, the
* way `gbrain setup codex` writes its hook trust entries. Removal strips the
* block and that approval.
+ *
+ * The same block also carries the skill-resolver lane's entry
+ * (`gbrain setup hermes --skill-loading resolve`, skill-resolver-hook.ts):
+ * config.yaml can hold one top-level `hooks:` key, so both lanes share one
+ * marked block, each entry with its own approval. Each lane writes and removes
+ * only its own entry, so declining the brain-first rule keeps the resolver
+ * and the reverse; the block goes when its last entry does.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
@@ -22,6 +29,7 @@ import { acquireNativeLockSync } from '../persistence/native-lock.ts';
import { loadBoundedYaml } from '../data-frontmatter.ts';
import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
import { renderBrainFirstTurnRule, writeUnlessChanged, type BrainFirstAccess } from './brain-first.ts';
+import { isSkillResolverCommand } from './skill-resolver-lane.ts';
const MARKERS: BlockMarkers = { begin: '# gbrain:turn-rule:begin', end: '# gbrain:turn-rule:end', label: 'turn-rule', rerun: 'gbrain setup hermes --instructions-only' };
const EVENT = 'pre_llm_call';
@@ -34,13 +42,29 @@ export function hermesTurnHookCommand(access: BrainFirstAccess): string {
return `/bin/echo '${JSON.stringify({ context: renderBrainFirstTurnRule(access, 'hermes') }).replace(/'/g, '\\u0027')}'`;
}
-const commandIn = (interior: string | undefined): string | null => {
- const quoted = /command: (".*")/.exec(interior ?? '')?.[1];
- return quoted ? (JSON.parse(quoted) as string) : null;
+/** The lanes that own an entry in gbrain's block, in the order the block lists them, with each entry's timeout. */
+export type HermesHookLane = 'turn-rule' | 'skill-resolver';
+const LANES: Record<HermesHookLane, { timeout: number; what: string }> = {
+ 'turn-rule': { timeout: 10, what: 'per-turn rule hook' },
+ 'skill-resolver': { timeout: 15, what: 'skill-resolver lane hook' },
};
+const laneOf = (command: string): HermesHookLane => (isSkillResolverCommand(command) ? 'skill-resolver' : 'turn-rule');
+
+/** Each lane's command in the block (the first entry of each lane). */
+function entriesIn(interior: string | undefined): Partial<Record<HermesHookLane, string>> {
+ const out: Partial<Record<HermesHookLane, string>> = {};
+ for (const m of (interior ?? '').matchAll(/command: (".*")/g)) {
+ const command = JSON.parse(m[1]!) as string;
+ out[laneOf(command)] ??= command;
+ }
+ return out;
+}
+
+const commandIn = (interior: string | undefined): string | null => entriesIn(interior)['turn-rule'] ?? null;
-function hookYaml(command: string): string {
- return `hooks:\n ${EVENT}:\n - command: ${JSON.stringify(command)}\n timeout: 10\n`;
+function hooksYaml(entries: Partial<Record<HermesHookLane, string>>): string {
+ const items = (Object.keys(LANES) as HermesHookLane[]).flatMap((lane) => (entries[lane] ? [` - command: ${JSON.stringify(entries[lane])}\n timeout: ${LANES[lane].timeout}\n`] : []));
+ return `hooks:\n ${EVENT}:\n${items.join('')}`;
}
interface Allowlist { approvals: Array<Record<string, unknown>> }
@@ -93,9 +117,26 @@ function revoke(hermesHome: string, command: string): void {
/** Write or update the hook (accepted decision). Never throws: anything gbrain cannot edit safely is printed to add by hand. */
export function syncHermesTurnHook(opts: { hermesHome: string; access: BrainFirstAccess; dryRun: boolean }): HermesTurnHookOutcome {
+ return syncHermesHook({ hermesHome: opts.hermesHome, lane: 'turn-rule', command: hermesTurnHookCommand(opts.access), dryRun: opts.dryRun });
+}
+
+/** A `pre_llm_call` entry with exactly this command in config.yaml outside gbrain's block (pasted by hand from a printed snippet). */
+function pastedIn(doc: Record<string, unknown> | null | undefined, command: string): boolean {
+ const entries = (doc?.hooks as Record<string, unknown> | undefined)?.[EVENT];
+ return Array.isArray(entries) && entries.some((e) => (e as { command?: unknown } | null)?.command === command);
+}
+
+/**
+ * Write or update one lane's entry in gbrain's block, keeping the other
+ * lane's. Never throws: anything gbrain cannot edit safely is printed to add
+ * by hand. The resolver's entry pasted by hand under the user's own `hooks:`
+ * (the printed snippet) is kept and approved.
+ */
+export function syncHermesHook(opts: { hermesHome: string; lane: HermesHookLane; command: string; dryRun: boolean }): HermesTurnHookOutcome {
const path = join(opts.hermesHome, 'config.yaml');
- const command = hermesTurnHookCommand(opts.access);
- const print = (why: string): HermesTurnHookOutcome => ({ action: 'print', path, detail: `${why}; add this to ${path} and approve it when Hermes asks (non-interactive runs: HERMES_ACCEPT_HOOKS=1)`, snippet: hookYaml(command) });
+ const { command, lane } = opts;
+ const what = LANES[lane].what;
+ const print = (why: string): HermesTurnHookOutcome => ({ action: 'print', path, detail: `${why}; add this to ${path} and approve it when Hermes asks (non-interactive runs: HERMES_ACCEPT_HOOKS=1)`, snippet: hooksYaml({ [lane]: command }) });
if (!existsSync(opts.hermesHome)) return print(`${opts.hermesHome} does not exist yet`);
try {
const missing = !existsSync(path);
@@ -105,22 +146,28 @@ export function syncHermesTurnHook(opts: { hermesHome: string; access: BrainFirs
if (probe.state === 'absent') {
const doc = loadBoundedYaml(text) as Record<string, unknown> | null | undefined;
if (doc !== null && doc !== undefined && typeof doc !== 'object') return print('config.yaml is not a YAML mapping');
+ if (doc && lane === 'skill-resolver' && pastedIn(doc as Record<string, unknown>, command)) {
+ readAllowlist(join(opts.hermesHome, ALLOWLIST));
+ if (!opts.dryRun) approve(opts.hermesHome, command);
+ return { action: 'keep', path, detail: `${what} (${EVENT}) in ${path}, added by hand` };
+ }
if (doc && 'hooks' in doc) return print('config.yaml already has a hooks: section, which gbrain does not edit');
}
readAllowlist(join(opts.hermesHome, ALLOWLIST));
- const next = spliceBlock(MARKERS, text, hookYaml(command));
+ const entries = entriesIn(probe.interior);
+ const next = spliceBlock(MARKERS, text, hooksYaml({ ...entries, [lane]: command }));
if (probe.state === 'absent' && !(loadBoundedYaml(next) as Record<string, unknown> | null)?.hooks) return print('config.yaml would not parse with the hook appended');
if (next === text) {
if (!opts.dryRun) approve(opts.hermesHome, command);
- return { action: 'keep', path, detail: `per-turn rule hook (${EVENT}) in ${path}` };
+ return { action: 'keep', path, detail: `${what} (${EVENT}) in ${path}` };
}
if (!opts.dryRun) {
writeUnlessChanged(path, text, missing, next);
- const previous = commandIn(probe.interior);
+ const previous = entries[lane];
if (previous && previous !== command) revoke(opts.hermesHome, previous);
approve(opts.hermesHome, command);
}
- return { action: 'write', path, detail: `per-turn rule hook (${EVENT}) in ${path}, approved in ${ALLOWLIST}` };
+ return { action: 'write', path, detail: `${what} (${EVENT}) in ${path}, approved in ${ALLOWLIST}` };
} catch (e) {
return print(`config.yaml could not be updated (${(e as Error).message})`);
}
@@ -128,20 +175,46 @@ export function syncHermesTurnHook(opts: { hermesHome: string; access: BrainFirs
/** Strip the hook and its approval (decline or --remove). Never throws. */
export function removeHermesTurnHook(opts: { hermesHome: string; dryRun: boolean }): HermesTurnHookOutcome {
+ return removeHermesHook({ ...opts, lane: 'turn-rule' });
+}
+
+/** Strip one lane's entry and its approval, keeping the other lane's; the block goes with its last entry. Never throws. */
+export function removeHermesHook(opts: { hermesHome: string; lane: HermesHookLane; dryRun: boolean }): HermesTurnHookOutcome {
const path = join(opts.hermesHome, 'config.yaml');
+ const what = LANES[opts.lane].what;
try {
- if (!existsSync(path)) return { action: 'skip', path, detail: `no per-turn rule hook in ${path}` };
+ if (!existsSync(path)) return { action: 'skip', path, detail: `no ${what} in ${path}` };
const text = readFileSync(path, 'utf8');
const probe = probeBlock(MARKERS, text);
- if (probe.state !== 'present') return { action: 'skip', path, detail: `no per-turn rule hook in ${path}` };
- const command = commandIn(probe.interior);
+ const entries = probe.state === 'present' ? entriesIn(probe.interior) : {};
+ const command = entries[opts.lane];
+ if (probe.state !== 'present' || (!command && (opts.lane === 'skill-resolver' || Object.keys(entries).length > 0))) return { action: 'skip', path, detail: `no ${what} in ${path}` };
+ const rest = { ...entries, [opts.lane]: undefined };
+ const left = Object.values(rest).some(Boolean);
if (!opts.dryRun) {
- writeUnlessChanged(path, text, false, removeBlock(MARKERS, text).text);
+ writeUnlessChanged(path, text, false, left ? spliceBlock(MARKERS, text, hooksYaml(rest)) : removeBlock(MARKERS, text).text);
if (command) revoke(opts.hermesHome, command);
}
- return { action: 'remove', path, detail: `per-turn rule hook removed from ${path}` };
+ return { action: 'remove', path, detail: `${what} removed from ${path}` };
} catch (e) {
- return { action: 'skip', path, detail: `per-turn rule hook in ${path} left as it is (${(e as Error).message})` };
+ return { action: 'skip', path, detail: `${what} in ${path} left as it is (${(e as Error).message})` };
+ }
+}
+
+/** Read-only: is the skill-resolver lane's entry in config.yaml (gbrain's block, else pasted by hand), and does Hermes's allowlist approve it? */
+export function inspectHermesResolverHook(hermesHome: string): { state: 'absent' | 'unapproved' | 'approved'; path: string; command?: string } {
+ const path = join(hermesHome, 'config.yaml');
+ try {
+ const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
+ const probe = probeBlock(MARKERS, text);
+ const doc = probe.state === 'absent' ? loadBoundedYaml(text) as Record<string, unknown> | null | undefined : null;
+ const pasted = doc && typeof doc === 'object' ? ((doc.hooks as Record<string, unknown> | undefined)?.[EVENT] as Array<{ command?: unknown }> | undefined) : undefined;
+ const command = probe.state === 'present' ? entriesIn(probe.interior)['skill-resolver']
+ : Array.isArray(pasted) ? pasted.map((e) => e?.command).find((c): c is string => typeof c === 'string' && isSkillResolverCommand(c)) : undefined;
+ if (!command) return { state: 'absent', path };
+ return { state: readAllowlist(join(hermesHome, ALLOWLIST)).approvals.some((e) => approves(e, command)) ? 'approved' : 'unapproved', path, command };
+ } catch {
+ return { state: 'absent', path };
}
}
diff --git a/src/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.ts
index 19391b7569..8248b2a0d2 100644
--- a/src/core/setup/skill-resolver-config.ts
+++ b/src/core/setup/skill-resolver-config.ts
@@ -20,7 +20,7 @@ import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { setCliExitVerdict } from '../cli-force-exit.ts';
-import { laneTurnSettings, validateMinMatch, validatePinned, validateSessionTokenBudget, validateTopK } from '../skills/resolver/config.ts';
+import { laneTurnSettings, validateMinMatch, validateOwnerSenders, validatePinned, validateSessionTokenBudget, validateTopK } from '../skills/resolver/config.ts';
const CONFIG_CAP_BYTES = 1024 * 1024;
const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -89,8 +89,8 @@ export function setResolverHarness(read: Exclude<ResolverConfigRead, { state: 'u
export const SKILL_RESOLVER_KEY_PREFIX = 'skills.resolver.';
/** The leaves `gbrain config set|unset|get` accepts (harnesses is setup's: --skill-loading resolve|off). */
-export const SKILL_RESOLVER_CONFIG_LEAVES = ['enabled', 'session_token_budget', 'auto_rebuild', 'lane_payload_chars', 'top_k', 'min_match', 'pinned', 'per_harness.<harness>.top_k', 'per_harness.<harness>.min_match'] as const;
-const PER_HARNESS_LEAF = /^per_harness\.([a-z-]+)\.(top_k|min_match)$/;
+export const SKILL_RESOLVER_CONFIG_LEAVES = ['enabled', 'session_token_budget', 'auto_rebuild', 'lane_payload_chars', 'top_k', 'min_match', 'pinned', 'per_harness.<harness>.top_k', 'per_harness.<harness>.min_match', 'per_harness.hermes.owner_sender_ids'] as const;
+const PER_HARNESS_LEAF = /^per_harness\.([a-z-]+)\.(top_k|min_match|owner_sender_ids)$/;
function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean | number | string | string[] } | { ok: false; error: string } {
const turnKey = leaf.match(PER_HARNESS_LEAF)?.[2] ?? leaf;
@@ -99,6 +99,7 @@ function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean
if (turnKey === 'top_k') return { ok: true, value: validateTopK(/^\d+$/.test(value) ? Number(value) : NaN, key) };
if (turnKey === 'min_match') return { ok: true, value: validateMinMatch(value, key) };
if (leaf === 'pinned') return { ok: true, value: validatePinned(value.split(',').map(s => s.trim()).filter(Boolean), key) };
+ if (turnKey === 'owner_sender_ids') return { ok: true, value: validateOwnerSenders(value.split(',').map(s => s.trim()).filter(Boolean), key) };
} catch (e) { return { ok: false, error: (e as Error).message.slice(key.length + 1) }; }
if (leaf === 'enabled' || leaf === 'auto_rebuild') {
if (value === 'true' || value === 'false') return { ok: true, value: value === 'true' };
@@ -122,7 +123,7 @@ export function runSkillResolverConfigKey(args: string[], home: string): boolean
if (!key?.startsWith(SKILL_RESOLVER_KEY_PREFIX) || !['set', 'unset', 'get'].includes(action ?? '')) return false;
const leaf = key.slice(SKILL_RESOLVER_KEY_PREFIX.length);
const fail = (msg: string): true => { console.error(`[config] ${msg}`); setCliExitVerdict(1); return true; };
- if (leaf === 'harnesses') return fail(`${key} is written by gbrain setup <claude-code|codex> --skill-loading resolve (and removed by --skill-loading off); nothing was written.`);
+ if (leaf === 'harnesses') return fail(`${key} is written by gbrain setup <claude-code|codex|hermes> --skill-loading resolve (and removed by --skill-loading off); nothing was written.`);
const nested = leaf.match(PER_HARNESS_LEAF);
if (!nested && !(SKILL_RESOLVER_CONFIG_LEAVES as readonly string[]).includes(leaf)) return fail(`Unknown config key "${key}". skills.resolver keys: ${SKILL_RESOLVER_CONFIG_LEAVES.join(', ')}. Nothing was written.`);
const read = readResolverConfig(home);
diff --git a/src/core/setup/skill-resolver-hook.ts b/src/core/setup/skill-resolver-hook.ts
index 56bfb85489..9a8cf845a0 100644
--- a/src/core/setup/skill-resolver-hook.ts
+++ b/src/core/setup/skill-resolver-hook.ts
@@ -16,34 +16,47 @@
* Codex sends SessionStart with source "compact" after it compacts),
* each trusted by its hash in config.toml beside it, like the turn-rule
* lane.
+ * - Hermes: its own `pre_llm_call` entry (`hook user-prompt --harness
+ * hermes`) in gbrain's marked `hooks:` block in $HERMES_HOME/config.yaml,
+ * beside the turn rule's (hermes-turn-hook.ts), approved in Hermes's
+ * shell-hooks-allowlist.json. Hermes splits the command like shlex with no
+ * shell and needs its first word to be a file, so it starts with
+ * /usr/bin/env. Hermes has no SessionStart: the lane resets a session's
+ * dedupe state itself when the history shrinks (in-place compaction).
*
- * Both run gbrain through the existing hook launcher (hook-launcher.ts); this
+ * All three run gbrain through the existing hook launcher (hook-launcher.ts); this
* module writes nothing else into the launcher's directory. Ownership: the
* marker, else the lane token in the command (Claude Code), the lane token
* (Codex). Nothing else in either file is touched.
*/
import { mkdirSync } from 'node:fs';
-import { dirname } from 'node:path';
+import { dirname, join } from 'node:path';
import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
import { codexHookCensus, codexHookGroupRuns, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';
import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';
import { buildClaudeHookCommand, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';
+import { shellQuote } from '../shell-quote.ts';
import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
+import { brainFirstTarget } from './brain-first.ts';
+import { inspectHermesResolverHook, removeHermesHook, syncHermesHook } from './hermes-turn-hook.ts';
import { readJsonObjectSafe } from './skill-resolver-config.ts';
import { ensureHookLauncher, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';
import { isSkillResolverCommand, isSkillResolverEntry, SKILL_RESOLVER_LANE, SKILL_RESOLVER_MARKER } from './skill-resolver-lane.ts';
-export type ResolverHarness = 'claude-code' | 'codex';
+export type ResolverHarness = 'claude-code' | 'codex' | 'hermes';
const CLAUDE_EVENTS: ClaudeHookEvent[] = ['UserPromptSubmit', 'SessionStart'];
const CODEX_EVENTS = ['UserPromptSubmit', 'SessionStart'] as const;
type CodexEvent = (typeof CODEX_EVENTS)[number];
const CODEX_TIMEOUT_SECS = 15;
-export interface ResolverHookPaths { claudeSettings?: string; codexHooks?: string; codexConfig?: string; hookLauncher?: string }
+export interface ResolverHookPaths { claudeSettings?: string; codexHooks?: string; codexConfig?: string; hookLauncher?: string; hermesHome?: string }
export interface ResolverHookOutcome { action: 'write' | 'keep' | 'remove' | 'skip' | 'refuse'; path: string; detail: string }
const claudePath = (p: ResolverHookPaths) => p.claudeSettings ?? claudeUserSettingsPath();
const codexPaths = (p: ResolverHookPaths) => ({ hooks: p.codexHooks ?? codexHooksPath(), config: p.codexConfig ?? codexConfigPath() });
+/** $HERMES_HOME (else ~/.hermes): where SOUL.md, config.yaml and skills/ live. */
+export const hermesHomeDir = (): string => dirname((brainFirstTarget('hermes') as { path: string }).path);
+const hermesHome = (p: ResolverHookPaths) => p.hermesHome ?? hermesHomeDir();
const laneEnv = (home: string | undefined) => ({ ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: SKILL_RESOLVER_LANE });
/** Every entry of this lane in a Claude Code settings file, by event. */
@@ -65,8 +78,14 @@ export function codexResolverGroup(bin: string, home: string | undefined, launch
const codexTrusted = (p: { hooks: string; config: string }, g: { event: CodexEvent; index: number }) => codexHookGroupRuns(p.hooks, p.config, g);
+/** The Hermes entry's command: no shell, so the environment goes through /usr/bin/env and every word is shlex-quoted. */
+export function hermesResolverCommand(bin: string, home: string | undefined, launcher: string): string {
+ return ['/usr/bin/env', `GBRAIN_HOOK_LANE=${SKILL_RESOLVER_LANE}`, ...(home ? [`GBRAIN_HOME=${home}`] : []), launcher, bin, 'hook', 'user-prompt', '--harness', 'hermes'].map((w) => (/^[\w.:/@=-]+$/.test(w) ? w : shellQuote(w))).join(' ');
+}
+
/** The commands this install's lane runs (what the hook entries would hold). */
export function skillResolverCommands(harness: ResolverHarness, bin: string, home: string | undefined, launcher: string): string[] {
+ if (harness === 'hermes') return [hermesResolverCommand(bin, home, launcher)];
if (harness === 'codex') return CODEX_EVENTS.flatMap((e) => codexResolverGroup(bin, home, launcher, e).hooks.map((h) => h.command));
return CLAUDE_EVENTS.map((e) => buildClaudeHookCommand(bin, e, laneEnv(home), launcher));
}
@@ -79,6 +98,10 @@ export function skillResolverCommands(harness: ResolverHarness, bin: string, hom
export type ResolverHookState = 'absent' | 'wired' | 'untrusted' | 'outdated';
export function inspectSkillResolverHook(harness: ResolverHarness, paths: ResolverHookPaths = {}): { state: ResolverHookState; path: string; commands: string[] } {
try {
+ if (harness === 'hermes') {
+ const h = inspectHermesResolverHook(hermesHome(paths));
+ return { state: h.state === 'absent' ? 'absent' : h.state === 'approved' ? 'wired' : 'untrusted', path: h.path, commands: h.command ? [h.command] : [] };
+ }
if (harness === 'codex') {
const p = codexPaths(paths);
const ours = codexOurs(p);
@@ -92,7 +115,7 @@ export function inspectSkillResolverHook(harness: ResolverHarness, paths: Resolv
const has = (event: string) => ours.some((o) => o.event === event);
return { state: !has('UserPromptSubmit') ? 'absent' : has('SessionStart') ? 'wired' : 'outdated', path, commands: ours.map((o) => String(o.entry.command)) };
} catch {
- return { state: 'absent', path: harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths), commands: [] };
+ return { state: 'absent', path: harness === 'hermes' ? join(hermesHome(paths), 'config.yaml') : harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths), commands: [] };
}
}
@@ -102,7 +125,8 @@ export function syncSkillResolverHook(opts: { harness: ResolverHarness; gbrainBi
const launcher = paths.hookLauncher ?? hookLauncherPath();
const launcherFresh = hookLauncherState(launcher).state === 'current';
if (!opts.dryRun) ensureHookLauncher(launcher);
- const out = opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, launcher, codexPaths(paths), !!opts.dryRun)
+ const out = opts.harness === 'hermes' ? syncHermes(opts.gbrainBin, opts.gbrainHome, launcher, hermesHome(paths), !!opts.dryRun)
+ : opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, launcher, codexPaths(paths), !!opts.dryRun)
: syncClaude(opts.gbrainBin, opts.gbrainHome, launcher, claudePath(paths), !!opts.dryRun);
return out.action === 'keep' && !launcherFresh ? { ...out, action: 'write', detail: `${out.detail}; hook launcher ${launcher}` } : out;
}
@@ -120,6 +144,12 @@ function syncClaude(bin: string, home: string | undefined, launcher: string, pat
return { action: 'write', path, detail };
}
+function syncHermes(bin: string, home: string | undefined, launcher: string, hermes: string, dryRun: boolean): ResolverHookOutcome {
+ const o = syncHermesHook({ hermesHome: hermes, lane: 'skill-resolver', command: hermesResolverCommand(bin, home, launcher), dryRun });
+ if (o.action === 'print') return { action: 'refuse', path: o.path, detail: `${o.detail}:\n${o.snippet}` };
+ return { action: o.action === 'keep' ? 'keep' : 'write', path: o.path, detail: o.detail };
+}
+
const trustPath = (key: string) => ['hooks', 'state', key];
/** Drop the trust entries of our groups, each only while it still trusts one of our commands. */
@@ -156,6 +186,10 @@ function syncCodex(bin: string, home: string | undefined, launcher: string, p: {
/** Remove the lane's hook (and, on Codex, its trust entry). Throws on a file it cannot write safely. */
export function removeSkillResolverHook(opts: { harness: ResolverHarness; paths?: ResolverHookPaths; dryRun?: boolean }): ResolverHookOutcome {
const paths = opts.paths ?? {};
+ if (opts.harness === 'hermes') {
+ const o = removeHermesHook({ hermesHome: hermesHome(paths), lane: 'skill-resolver', dryRun: !!opts.dryRun });
+ return { action: o.action === 'remove' ? 'remove' : 'skip', path: o.path, detail: o.detail };
+ }
if (opts.harness === 'codex') {
const p = codexPaths(paths);
const ours = codexOurs(p);
diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.ts
index a63e13bd81..11607d1e04 100644
--- a/src/core/setup/skill-resolver-setup.ts
+++ b/src/core/setup/skill-resolver-setup.ts
@@ -1,12 +1,14 @@
/**
- * skill-resolver-setup.ts — `gbrain setup <claude-code|codex> --skill-loading
- * resolve` (and its undo, `--skill-loading off|spring` and `setup --remove`).
+ * skill-resolver-setup.ts — `gbrain setup <claude-code|codex|hermes>
+ * --skill-loading resolve` (and its undo, `--skill-loading off|spring` and `setup --remove`).
*
* On: build the harness's user-level catalog (<harness>-user, from
- * ~/.claude/skills; Codex: ~/.agents/skills and CODEX_HOME/skills) and, for
+ * ~/.claude/skills; Codex: ~/.agents/skills and CODEX_HOME/skills; Hermes:
+ * $HERMES_HOME/skills) and, for
* Claude Code, claude-code-plugins from its enabled user-scope plugins; only
* when those builds indexed at least one skill, write the file-plane keys
- * (skill-resolver-config.ts) and the lane's hook (skill-resolver-hook.ts).
+ * (skill-resolver-config.ts) and the lane's hook (skill-resolver-hook.ts);
+ * Hermes also gets the operator's pins in SOUL.md (hermes-skill-pins.ts).
* Otherwise nothing is written and the result carries
* skill_resolver_setup_incomplete with the scanned directories. A re-run with
* a fresh catalog, the keys and the hook in place changes nothing. It ends
@@ -30,9 +32,10 @@ import { CLAUDE_PLUGINS_CATALOG, logsDir, sessionsDir, skillIndexRoot } from '..
import { resolveSkills } from '../skills/resolver/resolve.ts';
import { claudePluginRoots, readDirSources } from '../skills/resolver/sources.ts';
import { readResolverConfig, resolverHarnesses, setResolverHarness } from './skill-resolver-config.ts';
-import { inspectSkillResolverHook, removeSkillResolverHook, syncSkillResolverHook, type ResolverHarness, type ResolverHookPaths } from './skill-resolver-hook.ts';
+import { syncHermesPins } from './hermes-skill-pins.ts';
+import { hermesHomeDir, inspectSkillResolverHook, removeSkillResolverHook, syncSkillResolverHook, type ResolverHarness, type ResolverHookPaths } from './skill-resolver-hook.ts';
-export interface ResolverStep { step: 'catalog' | 'config' | 'hook' | 'state'; action: 'write' | 'keep' | 'remove' | 'skip'; detail: string }
+export interface ResolverStep { step: 'catalog' | 'config' | 'hook' | 'pins' | 'state'; action: 'write' | 'keep' | 'remove' | 'skip'; detail: string }
export interface ResolverSetupError { code: 'skill_resolver_setup_incomplete' | 'skill_resolver_config_unreadable'; message: string; scanned: string[] }
export interface ResolverSetupResult {
harness: ResolverHarness;
@@ -75,6 +78,7 @@ async function syncPluginCatalog(home: string, dryRun: boolean): Promise<{ skill
/** The user-level skill directories a harness loads natively, whether or not they exist. */
export function harnessSkillDirs(harness: ResolverHarness): string[] {
if (harness === 'claude-code') return [claudeUserSkillsDir()];
+ if (harness === 'hermes') return [join(hermesHomeDir(), 'skills')];
return [join(process.env.HOME?.trim() || '', '.agents', 'skills'), join(dirname(codexConfigPath()), 'skills')];
}
@@ -133,6 +137,10 @@ export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; g
const hook = syncSkillResolverHook({ harness, gbrainBin: opts.gbrainBin, gbrainHome: opts.gbrainHome, paths: opts.paths, dryRun });
if (hook.action === 'refuse') return { ...out, error: incomplete(dirs, hook.detail, 'The catalog and the config keys were written; re-run after fixing that.') };
out.steps.push({ step: 'hook', action: hook.action === 'keep' ? 'keep' : 'write', detail: hook.detail });
+ if (harness === 'hermes') {
+ const pins = syncHermesPins({ home, hermesHome: opts.paths?.hermesHome ?? hermesHomeDir(), dryRun });
+ if (pins) out.steps.push({ step: 'pins', action: pins.action, detail: pins.detail });
+ }
if (dryRun) return out;
const built = [...(skills ? [catalog] : []), ...(pluginSkills ? [CLAUDE_PLUGINS_CATALOG] : [])];
@@ -161,6 +169,10 @@ export async function removeSkillResolverSetup(opts: { harness: ResolverHarness;
if (cfg.state === 'unreadable') return { ...out, error: { code: 'skill_resolver_config_unreadable', scanned: [], message: `${cfg.path} cannot be read (${cfg.why}), so setup did not touch it or anything else for the skill resolver.` } };
const hook = removeSkillResolverHook({ harness, paths: opts.paths, dryRun });
if (hook.action === 'remove') out.steps.push({ step: 'hook', action: 'remove', detail: hook.detail });
+ if (harness === 'hermes') {
+ const pins = syncHermesPins({ home, hermesHome: opts.paths?.hermesHome ?? hermesHomeDir(), off: true, dryRun });
+ if (pins) out.steps.push({ step: 'pins', action: pins.action, detail: pins.detail });
+ }
const keys = setResolverHarness(cfg, harness, false, dryRun);
const left = resolverHarnesses(cfg.state === 'ok' ? cfg.doc : null).filter((h) => h !== harness);
if (keys.changed) out.steps.push({ step: 'config', action: 'remove', detail: `${left.length ? `${harness} from skills.resolver.harnesses` : 'skills.resolver.enabled and skills.resolver.harnesses'} in ${cfg.path}${keys.deletedFile ? ' (the file held nothing else, so it was removed)' : ''}` });
diff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.ts
index 1defacb2f4..5753630703 100644
--- a/src/core/skills/resolver/config.ts
+++ b/src/core/skills/resolver/config.ts
@@ -22,6 +22,10 @@
* an entry that is not an object (a hand-edited null) counts as unset
* skills.resolver.pinned skill ids the harness always loads itself,
* never suggested (at most 1,024)
+ * skills.resolver.per_harness.hermes.owner_sender_ids the senders whose
+ * turns get suggestions (Hermes's extra.sender_id); a turn from anyone
+ * else, or with no sender, gets none. Unset or empty: every turn. The
+ * same rule as the OpenClaw plugin's owner_sender_ids.
*/
import { readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
@@ -101,13 +105,28 @@ export function laneTurnSettings(section: Record<string, unknown>, harness: stri
const key = `${p}per_harness.${h}`;
if (!(HARNESSES as readonly string[]).includes(h)) throw configInvalid(key, `names no harness (one of ${HARNESSES.join(', ')})`);
if (!o || typeof o !== 'object' || Array.isArray(o)) continue;
- if (Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match')) throw configInvalid(key, 'may hold only top_k and min_match');
+ if (Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match' && (k !== 'owner_sender_ids' || h !== 'hermes'))) throw configInvalid(key, `may hold only top_k and min_match${h === 'hermes' ? ' and owner_sender_ids' : ''}`);
const r = o as Record<string, unknown>;
const parsed: LaneTurnSettings = {
...(r.top_k !== undefined ? { top_k: validateTopK(r.top_k, `${key}.top_k`) } : {}),
...(r.min_match !== undefined ? { min_match_strength: validateMinMatch(r.min_match, `${key}.min_match`) } : {}),
};
+ if (h === 'hermes' && r.owner_sender_ids !== undefined) validateOwnerSenders(r.owner_sender_ids, `${key}.owner_sender_ids`);
if (h === harness) mine = parsed;
}
return { ...global, ...mine };
}
+
+export const OWNER_SENDERS_MAX = 64;
+
+export function validateOwnerSenders(v: unknown, key: string): string[] {
+ if (Array.isArray(v) && v.length <= OWNER_SENDERS_MAX && v.every(x => typeof x === 'string' && /^[\x21-\x7e]{1,128}$/.test(x))) return v as string[];
+ throw configInvalid(key, `must be a list of at most ${OWNER_SENDERS_MAX} sender ids (1-128 visible characters each)`);
+}
+
+/** The senders whose turns get suggestions on `harness` (Hermes only), or null for every turn. Call after laneTurnSettings, which validates it. */
+export function laneOwnerSenders(section: Record<string, unknown>, harness: string): string[] | null {
+ const mine = (section.per_harness as Record<string, unknown> | undefined)?.[harness] as { owner_sender_ids?: string[] } | null | undefined;
+ const ids = harness === 'hermes' && mine && typeof mine === 'object' ? mine.owner_sender_ids : undefined;
+ return ids?.length ? ids : null;
+}
diff --git a/src/core/skills/resolver/hook-input.ts b/src/core/skills/resolver/hook-input.ts
index d72381340a..7b2ecfd81a 100644
--- a/src/core/skills/resolver/hook-input.ts
+++ b/src/core/skills/resolver/hook-input.ts
@@ -9,7 +9,10 @@
* byte scan for brackets and native indexOf jumps between quotes and
* backslashes (nesting and string ends checked, scalars not), and only kept
* strings are decoded, so a 5 MB history costs about as much as JSON.parse
- * of it. Leaf module: no I/O of its own.
+ * of it. It can also count the items of an array at a path (the same byte
+ * scan, counting commas at its own depth) and read a boolean at a path, so
+ * Hermes's history length and first-turn flag cost no extra pass. Leaf
+ * module: no I/O of its own.
*/
/** The turn input's message cap (resolve.ts MESSAGE_CAP_BYTES); resolve.ts is not loaded on the lane's main thread. */
@@ -20,9 +23,10 @@ type Mode = 'value' | 'key' | 'key-or-end' | 'colon' | 'after' | 'done';
type Num = 'sign' | 'zero' | 'int' | 'dot' | 'frac' | 'e' | 'esign' | 'exp';
/** A string being read: kept ones gather their raw JSON bytes (escapes included) up to `room`. */
interface Str { key: boolean; path: string | null; keep: boolean; raw: Buffer[]; room: number; over: boolean; esc: boolean }
-/** A discarded array or object being skipped: its open brackets and string state. */
-interface Skip { open: number[]; inStr: boolean; esc: boolean }
+/** A discarded array or object being skipped: its open brackets and string state; a counted array also tracks its top-level items (any: null until its first non-space byte). */
+interface Skip { open: number[]; inStr: boolean; esc: boolean; count?: { path: string; commas: number; any: boolean | null } }
+const COMMA = 0x2c;
const QUOTE = 0x22, BACKSLASH = 0x5c, OPEN_OBJECT = 0x7b, CLOSE_OBJECT = 0x7d, OPEN_ARRAY = 0x5b, CLOSE_ARRAY = 0x5d;
/**
@@ -31,8 +35,13 @@ const QUOTE = 0x22, BACKSLASH = 0x5c, OPEN_OBJECT = 0x7b, CLOSE_OBJECT = 0x7d, O
* the chunk ran out first (state kept in `s`), -2 when malformed.
*/
function skipScan(t: Uint8Array, i: number, s: Skip): number {
- const open = s.open, n = t.length;
+ const open = s.open, n = t.length, count = s.count;
let inStr = s.inStr, esc = s.esc, nb = -1;
+ if (count && count.any === null) {
+ while (i < n && isSpace(t[i]!)) i++;
+ if (i === n) return -1;
+ count.any = t[i] !== CLOSE_ARRAY;
+ }
while (i < n) {
if (esc) { esc = false; i++; continue; }
if (inStr) {
@@ -44,10 +53,11 @@ function skipScan(t: Uint8Array, i: number, s: Skip): number {
continue;
}
let c = 0;
- for (; i < n; i++) { c = t[i]!; if (c === QUOTE || c === OPEN_OBJECT || c === CLOSE_OBJECT || c === OPEN_ARRAY || c === CLOSE_ARRAY) break; }
+ for (; i < n; i++) { c = t[i]!; if (c === QUOTE || c === OPEN_OBJECT || c === CLOSE_OBJECT || c === OPEN_ARRAY || c === CLOSE_ARRAY || (count && c === COMMA)) break; }
if (i === n) break;
i++;
- if (c === QUOTE) inStr = true;
+ if (c === COMMA) { if (open.length === 1) count!.commas++; }
+ else if (c === QUOTE) inStr = true;
else if (c === OPEN_OBJECT || c === OPEN_ARRAY) open.push(c);
else if (open.pop() !== (c === CLOSE_OBJECT ? OPEN_OBJECT : OPEN_ARRAY)) return -2;
else if (open.length === 0) return i;
@@ -101,10 +111,28 @@ function decodeKept(s: Str): string | undefined {
* that is not an object. The stream is always read to its end.
*/
export async function readJsonFields(stream: AsyncIterable<Uint8Array | string> & { isTTY?: boolean }, paths: readonly string[], cap: number): Promise<Record<string, string> | null> {
+ return (await readHookFields(stream, { strings: paths }, cap))?.strings ?? null;
+}
+
+export interface HookFields { strings: Record<string, string>; counts: Record<string, number>; flags: Record<string, boolean> }
+
+/**
+ * readJsonFields plus, in the same pass, the item count of the array at each
+ * of `counts` and the boolean at each of `flags` (a path holding anything
+ * else is left out). Null on the same conditions, so a stream cut off inside
+ * a counted array yields no count at all.
+ */
+export async function readHookFields(stream: AsyncIterable<Uint8Array | string> & { isTTY?: boolean }, spec: { strings: readonly string[]; counts?: readonly string[]; flags?: readonly string[] }, cap: number): Promise<HookFields | null> {
if (stream.isTTY) return null;
- const wanted = new Set(paths);
+ const wanted = new Set(spec.strings);
+ const counted = new Set(spec.counts ?? []);
+ const flagged = new Set(spec.flags ?? []);
+ const paths = [...wanted, ...counted, ...flagged];
+ const leaves = new Set(paths);
const prefixes = new Set(paths.flatMap(p => p.split('.').slice(0, -1).map((_, i, a) => a.slice(0, i + 1).join('.'))));
const out: Record<string, string> = {};
+ const counts: Record<string, number> = {};
+ const flags: Record<string, boolean> = {};
const stack: string[] = [];
let mode = 'value' as Mode;
let keyPath: string | null = null;
@@ -121,7 +149,7 @@ export async function readJsonFields(stream: AsyncIterable<Uint8Array | string>
if (s.key) {
const parent = stack.at(-1)!;
const p = parent ? `${parent}.${value}` : value;
- keyPath = s.keep && !s.over && (wanted.has(p) || prefixes.has(p)) ? p : null;
+ keyPath = s.keep && !s.over && (leaves.has(p) || prefixes.has(p)) ? p : null;
mode = 'colon';
return true;
}
@@ -143,6 +171,7 @@ export async function readJsonFields(stream: AsyncIterable<Uint8Array | string>
const end = skipScan(t, i, skip);
if (end === -1) return true;
if (end === -2) return false;
+ if (skip.count) counts[skip.count.path] = skip.count.any ? skip.count.commas + 1 : 0;
skip = null;
i = end;
endValue();
@@ -196,10 +225,11 @@ export async function readJsonFields(stream: AsyncIterable<Uint8Array | string>
if (root && c !== OPEN_OBJECT) return false;
const path = root ? '' : keyPath;
if (c === OPEN_OBJECT && path !== null) { stack.push(path); mode = 'key-or-end'; }
+ else if (c === OPEN_ARRAY && path !== null && counted.has(path)) skip = { open: [c], inStr: false, esc: false, count: { path, commas: 0, any: null } };
else if (c === OPEN_OBJECT || c === OPEN_ARRAY) skip = { open: [c], inStr: false, esc: false };
else if (c === QUOTE) { const keep = path !== null && wanted.has(path); str = { key: false, path, keep, raw: [], room: keep ? cap * 6 + 12 : 0, over: false, esc: false }; }
- else if (c === 0x74) literal = 'rue';
- else if (c === 0x66) literal = 'alse';
+ else if (c === 0x74) { literal = 'rue'; if (path !== null && flagged.has(path)) flags[path] = true; }
+ else if (c === 0x66) { literal = 'alse'; if (path !== null && flagged.has(path)) flags[path] = false; }
else if (c === 0x6e) literal = 'ull';
else if (c === 0x2d) num = 'sign';
else if (isDigit(c)) num = c === 0x30 ? 'zero' : 'int';
@@ -214,5 +244,5 @@ export async function readJsonFields(stream: AsyncIterable<Uint8Array | string>
if (!bad) bad = !feed(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
}
} catch { return null; }
- return bad || mode !== 'done' || str || skip || literal || num !== null ? null : out;
+ return bad || mode !== 'done' || str || skip || literal || num !== null ? null : { strings: out, counts, flags };
}
diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.ts
index f74808184a..7dc644f2aa 100644
--- a/src/core/skills/resolver/hook-lane.ts
+++ b/src/core/skills/resolver/hook-lane.ts
@@ -14,7 +14,12 @@
* by the bounded streaming reader (hook-input.ts) over Bun's native stdin
* stream (about 4x faster than process.stdin on a multi-MB payload) so no
* history size is refused, and takes {"context": block}. Hermes has no
- * compaction event.
+ * compaction event and compacts in place (same session id), so the same
+ * pass counts extra.conversation_history and reads extra.is_first_turn: a
+ * first turn, or a history shorter than the last committed turn saw
+ * (session.ts historyShrank), starts the session's dedupe fresh. With
+ * per_harness.hermes.owner_sender_ids set, a turn whose extra.sender_id is
+ * not listed (or is empty) gets no block, as in the OpenClaw plugin.
*
* It runs the resolver in this process (never over serve's IPC), so it works
* with serve down and with no brain, and it always fails open: every path
@@ -77,11 +82,11 @@ import { spawn } from '../../spawn.ts';
import { claudeManagedSettingsPaths, claudeUserSettingsPath, codexHooksPath } from '../../bootstrap/host-specs.ts';
import { shellWords } from '../../setup/hook-launcher.ts';
import { isSkillResolverCommand, isSkillResolverEntry } from '../../setup/skill-resolver-lane.ts';
-import { laneTurnSettings, type LaneTurnSettings } from './config.ts';
+import { laneOwnerSenders, laneTurnSettings, type LaneTurnSettings } from './config.ts';
import { appendDailyLog, appendDailyLogSync, LANE_LOG } from './daily-log.ts';
-import { HOOK_FIELD_CAP, readJsonFields } from './hook-input.ts';
+import { HOOK_FIELD_CAP, readHookFields } from './hook-input.ts';
import { assertCatalogName, catalogFile, CLAUDE_PLUGINS_CATALOG, logsDir, resolverHome } from './paths.ts';
-import { type CommitHold, commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';
+import { type CommitHold, commitSessionAsync, historyShrank, sessionKey, type TurnDelta } from './session.ts';
import type { TurnOutput } from './resolve.ts';
import type { LaneWorkerTurn } from './hook-worker.ts';
import { laneWorkerFailed, startLaneWorker } from './lane-worker.ts';
@@ -197,7 +202,7 @@ async function readStdinBounded(stream: NodeJS.ReadableStream & { isTTY?: boolea
type LaneStdin = NodeJS.ReadableStream & { isTTY?: boolean };
/** One hook event's fields as the harness sent them, not yet checked. */
-interface HookEvent { prompt: string; sessionId?: unknown; cwd?: unknown; source?: unknown }
+interface HookEvent { prompt: string; sessionId?: unknown; cwd?: unknown; source?: unknown; history?: number; firstTurn?: boolean; senderId?: string }
/** `stdin` is the injected stream, else undefined for the process's own. */
interface HarnessIo { read: (stdin: LaneStdin | undefined) => Promise<HookEvent | null>; render: (block: string) => string }
@@ -219,8 +224,8 @@ const LANE_IO: Record<LaneHarness, HarnessIo> = {
hermes: {
read: async (stdin) => {
const source = stdin ?? (process.stdin.isTTY ? process.stdin : Bun.stdin.stream());
- const f = await readJsonFields(source, ['session_id', 'cwd', 'extra.user_message'], HOOK_FIELD_CAP);
- return f && { prompt: f['extra.user_message'] ?? '', sessionId: f.session_id, cwd: f.cwd };
+ const f = await readHookFields(source, { strings: ['session_id', 'cwd', 'extra.user_message', 'extra.sender_id'], counts: ['extra.conversation_history'], flags: ['extra.is_first_turn'] }, HOOK_FIELD_CAP);
+ return f && { prompt: f.strings['extra.user_message'] ?? '', sessionId: f.strings.session_id, cwd: f.strings.cwd, history: f.counts['extra.conversation_history'], firstTurn: f.flags['extra.is_first_turn'], senderId: f.strings['extra.sender_id'] ?? '' };
},
render: (block) => JSON.stringify({ context: block }),
},
@@ -327,6 +332,10 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHar
return { outcome: 'reset' };
}
+ const owners = laneOwnerSenders(settings.section, harness);
+ if (owners && !owners.includes(hookEvent.senderId ?? '')) return { outcome: 'skipped_sender' };
+ const reset = harness === 'hermes' && !!sessionId && (hookEvent.firstTurn === true || await historyShrank(home, sessionKey('on', harness, sessionId), hookEvent.history));
+
const prompt = hookEvent.prompt;
if (!prompt.trim() || /^\s*<(task-notification|teammate-message)[\s>]/.test(prompt)) return { outcome: 'empty' };
const spawnFn = io.spawn ?? spawnDetached;
@@ -346,7 +355,7 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHar
worker.once('message', resolve);
worker.once('error', () => resolve({ error: { code: 'skill_resolver_internal' } }));
worker.once('exit', () => resolve({ error: { code: 'skill_resolver_internal' } }));
- worker.postMessage({ input: { message: prompt, harness, ...turnSettings, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS) } satisfies LaneWorkerTurn);
+ worker.postMessage({ input: { message: prompt, harness, ...turnSettings, ...(sessionId ? { session_id: sessionId } : {}), ...(reset ? { reset_session: true } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS) } satisfies LaneWorkerTurn);
});
if (posted.error || !posted.output) return { outcome: 'error', code: posted.error?.code ?? 'skill_resolver_internal', catalogs };
const out = posted.output;
@@ -362,7 +371,7 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHar
}
const stall = env.GBRAIN_TEST_SKILL_LANE_STALL;
if (stall === 'commit-held' || stall === 'commit-written') ctl.commit.at = (stage) => (`commit-${stage}` === stall ? new Promise(() => {}) : Promise.resolve());
- if (posted.pending && !ctl.expired) await commitSessionAsync(home, posted.pending.key, posted.pending.delta, ctl.commit);
+ if (posted.pending && !ctl.expired) await commitSessionAsync(home, posted.pending.key, { ...posted.pending.delta, ...(hookEvent.history !== undefined ? { history: hookEvent.history } : {}) }, ctl.commit);
return { outcome, catalogs };
}
diff --git a/src/core/skills/resolver/session.ts b/src/core/skills/resolver/session.ts
index ff7033bd3f..d004bf9a9e 100644
--- a/src/core/skills/resolver/session.ts
+++ b/src/core/skills/resolver/session.ts
@@ -44,6 +44,8 @@ export interface SessionState {
last: Record<string, number>;
/** Skill ids already re-suggested once. */
again: Record<string, 1>;
+ /** Hermes: the conversation history length the last committed turn saw (a shorter one means Hermes compacted in place). */
+ history?: number;
}
export const freshState = (): SessionState => ({ v: 1, turn: 0, spent: 0, last: {}, again: {} });
@@ -60,13 +62,34 @@ export function loadSession(home: string, key: string): SessionState {
if (statSync(p).size > STATE_CAP_BYTES) return freshState();
const s = JSON.parse(readFileSync(p, 'utf8')) as SessionState;
if (s?.v !== 1 || typeof s.turn !== 'number' || typeof s.spent !== 'number' || !s.last || typeof s.last !== 'object') return freshState();
- return { v: 1, turn: s.turn, spent: s.spent, last: s.last, again: s.again && typeof s.again === 'object' ? s.again : {} };
+ return { v: 1, turn: s.turn, spent: s.spent, last: s.last, again: s.again && typeof s.again === 'object' ? s.again : {}, ...historyOf(s) };
} catch {
return freshState();
}
}
-export interface TurnDelta { tokens: number; suggested: string[]; resuggested: string[]; reset: boolean }
+export interface TurnDelta { tokens: number; suggested: string[]; resuggested: string[]; reset: boolean; history?: number }
+
+const historyOf = (s: { history?: unknown }) => (Number.isSafeInteger(s.history) && (s.history as number) >= 0 ? { history: s.history as number } : {});
+
+/**
+ * Whether a Hermes turn must start the session fresh: Hermes compacts in
+ * place (same session id) and sends hooks no compaction event, so a history
+ * shorter than the one the last committed turn saw is the compaction. A
+ * session with no stored length (a new one, or state from before this field)
+ * or a turn whose length is unknown never resets.
+ */
+export async function historyShrank(home: string, key: string, length: number | undefined): Promise<boolean> {
+ if (length === undefined) return false;
+ try {
+ const p = statePath(home, key);
+ if ((await stat(p)).size > STATE_CAP_BYTES) return false;
+ const stored = historyOf(JSON.parse(await readFile(p, 'utf8')) as { history?: unknown }).history;
+ return stored !== undefined && length < stored;
+ } catch {
+ return false;
+ }
+}
/** Apply one delivered turn. False when the commit was skipped (busy lock, file cap). */
export async function commitSession(home: string, key: string, delta: TurnDelta): Promise<boolean> {
@@ -95,6 +118,7 @@ function applyDelta(s: SessionState, delta: TurnDelta): SessionState {
s.spent += delta.tokens;
for (const id of delta.resuggested) s.again[id] = 1;
for (const id of delta.suggested) if (id in s.last || Object.keys(s.last).length < MAX_SESSION_IDS) s.last[id] = s.turn;
+ if (delta.history !== undefined) s.history = delta.history;
return s;
}
@@ -132,7 +156,7 @@ async function commitAsync(home: string, key: string, delta: TurnDelta, hold: Co
try {
if ((await stat(p)).size <= STATE_CAP_BYTES) {
const raw = JSON.parse(await readFile(p, 'utf8')) as SessionState;
- if (raw?.v === 1 && typeof raw.turn === 'number' && typeof raw.spent === 'number' && raw.last && typeof raw.last === 'object') s = { v: 1, turn: raw.turn, spent: raw.spent, last: raw.last, again: raw.again && typeof raw.again === 'object' ? raw.again : {} };
+ if (raw?.v === 1 && typeof raw.turn === 'number' && typeof raw.spent === 'number' && raw.last && typeof raw.last === 'object') s = { v: 1, turn: raw.turn, spent: raw.spent, last: raw.last, again: raw.again && typeof raw.again === 'object' ? raw.again : {}, ...historyOf(raw) };
}
} catch { /* none or unreadable: fresh */ }
}
diff --git a/test/setup-skill-resolver-hermes.test.ts b/test/setup-skill-resolver-hermes.test.ts
new file mode 100644
index 0000000000..fc711f1202
--- /dev/null
+++ b/test/setup-skill-resolver-hermes.test.ts
@@ -0,0 +1,267 @@
+/**
+ * GST-1850 PR 2: `gbrain setup hermes --skill-loading resolve`. The lane's
+ * `pre_llm_call` entry shares gbrain's one marked `hooks:` block in
+ * $HERMES_HOME/config.yaml with the brain-first turn rule, each entry with its
+ * own approval in shell-hooks-allowlist.json.
+ *
+ * Protects: the four combinations of turn rule and resolver (neither, turn
+ * rule only, resolver only, both) in either install order, and that declining
+ * the brain-first rule keeps the resolver (and the reverse); the catalog is
+ * built from $HERMES_HOME/skills, nested category folders included; a Hermes
+ * with no SOUL.md still gets the resolver and SOUL.md is never created; the
+ * operator's pins land in a marked SOUL.md block and leave with the lane; a
+ * config.yaml with the user's own hooks: section gets the entry printed, and
+ * the entry pasted from it is then approved and kept; a brainless install
+ * stays brainless; doctor reports the Hermes hook; config set takes
+ * per_harness.hermes.owner_sender_ids; the command splits the way
+ * Hermes splits it (shlex, no shell) with /usr/bin/env first.
+ */
+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { load } from 'js-yaml';
+import { runCli } from './helpers/cli-spawn.ts';
+import { hermesTurnHookCommand, inspectHermesResolverHook, inspectHermesTurnHook, removeHermesHook, removeHermesTurnHook, syncHermesHook, syncHermesTurnHook } from '../src/core/setup/hermes-turn-hook.ts';
+import { hermesResolverCommand } from '../src/core/setup/skill-resolver-hook.ts';
+import type { BrainFirstAccess } from '../src/core/setup/brain-first.ts';
+
+setDefaultTimeout(60_000);
+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+const tmp = (prefix: string) => { const d = mkdtempSync(join(tmpdir(), prefix)); roots.push(d); return d; };
+const read = (p: string) => (existsSync(p) ? readFileSync(p, 'utf8') : null);
+const approvals = (hermes: string) => (JSON.parse(read(join(hermes, 'shell-hooks-allowlist.json')) ?? '{"approvals":[]}').approvals as Array<{ event: string; command: string }>).map((a) => a.command);
+const entries = (hermes: string) => ((load(read(join(hermes, 'config.yaml')) ?? '') as { hooks?: { pre_llm_call?: Array<{ command: string; timeout: number }> } } | undefined)?.hooks?.pre_llm_call ?? []);
+
+describe('one hooks: block, two lanes (hermes-turn-hook.ts)', () => {
+ const access: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };
+ const rule = hermesTurnHookCommand(access);
+ const resolver = hermesResolverCommand('/opt/gbrain/bin/gbrain', undefined, '/opt/gbrain/hook-launcher/gbrain-hook');
+ const mine = '# my config\nmodel:\n default: alice-example-model\n';
+ function hermes(config = mine): string {
+ const d = tmp('gbrain-hermes-two-lanes-');
+ writeFileSync(join(d, 'config.yaml'), config);
+ return d;
+ }
+
+ test('neither: removing either lane from a config with no block changes nothing', () => {
+ const d = hermes();
+ expect(removeHermesTurnHook({ hermesHome: d, dryRun: false }).action).toBe('skip');
+ expect(removeHermesHook({ hermesHome: d, lane: 'skill-resolver', dryRun: false }).action).toBe('skip');
+ expect(read(join(d, 'config.yaml'))).toBe(mine);
+ expect(inspectHermesTurnHook(d).state).toBe('absent');
+ expect(inspectHermesResolverHook(d).state).toBe('absent');
+ });
+
+ test('resolver only: its own entry, its own approval, and the turn rule reads absent', () => {
+ const d = hermes();
+ expect(syncHermesHook({ hermesHome: d, lane: 'skill-resolver', command: resolver, dryRun: false }).action).toBe('write');
+ expect(entries(d)).toEqual([{ command: resolver, timeout: 15 }]);
+ expect(approvals(d)).toEqual([resolver]);
+ expect(inspectHermesTurnHook(d).state).toBe('absent');
+ expect(inspectHermesResolverHook(d)).toMatchObject({ state: 'approved', command: resolver });
+ expect(removeHermesTurnHook({ hermesHome: d, dryRun: false }).action).toBe('skip');
+ expect(entries(d)).toEqual([{ command: resolver, timeout: 15 }]);
+ });
+
+ test('both, in either order: the same bytes, the turn rule first, each approved; each lane leaves alone and the block goes with the last', () => {
+ const a = hermes();
+ syncHermesTurnHook({ hermesHome: a, access, dryRun: false });
+ expect(syncHermesHook({ hermesHome: a, lane: 'skill-resolver', command: resolver, dryRun: false }).action).toBe('write');
+ const b = hermes();
+ syncHermesHook({ hermesHome: b, lane: 'skill-resolver', command: resolver, dryRun: false });
+ expect(syncHermesTurnHook({ hermesHome: b, access, dryRun: false }).action).toBe('write');
+ expect(read(join(a, 'config.yaml'))).toBe(read(join(b, 'config.yaml')));
+ expect(entries(a)).toEqual([{ command: rule, timeout: 10 }, { command: resolver, timeout: 15 }]);
+ expect(approvals(a).sort()).toEqual([resolver, rule].sort());
+ expect(syncHermesTurnHook({ hermesHome: a, access, dryRun: false }).action).toBe('keep');
+ expect(syncHermesHook({ hermesHome: a, lane: 'skill-resolver', command: resolver, dryRun: false }).action).toBe('keep');
+ expect(inspectHermesTurnHook(a)).toMatchObject({ state: 'approved', command: rule });
+
+ expect(removeHermesTurnHook({ hermesHome: a, dryRun: false }).action).toBe('remove');
+ expect(entries(a)).toEqual([{ command: resolver, timeout: 15 }]);
+ expect(approvals(a)).toEqual([resolver]);
+ expect(removeHermesHook({ hermesHome: a, lane: 'skill-resolver', dryRun: false }).action).toBe('remove');
+ expect(read(join(a, 'config.yaml'))).toBe(mine);
+ expect(approvals(a)).toEqual([]);
+
+ expect(removeHermesHook({ hermesHome: b, lane: 'skill-resolver', dryRun: false }).action).toBe('remove');
+ expect(entries(b)).toEqual([{ command: rule, timeout: 10 }]);
+ expect(approvals(b)).toEqual([rule]);
+ });
+
+ test('turn rule only: an install from before the resolver keeps its exact bytes', () => {
+ const before = `${mine}# gbrain:turn-rule:begin\nhooks:\n pre_llm_call:\n - command: ${JSON.stringify(rule)}\n timeout: 10\n# gbrain:turn-rule:end\n`;
+ const d = hermes(before);
+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: false }).action).toBe('keep');
+ expect(read(join(d, 'config.yaml'))).toBe(before);
+ });
+
+ test('a new resolver command replaces only its own entry and moves only its own approval', () => {
+ const d = hermes();
+ syncHermesTurnHook({ hermesHome: d, access, dryRun: false });
+ syncHermesHook({ hermesHome: d, lane: 'skill-resolver', command: resolver, dryRun: false });
+ const moved = hermesResolverCommand('/usr/local/bin/gbrain', '/srv/alice-example', '/srv/alice-example/.gbrain/hook-launcher/gbrain-hook');
+ expect(syncHermesHook({ hermesHome: d, lane: 'skill-resolver', command: moved, dryRun: false }).action).toBe('write');
+ expect(entries(d)).toEqual([{ command: rule, timeout: 10 }, { command: moved, timeout: 15 }]);
+ expect(approvals(d).sort()).toEqual([moved, rule].sort());
+ });
+
+ test('the user\'s own hooks: section: the resolver entry is printed; pasted as printed, it is approved and kept', () => {
+ const theirs = 'hooks:\n pre_tool_call:\n - command: /usr/bin/true\n';
+ const d = hermes(theirs);
+ const o = syncHermesHook({ hermesHome: d, lane: 'skill-resolver', command: resolver, dryRun: false });
+ expect(o.action).toBe('print');
+ expect(o.snippet).toBe(`hooks:\n pre_llm_call:\n - command: ${JSON.stringify(resolver)}\n timeout: 15\n`);
+ expect(read(join(d, 'config.yaml'))).toBe(theirs);
+ const pasted = `${theirs} pre_llm_call:\n - command: ${JSON.stringify(resolver)}\n timeout: 15\n`;
+ writeFileSync(join(d, 'config.yaml'), pasted);
+ expect(inspectHermesResolverHook(d).state).toBe('unapproved');
+ expect(syncHermesHook({ hermesHome: d, lane: 'skill-resolver', command: resolver, dryRun: false }).action).toBe('keep');
+ expect(read(join(d, 'config.yaml'))).toBe(pasted);
+ expect(inspectHermesResolverHook(d)).toMatchObject({ state: 'approved', command: resolver });
+ });
+
+ test.skipIf(!Bun.which('python3'))('the command splits the way Hermes splits it (shlex, no shell), /usr/bin/env first', () => {
+ const odd = hermesResolverCommand("/opt/it's here/gbrain", '/home/alice example', '/home/alice example/.gbrain/hook-launcher/gbrain-hook');
+ const split = Bun.spawnSync(['python3', '-c', 'import json, shlex, sys; print(json.dumps(shlex.split(sys.argv[1])))', odd]);
+ expect(JSON.parse(split.stdout.toString())).toEqual(['/usr/bin/env', 'GBRAIN_HOOK_LANE=skill-resolver', 'GBRAIN_HOME=/home/alice example',
+ '/home/alice example/.gbrain/hook-launcher/gbrain-hook', "/opt/it's here/gbrain", 'hook', 'user-prompt', '--harness', 'hermes']);
+ expect(resolver).toBe('/usr/bin/env GBRAIN_HOOK_LANE=skill-resolver /opt/gbrain/hook-launcher/gbrain-hook /opt/gbrain/bin/gbrain hook user-prompt --harness hermes');
+ });
+});
+
+interface Box { home: string; hermes: string; project: string; bin: string; env: Record<string, string | undefined> }
+function box(opts: { soul?: boolean } = {}): Box {
+ const root = tmp('gbrain-setup-hermes-resolver-');
+ const home = join(root, 'home'), hermes = join(home, '.hermes'), project = join(root, 'project');
+ for (const d of [home, hermes, project, join(root, 'bin')]) mkdirSync(d, { recursive: true });
+ writeFileSync(join(hermes, 'config.yaml'), 'model: alice-example-model\n');
+ if (opts.soul !== false) writeFileSync(join(hermes, 'SOUL.md'), 'You are a helpful agent.\n');
+ const bin = join(root, 'bin', 'gbrain');
+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
+ chmodSync(bin, 0o755);
+ return { home, hermes, project, bin, env: {
+ HOME: home, GBRAIN_HOME: home, HERMES_HOME: hermes, PATH: '/usr/bin:/bin', CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,
+ GBRAIN_SKILL_LOADING: undefined, GBRAIN_HOOK_LANE: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_HOOKS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ } };
+}
+function skill(dir: string, name: string, description: string): void {
+ mkdirSync(join(dir, name), { recursive: true });
+ writeFileSync(join(dir, name, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\nSteps.\n`);
+}
+async function setup(b: Box, extra: string[]) {
+ const r = await runCli(['setup', 'hermes', '--gbrain-bin', b.bin, ...extra], { env: b.env, cwd: b.project });
+ let doc: any = null;
+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }
+ return { ...r, doc };
+}
+const configPath = (b: Box) => join(b.home, '.gbrain', 'config.json');
+const isResolver = (c: string) => c.includes('GBRAIN_HOOK_LANE=skill-resolver');
+const isRule = (c: string) => c.startsWith('/bin/echo ');
+
+describe('setup hermes --skill-loading resolve', () => {
+ test('on beside the turn rule, nested skill folders indexed; declining the rule keeps the resolver; off restores config.yaml', async () => {
+ const b = box();
+ skill(join(b.hermes, 'skills', 'devops'), 'deploy-widget', 'Deploy the widget service.');
+ const on = await setup(b, ['--skill-loading', 'resolve']);
+ expect(on.exitCode, on.stderr + on.stdout).toBe(0);
+ expect(on.stdout).toMatch(/skill resolver: on; 1 skills; fresh/);
+ expect(JSON.parse(read(configPath(b))!)).toEqual({ skills: { resolver: { enabled: true, harnesses: ['hermes'] } } });
+ expect(existsSync(join(b.home, '.gbrain', 'skill-index', 'hermes-user', 'receipt.json'))).toBe(true);
+ const both = entries(b.hermes).map((e) => e.command);
+ expect(both.length).toBe(2);
+ expect(isRule(both[0]!) && isResolver(both[1]!)).toBe(true);
+ expect(both[1]).toContain(`${b.bin} hook user-prompt --harness hermes`);
+ expect(approvals(b.hermes).sort()).toEqual([...both].sort());
+
+ const again = await setup(b, ['--skill-loading', 'resolve', '--json']);
+ expect(again.exitCode).toBe(0);
+ expect(again.doc.skill_resolver.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);
+
+ const declined = await setup(b, ['--no-instructions']);
+ expect(declined.exitCode, declined.stderr).toBe(0);
+ expect(entries(b.hermes).map((e) => e.command)).toEqual([both[1]]);
+ expect(approvals(b.hermes)).toEqual([both[1]]);
+
+ const off = await setup(b, ['--skill-loading', 'off']);
+ expect(off.exitCode, off.stderr).toBe(0);
+ expect(read(join(b.hermes, 'config.yaml'))).toBe('model: alice-example-model\n');
+ expect(approvals(b.hermes)).toEqual([]);
+ expect(read(configPath(b))).toBeNull();
+ });
+
+ test('a brainless, keyless install stays brainless: the config file holds only the resolver keys', async () => {
+ const b = box();
+ skill(join(b.hermes, 'skills'), 'deploy-widget', 'Deploy the widget service.');
+ expect((await setup(b, ['--no-instructions', '--skill-loading', 'resolve'])).exitCode).toBe(0);
+ expect(JSON.parse(read(configPath(b))!)).toEqual({ skills: { resolver: { enabled: true, harnesses: ['hermes'] } } });
+ expect(entries(b.hermes).map((e) => isResolver(e.command))).toEqual([true]);
+ expect(existsSync(join(b.home, '.gbrain', 'brain.pglite'))).toBe(false);
+ });
+
+ test('no SOUL.md: the resolver is still installed and SOUL.md is never created', async () => {
+ const b = box({ soul: false });
+ skill(join(b.hermes, 'skills'), 'deploy-widget', 'Deploy the widget service.');
+ const on = await setup(b, ['--skill-loading', 'resolve']);
+ expect(on.exitCode, on.stderr + on.stdout).toBe(0);
+ expect(entries(b.hermes).map((e) => isResolver(e.command))).toEqual([true]);
+ expect(existsSync(join(b.hermes, 'SOUL.md'))).toBe(false);
+ });
+
+ test('pins: none writes no block; a pin lands in a marked SOUL.md block; removing it, or the lane, strips the block', async () => {
+ const b = box();
+ skill(join(b.hermes, 'skills'), 'deploy-widget', 'Deploy the widget service.');
+ expect((await setup(b, ['--no-instructions', '--skill-loading', 'resolve'])).exitCode).toBe(0);
+ expect(read(join(b.hermes, 'SOUL.md'))).toBe('You are a helpful agent.\n');
+ const add = await runCli(['skills', 'pin', 'add', 'deploy-widget', '--catalog', 'hermes-user', '--line', 'when shipping the widget'], { env: b.env, cwd: b.project });
+ expect(add.exitCode, add.stderr).toBe(0);
+ const soul = read(join(b.hermes, 'SOUL.md'))!;
+ expect(soul.startsWith('You are a helpful agent.\n<!-- gbrain:skill-pins:begin -->\n<pinned_skills>')).toBe(true);
+ expect(soul).toContain('- id: "deploy-widget" when: "when shipping the widget"');
+ expect((await setup(b, ['--json'])).doc.skill_resolver.steps.find((s: any) => s.step === 'pins')).toMatchObject({ action: 'keep' });
+ expect((await runCli(['skills', 'pin', 'remove', 'deploy-widget', '--catalog', 'hermes-user'], { env: b.env, cwd: b.project })).exitCode).toBe(0);
+ expect(read(join(b.hermes, 'SOUL.md'))).toBe('You are a helpful agent.\n');
+ expect((await runCli(['skills', 'pin', 'add', 'deploy-widget', '--catalog', 'hermes-user'], { env: b.env, cwd: b.project })).exitCode).toBe(0);
+ expect(read(join(b.hermes, 'SOUL.md'))).toContain('gbrain:skill-pins:begin');
+ expect((await setup(b, ['--skill-loading', 'off'])).exitCode).toBe(0);
+ expect(read(join(b.hermes, 'SOUL.md'))).toBe('You are a helpful agent.\n');
+ });
+
+ test('the user\'s own hooks: section: refuses with the entry to paste and writes nothing to config.yaml', async () => {
+ const b = box();
+ const theirs = 'hooks:\n pre_tool_call:\n - command: /usr/bin/true\n';
+ writeFileSync(join(b.hermes, 'config.yaml'), theirs);
+ skill(join(b.hermes, 'skills'), 'deploy-widget', 'Deploy the widget service.');
+ const r = await setup(b, ['--no-instructions', '--skill-loading', 'resolve']);
+ expect(r.exitCode).not.toBe(0);
+ expect(`${r.stdout}${r.stderr}`).toContain('skill_resolver_setup_incomplete');
+ expect(`${r.stdout}${r.stderr}`).toContain('pre_llm_call');
+ expect(read(join(b.hermes, 'config.yaml'))).toBe(theirs);
+ });
+
+ test('config set takes per_harness.hermes.owner_sender_ids as a list, without a brain, and refuses it for another harness', async () => {
+ const b = box();
+ const run = (...args: string[]) => runCli(['config', ...args], { env: b.env, cwd: b.project });
+ expect((await run('set', 'skills.resolver.per_harness.hermes.owner_sender_ids', 'alice-example, bob-example')).exitCode).toBe(0);
+ expect(JSON.parse(read(configPath(b))!)).toEqual({ skills: { resolver: { per_harness: { hermes: { owner_sender_ids: ['alice-example', 'bob-example'] } } } } });
+ expect((await run('set', 'skills.resolver.per_harness.codex.owner_sender_ids', 'alice-example')).exitCode).not.toBe(0);
+ expect((await run('unset', 'skills.resolver.per_harness.hermes.owner_sender_ids')).exitCode).toBe(0);
+ expect(read(configPath(b))).toBeNull();
+ });
+
+ test('doctor reports the Hermes hook, and warns when its approval is gone', async () => {
+ const b = box();
+ skill(join(b.hermes, 'skills'), 'deploy-widget', 'Deploy the widget service.');
+ expect((await setup(b, ['--no-instructions', '--skill-loading', 'resolve'])).exitCode).toBe(0);
+ const doctor = async () => JSON.parse((await runCli(['doctor', '--only', 'skill_resolver', '--json'], { env: b.env, cwd: b.project })).stdout).checks.find((c: any) => c.name === 'skill_resolver');
+ expect(await doctor()).toMatchObject({ status: 'ok', details: { harnesses: [{ harness: 'hermes', on: true, hook: 'wired', catalogs: [{ name: 'hermes-user', fresh: true, skills: 1 }] }] } });
+ writeFileSync(join(b.hermes, 'shell-hooks-allowlist.json'), JSON.stringify({ approvals: [] }));
+ const warn = await doctor();
+ expect(warn.status).toBe('warn');
+ expect(warn.message).toContain('not approved');
+ expect(warn.fix.argv).toEqual(['gbrain', 'setup', 'hermes', '--skill-loading', 'resolve']);
+ });
+});
diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.ts
index 32fbfae8d3..43ddb7839e 100644
--- a/test/skill-resolver-hook-lane.test.ts
+++ b/test/skill-resolver-hook-lane.test.ts
@@ -14,7 +14,10 @@
* project root down to cwd) is built out of the turn and merged at rank time;
* a built claude-code-plugins catalog is searched; no built catalog ends the
* turn as no_catalog; Hermes reads extra.user_message from a stream of any size
- * and answers {"context"}; with the lane off it prints and writes nothing.
+ * and answers {"context"}, starts a session fresh on its first turn or when
+ * its history shrinks (in-place compaction), and honours
+ * per_harness.hermes.owner_sender_ids; with the lane off it prints and writes
+ * nothing.
*/
import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -23,7 +26,8 @@ import { join } from 'node:path';
import { Readable } from 'node:stream';
import { runCli } from './helpers/cli-spawn.ts';
import { CLAUDE_PLUGINS_CATALOG, LANE_DEADLINE_MS, projectCatalogPrefix, WORKER_SRC_PATH } from '../src/core/skills/resolver/hook-lane.ts';
-import { HOOK_FIELD_CAP, readJsonFields } from '../src/core/skills/resolver/hook-input.ts';
+import { HOOK_FIELD_CAP, readHookFields, readJsonFields } from '../src/core/skills/resolver/hook-input.ts';
+import { historyShrank, sessionKey } from '../src/core/skills/resolver/session.ts';
import { MESSAGE_CAP_BYTES } from '../src/core/skills/resolver/resolve.ts';
import { dailyLogFile, LANE_LOG } from '../src/core/skills/resolver/daily-log.ts';
@@ -589,6 +593,51 @@ describe('skill-resolver lane: hermes', () => {
}
});
+ test('in-place compaction: a history shorter than the last turn saw offers a deduped skill again; a longer or unknown one does not', async () => {
+ const b = await hermesBox();
+ const ask = (n: number | null) => hook(b, hermesCmd(b), { session_id: 'h5', extra: { user_message: 'please deploy the widget to staging', ...(n === null ? {} : { conversation_history: history(n * 200).slice(0, n) }) } }, WIDE);
+ expect(JSON.parse((await ask(4)).stdout).context).toContain('id: "deploy-widget"');
+ expect((await ask(6)).stdout).toBe('');
+ expect((await ask(null)).stdout).toBe('');
+ expect(JSON.parse((await ask(2)).stdout).context).toContain('id: "deploy-widget"');
+ expect((await ask(3)).stdout).toBe('');
+ });
+
+ test('is_first_turn starts the session fresh even when the history did not shrink', async () => {
+ const b = await hermesBox();
+ const turn = (first: boolean) => ({ session_id: 'h6', extra: { user_message: 'please deploy the widget to staging', conversation_history: [], is_first_turn: first } });
+ expect(JSON.parse((await hook(b, hermesCmd(b), turn(true), WIDE)).stdout).context).toContain('id: "deploy-widget"');
+ expect((await hook(b, hermesCmd(b), turn(false), WIDE)).stdout).toBe('');
+ expect(JSON.parse((await hook(b, hermesCmd(b), turn(true), WIDE)).stdout).context).toContain('id: "deploy-widget"');
+ });
+
+ test('owner_sender_ids: a listed sender gets the block; an unlisted, empty or missing sender gets none, as in the OpenClaw plugin', async () => {
+ const b = await hermesBox({ per_harness: { hermes: { owner_sender_ids: ['alice-example'] } } });
+ const ask = (id: string, sender?: string) => hook(b, hermesCmd(b), { session_id: id, extra: { user_message: 'please deploy the widget to staging', ...(sender === undefined ? {} : { sender_id: sender }) } }, WIDE);
+ expect((await ask('h7a', '')).stdout).toBe('');
+ expect((await ask('h7b')).stdout).toBe('');
+ expect((await ask('h7c', 'bob-example')).stdout).toBe('');
+ expect(laneLog(b).map((l) => l.outcome)).toEqual(['skipped_sender', 'skipped_sender', 'skipped_sender']);
+ expect(sessions(b)).toEqual([]);
+ expect(JSON.parse((await ask('h7d', 'alice-example')).stdout).context).toContain('id: "deploy-widget"');
+ const open = await hermesBox({ per_harness: { hermes: { owner_sender_ids: [] } } });
+ expect(JSON.parse((await hook(open, hermesCmd(open), { session_id: 'h7e', extra: { user_message: 'please deploy the widget to staging', sender_id: '' } }, WIDE)).stdout).context).toContain('id: "deploy-widget"');
+ });
+
+ test('a stored session from before the history field, or a turn with no history, never resets', async () => {
+ const b = await hermesBox();
+ const home = join(b.home, '.gbrain');
+ const key = sessionKey('on', 'hermes', 'h8');
+ mkdirSync(join(b.home, '.gbrain', 'skill-index', 'sessions'), { recursive: true });
+ writeFileSync(join(b.home, '.gbrain', 'skill-index', 'sessions', key + '.json'), JSON.stringify({ v: 1, turn: 3, spent: 10, last: { 'deploy-widget': 3 }, again: {} }));
+ expect(await historyShrank(home, key, 0)).toBe(false);
+ expect(await historyShrank(home, key, undefined)).toBe(false);
+ expect(await historyShrank(home, sessionKey('on', 'hermes', 'none-yet'), 0)).toBe(false);
+ writeFileSync(join(b.home, '.gbrain', 'skill-index', 'sessions', key + '.json'), JSON.stringify({ v: 1, turn: 3, spent: 10, last: {}, again: {}, history: 5 }));
+ expect(await historyShrank(home, key, 4)).toBe(true);
+ expect(await historyShrank(home, key, 5)).toBe(false);
+ });
+
test('skills.resolver.lane_payload_chars caps the Hermes JSON too', async () => {
const b = await hermesBox({ lane_payload_chars: 500 });
const r = await hook(b, hermesCmd(b), { session_id: 'h4', extra: { user_message: 'deploy the widget, write the changelog and triage the bug' } }, WIDE);
@@ -625,3 +674,29 @@ describe('readJsonFields: the bounded streaming hook reader', () => {
expect(await readJsonFields(chunks('{"session_id": 7, "extra": {"user_message": ["x"]}}', 4), PATHS, 100)).toEqual({});
});
});
+
+describe('readHookFields: counts and flags in the same streaming pass', () => {
+ const chunks = (text: string, size: number) => { const bytes = Buffer.from(text); return Readable.from(Array.from({ length: Math.ceil(bytes.length / size) }, (_, i) => bytes.subarray(i * size, (i + 1) * size))); };
+ const SPEC = { strings: ['extra.user_message'], counts: ['extra.conversation_history'], flags: ['extra.is_first_turn'] };
+
+ test('counts top-level items only (nested arrays and commas inside strings do not count) across any chunk boundary, and reads booleans', async () => {
+ const history = [{ role: 'user', content: 'a, b, [c], {d}' }, [1, [2, 3]], 'x,y', 4, null, { content: '\\",' }];
+ const text = JSON.stringify({ extra: { conversation_history: history, is_first_turn: false, user_message: 'hi' } });
+ for (const size of [1, 2, 5, 64 * 1024]) {
+ expect(await readHookFields(chunks(text, size), SPEC, 100)).toEqual({ strings: { 'extra.user_message': 'hi' }, counts: { 'extra.conversation_history': history.length }, flags: { 'extra.is_first_turn': false } });
+ }
+ for (const [doc, n] of [['[]', 0], ['[ ]', 0], [' [5]', 1], ['[{}]', 1], ['["",""]', 2]] as const) {
+ expect((await readHookFields(chunks('{"extra":{"conversation_history":' + doc + '}}', 1), SPEC, 100))?.counts).toEqual({ 'extra.conversation_history': n });
+ }
+ });
+
+ test('a 5 MB history is counted; a stream cut off inside it yields null; a non-array or non-boolean value is left out', async () => {
+ const item = { role: 'user', content: 'An earlier turn, with "quotes" and a , comma.' };
+ const big = Array.from({ length: Math.ceil(5e6 / JSON.stringify(item).length) }, () => item);
+ const text = JSON.stringify({ extra: { conversation_history: big, user_message: 'deploy', is_first_turn: true } });
+ expect(text.length).toBeGreaterThan(5e6);
+ expect(await readHookFields(chunks(text, 64 * 1024), SPEC, 100)).toEqual({ strings: { 'extra.user_message': 'deploy' }, counts: { 'extra.conversation_history': big.length }, flags: { 'extra.is_first_turn': true } });
+ expect(await readHookFields(chunks(text.slice(0, 3e6), 64 * 1024), SPEC, 100)).toBeNull();
+ expect(await readHookFields(chunks('{"extra":{"conversation_history":"many","is_first_turn":1}}', 3), SPEC, 100)).toEqual({ strings: {}, counts: {}, flags: {} });
+ });
+});