Skip to content

fix(recall): read each agent's session variable so recall quality joins its session - #887

Merged
jeff-r2026 merged 4 commits into
Tencent:mainfrom
SaulMoro:fix/883-recall-session-id
Sep 29, 2026
Merged

jeff-r2026 merged 4 commits into
Tencent:mainfrom
SaulMoro:fix/883-recall-session-id

Conversation

@SaulMoro

@SaulMoro SaulMoro commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

teamai recall recorded recall quality under an id that no hook ever uses, so contribute-check's knowledge-gap bonus never applied (#883, part 1). Recall now reads the agent's own session variable, which equals the session_id its hooks receive. Inside a Pi or OpenCode shell it reads none of them, because those bridges send hooks no session id and any variable they see is inherited from an outer agent. When one agent runs inside another, the inner agent's session wins.

 teamai recall "<query>"                       run from the agent's shell, no hook payload
-  recordRecallQuality(deriveSessionId({}))    payload → CLAUDE_SESSION_ID (not set by Claude Code) → pid-<ppid>, new per shell
+  recordRecallQuality(await agentSessionIdFromEnv() ?? deriveSessionId({}))
+    PI_SESSION_ID or OPENCODE set → undefined        (bridge agent: main's fallback)
+    set = CLAUDE_CODE_SESSION_ID, CODEX_SESSION_ID, CODEBUDDY_SESSION_ID, COPILOT_AGENT_SESSION_ID,
+          CURSOR_CONVERSATION_ID, CLAUDE_SESSION_ID   (distinct, non-empty)
+    one id  → it
+    several → the one whose current run started last (latest session_start, else first event), else the first in that order
 Stop hook → contribute-check
   readRecallQuality(<hook session_id>)        now finds what recall wrote
src/utils/session-id.ts    + AGENT_SESSION_ENV, BRIDGE_AGENT_ENV, agentSessionIdFromEnv(); deriveSessionId unchanged
src/recall.ts              records under the agent session
src/contribute.ts          marks the agent session contributed (was a no-op outside CodeBuddy)
src/save-session.ts        `session save` defaults to the agent session, else the most recent
src/index.ts + commands.md + docs/usage-guide{,.zh-CN}.md   help and docs for `session save`
vitest setup               clears the agent variables and bridge markers for every test file

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature causing existing behavior to change)
  • Documentation only
  • Refactor / internal cleanup

