Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
turn rule names tools behind tool_search; brain_hot_memory docs; QM advertise verbs; guides
garrytan2f85ece382d0
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex d763ecab92..5af7db07bd 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -30,6 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners; on the brain it just created it runs the setup migrations init left pending (`finishFreshSetupMigrations`, `src/commands/setup-migrations.ts`: one `apply-migrations --yes --no-autopilot-install --json` child built by `setupMigrationsArgv` in `migrations/fresh-install.ts`, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing `~/.claude/AGENTS.md`, `~/.openclaw/AGENTS.md` or OpenClaw cron manifest (`hostRewriteTargets`)) and replaces init's `[init] Migrations:` line with `[setup] Migrations: …` (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a `Memory:` line naming `remember` (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer, so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`); `gbrain post-upgrade` prints the same command (`brain-first-upgrade-notice.ts`, `instructionBlockUpgradeHints`). The Claude Code and Codex plugin manifests declare setup's UserPromptSubmit hook with `GBRAIN_HOOK_LANE=plugin`; it yields when another gbrain lane wires the event (`bootstrap/plugin-lanes.ts` `pluginHookYields`; `test/plugin-turn-hook.test.ts`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).+- `src/core/setup/turn-hook.ts` + `src/core/setup/turn-hook-check.ts` — the per-turn rule hook for installs whose MCP came from a plain `mcp add` or another installer: a `turn-rule-v1` Claude Code UserPromptSubmit entry or a Codex `hooks.json` group plus its `config.toml` trust entry, running `GBRAIN_HOOK_LANE=turn-rule gbrain hook user-prompt` (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by `setup <claude-code|codex> --instructions-only`, `connect --install`, the hosted `harness connect --install` and `bootstrap harness` (not in registrar mode); with no absolute binary the outcome is `print` with the one-line next step. `inspectTurnHook` (files only) feeds doctor `harness_wiring` (`turnHookViews`, `withTurnHooks`: untrusted, or missing beside a ledger block, warns with code `turn_hook_not_loaded`); `verifyTurnHook` runs the hook (Claude Code, Codex), `openclaw plugins inspect gbrain-turn-rule --runtime --json` or `hermes hooks doctor`, and every install path exits non-zero with `turn_hook_not_loaded` when it fails (`docs/guides/repair.md#turn-hook-not-loaded`). OpenClaw and Hermes rules name the gbrain tools and the `tool_search` route (`renderBrainFirstTurnRule(access, harness)`; `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`).- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.diff --git a/docs/integrations/qm-harness.md b/docs/integrations/qm-harness.mdindex aad0200c56..2c561f13cc 100644--- a/docs/integrations/qm-harness.md+++ b/docs/integrations/qm-harness.md@@ -131,11 +131,19 @@ gbrain config set mcp.publish_advisor truegbrain sources add org-wiki --path ~/brains/org-wikigbrain sync --all # cron this-# 4. Serve over HTTP MCP (OAuth 2.1):+# 4. Serve over HTTP MCP (OAuth 2.1), listing the 7 memory verbs:gbrain serve --http --bind 0.0.0.0 --port 3131 \- --public-url https://brain.acme-example.com+ --public-url https://brain.acme-example.com --advertise verbs```+`--advertise verbs` is the registration default gbrain's own installers use+(`--surface starter --advertise verbs` since v0.60.503.0). QM sends every listed+tool schema on every request, so a bare serve costs each turn about 11,800 input+tokens for 33 tool schemas; with `--advertise verbs` it lists the seven verbs+plus `request_tools`. Every operation stays callable, so the `gbrain` tool in the+sandbox keeps working: the server keeps the `full` ceiling here because the+skill's `gbrain link` (`add_link`) is outside `starter`.+Never hand sandboxes `DATABASE_URL` — direct DB access bypasses OAuth, sourcefederation, and the write fence entirely.diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.mdindex f3d9c80f39..1898696b27 100644--- a/docs/mcp/CLAUDE_CODE.md+++ b/docs/mcp/CLAUDE_CODE.md@@ -193,8 +193,16 @@ re-run upgrades the block in place, `--dry-run` previews it,`gbrain setup claude-code` and `gbrain connect --install` write it for you.While the block is installed, setup's UserPromptSubmit hook also leads every turnwith the same rule, beside the user's message, whether or not `gbrain serve` has-context to add (`--no-hooks` installs no hook).-`gbrain doctor` warns when the block is missing or out of date.+context to add (`--no-hooks` installs no hook). After a plain `claude mcp add`,+`--instructions-only` adds that hook on its own (a `turn-rule-v1` entry in+`~/.claude/settings.json` that prints only the rule and reads no brain data),+unless setup, bootstrap or a gbrain plugin already carries it. It runs the hook+once to prove it loads and exits non-zero with `turn_hook_not_loaded` when it+does not ([repair](../guides/repair.md#turn-hook-not-loaded)); `/hooks` inside a+session lists it. With no absolute gbrain binary to put in the hook, it prints+the step instead.+`gbrain doctor` warns when the block is missing or out of date, or its per-turn+hook is missing or untrusted.## Verifydiff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.mdindex cf4783537f..2e1383e69a 100644--- a/docs/mcp/CODEX.md+++ b/docs/mcp/CODEX.md@@ -212,7 +212,14 @@ re-run upgrades the block in place, `--dry-run` previews it,`gbrain setup codex` and `gbrain connect --agent codex --install` write it foryou; the Codex plugin and a hand-run `codex mcp add` do not. While the block isinstalled, setup's UserPromptSubmit hook also leads every turn with the same rule.-`gbrain doctor` warns when the block is missing or out of date.+After a hand-run `codex mcp add`, `--instructions-only` adds that hook on its own+(a group in `$CODEX_HOME/hooks.json` that prints only the rule, trusted in+`config.toml`), unless setup, bootstrap or a gbrain plugin already carries it. It+runs the hook once and exits non-zero with `turn_hook_not_loaded` when it does+not load ([repair](../guides/repair.md#turn-hook-not-loaded)); `/hooks` inside a+session lists it.+`gbrain doctor` warns when the block is missing or out of date, or its per-turn+hook is missing or untrusted.## Always-loaded core memorydiff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.mdindex af92ed0b7b..bb4babb783 100644--- a/docs/mcp/HERMES.md+++ b/docs/mcp/HERMES.md@@ -72,9 +72,20 @@ reaches the model next to the turn instead of only in the system prompt. Textoutside the markers is never touched, and a re-run after an upgrade rewrites thecommand and moves its approval. When config.yaml already has a `hooks:` section,setup prints the entry to add yourself instead; approve it when Hermes asks (or-set `HERMES_ACCEPT_HOOKS=1`). `hermes hooks doctor` checks it.+set `HERMES_ACCEPT_HOOKS=1`). `hermes hooks doctor` checks it: setup runs it+when `hermes` is on PATH and exits non-zero with `turn_hook_not_loaded` when the+hook is not healthy ([repair](../guides/repair.md#turn-hook-not-loaded)).`--no-instructions` and `--remove` take the hook and its approval out.+Hermes lists gbrain's tools only inside `tool_search`'s description, so with an+MCP connection the rule also names them (`mcp_gbrain_recall`, `mcp_gbrain_entity`+and the rest) and says to find them with `tool_search`.++Search results also carry `_meta.brain_hot_memory`, the brain's recent facts.+Hermes may pass them to the model; they can include other sessions' facts, so+see [the channel's contract](../protocol/MCP_META_CHANNELS.md#brain_hot_memory)+before relying on them.+## Direct config (equally supported)The add command writes an `mcp_servers` block into `$HERMES_HOME/config.yaml`diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.mdindex d0e62b730b..9be826b9dd 100644--- a/docs/mcp/OPENCLAW.md+++ b/docs/mcp/OPENCLAW.md@@ -108,6 +108,15 @@ and prints those commands to run on the OpenClaw host; restart a running gatewayafterwards. `--no-instructions` and `--remove` uninstall the plugin and deleteits directory. A re-run after an upgrade rewrites the plugin with the new text.+OpenClaw lists no gbrain tool after `openclaw mcp set`: the model reaches them+only through `tool_search`, whose results it frames as external data. With an+MCP connection the rule therefore names the tools (`recall`, `entity`, `search`,+`query`) and says to find them with `tool_search` and run them with `tool_call`.+With `openclaw` on PATH, setup runs+`openclaw plugins inspect gbrain-turn-rule --runtime --json` and exits non-zero+with `turn_hook_not_loaded` unless the plugin shows as loaded with+`before_prompt_build` ([repair](../guides/repair.md#turn-hook-not-loaded)).+## Scheduled jobs and workspace scriptsOpenClaw cron jobs, workspace scripts and hooks run with another `HOME` anddiff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex 0e4f0bb0b2..e0f0d49089 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -30,11 +30,77 @@ shape for it.| Key | Producer | Contents ||-----|----------|----------|-| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call; each fact carries `trust_tier` and `origin`, and `suppressed` (`{withheld, review}`, present only when non-zero) counts unconfirmed agent-written facts activation control withheld, never their content |+| `brain_hot_memory` | dispatch `metaHook` on stdio and HTTP (`getBrainHotMemoryMeta`, [details](#brain_hot_memory)) | Hot-memory facts relevant to the call; each fact carries `trust_tier` and `origin`, and `suppressed` (`{withheld, review}`, present only when non-zero) counts unconfirmed agent-written facts activation control withheld, never their content || `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |+## `brain_hot_memory`++The brain's recent facts, attached to tool results so a harness can keep them+in front of the model without a separate call.++**When it is sent.** On a successful tool call over stdio (`gbrain serve`) and+over HTTP (`gbrain serve --http`), except `recall`, `extract_facts` and+`forget_fact`, which already return facts. It is absent when there is nothing+to send, and it is best-effort: if it cannot be built, the key is left out and+the tool call still succeeds. It cannot be turned off per call.++**Which facts.** Up to 10 facts from the call's source, ranked by decayed+confidence, with duplicates collapsed:++- facts recorded in the caller's session, when the request carries+ `_meta.session_id` (beside `arguments` or at request level); otherwise+- the source's newest facts from the last 24 hours, from any session.+ `context.hot_memory.session_only` narrows only the hook and `context_pack`+ paths, never this key.++Remote callers get world-visible facts only (private pages are excluded unless+`search.remote_private_pages` allows them), and the trust floor, quarantine and+activation control apply. Payloads are cached for up to 30 seconds per engine,+source, tier, session and eligibility; any write, forget or trust change+invalidates them.++**Shape** (fields are additive-forever, per rule 2):++```json+{+ "brain_hot_memory": {+ "source_id": "default",+ "session_id": "s-123",+ "suppressed": { "withheld": 1, "review": 0 },+ "facts": [+ {+ "id": 42, "fact": "Prefers morning meetings", "kind": "preference",+ "notability": "high", "entity_slug": "people/alice-example",+ "valid_from": "2026-10-01T00:00:00.000Z", "created_at": "2026-10-01T09:30:00.000Z",+ "context": null, "confidence": 0.91,+ "trust_tier": "agent_written", "origin": "mcp:user_said", "unconfirmed": true+ }+ ]+ }+}+```++`suppressed` appears only when activation control withheld facts, and counts+them without their content. `attributed_to`, `entity_slugs` and `unconfirmed`+appear only when set.++**Using it from a harness.** Most harnesses drop `_meta` before the model+(rule 5), so these facts reach the model only if the harness copies them in:++1. Send a stable `_meta.session_id` per conversation, so the block carries+ that conversation's facts instead of the source's newest.+2. Read `result._meta.brain_hot_memory.facts` from each tool result and add+ them to the next model turn as context, labeled as saved memory.+3. Apply your own access rules before showing them: the 24-hour fallback can+ carry another session's facts, such as a different user's direct messages+ on a shared brain. Treat `unconfirmed: true` and `trust_tier:+ "agent_written"` facts as claims to check, not as the user's words.++A harness that cannot do this still gets the same facts on purpose through the+per-turn hook or `context_pack` ([ambient writeback](../guides/ambient-writeback.md)).+Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS) is aseparate, client-to-server plane. The eval-report `_meta.metric_glossary`lives in JSON BODIES of eval commands — a third, unrelated plane. Ambientdiff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex b6b1bf59eb..e88b27f311 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -204,7 +204,7 @@ const SUBCOMMAND_HELP: Record<string, string> = {hooks:'gbrain bootstrap hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]\n' +' [--seat <label> | --no-seat] [--surface verbs|starter|full] [--adopt [--name <server>]]\n' +- ` Register MCP (--surface ${REGISTRATION_SURFACE} --advertise ${REGISTRATION_ADVERTISE} unless given; a replaced entry keeps its surface) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n` ++ ` Register MCP (--surface ${REGISTRATION_SURFACE} --advertise ${REGISTRATION_ADVERTISE} unless given; a replaced entry keeps its surface, full when unreadable) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n` +' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).\n' +' --adopt (Codex): record the project .codex/config.toml server you manage yourself as the wire evidence after a passing verify; writes no config.',verify:@@ -1487,7 +1487,7 @@ async function runHooks();return 1;}- const re = await runner(surfaceFlag || priorSurface === undefined ? argv : buildArgvs(priorSurface, priorAdvertise)[0]);+ const re = await runner(surfaceFlag ? argv : buildArgvs(priorSurface ?? 'full', priorAdvertise)[0]);if (re.code !== 0 && !/already exists|already registered/i.test(re.stderr + re.stdout)) {console.error(`MCP re-registration failed (${argv.join(' ')}): ${re.stderr.trim() || `exit ${re.code}`}`);return 1;diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex 59b0f2c7b6..935e54451a 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -84,11 +84,25 @@ export function renderBrainFirstSnippet(harness: string, access: BrainFirstAcces* left chat bots answering without the brain (harness-evals: 0 of 80 on* OpenClaw and Hermes); the same rule next to the turn was followed.*/-export function renderBrainFirstTurnRule(access: BrainFirstAccess): string {+export function renderBrainFirstTurnRule(access: BrainFirstAccess, harness?: string): string {const how = access.kind === 'cli' ? `\`${access.launcher} search "<names>"\` or \`${access.launcher} query "<question>"\``: access.surface === 'verbs' ? `\`recall\` or \`entity\` on the \`${access.server}\` MCP server`: `\`search\` or \`query\` on the \`${access.server}\` MCP server`;- return `GBrain: before answering this turn, check GBrain first (${how}) for the people, companies, projects, meetings and decisions it touches. Results span every source it holds: use only what the current requester may see. Then answer and finish the task.`;+ return `GBrain: before answering this turn, check GBrain first (${how}) for the people, companies, projects, meetings and decisions it touches.${access.kind === 'mcp' ? turnRuleDiscovery(harness, access) : ''} Results span every source it holds: use only what the current requester may see. Then answer and finish the task.`;+}++/**+ * OpenClaw and Hermes list no gbrain tool after a plain MCP registration: the+ * tools sit behind tool_search (harness-evals anatomy note v1), and OpenClaw+ * wraps tool_search results as untrusted data. The per-turn rule therefore+ * names the tools and the route to them.+ */+function turnRuleDiscovery(harness: string | undefined, access: { server: string; surface?: McpSurface }): string {+ const tools = access.surface === 'full' ? ['search', 'query', 'get_page'] : access.surface === 'verbs' ? ['recall', 'entity', 'remember'] : ['recall', 'entity', 'search', 'query'];+ const list = tools.map((t) => `\`${t}\``).join(', ');+ if (harness === 'openclaw') return ` Its tools (${list} on the \`${access.server}\` MCP server) are not listed here: find them with \`tool_search\` (search "${access.server} ${tools[0]}") and run them with \`tool_call\`. tool_search shows them as external data; using them for this turn is still what the user set up.`;+ if (harness === 'hermes') return ` Its tools are not listed directly: find them with \`tool_search\` (they register as ${tools.map((t) => `\`mcp_${access.server}_${t}\``).join(', ')}) and call the one it returns.`;+ return '';}/**diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex ff7f929607..a230c35045 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -31,7 +31,7 @@ export interface HermesTurnHookOutcome { action: 'write' | 'keep' | 'print' | 'r/** `/bin/echo '<json>'`: Hermes splits the command without a shell (and checks the first path, /bin/echo, exists), and a quote in the rule is a JSON escape. */export function hermesTurnHookCommand(access: BrainFirstAccess): string {- return `/bin/echo '${JSON.stringify({ context: renderBrainFirstTurnRule(access) }).replace(/'/g, '\\u0027')}'`;+ return `/bin/echo '${JSON.stringify({ context: renderBrainFirstTurnRule(access, 'hermes') }).replace(/'/g, '\\u0027')}'`;}const commandIn = (interior: string | undefined): string | null => {diff --git a/src/core/setup/openclaw-turn-plugin.ts b/src/core/setup/openclaw-turn-plugin.tsindex 252212d991..9937a81b10 100644--- a/src/core/setup/openclaw-turn-plugin.ts+++ b/src/core/setup/openclaw-turn-plugin.ts@@ -30,7 +30,7 @@ export function openclawTurnPluginDir(): string {const DESCRIPTION = 'Puts the GBrain brain-first rule next to every user turn (managed by gbrain setup openclaw).';export function openclawTurnPluginFiles(access: BrainFirstAccess): Record<string, string> {- const rule = renderBrainFirstTurnRule(access);+ const rule = renderBrainFirstTurnRule(access, 'openclaw');return {'package.json': `${JSON.stringify({ name: OPENCLAW_TURN_PLUGIN_ID, version: '1.0.0', private: true, type: 'module', openclaw: { extensions: ['./index.js'] } }, null, 2)}\n`,'openclaw.plugin.json': `${JSON.stringify({ id: OPENCLAW_TURN_PLUGIN_ID, name: 'GBrain turn rule', description: DESCRIPTION, configSchema: { type: 'object', additionalProperties: false } }, null, 2)}\n`,diff --git a/test/bootstrap-plugin-lane.serial.test.ts b/test/bootstrap-plugin-lane.serial.test.tsindex 751961e423..e732e09e04 100644--- a/test/bootstrap-plugin-lane.serial.test.ts+++ b/test/bootstrap-plugin-lane.serial.test.ts@@ -34,7 +34,7 @@ import {} from '../src/core/bootstrap/harness.ts';import { initState, setAnswer, readBackHash, confirm } from '../src/core/bootstrap/interview.ts';import { readReceipt } from '../src/core/bootstrap/format.ts';-import { REGISTRATION_SURFACE } from '../src/core/mcp-registration.ts';+import { REGISTRATION_ADVERTISE, REGISTRATION_SURFACE } from '../src/core/mcp-registration.ts';const REQUIRED_ANSWERS: Record<string, string> = {AGENT_NAME: 'Lanekeeper',@@ -284,7 +284,7 @@ describe('runHooks plugin-lane skip (serial: env fixtures)', () => {test('hooks --help names the real default surface (#7962)', async () => {const r = await capture(() => runBootstrap(['hooks', '--help']));- expect(r.out + r.err).toContain(`--surface ${REGISTRATION_SURFACE} unless given`);+ expect(r.out + r.err).toContain(`--surface ${REGISTRATION_SURFACE} --advertise ${REGISTRATION_ADVERTISE} unless given; a replaced entry keeps its surface, full when unreadable`);});test('codex + plugin + --mcp-even-if-plugin → registration forced through', async () => {diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex 7a15b7189d..921f829865 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -97,6 +97,22 @@ describe('per-turn rule: Claude Code and Codex user-prompt hook', () => {});});+describe('per-turn rule names the tools where tool_search hides them', () => {+ test('OpenClaw: names the gbrain tools and the tool_search / tool_call route; Hermes: names mcp_<server>_<tool>', () => {+ const starter = { kind: 'mcp', server: 'gbrain', surface: 'starter' } as const;+ const openclaw = renderBrainFirstTurnRule(starter, 'openclaw');+ expect(openclaw).toContain('find them with `tool_search` (search "gbrain recall") and run them with `tool_call`');+ expect(openclaw).toContain('`recall`, `entity`, `search`, `query` on the `gbrain` MCP server');+ expect(openclaw).toContain('tool_search shows them as external data');+ const hermes = renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain', surface: 'verbs' }, 'hermes');+ expect(hermes).toContain('find them with `tool_search` (they register as `mcp_brain_recall`, `mcp_brain_entity`, `mcp_brain_remember`)');+ // Claude Code and Codex list MCP tools directly; a CLI launcher needs no discovery.+ expect(renderBrainFirstTurnRule(starter, 'claude-code')).not.toContain('tool_search');+ expect(renderBrainFirstTurnRule(starter)).not.toContain('tool_search');+ expect(renderBrainFirstTurnRule({ kind: 'cli', launcher: '/opt/gbrain' }, 'openclaw')).not.toContain('tool_search');+ });+});+describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {const access: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };const cmd = hermesTurnHookCommand(access);@@ -117,8 +133,8 @@ describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {expect(c.endsWith("'")).toBe(true);const inner = c.slice("/bin/echo '".length, -1);expect(inner).not.toContain("'");- expect(JSON.parse(inner)).toEqual({ context: renderBrainFirstTurnRule(quoted) });- expect(JSON.parse(cmd.slice("/bin/echo '".length, -1))).toEqual({ context: renderBrainFirstTurnRule(access) });+ expect(JSON.parse(inner)).toEqual({ context: renderBrainFirstTurnRule(quoted, 'hermes') });+ expect(JSON.parse(cmd.slice("/bin/echo '".length, -1))).toEqual({ context: renderBrainFirstTurnRule(access, 'hermes') });});test('a flow-style config.yaml, or an allowlist gbrain cannot read, gets the entry printed and both files left as they are', () => {@@ -264,7 +280,7 @@ describe('per-turn rule: OpenClaw before_prompt_build plugin', () => {const handlers: Record<string, () => unknown> = {};mod.default.register({ on: (event: string, fn: () => unknown) => { handlers[event] = fn; } });expect(Object.keys(handlers)).toEqual(['before_prompt_build']);- expect(handlers.before_prompt_build()).toEqual({ prependContext: renderBrainFirstTurnRule(access) });+ expect(handlers.before_prompt_build()).toEqual({ prependContext: renderBrainFirstTurnRule(access, 'openclaw') });expect(syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run }).action).toBe('keep');});});