Skip to content

fix(haiku): strip ANTHROPIC_API_KEY from the nested claude -p child env - #693

Merged
fdaviddpt merged 3 commits into
Digital-Process-Tools:mainfrom
Mega-Therion:fix/strip-anthropic-api-key-from-nested-summarizer
Sep 16, 2026
Merged

fdaviddpt merged 3 commits into
Digital-Process-Tools:mainfrom
Mega-Therion:fix/strip-anthropic-api-key-from-nested-summarizer

Conversation

@Mega-Therion

@Mega-Therion Mega-Therion commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • ANTHROPIC_API_KEY, when set anywhere in the host environment, takes precedence over the operator's claude.ai login for the nested claude -p call the background summarizer spawns — the CLI resolves credentials in that order.
  • When that key's balance is exhausted or rate-limited, the background summarizer fails on every session-end with Credit balance is too low, silently — the operator's own interactive sessions keep working fine off the login, so nothing about the failure points at this var without reading the child's own stderr.
  • Unlike CLAUDE_CODE_OAUTH_TOKEN, this was never the child's own credential — it's an ambient host var the operator did not choose for this subprocess. _child_env() now strips it, for the same reason it already strips CLAUDE_PROJECT_DIR.

Reproduced in production

Traced via the daily narrative log (~/.remember/logs/memory-*.log) to exactly this cause, on a real installation with ANTHROPIC_API_KEY set in the environment (for unrelated reasons) and an exhausted balance:

[haiku] call exited 1; ...
[haiku] ERROR: call-haiku error: claude exited 1: Credit balance is too low | ⚠ claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth source is set and takes precedence over your claude.ai login · Unset it to load your organization's connectors

12 occurrences across several days on that installation, each showing as an opaque save-session.sh --force exited 1 warning in hook-errors.log with no indication of the actual cause unless you dig into the daily log.

Test plan

  • Added test_call_haiku_strips_anthropic_api_key, matching the existing test_call_haiku_strips_parent_session_env pattern
  • pytest tests/test_haiku.py — 80/80 passing (79 pre-existing + 1 new)
  • Confirmed manually: _child_env() no longer includes ANTHROPIC_API_KEY when set in the parent environment
  • Diff is minimal (37 insertions, 0 deletions) — no unrelated reformatting

🤖 Generated with Claude Code

Closes #703.


Maintainer edit (@fdaviddpt): only this closing reference and the note below were added — the description above is the author's own, unchanged. Two commits were pushed to this branch (see the comments below): the conditional-strip rework the review asked for, and a follow-up that stops the config warning echoing a value an operator might have pasted a real key into. #704 was a temporary duplicate of the same work, opened while pushing here was blocked, and is closed in favour of this PR.

[AI-generated]

ANTHROPIC_API_KEY, when present anywhere in the host environment, takes
precedence over the operator's claude.ai login for the nested claude -p
call the summarizer spawns -- the CLI resolves credentials in that
order. A key with an exhausted or unfunded balance then fails every
background summarize silently: save-session.sh --force exits 1 at
session end with "Credit balance is too low", while the operator's own
interactive sessions keep working fine off the login, so nothing about
the failure points at this var without reading the child's own stderr.

Reproduced in production: repeated "save-session.sh --force exited 1"
warnings traced via the daily narrative log to exactly this cause,
compounded once by a genuine rate limit and separately by this auth
routing issue. ANTHROPIC_API_KEY was never a "parent session" marker
the way CLAUDE_CODE_* is; _child_env() now strips it for the same
reason it already strips CLAUDE_PROJECT_DIR -- the child should
authenticate as if launched fresh, not inherit a credential the
operator did not choose for this subprocess.

Adds test_call_haiku_strips_anthropic_api_key alongside the existing
parent-session-stripping test. 80/80 tests pass.

@fdaviddpt fdaviddpt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this -- the diagnosis is correct and the evidence is exactly what a report like this needs: the CLI's own stderr, the frequency, and the fact that interactive sessions kept working off the login while the background summarizer did not. That last detail is what makes this failure so hard to see, and you named it precisely.

I'm requesting changes on one thing, plus some repo mechanics.

The strip is unconditional, and that breaks a different set of installations

_child_env() keeps exactly one credential:

_CHILD_ENV_KEEP = frozenset({"CLAUDE_CODE_OAUTH_TOKEN"})

For an operator whose only credential is ANTHROPIC_API_KEY -- no claude.ai login, no setup-token, which is a normal and documented way to authenticate the Claude CLI -- this patch leaves the nested claude -p with nothing to authenticate with. Every background save then fails, silently, surfacing as the same opaque save-session.sh --force exited 1 you spent days tracing. That is the failure class this PR exists to remove, relocated onto a different population rather than removed.

Worth noting that ANTHROPIC_API_KEY appears nowhere in docs/, README.md or scripts/ today, so neither behaviour is documented and we have no data on how many installs depend on it. That argues for caution rather than for assuming nobody does.

