Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(claude-cli): opt back in with GBRAIN_CLAUDE_CLI_USER_SETTINGS=1; disclose the default flip
garrytanf16a4c4c393a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84ebc5b9e7..22b46ca131 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,7 +14,7 @@ identifiers and attribution are available in the pre-removal Git revision**OpenClaw setups stop breaking each other, upgrades stop breaking OpenClaw, and four other harness fixes land.** Six fixes for people running gbrain with OpenClaw. Setting up one agent's workspace no longer rewrites or removes the per-turn brain rule every other agent on the same gateway relies on. Background turns (heartbeats, cron, finished commands) no longer get told to answer. `gbrain upgrade` no longer reinstalls gbrain in a way OpenClaw refuses to load as a plugin. `gbrain doctor` stops failing on skills another tool put in the workspace. The OpenClaw guide now leads with an install route that works and documents OpenClaw's own remote MCP connection.-**gbrain's background claude-cli calls no longer read your personal Claude Code instructions.** On Claude Code 2.1.314 or newer the claude-cli provider runs its child with `--setting-sources ""`, so your `~/.claude/CLAUDE.md`, memory and `settings.json` stop steering gbrain's extraction and summary calls (and stop adding about 42k cached tokens to each). The trade-off: `settings.json`'s `env`, `apiKeyHelper` and permission rules don't reach the child either; the subscription login is kept. Older CLIs are unchanged.+**gbrain's background claude-cli calls no longer read your personal Claude Code instructions.** On Claude Code 2.1.314 or newer the claude-cli provider runs its child with `--setting-sources ""`, so your `~/.claude/CLAUDE.md`, memory and `settings.json` stop steering gbrain's extraction and summary calls (and stop adding about 42k cached tokens to each). The trade-off: `settings.json`'s `env`, `apiKeyHelper` and permission rules don't reach the child either; the subscription login is kept. To load them again, set `GBRAIN_CLAUDE_CLI_USER_SETTINGS=1` in your shell or `~/.gbrain/.env`. Older CLIs are unchanged.Four more harness fixes: a per-turn hook you paste into Hermes by hand now counts, `gbrain setup claude-code --instructions-only` writes the per-turn rule hook on Windows, `request_tools` stops promising tools a stdio session cannot call, and `gbrain schema show --source` reads that source's pack.@@ -37,9 +37,10 @@ Four more harness fixes: a per-turn hook you paste into Hermes by hand now count- `src/core/mcp-registration.ts`: `openclawThinClientBlock` names OpenClaw's native remote MCP route.- Docs: `docs/mcp/OPENCLAW.md`, `docs/guides/upgrades-auto-update.md`, `TODOS.md`.- Tests: `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`, `test/check-resolvable.test.ts`, `test/mcp-registration-blocks.test.ts`, and the upgrade suites that pin the child `bun` argv.-- `src/core/ai/providers/claude-cli-language-model.ts`: `runClaude` adds `--setting-sources ""` when a cached `claude --version` (once per binary per process) reads `SETTING_SOURCES_MIN_VERSION` (2.1.314) or newer. Reported and first fixed by @Masashi-Ono0611 (#8350).+- `src/core/ai/providers/claude-cli-language-model.ts`: `runClaude` adds `--setting-sources ""` when a cached `claude --version` (once per binary per process) reads `SETTING_SOURCES_MIN_VERSION` (2.1.314) or newer. `GBRAIN_CLAUDE_CLI_USER_SETTINGS=1` skips the flag and the probe, and a cwd `.env` cannot set it (`src/core/env-trust.ts`). Reported and first fixed by @Masashi-Ono0611 (#8350).- Docs: `docs/ai-providers/claude-cli.md` (the trade-off), `docs/guides/skillopt.md`, `docs/architecture/key-files/core-ai-continued.md`.-- Tests: `test/claude-cli-setting-sources-8342.test.ts`; the `test/claude-cli-output-cap.test.ts` stub answers `--version`.+- `src/core/behavior-change-notice.ts`: the `claude_cli_setting_sources_8342` row.+- Tests: `test/claude-cli-setting-sources-8342.test.ts` (including the opt-in); the `test/claude-cli-output-cap.test.ts` stub answers `--version`.## [0.60.620.0] - 2026-11-09diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.mdindex fcbc1840f7..12b37ee6f6 100644--- a/docs/ai-providers/claude-cli.md+++ b/docs/ai-providers/claude-cli.md@@ -135,7 +135,10 @@ Trade-off: `--setting-sources ""` loads no settings source at all, so the`env` block, `apiKeyHelper` and permission rules in your `settings.json` don'treach the child either. The subscription (OAuth) login is kept, but a claudelogin or proxy that depends on `settings.json` doesn't apply to gbrain's-claude-cli calls on these versions.+claude-cli calls on these versions. To load them again, set+`GBRAIN_CLAUDE_CLI_USER_SETTINGS=1` in the environment gbrain runs in (your+shell or `~/.gbrain/.env`; a project `.env` can't set it): the child then gets+no `--setting-sources` flag and gbrain skips the version probe.The adapter does not use `claude`'s own agentic tool-calling — it injects afenced instruction block into the system prompt teaching the model adiff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.mdindex 7486906f5b..40815c8d9e 100644--- a/docs/architecture/key-files/core-ai-continued.md+++ b/docs/architecture/key-files/core-ai-continued.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Provider adapters, recipes and the Voyage width plumbing.-- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287), and a CLI at `SETTING_SOURCES_MIN_VERSION` (2.1.314) or newer also gets `--setting-sources ""` (#8342: no user CLAUDE.md, memory or settings.json; one async `claude --version` per binary per process, false when unreadable). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`). #6791: every child also gets `--verbose`, so the json stdout is the session's event array; `doGenerate` takes its text from `resolveClaudeCliAnswer` (`claude-cli-continuation.ts`) and, when that refuses a continued answer, returns empty text, no tool calls, finish `length` and `providerMetadata['claude-cli'] = { code: 'continuation_unproven', reason }` before any `<use_tools>` block is parsed.+- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287), and a CLI at `SETTING_SOURCES_MIN_VERSION` (2.1.314) or newer also gets `--setting-sources ""` (#8342: no user CLAUDE.md, memory or settings.json; one `claude --version` per binary per process, killed at 5 s, false when unreadable; `GBRAIN_CLAUDE_CLI_USER_SETTINGS=1` skips flag and probe). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`). #6791: every child also gets `--verbose`, so the json stdout is the session's event array; `doGenerate` takes its text from `resolveClaudeCliAnswer` (`claude-cli-continuation.ts`) and, when that refuses a continued answer, returns empty text, no tool calls, finish `length` and `providerMetadata['claude-cli'] = { code: 'continuation_unproven', reason }` before any `<use_tools>` block is parsed.- `src/core/ai/providers/claude-cli-continuation.ts` — what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope's `result` / `stop_reason` are then only the continuation's. `resolveClaudeCliAnswer(run, requestedCap)` keeps the envelope `result` when there was no continuation (or the envelope already says `max_tokens`); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a `message.id` are one segment; `<synthetic>` error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal `result`, no `tombstone` event, every earlier text-bearing segment to report `max_tokens` or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is `continuation_unproven` with reason `segments_unmatched`. Without events (a bare envelope) a continuation is inferred from `num_turns > 1` or output tokens above the cap (the forwarded positive-integer `maxOutputTokens`, else `CLAUDE_CLI_DEFAULT_OUTPUT_CAP` = 32000) and refused as `events_missing`; an event array with no assistant message under those signals is `no_assistant_events`; one segment with output above a requested cap is `segments_unmatched`. Each reason's first refusal in a process writes one notice naming its remedy (`CONTINUATION_UNPROVEN_REMEDY`: upgrade the CLI for the first two, raise the caller's output cap for the third). Nothing is read from disk, so a hermetic `CLAUDE_CONFIG_DIR` changes nothing. The notice is one `[claude-cli] continuation_unproven (<reason>)` stderr line; `continuationUnprovenMetadata` builds the provider metadata. Pinned by `test/claude-cli-continuation-6791.test.ts`.diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex 6c5eb13170..1ed8e913cd 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -25,7 +25,8 @@* skill resolution. On a CLI at SETTING_SOURCES_MIN_VERSION or newer,* `--setting-sources ""` keeps user-level ~/.claude/CLAUDE.md, memory and* settings out of the child (#8342) without `--bare`, which forces- * ANTHROPIC_API_KEY auth; an older CLI still loads them. #4119: to isolate+ * ANTHROPIC_API_KEY auth; an older CLI still loads them, and+ * GBRAIN_CLAUDE_CLI_USER_SETTINGS=1 loads them again. #4119: to isolate* the whole config dir (SkillOpt rollouts), set* GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG — see resolveHermeticConfigDir.*@@ -474,8 +475,9 @@ function runClaude(if (thinkingOff) env.MAX_THINKING_TOKENS = '0';// #8342: load no settings source, so the user's own ~/.claude/CLAUDE.md,// memory and settings.json never steer this call. Unlike --bare this- // keeps the subscription login.- if (takesNoSettingSources(env)) args.push('--setting-sources', '');+ // keeps the subscription login. GBRAIN_CLAUDE_CLI_USER_SETTINGS=1 opts+ // back in (no flag, no version probe).+ if (process.env.GBRAIN_CLAUDE_CLI_USER_SETTINGS !== '1' && takesNoSettingSources(env)) args.push('--setting-sources', '');const child = spawn(claudeBin(), args, {stdio: ['pipe', 'pipe', 'pipe'],cwd: ensureCleanCwd(),diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2e82668a4c..af82dcb299 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },+ { since: '0.60.620.0', id: 'claude_cli_setting_sources_8342', text: 'On Claude Code 2.1.314 or newer, the claude-cli provider now runs its child with `--setting-sources ""`, so your own `~/.claude/CLAUDE.md`, memory and `settings.json` no longer steer gbrain\'s background claude-cli calls. The subscription login is kept, but `settings.json`\'s `env`, `apiKeyHelper` and permission rules no longer reach the child either. `GBRAIN_CLAUDE_CLI_USER_SETTINGS=1` (shell or ~/.gbrain/.env) loads them again. Older CLIs are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/env-trust.ts b/src/core/env-trust.tsindex 768eb20710..9de7de6d27 100644--- a/src/core/env-trust.ts+++ b/src/core/env-trust.ts@@ -173,6 +173,7 @@ export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [// --- exec-target: gbrain spawns the named program ------------------------'GBRAIN_CLAUDE_CLI_BIN', // binary run for the claude-cli language model'GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG', // becomes that binary's CLAUDE_CONFIG_DIR → its hooks/settings+ 'GBRAIN_CLAUDE_CLI_USER_SETTINGS', // #8342: =1 lets the user's ~/.claude CLAUDE.md and settings.json back into that binary's calls'GBRAIN_JOB_CHILD_CLI', // CLI the job-isolation worker spawns per job'GBRAIN_BIN_OVERRIDE', // gbrain binary used by claw-test// --- root / registry redirect ------------------------------------------diff --git a/test/claude-cli-setting-sources-8342.test.ts b/test/claude-cli-setting-sources-8342.test.tsindex a9846274ad..375d51c28f 100644--- a/test/claude-cli-setting-sources-8342.test.ts+++ b/test/claude-cli-setting-sources-8342.test.ts@@ -36,13 +36,13 @@ function stub(versionLine: string) {`cat "${response}"`,].join('\n') + '\n');chmodSync(bin, 0o755);- const call = async () => {- await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin }, () => new ClaudeCliLanguageModel('claude-sonnet-5-5').doGenerate({+ const call = async (extraEnv: Record<string, string | undefined> = {}) => {+ await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, ...extraEnv }, () => new ClaudeCliLanguageModel('claude-sonnet-5-5').doGenerate({prompt: [{ role: 'user', content: [{ type: 'text', text: 'Reply OK' }] }],} as LanguageModelV2CallOptions));return readFileSync(join(dir, 'argv'), 'utf8').trimEnd().split('\n').map((l) => l.slice(1, -1));};- const probes = () => readFileSync(join(dir, 'probes'), 'utf8').trimEnd().split('\n').length;+ const probes = () => { try { return readFileSync(join(dir, 'probes'), 'utf8').trimEnd().split('\n').length; } catch { return 0; } };return { call, probes };}@@ -82,6 +82,15 @@ describe('claude-cli keeps the user\'s own settings and CLAUDE.md out of the chiexpect(readFileSync(join(dir, 'probe-cwd'), 'utf8').trim()).not.toBe(process.cwd());}, 30_000);+ test('GBRAIN_CLAUDE_CLI_USER_SETTINGS=1 opts back in: no --setting-sources and no version probe', async () => {+ const s = stub('2.1.316 (Claude Code)');+ const argv = await s.call({ GBRAIN_CLAUDE_CLI_USER_SETTINGS: '1' });+ expect(settingSources(argv)).toBeNull();+ expect(argv).toContain('--settings');+ expect(s.probes()).toBe(0);+ expect(settingSources(await s.call({ GBRAIN_CLAUDE_CLI_USER_SETTINGS: '0' }))).toBe('');+ });+test('an older or unreadable version keeps today\'s argv', async () => {for (const line of ['2.1.313 (Claude Code)', '2.0.60 (Claude Code)', 'not a version']) {const argv = await stub(line).call();