agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

fix: remove premature session/end call from stop hook

Open LeonemFu opened this issue 6 months ago • 2 comments

Summary

Removes the premature /agentmemory/session/end call from the stop.mjs hook script that was causing Claude Code sessions to be marked completed mid-conversation.

Problem

src/hooks/stop.ts fired /agentmemory/session/end on every agentStop event. In Claude Code CLI, agentStop fires after every assistant turn — not just at session exit — because Claude Code has a dedicated sessionEnd hook for true exit. This caused:

  • Sessions marked completed while the user was still actively chatting.
  • session-end.mjs lifecycle events (slot-reflect, graph-extract, consolidation) firing prematurely or against an already-completed session.
  • Log noise from event::session::stopped trigger failed.

Root Cause

The /session/end call was intentionally added in commit 35512414 (#579) as a workaround for Codex, which does not fire a separate SessionEnd event. At the time it was assumed to be "harmless idempotent" for Claude Code, but that assumption was incorrect — Claude Code fires agentStop after every assistant turn.

Why not guard by agent type?

We cannot reliably detect Codex from the hook payload (no confirmed entrypoint value or other identifier). A black-list guard (entrypoint !== "cli") would still incorrectly fire session/end for Hermes and other agents that also lack a dedicated SessionEnd hook. A white-list guard is not possible without a known Codex identifier.

Changes

  • src/hooks/stop.ts: Commented out the session/end fetch with a TODO(codex-session-end) explaining the regression.
  • test/copilot-plugin.test.ts: Added a test verifying stop.mjs calls /summarize but not /session/end.
  • plugin/scripts/stop.mjs: Rebuilt from source.

Verification

npm run build
npx vitest run test/copilot-plugin.test.ts

All 17 tests in copilot-plugin.test.ts pass, including the new stop-hook behavior test.

Regression Note

Codex sessions will no longer be auto-closed on the Stop hook. This is a known regression that can be reverted once a reliable Codex identifier is available in the hook payload.

Related

Fixes #745

  • Commit 35512414 — originally added session/end to stop.mjs as a Codex workaround (#579, fixes #493).

Summary by CodeRabbit

  • Bug Fixes

    • Fixed premature session termination that interrupted agent workflows. Sessions now maintain proper continuity without unexpected interruptions from stop events.
    • Improved shutdown process with enhanced timeout handling for better reliability during graceful session closure.
  • Tests

    • Added comprehensive test coverage for session shutdown behavior.

LeonemFu avatar May 31 '26 12:05 LeonemFu

@LeonemFu is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar May 31 '26 12:05 vercel[bot]

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9ee1e897-a30d-47f5-9799-4b6bfae0c5a1

📥 Commits

Reviewing files that changed from the base of the PR and between fd9e3bd42d6208a33f0ee9de1442fdbb60eab106 and a91b93cfe84f927c27890d08aed4daa9a30e63ee.

📒 Files selected for processing (3)
  • plugin/scripts/stop.mjs
  • src/hooks/stop.ts
  • test/copilot-plugin.test.ts
💤 Files with no reviewable changes (1)
  • plugin/scripts/stop.mjs

📝 Walkthrough

Walkthrough

The agentStop hook is refactored to call only the /agentmemory/summarize endpoint instead of both summarize and session/end, preventing Claude Code from marking sessions as completed mid-conversation. The timeout for summarize is increased from 5 seconds to 120 seconds. A test validates the new behavior.

Changes

Stop Hook Endpoint Refactoring

Layer / File(s) Summary
Stop hook endpoint change
src/hooks/stop.ts, plugin/scripts/stop.mjs
The source hook removes the active fetch call to /agentmemory/session/end, replacing it with TODO comments and a commented-out version. The generated script transitions from posting to session/end (5s timeout) to posting to summarize (120s timeout), while continuing to send { sessionId } and ignore request failures before scheduling delayed exit.
Stop hook test validation
test/copilot-plugin.test.ts
A new test executes scripts/stop.mjs, asserts stdout is empty, and verifies that /agentmemory/summarize is called while /agentmemory/session/end is not called.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • rohitg00/agentmemory#579: Originally added the /agentmemory/session/end call to the stop hook as a Codex workaround; this PR removes it for Claude Code compatibility.
  • rohitg00/agentmemory#698: Modifies the api::session::end behavior and downstream graph extraction that fires when the session-end event is triggered; removing the premature /session/end call from stop.mjs affects this endpoint's invocation pattern.

Poem

🐰 A stop hook hops with grace, No more sessions ended mid-race, Summarize alone now thrives, Claude Code's conversations stay alive, One endpoint, clean and true— The session ends when users do!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: removing the premature /agentmemory/session/end call from the stop hook that was causing Claude Code sessions to be marked as completed mid-conversation.
Linked Issues check ✅ Passed The PR addresses the primary objective from #745 by removing the premature session/end call from stop hooks, though it implements Option C (complete removal) rather than Option A (agent-type guard), accepting a temporary Codex regression.
Out of Scope Changes check ✅ Passed All changes are directly within scope: stop.ts removes the session/end call with TODO comments, stop.mjs reflects the rebuilt output, and the new test verifies the hook no longer calls /session/end.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 31 '26 12:05 coderabbitai[bot]