Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
review fixes: never run a repo-committed hook, honor --no-hooks and GBRAIN_HOOKS=0, hook follows the block (Hermes lock), codex yields only to a running group, no banner in the turn-rule lane, removal notes
garrytan9a01d2646c3a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b90b09de48..76330e403f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1740 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1557 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2)+src/core/behavior-change-notice.ts 1558 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move)diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex ac546c4cea..2818e9384b 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -1130,10 +1130,10 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// 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', io.cwd ?? process.cwd());- // The turn-rule lane's connection may reach another brain, so it never reads this machine's context.+ // The turn-rule lane's connection may reach another brain, so it never reads this machine's context or banners.if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE) return { outcome: 'ok', reason: 'rule_only' };+ banner = io.disablePushBanner ? null : (pendingPushFailureBanner() ?? pendingBackupBanner());const j = await readStdinJson(io, 300);if (!j) return { outcome: 'degraded', reason: 'no_stdin' };diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 46fd533d61..c512a2d86a 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -754,14 +754,16 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>}const off = flags.remove || instructions?.decision.value === 'declined';const rerun = ['gbrain', 'setup', harness, '--instructions-only', ...(flags.name !== 'gbrain' ? ['--name', flags.name] : []), ...(flags.workspace ? ['--workspace', flags.workspace] : []), ...(projectDir && harness === 'claude-code' ? ['--scope', 'project'] : [])];- const turnHook = harness === 'hermes'+ // The hook carries the block's rule, so it follows the block: none while no block could be placed (Hermes without a SOUL.md).+ const placed = instructions?.action === 'write' || instructions?.action === 'keep';+ const turnHook = !off && !placed ? null : harness === 'hermes'? (off ? removeHermesTurnHook({ hermesHome: dirname(target.path), dryRun: flags.dryRun }) : syncHermesTurnHook({ hermesHome: dirname(target.path), access, dryRun: flags.dryRun })): harness === 'openclaw'? (off ? removeOpenclawTurnPlugin({ dryRun: flags.dryRun }) : syncOpenclawTurnPlugin({ access, dryRun: flags.dryRun })): isTurnRuleHarness(harness) ? turnRuleHookFor(harness, off, flags, projectDir, rerun.join(' ')) : null;// Loud failure: an accepted install whose per-turn hook does not load exits non-zero and names the harness's own check.// A 'print' outcome installed nothing and already names the step that does, so it is reported, not verified.- const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && turnHook && turnHook.action !== 'print' ? verifyTurnHook(harness, { projectDir }) : null;+ const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;const code = instructions?.action === 'preserve' || (check && !check.ok) ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));@@ -769,7 +771,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>}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}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}${'next' in turnHook && turnHook.next ? `; wire it with: ${turnHook.next}` : ''}`);- else if (!off) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);+ else if (!off && placed) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);if (check?.ok) say(out, ` verify ${'turn hook'.padEnd(7)} ${check.message}`);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.');@@ -784,7 +786,8 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>*/function turnRuleHookFor(harness: TurnRuleHarness, off: boolean, flags: SetupFlags, projectDir: string | undefined, rerun: string): TurnHookOutcome {const paths = projectDir ? { claudeSettings: join(projectDir, '.claude', 'settings.local.json') } : {};- if (off) return removeTurnRuleHook({ harness, paths, dryRun: flags.dryRun });+ if (off || flags.noHooks) return removeTurnRuleHook({ harness, paths, dryRun: flags.dryRun });+ if (process.env.GBRAIN_HOOKS === '0') return { harness, action: 'skip', path: '', detail: 'GBRAIN_HOOKS=0 is set: no per-turn hook installed' };const carried = inspectTurnHook(harness, { projectDir });if (carried.state !== 'missing' && carried.via !== 'turn-rule') return { harness, action: 'skip', path: '', detail: `per-turn rule already carried: ${carried.detail}` };return syncTurnRuleHook({ harness, gbrainBin: flags.gbrainBin ?? resolveGbrainBin(), gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined, paths, dryRun: flags.dryRun, rerun });diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2d1191c9b5..f373fea7e7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1359,7 +1359,6 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.502.0', id: 'provider_key_rules_7959', text: 'The secret scanner now catches OpenRouter (`sk-or-v1-`), Groq (`gsk_`), xAI (`xai-`), Perplexity (`pplx-`) and Replicate (`r8_`) API keys: `gbrain sources push` refuses a page that holds one, and search, recall and transcript import redact it. Rotate such a key with its provider rather than allowlisting it. `gbrain doctor` asks once for a fresh `gbrain transcripts audit-secrets` run.' },{ since: '0.60.504.0', text: '`gbrain sync status` and doctor `managed_sync_blocked` no longer read a managed sync pass `pass_abandoned` while a process still renews its drain lease (a pass started over earlier interrupted ones), nor `pass_interrupted` when the pass ended between their pass and lease reads; liveness reads the database clock, and doctor keeps status\'s quiet-window rule when the lock read fails. A pass stopped by a lost database connection, a statement timeout, write back-pressure or a lost drain lease now ends `resumable` (`stop_reason` `transient` or `lease_lost`) instead of reading killed. The on-commit notifier, the notifier block and `sources status` `writer_heartbeat` no longer count a killed holder\'s lock row as a live holder, so the notifier starts the sync that takes its expired lease over.' },{ since: '0.60.504.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) binds its own read socket for resolve, turn_context and context_pack instead of the source and legacy sockets, so a read-write serve started later for the same source always answers delegated sync, nudge and sweep requests; before, a read-only serve that bound first made the CLI fall back with `unsupported_kind`.' },- // GBRA-243. since: '0.60.505.0' is stamped at the merge slot.{ since: '0.60.505.0', id: 'turn_hook_every_install_gbra243', text: 'Every harness install path now wires the per-turn brain-first hook: `gbrain setup claude-code|codex --instructions-only` (after a plain `mcp add`), `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness` (Codex, and Claude Code when its own hooks are off) add one UserPromptSubmit entry that prints only the "check gbrain first" rule and reads no brain data; it yields to setup, bootstrap and plugin hooks, so a turn still gets the rule once. Each install runs the hook (or `openclaw plugins inspect gbrain-turn-rule --runtime --json`, `hermes hooks doctor`) and exits non-zero with `turn_hook_not_loaded` when it does not load; doctor `harness_wiring` warns the same way. `--no-instructions` or `--no-hooks` installs none, and registrar mode stays MCP-only. On OpenClaw and Hermes the per-turn rule now names the gbrain tools and the `tool_search` route.' },];diff --git a/src/core/bootstrap/harness-brain-first.ts b/src/core/bootstrap/harness-brain-first.tsindex a10f5d44ad..99a6b29d0b 100644--- a/src/core/bootstrap/harness-brain-first.ts+++ b/src/core/bootstrap/harness-brain-first.ts@@ -42,7 +42,7 @@ export function removeHarnessBrainFirst(server: string, log: (line: string) => v/*** The per-turn rule for hosts whose hooks this lane does not otherwise wire:* Codex always (the bootstrap Codex lane wires only SessionEnd capture), Claude- * Code when its lifecycle hooks are off here (registrar mode). Opted out+ * Code when its lifecycle hooks are off here. Registrar mode wires none. Opted out* (block declined) removes it. Returns false when a hook could not be wired or* does not load, so the install fails loudly.*/diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsindex 9a82a0bf48..f7afbeb741 100644--- a/src/core/setup/turn-hook-check.ts+++ b/src/core/setup/turn-hook-check.ts@@ -15,7 +15,7 @@ import { existsSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import type { Action } from '../agent-output.ts';import { bunSpawnSync } from '../spawn.ts';-import { codexHookCensus, codexHookTrustHash } from '../bootstrap/codex-hooks.ts';+import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash } from '../bootstrap/codex-hooks.ts';import { readCodexTomlTable } from '../bootstrap/codex-toml.ts';import { classifyHarnessHook } from '../bootstrap/hooks.ts';import { GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';@@ -23,7 +23,7 @@ import { enabledPluginLanes } from '../bootstrap/plugin-lanes.ts';import { brainFirstTarget, openclawConfigPath, parseJson5ish } from './brain-first.ts';import { inspectHermesTurnHook } from './hermes-turn-hook.ts';import { OPENCLAW_TURN_PLUGIN_ID, openclawTurnPluginDir } from './openclaw-turn-plugin.ts';-import { isTurnRuleEntry, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnHookPaths } from './turn-hook.ts';+import { isOtherGbrainEntry, isTurnRuleEntry, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnHookPaths } from './turn-hook.ts';export const TURN_HOOK_NATIVE_INSPECT: Record<string, string> = {'claude-code': '/hooks (inside a Claude Code session)',@@ -41,6 +41,8 @@ export interface TurnHookState {detail: string;/** The hook command gbrain can run to prove it (Claude Code and Codex, not plugin lanes). */command?: string;+ /** The file the command came from. */+ source?: string;native_inspect?: string;}@@ -66,9 +68,10 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =if (harness === 'claude-code') {const files = [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, '.claude', 'settings.local.json'), join(opts.projectDir, '.claude', 'settings.json')] : [])];for (const path of files) {- const entries = claudeEntries(path).filter(isGbrainPromptEntry);+ const committed = !!opts.projectDir && path === join(opts.projectDir, '.claude', 'settings.json');+ const entries = claudeEntries(path).filter((e) => isTurnRuleEntry(e) || isOtherGbrainEntry(e, committed));const effective = entries.find((e) => !isTurnRuleEntry(e)) ?? entries[0];- if (effective) return { harness, state: 'wired', via: isTurnRuleEntry(effective) ? 'turn-rule' : effective[GBRAIN_HOOK_MARKER_KEY] === 'setup-v1' ? 'setup' : 'bootstrap', detail: `UserPromptSubmit hook in ${path}`, command: String(effective.command), native_inspect };+ if (effective) return { harness, state: 'wired', via: isTurnRuleEntry(effective) ? 'turn-rule' : effective[GBRAIN_HOOK_MARKER_KEY] === 'setup-v1' ? 'setup' : 'bootstrap', detail: `UserPromptSubmit hook in ${path}`, command: String(effective.command), source: path, native_inspect };}if (plugin) return { harness, state: 'wired', via: 'plugin', detail: `the '${plugin.plugin}' plugin declares the UserPromptSubmit hook`, native_inspect };return { harness, state: 'missing', detail: `no gbrain UserPromptSubmit hook in ${files.join(' or ')}`, native_inspect };@@ -82,7 +85,7 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =const key = `${codexHooksPath()}:user_prompt_submit:${g.index}:0`;let table: { trusted_hash?: unknown } | undefined;try { table = readCodexTomlTable(codexConfigPath(), ['hooks', 'state', key]) as typeof table; } catch { table = undefined; }- const trusted = table?.trusted_hash === codexHookTrustHash('user_prompt_submit', command, 15);+ const trusted = table?.trusted_hash === codexHookTrustHash('user_prompt_submit', command, 15) && (g.lane === 'turn-rule' || codexHookGroupRuns(codexHooksPath(), codexConfigPath(), g));return { harness, state: trusted ? 'wired' : 'untrusted', via: g.lane as TurnHookState['via'], command, native_inspect,detail: trusted ? `UserPromptSubmit hook in ${codexHooksPath()}, trusted in ${codexConfigPath()}` : `UserPromptSubmit hook in ${codexHooksPath()} has no matching trust entry in ${codexConfigPath()}, so Codex does not run it` };}@@ -110,9 +113,14 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =}type Run = (argv: string[], stdin?: string) => { ok: boolean; output: string };+/** Only what a hook needs to find the brain and the rule; never provider keys. */+function hookEnv(): Record<string, string> {+ return Object.fromEntries(Object.entries(process.env).filter((e): e is [string, string] => e[1] !== undefined && /^(HOME|PATH|USER|LANG|TMPDIR|XDG_CONFIG_HOME|CLAUDE_CONFIG_DIR|CODEX_HOME|GBRAIN_HOME|GBRAIN_AGENT_INSTRUCTIONS|GBRAIN_HOOKS)$/.test(e[0])));+}const defaultRun: Run = (argv, stdin) => {try {- const r = bunSpawnSync(argv, { stdin: stdin === undefined ? 'ignore' : Buffer.from(stdin), stdout: 'pipe', stderr: 'pipe', env: process.env, timeout: 60_000 });+ // From the home directory: a project's own gbrain hook would make the turn-rule lane yield there.+ const r = bunSpawnSync(argv, { stdin: stdin === undefined ? 'ignore' : Buffer.from(stdin), stdout: 'pipe', stderr: 'pipe', env: hookEnv(), cwd: process.env.HOME || undefined, timeout: 60_000 });return { ok: r.exitCode === 0, output: `${r.stdout.toString()}${r.stderr.toString()}` };} catch (e) { return { ok: false, output: (e as Error).message }; }};@@ -136,6 +144,8 @@ export function verifyTurnHook(harness: string, opts: { projectDir?: string; runif (state.state === 'untrusted') return fail('untrusted', state.detail);if (state.via === 'plugin') return { ok: true, state, reason: 'plugin_lane', message: `${state.detail}; check it with ${state.native_inspect}` };if ((harness === 'claude-code' || harness === 'codex') && state.command) {+ // A command from a project's settings file is the repo's, not the user's: never run it.+ if (harness === 'claude-code' && state.source !== claudeUserSettingsPath()) return { ok: true, state, reason: 'project_unverified', message: `${state.detail}; a project hook is not run here, so check it with ${state.native_inspect}` };const r = run(['sh', '-c', state.command], JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: '', session_id: 'gbrain-install-check' }));if (!r.ok) return fail('hook_failed', `the UserPromptSubmit hook exited non-zero (${r.output.trim().split('\n').at(-1) || 'no output'})`);if (!r.output.includes('GBrain: before answering')) return fail('no_rule', 'the UserPromptSubmit hook ran but did not add the brain-first rule (is the brain-first block installed for this harness?)');@@ -188,6 +198,7 @@ export function installerTurnHook(opts: { harness: string; accepted: boolean; gbreturn { outcome: { harness, action: 'skip', path: '', detail: `${harness} has no per-turn hook gbrain can install; the rule reaches it through its instruction file only` }, verdict: null };}if (!opts.accepted) return { outcome: removeTurnRuleHook({ harness, paths: opts.paths }), verdict: null };+ if (process.env.GBRAIN_HOOKS === '0') return { outcome: { harness, action: 'skip', path: '', detail: 'GBRAIN_HOOKS=0 is set: no per-turn hook installed' }, verdict: null };const carried = opts.paths ? null : inspectTurnHook(harness);const outcome = carried && carried.state !== 'missing' && carried.via !== 'turn-rule'? { harness, action: 'skip' as const, path: '', detail: `per-turn rule already carried: ${carried.detail}` }diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.tsindex 3d29da156b..8a007ed13d 100644--- a/src/core/setup/turn-hook.ts+++ b/src/core/setup/turn-hook.ts@@ -2,7 +2,7 @@* turn-hook.ts — the per-turn brain-first rule on install paths that do not* run `gbrain setup`'s own hooks: `gbrain connect --install` (a remote brain),* `gbrain connect --harness … --install` (a hosted grant),- * `gbrain bootstrap harness` (Codex, and Claude Code in registrar mode) and+ * `gbrain bootstrap harness` (Codex, and Claude Code when its own hooks are off) and* `gbrain setup <claude-code|codex> --instructions-only` (a bare `mcp add`* registration gbrain did not write).*@@ -32,7 +32,7 @@ import { existsSync, mkdirSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { bunSpawnSync } from '../spawn.ts';import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';-import { codexHookCensus, codexHookTrustHash, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';+import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';@@ -99,10 +99,10 @@ function claudePromptEntries(path: string): Array<Record<string, unknown>> {.filter((e): e is Record<string, unknown> => !!e && typeof e === 'object');}-/** An entry another gbrain lane owns (setup, workspace bootstrap, bootstrap harness). */-function isOtherGbrainEntry(e: Record<string, unknown>): boolean {+/** An entry another gbrain lane owns (setup, workspace bootstrap, bootstrap harness). A repo's committed settings.json counts only a command that parses as gbrain's hook, never a bare marker. */+export function isOtherGbrainEntry(e: Record<string, unknown>, committed = false): boolean {if (isTurnRuleEntry(e)) return false;- return typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, EVENT, 'any');+ return (!committed && typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string') || !!classifyHarnessHook(e, EVENT, 'any');}/**@@ -112,10 +112,12 @@ function isOtherGbrainEntry(e: Record<string, unknown>): boolean {*/export function turnRuleHookYields(harness: string, cwd: string): boolean {if (harness === 'codex') {- try { return codexHookCensus(codexHooksPath()).some((g) => g.event === EVENT && (g.lane === 'setup' || g.lane === 'bootstrap')); } catch { return false; }+ // Only a group Codex actually runs (trusted, enabled) carries the rule.+ try { return codexHookCensus(codexHooksPath()).some((g) => g.event === EVENT && (g.lane === 'setup' || g.lane === 'bootstrap') && codexHookGroupRuns(codexHooksPath(), codexConfigPath(), g)); } catch { return false; }}- return [claudeUserSettingsPath(), join(cwd, '.claude', 'settings.json'), join(cwd, '.claude', 'settings.local.json')]- .some((p) => claudePromptEntries(p).some(isOtherGbrainEntry));+ return claudePromptEntries(claudeUserSettingsPath()).some((e) => isOtherGbrainEntry(e))+ || claudePromptEntries(join(cwd, '.claude', 'settings.local.json')).some((e) => isOtherGbrainEntry(e))+ || claudePromptEntries(join(cwd, '.claude', 'settings.json')).some((e) => isOtherGbrainEntry(e, true));}/** Install or refresh the turn-rule hook. Never throws; anything it cannot write safely comes back as `print` with the command that wires it. */@@ -196,7 +198,8 @@ export function removeTurnRuleHook(opts: { harness: TurnRuleHarness; paths?: Turif (!opts.dryRun) {const commands = ours.flatMap((g) => g.commands);for (const g of ours) dropOurTrust(p.config, trustKey(p.hooks, g.index), commands);- writeCodexSetupHooks(p.hooks, { want: {}, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });+ const w = writeCodexSetupHooks(p.hooks, { want: {}, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });+ if (w.notes.length) return { harness: 'codex', action: 'remove', path: p.hooks, detail: `per-turn rule hook removed from ${p.hooks}; ${w.notes.join(' ')}` };}return { harness: 'codex', action: 'remove', path: p.hooks, detail: `per-turn rule hook removed from ${p.hooks}` };}diff --git a/test/turn-hook-install-paths.test.ts b/test/turn-hook-install-paths.test.tsindex 6ae4c93a8b..3654acbec9 100644--- a/test/turn-hook-install-paths.test.ts+++ b/test/turn-hook-install-paths.test.ts@@ -10,7 +10,7 @@* Spawns `bun src/cli.ts setup` against a temp HOME / GBRAIN_HOME.*/import { afterAll, describe, expect, test } from 'bun:test';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { runCli } from './helpers/cli-spawn.ts';@@ -117,6 +117,42 @@ describe('setup --instructions-only after a plain mcp add', () => {});});+describe('review fixes: repo-committed hooks, the hooks opt-outs, Hermes without a SOUL.md', () => {+ test('a project whose committed .claude/settings.json carries a bare gbrain marker is never run, and does not count as carrying the rule', async () => {+ const b = box();+ const ran = join(b.root, 'ran');+ mkdirSync(join(b.project, '.claude'), { recursive: true });+ writeFileSync(join(b.project, '.claude', 'settings.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: `touch '${ran}'`, _gbrain: 'setup-v1' }] }] } }));+ const r = await setup(b, ['claude-code', '--instructions-only', '--scope', 'project', '--gbrain-bin', b.bin, '--json']);+ expect(existsSync(ran)).toBe(false);+ expect(r.exitCode).toBe(0);+ expect(r.doc.turn_hook).toMatchObject({ action: 'write' });+ expect(readFileSync(join(b.project, '.claude', 'settings.local.json'), 'utf8')).toContain(TURN_RULE_LANE_TOKEN);+ });++ test('--no-hooks and GBRAIN_HOOKS=0 write no per-turn hook and pass', async () => {+ const b = box();+ const flagged = await setup(b, ['codex', '--instructions-only', '--no-hooks', '--gbrain-bin', b.bin, '--json']);+ expect(flagged.exitCode).toBe(0);+ expect(existsSync(join(b.home, '.codex', 'hooks.json')) ? readFileSync(join(b.home, '.codex', 'hooks.json'), 'utf8') : '').not.toContain(TURN_RULE_LANE_TOKEN);+ const env = await runCli(['setup', 'codex', '--instructions-only', '--gbrain-bin', b.bin, '--json'], { env: { ...b.env, GBRAIN_HOOKS: '0' }, cwd: b.project });+ expect(env.exitCode).toBe(0);+ expect(existsSync(join(b.home, '.codex', 'hooks.json')) ? readFileSync(join(b.home, '.codex', 'hooks.json'), 'utf8') : '').not.toContain(TURN_RULE_LANE_TOKEN);+ await withEnv({ ...b.env, GBRAIN_HOOKS: '0' }, async () => {+ expect(installerTurnHook({ harness: 'codex', accepted: true, gbrainBin: b.bin, rerun: '' })).toMatchObject({ outcome: { action: 'skip' }, verdict: null });+ });+ });++ test('hermes without a SOUL.md: no block, so no hook, no allowlist lock file, nothing written beside it', async () => {+ const b = box();+ const hermesHome = join(b.home, '.hermes');+ mkdirSync(hermesHome, { recursive: true });+ const r = await runCli(['setup', 'hermes', '--instructions-only', '--json'], { env: b.env, cwd: b.project });+ expect(r.exitCode).toBe(0);+ expect(readdirSync(hermesHome)).toEqual([]);+ });+});+describe('the rule follows the recorded decision (#7962)', () => {test('codex: --no-instructions after an AGENTS.override.md appears also strips the AGENTS.md block, so the rule stops', async () => {const b = box();