Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: per-turn hook on every install path
garrytana97d0f1d6e8a
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4ab43ef738..48fecfd1cc 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4387,6 +4387,18 @@ Reasons: `corpus_source_other`, `corpus_source_unresolved`, `corpus_legacy_unsta|---|---|---|---|---|---|---|| The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it. | Only the operator of the brain host can change what blocks this. | Ask the user to run the named gbrain command on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### turn_hook_not_loaded++<a id="turn_hook_not_loaded"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The per-turn hook that puts "check gbrain first" next to every user turn is missing, untrusted, or does not load in the harness. | Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it. | Correct the request using the message above, then retry. Run: gbrain doctor --only harness_wiring --json | agent | `repeat the read that failed` | 1 | no |++Reasons: `missing`, `untrusted`, `hook_failed`, `no_rule`, `not_loaded`.++More: [docs/guides/repair.md#turn-hook-not-loaded](../../docs/guides/repair.md#turn-hook-not-loaded)+### two_consumers_on_host<a id="two_consumers_on_host"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex c9020c78b7..8650412aef 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -4005,9 +4005,12 @@ The message names the guide for the harness you asked for (OpenClaw:`gbrain bootstrap harness --harness <claude-code|codex>`.- `unowned_entry`: the harness configuration already has an entry under thesame MCP server name, and its hash is not one this setup recorded (you or- another tool wrote it, or you edited it). Setup never overwrites it. Pick- another name with `--name`, or remove that entry yourself and run setup- again.+ another tool wrote it, or you edited it). Setup never overwrites it. A bare+ `claude mcp add` or `codex mcp add` registration is the usual cause: keep+ it and run `gbrain setup <claude-code|codex> --instructions-only`, which+ adds the brain-first block and the per-turn hook and leaves the entry alone.+ Or pick another name with `--name`, or remove that entry yourself and run+ setup again.- `other_install`: the connection receipt for this name belongs to a gbraininstall with a different `GBRAIN_HOME`. Run setup with `--name <other>` soeach install owns its own entries.@@ -4032,6 +4035,40 @@ the hosted one. Manage that connection with `gbrain connect <mcp-url>--harness <claude-code|codex> --install`; `gbrain doctor --only harness_wiring` showswhich brain the registration reaches.+### Turn hook not loaded++<a id="turn-hook-not-loaded"></a>++`turn_hook_not_loaded`: the per-turn hook that puts "check GBrain first"+beside every user turn is not running in the harness. Agents use the brain+when that rule reaches them on every turn; the MCP tool list or an+instruction file alone rarely gets the brain used. The `reason` says what+the install check found:++- `missing`: no gbrain per-turn hook is configured for the harness.+- `untrusted`: the hook is configured but the harness will not run it yet+ (Codex: no matching trust entry, trust it in `/hooks`; OpenClaw:+ `hooks.allowConversationAccess` is off; Hermes: the command is not in+ `shell-hooks-allowlist.json`).+- `hook_failed`: the Claude Code or Codex hook command exited non-zero.+- `no_rule`: the hook ran but added no rule, usually because the+ brain-first block for that harness was opted out.+- `not_loaded`: the harness's own check does not show the hook loaded.++Run `fix.argv` (it re-runs the install that writes the hook), then check+with the harness's own command:++| Harness | Check |+|---|---|+| Claude Code | `/hooks` in a session lists the UserPromptSubmit hook |+| Codex | `/hooks` in a session; trust the hook there if it asks |+| OpenClaw | `openclaw plugins inspect gbrain-turn-rule --runtime --json` shows it loaded with `before_prompt_build` |+| Hermes | `hermes hooks doctor` shows the `pre_llm_call` hook healthy |++`gbrain doctor --only harness_wiring --json` reports the same state per+harness. opencode and Cursor have no per-turn hook gbrain can install; the+rule reaches them through their instruction file only.+## Connection noticesTwo notices tell an agent, on its own MCP connection, why something itdiff --git a/src/commands/connect.ts b/src/commands/connect.tsindex c4bd1e092a..b801b67029 100644--- a/src/commands/connect.ts+++ b/src/commands/connect.ts@@ -44,7 +44,10 @@ import type { ConnectProbeResult } from '../core/connect-probe.ts';import { probeBrainIdentity, DEFAULT_PROBE_TIMEOUT_MS } from '../core/connect-probe.ts';import { opencodeGlobalConfigPath } from '../core/bootstrap/host-specs.ts';import { acquireBootstrapLock } from '../core/bootstrap/lock.ts';-import { brainFirstTarget, describeBrainFirstOutcome, installerBrainFirst, isBrainFirstHarness } from '../core/setup/brain-first.ts';+import { brainFirstTarget, describeBrainFirstOutcome, installerBrainFirst, isBrainFirstHarness, priorBrainFirst } from '../core/setup/brain-first.ts';+import { describeTurnHookOutcome } from '../core/setup/turn-hook.ts';+import { installerTurnHook, TURN_HOOK_NATIVE_INSPECT, turnHookFix } from '../core/setup/turn-hook-check.ts';+import { resolveGbrainBin } from '../core/gbrain-bin.ts';import {GBRAIN_REMOTE_TOKEN_ENV,reconcileOpencodeSiblingGlobal,@@ -440,6 +443,8 @@ export interface ConnectDeps {): { configPath: string; replacedPrior: boolean } | Promise<{ configPath: string; replacedPrior: boolean }>;/** After a successful registration: the brain-first block in the agent's own instruction file. Returns the line to print. */writeInstructions(agent: AgentId, name: string, optOut: boolean): string | null;+ /** After the block: the per-turn hook that puts the rule next to every turn (src/core/setup/turn-hook.ts). `ok: false` fails the install loudly. */+ writeTurnHook(agent: AgentId): { lines: string[]; ok: boolean };}async function defaultPromptYesNo(question: string): Promise<boolean> {@@ -504,6 +509,16 @@ const defaultDeps: ConnectDeps = {const o = installerBrainFirst({ target, access: { kind: 'mcp', server: name }, writer: `gbrain connect --agent ${agent} --install`, instructions: optOut ? false : undefined });return `${describeBrainFirstOutcome(o, false).trim()}${o.decision.value === 'accepted' ? ' (opt out with --no-instructions)' : ''}`;},+ writeTurnHook: (agent) => {+ const target = isBrainFirstHarness(agent) ? brainFirstTarget(agent) : null;+ const accepted = !!target && !('error' in target) && priorBrainFirst(agent, target.path)?.status === 'installed' && process.env.GBRAIN_AGENT_INSTRUCTIONS !== '0';+ const rerun = ['gbrain', 'setup', agent, '--instructions-only'];+ const { outcome, verdict } = installerTurnHook({ harness: agent, accepted, gbrainBin: resolveGbrainBin(), gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined, rerun: rerun.join(' ') });+ const lines = [describeTurnHookOutcome(outcome).trim()];+ if (!verdict || verdict.ok) return { lines: verdict ? [...lines, `verify turn hook ${verdict.message}`] : lines, ok: true };+ const fix = turnHookFix(agent, rerun);+ return { lines: [...lines, `error turn_hook_not_loaded (${verdict.reason}): the per-turn gbrain hook is not active: ${verdict.message}. Fix: ${rerun.join(' ')}. Verify: ${fix.verify?.argv?.join(' ')}${TURN_HOOK_NATIVE_INSPECT[agent] ? `; the harness's own check: ${TURN_HOOK_NATIVE_INSPECT[agent]}` : ''}.`], ok: false };+ },writeOpencodeRemoteEntry: async (name, url, opts) => {// The writer's contract: callers hold acquireBootstrapLock on the config// dir (harness.ts [X11] parity) — the user-global file is shared across@@ -768,6 +783,7 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDeps);const ocInstructions = deps.writeInstructions(f.agent, f.name, f.noInstructions);if (ocInstructions) console.error(ocInstructions);+ for (const line of deps.writeTurnHook(f.agent).lines) console.error(line);if (deps.env(ENV_VAR) !== realToken) {console.error(`opencode resolves {env:${ENV_VAR}} at read time. Add this to your shell profile so sessions can reach the brain:`);console.error(` export ${ENV_VAR}=<your-token>`);@@ -818,6 +834,8 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDepsconsole.error(`Added MCP server '${f.name}' -> ${url}.`);const instructions = deps.writeInstructions(f.agent, f.name, f.noInstructions);if (instructions) console.error(instructions);+ const turnHook = deps.writeTurnHook(f.agent);+ for (const line of turnHook.lines) console.error(line);// Codex reads the token from the env var at runtime, not from its config.// If the current env doesn't already carry it, the user must export it.@@ -833,6 +851,7 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDepsconsole.error(`Verified: ${probe.identity || 'brain reachable'}`);console.error('');console.error(LEARN_INSTRUCTION);+ if (!turnHook.ok) process.exit(1);return;}// Server is registered, but end-to-end auth did not verify. Exit non-zero sodiff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 3acbf40cde..ac546c4cea 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -122,6 +122,7 @@ import { withoutPhysicalRootMetadata } from '../core/persistence/root-metadata.timport { 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';+import { TURN_RULE_LANE, turnRuleHookYields } from '../core/setup/turn-hook.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -342,6 +343,8 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>}// Plugin lane (the Claude Code and Codex plugin manifests): yields to any other gbrain lane wiring this event.if (process.env.GBRAIN_HOOK_LANE === 'plugin' && pluginHookYields(io.harness ?? 'claude-code', event, io.cwd ?? process.cwd())) return 0;+ // Turn-rule lane (src/core/setup/turn-hook.ts): rule only, and only when no other gbrain lane wires this event.+ if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE && event === 'user-prompt' && turnRuleHookYields(io.harness ?? 'claude-code', io.cwd ?? process.cwd())) return 0;switch (event) {case 'session-start':@@ -1128,7 +1131,9 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// 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');+ 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.+ if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE) return { outcome: 'ok', reason: 'rule_only' };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 89eacb65c0..e9e74935e1 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -23,9 +23,11 @@* Engine-free: setup never opens the database itself.*/import { realpathSync } from 'node:fs';-import { dirname } from 'node:path';+import { dirname, join } from 'node:path';import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';import { removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../core/setup/openclaw-turn-plugin.ts';+import { isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';+import { inspectTurnHook, turnHookFix, verifyTurnHook, type TurnHookVerdict } from '../core/setup/turn-hook-check.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';@@ -420,8 +422,8 @@ export async function runSetup(args: string[]): Promise<number> {if (liveOwner && !liveOwner.ours) return refuse(liveServeConflict(liveOwner, 'claude-code', flags.name), out);if (found.mcp.state === 'unowned' && !pluginOwner) {return refuse(ownerConflict('unowned_entry', `${found.configPath} already has an MCP server named '${flags.name}' that gbrain setup did not write (or it was edited since); setup never overwrites it.`, {- actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--name', `${flags.name}-local`, '--dry-run', '--json'],- why: 'Preview a setup under another name, or remove that entry yourself and run setup again.', verify: verifyDryRun('claude-code', flags.name) }), out);+ actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--instructions-only', ...(flags.name === 'gbrain' ? [] : ['--name', flags.name]), ...(scope === 'project' ? ['--scope', 'project'] : [])],+ why: 'Keeps that entry and adds only the brain-first block and the per-turn hook, so its sessions are told to check gbrain first on every turn. Or preview a setup under another name (--name), or remove that entry yourself and run setup again.', verify: verifyDryRun('claude-code', flags.name) }), out);}const harnessReceipt = readHarnessReceiptState(brainHome);const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'claude-code');@@ -561,8 +563,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConif (liveOwner && !liveOwner.ours) return refuse(liveServeConflict(liveOwner, 'codex', flags.name), out);if (found.mcp.state === 'unowned' && !pluginOwner) {return refuse(ownerConflict('unowned_entry', `${found.configPath} already has [mcp_servers.${flags.name}] that gbrain setup did not write (or it was edited since); setup never overwrites it.`, {- actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--name', `${flags.name}-local`, '--dry-run', '--json'],- why: 'Preview a setup under another name, or remove that table yourself and run setup again.', verify: verifyDryRun('codex', flags.name) }), out);+ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--instructions-only', ...(flags.name === 'gbrain' ? [] : ['--name', flags.name])],+ why: 'Keeps that table and adds only the brain-first block and the per-turn hook, so its sessions are told to check gbrain first on every turn. Or preview a setup under another name (--name), or remove that table yourself and run setup again.', verify: verifyDryRun('codex', flags.name) }), out);}const harnessReceipt = readHarnessReceiptState(brainHome);const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'codex');@@ -729,23 +731,47 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>instructions = syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });}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'? (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 }))- : null;- const code = instructions?.action === 'preserve' ? 1 : 0;+ : 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.+ const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && turnHook ? 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 } : {}), 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 } : {}), ...(check ? { turn_hook_check: check } : {}), 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}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}`);+ 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.`);+ 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.');+ if (check && !check.ok) return refuse(turnHookNotLoaded(harness, check, rerun), out);return code;}+/**+ * Claude Code and Codex under --instructions-only (a plugin or a bare `mcp add`+ * serves MCP): the per-turn rule hook, unless setup's own hooks, a bootstrap+ * lane or a gbrain plugin already carry the rule.+ */+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 });+ 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 });+}++function turnHookNotLoaded(harness: string, check: TurnHookVerdict, rerun: string[]): OperationError {+ const fix = turnHookFix(harness, rerun);+ return opError('turn_hook_not_loaded', `The per-turn gbrain hook for ${harness} is not active: ${check.message}.`, fix.why, { reason: check.reason, docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix });+}+async function finish(out: Out, doc: {harness?: SetupHarnessId; dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: Array<{ step: string; action: string; detail: string }>; states: string[];verify: { ok: boolean; reason: string; message: string } | null; notices: Notice[]; notes: string[]; preserved?: unknown[];diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.tsindex 188c7447a4..70a3504447 100644--- a/src/core/bootstrap/codex-hooks.ts+++ b/src/core/bootstrap/codex-hooks.ts@@ -356,6 +356,7 @@ export function removeCodexHooks(opts: { hooksPath?: string; configPath?: string// (src/core/setup/codex.ts), so an edited group is preserved, never removed.export const CODEX_SETUP_LANE_TOKEN = 'GBRAIN_HOOK_LANE=setup';+const TURN_RULE_LANE_TOKEN = 'GBRAIN_HOOK_LANE=turn-rule';export const CODEX_SETUP_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'] as const;export type CodexSetupEvent = (typeof CODEX_SETUP_EVENTS)[number];@@ -370,9 +371,9 @@ const SETUP_EVENT_SPECS: Record<CodexSetupEvent, { stateName: string; timeout: nexport interface CodexHookGroup { hooks: Array<{ type: 'command'; command: string; timeout: number }> }-/** Setup's group for one event. `env` is POSIX `env` (any $SHELL parses it); the values pin this install. */-export function codexSetupHookGroup(gbrainBin: string, event: CodexSetupEvent, env: { GBRAIN_HOME?: string; GBRAIN_SOURCE?: string }): CodexHookGroup {- const assignments = [CODEX_SETUP_LANE_TOKEN, ...(env.GBRAIN_HOME ? [`GBRAIN_HOME=${env.GBRAIN_HOME}`] : []), ...(env.GBRAIN_SOURCE ? [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`] : [])];+/** Setup's group for one event (or the turn-rule lane's, src/core/setup/turn-hook.ts). `env` is POSIX `env` (any $SHELL parses it); the values pin this install. */+export function codexSetupHookGroup(gbrainBin: string, event: CodexSetupEvent, env: { GBRAIN_HOME?: string; GBRAIN_SOURCE?: string }, lane = 'setup'): CodexHookGroup {+ const assignments = [`GBRAIN_HOOK_LANE=${lane}`, ...(env.GBRAIN_HOME ? [`GBRAIN_HOME=${env.GBRAIN_HOME}`] : []), ...(env.GBRAIN_SOURCE ? [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`] : [])];const spec = SETUP_EVENT_SPECS[event];const command = event === 'SessionEnd'? ['env', ...assignments].map(shellQuote).join(' ') + ' ' + buildCodexSessionEndCommand(gbrainBin)@@ -387,7 +388,7 @@ export function codexSetupTrustEntry(hooksPath: string, event: CodexSetupEvent,return { key: `${hooksPath}:${stateName}:${index}:0`, trusted_hash: codexHookTrustHash(stateName, handler.command, handler.timeout) };}-export interface CodexHookCensusGroup { event: string; index: number; hash: string; lane: 'setup' | 'bootstrap' | 'other'; commands: string[] }+export interface CodexHookCensusGroup { event: string; index: number; hash: string; lane: 'setup' | 'bootstrap' | 'turn-rule' | 'other'; commands: string[] }function loadHooksJson(hooksPath: string): { doc: HooksJson; hooks: NonNullable<HooksJson['hooks']> } {if (!existsSync(hooksPath)) return { doc: {}, hooks: {} };@@ -418,6 +419,7 @@ export function codexHookCensus(hooksPath: string): CodexHookCensusGroup[] {groups.forEach((group, index) => {const commands = (Array.isArray(group?.hooks) ? group.hooks : []).map((h) => h?.command).filter((c): c is string => typeof c === 'string');const lane = commands.some((c) => c.includes(CODEX_SETUP_LANE_TOKEN)) ? 'setup'+ : commands.some((c) => c.includes(TURN_RULE_LANE_TOKEN)) ? 'turn-rule': commands.some((c) => CONTEXT_LANE_TOKENS.some((t) => c.includes(t))) ? 'bootstrap' : 'other';out.push({ event, index, hash: ownedEntryFingerprint(group), lane, commands });});diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 6c4d6f4d56..e3d0089d55 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -113,6 +113,7 @@ export const ERROR_CATALOGUE = {setup_harness_unsupported: { code: 'setup_harness_unsupported', docs: 'docs/guides/repair.md#setup-harness-unsupported' },setup_owner_conflict: { code: 'setup_owner_conflict', docs: 'docs/guides/repair.md#setup-owner-conflict' },setup_hosted_connection: { code: 'setup_hosted_connection', docs: 'docs/guides/repair.md#setup-hosted-connection' },+ turn_hook_not_loaded: { code: 'turn_hook_not_loaded', docs: 'docs/guides/repair.md#turn-hook-not-loaded' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 16340256d3..72023b432b 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -646,6 +646,7 @@ export const CODES = {setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },+ turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex 1ec617a0a1..59b0f2c7b6 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -22,7 +22,7 @@*/import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';import { homedir } from 'node:os';-import { join } from 'node:path';+import { basename, dirname, isAbsolute, join, relative } from 'node:path';import { parse as parseJsonc, type ParseError } from 'jsonc-parser';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';import { claudeUserMemoryPath, codexAgentsOverridePath, codexGlobalAgentsPath, opencodeConfigDir } from '../bootstrap/host-specs.ts';@@ -96,13 +96,31 @@ export function renderBrainFirstTurnRule(access: BrainFirstAccess): string {* on only while a block is recorded as installed for that harness (its access* names the tools), off under GBRAIN_AGENT_INSTRUCTIONS=0.*/-export function brainFirstTurnRule(harness: string): string | null {+export function brainFirstTurnRule(harness: string, cwd: string = process.cwd()): string | null {if (process.env[BRAIN_FIRST_OPT_OUT_ENV] === '0') return null;- const installed = readBrainFirstLedger().filter((e) => e.harness === harness && e.status === 'installed' && e.access)+ // A project-scope record (CLAUDE.local.md, a Cursor rule) applies only inside its project, and a+ // user-scope opt-out silences the rule everywhere else, so a project install never leaks into other sessions.+ const entries = readBrainFirstLedger().filter((e) => e.harness === harness && e.access);+ const userDeclined = entries.some((e) => !isProjectSurface(e.harness, e.path) && e.status === 'declined');+ const installed = entries.filter((e) => e.status === 'installed' && (isProjectSurface(e.harness, e.path) ? isInside(cwd, projectRootOf(e.harness, e.path)) : !userDeclined)).sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))[0];return installed ? renderBrainFirstTurnRule(installed.access) : null;}+/** A block written into one project (Claude Code's CLAUDE.local.md, a Cursor rule), not a user-global file. */+export function isProjectSurface(harness: string, path: string): boolean {+ return (harness === 'claude-code' && basename(path) === 'CLAUDE.local.md') || harness === 'cursor';+}++function projectRootOf(harness: string, path: string): string {+ return harness === 'cursor' ? dirname(dirname(dirname(path))) : dirname(path);+}++function isInside(cwd: string, root: string): boolean {+ const rel = relative(root, cwd);+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));+}+export const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';export interface BrainFirstTarget {@@ -137,12 +155,17 @@ export function openclawStateDir(): string {return join(home(), profile && profile !== 'default' ? `.openclaw-${profile}` : '.openclaw');}+/** openclaw.json: OPENCLAW_CONFIG_PATH, else <state dir>/openclaw.json. */+export function openclawConfigPath(): string {+ return process.env.OPENCLAW_CONFIG_PATH?.trim() ? expandHome(process.env.OPENCLAW_CONFIG_PATH.trim()) : join(openclawStateDir(), 'openclaw.json');+}+/*** openclaw.json is JSON5. Comments and trailing commas parse as JSONC; bare* object keys are quoted first. Anything else reads as unparseable, and the* caller asks for --workspace rather than guess.*/-function parseJson5ish(text: string): unknown {+export function parseJson5ish(text: string): unknown {const quotedKeys = text.replace(/([{,]\s*)([A-Za-z_$][\w$-]*)\s*:/g, '$1"$2":');const doubleQuoted = quotedKeys.replace(/'((?:[^'\\\n]|\\.)*)'/g, (_m, s: string) => JSON.stringify(s.replace(/\\'/g, "'")));for (const candidate of [text, quotedKeys, doubleQuoted]) {@@ -161,7 +184,7 @@ function parseJson5ish(text: string): unknown {* workspace, so the caller must name one.*/export function resolveOpenclawWorkspace(): { path: string } | { error: string } {- const configPath = process.env.OPENCLAW_CONFIG_PATH?.trim() ? expandHome(process.env.OPENCLAW_CONFIG_PATH.trim()) : join(openclawStateDir(), 'openclaw.json');+ const configPath = openclawConfigPath();let configured: string | undefined;if (existsSync(configPath)) {const cfg = parseJson5ish(readFileSync(configPath, 'utf8')) as { agents?: { defaults?: { workspace?: unknown }; list?: unknown; entries?: unknown } } | undefined;@@ -337,6 +360,13 @@ export function syncBrainFirst(opts: { target: BrainFirstTarget; access: BrainFireturn out('preserve', `the brain-first markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`);}if (decision.value === 'declined') {+ // The target moved (Codex: a non-empty AGENTS.override.md now wins), so an opt-out also strips the+ // blocks this harness still has at its other user-global paths; otherwise their records keep the per-turn rule on.+ if (!target.project) {+ for (const other of readBrainFirstLedger().filter((e) => e.harness === target.harness && e.path !== target.path && e.status === 'installed' && !isProjectSurface(e.harness, e.path))) {+ syncBrainFirst({ ...opts, target: { ...target, path: other.path }, access: other.access });+ }+ }if (before.state === 'no_file' || before.state === 'absent') {record('declined', false);return out('skip', `no brain-first block in ${target.path}; opt-out recorded`);diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.tsindex 2b8b8b5a50..26d43a6f96 100644--- a/src/core/setup/claude-code.ts+++ b/src/core/setup/claude-code.ts@@ -37,6 +37,7 @@ import {type ClaudeHookEvent,} from '../bootstrap/host-specs.ts';import { stdioServeArgv } from '../mcp-registration.ts';+import { isTurnRuleEntry } from './turn-hook.ts';import type { McpSurface } from '../../mcp/surface.ts';export type WiringScope = 'user' | 'project';@@ -203,6 +204,7 @@ function hookCensus(settingsPath: string): HookCensus {if (!Array.isArray(entries)) continue;for (const entry of entries) {const marker = (entry as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY];+ if (isTurnRuleEntry(entry)) continue;if ((typeof marker === 'string' && marker !== GBRAIN_SETUP_MARKER_VALUE) || classifyHarnessHook(entry, event, 'any')) {if ((CLAUDE_HOOK_EVENTS as readonly string[]).includes(event)) otherLane.add(event);continue;diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex f3fb333d5f..b28a364ee8 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -123,3 +123,16 @@ export function removeHermesTurnHook(opts: { hermesHome: string; dryRun: booleanreturn { action: 'skip', path, detail: `per-turn rule hook in ${path} left as it is (${(e as Error).message})` };}}++/** Read-only: is the marked hook in config.yaml, and does Hermes's allowlist approve its exact command? */+export function inspectHermesTurnHook(hermesHome: string): { state: 'absent' | 'unapproved' | 'approved'; path: string; command?: string } {+ const path = join(hermesHome, 'config.yaml');+ try {+ const probe = probeBlock(MARKERS, existsSync(path) ? readFileSync(path, 'utf8') : '');+ const command = probe.state === 'present' ? commandIn(probe.interior) : null;+ if (!command) return { state: 'absent', path };+ return { state: readAllowlist(join(hermesHome, ALLOWLIST)).approvals.some((e) => approves(e, command)) ? 'approved' : 'unapproved', path, command };+ } catch {+ return { state: 'absent', path };+ }+}diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsnew file mode 100644index 0000000000..52f4fd557e--- /dev/null+++ b/src/core/setup/turn-hook-check.ts@@ -0,0 +1,197 @@+/**+ * turn-hook-check.ts — is the per-turn brain-first hook wired, and does it+ * load? Read by doctor's harness_wiring check (`inspectTurnHook`, files only)+ * and by every install path (`verifyTurnHook`, which also runs the hook or+ * the harness's own inspect command), so an install whose hook cannot load+ * fails loudly with the command that shows why.+ *+ * Native inspect commands, per harness:+ * Claude Code /hooks inside a session (lists UserPromptSubmit hooks)+ * Codex /hooks inside a session (trust a hook there)+ * OpenClaw openclaw plugins inspect gbrain-turn-rule --runtime --json+ * Hermes hermes hooks doctor+ */+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 { 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';+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';++export const TURN_HOOK_NATIVE_INSPECT: Record<string, string> = {+ 'claude-code': '/hooks (inside a Claude Code session)',+ codex: '/hooks (inside a Codex session)',+ openclaw: `openclaw plugins inspect ${OPENCLAW_TURN_PLUGIN_ID} --runtime --json`,+ hermes: 'hermes hooks doctor',+};++export interface TurnHookState {+ harness: string;+ /** wired: a per-turn hook is configured; untrusted: configured but the harness will not run it yet; missing: none; not_supported: the harness has no per-turn hook gbrain can install. */+ state: 'wired' | 'untrusted' | 'missing' | 'not_supported';+ /** Which lane carries it. */+ via?: 'setup' | 'bootstrap' | 'turn-rule' | 'plugin' | 'native';+ detail: string;+ /** The hook command gbrain can run to prove it (Claude Code and Codex, not plugin lanes). */+ command?: string;+ native_inspect?: string;+}++function readJson(path: string): Record<string, unknown> | null {+ if (!existsSync(path)) return null;+ try { return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>; } catch { return null; }+}++function claudeEntries(path: string): Array<Record<string, unknown>> {+ const groups = (readJson(path)?.hooks as Record<string, unknown> | undefined)?.UserPromptSubmit;+ if (!Array.isArray(groups)) return [];+ return groups.flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : []))+ .filter((e): e is Record<string, unknown> => !!e && typeof e === 'object');+}++const isGbrainPromptEntry = (e: Record<string, unknown>) =>+ isTurnRuleEntry(e) || typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, 'UserPromptSubmit', 'any');++/** Files only, no process run. `projectDir`: a project-scope Claude Code install's directory. */+export function inspectTurnHook(harness: string, opts: { projectDir?: string } = {}): TurnHookState {+ const native_inspect = TURN_HOOK_NATIVE_INSPECT[harness];+ const plugin = enabledPluginLanes('gbrain').find((l) => l.harness === harness);+ 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 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 (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 };+ }+ if (harness === 'codex') {+ let groups: ReturnType<typeof codexHookCensus> = [];+ try { groups = codexHookCensus(codexHooksPath()).filter((g) => g.event === 'UserPromptSubmit' && g.lane !== 'other'); } catch { /* unparseable: Codex skips it too */ }+ const g = groups.find((x) => x.lane !== 'turn-rule') ?? groups[0];+ if (g) {+ const command = g.commands[0]!;+ 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);+ 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` };+ }+ if (plugin) return { harness, state: 'wired', via: 'plugin', detail: `the '${plugin.plugin}' plugin declares the UserPromptSubmit hook (Codex runs it once you trust it in /hooks)`, native_inspect };+ return { harness, state: 'missing', detail: `no gbrain UserPromptSubmit hook in ${codexHooksPath()}`, native_inspect };+ }+ if (harness === 'openclaw') {+ const dir = openclawTurnPluginDir();+ const cfg = existsSync(openclawConfigPath()) ? parseJson5ish(readFileSync(openclawConfigPath(), 'utf8')) as { plugins?: { entries?: Record<string, { enabled?: unknown; hooks?: { allowConversationAccess?: unknown } }> } } | undefined : undefined;+ const entry = cfg?.plugins?.entries?.[OPENCLAW_TURN_PLUGIN_ID];+ if (!existsSync(join(dir, 'index.js'))) return { harness, state: 'missing', detail: `no per-turn rule plugin at ${dir}`, native_inspect };+ if (!entry || entry.enabled === false) return { harness, state: 'missing', detail: `${dir} exists but ${openclawConfigPath()} does not enable ${OPENCLAW_TURN_PLUGIN_ID}`, native_inspect };+ if (entry.hooks?.allowConversationAccess !== true) return { harness, state: 'untrusted', via: 'native', detail: `${OPENCLAW_TURN_PLUGIN_ID} is enabled without plugins.entries.${OPENCLAW_TURN_PLUGIN_ID}.hooks.allowConversationAccess, so OpenClaw skips its before_prompt_build hook`, native_inspect };+ return { harness, state: 'wired', via: 'native', detail: `${OPENCLAW_TURN_PLUGIN_ID} (before_prompt_build) enabled in ${openclawConfigPath()}`, native_inspect };+ }+ if (harness === 'hermes') {+ const target = brainFirstTarget('hermes');+ const home = 'error' in target ? '' : dirname(target.path);+ const h = inspectHermesTurnHook(home);+ if (h.state === 'absent') return { harness, state: 'missing', detail: `no gbrain pre_llm_call hook in ${h.path}`, native_inspect };+ if (h.state === 'unapproved') return { harness, state: 'untrusted', via: 'native', detail: `the gbrain pre_llm_call hook in ${h.path} is not in Hermes's shell-hooks-allowlist.json, so Hermes does not run it`, native_inspect };+ return { harness, state: 'wired', via: 'native', detail: `pre_llm_call hook in ${h.path}, approved`, native_inspect };+ }+ return { harness, state: 'not_supported', detail: `${harness} has no per-turn hook gbrain can install; the rule reaches it only through its instruction file` };+}++type Run = (argv: string[], stdin?: string) => { ok: boolean; output: string };+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 });+ return { ok: r.exitCode === 0, output: `${r.stdout.toString()}${r.stderr.toString()}` };+ } catch (e) { return { ok: false, output: (e as Error).message }; }+};+const which = (bin: string): string | null => { try { return Bun.which(bin, { PATH: process.env.PATH ?? '' }); } catch { return null; } };++export interface TurnHookVerdict { ok: boolean; state: TurnHookState; reason: string; message: string }++/**+ * Install-time proof that the hook loads: Claude Code and Codex run the+ * configured command once and look for the rule in its output; OpenClaw runs+ * its runtime inspect; Hermes runs `hermes hooks doctor`. A harness binary+ * that is not on PATH leaves the file-level answer standing.+ */+export function verifyTurnHook(harness: string, opts: { projectDir?: string; run?: Run; which?: (bin: string) => string | null } = {}): TurnHookVerdict {+ const run = opts.run ?? defaultRun;+ const find = opts.which ?? which;+ const state = inspectTurnHook(harness, opts);+ const fail = (reason: string, message: string): TurnHookVerdict => ({ ok: false, state, reason, message });+ if (state.state === 'not_supported') return { ok: true, state, reason: 'not_supported', message: state.detail };+ if (state.state === 'missing') return fail('missing', state.detail);+ if (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) {+ 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?)');+ return { ok: true, state, reason: 'ran', message: `${state.detail}; it ran and added the rule` };+ }+ if (harness === 'openclaw') {+ const bin = find('openclaw');+ if (!bin) return { ok: true, state, reason: 'native_unavailable', message: `${state.detail}; openclaw is not on PATH, so run ${state.native_inspect} on the OpenClaw host` };+ const r = run([bin, 'plugins', 'inspect', OPENCLAW_TURN_PLUGIN_ID, '--runtime', '--json']);+ const loaded = r.ok && r.output.includes('before_prompt_build') && /"(?:status)"\s*:\s*"loaded"|"imported"\s*:\s*true/.test(r.output) && !/"status"\s*:\s*"(?:error|disabled)"/.test(r.output);+ return loaded ? { ok: true, state, reason: 'ran', message: `${state.detail}; openclaw loads it with before_prompt_build` }+ : fail('not_loaded', `\`${state.native_inspect}\` does not show ${OPENCLAW_TURN_PLUGIN_ID} loaded with before_prompt_build`);+ }+ if (harness === 'hermes') {+ const bin = find('hermes');+ if (!bin) return { ok: true, state, reason: 'native_unavailable', message: `${state.detail}; hermes is not on PATH, so run ${state.native_inspect} on the Hermes host` };+ const r = run([bin, 'hooks', 'doctor']);+ const block = r.output.split(/\n(?=\s*\[)/).find((b) => /\[pre_llm_call\]/.test(b) && b.includes('GBrain'));+ if (!r.ok || !block) return fail('not_loaded', `\`hermes hooks doctor\` does not list gbrain's pre_llm_call hook`);+ if (/✗|⚠/.test(block)) return fail('not_loaded', `\`hermes hooks doctor\` reports a problem with gbrain's pre_llm_call hook: ${block.split('\n').filter((l) => /✗|⚠/.test(l)).map((l) => l.trim()).join(' ')}`);+ return { ok: true, state, reason: 'ran', message: `${state.detail}; hermes hooks doctor reports it healthy` };+ }+ return { ok: true, state, reason: 'wired', message: state.detail };+}++/**+ * The operator-protocol fix for a hook that is missing or does not load:+ * re-run the install that writes it, then verify with the harness's own+ * inspect command (OpenClaw, Hermes) or doctor (Claude Code, Codex, whose+ * inspect is the in-session /hooks menu).+ */+export function turnHookFix(harness: string, rerun: string[]): Action {+ const native = TURN_HOOK_NATIVE_INSPECT[harness];+ const verify = harness === 'openclaw' ? ['openclaw', 'plugins', 'inspect', OPENCLAW_TURN_PLUGIN_ID, '--runtime', '--json']+ : harness === 'hermes' ? ['hermes', 'hooks', 'doctor'] : ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'];+ return { argv: rerun, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: { argv: verify },+ why: `Writes the per-turn hook that puts "check gbrain first" next to every turn; without it agents rarely use the brain. ${native ? `The harness's own check: ${native}.` : ''}`.trim() };+}++/**+ * The installer lanes' per-turn hook (`gbrain connect --install`, the hosted+ * harness install, `gbrain bootstrap harness`): with the brain-first block+ * accepted, install the turn-rule hook unless another gbrain lane already+ * carries the rule, then prove it loads; declined, remove it. opencode and+ * other clients get `not_supported` (no per-turn hook to install).+ */+export function installerTurnHook(opts: { harness: string; accepted: boolean; gbrainBin: string | null; gbrainHome?: string; paths?: TurnHookPaths; rerun: string; verify?: boolean }): { outcome: TurnHookOutcome; verdict: TurnHookVerdict | null } {+ const { harness } = opts;+ if (!isTurnRuleHarness(harness)) {+ return { 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 };+ 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}` }+ : syncTurnRuleHook({ harness, gbrainBin: opts.gbrainBin, gbrainHome: opts.gbrainHome, paths: opts.paths, rerun: opts.rerun });+ if (outcome.action === 'print') return { outcome, verdict: { ok: false, state: { harness, state: 'missing', detail: outcome.detail }, reason: 'missing', message: outcome.detail } };+ return { outcome, verdict: opts.verify === false || opts.paths ? null : verifyTurnHook(harness) };+}diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.tsnew file mode 100644index 0000000000..6de396e8b5--- /dev/null+++ b/src/core/setup/turn-hook.ts@@ -0,0 +1,216 @@+/**+ * 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 setup <claude-code|codex> --instructions-only` (a bare `mcp add`+ * registration gbrain did not write).+ *+ * Why: harness evals found the brain is used when "check gbrain first" reaches+ * the model on every turn (a per-turn hook: 80 of 80) and almost never when it+ * rides only the MCP tool list (2 of 99) or a startup file (0 of 80).+ *+ * The hook is one UserPromptSubmit entry running+ * `env GBRAIN_HOOK_LANE=turn-rule <gbrain> hook user-prompt`. In that lane the+ * hook adds only the rule (read from the brain-first ledger, so an opt-out or+ * GBRAIN_AGENT_INSTRUCTIONS=0 silences it) and never reads local context: the+ * connection may point at another brain. It yields when another gbrain lane+ * (setup, bootstrap) wires the same event, so a turn gets the rule once; a+ * gbrain plugin yields to it the same way.+ *+ * Ownership: Claude Code entries carry the `turn-rule-v1` marker, and the+ * command (lane token + `hook user-prompt`) identifies them when Claude Code+ * dropped the marker on a rewrite. Codex groups are identified by the lane+ * token; the trust entry Codex requires is written beside the group and owned+ * by its hash. Nothing else in either file is touched.+ *+ * `inspectTurnHook` (doctor) and `verifyTurnHook` (install time) answer+ * whether a per-turn hook is wired and loads, naming the harness's own+ * inspect command when it does not.+ */+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 { 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';++export const TURN_RULE_LANE = 'turn-rule';+export const TURN_RULE_MARKER = 'turn-rule-v1';+export const TURN_RULE_LANE_TOKEN = 'GBRAIN_HOOK_LANE=turn-rule';+const EVENT = 'UserPromptSubmit';+const TRUST_STATE = 'user_prompt_submit';++export type TurnRuleHarness = 'claude-code' | 'codex';+export function isTurnRuleHarness(h: string): h is TurnRuleHarness { return h === 'claude-code' || h === 'codex'; }++export interface TurnHookPaths {+ /** Claude Code settings.json (default: the user settings file). */+ claudeSettings?: string;+ /** Codex hooks.json and config.toml (default: CODEX_HOME's). */+ codexHooks?: string;+ codexConfig?: string;+}++export interface TurnHookOutcome {+ harness: string;+ action: 'write' | 'keep' | 'remove' | 'skip' | 'print';+ path: string;+ detail: string;+ /** For `print`: the one command that wires it. */+ next?: string;+}++const claudePath = (p: TurnHookPaths) => p.claudeSettings ?? claudeUserSettingsPath();+const codexPaths = (p: TurnHookPaths) => ({ hooks: p.codexHooks ?? codexHooksPath(), config: p.codexConfig ?? codexConfigPath() });++export function claudeTurnRuleCommand(gbrainBin: string, gbrainHome?: string): string {+ return buildClaudeHookCommand(gbrainBin, EVENT, { ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE });+}++export function codexTurnRuleGroup(gbrainBin: string, gbrainHome?: string): CodexHookGroup {+ return codexSetupHookGroup(gbrainBin, EVENT, gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}, TURN_RULE_LANE);+}++/** A Claude Code hook entry that is this lane's: marked, or (marker dropped) its command shape. */+export function isTurnRuleEntry(entry: unknown): boolean {+ if (!entry || typeof entry !== 'object') return false;+ const e = entry as Record<string, unknown>;+ if (e[GBRAIN_HOOK_MARKER_KEY] === TURN_RULE_MARKER) return true;+ return !Object.prototype.hasOwnProperty.call(e, GBRAIN_HOOK_MARKER_KEY) && typeof e.command === 'string'+ && e.command.includes(TURN_RULE_LANE_TOKEN) && /\shook user-prompt(?:\s|$)/.test(e.command);+}++function readJson(path: string): Record<string, unknown> | null {+ if (!existsSync(path)) return null;+ try {+ const v = JSON.parse(readFileSync(path, 'utf8')) as unknown;+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;+ } catch { return null; }+}++/** Every command entry under UserPromptSubmit in a Claude Code settings file. */+function claudePromptEntries(path: string): Array<Record<string, unknown>> {+ const groups = (readJson(path)?.hooks as Record<string, unknown> | undefined)?.[EVENT];+ if (!Array.isArray(groups)) return [];+ return groups.flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : []))+ .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 {+ if (isTurnRuleEntry(e)) return false;+ return typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, EVENT, 'any');+}++/**+ * Runtime dedupe for the turn-rule lane: another gbrain lane already wires+ * UserPromptSubmit for this harness, and that hook adds the same rule.+ * Fail-open (an unreadable file counts as not wired).+ */+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; }+ }+ return [claudeUserSettingsPath(), join(cwd, '.claude', 'settings.json'), join(cwd, '.claude', 'settings.local.json')]+ .some((p) => claudePromptEntries(p).some(isOtherGbrainEntry));+}++/** Install or refresh the turn-rule hook. Never throws; anything it cannot write safely comes back as `print` with the command that wires it. */+export function syncTurnRuleHook(opts: { harness: TurnRuleHarness; gbrainBin: string | null; gbrainHome?: string; paths?: TurnHookPaths; dryRun?: boolean; rerun: string }): TurnHookOutcome {+ const paths = opts.paths ?? {};+ const where = opts.harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths);+ const print = (why: string): TurnHookOutcome => ({ harness: opts.harness, action: 'print', path: where, detail: `per-turn rule hook not installed: ${why}`, next: opts.rerun });+ if (!opts.gbrainBin || !opts.gbrainBin.startsWith('/')) return print('no absolute gbrain binary was found (harnesses inherit no PATH); install gbrain globally or pass --gbrain-bin');+ try {+ return opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, codexPaths(paths), !!opts.dryRun, print)+ : syncClaude(opts.gbrainBin, opts.gbrainHome, claudePath(paths), !!opts.dryRun);+ } catch (e) {+ return print((e as Error).message);+ }+}++function syncClaude(bin: string, home: string | undefined, path: string, dryRun: boolean): TurnHookOutcome {+ const command = claudeTurnRuleCommand(bin, home);+ const want = { type: 'command', command, timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[EVENT] };+ const wantHash = hookEntryHash(want)!;+ const ours = claudePromptEntries(path).filter(isTurnRuleEntry);+ const detail = `per-turn rule hook (UserPromptSubmit) in ${path}`;+ if (ours.length === 1 && hookEntryHash(ours[0]) === wantHash) return { harness: 'claude-code', action: 'keep', path, detail };+ if (dryRun) return { harness: 'claude-code', action: 'write', path, detail };+ mkdirSync(dirname(path), { recursive: true });+ const owned = new Set([wantHash, ...ours.map((e) => hookEntryHash(e)).filter((h): h is string => !!h)]);+ writeClaudeHooksAt(path, { gbrainBin: bin, env: { ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE, GBRAIN_SEAT: '' },+ events: [EVENT], marker: TURN_RULE_MARKER, ownedEntryHashes: owned, freshMode: 0o600 });+ return { harness: 'claude-code', action: 'write', path, detail };+}++const trustPath = (key: string) => ['hooks', 'state', key];+const trustKey = (hooksPath: string, index: number) => `${hooksPath}:${TRUST_STATE}:${index}:0`;++/** Our groups in hooks.json with the trust table Codex would read for each. */+function codexOurs(paths: { hooks: string; config: string }) {+ return codexHookCensus(paths.hooks).filter((g) => g.event === EVENT && g.lane === 'turn-rule');+}++/** Remove the trust table at `key` only when it trusts exactly one of our commands. */+function dropOurTrust(config: string, key: string, commands: string[]): void {+ const table = readCodexTomlTable(config, trustPath(key)) as { trusted_hash?: unknown } | undefined;+ if (!table || !commands.some((c) => codexHookTrustHash(TRUST_STATE, c, 15) === table.trusted_hash)) return;+ removeCodexTomlTable(config, trustPath(key));+}++function syncCodex(bin: string, home: string | undefined, paths: { hooks: string; config: string }, dryRun: boolean, print: (why: string) => TurnHookOutcome): TurnHookOutcome {+ const group = codexTurnRuleGroup(bin, home);+ const hash = ownedEntryFingerprint(group);+ const ours = codexOurs(paths);+ const detail = `per-turn rule hook (UserPromptSubmit) in ${paths.hooks}, trusted in ${paths.config}`;+ const current = ours.length === 1 && ours[0]!.hash === hash;+ const { key, trusted_hash } = codexSetupTrustEntry(paths.hooks, EVENT, current ? ours[0]!.index : 0, group);+ const trusted = current && (readCodexTomlTable(paths.config, trustPath(key)) as { trusted_hash?: unknown } | undefined)?.trusted_hash === trusted_hash;+ if (current && trusted) return { harness: 'codex', action: 'keep', path: paths.hooks, detail };+ if (dryRun) return { harness: 'codex', action: 'write', path: paths.hooks, detail };+ mkdirSync(dirname(paths.hooks), { recursive: true, mode: 0o700 });+ const commands = ours.flatMap((g) => g.commands);+ for (const g of ours) dropOurTrust(paths.config, trustKey(paths.hooks, g.index), commands);+ const w = writeCodexSetupHooks(paths.hooks, { want: { [EVENT]: group }, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });+ const index = w.indexes[EVENT];+ if (index === undefined) return print(`${paths.hooks} did not take the hook`);+ const entry = codexSetupTrustEntry(paths.hooks, EVENT, index, group);+ const existing = readCodexTomlTable(paths.config, trustPath(entry.key)) as { trusted_hash?: unknown } | undefined;+ if (existing === undefined) appendCodexTomlTable(paths.config, trustPath(entry.key), { trusted_hash: entry.trusted_hash }, 'gbrain turn-rule hook: trusts the per-turn brain-first rule; owned by its hash');+ else if (existing.trusted_hash !== entry.trusted_hash) return print(`${paths.config} already has a different [hooks.state."${entry.key}"]; trust gbrain's UserPromptSubmit hook in Codex's /hooks`);+ return { harness: 'codex', action: 'write', path: paths.hooks, detail };+}++/** Remove the turn-rule hook (opt-out or uninstall). Never throws. */+export function removeTurnRuleHook(opts: { harness: TurnRuleHarness; paths?: TurnHookPaths; dryRun?: boolean }): TurnHookOutcome {+ const paths = opts.paths ?? {};+ try {+ if (opts.harness === 'codex') {+ const p = codexPaths(paths);+ const ours = codexOurs(p);+ if (ours.length === 0) return { harness: 'codex', action: 'skip', path: p.hooks, detail: `no per-turn rule hook in ${p.hooks}` };+ if (!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() });+ }+ return { harness: 'codex', action: 'remove', path: p.hooks, detail: `per-turn rule hook removed from ${p.hooks}` };+ }+ const path = claudePath(paths);+ const ours = claudePromptEntries(path).filter(isTurnRuleEntry);+ if (ours.length === 0) return { harness: 'claude-code', action: 'skip', path, detail: `no per-turn rule hook in ${path}` };+ if (!opts.dryRun) removeClaudeHooksAt(path, TURN_RULE_MARKER, { ownedEntryHashes: new Set(ours.map((e) => hookEntryHash(e)).filter((h): h is string => !!h)) });+ return { harness: 'claude-code', action: 'remove', path, detail: `per-turn rule hook removed from ${path}` };+ } catch (e) {+ return { harness: opts.harness, action: 'skip', path: opts.harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths), detail: `per-turn rule hook left as it is (${(e as Error).message})` };+ }+}++export function describeTurnHookOutcome(o: TurnHookOutcome, dryRun = false): string {+ const verb = dryRun && (o.action === 'write' || o.action === 'remove') ? `would ${o.action}` : o.action;+ return ` ${verb.padEnd(8)} ${'turn hook'.padEnd(7)} ${o.detail}${o.next ? `; wire it with: ${o.next}` : ''}`;+}diff --git a/test/connect.test.ts b/test/connect.test.tsindex aa65dacfef..9a40ce5ed3 100644--- a/test/connect.test.ts+++ b/test/connect.test.ts@@ -509,6 +509,7 @@ function installDeps(over: Partial<ConnectDeps> = {}): ConnectDeps {registerOAuthClient: () => ({ ok: true, clientId: 'gbrain_cl_minted', clientSecret: 'gbrain_cs_minted' }),writeOpencodeRemoteEntry: (name) => ({ configPath: `/tmp/xdg/opencode/opencode.jsonc (${name})`, replacedPrior: false }),writeInstructions: (agent, name, optOut) => (optOut ? null : `write instructions brain-first block for ${agent} '${name}'`),+ writeTurnHook: (agent) => ({ lines: [`write turn hook per-turn rule hook for ${agent}`], ok: true }),...over,};}