Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat: per-turn brain-first rule on every install lane (GBRA-188 ask 4)

garrytan3f4a91f92dd4
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 215273726d..b10fe10d24 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -153,7 +153,7 @@ Registering MCP makes the tools available; it does not make agents use them.
Without a line in the harness's own instructions, sessions rarely call the
brain. So setup also writes one short marked block (`<!-- gbrain:brain-first:begin -->`
… `<!-- gbrain:brain-first:end -->`) into the file the harness loads every
-session: search the brain before reading sources one by one, read the best hit,
+session: before answering any turn, search the brain first, read the best hit,
fill gaps with other tools, apply your own access rules (`source_ids` narrows a
search to what the current requester may see), then finish the task.
@@ -179,6 +179,14 @@ install, and the thin-client `GBRAIN-INSTRUCTIONS.md` starts with it.
`gbrain doctor` (`harness_wiring`) warns when a registered harness's block is
missing, stale or damaged, with a fix that rewrites only the block.
+A rule in the system prompt is easy for a model to pass over, so the same rule
+also rides each turn where the harness has a per-turn hook: Claude Code and
+Codex get it from setup's UserPromptSubmit hook while the block is installed,
+OpenClaw from gbrain's context engine, and Hermes from a marked `pre_llm_call`
+hook (`gbrain hook turn-rule`) that `gbrain setup hermes` adds to its config.yaml.
+Cursor's rule is always applied; opencode reads its AGENTS.md on every request.
+The opt-out turns the per-turn rule off with the block.
+
## Harness capability table
The table is data (`src/core/setup/capabilities.ts`, version 2). Push is never
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 531dda9315..8506d5900d 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -174,12 +174,15 @@ brain nobody told them about, so finish the install with:
gbrain setup claude-code --instructions-only
```
-It writes one short marked block into `~/.claude/CLAUDE.md` (with `--scope project`, `./CLAUDE.local.md`): search the brain before reading
-sources one by one, read the best hit, fill gaps with other tools, apply your own
+It writes one short marked block into `~/.claude/CLAUDE.md` (with `--scope project`, `./CLAUDE.local.md`): before answering any turn,
+search the brain first, read the best hit, fill gaps with other tools, apply your own
access rules, then finish the task. Text outside the markers is never touched, a
re-run upgrades the block in place, `--dry-run` previews it,
`--no-instructions` opts out (and is remembered) and `--remove` takes it out.
`gbrain setup claude-code` and `gbrain connect --install` write it for you.
+While the block is installed, setup's UserPromptSubmit hook also leads every turn
+with 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.
## Verify
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index d75c298be7..df4234a361 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -192,13 +192,14 @@ gbrain setup codex --instructions-only
```
It writes one short marked block into `$CODEX_HOME/AGENTS.md` (or a non-empty `AGENTS.override.md`, since Codex
-then reads only the override): search the brain before reading
-sources one by one, read the best hit, fill gaps with other tools, apply your own
+then reads only the override): before answering any turn,
+search the brain first, read the best hit, fill gaps with other tools, apply your own
access rules, then finish the task. Text outside the markers is never touched, a
re-run upgrades the block in place, `--dry-run` previews it,
`--no-instructions` opts out (and is remembered) and `--remove` takes it out.
`gbrain setup codex` and `gbrain connect --agent codex --install` write it for
-you; the Codex plugin and a hand-run `codex mcp add` do not.
+you; the Codex plugin and a hand-run `codex mcp add` do not. While the block is
+installed, setup's UserPromptSubmit hook also leads every turn with the same rule.
`gbrain doctor` warns when the block is missing or out of date.
## Always-loaded core memory
diff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.md
index bdea4442e0..1201b80945 100644
--- a/docs/mcp/HERMES.md
+++ b/docs/mcp/HERMES.md
@@ -40,8 +40,8 @@ gbrain setup hermes --instructions-only
```
It writes one short marked block into `$HERMES_HOME/SOUL.md` (default `~/.hermes/SOUL.md`), after your identity
-text, which stays first and unchanged: search the brain before reading
-sources one by one, read the best hit, fill gaps with other tools, apply your own
+text, which stays first and unchanged: before answering any turn,
+search the brain first, read the best hit, fill gaps with other tools, apply your own
access rules, then finish the task. Text outside the markers is never touched, a
re-run upgrades the block in place, `--dry-run` previews it,
`--no-instructions` opts out (and is remembered) and `--remove` takes it out.
@@ -49,6 +49,24 @@ re-run upgrades the block in place, `--dry-run` previews it,
creates `SOUL.md`: Hermes uses a non-empty one instead of its default identity,
so start Hermes once (it seeds the file) or write your identity there first.
+The same rule also rides every turn. Setup appends a marked `pre_llm_call` shell
+hook to `$HERMES_HOME/config.yaml` and records its approval in Hermes's
+`shell-hooks-allowlist.json` for that exact command:
+
+```yaml
+hooks:
+ pre_llm_call:
+ - command: "/absolute/path/to/gbrain hook turn-rule"
+```
+
+Hermes appends the hook's `{"context": ...}` output to each user message, so the
+rule reaches the model next to the turn instead of only in the system prompt.
+Text outside the markers is never touched. When config.yaml already has a
+`hooks:` section, or setup has no absolute gbrain path (`--gbrain-bin`), setup
+prints the entry to add yourself instead; approve it when Hermes asks (or set
+`HERMES_ACCEPT_HOOKS=1`). `--no-instructions` and `--remove` take the hook and its
+approval out, and the hook prints nothing under `GBRAIN_AGENT_INSTRUCTIONS=0`.
+
## 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.md
index a56549d0ae..30ca9f9a5b 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -86,7 +86,9 @@ workspace, else `agents.defaults.workspace`, else `~/.openclaw/workspace`; with
several agents, pass `--workspace`). Text outside the markers is never touched,
a re-run upgrades the block in place, `--no-instructions` opts out and is
remembered, and `--remove` takes it out. A thin-client install puts the same
-block at the top of `GBRAIN-INSTRUCTIONS.md`.
+block at the top of `GBRAIN-INSTRUCTIONS.md`. With gbrain's context engine plugin, the
+same rule also rides every turn in its per-turn addition (off after
+`--no-instructions` or under `GBRAIN_AGENT_INSTRUCTIONS=0`).
## Scheduled jobs and workspace scripts
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 502fbce283..6285ac8328 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -34,7 +34,7 @@ src/commands/sources.ts 2086 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set
src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edges
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
-src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
+src/commands/hook.ts 1959 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +27 GBRA-188 per-turn brain-first rule: user-prompt fallback emission, the turn-rule event (Hermes pre_llm_call), its HookIo seam and help (rule and ledger read in core/setup/brain-first.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index 02ab3e38fc..af8fd42a97 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -20,7 +20,7 @@
export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable', 'ghosts', 'status'] as const;
export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;
export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;
-export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
+export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact', 'turn-rule'] as const;
export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;
export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date', 'retry'] as const;
export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index b0741384ab..1b322b7797 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -120,6 +120,7 @@ import { isClaudeCliSelfTranscriptPath } from '../core/ai/providers/claude-cli-s
import { withoutPhysicalRootMetadata } from '../core/persistence/root-metadata.ts';
import { HOOK_SUBCOMMANDS as HOOK_EVENTS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';
import { isManagedFilesystemPath } from '../core/persistence/filesystem-guard.ts';
+import { brainFirstTurnRule } from '../core/setup/brain-first.ts';
// ── Tunables ────────────────────────────────────────────────────────────────
@@ -225,6 +226,12 @@ export interface HookIo {
* a banner on stay-silent turns and read as a false fire).
*/
disablePushBanner?: boolean;
+ /**
+ * TEST SEAM: the per-turn brain-first rule user-prompt leads every turn
+ * with. `undefined` = read it from the brain-first ledger; `null` = none
+ * (BrainBench and bootstrap verify measure the context block alone).
+ */
+ turnRule?: string | null;
/**
* TEST SEAM (v0.46.15, codex ship-review): suppress hook telemetry WRITES
* (heartbeat JSONL). Telemetry paths resolve from GBRAIN_HOME/homedir —
@@ -260,6 +267,9 @@ Events (wired into .claude/settings.local.json by gbrain bootstrap):
compact (PreCompact) bank the window's standing entities into the
session cursor so the post-compaction session-start serves
a warm context pack; emits nothing
+ turn-rule (Hermes pre_llm_call) print the per-turn brain-first rule as
+ {"context": ...}; nothing after --no-instructions or under
+ GBRAIN_AGENT_INSTRUCTIONS=0
Env: GBRAIN_HOOKS=0 disables all events (immediate exit 0).
All events fail open: errors exit 0 with empty stdout and a heartbeat entry at
@@ -344,6 +354,8 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>
return hookSessionEnd(io);
case 'compact':
return hookCompact(io);
+ case 'turn-rule':
+ return hookTurnRule(io);
default:
return 1; // unreachable
}
@@ -1110,12 +1122,15 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// budgeted by the 800ms deadline, not free-ride before the race starts.
let banner: ReturnType<typeof pendingPushFailureBanner> = null;
let wrotePayload = false;
+ // Per-turn brain-first rule (brain-first.ts): every turn, with or without a block.
+ let turnRule: string | null = null;
const work = (async (): Promise<UserPromptOutcome> => {
// Push failure wins the single banner slot; the monthly backup notice
// rides the same rail (systemMessage + additionalContext) when no push
// failure is pending. Both are cache/file readers, budgeted by the race.
banner = io.disablePushBanner ? null : (pendingPushFailureBanner() ?? pendingBackupBanner());
+ turnRule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule(io.harness ?? 'claude-code');
const j = await readStdinJson(io, 300);
if (!j) return { outcome: 'degraded', reason: 'no_stdin' };
@@ -1220,7 +1235,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// trim defensively rather than letting the harness divert-and-drop. The
// banner (≤300 chars, fixed) rides inside the same payload [D5] — only
// blockText is trimmed, so the failure notice survives the cap loop.
- const bannerPrefix = banner ? `${banner.text}\n\n` : '';
+ const bannerPrefix = [banner?.text, turnRule].filter(Boolean).map((t) => `${t}\n\n`).join('');
const buildPayload = (block: string) =>
JSON.stringify({
hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: bannerPrefix + block },
@@ -1265,16 +1280,19 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// (no_serve, ipc_unavailable, no_pglite_path, empty windows, transcript
// aborts, …) still surfaces the push failure — unless the deadline expired,
// in which case record() was never called and the banner re-fires next turn.
- // (Local copy: TS cannot track the closure-side assignment of `banner`.)
- const pendingBanner = banner as { text: string; record: () => void } | null;
- if (pendingBanner && !wrotePayload && !expired) {
- guardedWrite(
+ // The per-turn rule rides the same fallback on every path, the deadline included.
+ // (Local copies: TS cannot track the closure-side assignments.)
+ const pendingBanner = (expired ? null : banner) as { text: string; record: () => void } | null;
+ const rule = turnRule as string | null;
+ if (!wrotePayload && (pendingBanner || rule)) {
+ write(
+ io,
JSON.stringify({
- hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: pendingBanner.text },
- systemMessage: pendingBanner.text,
+ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: [pendingBanner?.text, rule].filter(Boolean).join('\n\n') },
+ ...(pendingBanner ? { systemMessage: pendingBanner.text } : {}),
}) + '\n',
);
- pendingBanner.record();
+ pendingBanner?.record();
}
await writeHeartbeat(io, {
ts: new Date().toISOString(),
@@ -1288,6 +1306,15 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
return 0;
}
+// ── turn-rule (Hermes pre_llm_call) ───────────────────────────────────────────
+
+/** Hermes `hooks.pre_llm_call`: Hermes appends stdout `{"context": ...}` to each user message. File reads only. */
+function hookTurnRule(io: HookIo): number {
+ const rule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule('hermes', { kind: 'mcp', server: 'gbrain' });
+ if (rule) write(io, `${JSON.stringify({ context: rule })}\n`);
+ return 0;
+}
+
// ── compact (PreCompact banking, v0.45.7 ambient recall) ─────────────────────
/** Self-deadline for the compact event (harness timeout is 5s). */
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 242d48d1f3..397b86f62c 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -23,6 +23,8 @@
* Engine-free: setup never opens the database itself.
*/
import { realpathSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';
import { opError, OperationError } from '../core/ops/contract.ts';
import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
@@ -126,16 +128,21 @@ Flags:
existing block is removed and the opt-out is remembered.
GBRAIN_AGENT_INSTRUCTIONS=0 does the same.
--instructions Opt back in after an earlier --no-instructions.
- --instructions-only Manage only the brain-first block: no brain, MCP or hook changes.
+ --instructions-only Manage only the brain-first block (on Hermes, with its per-turn
+ hook): no brain, MCP or other hook changes.
Works for a hosted connection too, and for any harness below.
--workspace DIR OpenClaw: the agent workspace whose AGENTS.md gets the block
(default: agents.defaults.workspace, then ~/.openclaw/workspace).
Brain-first instructions: registering MCP is not enough; agents use a brain they
are told about. By default setup also writes one short marked block into the
-harness's own instruction file (search the brain first, read the hit, fill gaps
-with other tools, apply your own access rules, finish the task). Text outside the
-markers is never touched; a re-run upgrades the block in place.
+harness's own instruction file (before answering any turn, search the brain
+first, read the hit, fill gaps with other tools, apply your own access rules,
+finish the task). Text outside the markers is never touched; a re-run upgrades
+the block in place. The same rule rides each turn where the harness has a per-turn
+hook: Claude Code and Codex get it from setup's UserPromptSubmit hook, OpenClaw
+from gbrain's context engine, Hermes from a marked pre_llm_call hook setup adds
+to $HERMES_HOME/config.yaml (gbrain hook turn-rule); Cursor's rule is always applied.
claude-code ~/.claude/CLAUDE.md (project scope: ./CLAUDE.local.md)
codex $CODEX_HOME/AGENTS.md (a non-empty AGENTS.override.md instead)
opencode ~/.config/opencode/AGENTS.md
@@ -719,12 +726,17 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const decision = resolveBrainFirstDecision(flags.instructions, priorBrainFirst(harness, target.path));
instructions = syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });
}
+ const hermesHome = harness === 'hermes' ? dirname(target.path) : null;
+ const turnHook = !hermesHome ? null : flags.remove || instructions?.decision.value === 'declined'
+ ? removeHermesTurnHook({ hermesHome, dryRun: flags.dryRun })
+ : syncHermesTurnHook({ hermesHome, launcher: flags.gbrainBin ?? resolveGbrainBin(), dryRun: flags.dryRun });
const code = instructions?.action === 'preserve' ? 1 : 0;
if (out.json) {
- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
return code;
}
if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));
+ if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}`);
if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);
if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');
return code;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 02d0ab1ed5..82f6ff2a46 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1271,6 +1271,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-188. since: 'TBD' is stamped at the merge slot.
{ since: 'TBD', id: 'brain_first_instructions_gbra188', text: 'Harness installs now write a short marked brain-first block into the harness\'s own instruction file by default (Claude Code ~/.claude/CLAUDE.md, Codex AGENTS.md or a non-empty AGENTS.override.md, opencode AGENTS.md, the OpenClaw workspace AGENTS.md, an existing Hermes SOUL.md, a Cursor project rule): `gbrain setup <harness>`, `gbrain connect --install`, `gbrain bootstrap harness` and the thin-client GBRAIN-INSTRUCTIONS.md. Text outside the markers is never touched and a re-run upgrades the block in place. `--no-instructions` or GBRAIN_AGENT_INSTRUCTIONS=0 removes it and is remembered; `--remove` strips it; `gbrain setup <harness> --instructions-only` manages only the block. doctor `harness_wiring` warns when a registered harness\'s block is missing, stale or damaged.' },
{ since: 'TBD', id: 'install_surface_starter_gbra188', text: 'New stdio registrations gbrain writes (`gbrain setup`, `gbrain bootstrap hooks`, the readiness and `gbrain init` registration lines) now pin `--surface starter`, the daily-driver tool list, instead of `--surface full` (Garry, 2026-10-24; gbrain-evals#191: reach and accuracy unchanged, 17-23% fewer input tokens). An existing registration keeps its surface and is never rewritten; the Codex and Claude Code plugins and a bare `gbrain serve` stay on full. `--surface full` is the opt-in for every operation, any parameter the starter list leaves out is still accepted, and `request_tools` returns full schemas or widens the session to a left-out tool. doctor `harness_wiring` notes a full registration as information only.' },
+ { since: 'TBD', id: 'brain_first_turn_rule_gbra188', text: 'The brain-first rule now rides every turn, not only the system prompt (Garry, 2026-10-25). The block (v2) opens with "before answering any turn, check GBrain first"; while it is installed, the Claude Code and Codex UserPromptSubmit hook leads each turn with that one-line rule, with or without a context block; gbrain\'s OpenClaw context engine adds it to its per-turn addition; and `gbrain setup hermes` adds a marked `pre_llm_call` shell hook (`gbrain hook turn-rule`) to $HERMES_HOME/config.yaml and approves that command in Hermes\'s shell-hooks-allowlist.json, or prints the entry when config.yaml already has a `hooks:` section. `--no-instructions` or GBRAIN_AGENT_INSTRUCTIONS=0 turns the rule off with the block.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index 79239101a8..8d8cd7b70e 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -1018,6 +1018,7 @@ async function checkHooksSmoke(engine: BrainEngine, ws: string, sourceId: string
out += s;
},
cwd: ws,
+ turnRule: null,
});
const elapsed = Date.now() - t0;
if (code !== 0) return { id, ok: false, detail: `hook exited ${code} (must fail open with exit 0)` };
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 771a93203a..a812ef2c73 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -74,7 +74,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'git': ['--abbrev-ref', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--autostash', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--format', '--get', '--get-all', '--get-url', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--literal-pathspecs', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--name-only', '--name-status', '--no-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--short', '--show-toplevel', '--source', '--staged', '--stat', '--topo-order', '--type', '--uninstall', '--unset-all', '--untracked-files', '--verify', '--write-tree'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
- 'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index 528dfc7e48..c24ed8e2b2 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -22,6 +22,7 @@ import { backupNagReadOnlyConsult, backupNoticeText, loadBackupStatus } from './
import { estimateMessageTokens, openClawCoreLane } from './context/openclaw-core.ts';
import { TURN_CONTEXT_ENVELOPE } from './context/turn-context-envelope.ts';
import { loadContextModule } from './context/load-warning.ts';
+import { brainFirstTurnRule } from './setup/brain-first.ts';
// Types inlined from openclaw/plugin-sdk to avoid hard dependency during development.
// At runtime inside OpenClaw, the real SDK is available; these types ensure build compat.
@@ -1383,6 +1384,13 @@ export function createGBrainContextEngine(ctx: {
const parts = [contextBlock, ...await openClawCoreLane(workspaceDir, CHECKPOINT_POLL_TIMEOUT_MS).additions({
sessionId: sanitizeEngineSessionId(sessionId ?? sessionKey ?? null), messages: msgs, tokenBudget, availableTools })];
if (checkpointBlock) parts.push(checkpointBlock);
+ // The per-turn brain-first rule (brain-first.ts): on unless the block was declined for OpenClaw.
+ try {
+ const turnRule = brainFirstTurnRule('openclaw', { kind: 'mcp', server: 'gbrain' });
+ if (turnRule) parts.push(turnRule);
+ } catch {
+ /* a rule must never break context assembly */
+ }
if (memoryAddition) parts.push(memoryAddition);
if (reflexAddition) parts.push(reflexAddition);
diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.ts
index 217822d228..09a9f0190b 100644
--- a/src/core/setup/brain-first.ts
+++ b/src/core/setup/brain-first.ts
@@ -31,7 +31,7 @@ import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../mana
import { ensureGitExcluded } from '../context/compiled-core.ts';
import type { McpSurface } from '../../mcp/surface.ts';
-export const BRAIN_FIRST_VERSION = 1;
+export const BRAIN_FIRST_VERSION = 2;
export const BRAIN_FIRST_BEGIN = '<!-- gbrain:brain-first:begin -->';
export const BRAIN_FIRST_END = '<!-- gbrain:brain-first:end -->';
export const BRAIN_FIRST_OPT_OUT_ENV = 'GBRAIN_AGENT_INSTRUCTIONS';
@@ -53,8 +53,8 @@ export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess,
const tool = (mcp: string, cli: string) => (access.kind === 'mcp' ? `\`${mcp}\`` : `\`${access.launcher} ${cli}\``);
const where = access.kind === 'mcp' ? `the \`${access.server}\` MCP server` : `the \`${access.launcher}\` command`;
const lookup = access.kind === 'mcp' && access.surface === 'verbs'
- ? '- Check the brain before reading files, mail or other sources one by one: `recall` for what was said or decided, `entity` for a person or company.'
- : `- Search the brain before reading files, mail or other sources one by one: ${tool('search', 'search "<names or phrases>"')} for names and phrases, ${tool('query', 'query "<question>"')} for questions. Then read the best hit with ${tool('get_page', 'get <slug>')}.`;
+ ? '- Before answering any turn, check GBrain first, before files, mail or other sources: `recall` for what was said or decided, `entity` for a person or company.'
+ : `- Before answering any turn, check GBrain first, before files, mail or other sources: ${tool('search', 'search "<names or phrases>"')} for names and phrases, ${tool('query', 'query "<question>"')} for questions. Then read the best hit with ${tool('get_page', 'get <slug>')}.`;
return [
`<!-- gbrain brain-first v${BRAIN_FIRST_VERSION}: managed by gbrain and replaced on upgrade; edit outside these markers. Opt out: ${optOut} -->`,
'## Memory: check GBrain first',
@@ -77,6 +77,34 @@ export function renderBrainFirstSnippet(harness: string, access: BrainFirstAcces
return `${BRAIN_FIRST_BEGIN}\n${renderBrainFirstBlock(harness, access, optOut)}\n${BRAIN_FIRST_END}\n`;
}
+/**
+ * The per-turn rule: one line a harness's per-turn hook puts beside every user
+ * turn (Claude Code and Codex UserPromptSubmit, Hermes pre_llm_call, OpenClaw's
+ * context engine). An instruction in the system prompt alone left agents
+ * mostly answering without the brain; the same rule next to the turn did not.
+ */
+export function renderBrainFirstTurnRule(access: BrainFirstAccess): 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. Then answer and finish the task.`;
+}
+
+/**
+ * The per-turn rule for one harness, or null. Off under GBRAIN_AGENT_INSTRUCTIONS=0
+ * and after a recorded decline; an installed block's access names the tools.
+ * `fallback` is the access for a lane that turns the rule on without a ledger
+ * entry (OpenClaw's context engine, Hermes's hook); without one, only a
+ * recorded install turns it on.
+ */
+export function brainFirstTurnRule(harness: string, fallback?: BrainFirstAccess): string | null {
+ if (process.env[BRAIN_FIRST_OPT_OUT_ENV] === '0') return null;
+ const entries = readBrainFirstLedger().filter((e) => e.harness === harness);
+ const installed = entries.filter((e) => e.status === 'installed' && e.access).sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))[0];
+ if (installed) return renderBrainFirstTurnRule(installed.access);
+ return entries.length === 0 && fallback ? renderBrainFirstTurnRule(fallback) : null;
+}
+
export const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';
export interface BrainFirstTarget {
diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.ts
new file mode 100644
index 0000000000..d2a893a6e0
--- /dev/null
+++ b/src/core/setup/hermes-turn-hook.ts
@@ -0,0 +1,115 @@
+/**
+ * hermes-turn-hook.ts — Hermes's native per-turn hook for the brain-first
+ * rule: a marked `hooks.pre_llm_call` shell hook in $HERMES_HOME/config.yaml
+ * running `<gbrain> hook turn-rule`, whose `{"context": ...}` output Hermes
+ * appends to every user message. The block in SOUL.md reaches the system
+ * prompt only; this puts the same rule next to each turn.
+ *
+ * Ownership is by YAML comment markers; text outside them is never touched.
+ * gbrain appends its block only when config.yaml has no top-level `hooks:`
+ * key (a second one would be invalid YAML) and prints the entry to add by
+ * hand otherwise. Hermes runs a shell hook only after approval, so setup
+ * 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.
+ */
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { isAbsolute, join } from 'node:path';
+import { load } from 'js-yaml';
+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
+import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
+import { writeUnlessChanged } from './brain-first.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';
+const ALLOWLIST = 'shell-hooks-allowlist.json';
+
+export interface HermesTurnHookOutcome { action: 'write' | 'keep' | 'print' | 'remove' | 'skip'; path: string; detail: string; snippet?: string }
+
+export const hermesTurnHookCommand = (launcher: string): string => `${launcher} hook turn-rule`;
+
+function hookYaml(command: string): string {
+ return `hooks:\n ${EVENT}:\n - command: ${JSON.stringify(command)}\n timeout: 10\n`;
+}
+
+interface Allowlist { approvals: Array<Record<string, unknown>> }
+
+function readAllowlist(path: string): Allowlist {
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as Allowlist;
+ return raw && Array.isArray(raw.approvals) ? raw : { ...raw, approvals: [] };
+ } catch {
+ return { approvals: [] };
+ }
+}
+
+const approves = (e: Record<string, unknown>, command: string) => e.event === EVENT && e.command === command;
+
+function approve(hermesHome: string, command: string): void {
+ const path = join(hermesHome, ALLOWLIST);
+ const list = readAllowlist(path);
+ if (list.approvals.some((e) => approves(e, command))) return;
+ let mtime: string | null = null;
+ try { mtime = statSync(command.split(' ')[0]!).mtime.toISOString(); } catch { /* Hermes records null for a missing script too */ }
+ list.approvals.push({ event: EVENT, command, approved_at: new Date().toISOString(), script_mtime_at_approval: mtime });
+ atomicWriteTextFile(path, `${JSON.stringify(list, null, 2)}\n`, { freshMode: 0o600 });
+}
+
+function revoke(hermesHome: string, command: string): void {
+ const path = join(hermesHome, ALLOWLIST);
+ if (!existsSync(path)) return;
+ const list = readAllowlist(path);
+ const kept = list.approvals.filter((e) => !approves(e, command));
+ if (kept.length !== list.approvals.length) atomicWriteTextFile(path, `${JSON.stringify({ ...list, approvals: kept }, null, 2)}\n`, { freshMode: 0o600 });
+}
+
+/** 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; launcher: string | null; dryRun: boolean }): HermesTurnHookOutcome {
+ const path = join(opts.hermesHome, 'config.yaml');
+ const command = hermesTurnHookCommand(opts.launcher ?? 'gbrain');
+ 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) });
+ if (!opts.launcher || !isAbsolute(opts.launcher)) return print('no absolute gbrain launcher (pass --gbrain-bin)');
+ if (!existsSync(opts.hermesHome)) return print(`${opts.hermesHome} does not exist yet`);
+ try {
+ const missing = !existsSync(path);
+ const text = missing ? '' : readFileSync(path, 'utf8');
+ const probe = probeBlock(MARKERS, text);
+ if (probe.state === 'damaged') return print('the gbrain turn-rule markers in config.yaml are damaged');
+ if (probe.state === 'absent') {
+ const doc = load(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 && 'hooks' in doc) return print('config.yaml already has a hooks: section, which gbrain does not edit');
+ }
+ const next = spliceBlock(MARKERS, text, hookYaml(command));
+ if (next === text) {
+ if (!opts.dryRun) approve(opts.hermesHome, command);
+ return { action: 'keep', path, detail: `per-turn rule hook (${EVENT}) in ${path}` };
+ }
+ if (!opts.dryRun) {
+ writeUnlessChanged(path, text, missing, next);
+ approve(opts.hermesHome, command);
+ }
+ return { action: 'write', path, detail: `per-turn rule hook (${EVENT}) in ${path}, approved in ${ALLOWLIST}` };
+ } catch (e) {
+ return print(`config.yaml could not be updated (${(e as Error).message})`);
+ }
+}
+
+/** Strip the hook and its approval (decline or --remove). Never throws. */
+export function removeHermesTurnHook(opts: { hermesHome: string; dryRun: boolean }): HermesTurnHookOutcome {
+ const path = join(opts.hermesHome, 'config.yaml');
+ try {
+ if (!existsSync(path)) return { action: 'skip', path, detail: `no per-turn rule hook 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 quoted = /command: (".*")/.exec(probe.interior ?? '')?.[1];
+ if (!opts.dryRun) {
+ writeUnlessChanged(path, text, false, removeBlock(MARKERS, text).text);
+ if (quoted) revoke(opts.hermesHome, JSON.parse(quoted) as string);
+ }
+ return { action: 'remove', path, detail: `per-turn rule hook removed from ${path}` };
+ } catch (e) {
+ return { action: 'skip', path, detail: `per-turn rule hook in ${path} left as it is (${(e as Error).message})` };
+ }
+}
diff --git a/src/eval/brainbench/adapters/claude-code.ts b/src/eval/brainbench/adapters/claude-code.ts
index db93af15f8..97e4a5ad00 100644
--- a/src/eval/brainbench/adapters/claude-code.ts
+++ b/src/eval/brainbench/adapters/claude-code.ts
@@ -229,6 +229,7 @@ export class ClaudeCodeAdapter implements HarnessAdapter {
userPromptDeadlineMs: BENCH_USER_PROMPT_DEADLINE_MS,
configOverride: cfg,
disablePushBanner: true,
+ turnRule: null,
// Telemetry paths resolve from GBRAIN_HOME/homedir, not configOverride
// — without this, every fixture turn appends to the OPERATOR's real
// hook heartbeat history (codex ship-review).
diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.ts
new file mode 100644
index 0000000000..baae08b811
--- /dev/null
+++ b/test/brain-first-turn-rule.test.ts
@@ -0,0 +1,203 @@
+/**
+ * The per-turn brain-first rule (src/core/setup/brain-first.ts): one line a
+ * harness's per-turn hook puts beside every user turn. Pins who gets it and
+ * when it is off: Claude Code / Codex UserPromptSubmit (only while a block is
+ * installed for that harness), Hermes `gbrain hook turn-rule` and the
+ * config.yaml hook setup writes for it, OpenClaw's context engine (on unless
+ * declined), and the opt-out for all of them.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { 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 { withEnv } from './helpers/with-env.ts';
+import { brainFirstTurnRule, renderBrainFirstTurnRule, type BrainFirstAccess } from '../src/core/setup/brain-first.ts';
+import { runHook } from '../src/commands/hook.ts';
+import { createGBrainContextEngine } from '../src/core/context-engine.ts';
+import { removeHermesTurnHook, syncHermesTurnHook } from '../src/core/setup/hermes-turn-hook.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+function home(entries: Array<{ harness: string; status: 'installed' | 'declined'; access?: BrainFirstAccess }> | null): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-turn-rule-'));
+ roots.push(root);
+ if (entries) {
+ mkdirSync(join(root, '.gbrain'), { recursive: true });
+ writeFileSync(join(root, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: entries.map((e, i) => ({
+ path: join(root, `file-${i}.md`), block_version: 2, access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: false,
+ updated_at: new Date(Date.UTC(2026, 9, 25, 0, i)).toISOString(), ...e,
+ })) }));
+ }
+ return root;
+}
+
+const env = (root: string, extra: Record<string, string | undefined> = {}) => ({ GBRAIN_HOME: root, GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_HOOKS: undefined, ...extra });
+
+async function userPrompt(root: string, harness?: string, extra: Record<string, string | undefined> = {}): Promise<string> {
+ let out = '';
+ await withEnv(env(root, extra), async () => {
+ const code = await runHook(['user-prompt', ...(harness ? ['--harness', harness] : [])], {
+ stdin: JSON.stringify({ prompt: 'what did alice-example decide about the launch?', session_id: 's1' }),
+ write: (s) => { out += s; }, cwd: root, configOverride: null, disablePushBanner: true, disableTelemetry: true,
+ });
+ expect(code).toBe(0);
+ });
+ return out;
+}
+
+describe('per-turn rule: text and decision', () => {
+ test('names the tools of the recorded access', () => {
+ expect(renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' })).toContain('before answering this turn, check GBrain first (`search` or `query` on the `gbrain` MCP server)');
+ expect(renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain', surface: 'verbs' })).toContain('`recall` or `entity` on the `brain` MCP server');
+ expect(renderBrainFirstTurnRule({ kind: 'cli', launcher: '/opt/gbrain' })).toContain('`/opt/gbrain search "<names>"`');
+ });
+
+ test('a recorded install turns it on with its access; a decline or the opt-out turns it off, fallback or not', async () => {
+ const fallback: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };
+ await withEnv(env(home(null)), async () => {
+ expect(brainFirstTurnRule('claude-code')).toBeNull();
+ expect(brainFirstTurnRule('openclaw', fallback)).toBe(renderBrainFirstTurnRule(fallback));
+ });
+ await withEnv(env(home([{ harness: 'claude-code', status: 'installed', access: { kind: 'mcp', server: 'brain', surface: 'verbs' } }])), async () => {
+ expect(brainFirstTurnRule('claude-code')).toBe(renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain', surface: 'verbs' }));
+ expect(brainFirstTurnRule('codex')).toBeNull();
+ });
+ await withEnv(env(home([{ harness: 'openclaw', status: 'declined' }])), async () => {
+ expect(brainFirstTurnRule('openclaw', fallback)).toBeNull();
+ });
+ await withEnv(env(home([{ harness: 'claude-code', status: 'installed' }]), { GBRAIN_AGENT_INSTRUCTIONS: '0' }), async () => {
+ expect(brainFirstTurnRule('claude-code')).toBeNull();
+ expect(brainFirstTurnRule('openclaw', fallback)).toBeNull();
+ });
+ });
+});
+
+describe('per-turn rule: Claude Code and Codex user-prompt hook', () => {
+ test('with a block installed, every turn carries the rule even when serve has no context to add', async () => {
+ const out = await userPrompt(home([{ harness: 'claude-code', status: 'installed' }]));
+ const doc = JSON.parse(out.trim());
+ expect(doc.hookSpecificOutput).toEqual({ hookEventName: 'UserPromptSubmit', additionalContext: renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' }) });
+ expect(doc.systemMessage).toBeUndefined();
+ });
+
+ test('codex reads its own ledger entry', async () => {
+ const root = home([{ harness: 'codex', status: 'installed' }]);
+ expect(await userPrompt(root, 'codex')).toContain('check GBrain first');
+ expect(await userPrompt(root)).toBe('');
+ });
+
+ test('no block, a declined block, GBRAIN_AGENT_INSTRUCTIONS=0 or the null seam: stdout stays empty', async () => {
+ expect(await userPrompt(home(null))).toBe('');
+ expect(await userPrompt(home([{ harness: 'claude-code', status: 'declined' }]))).toBe('');
+ expect(await userPrompt(home([{ harness: 'claude-code', status: 'installed' }]), undefined, { GBRAIN_AGENT_INSTRUCTIONS: '0' })).toBe('');
+ let out = '';
+ await withEnv(env(home([{ harness: 'claude-code', status: 'installed' }])), async () => {
+ await runHook(['user-prompt'], { stdin: JSON.stringify({ prompt: 'hi' }), write: (s) => { out += s; }, configOverride: null, disablePushBanner: true, disableTelemetry: true, turnRule: null });
+ });
+ expect(out).toBe('');
+ });
+});
+
+describe('per-turn rule: Hermes turn-rule hook', () => {
+ async function turnRule(root: string, extra: Record<string, string | undefined> = {}): Promise<string> {
+ let out = '';
+ await withEnv(env(root, extra), async () => {
+ expect(await runHook(['turn-rule'], { write: (s) => { out += s; } })).toBe(0);
+ });
+ return out;
+ }
+
+ test('prints Hermes\'s {"context": ...} wire shape by default and with an installed block', async () => {
+ expect(JSON.parse(await turnRule(home(null)))).toEqual({ context: renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' }) });
+ expect(JSON.parse(await turnRule(home([{ harness: 'hermes', status: 'installed', access: { kind: 'mcp', server: 'brain' } }])))).toEqual({ context: renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain' }) });
+ });
+
+ test('prints nothing after a decline, under the opt-out or with hooks off', async () => {
+ expect(await turnRule(home([{ harness: 'hermes', status: 'declined' }]))).toBe('');
+ expect(await turnRule(home(null), { GBRAIN_AGENT_INSTRUCTIONS: '0' })).toBe('');
+ expect(await turnRule(home(null), { GBRAIN_HOOKS: '0' })).toBe('');
+ });
+});
+
+describe('per-turn rule: OpenClaw context engine', () => {
+ async function addition(root: string, extra: Record<string, string | undefined> = {}): Promise<string> {
+ const ws = mkdtempSync(join(tmpdir(), 'gbrain-turn-rule-ws-'));
+ roots.push(ws);
+ let text = '';
+ await withEnv(env(root, extra), async () => {
+ const result = await createGBrainContextEngine({ workspaceDir: ws }).assemble({ sessionId: 's1', messages: [], tokenBudget: 100000 });
+ text = result.systemPromptAddition ?? '';
+ });
+ return text;
+ }
+
+ test('every assemble carries the rule unless OpenClaw\'s block was declined or the opt-out is set', async () => {
+ const rule = renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' });
+ expect(await addition(home(null))).toContain(rule);
+ expect(await addition(home([{ harness: 'openclaw', status: 'declined' }]))).not.toContain('check GBrain first');
+ expect(await addition(home(null), { GBRAIN_AGENT_INSTRUCTIONS: '0' })).not.toContain('check GBrain first');
+ });
+});
+
+describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {
+ const launcher = '/opt/gbrain/bin/gbrain';
+ const cmd = `${launcher} hook turn-rule`;
+ function hermes(config?: string, approvals: unknown[] = []): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-hermes-home-'));
+ roots.push(dir);
+ if (config !== undefined) writeFileSync(join(dir, 'config.yaml'), config);
+ if (approvals.length) writeFileSync(join(dir, 'shell-hooks-allowlist.json'), JSON.stringify({ approvals }));
+ return dir;
+ }
+ const cfg = (d: string) => readFileSync(join(d, 'config.yaml'), 'utf8');
+ const approvals = (d: string) => JSON.parse(readFileSync(join(d, 'shell-hooks-allowlist.json'), 'utf8')).approvals as Array<Record<string, unknown>>;
+
+ test('appends a marked hook after the user\'s text, approves exactly that command, keeps on a re-run, and removal undoes both', () => {
+ const mine = '# my config\nmodel:\n default: alice-example-model\n';
+ const other = { event: 'pre_tool_call', command: '/usr/bin/true', approved_at: 'x', script_mtime_at_approval: null };
+ const d = hermes(mine, [other]);
+ expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false }).action).toBe('write');
+ const text = cfg(d);
+ expect(text.startsWith(mine)).toBe(true);
+ expect(load(text)).toEqual({ model: { default: 'alice-example-model' }, hooks: { pre_llm_call: [{ command: cmd, timeout: 10 }] } });
+ expect(approvals(d)).toEqual([other, expect.objectContaining({ event: 'pre_llm_call', command: cmd })]);
+ expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false }).action).toBe('keep');
+ expect(cfg(d)).toBe(text);
+ expect(approvals(d)).toHaveLength(2);
+ expect(removeHermesTurnHook({ hermesHome: d, dryRun: false }).action).toBe('remove');
+ expect(cfg(d)).toBe(mine);
+ expect(approvals(d)).toEqual([other]);
+ });
+
+ test('a new launcher path rewrites the block in place', () => {
+ const d = hermes('');
+ syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false });
+ expect(syncHermesTurnHook({ hermesHome: d, launcher: '/usr/local/bin/gbrain', dryRun: false }).action).toBe('write');
+ expect(load(cfg(d))).toEqual({ hooks: { pre_llm_call: [{ command: '/usr/local/bin/gbrain hook turn-rule', timeout: 10 }] } });
+ });
+
+ test('prints the entry instead of editing: a hooks: section of the user\'s, no absolute launcher, no Hermes home, damaged markers', () => {
+ const theirs = 'hooks:\n pre_tool_call:\n - command: /usr/bin/true\n';
+ const d = hermes(theirs);
+ const o = syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false });
+ expect(o.action).toBe('print');
+ expect(o.snippet).toContain(`- command: "${cmd}"`);
+ expect(cfg(d)).toBe(theirs);
+ expect(existsSync(join(d, 'shell-hooks-allowlist.json'))).toBe(false);
+ expect(syncHermesTurnHook({ hermesHome: hermes(''), launcher: null, dryRun: false }).action).toBe('print');
+ expect(syncHermesTurnHook({ hermesHome: hermes(''), launcher: 'gbrain', dryRun: false }).action).toBe('print');
+ expect(syncHermesTurnHook({ hermesHome: join(tmpdir(), 'gbrain-no-such-hermes-home'), launcher, dryRun: false }).action).toBe('print');
+ const damaged = hermes('# gbrain:turn-rule:begin\nmodel: x\n');
+ expect(syncHermesTurnHook({ hermesHome: damaged, launcher, dryRun: false }).action).toBe('print');
+ expect(cfg(damaged)).toBe('# gbrain:turn-rule:begin\nmodel: x\n');
+ });
+
+ test('dry-run writes nothing', () => {
+ const d = hermes('model: x\n');
+ expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: true }).action).toBe('write');
+ expect(cfg(d)).toBe('model: x\n');
+ expect(existsSync(join(d, 'shell-hooks-allowlist.json'))).toBe(false);
+ });
+});
diff --git a/test/setup-brain-first.test.ts b/test/setup-brain-first.test.ts
index 94ecee24b8..c980f1fa26 100644
--- a/test/setup-brain-first.test.ts
+++ b/test/setup-brain-first.test.ts
@@ -90,7 +90,7 @@ for (const lane of LANES) {
const text = read(path);
expect(text.startsWith(lane.existing)).toBe(true);
expect(blocks(text)).toBe(1);
- expect(text).toContain('Search the brain before reading files');
+ expect(text).toContain('Before answering any turn, check GBrain first, before files, mail or other sources');
expect(text).toContain('apply your own access rules');
expect(text).toContain('finish the whole task');
expect(ledger(b)).toEqual([expect.objectContaining({ harness: lane.harness, path, status: 'installed', created_file: false })]);
@@ -231,6 +231,25 @@ describe('brain-first block: placement rules', () => {
expect(read(join(b.home, '.hermes', 'SOUL.md')).startsWith(soul)).toBe(true);
});
+ test('hermes: setup adds the pre_llm_call hook that carries the rule on every turn; the opt-out and --remove take it out', async () => {
+ const b = box();
+ mkdirSync(join(b.home, '.hermes'), { recursive: true });
+ writeFileSync(join(b.home, '.hermes', 'SOUL.md'), 'You are Hermes.\n');
+ writeFileSync(join(b.home, '.hermes', 'config.yaml'), 'model:\n default: x\n');
+ const config = () => read(join(b.home, '.hermes', 'config.yaml'));
+ const first = await setup(b, ['hermes', '--gbrain-bin', b.bin]);
+ expect(first.doc.turn_hook).toMatchObject({ action: 'write', path: join(b.home, '.hermes', 'config.yaml') });
+ expect(config()).toContain(` pre_llm_call:\n - command: ${JSON.stringify(`${b.bin} hook turn-rule`)}`);
+ expect(read(join(b.home, '.hermes', 'SOUL.md'))).toContain(BRAIN_FIRST_BEGIN);
+ const declined = await setup(b, ['hermes', '--no-instructions']);
+ expect(declined.doc.turn_hook.action).toBe('remove');
+ expect(config()).toBe('model:\n default: x\n');
+ await setup(b, ['hermes', '--instructions', '--gbrain-bin', b.bin]);
+ expect(config()).toContain('pre_llm_call');
+ expect((await setup(b, ['hermes', '--remove'])).doc.turn_hook.action).toBe('remove');
+ expect(config()).toBe('model:\n default: x\n');
+ });
+
test('a damaged block is preserved and reported, never guessed through', async () => {
const b = box();
const path = join(b.home, '.claude', 'CLAUDE.md');