Skip to content

feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs - #524

Merged
amiddavid merged 5 commits into
mainfrom
lc-default/public
Oct 14, 2026
Merged

amiddavid merged 5 commits into
mainfrom
lc-default/public

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Stacked on #520. Makes the client lifecycle signals (session end: /exit, Ctrl-C twice, Ctrl-D, closing the terminal, /clear, logout; compaction; resume) part of the default cache strategy whenever the keep-alive runs.

Changes

  • Proxy: /signal and its effects are on unless CONTEXT_GURU_CLIENT_SIGNALS=off or the keep-alive kill switch (CONTEXT_GURU_KEEPALIVE=off). The route also accepts a raw Claude Code / Codex hook payload: only session_id, hook_event_name and reason/source/notification_type are read, the rest is discarded unread (body cap 4 KiB). A held entry remembers the client's session-id header (Codex), so a Codex signal matches a session the proxy keys by content hash. Session identity is unchanged.
  • Claude Code plugin: client_signals defaults to auto: send to the plugin's loopback proxy, or to a hosted service (recognised by x-context-guru-token in ANTHROPIC_CUSTOM_HEADERS, now the header used). on = any base URL, off = never. The local proxy needs no credential (subscription logins export none).
  • Codex plugin: SessionEnd and SessionStart (compact|resume|clear, async) hooks run codex_plugin.py signal, which posts the closed fields to the local proxy. Codex runs plugin hooks only after the user trusts them in /hooks.
  • Hosted setup page: the settings snippet gains SessionEnd and SessionStart compact hooks (one curl --data-binary @- to <base>/signal).
  • Deploy: deploy/service/context-guru.service states CONTEXT_GURU_CLIENT_SIGNALS=on. This PR changes no running deployment.
  • Docs: client lifecycle signals section in docs/how-to/cache-keepalive.md; Codex README.

Tests

  • go test ./proxy ./session ./apply ./context-guru-plugin and the Codex plugin tests pass.
  • New: the default follows the keep-alive; the Codex header alias retires and blocks re-arm; raw-payload and oversize validation; the hosted snippet authenticates by token header; plugin auto sends to loopback without a token and to a remote URL only with the hosted token header.

Live check

Real Claude Code 2.1.296 and Codex 0.162.1 sessions through an experimental proxy built from this branch:

  • Claude Code: /exit, Ctrl-C twice, Ctrl-D, closing the terminal, /clear and /compact each reached the proxy and released the held entry; no pings after the exit. With the hook off, the same exit kept pinging. claude --resume kept the session id, re-armed the hold, and its first request read the full prefix from the provider cache.
  • Codex: /exit, /quit, Ctrl-C twice and Ctrl-D send SessionEnd and release the entry. Closing the terminal sends nothing (a Codex limitation). codex resume and /compact are delivered. Untrusted plugin hooks do not run. Without the session-id alias, a Codex SessionEnd matched nothing.
  • Hook wall time is about 50 ms (plugin) and 90 ms (Codex) per event, and the same when the proxy is down.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: APPROVE at f6f13f5. (Posted as a comment: GitHub does not let the author account approve.) Stacked on #520.

Verified:

  • Same code as the private review. The two commits are a straight cherry-pick of the private-mirror change that was reviewed and approved there. The patch is identical line for line. The only differences are hunk offsets, plus one context comment from the campaign code that #520 does not carry.
  • Checks. gofmt and go vet are clean on proxy, dash and context-guru-plugin. go test ./proxy and ./dash pass in full, the plugin Signal tests pass, and the 35 Codex plugin tests pass (pytest).
  • Attribution. Both commits are by Osher-Elhadad and signed off, with no AI attribution.
  • Publication. The PR body, commit messages, docs and comments carry no research figures, dollar amounts, internal paths, hosts or account/session identifiers. The "Live check" section describes product behaviour only (which exits deliver, hook wall time), which is fine for a public PR. The only path in the diff is the fake /home/u/... in a test.