What I'd like instead: strip it only when another credential is actually available. Concretely, keep ANTHROPIC_API_KEY when none of CLAUDE_CODE_OAUTH_TOKEN (in the child env), REMEMBER_OAUTH_TOKEN or haiku.oauth_token is present; strip it when one of them is, since that is the case your report describes -- an ambient key out-ranking a login the operator actually chose. _inject_configured_oauth_token() already resolves the configured-token half, so the check has somewhere natural to live.

Test coverage

The new test is a good positive control. It needs its negative twin, and this repo asks for that pairing explicitly (CLAUDE.md: "a negative assertion needs a positive control", and the same in reverse): a case where ANTHROPIC_API_KEY is the sole credential and therefore survives. Without it, a future refactor that strips unconditionally again passes the suite.

test_call_haiku_keeps_oauth_token is the pattern to mirror.

Repo mechanics

  • A changelog fragment is a merge gate here. Add changelog.d/<issue>.fixed.md -- one line, user-facing. The oss changelog check fails without it.
  • No linked issue. A Closes #N line binds the PR to an issue; a bare #N does not. Happy for you to file one describing the symptom, or I can.
  • CI on this PR was waiting on first-time-contributor approval; I've approved it, so the twelve legs will report shortly.

Separately, and not your problem to fix

Your logs showed the real cause in memory-*.log while hook-errors.log carried only the exit code. That propagation gap is a bug of ours independent of this change, and it is why this took days instead of minutes to find -- filed as #694 with your trace as the evidence. Thanks for surfacing it.

…hen it is the only credential

@Mega-Therion diagnosed this and the strip itself is theirs; this commit makes
it conditional, which is what the review asked for.

An unconditional strip does not remove the reported outage, it relocates it:
authenticating the CLI with ANTHROPIC_API_KEY alone is normal and documented,
and for those installs dropping the key leaves the nested claude -p with no
credential at all -- every background save failing silently, the same shape
that took the reporter days to trace.

So the key is now dropped only when another credential is visible
(CLAUDE_CODE_OAUTH_TOKEN, a configured OAuth token, or a login at
~/.claude/.credentials.json) and kept when it is the only one there is. A
login held in an OS keychain is invisible to this process, so auto keeps the
key for those operators -- todays behaviour, not a new failure -- and the new
haiku.anthropic_api_key config key (auto|keep|strip) is how they overrule it.
An unrecognised value falls back to auto and says so, rather than grading
silently as one of the two behaviours.

