Repository navigation
feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs - #524
Conversation
OsherElhadad
left a comment
There was a problem hiding this comment.
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.
gofmtandgo vetare clean onproxy,dashandcontext-guru-plugin.go test ./proxyand./dashpass in full, the pluginSignaltests 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):
- The token is in curl's argv (
dash/ui/app.jsclaudeSettings:-H "$ANTHROPIC_CUSTOM_HEADERS")./proc/<pid>/cmdlineis 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. - The docs say "content-free event", but the hosted snippet posts Claude Code's raw hook payload. That payload includes
cwdandtranscript_path. The service reads only the three closed fields, but those values still leave the machine. Say so indocs/how-to/cache-keepalive.mdand in the setup page hint. The plugin'ssignal.shdoes send only the closed fields, so the plugin wording is right. - An unknown
SessionEndreason gets a 400. If a later Claude Code version adds a reason, that exit path silently stops retiring. Mapping an unrecognisedSessionEndreason tootherkeeps the closed set and the behaviour. - The extra
e.tenant == tenantIDguard 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
left a comment
There was a problem hiding this comment.
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:
- 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. Nosh,sedorcurlprocess carried the token:printfis a builtin,sedreads the header on stdin andcurlgets it as-K -config. A two-lineANTHROPIC_CUSTOM_HEADERSdelivered both headers. It works undershandbash --posix. - Only three fields leave the machine. The body is exactly
session_id,hook_event_nameandreason/source(the unused one is empty). That holds for a pretty-printed payload, andcwdandtranscript_pathnever appear. I tried injection:x"; rm -rf /comes out as an empty id (refused server-side), and acwdcontaining","reason":"logoutor"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--dataJSON. - Unknown reasons. An unknown SessionEnd reason now reads as
otherand returns 204, and an unknown SessionStart source is still 400. With the mapping disabled, TestSignalValidation fails. - The alias tenant guard is tested. With
e.tenant == tenantIDremoved 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
left a comment
There was a problem hiding this comment.
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
-
Compact retires every thread of the session, not only the compacted one.
proxy/clientsignal.go:190callsretireSessionStartedBefore. The loop atproxy/keepalive.go:963matches the main key and everybase\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 (
"") anda:sub1in one session, both held. Advance 30 s. SendSessionStart 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_SIGNALSunset). - 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
cutoffis set (the compact path), skip entries withe.thread != "". This passes my test and the existingSignal|Lifecycle|Compact|SessionEnd|Codextests.SessionEndkeeps 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 thatinternal/threadmarkscompacting. - Test: please add a test like mine to this PR. My file is
proxy/review524_test.go(not committed).
- Failing case (I wrote it): record main (
-
Merge conflict with #525 is one hunk.
git merge-treeshows a conflict only in thee := &kaEntry{...}literal inrecord(proxy/keepalive.gonear line 817). #524 changes thetenant:line to addclient: client. #525 changes it to addrefreshedAt: startedAtand movesbody: owned, up: upto 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. -
CI
puregofailure is a flake, not this PR. The failing test isTestCacheAwareRealContentChangeInsideSpanStillDeclines(proxy/cache_aware_moving_cache_control_integration_test.go:301). It does not touch signals orkeepalive.go. The run before it (same PR, 3 minutes earlier) passed. On box 1 the fullgo test ./proxywithCGO_ENABLED=0ran 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. -
Merge with #519: clean. #519 is already on main (
06c09ac).git merge-treeof #524 withorigin/mainshows no conflict.
What I verified
- Signals only remove spend.
recordonly callsretireon an end mark.signalonly callsretire*ormarkEnded. No path extends a hold or arms a ping. This holds for the raw payload and for the Codex alias (session-idheader). - Tenant scope. The signal key is
tenant\0tenant:sid. The prefix match usesbase+"\x00", so one session cannot match another. The alias match also requirese.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
SessionEndreason becomesother. Unknown events and kinds are refused with 400. - Hooks never break the client.
signal.shexits 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.SessionStartsends in the background. Codexsignal_hookcatches all errors, has a 1 s timeout, and returns 0. - Credential,
automode. It sends only to loopback or whenx-context-guru-tokenis inANTHROPIC_CUSTOM_HEADERS. With that header, only the context-guru header goes out, not the provider key. - Tests on box 1:
go test ./proxyfull 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
- Local proxy needs no credential. Any local process, or a web page that posts
text/plainto127.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 thex-context-guru-tokenis required (I see 401 and the auth rate limit in the test log). Do you agree? autotreats any loopback URL as context-guru. IfANTHROPIC_BASE_URLis another local gateway (for example LiteLLM onlocalhost:4000),signal.shsendsANTHROPIC_AUTH_TOKENto its/signalpath. That host already gets the token on every request, so I rate this low. Shouldautoalso check the port, or the proxy's/health?- Subagent compaction (open from #520). Does
SessionStart source=compactfire 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)
5a46885 to
9f9980f
Compare
|
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, 3. purego. I'll watch this run and re-run the job if it fails. It is the unrelated Questions.
|
OsherElhadad
left a comment
There was a problem hiding this comment.
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. gofmtandgo vetare 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.
…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]>
… by the token header 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]>
9f9980f to
ba8cd68
Compare
…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]>
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
/signaland its effects are on unlessCONTEXT_GURU_CLIENT_SIGNALS=offor the keep-alive kill switch (CONTEXT_GURU_KEEPALIVE=off). The route also accepts a raw Claude Code / Codex hook payload: onlysession_id,hook_event_nameandreason/source/notification_typeare read, the rest is discarded unread (body cap 4 KiB). A held entry remembers the client'ssession-idheader (Codex), so a Codex signal matches a session the proxy keys by content hash. Session identity is unchanged.client_signalsdefaults toauto: send to the plugin's loopback proxy, or to a hosted service (recognised byx-context-guru-tokeninANTHROPIC_CUSTOM_HEADERS, now the header used).on= any base URL,off= never. The local proxy needs no credential (subscription logins export none).SessionEndandSessionStart(compact|resume|clear, async) hooks runcodex_plugin.py signal, which posts the closed fields to the local proxy. Codex runs plugin hooks only after the user trusts them in/hooks.SessionEndandSessionStart compacthooks (onecurl --data-binary @-to<base>/signal).deploy/service/context-guru.servicestatesCONTEXT_GURU_CLIENT_SIGNALS=on. This PR changes no running deployment.docs/how-to/cache-keepalive.md; Codex README.Tests
go test ./proxy ./session ./apply ./context-guru-pluginand the Codex plugin tests pass.autosends 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:
/exit, Ctrl-C twice, Ctrl-D, closing the terminal,/clearand/compacteach reached the proxy and released the held entry; no pings after the exit. With the hook off, the same exit kept pinging.claude --resumekept the session id, re-armed the hold, and its first request read the full prefix from the provider cache./exit,/quit, Ctrl-C twice and Ctrl-D send SessionEnd and release the entry. Closing the terminal sends nothing (a Codex limitation).codex resumeand/compactare delivered. Untrusted plugin hooks do not run. Without thesession-idalias, a Codex SessionEnd matched nothing.