Recommended before the hosted setup page change is deployed (not blocking the merge; these were raised on the private review and are unchanged here):

  1. The token is in curl's argv (dash/ui/app.js claudeSettings: -H "$ANTHROPIC_CUSTOM_HEADERS"). /proc/<pid>/cmdline is readable by other local users for the life of each send, and this is the long-lived account token. -K - cannot be used because stdin carries the payload. curl >= 8.3 can take it from the environment instead: --variable %ANTHROPIC_CUSTOM_HEADERS --expand-header '{{ANTHROPIC_CUSTOM_HEADERS}}'. Alternatively, document the exposure next to the snippet.
  2. The docs say "content-free event", but the hosted snippet posts Claude Code's raw hook payload. That payload includes cwd and transcript_path. The service reads only the three closed fields, but those values still leave the machine. Say so in docs/how-to/cache-keepalive.md and in the setup page hint. The plugin's signal.sh does send only the closed fields, so the plugin wording is right.
  3. An unknown SessionEnd reason gets a 400. If a later Claude Code version adds a reason, that exit path silently stops retiring. Mapping an unrecognised SessionEnd reason to other keeps the closed set and the behaviour.
  4. The extra e.tenant == tenantID guard on the alias match is untested. Removing it passes every test, although cross-tenant retire is already impossible because both keys are tenant-prefixed. A one-line cross-tenant case would pin it.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review: APPROVE at 5a46885. (Posted as a comment: GitHub does not let the author account approve.)

All four notes from the earlier review are fixed, and I checked each one:

  1. The token is out of argv. I extracted the hook command from claudeSettings (exactly as the settings JSON carries it) and ran it against a slow local listener while scanning every /proc/*/cmdline. No sh, sed or curl process carried the token: printf is a builtin, sed reads the header on stdin and curl gets it as -K - config. A two-line ANTHROPIC_CUSTOM_HEADERS delivered both headers. It works under sh and bash --posix.
  2. Only three fields leave the machine. The body is exactly session_id, hook_event_name and reason/source (the unused one is empty). That holds for a pretty-printed payload, and cwd and transcript_path never appear. I tried injection: x"; rm -rf / comes out as an empty id (refused server-side), and a cwd containing ","reason":"logout or "session_id": "evil" is JSON-escaped, so it cannot match. Command substitution output is limited to [A-Za-z0-9._:-], so nothing can break out of the --data JSON.
  3. Unknown reasons. An unknown SessionEnd reason now reads as other and returns 204, and an unknown SessionStart source is still 400. With the mapping disabled, TestSignalValidation fails.
  4. The alias tenant guard is tested. With e.tenant == tenantID removed from the alias match, TestCodexSessionEndMatchesTheSessionIDHeader fails ("another tenant's signal retired this tenant's aliased entry").

Also: gofmt and go vet are clean on proxy, dash and context-guru-plugin, and the proxy signal/lifecycle tests and plugin Signal tests pass. Both commits are by Osher-Elhadad and signed off, with no AI attribution. The PR text and docs carry no numbers.

Nit (non-blocking): sed 's/.*"KEY" *: *"…".*/' is greedy, so the LAST occurrence of a key wins. A payload with a nested object carrying its own session_id would send that inner value. Claude Code's SessionEnd/SessionStart payloads are flat today, so this is only worth a comment, or anchoring on the first occurrence.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Verdict

Request changes (one defect). A compact signal retires the cache of idle subagents. #524 turns this on by default for every keep-alive user. The purego CI failure is not caused by this PR. The merge conflict with #525 is small.