Test Plan

  • npx tsc --noEmit passes
  • npm run lint passes
  • npx vitest run passes (run as env -u CLAUDE_CONFIG_DIR npx vitest run until fix(tests): prevent model tests from overwriting Claude config (P1) #890 lands): 337 files, 5270 passed, 1 skipped
  • env -u CLAUDE_CONFIG_DIR npm run test:e2e passes: 59 files passed, 3 skipped; 368 tests passed, 26 skipped
  • Added/updated tests for the change

Regression test, driving recall() (recall-scope-isolation.test.ts):

records recall quality under the agent session, where contribute-check reads it for the Stop hook (#883)
  CLAUDE_CODE_SESSION_ID = <hook session_id>
  recall(<query with no match>)
  expect readRecallQuality(<hook session_id>) → { hitCount: 0, missCount: 1 }
  expect applyPhase2Adjustments(0, <hook session_id>).isKnowledgeGap → true

before (src/recall.ts from main):  × AssertionError: expected null to deeply equal ObjectContaining{…}
after:                             ✓

session-id.test.ts pins the variable order, each variable, that PI_SESSION_ID or OPENCODE returns undefined even with an inherited variable, the nested case (including when the outer session fires last, and a resumed inner session whose first event predates the outer one), CodeBuddy's own variable before its CLAUDE_SESSION_ID alias, empty values, and that a hook with no session_id keeps its pid-<ppid>-<cwd> fallback even when it inherits CLAUDE_CODE_SESSION_ID.

Real CLI (npm run build, sandbox HOME with one team doc, recall --dry-run "session"):

before, main 5fb316c7, run twice from Claude Code (CLAUDE_CODE_SESSION_ID set)
$ ls ~/.teamai/sessions
pid-53099-recall-cache.json
pid-61883-recall-cache.json                        one orphan per shell

after, this branch
$ recall … (Claude Code session)                                → 5624be7c-ac77-4942-b1d3-60a701bd38b3-recall-cache.json
$ env -u CLAUDE_CODE_SESSION_ID CODEX_SESSION_ID=7f3c… recall …  → 7f3c2a10-5b6e-4d8f-9a01-2c3d4e5f6a7b-recall-cache.json
$ env -u CLAUDE_CODE_SESSION_ID recall …   (no agent variable)   → pid-46134-recall-cache.json   (fallback unchanged)

contribute-edge-modes.test.ts checks that contribute() marks the agent's session contributed, and does not mark an outer Claude session from a Pi shell. save-session.test.ts checks that session save uses the agent's session, falls back to the most recent session, and uses the most recent session from a Pi shell started by Claude Code. recall-scope-isolation.test.ts checks that recall from that Pi shell writes nothing under the Claude session.

Nested agents, real CLI (npm run build, temp HOME, CLAUDE_CONFIG_DIR and all agent variables unset), session save --dry-run:

events: Claude Code 10:00, then Pi (pid-4242-/tmp) 10:02-10:03
CLAUDE_CODE_SESSION_ID=outer-claude-0000 PI_SESSION_ID=pi-own-id
  → Would record session pid-4242 (0 tools, …)        Pi shell: most recent session, not the outer Claude one
CLAUDE_CODE_SESSION_ID=outer-claude-0000 OPENCODE=1
  → Would record session pid-4242 (0 tools, …)        same for OpenCode
CLAUDE_CODE_SESSION_ID=outer-claude-0000
  → Would record session outer-cl (1 tools, …)        single variable unchanged

events: Claude Code 10:00, Codex 10:02-10:03, Claude Code again 10:05
CLAUDE_CODE_SESSION_ID=outer-claude-0000 CODEX_SESSION_ID=inner-codex-1111
  → Would record session inner-co (0 tools, …)        inner agent wins though the outer fired last

events: Claude session_start yesterday 09:00; Codex session_start today 10:00;
        Claude session_start (resume) 10:05; Codex again 10:07
CODEX_SESSION_ID=outer-codex-3333 CLAUDE_CODE_SESSION_ID=inner-claude-2222
  → Would record session inner-cl (1 tools, …)        resumed inner agent wins
CODEX_SESSION_ID=outer-codex-3333
  → Would record session outer-co (1 tools, …)        single variable unchanged

Before the fix, these cases fail. Against main: the order list still contained PI_SESSION_ID, PI_SESSION_ID alone returned pi-session, and the nested case returned outer-claude. Against 4b3f325: CLAUDE_CODE_SESSION_ID with PI_SESSION_ID or OPENCODE returned outer-claude, as did the nested case when the outer session fired last. Against fb97e0d: the resumed inner Claude session returned outer-codex. From a Pi shell, recall wrote Claude's recall cache, contribute marked Claude's session contributed, and session save recorded the Claude session.

Related Issues

Refs #883 (part 1). Part 2, adoption, is proposed in #884.

Notes for Reviewers

Door: two-way. It adds no stored format or migration: a revert only renames future cache files back to pid ids.

Blast Radius: small.

  • Hooks don't change: deriveSessionId is the same as on main. Putting the agent variables there would have moved the OpenCode, Pi and OMP bridges, which send no session_id, onto an outer agent's session when started from its shell. A test pins that.
  • session save inside an agent shell now records that agent's session instead of the most recent one, which is what its help already promised with $CLAUDE_SESSION_ID. If hooks never recorded that session it prints No events found for session <id>.; --session-id still overrides.
  • contribute now marks the current session contributed on Claude Code, Codex and the others, so contribute-check stops hinting a session that already contributed.
  • Nested agents: a shell also sees the outer agent's variables. Seen live: codex exec started from a Claude Code shell recorded under the Claude session. When several different ids are set, the one whose current run started last wins, because the inner agent always starts after the outer one. This holds even when the outer agent keeps firing hooks, for example with a background codex exec or parallel subagents. A run starts at the session's latest session_start event, or at its first event if it has none, so a resumed session (claude --resume of yesterday's session from a new Codex session) counts from its resume. teamai registers SessionStart with matcher * (builtin-hooks.ts), so every SessionStart call records session_start. Claude Code and Codex fire SessionStart on startup, resume, clear and compact (Codex: codex-rs/hooks/src/events/session_start.rs and the hooks docs). I did not check CodeBuddy, Copilot or Cursor on resume; without a resume start event they fall back to the first event, as in fb97e0d. Limit: SessionStart also fires on compaction, so an outer agent that compacts while the inner one runs (possible only with a background or parallel call) counts as started later and wins. Stored events do not record source, so this cannot be told apart without a format change. events.jsonl is read only when more than one id is set. If the inner agent has no hooks installed, its session has no events and the outer one is picked; no hook would read the inner id anyway. Proposal: attribute recall and adoption to the agent session in every agent #884 still covers adoption through PostToolUse.
  • Pi and OpenCode (bridge agents): their bridges send hooks no session id, so hooks record under pid-<ppid>-<cwd>. Any id in their shell is inherited from an outer agent. Pi's bash tool sets PI_SESSION_ID (on by default) and OpenCode sets OPENCODE=1. When either is set, agentSessionIdFromEnv returns undefined and each command falls back as on main: recall uses deriveSessionId({}), contribute marks nothing, and session save uses the most recent session. The trade-off is reverse nesting: Claude Code or Codex started from a Pi or OpenCode shell also falls back, as on main, so it does not join its own hook session. OMP exports no marker I could find, so OMP started from another agent's shell still sees the outer id. Forwarding the bridge's own session id in hook payloads would fix both, and is a separate change.
  • Pre-existing and unchanged: deriveSessionId's CLAUDE_SESSION_ID step, used by hooks and by recall's fallback, has the same inherited-id problem when a bridge agent runs under CodeBuddy, which sets that alias.
  • Only the Claude Code path ran in a real session. Codex, CodeBuddy, Copilot and Cursor setting these variables, and the Pi and OpenCode markers, come from their docs and source; the Codex path ran with the variable set by hand.
  • The vitest setup file exists because in an agent shell 26 tests read the host's session id, and one wrote {"contributed": true} into the real ~/.teamai.
  • skill-commands-exist.test.ts failed once under full parallel load (command.commands undefined), then passed alone and in two full runs. It is unrelated to this change.

…ns its session

`teamai recall` recorded recall quality under deriveSessionId({}), which
falls back from the payload to CLAUDE_SESSION_ID. Claude Code does not set
that variable (it sets CLAUDE_CODE_SESSION_ID), so recall used pid-<ppid>, a
new id per shell, and contribute-check never found it under the hook's
session_id: the knowledge-gap bonus never applied.

agentSessionIdFromEnv reads each agent's session variable (Claude Code,
Codex, CodeBuddy, Copilot CLI, Cursor, Pi, then CLAUDE_SESSION_ID). recall,
contribute and session save use it; they are CLI commands with no hook
payload. deriveSessionId is unchanged, so hooks keep their ids: a bridge
that sends no session_id (OpenCode, Pi, OMP) would otherwise inherit the
outer agent's variable when started from another agent's shell.

A vitest setup file clears those variables, so the suite does not depend on
the agent shell it runs in, and tests that do not isolate HOME cannot write
the live session's state into the real ~/.teamai.

Refs Tencent#883 (part 1)
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] PI_SESSION_ID cannot join Pi’s hook session. agentSessionIdFromEnv() selects it for recall, contribute, and session save, but the generated Pi bridge sends only cwd/tool fields, so hooks remain stored under the pid-<ppid>-<cwd> fallback. Consequently recall quality and contributed state are invisible to contribute-check, and session save can fail with “No events found.” Forward the Pi session ID in hook payloads or remove this variable from the list. src/utils/session-id.ts:24
  • [P2 non-blocking] The fixed precedence chooses an outer agent’s ID in nested sessions. For example, Codex launched from Claude inherits CLAUDE_CODE_SESSION_ID while setting CODEX_SESSION_ID; line 19 wins, although Codex hooks use the Codex session. Recall/contribution state is then attached to the wrong session. src/utils/session-id.ts:19

The PR description includes a representative real-CLI verification, so its testing record is sufficient.

Pi's hook bridge sends no session id, so Pi hooks record under the
pid-<ppid>-<cwd> fallback. Reading PI_SESSION_ID made recall, contribute
and session save use an id with no events: contribute-check never saw the
recall quality or contributed state, and session save reported "No events
found". It is no longer read.

An agent started from another agent's shell inherits the outer agent's
variable next to its own (Codex inside Claude Code has both
CLAUDE_CODE_SESSION_ID and CODEX_SESSION_ID), and the fixed order picked
the outer one. When several distinct ids are set, agentSessionIdFromEnv
now picks the one whose session has the latest hook event, falling back to
the variable order when none has events. The common single-variable case
reads no events.

Refs Tencent#883 (part 1)
@github-actions

Copy link
Copy Markdown

Review Result

  • No new findings in the current diff.
  • Prior [P1 blocking] Pi session issue is resolved: PI_SESSION_ID is excluded.
  • Prior [P2 non-blocking] nested-agent precedence issue is resolved using the latest matching hook event.
  • The PR description includes representative real-CLI verification, so the testing record is sufficient.

…rted session

Pi and OpenCode export none of AGENT_SESSION_ENV, so started from a Claude
Code or Codex shell they saw only the outer agent's inherited id.
contribute then marked the outer session contributed, which suppressed its
contribute-check hint; recall skewed the outer recall cache; and session
save recorded the outer session. When a bridge marker is set (PI_SESSION_ID,
set by Pi's bash tool, or OPENCODE, set by OpenCode), agentSessionIdFromEnv
returns undefined, so each caller's fallback from main applies. An agent
started from a Pi or OpenCode shell falls back too, as on main. OMP exports
no marker.

With several ids set, the id whose session started last now wins, instead
of the id with the latest event. The inner agent always starts after the
outer one, and a background `codex exec` or parallel subagents keep the
outer session firing hooks.

Tests now cover contribute marking the agent session, session save using
the agent session and falling back to the most recent, and the nested Pi
case through recall, contribute and session save.

Refs Tencent#883 (part 1)
@github-actions

Copy link
Copy Markdown

Findings

  • [P2 non-blocking] Resumed inner sessions can still resolve to the outer agent. The selection compares each ID’s earliest historical event; if a new Codex session launches claude --resume for a Claude session created yesterday, the outer Codex ID appears newer and receives recall/contribution state instead of the active Claude ID. Use the latest current-run/session-start boundary rather than the session’s first-ever event. src/utils/session-id.ts:60

Review Status

  • Both findings from earlier passes are resolved in the current diff.
  • The PR description includes representative real-CLI verification, so its testing record is sufficient.

…ed one wins

agentSessionIdFromEnv compared each id's first event. `claude --resume` of
yesterday's session, run from a new Codex session, then looked older than
Codex, and recall and contribute state went to the outer Codex session.

Each id now counts from its latest session_start event, falling back to its
first event. Claude Code and Codex fire SessionStart on resume, and teamai
registers it with matcher '*', so every resume records one.

Refs Tencent#883 (part 1)
@github-actions

Copy link
Copy Markdown

Findings

  • [P3 nit] Bridge markers mask a nested agent’s valid ID. If Pi launches Codex, the child inherits PI_SESSION_ID and sets CODEX_SESSION_ID, but the early return selects no agent session; recall/contribution state therefore cannot join Codex’s hook session. Check for a matching agent ID before treating the process as the bridge itself. src/utils/session-id.ts:55
  • [P3 nit] Every latest session_start is treated as a new run boundary. During a background/parallel nested session, an outer agent’s later compact or clear event makes the outer ID win, so subsequent inner-agent recall, contribution, or session-save state is attached to the wrong session. src/utils/session-id.ts:68

Review Status

  • Prior PI_SESSION_ID and resumed-session findings are resolved.
  • The PR description includes representative real-CLI verification, so its testing record is sufficient.

@jeff-r2026
jeff-r2026 merged commit 11657bc into Tencent:main Sep 29, 2026
13 checks passed
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
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.

2 participants