A failure that looks like a credential failure now names the variable and the
config key in the RuntimeError, so it reaches hook-errors.log where the
operator is already looking rather than the daily log alone (#694). The marker
list is deliberately narrow: a hint on every failure would point unrelated
outages at an innocent variable.

Tests pair every strip case with its keep twin -- an unconditional strip and
an unconditional keep each fail here -- and the failure hint has both a
negative control (no key set) and a wrong-cause control (key set, prompt-length
failure).

Co-Authored-By: Max <noreply>
@fdaviddpt

Copy link
Copy Markdown
Contributor

I've finished this one, in #704. Your commit is the first of the two there, unchanged and under your name — #704 adds the condition my review asked for rather than replacing your work, and the issue it closes (#703) is filed with your trace as the evidence.

Two things worth saying plainly.

Why I did not push to your branch. That was my first move — maintainer_can_modify is set on this PR, so it was available — and my tooling declined to write to someone else's fork. Rather than ask you to wait on that, I put the same two commits on a branch here. If you would rather carry it yourself, say so and I will close #704 and hand you the diff; the work is genuinely yours to finish if you want it.

What changed from your patch. The strip is now conditional. ANTHROPIC_API_KEY is dropped when another credential is visible — CLAUDE_CODE_OAUTH_TOKEN, a configured OAuth token, or a login at ~/.claude/.credentials.json — and kept when it is the only credential on the host, because for an operator who authenticates the CLI with that key alone a strip leaves the child with nothing and every background save fails in exactly the shape you spent days tracing. A claude.ai login in the macOS Keychain is invisible to this process, so there is a haiku.anthropic_api_key config key (auto/keep/strip) for the operators the automatic rule cannot see. And a credential-shaped failure now names the variable in the error itself, which is the part of your report I kept coming back to: the mechanism was findable, but only by someone willing to read the child's stderr in a daily log.

The negative twin — the key surviving when it is the only credential — is the test that fails against the original patch, and it is there so a future refactor cannot quietly strip again.

Closing this in favour of #704. Thank you for the report; the trace in it is what made the whole thing tractable, and the framing in your description (interactive sessions fine, background summarizer dead) is what pointed at the credential order in the first place.

[AI-generated]

CodeQL was right: the warning quoted the rejected config value, and this keys
NAME invites an operator to paste an actual API key into it. A typo would then
have written that credential to the daily log in clear text -- a leaked secret
on disk as the punishment for a misspelling.

The warning now names the length and type, the legal values and the fallback,
and says explicitly that the value is withheld and why. The test asserts the
absence (a pasted key-shaped value must not appear) and gains its positive
control: a recognised value warns about nothing, so warns-on-bad-value cannot
silently become warns-on-everything.

Co-Authored-By: Max <noreply>
@fdaviddpt

Copy link
Copy Markdown
Contributor

Correction to my comment above: the push to this branch went through on a retry, so the work is here, not in #704 — I've closed that one as a duplicate. Your branch now carries three commits: yours, the conditional-strip rework, and one more described below. Nothing of yours was rewritten; both of mine sit on top of 040fa8b.

The third commit is worth naming, because CodeQL caught it on the second push and it was right to. My warning for an unrecognised haiku.anthropic_api_key value quoted the value back — and that key's name invites someone to paste an actual API key into the field. A typo would then have written a live credential to the daily log in clear text. It now reports the length and type, the legal values and the fallback, and says the value is withheld and why. The test asserts the absence, with a positive control (a recognised value warns about nothing) so "warns on a bad value" cannot quietly become "warns on everything".

I also added Closes #703 to the description and a short note marking that edit — your text above is untouched.

CI is running on the branch now. Once it is green this is ready to merge as yours.

[AI-generated]

@fdaviddpt

Copy link
Copy Markdown
Contributor

Merging this — the change my earlier review asked for is in the branch, so treat that CHANGES_REQUESTED as answered rather than standing. (I could not clear the review itself: approving a pull request is an action my tooling holds back from me, which seems right. The maintainer's decision to merge is on the record here instead.)

State at the merge, named rather than summarised:

  • 15 legs passed, 0 failed on c90b49b.
  • One CodeQL check run is neutral, not green: "1 configuration not found: /language:actions". That is code scanning declining to compute the PR-vs-main alert diff for the actions configuration — not a failed analysis. Both analyses on this sha (Analyze (python), Analyze (actions)) concluded success, and this branch touches no workflow files, so there is no actions-language alert it could have introduced.
  • The base is 7 commits behind main. The green tally is therefore evidence about this branch's merge-base, not about the tree that lands. Merging on that basis deliberately; main's own run is what settles it, and anything that surfaces there is a follow-up rather than a reason to hold this.
  • The first CI attempt on this branch produced two runs with zero jobs and a failure conclusion — nothing ran. A re-run produced the full matrix and passed. Transient, GitHub-side.

Thank you again for the report, the trace, and the patch. Landing as yours.

[AI-generated]

@fdaviddpt
fdaviddpt merged commit 7014551 into Digital-Process-Tools:main Sep 16, 2026
29 checks passed
fdaviddpt added a commit that referenced this pull request Sep 16, 2026
…u failure detail to hook-errors.log (#714)

* fix(#691,#694): stop sorting every transcript to read one, route Haiku failure detail to hook-errors.log

#691: previous_transcript() (and its no-CURRENT_SESSION_ID sibling)
forked `ls -t` over the whole session directory on every start just to read
one line off the top, throwing the sort away -- the only per-session cost
that grows with how long a project has been used (0.104s at 500 past
transcripts, 0.41s at 2000, per #660's own diagnostic). Both call sites are
now a single pass over the glob that compares mtimes with bash's own `-nt`
test builtin, so the cost no longer scales with transcript count at all.

#694: a failed background save reported only `exited 1` in hook-errors.log
while the nested Haiku CLI's own failure detail -- already computed and
already length-capped -- went only to the daily narrative log nobody reads
while diagnosing a live outage (#693: 12 occurrences over several days
before anyone found it in the second file). save-session.sh's two internal
failure sites (a failed call, an empty response) now call report_error()
instead of log() alone, so the same detail reaches the file /remember:doctor
tails and a reporter is asked to paste. Propagation only, no new diagnosis.

New tests for both, each with a real red-before-fix run; guard set checked
via scripts/lane_setup.py (no cross-cutting guards apply in this repo).
Changelog fragments for both issues, verified against .oss/assemble_changelog.py --check.
A new module-level win32 skip gets its docs/windows-skip-triage.md row in
this same commit, per CLAUDE.md's own convention.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(#691): normalize path separators before comparing bash and pathlib output

Self-review finding (oss:auditor) on e0357f6: three assertions in
tests/test_previous_transcript_no_sort_691.py compared bash's own glob
output (always joined with a literal forward slash, verbatim on whatever
$dir it was handed) against Python's str(Path) (all-backslash on
Windows), so a passing local run would still fail on windows-latest CI --
a correct fix reported as broken by its own test. Folds every occurrence
of the platform separator byte to a forward slash on both sides before
comparing. Re-ran the file after the fix: all 5 tests still pass.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An ambient ANTHROPIC_API_KEY out-ranks the operator's login for the nested summarizer, and an exhausted one fails every background save silently

2 participants