Findings

  1. Compact retires every thread of the session, not only the compacted one. proxy/clientsignal.go:190 calls retireSessionStartedBefore. The loop at proxy/keepalive.go:963 matches the main key and every base\x00<thread> key. Only the main agent compacts. An idle subagent or teammate loses its keep-alive pings and pays a full cache write on its next turn.

    • Failing case (I wrote it): record main ("") and a:sub1 in one session, both held. Advance 30 s. Send SessionStart compact. Result: both entries gone. The test needs the subagent entry to survive. It fails on the PR code with default settings (CONTEXT_GURU_CLIENT_SIGNALS unset).
    • Why it blocks #524: #520 left this off by default. #524 makes it default for all users. This is the concern from the #520 review.
    • Fix I tried: when cutoff is set (the compact path), skip entries with e.thread != "". This passes my test and the existing Signal|Lifecycle|Compact|SessionEnd|Codex tests. SessionEnd keeps the full-session retire. #519 is on main now, so the compaction call stays on the main thread ("") and this rule is enough. If you prefer, read the thread that internal/thread marks compacting.
    • Test: please add a test like mine to this PR. My file is proxy/review524_test.go (not committed).
  2. Merge conflict with #525 is one hunk. git merge-tree shows a conflict only in the e := &kaEntry{...} literal in record (proxy/keepalive.go near line 817). #524 changes the tenant: line to add client: client. #525 changes it to add refreshedAt: startedAt and moves body: owned, up: up to a new line. Combine as:

    tenant: tn.ID, session: session, client: client, thread: threadID, startedAt: startedAt, refreshedAt: startedAt,
    body: owned, up: up,

    The two struct fields (client, refreshedAt) sit in different places and merge on their own. Whoever merges second rebases and takes both.

  3. CI purego failure is a flake, not this PR. The failing test is TestCacheAwareRealContentChangeInsideSpanStillDeclines (proxy/cache_aware_moving_cache_control_integration_test.go:301). It does not touch signals or keepalive.go. The run before it (same PR, 3 minutes earlier) passed. On box 1 the full go test ./proxy with CGO_ENABLED=0 ran 63 s and this test passed. It passed 5 of 5 alone, with and without cgo. Other branches (feat/adapt-cache, feat/remove-heuristic-deletion) show a CI failure too. Please re-run the job. Someone should look at the test timing in a separate issue.

  4. Merge with #519: clean. #519 is already on main (06c09ac). git merge-tree of #524 with origin/main shows no conflict.

What I verified

  • Signals only remove spend. record only calls retire on an end mark. signal only calls retire* or markEnded. No path extends a hold or arms a ping. This holds for the raw payload and for the Codex alias (session-id header).
  • Tenant scope. The signal key is tenant\0tenant:sid. The prefix match uses base+"\x00", so one session cannot match another. The alias match also requires e.tenant == tenantID. A payload can only name a session id the sender knows, in the sender's own tenant.
  • Raw payload. Only 3 fields plus the 4 KiB cap. Unknown fields are dropped. An unknown SessionEnd reason becomes other. Unknown events and kinds are refused with 400.
  • Hooks never break the client. signal.sh exits 0 on every path, has a 2 s curl limit and a 5 s hook timeout, and sends only 3 checked fields. The credential goes to curl on stdin. SessionStart sends in the background. Codex signal_hook catches all errors, has a 1 s timeout, and returns 0.
  • Credential, auto mode. It sends only to loopback or when x-context-guru-token is in ANTHROPIC_CUSTOM_HEADERS. With that header, only the context-guru header goes out, not the provider key.
  • Tests on box 1: go test ./proxy full run (CGO_ENABLED=0): only my new test fails. go test -race -run 'Signal|Lifecycle|Compact|Retire|SessionEnd|Codex' ./proxy ./context-guru-plugin: only my new test fails. No live test (per the release rule).

