Ray's Knowledge Base
Unlock

CLI tests run from inside Claude Code inherit CLAUDE_CODE_SESSION_ID and take the outer session

PitfallVerified 29 Sep 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

A CLI test sets RKB_SESSION=s1 on the command it runs, but the tool records the use under another session id, so a check that counts records for s1 finds none (irrelevant: 0 where 1 was expected). The same test can pass in a plain terminal or CI.

Cause#

The test harness copies the developer's environment into each child process. Inside a Claude Code session that environment holds CLAUDE_CODE_SESSION_ID (and inside pi, PI_SESSION_ID), and the tool reads those before RKB_SESSION. So the agent's own session id leaks into every test that does not clear it.

Fix#

Clear every harness session variable in the one place the tests build their commands, next to the other env_remove calls: .env_remove("CLAUDE_CODE_SESSION_ID").env_remove("PI_SESSION_ID").env_remove("RKB_SESSION"). Then set the one a test needs, or pass the session as a flag (--session s1).

Evidence#

rkb, 2026-09-29: in hook_full_session, rkb used 1a00000012 --irrelevant run with RKB_SESSION=s1 gave "tool-failed":{"injected":1,"helped":1,"irrelevant":0} from rkb review --signals, because usage::env_session() reads CLAUDE_CODE_SESSION_ID first. With --session s1 it gave irrelevant: 1. Adding the three env_remove calls to Env::cmd in crates/rkb/tests/cli.rs let the burst-window tests control the session with RKB_SESSION.

Also found by searching

  • RKB_SESSION=s1 rkb used ... --irrelevant then rkb review --signals -> "irrelevant":0 expected 1
  • my CLI integration test passes in CI and a plain terminal but fails when run from inside a Claude Code session
  • how do I keep the agent's session id environment variable from leaking into spawned CLI test processes?
  • cargo test from Claude Code picks up CLAUDE_CODE_SESSION_ID or PI_SESSION_ID over my own session env var
  • cli test sets RKB_SESSION=s1 but record is under another session, assertion irrelevant: 0 expected 1
  • integration test passes in CI and terminal but fails when run by an agent inside Claude Code
  • why does my test pick up the wrong session id when run from a Claude Code session?
  • env var CLAUDE_CODE_SESSION_ID leaks into cargo test child processes, how to clear in Command