Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(claude-cli): keep user-level CLAUDE.md out of the child with --setting-sources

garrytan0f3dca47dfe5
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index 63eeece1ba..08f456a32b 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -125,9 +125,11 @@ stdin:
`--bare` (which would skip loading the user-level `~/.claude/CLAUDE.md`
entirely) is not among the flags passed, because it also forces
-`ANTHROPIC_API_KEY` auth (per the recipe's source comment). One effect of
-not passing it: the user-level `~/.claude/CLAUDE.md` still loads and gets
-cached tokens on every call.
+`ANTHROPIC_API_KEY` auth (per the recipe's source comment). On Claude Code
+2.1.314 or newer the child gets `--setting-sources ""` instead, so your
+user-level `~/.claude/CLAUDE.md`, memory and `settings.json` stay out of
+every call and the login is kept (gbrain reads `claude --version` once per
+binary per process). An older CLI still loads them on every call.
The adapter does not use `claude`'s own agentic tool-calling — it injects a
fenced instruction block into the system prompt teaching the model a
@@ -155,7 +157,7 @@ above.
| Prompt caching | The recipe declares `supports_prompt_cache: true`: Claude Code caches prompt prefixes itself on every `--print` run (Anthropic's Claude Code docs put `-p` runs in the main-conversation TTL bucket — one hour on a subscription, five minutes on an API key). gbrain cannot place `cache_control` breakpoints on this path — the adapter renders messages to stdin text and ignores `providerOptions` — so caching is automatic rather than gateway-driven, and `doctor`'s `subagent_capability` does not grade a claude-cli subagent tier `degraded:no_caching`. `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens` (next row). |
| Usage / token counts | Reported `usage.input_tokens` / `usage.output_tokens` are read straight from the CLI's `--output-format json` envelope (`result.usage?.input_tokens` / `output_tokens`); gbrain does not independently count tokens for this path. The envelope's `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens`, so cache reads are counted in gbrain's usage accounting; `cache_creation_input_tokens` is not surfaced (the AI SDK's usage shape has no corresponding field). |
| Cost figures | The recipe declares `cost_per_1m_input_usd: 3.0` / `cost_per_1m_output_usd: 15.0` — the same Sonnet-class figures the `anthropic` recipe declares (`price_last_verified: 2026-06-17`) — purely so gbrain's budget ledger has a number to attribute per call. Neither the recipe nor the adapter code checks what you're actually billed; treat these as the ledger's nominal per-call number, not a verified charge. The `--max-usd` / `--max-cost` budget gate does not read them either: it prices `claude-cli:<model>` at the nominal Anthropic rate for that model, and a short alias (`claude-cli:haiku`) prices identically to the dated id it resolves to; `pricing.overrides` forces $0 or a real rate for any `claude-cli:*` string, and on a subscription one line prices every claude-cli model: `gbrain pricing set 'claude-cli:*' --rate 0` (an exact model entry still wins; at $0 no cap limits claude-cli calls). |
-| User-level CLAUDE.md | `~/.claude/CLAUDE.md` still loads on every call (see above) — only the working directory changes (see "What actually happens on a call" for exactly what that directory is and isn't). |
+| User-level CLAUDE.md | Kept out on Claude Code 2.1.314 or newer (`--setting-sources ""`); an older CLI loads `~/.claude/CLAUDE.md` on every call (see above). Otherwise only the working directory changes (see "What actually happens on a call" for exactly what that directory is and isn't). |
## Doctor probe timeout: per-recipe, 30s for claude-cli
diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.md
index 0f3d5a5c62..7486906f5b 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). 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 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-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/docs/guides/skillopt.md b/docs/guides/skillopt.md
index 4268f79160..11b726ac94 100644
--- a/docs/guides/skillopt.md
+++ b/docs/guides/skillopt.md
@@ -522,8 +522,10 @@ rollout rather than one batch.
### Hermetic claude-cli rollouts (`CLAUDE_CONFIG_DIR` recipe)
When the target model routes through the `claude-cli:` recipe, each rollout
-child inherits the operator's user-level `~/.claude` state — CLAUDE.md
-memory, `settings.json`, hooks. That contaminates measurements: a skill can
+child inherits the operator's user-level `~/.claude` state: on Claude Code
+older than 2.1.314 that includes CLAUDE.md memory and `settings.json` (newer
+CLIs get `--setting-sources ""`, which keeps those out), and on every version
+the rest of the config dir. That contaminates measurements: a skill can
score well only because YOUR user-level instructions carried it. For hermetic
runs, set:
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 2bf3f97587..e3932ff69c 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -22,13 +22,12 @@
* The subprocess is spawned from a dedicated tmpdir so claude-cli's
* CLAUDE.md auto-discovery has no local files to find. `--system-prompt`
* replaces the default system prompt; `--disable-slash-commands` skips
- * skill resolution. User-level ~/.claude/CLAUDE.md still loads because
- * the only way to skip it is `--bare`, which forces ANTHROPIC_API_KEY
- * auth and defeats the whole point of this provider. The ~42k cached
- * tokens from user-level instructions are accepted as a cost-trivial
- * trade-off on the subscription path. #4119: when those user-level
- * instructions must NOT leak into a measurement (SkillOpt rollouts),
- * set GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG — see resolveHermeticConfigDir.
+ * 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
+ * the whole config dir (SkillOpt rollouts), set
+ * GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG — see resolveHermeticConfigDir.
*
* doStream is not yet implemented; the model declares no streaming. Callers
* (gateway.toolLoop primarily) use doGenerate.
@@ -362,6 +361,34 @@ function claudeCliVersion(env: NodeJS.ProcessEnv): string | null {
return /\d+\.\d+\.\d+/.exec(typeof r.stdout === 'string' ? r.stdout : '')?.[0] ?? null;
}
+/** Oldest claude CLI that gets `--setting-sources ""` (#8342): 2.1.314 fixed
+ * an excluded settings file still supplying some settings. Older CLIs keep
+ * the argv above. */
+export const SETTING_SOURCES_MIN_VERSION = '2.1.314';
+
+const settingSourcesProbes = new Map<string, Promise<boolean>>();
+
+/** Whether the CLI at `bin` is SETTING_SOURCES_MIN_VERSION or newer: one
+ * `claude --version` per binary per process; false when it cannot be read. */
+function takesNoSettingSources(bin: string): Promise<boolean> {
+ let probe = settingSourcesProbes.get(bin);
+ if (!probe) {
+ probe = new Promise((resolve) => {
+ let stdout = '';
+ const child = spawn(bin, ['--version'], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 });
+ child.stdout.on('data', (chunk) => { stdout += String(chunk); });
+ child.on('error', () => resolve(false));
+ child.on('close', () => {
+ const found = /(\d+)\.(\d+)\.(\d+)/.exec(stdout)?.slice(1).map(Number);
+ const min = SETTING_SOURCES_MIN_VERSION.split('.').map(Number);
+ resolve(!!found && (found[0]! - min[0]! || found[1]! - min[1]! || found[2]! - min[2]!) >= 0);
+ });
+ });
+ settingSourcesProbes.set(bin, probe);
+ }
+ return probe;
+}
+
/**
* #6918: Claude Code thinks by default on Claude 5 models, and the API needs
* thinking.budget_tokens of at least 1024 and below max_tokens, so a call
@@ -379,13 +406,14 @@ export function thinkingDisabledBelowFloor(maxOutputTokens: number | undefined):
* the parsed `--output-format json` envelope. Aborts propagate to SIGTERM on
* the child.
*/
-function runClaude(
+async function runClaude(
systemPrompt: string,
userPrompt: string,
model: string,
signal?: AbortSignal,
maxOutputTokens?: number,
): Promise<ClaudeRun> {
+ const noSettingSources = await takesNoSettingSources(claudeBin());
return new Promise((resolve, reject) => {
// #6424: forward the call's output cap. The inline --settings env sits
// above the user's settings.json env block, so both carry it.
@@ -418,6 +446,10 @@ function runClaude(
// subscription login (credentials are not settings). Accepted by every
// CLI that accepts the flags above.
'--settings', settings,
+ // #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.
+ ...(noSettingSources ? ['--setting-sources', ''] : []),
];
if (systemPrompt) {
args.push('--system-prompt', systemPrompt);
diff --git a/test/claude-cli-output-cap.test.ts b/test/claude-cli-output-cap.test.ts
index 9969a56237..863d6b9636 100644
--- a/test/claude-cli-output-cap.test.ts
+++ b/test/claude-cli-output-cap.test.ts
@@ -60,7 +60,7 @@ async function withCli<T>(
): Promise<T> {
const dir = mkdtempSync(join(tmpdir(), 'claude-output-cap-'));
const capsPath = join(dir, 'caps');
- const lines = ['#!/bin/sh', 'cat > /dev/null', `printf '%s\\n' "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" >> "${capsPath}"`];
+ const lines = ['#!/bin/sh', 'if [ "$1" = "--version" ]; then echo "2.1.316 (Claude Code)"; exit 0; fi', 'cat > /dev/null', `printf '%s\\n' "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" >> "${capsPath}"`];
for (const [cap, { body, exit }] of Object.entries(responses)) {
const file = join(dir, `response-${cap === '*' ? 'default' : cap}.txt`);
writeFileSync(file, typeof body === 'string' ? body : JSON.stringify(body));
diff --git a/test/claude-cli-setting-sources-8342.test.ts b/test/claude-cli-setting-sources-8342.test.ts
new file mode 100644
index 0000000000..8fca27426e
--- /dev/null
+++ b/test/claude-cli-setting-sources-8342.test.ts
@@ -0,0 +1,70 @@
+/**
+ * #8342: the claude-cli child must not read the user's own Claude Code
+ * settings and instructions (~/.claude/CLAUDE.md, settings.json): they would
+ * steer gbrain's background calls. `--setting-sources ""` loads no settings
+ * source and keeps the subscription login. The child gets it only when
+ * `claude --version` reports SETTING_SOURCES_MIN_VERSION or newer, probed once
+ * per binary; an older or unreadable version keeps today's argv.
+ *
+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI and records its
+ * argv; no live CLI or provider account is used.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';
+import { ClaudeCliLanguageModel, SETTING_SOURCES_MIN_VERSION } from '../src/core/ai/providers/claude-cli-language-model.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SUCCESS = { type: 'result', subtype: 'success', is_error: false, result: 'OK', stop_reason: 'end_turn', session_id: 'synthetic-session', num_turns: 1, usage: { input_tokens: 5, output_tokens: 1 } };
+const dirs: string[] = [];
+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });
+
+function stub(versionLine: string) {
+ const dir = mkdtempSync(join(tmpdir(), 'claude-setting-sources-'));
+ dirs.push(dir);
+ const response = join(dir, 'response.json');
+ writeFileSync(response, JSON.stringify(SUCCESS));
+ const bin = join(dir, 'claude');
+ writeFileSync(bin, [
+ '#!/bin/sh',
+ `if [ "$1" = "--version" ]; then echo probe >> "${dir}/probes"; echo '${versionLine}'; exit 0; fi`,
+ 'cat > /dev/null',
+ `: > "${dir}/argv"`,
+ `for a in "$@"; do printf '[%s]\\n' "$a" >> "${dir}/argv"; done`,
+ `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({
+ 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;
+ return { call, probes };
+}
+
+const settingSources = (argv: string[]) => {
+ const i = argv.indexOf('--setting-sources');
+ return i < 0 ? null : argv[i + 1];
+};
+
+describe('claude-cli keeps the user\'s own settings and CLAUDE.md out of the child (#8342)', () => {
+ test(`${SETTING_SOURCES_MIN_VERSION} and newer: --setting-sources "" on every call, probed once per binary`, async () => {
+ const s = stub('2.1.316 (Claude Code)');
+ expect(settingSources(await s.call())).toBe('');
+ expect(settingSources(await s.call())).toBe('');
+ expect(s.probes()).toBe(1);
+ expect(settingSources(await stub(`${SETTING_SOURCES_MIN_VERSION} (Claude Code)`).call())).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();
+ expect(settingSources(argv)).toBeNull();
+ expect(argv).toContain('--settings');
+ }
+ });
+});