Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: turn-rule lane, install verify, turn_hook_not_loaded

garrytan02f7e7588494
diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.ts
index ff94e6877e..4e9dd3e462 100644
--- a/src/commands/harness-connect.ts
+++ b/src/commands/harness-connect.ts
@@ -36,7 +36,11 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);
if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);
}
- if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);
+ const turnHookError = (result as { turn_hook?: { error?: { message: string; fix: { argv?: string[] } } } }).turn_hook?.error;
+ if (turnHookError) {
+ console.error(`turn_hook_not_loaded: the per-turn gbrain hook is not active: ${turnHookError.message}. Fix: ${turnHookError.fix.argv?.join(' ')}`);
+ setCliExitVerdict(1);
+ } else if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);
} catch (error) {
console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));
setCliExitVerdict(1);
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index e9e74935e1..8dcd0353d6 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -465,8 +465,10 @@ export async function runSetup(args: string[]): Promise<number> {
verify = await smokeStdioRegistration({ harness: 'claude-code', source: found.configPath, kind: 'stdio', command: entry.command, args: entry.args, env: entry.env });
}
const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];
+ const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('claude-code', { projectDir }) : null;
const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,
- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions });
+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, turnHook });
+ if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('claude-code', turnHook, ['gbrain', 'setup', 'claude-code', ...(scope === 'project' ? ['--scope', 'project'] : [])]), out);
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
if (e instanceof OperationError) return refuse(e, out);
@@ -610,8 +612,10 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
}
const push = capabilityRows('codex')[0]!.push;
const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];
+ const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('codex') : null;
const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,
- steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions });
+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions, turnHook });
+ if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('codex', turnHook, ['gbrain', 'setup', 'codex']), out);
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
if (e instanceof OperationError) return refuse(e, out);
@@ -738,7 +742,8 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
? (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.
- const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && turnHook ? verifyTurnHook(harness, { projectDir }) : null;
+ // 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 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));
@@ -776,6 +781,7 @@ 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[];
instructions?: BrainFirstOutcome | null;
+ turnHook?: TurnHookVerdict | null;
}): Promise<number> {
const harness = doc.harness ?? 'claude-code';
const state = doc.states.at(-1) ?? null;
@@ -783,7 +789,7 @@ async function finish(out: Out, doc: {
await writeJsonDocument(`${JSON.stringify({
harness, dry_run: doc.dryRun, remove: doc.remove ?? false,
...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),
- steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, states: doc.states, state, verify: doc.verify,
+ steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, ...(doc.turnHook ? { turn_hook_check: doc.turnHook } : {}), states: doc.states, state, verify: doc.verify,
capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),
}, null, 2)}\n`, (t) => process.stdout.write(t));
@@ -791,6 +797,7 @@ async function finish(out: Out, doc: {
}
if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));
if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);
+ if (doc.turnHook?.ok) say(out, `Turn hook: ok (${doc.turnHook.reason}): ${doc.turnHook.message}`);
if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);
if (state && !doc.remove) say(out, harness === 'codex'
? 'Next: start a new Codex session (config and hooks are read at session start) and check that /mcp lists gbrain.'
diff --git a/src/core/bootstrap/harness-brain-first.ts b/src/core/bootstrap/harness-brain-first.ts
index 7a602903f9..cec2932487 100644
--- a/src/core/bootstrap/harness-brain-first.ts
+++ b/src/core/bootstrap/harness-brain-first.ts
@@ -4,6 +4,10 @@
* the managed block in its own instruction file; removal strips only the
* blocks this lane recorded.
*/
+import { dirname, join } from 'node:path';
+import { claudeUserSettingsPath, codexConfigPath } from './host-specs.ts';
+import { describeTurnHookOutcome, removeTurnRuleHook } from '../setup/turn-hook.ts';
+import { installerTurnHook, TURN_HOOK_NATIVE_INSPECT, type TurnHookVerdict } from '../setup/turn-hook-check.ts';
import { brainFirstTargetAt, codexInstructionFile, describeBrainFirstOutcome, installerBrainFirst, readBrainFirstLedger, removeBrainFirst } from '../setup/brain-first.ts';
const WRITER = 'gbrain bootstrap harness';
@@ -34,3 +38,44 @@ export function removeHarnessBrainFirst(server: string, log: (line: string) => v
log(describeBrainFirstOutcome(removeBrainFirst({ harness: e.harness, path: e.path, dryRun: false, server }), false).trim());
}
}
+
+/**
+ * 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
+ * (block declined) removes it. Returns false when a hook could not be wired or
+ * does not load, so the install fails loudly.
+ */
+export function writeHarnessTurnHooks(opts: { hosts: readonly BrainFirstHost[]; claudeHooksWired: boolean; noHooks: boolean; gbrainBin: string | null;
+ userSettingsPath: string; codexConfig: string; log: (line: string) => void; logError: (line: string) => void }): { ok: boolean; results: Array<{ host: string; action: string; detail: string; check?: TurnHookVerdict }> } {
+ const results: Array<{ host: string; action: string; detail: string; check?: TurnHookVerdict }> = [];
+ let ok = true;
+ if (opts.noHooks) return { ok, results };
+ const ledger = readBrainFirstLedger();
+ for (const host of opts.hosts) {
+ if (host === 'opencode' || (host === 'claude-code' && opts.claudeHooksWired)) continue;
+ const paths = host === 'codex' ? { codexHooks: join(dirname(opts.codexConfig), 'hooks.json'), codexConfig: opts.codexConfig } : { claudeSettings: opts.userSettingsPath };
+ const sandboxed = host === 'codex' ? opts.codexConfig !== codexConfigPath() : opts.userSettingsPath !== claudeUserSettingsPath();
+ const accepted = process.env.GBRAIN_AGENT_INSTRUCTIONS !== '0' && ledger.some((e) => e.harness === host && e.writer === WRITER && e.status === 'installed');
+ const { outcome, verdict } = installerTurnHook({ harness: host, accepted, gbrainBin: opts.gbrainBin, gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined,
+ paths: sandboxed ? paths : undefined, rerun: `gbrain setup ${host} --instructions-only` });
+ opts.log(describeTurnHookOutcome(outcome).trim());
+ results.push({ host, action: outcome.action, detail: outcome.detail, ...(verdict ? { check: verdict } : {}) });
+ if (verdict && !verdict.ok) {
+ ok = false;
+ opts.logError(`turn_hook_not_loaded (${verdict.reason}): the per-turn gbrain hook for ${host} is not active: ${verdict.message}. Fix: gbrain setup ${host} --instructions-only; check: ${TURN_HOOK_NATIVE_INSPECT[host]}`);
+ }
+ }
+ return { ok, results };
+}
+
+/** Uninstall: drop the turn-rule hook for a host once no brain-first block is recorded for it any more. */
+export function removeHarnessTurnHooks(opts: { userSettingsPath: string; codexConfig: string; log: (line: string) => void }): void {
+ const ledger = readBrainFirstLedger();
+ for (const host of ['claude-code', 'codex'] as const) {
+ if (ledger.some((e) => e.harness === host && e.status === 'installed')) continue;
+ const paths = host === 'codex' ? { codexHooks: join(dirname(opts.codexConfig), 'hooks.json'), codexConfig: opts.codexConfig } : { claudeSettings: opts.userSettingsPath };
+ const o = removeTurnRuleHook({ harness: host, paths });
+ if (o.action === 'remove') opts.log(describeTurnHookOutcome(o).trim());
+ }
+}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index c6b2fd9c1c..ca97592da4 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -59,7 +59,7 @@ import {
renderAmbientInstructionBlock,
stripAmbientWritebackBlockAt,
} from './instructions-block.ts';
-import { removeHarnessBrainFirst, writeHarnessBrainFirst } from './harness-brain-first.ts';
+import { removeHarnessBrainFirst, removeHarnessTurnHooks, writeHarnessBrainFirst, writeHarnessTurnHooks } from './harness-brain-first.ts';
import { createEngine } from '../engine-factory.ts';
import { isValidSourceId } from '../source-id.ts';
import { ALL_SOURCES, isResolverUserError, localFederatedSourceIds, resolveSourceWithTier } from '../source-resolver.ts';
@@ -572,6 +572,8 @@ export function buildConsentBlock(p: {
* apply will write [X7 parity]. */
instructionsPaths?: string[];
skills?: 'follow' | 'memory-only';
+ /** Hosts that get only the per-turn brain-first rule hook (src/core/setup/turn-hook.ts). */
+ turnRuleHosts?: string[];
}): string {
const lines: string[] = [
'gbrain bootstrap harness — wire framework-spawned coding sessions to this brain',
@@ -640,11 +642,12 @@ export function buildConsentBlock(p: {
...(p.wireOpencode ? ['opencode'] : []),
];
const hosts = `EVERY ${hostNames.join(' and ')} session`;
- const hookLine = !(p.wireClaude && p.hooks)
- ? (p.codexCapture ? 'One hook is wired: Codex SessionEnd transcript capture.' : 'No hooks are wired by this invocation.')
+ const turnRule = p.turnRuleHosts?.length ? `The per-turn brain-first rule hook (UserPromptSubmit: one line telling the agent to check gbrain first; it reads no brain data) is wired for ${p.turnRuleHosts.join(' and ')}. ` : '';
+ const hookLine = turnRule + (!(p.wireClaude && p.hooks)
+ ? (p.codexCapture ? 'One hook is wired: Codex SessionEnd transcript capture.' : turnRule ? 'No other hooks are wired by this invocation.' : 'No hooks are wired by this invocation.')
: p.capture
? 'Hooks run in every Claude Code session (context injection + transcript capture); auto-commit/push lanes stay inert outside gbrain agent workspaces.'
- : 'Hooks run in every Claude Code session (context injection only — capture is OFF); auto-commit/push lanes stay inert outside gbrain agent workspaces.';
+ : 'Hooks run in every Claude Code session (context injection only — capture is OFF); auto-commit/push lanes stay inert outside gbrain agent workspaces.');
const offRamps = [
'GBRAIN_HOOKS=0 (runtime)',
'`gbrain bootstrap harness --remove`',
@@ -1013,6 +1016,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
codexConfig: d.codexConfig,
opencodeConfig: d.opencodeConfig,
...(instructionsPaths.length > 0 ? { instructionsPaths } : {}),
+ turnRuleHosts: flags.noHooks || registrarMode || flags.noInstructions || process.env.GBRAIN_AGENT_INSTRUCTIONS === '0' ? []
+ : [...(wireClaude && !wireHooks ? ['Claude Code'] : []), ...(wireCodex ? ['Codex'] : [])],
});
d.log(consent);
const harnesses = [wireClaude ? 'Claude Code' : null, wireCodex ? 'Codex' : null, wireOpencode ? 'opencode' : null].filter(Boolean).join(', ');
@@ -1985,6 +1990,9 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// 10b. Brain-first instructions beside each confirmed MCP entry.
writeHarnessBrainFirst({ hosts: hosts.filter((h) => targets.some((t) => t.host === h && t.kind === 'mcp' && t.state === 'confirmed')),
server: flags.name, optOut: flags.noInstructions === true, paths: d, log: d.log });
+ // 10c. The same rule next to every turn where this lane wires no UserPromptSubmit hook of its own.
+ const turnHooks = writeHarnessTurnHooks({ hosts: hosts.filter((h) => targets.some((t) => t.host === h && t.kind === 'mcp' && t.state === 'confirmed')),
+ claudeHooksWired: wireHooks, noHooks: flags.noHooks || registrarMode, gbrainBin: d.gbrainBin, userSettingsPath: d.userSettingsPath, codexConfig: d.codexConfig, log: d.log, logError: d.logError });
// 11. Degradation + skew honesty.
if (health.engine === 'postgres') {
@@ -2020,13 +2028,14 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
degraded_per_turn: health.engine === 'postgres',
smoke_ok: smokeOk,
receipt_path: harnessReceiptPath(d.gbrainHome),
+ turn_hooks: turnHooks.results,
},
null,
2,
),
);
}
- return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;
+ return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk && turnHooks.ok ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;
}
// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────
@@ -2262,6 +2271,7 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
}
removeHarnessBrainFirst(flags.name, d.log);
+ removeHarnessTurnHooks({ userSettingsPath: d.userSettingsPath, codexConfig: d.codexConfig, log: d.log });
if (remaining.length === 0 && tokenDone && skillsDone) {
deleteHarnessReceipt(d.gbrainHome);
diff --git a/src/core/bootstrap/plugin-lanes.ts b/src/core/bootstrap/plugin-lanes.ts
index 4d2b77d3e4..4f288cabc9 100644
--- a/src/core/bootstrap/plugin-lanes.ts
+++ b/src/core/bootstrap/plugin-lanes.ts
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { codexHookCensus, codexHookGroupRuns } from './codex-hooks.ts';
import { classifyHarnessHook } from './hooks.ts';
+import { isTurnRuleEntry } from '../setup/turn-hook.ts';
import { claudeSetupPaths } from '../setup/claude-code.ts';
import { codexSetupPaths } from '../setup/codex.ts';
import { CLAUDE_HOOK_SUBCOMMAND, claudeUserSettingsPath, codexConfigPath, codexHooksPath, GBRAIN_HOOK_MARKER_KEY } from './host-specs.ts';
@@ -220,7 +221,7 @@ export function pluginHookYields(harness: string, subcommand: string, cwd: strin
if (!Array.isArray(groups)) continue;
for (const g of groups) {
const entries = (g as { hooks?: unknown })?.hooks;
- if (Array.isArray(entries) && entries.some((e) => typeof (e as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY] === 'string' || classifyHarnessHook(e, event, 'any'))) return true;
+ if (Array.isArray(entries) && entries.some((e) => typeof (e as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY] === 'string' || classifyHarnessHook(e, event, 'any') || isTurnRuleEntry(e))) return true;
}
} catch { /* fail-open */ }
}
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index 85a7a9b4a1..2501341c1f 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -19,6 +19,9 @@ import { installSharedSkillsConnection } from './shared-skills.ts';
import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';
import { harnessSharedSkillsRoot } from './status.ts';
import { gitChildEnv } from '../git-env.ts';
+import { installerTurnHook, turnHookFix } from '../setup/turn-hook-check.ts';
+import type { TurnHookPaths } from '../setup/turn-hook.ts';
+import { resolveGbrainBin } from '../gbrain-bin.ts';
import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';
export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;
@@ -103,6 +106,13 @@ function instructionFileBeside(connection: string, configPath: string): { harnes
return { harness: 'claude-code', path: process.env.CLAUDE_CONFIG_DIR?.trim() === dir ? join(dir, 'CLAUDE.md') : join(dir, '.claude', 'CLAUDE.md') };
}
+/** The per-turn hook files next to a config this install was pointed at (tests, a non-default config). */
+function turnHookPathsBeside(connection: string, configPath: string): TurnHookPaths {
+ const dir = dirname(configPath);
+ if (connection === 'codex-toml') return { codexHooks: join(dir, 'hooks.json'), codexConfig: configPath };
+ return { claudeSettings: process.env.CLAUDE_CONFIG_DIR?.trim() === dir ? join(dir, 'settings.json') : join(dir, '.claude', 'settings.json') };
+}
+
/** Install only in the current environment. Foreign entries are never adopted. */
export async function installHarnessConnection(c: HarnessCredentials, opts: InstallOptions) {
// A cached unexpired token may be the invalidated one; every later step (config and shared skills) uses the new token.
@@ -175,11 +185,16 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
const beside = instructionFileBeside(adapter.connection, configPath);
const instructions = installerBrainFirst({ target: brainFirstTargetAt(beside.harness, beside.path), access: { kind: 'mcp', server: name },
writer: `gbrain connect --harness ${adapter.id} --install`, instructions: opts.instructions, remove: opts.remove });
+ const turn = installerTurnHook({ harness: beside.harness, accepted: !opts.remove && instructions.decision.value === 'accepted' && instructions.action !== 'preserve',
+ gbrainBin: resolveGbrainBin(), gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined, paths: opts.configPath ? turnHookPathsBeside(adapter.connection, configPath) : undefined,
+ rerun: `gbrain setup ${beside.harness} --instructions-only` });
+ const turn_hook = { ...turn.outcome, ...(turn.verdict ? { check: turn.verdict } : {}),
+ ...(turn.verdict && !turn.verdict.ok ? { error: { code: 'turn_hook_not_loaded', reason: turn.verdict.reason, message: turn.verdict.message, fix: turnHookFix(beside.harness, ['gbrain', 'setup', beside.harness, '--instructions-only']) } } : {}) };
if (opts.remove) {
if (existsSync(receiptPath)) unlinkSync(receiptPath);
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
const pending = 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true;
- return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions,
+ return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions, turn_hook,
next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
: 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };
}
@@ -187,7 +202,7 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };
atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
- return { ...nextReceipt, shared_skills, instructions, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };
+ return { ...nextReceipt, shared_skills, instructions, turn_hook, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };
} finally { lock.release(); }
}
diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.ts
index 6de396e8b5..3d29da156b 100644
--- a/src/core/setup/turn-hook.ts
+++ b/src/core/setup/turn-hook.ts
@@ -180,7 +180,7 @@ function syncCodex(bin: string, home: string | undefined, paths: { hooks: string
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');
+ if (existing === undefined) appendCodexTomlTable(paths.config, trustPath(entry.key), { trusted_hash: entry.trusted_hash }, 'gbrain setup (turn-rule): trusts the per-turn brain-first rule hook; 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 };
}
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index 292f07d06d..6fc9bf9acf 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -475,7 +475,11 @@ describe('full apply', () => {
test('--no-capture declines the Codex SessionEnd capture hook (capture is its own consent item)', async () => {
const f = makeFake();
expect(await applyHarness(flags(['--harness', 'codex', '--no-capture']), f.deps)).toBe(0);
- expect(existsSync(join(dirname(f.codexConfig), 'hooks.json'))).toBe(false);
+ // The per-turn rule hook is not capture: it stays, and no SessionEnd capture group is written.
+ const declined = readFileSync(join(dirname(f.codexConfig), 'hooks.json'), 'utf8');
+ expect(declined).not.toContain('hook session-end');
+ expect(declined).not.toContain('SessionEnd');
+ expect(declined).toContain('GBRAIN_HOOK_LANE=turn-rule');
const g = makeFake();
expect(await applyHarness(flags(['--harness', 'codex']), g.deps)).toBe(0);
expect(g.out.join('\n')).toMatch(/Codex session-transcript capture/);