Questions

  1. Local proxy needs no credential. Any local process, or a web page that posts text/plain to 127.0.0.1 (the decoder ignores Content-Type), can retire a session. It must know the session id (a UUID), and the result is only lost pings. I think this is acceptable for loopback. On a hosted proxy the x-context-guru-token is required (I see 401 and the auth rate limit in the test log). Do you agree?
  2. auto treats any loopback URL as context-guru. If ANTHROPIC_BASE_URL is another local gateway (for example LiteLLM on localhost:4000), signal.sh sends ANTHROPIC_AUTH_TOKEN to its /signal path. That host already gets the token on every request, so I rate this low. Should auto also check the port, or the proxy's /health?
  3. Subagent compaction (open from #520). Does SessionStart source=compact fire when a subagent compacts itself? With the fix in finding 1, a subagent compact would not retire its entry. That is the safe direction (it only costs pings). Please confirm it is acceptable.

Reviewed by an AI reviewer (Claude)

@amiddavid
amiddavid dismissed their stale review October 14, 2026 13:14

The defect is in the code #520 adds (the compact branch of keeper.signal). It will be fixed in #520, and #524 gets the fix when it rebases on main. The findings stay valid as comments.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Thanks. Point-by-point reply. #524 is rebased onto the updated #520 (head 9f9980f).

1. Compact retires every thread. Fixed in #520 (d221800): on the compact path, only main-thread entries are retired, and SessionEnd still retires the whole session. #524 carries the fix after the rebase.

2. Conflict with #525. At the current heads, git merge-tree of #525 (ee7b7f1) with #524 and with #527 shows no conflict. If the second PR to merge does conflict in the kaEntry literal, I'll rebase and take both fields, as you described. I've told the #525 owner.

3. purego. I'll watch this run and re-run the job if it fails. It is the unrelated TestCacheAwareRealContentChangeInsideSpanStillDeclines.

Questions.

  1. Loopback without a credential: accepted. /signal now also refuses any body that is not application/json (415, in feat(keepalive): client lifecycle signals retire a session's cache on exit and compaction #520), so a web page cannot send a no-preflight text/plain POST to it.
  2. auto treats any loopback URL as context-guru: I'm leaving it. That host already gets the same token on every request, the cost is one 404 per session end, and a port or /healthz probe would add a request to every exit.
  3. Subagent compaction: the payload carries no agent id. If a subagent compacts, its entry is kept, which is the safe direction.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review: APPROVE at 9f9980f. It is rebased on #520 d221800. (Posted as a comment: GitHub does not let the author account approve.)

  • The range-diff against the approved 5a46885 shows only the expected conflict resolution in the retire loop. The alias ownership (e.client != "" && e.tenant == tenantID && e.client == session) and the compact thread rule are both kept.
  • Each guard is pinned by a test:
    • Removing the thread rule fails TestRawPayloadAndCodexAliasKeepSubagentsOnCompact and TestCompactRetiresOnlyTheMainThread.
    • Removing the alias match fails TestRawPayloadAndCodexAliasKeepSubagentsOnCompact.
    • Removing the tenant check fails TestCodexSessionEndMatchesTheSessionIDHeader.
  • The hosted snippet and the Codex hook send Content-Type: application/json, so they pass #520's 415 check.
  • gofmt and go vet are clean. The proxy, dash and plugin signal tests pass, as do the 41 Codex tests. CI is green, and all commits are signed off with no AI attribution.

Approved. Merge after #520.

Osher-Elhadad added 5 commits October 14, 2026 20:45
…keep-alive runs

The proxy accepts /signal unless CONTEXT_GURU_CLIENT_SIGNALS=off or the keep-alive kill switch is
set, and also takes a raw hook payload (only session id, event and reason are read). Codex
sessions match a signal through the session-id header. The Claude Code plugin sends by default to
its own proxy or a hosted service (client_signals auto|on|off, works without a token); the Codex
plugin gains SessionEnd/SessionStart hooks; the hosted setup snippet includes the hooks; the service
unit states the setting.

Signed-off-by: Osher-Elhadad <[email protected]>
… reasons count as other

The hosted setup hook now passes the header to curl as config on stdin (printf is a builtin) and
the payload on fd 3, so no process argv holds the token, and a multi-line ANTHROPIC_CUSTOM_HEADERS
works. A SessionEnd reason a newer client adds reads as "other" instead of 400. The docs and the
setup hint say the hosted hook posts the raw payload (cwd, transcript path; read fields only).
Adds a cross-tenant test for the alias guard.

Signed-off-by: Osher-Elhadad <[email protected]>
…ason

It picks the three fields out of Claude Code's payload (id characters only) instead of forwarding
it, so the working directory and transcript path no longer leave the machine.

Signed-off-by: Osher-Elhadad <[email protected]>
…agent on compact

They reach the same retire as the plugin shape: compact retires the main thread only, SessionEnd
every thread. The hosted-snippet test sends the JSON content type /signal now requires.

Signed-off-by: Osher-Elhadad <[email protected]>
@amiddavid
amiddavid changed the base branch from port/lifecycle-signals to main October 14, 2026 18:01
@amiddavid
amiddavid merged commit 0e2a540 into main Oct 14, 2026
11 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 14, 2026
amiddavid added a commit to AIMikav/context-guru that referenced this pull request Nov 9, 2026
…gin to 0.2.1

Both plugins changed in v0.5.1: the Claude Code plugin gained the lifecycle
signal hooks (rossoctl#520, rossoctl#524) and the per-agent money status line (rossoctl#525); the
Codex plugin gained its SessionEnd and SessionStart hooks (rossoctl#524). A new
version number is what makes an installed plugin update.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants