Repository navigation
feat(contextguru): [cg] Port Responses, the Anthropic incoming model, the marker cap and xhigh from #1412 - #2061
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 1 minute. View limit details
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. |
96e5a9d to
5fa0acc
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This PR ports the #1412 work into context-guru. It adds an incoming model for Anthropic Messages, built on cheapmodel.Anthropic over a deduped, TTL-swept credential hold. It adds the summarizer's prefix asker, backed by a bounded forwarded-body stash. It also handles the Responses API (dialectFor / apply.Opts.API, with /v1/responses in the default paths), caps marker_mode at summary, defaults the engine to xhigh, and fills the oauth-* beta in the dispatcher. I reviewed only this PR's change on top of #2060 (1661c70d...5fa0acc6). The design holds up:
- the hold lifecycle covers sweep,
Shutdownordering and reconfigure, - the received body is paired with the forwarded one on the request's own
pctx, not in a session-keyed map, - redirected and non-200 requests are not stashed,
- under
observe, no hold is taken and no model is built, - spend ops reuse the late-drop path.
The CLAUDE.md and docs updates describe the retention of the holds and the stash accurately.
I'm requesting changes for one blocking issue, and it is in the tests, not the product code. At this head the contextguru tests share one on-disk state database, so they depend on order and timing: go test -count=2 ./plugins/contextguru/ fails every time here and passes on #2060's head. Go CI (core)'s Test step is also red on this head and green on #2060.
Non-blocking: one suggestion (the prefix ask replays the agent's body with only the oauth-* betas, unlike the keep-alive ping) and one nit on reconfigure.
Verified locally on the PR head, with GOWORK=off, in core: go vet is clean, gofmt -l is empty, and go test -race -count=1 ./plugins/contextguru/ ./plugins/all/ passes, and 6 of 6 single runs of the contextguru package under -race pass. -count=2 fails, as described in the inline comment. I also checked the new context-guru v0.7.5-beta.2 APIs (cheapmodel.Anthropic.CompletePrefixed, tooldefer.AuthBetas, CapMarkerMode).
Author: boazdavid (maintainer)
Areas reviewed: Go (core/plugins/contextguru), Docs (CLAUDE.md, docs/*.md)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit in this layer, signed off (DCO passes)
CI status: Go CI (core) fails in its Test step on this head and passes on #2060's. I couldn't download the log; see the must-fix comment. The other three failures don't come from this layer:
- CodeQL's one alert is
core/accounting/savings.go:413(alert 365). It is open on #2057 and #2060 too, and this PR does not touch that file. - Pre-commit fails on
check-doc-linksfordocs/configuration.md→laptop-service.md#the-metrics_push-configuration. That link is broken onmaintoo. The files this PR changes pass every hook. Go CI (core peerproc, macOS)hit the 10-minute job limit while GitHub reported macOS runner capacity limits. #2060's run of the same job took 9m29s.
| engine := p.cfg.Engine | ||
| if len(engine) == 0 { | ||
| engine = []byte("preset: balanced") | ||
| engine = []byte("preset: xhigh") |
There was a problem hiding this comment.
must-fix — with this default, the contextguru tests become order- and timing-dependent, and Go CI (core) is red on this head.
TestMain (from #2058) gives every test in the package one shared context-guru-state.db. The disk store flushes every second (store/disk.go defaultFlushEvery). billedFor always uses session s1, so TestOnFinish_SkipsSubagentAndFailedRequests can read the billed input that TestOnFinish_RecordsBilledInput wrote on another instance, once that write has been flushed and reloaded from disk:
--- FAIL: TestOnFinish_SkipsSubagentAndFailedRequests
windows_test.go:83: subagent: recorded billed input "49003", want nothing
windows_test.go:83: failed: recorded billed input "49003", want nothing
What I reproduced, with GOWORK=off in core:
go test -count=2 ./plugins/contextguru/fails every time on this head (5fa0acc). On feat(contextguru): [cg] Turn context-guru on by default on a local install #2060's head (1661c70) it passes, including-count=3.-count=1passed 6 of 6 runs locally. It is timing-dependent: a 1.5 s delay at the top of the Skips test makes it fail on both heads, so the isolation gap is latent from feat(contextguru): [cg] Keep the session state on disk #2058. This layer is where it starts to show, probably because the heavierxhighdefault pipeline puts a flush tick between the two tests far more often.- The
Teststep ofGo CI (core)failed on this head and passed on feat(contextguru): [cg] Turn context-guru on by default on a local install #2060 and feat(accounting): [cg] Push the accountant's metrics to a central collector #2062. I could not download the job log, because the log-storage host is not reachable from my sandbox, so I can't confirm this is the test that failed there. A rerun would tell.
Suggested fix: give each configured() plugin its own database, for example by overriding stateDBPathFor with t.TempDir() and restoring it in t.Cleanup, as statedb_test.go already does. Unique session ids per test in billedFor would work too. Then go test -count=3 ./plugins/contextguru/ should pass, and core CI should be green.
| // token's incoming-model calls can 401 for a missing beta the direct client always sent | ||
| // (review finding). A caller that DID set one (tooldefer.RunProbeBeta's own beta argument) | ||
| // is left alone — its choice is deliberate, not an oversight to fill. | ||
| if h.authBeta != "" && hreq.Header.Get("Anthropic-Beta") == "" { |
There was a problem hiding this comment.
suggestion — the prefix ask replays the whole forwarded body, but only the oauth-* betas go with it.
prefixAsker.Ask → cheapmodel.Anthropic.CompletePrefixed sends the stashed forwarded body (the agent's own tools, thinking, and whatever else Claude Code put in it) with anthropicHeaders(). The only Anthropic-Beta it gets is this fill, which tooldefer.AuthBetas cuts down to oauth-*. TestDoFillsTheRequestsOwnAuthBetaWhenTheCallerSetNone pins that prompt-caching-… is dropped. Claude Code's own traffic in this repo's fixtures sends claude-code-20250219,context-1m-2025-08-07,interleaved-thinking-2025-05-14 (core/plugins/inferenceparser/testdata/claude-code/*/request.headers). So a replayed body that depends on one of those betas can come back 400, or read a different cache entry:
- a
context_managementfield (core/translatealready treats it as a known Anthropic request field), - a transcript over 200k tokens on a model that needs
context-1m(the stash bounds say they are sized for the summarizer firing at 900k on a 1M window), - interleaved thinking blocks.
Each case fails open, so the summarizer quietly does nothing that turn. The keep-alive ping replays the same kind of body and copies the request's full Anthropic-Beta for that reason (keepalive.PingHeaders). I could not test this against the live API. The engine proxy has the same gap, so this is not a regression of the port. Still, it may be worth holding the request's full Anthropic-Beta for the incoming-model holds (none of those values is a secret), or at least for CompletePrefixed calls. If you have checked it live and it is fine, a comment saying so would help.
| // nothing above can fail, so a failed Configure leaves the old holds in place. A second | ||
| // Configure on one instance releases the first one's holds. | ||
| if p.holds != nil { | ||
| p.holds.releaseAll() |
There was a problem hiding this comment.
nit — a second Configure releases the old holds but does not stop their sweep. If Init already ran, the old startSweep goroutine keeps ticking on the replaced credHolds until the process exits, and the new one gets no sweep. The keeper branch above calls p.keeper.Shutdown() for the same case. Production builds a fresh instance per reload, so only tests reach this today. Calling p.holds.stopSweep() before releaseAll() here would make it match Shutdown.
5fa0acc to
925cdcd
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-review after the stack was rebased (5fa0acc → 925cdcd). I reviewed only this layer, 53b3dc46...925cdcda on top of #2060. The layer is byte-identical to the one I reviewed at 5fa0acc (git range-diff reports =). The rebase changed only lower layers (core/accounting/wire, facts, core/cost/settle), and none of those touch core/plugins/contextguru. I'm withdrawing the earlier must-fix, which means this layer now has nothing blocking:
- The shared-state-DB test flake is not caused by this layer. On #2060's new head (53b3dc4),
go test -count=2 ./plugins/contextguru/now fails 4 of 4 runs with the sameTestOnFinish_SkipsSubagentAndFailedRequests: recorded billed input "49003". On this head it failed 2 of 3 runs. So the failure comes from the package-wideTestMainstate DB that #2058 adds, not from thexhighdefault here. It should still be fixed, and the right place is #2058: give eachconfigured()plugin its own DB viastateDBPathFor+t.TempDir(), or give each test its own session id. The fix will then carry up the stack.Go CI (core)is green on this head,Teststep included, and the job has no annotations. - My earlier suggestion (the prefix ask only sends the oauth-*
Anthropic-Beta, while the keep-alive ping copies the full header) and nit (a secondConfiguredoesn'tstopSweep()the old holds) still apply to the same lines. I won't repeat them inline. Neither one blocks.
Design re-checked on this head: hold dedup, TTL sweep and Shutdown ordering; the received/forwarded body pairing on the request's own pctx; no stash for redirected, subagent or non-200 requests; no hold and no model under observe; Responses routing (dialectFor, no llmclient incoming model for api == "responses"); the CapMarkerMode("summary") cap; and the oauth-beta fill that leaves a caller-set beta alone. The docs and CLAUDE.md retention notes match the code.
Verified locally on 925cdcd, GOWORK=off, in core: go vet ./plugins/... is clean, gofmt -l plugins/contextguru is empty, and go test -race -count=1 ./plugins/contextguru/ ./plugins/all/ passes 3 of 3 runs.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin — maintainer)
Areas reviewed: Go (core/plugins/contextguru), Docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit in this layer (925cdcd), signed off (DCO passes)
CI status: Go CI (core) passes. The two failures come from lower layers, not this one:
- CodeQL alert 365 is at
core/accounting/savings.go:413, from #2057. - Pre-commit
check-doc-linksfails ondocs/configuration.md→laptop-service.md#the-metrics_push-configuration. That link was added in #2057 (f088aee).scripts/dev/check-doc-links.pyreproduces it on #2060's head and passes onmain.
Some jobs were still pending when I posted.
925cdcd to
6f85f11
Compare
53b3dc4 to
b26c58c
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-review after the stack was rebased again (925cdcd → 6f85f11). I reviewed only this layer, b26c58c8...6f85f119 on top of #2060. git range-diff against the layer I approved at 925cdcd shows one real change: meteredDispatcher now reports through a pipeline.OpReporter captured in anthropicIncoming instead of holding pctx and calling ReportOpsAs. That matches how cgModel reports in the lower layers. anthropicIncoming is only reached from OnRequest → modelsFor, while the pipeline has the plugin set as current, so the operator stamp is right. TestAnthropicIncomingCallIsSpendOp now sets the current plugin before it builds the model, so it covers that ordering. The rest of the range-diff is context that moved with the rebase (the Init/stateDisk.Swap code from #2058). Nothing in this layer blocks.
- The shared-state-DB flake I traced to #2058 last time looks fixed lower in the stack:
go test -count=2and-count=3 ./plugins/contextguru/both pass on this head. - My earlier suggestion (the prefix ask sends only the oauth-*
Anthropic-Beta, while the keep-alive ping copies the full header) and nit (a secondConfiguredoesn'tstopSweep()the old holds,plugin.go:438) still apply. I'm not repeating them inline. Neither blocks. - One new nit inline: a doc comment that still describes the old
pctx/dryRuncapture.
Design re-checked on this head: hold dedup, the TTL sweep and Shutdown ordering; the received/forwarded body pairing on the request's own pctx; no stash for redirected, subagent or non-200 requests; no hold and no model under observe; Responses routing (dialectFor, no llmclient incoming model for api == "responses"); the CapMarkerMode("summary") cap; and the oauth-beta fill that leaves a beta the caller set alone. CLAUDE.md and the docs are unchanged from 925cdcd and still match the code.
Verified locally on 6f85f11, GOWORK=off, in core: gofmt -l plugins/contextguru is empty and go vet ./... is clean. go test -race -count=1 ./plugins/contextguru/ ./plugins/all/ passes 3 of 3 runs, and go test -count=2 and -count=3 ./plugins/contextguru/ pass.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin — maintainer)
Areas reviewed: Go (core/plugins/contextguru), Docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit in this layer (6f85f11), signed off (DCO passes)
CI status: Only DCO (pass) and CodeRabbit (skipped) have reported on this head. No GitHub Actions run was created for it, and none for #2060's or #2062's new heads either, so Go CI, CodeQL and pre-commit have not run on this rebase. My local runs above stand in for them. A re-trigger would confirm.
|
|
||
| // meteredDispatcher reports each call it sends as a KindSpend op on the request it was made for, | ||
| // from the usage block of the Anthropic response, as cgModel.Complete does from llmclient's. Like | ||
| // cgModel, it captures pctx, dryRun and the late-drop counter on the request goroutine, and a |
There was a problem hiding this comment.
nit — this comment is stale after the switch to OpReporter. meteredDispatcher no longer captures pctx or dryRun. It holds a pipeline.OpReporter built in anthropicIncoming, which fixes the operator and the dry-run state on the request goroutine. Something like "it captures an OpReporter (operator and dry-run state fixed on the request goroutine) and the late-drop counter" would match the code.
6d85129 to
e2a97f5
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I re-reviewed after the stack was rebased onto #2060's new head (0fb546e). I reviewed only this layer, 0fb546e0...c4f42f66. git range-diff against the layer I approved at 6d85129 shows both commits as = (507a063 = e2a97f5, 6d85129 = c4f42f6), so this push did not change the layer. The base moved only in core/accounting, where host.go and savings.go now run client-controlled log values through logSafe. That code lives in a lower layer. Nothing in this layer calls it, and this layer adds no log lines of its own. Nothing here blocks.
I re-read the layer on this head:
- the dispatcher's oauth-*
Anthropic-Betafill - the credential-hold dedup, the TTL sweep, and the
Shutdownordering (stopSweepbeforereleaseAll) - the received/forwarded body pairing on the request's own
pctx, and no stash on redirected or non-200 requests dialectForwith Responses routing- the
CapMarkerMode("summary")cap and thepreset: xhighdefault - no hold taken under
observe
anthropicCall still decodes into plain int/string fields, so a null or missing usage field cannot fail the parse.
Still open from earlier rounds, all non-blocking and not repeated inline:
- suggestion: the prefix ask sends only the oauth-*
Anthropic-Beta, while the keep-alive ping copies the full header. - suggestion: the
CLAUDE.mdmerge says the keeper holds "no content". #2059's wording, whichdocs/laptop-service.mdhere keeps, says a keeper entry holds the thread's last request body. - nit: a second
Configurereleases the old holds without callingstopSweep()(plugin.go:456-459). - nit: the
meteredDispatcherdoc comment still says it capturespctx/dryRun, but it now holds anOpReporter.
Verified locally on c4f42f6, GOWORK=off, in core:
gofmt -l plugins/contextguruis empty.go vetis clean on./plugins/contextguru/and./accounting/....go build ./...passes.go test -count=2 ./plugins/contextguru/ ./accounting/...passes.go test -race ./plugins/contextguru/passes.
Author: boazdavid (CONTRIBUTOR; admin on the repo, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru), docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md)
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this layer, DCO passing
CI status: CodeQL fails with the two core/accounting alerts (host.go:266 log injection, savings.go:422 clear-text logging). Those lines come from lower layers, and #2060's head fails the same check. CodeQL apparently doesn't treat logSafe as a sanitizer, so that is for the accounting layer to settle. Image builds, Windows, Rust and lint are green. Go CI (core) and the other Go jobs were still pending when I posted, which is why I ran the checks above locally.
c4f42f6 to
3a2eeba
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I re-reviewed after the stack was rebased onto #2060's new head (b9c2487). I reviewed only this layer, b9c2487...3a2eeba. git range-diff against the layer I approved at c4f42f6 shows 3a2eeba as = and ee66d84 as changed only where it had to absorb #2060's new base. The base now hardcodes the inference paths, renames model to cheap_model, and adds cache.strategy, cache_mode and the 1-hour-head knobs. The conflict resolution is sound:
/v1/responsesmoved into the hardcodedinferencePaths, andTestConfigure_DefaultPathsIncludeResponsesand thedialectFortable still cover it.- The
preset: xhighdefault now runs throughinjectDefaultCacheStrategybeforeCapMarkerMode("summary"), so the default install still getscache.strategy: auto. APIandPrefixAsksit next to the base's newCacheMode/HeadTTL1h/HeadTTLMinBytesinapply.Opts.- The hold dispatcher is built on
p.localInstall.
Nothing here blocks. Three small leftovers from the rename are inline: one suggestion and two nits.
Still open from earlier rounds, all non-blocking and not repeated inline:
- suggestion: the prefix ask sends only the oauth-*
Anthropic-Beta, while the keep-alive ping copies the full header (dispatcher.go:178). - suggestion: the
CLAUDE.mdmerge still says the keeper holds "no content". #2059's wording, whichdocs/laptop-service.mdhere keeps, says a keeper entry holds the thread's last request body (CLAUDE.md:272). - nit: a second
Configurereleases the old holds without callingstopSweep()(plugin.go:514-517). - nit: the
meteredDispatcherdoc comment still says it capturespctx/dryRun, but it holds apipeline.OpReporter(incoming_anthropic.go:195-199).
This layer adds no new JSON decoders. anthropicCall still decodes into plain int/string fields, so a null or missing usage field cannot fail the parse.
Verified locally on 3a2eeba, GOWORK=off, in core:
gofmt -l plugins/contextguruis empty.go vetis clean on./plugins/contextguru/and./accounting/....go build ./...passes.go test -count=2 ./plugins/contextguru/ ./accounting/...passes.go test -race -count=3 ./plugins/contextguru/passes.cmd/cortexbuilds andgo vet ./...is clean there.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru), docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md)
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this layer, DCO passing
CI status: every job except DCO was still pending on this head when I posted (the push was minutes old), which is why I ran the checks above locally.
|
|
||
| - **OpenAI Chat Completions:** through `llmclient`, on the request's endpoint and `Authorization`. | ||
| - **Anthropic Messages** (`/v1/messages`, Claude Code's traffic): through context-guru's `cheapmodel.Anthropic`, on the request's endpoint and credential (`x-api-key` or `Authorization`). The credential is held in memory, masked, one hold per credential, and released 2 hours after its last use (on a timer, not only on the next matching request), on a config reload, or at `Shutdown`. The request's own `Anthropic-Beta` oauth-* values (`tooldefer.AuthBetas`) are held too and sent on the call when `cheapmodel` set none: a Claude subscription (OAuth) token can need one to authenticate directly against `api.anthropic.com`, and without it the call 401s — failing open, but silently, since the summarizer then does nothing that turn. It is held, not borrowed, because `cache_aware_summarizer` commissions its call in the background and the request returns first. On Anthropic the summarizer asks one question appended to the previous turn's forwarded body, so the provider's prompt cache serves the whole transcript. The plugin keeps that body in memory for the last 16 sessions (main agent only, a 200 response only, at most 8 MiB per body and 96 MiB in total). | ||
| - **OpenAI Responses API:** none. A Responses request uses the `model` block, or the component degrades to deterministic. |
There was a problem hiding this comment.
suggestion — this line points operators at the model block, but #2060 renamed it to cheap_model. Configure uses plain json.Unmarshal with no DisallowUnknownFields, so an operator who follows this line and writes model: gets no error and no static model. Every Responses request then silently degrades to deterministic. The base text had the same stale name, but this layer rewrites the line, and line 23 above already says cheap_model.
| - **OpenAI Responses API:** none. A Responses request uses the `model` block, or the component degrades to deterministic. | |
| - **OpenAI Responses API:** none. A Responses request uses the `cheap_model` block, or the component degrades to deterministic. |
| // Engine config: default to the balanced preset when none is supplied. | ||
| // Engine config: default to the xhigh preset when none is supplied. xhigh includes the | ||
| // model-calling components (cache_aware_summarizer, extract_llm, extract_llm_sweep). They act | ||
| // only where a model client resolves (a model: block, or the request's own model), and each |
There was a problem hiding this comment.
nit — after the cheap_model rename this should say "a cheap_model: block". The docs and the line-15 package comment already do.
| {Name: "model", Type: "object", Description: "Optional static cheap model for LLM-backed components (summarize, extract:code)."}, | ||
| {Name: "engine", Type: "object", Description: "Native context-guru config: preset / pipeline / per-component (marker_mode) / store."}, | ||
| {Name: "cheap_model", Type: "object", Description: "Optional static cheap model for LLM-backed components (summarize, extract:code); context-guru-proxy's own name for the same concept is CHEAP_MODEL*. Its calls honour HTTPS_PROXY except on a local install, where it points at Cortex itself. max_concurrent bounds concurrent calls to it, process-wide; default 4, the same default as context-guru-proxy's --cheap-model-concurrent flag."}, | ||
| {Name: "engine", Type: "object", Description: "Native context-guru config: preset / pipeline / per-component (marker_mode) / store / cache. " + |
There was a problem hiding this comment.
nit — the rebase dropped this layer's earlier addition to the engine description ("Default: preset xhigh. marker_mode is capped at summary."). That was the only place agentop / /v1/plugins told an operator that marker_mode: full is silently lowered to summary. Consider adding it back after the cache.strategy text.
3a2eeba to
935786a
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I re-reviewed after the stack was rebased onto #2060's new head (997990b), which now also carries e21f17a (OneHourFirst) and cd8e41b. I reviewed only this layer, 997990b...935786a. git range-diff against the layer I approved at 3a2eeba shows 5a8036e as =. 70d6dfc changed only where it absorbs the base's new oneHourFirstFor. OneHourFirst: p.oneHourFirstFor(provider, pctx.Host) now sits next to HeadTTL1h/HeadTTLMinBytes, API and PrefixAsk in apply.Opts, and nothing from either side was lost.
The new commit, 935786a, is sound. It moves startSweep's first releaseExpired out of the goroutine and runs it before startSweep returns:
- The lock order is unchanged.
releaseExpiredtakesh.muand thend.mu(viaRelease), asholddoes.Initis the only caller and holds neither lock, so the synchronous pass cannot deadlock. TestStartSweepReleasesAlreadyExpiredHoldWithNoRequestnow asserts right afterstartSweepreturns, with no poll.scripts/dev/check-test-timing.pypasses oncore/plugins/contextguru/*_test.goand on every changed_test.gofile in the PR.
One remark on the commit message, non-blocking. It says the change "closes a real race for production callers". Configure builds a fresh, empty credHolds right before Init runs (plugin.go:522), so in production no expired hold exists for the first pass to find. The change is a correct fix for test determinism and keeps the doc's "runs immediately" promise. It does not fix a production race. One doc nit is inline.
Still open from earlier rounds, all non-blocking and not repeated inline:
- suggestion: the prefix ask sends only the oauth-*
Anthropic-Beta, while the keep-alive ping copies the full header (dispatcher.go). - suggestion: the
CLAUDE.mdmerge still says the keeper holds "no content", but a keeper entry holds the thread's last request body (CLAUDE.md:272). - nit: a second
Configurereleases the old holds without callingstopSweep(), so the old sweep goroutine keeps running (plugin.go:514-517). - nit: the
meteredDispatcherdoc comment still says it capturespctx/dryRun, but it holds apipeline.OpReporter(incoming_anthropic.go:195-199).
This layer adds no new JSON decoders.
Verified locally on 935786a, GOWORK=off, in core:
gofmt -l plugins/contextguruis empty.go vet ./plugins/contextguru/is clean.go build ./...passes.go test -race -count=1 ./plugins/contextguru/...passes.go test -race -count=50 -run Sweep ./plugins/contextguru/passes.go test -count=1 ./accounting/... ./plugins/contextguru/...passes.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru), rebase conflict resolution in plugin.go
Agent/IDE config (.claude/.vscode): none
Commits: 3 in this layer, all signed off, DCO passing
CI status: every job except DCO was still queued (pending) on this head after about 30 minutes, so I ran the checks above locally.
| } | ||
|
|
||
| // releaseExpired is releaseExpiredLocked with its own lock, for the sweep goroutine, which does | ||
| // not otherwise touch h.mu. |
There was a problem hiding this comment.
nit: startSweep now also calls this synchronously, on Init's goroutine, before the sweep goroutine starts. So "for the sweep goroutine, which does not otherwise touch h.mu" is no longer the whole story. Maybe: "for startSweep's first pass and the sweep goroutine, neither of which otherwise holds h.mu".
huang195
left a comment
There was a problem hiding this comment.
Summary
I reviewed this layer only (cg/07-local-default-on...cg/08-contextguru-1412-port at 935786a2, 3 commits, 11 files), against context-guru v0.7.7. I read the production code in full: incoming_anthropic.go, and the plugin.go, dispatcher.go and keepalive.go changes. The pairing of the received body with the forwarded body on pctx is correct. The hold sweep stops before releaseAll, and a redirected request stashes nothing. The oauth-beta fill sends only oauth-* values, and only when the caller sets no beta.
The 12-minute hold claim from my #2059 review is still in CLAUDE.md, docs/laptop-service.md and docs/session-api.md. I do not repeat it here.
Author: boazdavid (MEMBER, maintainer)
Areas reviewed: Go (core/plugins/contextguru), docs
Agent/IDE config (.claude/.vscode): none
Commits: 3 in this layer. DCO passes.
CI status: pending. Only DCO has finished.
Not checked: go test (I ran no build), a live Anthropic incoming-model call, and an OAuth (subscription) token.
Assisted-By: Claude (Anthropic AI) [email protected]
| engine := p.cfg.Engine | ||
| if len(engine) == 0 { | ||
| engine = []byte("preset: balanced") | ||
| engine = []byte("preset: xhigh") |
There was a problem hiding this comment.
must-fix: The default engine changes from preset: balanced to preset: xhigh, and the PR body has no upgrade note. Any config with no engine: key moves to xhigh after the upgrade: a cluster, or a laptop where the user turns context-guru on. xhigh runs cache_aware_summarizer, extract_llm and extract_llm_sweep. On Anthropic traffic, this PR also gives those components the agent's own model on the caller's credential. So the upgrade starts billed calls on the agent's own model (for example Opus), and each caller's credential is held for 2 h. Session budgets do not count that spend (#2059's doc).
Please keep balanced as the default, or add an upgrade note like the one #2059 has, with the opt-out (engine: {preset: balanced}).
| if model == "" { | ||
| return cheapmodel.Anthropic{}, false | ||
| } | ||
| ref := p.holds.hold(pctx, time.Now()) |
There was a problem hiding this comment.
suggestion: anthropicIncoming takes a 2 h credential hold on every Anthropic request that is not under observe. It does this also when no component in the pipeline can use a model, for example with an explicit preset: balanced. Such a hold has no use. The engine can tell you: components.Component.NeedsModel(), with Pipeline.Names() and Find(). Please check once in Configure, and take no hold (and stash nothing) when no component needs a model.
| // ask would never find a prefix. These are sized for that window. Only main-agent bodies are | ||
| // stashed, one entry per session. | ||
| const ( | ||
| maxStashSessions = 16 |
There was a problem hiding this comment.
suggestion: The stash keeps up to 96 MiB of conversation text in plaintext, with no time bound. The keeper masks its bodies, but the stash does not. A prefix ask exists only to hit the provider's prompt cache, and that cache lives at most 1 h. After 1 h, an entry gives no cache benefit, but it still holds the whole conversation. Please drop an entry older than the cache TTL (or 1 h) in the hold sweep that already runs every 10 min.
| b.WriteString(pctx.Scheme + "\x00" + pctx.Host) | ||
| for _, name := range authHeaderNames { | ||
| for _, v := range pctx.Headers.Values(name) { | ||
| b.WriteString("\x00" + name + "\x00" + v) |
There was a problem hiding this comment.
nit: credKey writes each raw credential value into a strings.Builder on every Anthropic request. This makes one more plaintext copy in the heap, and no code can zero it. credID in mask.go masks the value before it hashes it. Please do the same here, or reuse credID plus the scheme and host.
166df02 to
1e32f72
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-reviewed this layer only — cg/07-local-default-on...cg/08-contextguru-1412-port at 935786a2 (3 commits, 11 files) — against context-guru v0.7.7 (tag 30a8076). The Anthropic incoming-model path, the Responses dialect, the marker cap and the oauth-beta fill read correctly to me; TestConfigure_NoReversibleMarkersEvenUnderAFullPreset covers exactly the cap's point. Two things in this layer, both docs/coverage rather than logic — one is a regression this diff introduces.
must-fix — CLAUDE.md:271: the new sentence says the keeper holds "no content", but recordFor puts Body: pctx.Body on the keepalive.Record (core/plugins/contextguru/keepalive.go:139) and the keeper keeps that copy masked and re-sends it in every ping (context-guru keepalive/keeper.go:88-95). docs/session-api.md:414 in this same PR says the opposite — "A keeper entry does hold content:" — and so does docs/laptop-service.md. The text this diff replaced was the accurate one. (Inline.)
suggestion — core/plugins/contextguru/plugin.go:161: only /v1/responses is gated, while cortex's own Responses suffix is /responses (core/parse/inference/dialect.go:37), which deliberately covers Codex's /backend-api/codex/responses too (core/listener/forwardproxy/upgrade.go:35). A Codex request on that path is a Responses body cortex parses, but gated() returns false for it. (Inline.)
Still open from earlier rounds, not repeated inline:
- must-fix — huang195's upgrade note for
preset: balanced→preset: xhigh(plugin.go:398). Confirmed: a config with noengine:now runscache_aware_summarizer,extract_llmandextract_llm_sweep, and on Anthropic this layer hands them the caller's own model on the caller's credential. The PR body has no upgrade note; #2059's body has the pattern to follow. - must-fix — the "12 minutes" hold claim (
CLAUDE.md:275,docs/laptop-service.md,docs/session-api.md). WithWaitPlanon by default (keepalive.go:43),MaxPingsis raised to the plan count (keepalive/keeper.go:1718) andhold()is(MaxPings+1) × Idle(keepalive/keeper.go:288). At 240 s idle that is 36 min on a tool wait (8+1), 24 min background, 16 min human — not 12.TestKeepAliveHoldFollowsTheBilledTierpins 12 minutes on a policy with no wait plan, so it cannot catch it. - suggestion (huang195) — no hold when no component needs a model; a 1 h bound on the stash; and
credKeyhashing the raw credential rather than reusingcredID's masking.
Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (core/plugins/contextguru), docs (CLAUDE.md, docs/*)
Agent/IDE config (.claude/.vscode): none
Commits: 3 in this layer (16 in the PR), all signed off, DCO passing
CI status: pending at 935786a (DCO passed; every other job still queued)
Not checked:
go build,go vet,go test— the Go module CDN is unreachable from this sandbox (proxy.golang.org zips redirect to storage.googleapis.com, which times out;modernc.org/[email protected]likewise), socore/plugins/contextgurucannot compile here.gofmt -l core/plugins/contextguruis empty at this head.- A live Anthropic call on an OAuth (subscription) token, and the Responses path end to end.
Generated by repoman github-pr-review@af425c8.
| per-thread billing mode and pending ping facts in `core/accounting.Host`, the | ||
| context-guru keeper's entries, the context-guru incoming-model credential holds and | ||
| forwarded-body stash, and the context-guru plugin's session state in | ||
| `~/.cortex/context-guru-state.db`. The accountant state and the keeper hold session and thread |
There was a problem hiding this comment.
must-fix: This now says the keeper holds "no content", but it holds the thread's last request body. recordFor sets Body: pctx.Body on the keepalive.Record (core/plugins/contextguru/keepalive.go:139), and the keeper keeps that copy masked and re-sends it in every ping (context-guru v0.7.7 keepalive/keeper.go:88-95: "the bytes last sent upstream, held MASKED"). docs/session-api.md:414 in this same PR still says "A keeper entry does hold content:" and docs/laptop-service.md still says "the thread's last request body (the whole conversation), both masked" — so the three docs now disagree, and the sentence this diff replaced was the accurate one.
Concretely: after DELETE /v1/sessions/{id}, an operator reading this paragraph concludes the conversation is gone, while the keeper keeps it for (MaxPings+1) × Idle and sends it upstream again on each ping.
Suggested fix: restore the dropped clause, e.g. "…and a billing mode, no content; the keeper also holds the caller's credential and the thread's last request body (the whole forwarded conversation), both masked."
| // context-guru-proxy has no equivalent knob either -- it hardcodes its own routes | ||
| // (/openai, /anthropic, /healthz, /stats, /expand) the same way, because the whole point of | ||
| // that binary is to always run the engine on them. See gated. | ||
| var inferencePaths = []string{"/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses"} |
There was a problem hiding this comment.
suggestion: Only /v1/responses is gated here, while cortex's own Responses suffix is /responses (core/parse/inference/dialect.go:37) — deliberately, because Codex's /backend-api/codex/responses and the public path share no prefix; core/listener/forwardproxy/upgrade.go:35 matches the same way.
Concrete case: a Codex request to /backend-api/codex/responses carries a Responses body that cortex parses, but gated() returns false, so context-guru never sees it — no compaction and no summarizer on that traffic. I ran a faithful copy of gated() with these four paths:
/v1/responses gated=true
/openai/v1/responses gated=true
/responses gated=false
/backend-api/codex/responses gated=false
Suggested fix: gate and classify on the /responses suffix in both gated and dialectFor, matching the parser. apply.Opts.API already accepts "responses", so nothing downstream changes.
| // stashSent stores a finished main-agent request's two bodies for the next turn's prefix ask. | ||
| // Only a 200 is a valid prefix: a rejected send populated no prompt cache. pctx.Body in OnFinish | ||
| // is the body that went upstream. A shadow run (on_error: observe) sent the client's body, which | ||
| // is still pctx.Body, so the stash matches what upstream cached in that case too. |
There was a problem hiding this comment.
nit: This sentence describes a case that cannot happen. Under on_error: observe, modelsFor returns an empty ModelSpec (plugin.go:963), so no cheapmodel.Anthropic is built, no pendingBody is set, and stashSent returns at its pre == nil check long before this point — a shadow run stashes nothing.
Suggested fix: drop the sentence, or state the real reason (no incoming model is built under observe, so there is nothing to stash).
1e32f72 to
ab25fdf
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Reviewed this layer only — c2e8a48, 84af8d2f, 1e32f72c (3 commits, 22 files). The three other commits since the last review are lower layers: a8ccd49d was covered in #2059's last round, and 81125a5d / b168e08 are #2059's and #2060's. I read the library at the exact content CI builds — context-guru v0.7.7 as the checksum database pins it (commit 23a4b03), not the current GitHub tag; see the go.mod comment. The Responses routing, xhigh default, marker cap and retired-key warnings read correctly, and the Responses decode, the cap and the default each have a test that would fail without the change.
Head moved during this review. The branch was rebased to
ab25fdf7and gained6c7cbc6d("make a null engine match an absent one, and correct the hold-duration docs"). Nothing below changes at that head:6c7cbc6dtouchesConfigure's null-engine default and the four hold-duration doc passages (which resolves the "12 minutes" item from earlier rounds — thank you), not the new incoming-Anthropic asker. The next cycle reviewsab25fdf7as a delta.
Two must-fixes, both inline:
- must-fix — the new
prefixAskerimplementsAsk+CoversSpanbut notcomponents.PrefixCoveredAsker.AskCovered. On Anthropic this asker is the summarizer's only path (usePrefixAskis true for every Anthropic incoming-model request), and that call runs detached, so the summarizer falls back to its two-read check-then-ask branch — the one its own comment warns about and the engine's proxy implementsAskCoveredto avoid. A one-shot request finishing inside theCoversSpan+Askwindow makes the ask go out over a body the check never approved; the reply becomes a checkpoint for a span the model never read. Fix is small and the proxy is the model. - must-fix —
CLAUDE.md:271still says the keeper holds "no content", contradictingrecordFor'sBody: pctx.Bodyanddocs/session-api.md:414. This delta rewrote that paragraph (and the sentence survives the rebase), so the wrong claim is new text.
Suggestions inline: the oauth-beta fill is frozen per credential rather than per request; Codex's /backend-api/codex/responses is not gated; v0.7.7's tag was moved, so the pinned version is not immutable. A one-word comment nit on profiles.go.
Still open from earlier rounds, not repeated inline:
- must-fix — the upgrade note for the
preset: balanced→preset: xhighdefault. Any context-guru install with noengine:key now runscache_aware_summarizer,extract_llmandextract_llm_sweep, and on Anthropic they call the model on the caller's own credential. This PR's body has no upgrade note; #2059's body shows the pattern. - suggestion (huang195) — no hold when no component needs a model; a 1 h bound on the stash; and
credKeyhashing the raw credential rather than reusingcredID's masking.
Author: boazdavid (CONTRIBUTOR — returning external, elevated scrutiny)
Areas reviewed: Go (core/plugins/contextguru — incoming_anthropic.go, plugin.go, dispatcher.go, keepalive.go), docs (CLAUDE.md, docs/*), scripts/profile-tags, dependency metadata (core/go.mod / go.sum against the checksum database)
Agent/IDE config (.claude/.vscode): none (gate run over the PR diff: no matches, including renames)
Commits: 3 in this layer (16 in the PR), all signed off, DCO passing
CI status: pending at 1e32f72c — DCO success, 35 queued, 2 skipped, 1 neutral; no Go job has finished
Not checked:
go build,go vet,go test—modernc.org/sqlite v1.56.0's zip is absent from the module cache andproxy.golang.org's zip endpoint fails TLS from this sandbox (unexpected eof while reading), socore/plugins/contextgurucannot compile here; §3.12 rules out fetching a toolchain to make a probe run.- A live Anthropic call on an OAuth token, and the Responses path end to end — no credential or upstream in this sandbox.
Verified by: sum.golang.org/lookup/github.com/rossoctl/[email protected] → h1:dmVlQ…; gh api repos/rossoctl/context-guru/git/tags/f03d2f88 → commit 30a80767; a go build of core/plugins/contextguru with a local replace at commit 23a4b03 → checksum mismatch: downloaded h1:6j+87… vs go.sum h1:dmVlQ…; the library read at 23a4b03 (apply/opts.go:130, components/component.go:316,326, components/offload/cache_aware_summarizer.go:813,938-945, proxy/prefixask.go:240,272); gofmt -l over core/plugins/contextguru, scripts/profile-tags and cmd/cortex/local.go (empty); git grep for Body: in keepalive.go and for .claude/.vscode in the diff. The worktrees, the module replace and the context-guru clone were deleted afterwards.
Generated by repoman github-pr-review@af425c8.
| cli cheapmodel.Anthropic | ||
| } | ||
|
|
||
| func (p prefixAsker) Ask(ctx context.Context, session, ask string) (string, cgcomponents.PrefixUsage, error) { |
There was a problem hiding this comment.
must-fix — prefixAsker must implement components.PrefixCoveredAsker.AskCovered; without it the coverage check and the ask read the stash twice, which is the race this stash exists to prevent.
On Anthropic this asker is the summarizer's only path: cheapmodel.Anthropic has no MessagesModel, so usePrefixAsk := mm == nil && c.PrefixAsk != nil is true on every request (context-guru components/offload/cache_aware_summarizer.go:813), and the call runs detached (startAsyncSummary). With Ask + CoversSpan only, the summarizer takes its two-read branch (:938-945), and that branch's own comment says why it is unsafe:
Check and ask on ONE read of the stash when the asker can: this call runs detached, and the thread's next request can replace the stashed body between a separate CoversSpan and Ask.
Concrete case. Turn N commissions a summary with requiredCount/requiredHash for its span. CoversSpan selects the entry, then normalizes and hashes preBody outside the lock (:333-346) — tens of milliseconds on a large transcript. In that window a Claude Code one-shot call (title / permission monitor — the pendingBody comment above says these share the main turn's session id) finishes, and stashSent replaces the entry with its short body. Ask then re-reads the map via sentStash.get and sends the one-shot body with the summarizer's question appended. The reply is stored as the checkpoint for turn N's span: a checkpoint claiming a span the model never read, which is exactly the silent context loss the pendingBody comment says this stash was built to avoid.
Suggested fix: give sentStash a one-snapshot method and implement the interface. The engine's own proxy is the model — snapshotCovering selects the entry once, checks coverage against its preBody, and returns its own forwarded (proxy/prefixask.go:240), and AskCovered calls CompletePrefixed on that body (:272). Here that is a snapshotCovering(session, count, hash) ([]byte, error) over sentStash (returning ErrNoPrefix for a missing session and ErrStalePrefix for a short one) plus an AskCovered on prefixAsker. The library's afterEntryRead hook in snapshotRead is the seam it uses to test this exact interleaving; there is no equivalent test here.
| per-thread billing mode and pending ping facts in `core/accounting.Host`, the | ||
| context-guru keeper's entries, the context-guru incoming-model credential holds and | ||
| forwarded-body stash, and the context-guru plugin's session state in | ||
| `~/.cortex/context-guru-state.db`. The accountant state and the keeper hold session and thread |
There was a problem hiding this comment.
must-fix — the keeper does hold content, and this sentence says it does not.
recordFor puts Body: pctx.Body on the keepalive.Record (core/plugins/contextguru/keepalive.go:134), masked, and every ping re-sends it. docs/session-api.md:414-416 in this same PR says so plainly — "A keeper entry does hold content: … forwarded conversation, both masked" — and docs/laptop-service.md says "the thread's last request body (the whole conversation)". Only CLAUDE.md now omits it, and this delta rewrote this paragraph, so the omission is new text rather than a stale line. This is the finding raised last round, surviving the rewrite.
It matters beyond accuracy: this paragraph is the reference an operator reads before deciding whether DELETE /v1/sessions leaves conversation text on disk, and the same paragraph already exists to answer that.
Suggested fix: "The accountant state holds session and thread ids, content hashes and a billing mode, no content. A keeper entry also holds the caller's credential, masked, and the thread's last request body — the whole forwarded conversation, masked."
| auth = append(auth, heldHeader{name: name, val: b}) | ||
| } | ||
| } | ||
| authBeta := tooldefer.AuthBetas(reqHeaders.Values("Anthropic-Beta")) |
There was a problem hiding this comment.
suggestion — the oauth-beta fill is captured per credential-first-use, not per request, so a session whose first request carried no oauth-* beta never sends one.
authBeta is read here, when the dispatcher entry is created. credHolds.hold reuses that entry for every later request whose credKey matches, and credKey digests scheme, host and the auth-header values only (incoming_anthropic.go:144-159) — a different Anthropic-Beta does not create a new hold, and nothing updates heldTarget.authBeta on reuse.
Concrete case: request 1 on a Claude subscription carries only non-oauth betas (tooldefer.AuthBetas filters everything without the oauth- prefix, so authBeta == ""); request 2 carries oauth-2026-01-01 and reuses the hold, so Do sets nothing and the incoming-model call 401s — the silent fail-open this change exists to remove — for up to incomingHoldTTL (2 h). The docs state the behaviour per request ("The request's own Anthropic-Beta oauth-* values are held too and sent on the call when cheapmodel set none"), which this does not deliver in that case.
Suggested fix: refresh the held beta on reuse when the new request's value is non-empty (d.setAuthBeta(ref, beta) beside Release), or fold the beta into credKey so a differing beta gets its own hold. Otherwise narrow the doc sentence to "the values the first request on that credential carried".
| // context-guru-proxy has no equivalent knob either -- it hardcodes its own routes | ||
| // (/openai, /anthropic, /healthz, /stats, /expand) the same way, because the whole point of | ||
| // that binary is to always run the engine on them. See gated. | ||
| var inferencePaths = []string{"/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses"} |
There was a problem hiding this comment.
suggestion — /v1/responses is gated, but not the Responses path Cortex itself recognises.
gated matches by suffix (:913-921) and dialectFor likewise (:937-945), so this list covers only paths ending /v1/responses. Cortex's own inference parser matches the last segment — responsesSuffix = "/responses" — deliberately, so Codex's chatgpt.com gateway at /backend-api/codex/responses is read as Responses (core/parse/inference/dialect.go:37, core/listener/forwardproxy/upgrade.go:35). A Codex request on that path is a Responses body cortex parses, but gated() returns false and context-guru does nothing on it. TestDialectFor covers /v1/responses and /openai/v1/responses only, so it cannot catch the gap.
Suggested fix: match /responses the way the parser does (or add the Codex prefix), and add /backend-api/codex/responses to TestDialectFor so the next reader sees the intended scope.
| github.com/open-policy-agent/opa v1.22.4 | ||
| github.com/rossoctl/accountant v0.5.0 | ||
| github.com/rossoctl/context-guru v0.7.4 | ||
| github.com/rossoctl/context-guru v0.7.7 |
There was a problem hiding this comment.
suggestion — v0.7.7 is not an immutable version: the tag was moved after the proxy cached it, so CI and a GOPROXY=direct build compile two different trees.
sum.golang.org/lookup/github.com/rossoctl/[email protected]returnsh1:dmVlQxu3vZtaHe1OuBy80RWnyt+dzxr36skd+IO+IYg=— this go.sum line — which is commit23a4b03(the proxy'sv0.7.7.info). That is what CI builds.- GitHub's tag now dereferences to commit
30a80767(git/tags/f03d2f88→30a80767), two commits later:d0dea8bb(test timing) and30a80767(release.gitignore). - Building the moved tag against this go.sum fails, reproduced here:
go: github.com/rossoctl/[email protected]: checksum mismatch / downloaded: h1:6j+87kuCN780fTDykq9aiG8gNmG3omVC4rmGG0a01/0= / go.sum: h1:dmVlQxu3….
The two extra commits touch only tests and .gitignore, so the API this PR uses is identical in both trees — nothing is broken today. But every build that resolves the tag directly (GOPROXY=direct, a warm direct-mode module cache, GOPRIVATE) fails verification, and "v0.7.7" no longer names one tree.
Suggested fix: have context-guru cut an immutable v0.7.8 at 30a80767 and bump to it here with go mod tidy, rather than leaving a re-tagged version pinned.
| // Artifact contents: | ||
| // | ||
| // local desktop cortex — the three parsers, tool-prune and script | ||
| // local desktop cortex — the three parsers, tool-prune, context-guru and script |
There was a problem hiding this comment.
nit — the artifact-contents line below (line 44) still says full is "all seventeen", but this change adds contextguru to full as well, which makes it eighteen; TestTags_ReproduceTodaysDefaults lists eighteen tags for full. One-word fix.
ab25fdf to
dfd0565
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Reviewed this layer only at dfd0565c — this PR's four commits over cg/07-local-default-on (e572704d) — with the new commit as the delta over the head I first read. Both must-fixes from the last pass are closed, and closed properly:
components.PrefixCoveredAsker—sentStash.getCoveredchecks coverage and returns the entry'sforwardedunder one lock,prefixAsker.AskCoveredcalls it, andvar _ cgcomponents.PrefixCoveredAsker = prefixAsker{}makes a future signature drift a compile error. Thecount >= 0guard keeps thenorm[:count]slice safe on the negative case, andErrNoPrefix/ErrStalePrefixare the two errors the engine's ownsnapshotCoveringreturns.TestPrefixAskerAskCoveredpins both, plus the covered case against a livehttptestupstream.CLAUDE.mdnow separates the two: "The accountant state holds session and thread ids, content hashes and a billing mode, no content. The keeper DOES hold content …", which matchesrecordFor'sBody: pctx.Bodyanddocs/session-api.md.
The rebase also brought in #2059's fuller hold paragraph, so the "12 minutes" item that survived the last rewrite is gone from this branch too — with one residue: the four-count list still includes "24 waiting on background work", which cannot occur in Cortex (recordFor leaves OpenTasks nil, the keeper is built with Dispatcher only). That is inline on #2059 and not repeated here.
Two nits inline. Nothing blocking.
Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (core/plugins/contextguru: incoming_anthropic.go, keepalive_test.go), CLAUDE.md, docs, against rossoctl/context-guru v0.7.7
Agent/IDE config (.claude/.vscode): none (checked the PR's changed-file list)
Commits: 18 in the PR, all signed off: yes (DCO passes)
CI status: pending at dfd0565c — DCO passed, 35 queued, 3 skipped
Not checked:
go build,go vet,go test,-race—modernc.org/sqlite v1.56.0's zip is not in the module cache andproxy.golang.org's zip endpoint fails from this sandbox (net/http: TLS handshake timeout); §3.12 rules out fetching a toolchain to make a probe run- A live Anthropic call on an OAuth token, and the Responses path end to end
Still open from earlier rounds (unchanged here, so not repeated inline): the oauth-beta fill being frozen per credential rather than per request; /backend-api/codex/responses not being gated; v0.7.7's moved tag; scripts/profile-tags/profiles.go still saying "all seventeen" for full.
Verified by: gofmt -l over core/plugins/contextguru (empty at this head); source read of getCovered/AskCovered and the engine interface at v0.7.7 (components/component.go, proxy/prefixask.go:240-272); git grep for .claude/.vscode over the PR's file list. The worktrees were deleted afterwards.
Generated by repoman github-pr-review@af425c8.
| // a no-op: injectDefaultCacheStrategy must not add a cache: key to a null engine. | ||
| // engine: null must not panic (the original finding) and must not diverge from an absent | ||
| // engine: either (review finding, a second pass over the first fix): both reach Configure's | ||
| // own default-to-balanced path, so both build a keeper under keep-alive's on-by-default rule, |
There was a problem hiding this comment.
nit — the comment says "both reach Configure's own default-to-balanced path", but this layer changed the default to preset: xhigh (plugin.go:414). The assertion below is still right (both build a keeper); only the word is stale, and it is the sentence a reader uses to decide whether the two cases are meant to be identical.
Suggested fix: "both reach Configure's own default (preset: xhigh) path".
| norm := apply.NormalizeMessages(bschemas.Anthropic, []byte(`{}`)) | ||
| hash := cgcomponents.SpanHash(norm[:0]) | ||
|
|
||
| if _, _, err := a.AskCovered(context.Background(), "k", 0, "wrong-hash", "summarize"); !errors.Is(err, cgcomponents.ErrStalePrefix) { |
There was a problem hiding this comment.
nit — the test covers ErrNoPrefix and a hash mismatch, but not the other half of getCovered's staleness condition: count > len(norm), the short-body case, which returns ErrStalePrefix from a different line than the hash comparison. A one-line case (a.AskCovered(ctx, "k", len(norm)+1, hash, …)) pins it; without it, deleting that clause still passes.
Suggested fix: add the case to TestPrefixAskerAskCovered, beside the hash-mismatch one.
…marker cap and xhigh from rossoctl#1412 Take the rossoctl#1412 work into context-guru. Add the Anthropic incoming-model path (incoming_anthropic.go): read the request's own model, cap the markers, and default the effort to xhigh. Handle the Responses shape. Fill the oauth-beta header in the dispatcher. plugin.go and the dispatcher route the new incoming model; the tests cover the Responses decode, the marker cap and the xhigh default. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…model dispatcher Left referencing the pre-rename p.local during the previous commit's rebase, so the build broke. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
main now runs check-test-timing in pre-commit and CI (rossoctl#2080), which flagged TestStartSweepReleasesAlreadyExpiredHoldWithNoRequest's polling loop: it waited on the sweep goroutine's first releaseExpired with no event to block on. startSweep's own doc already promises the first pass "runs immediately"; running it synchronously, before the periodic goroutine starts, keeps that promise exactly and also closes a real race for production callers: a credential hold expired before Init can otherwise outlive startSweep's return until the next tick or a request arrives. The test now checks the hold is gone right after startSweep returns, no wait needed. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…rrect a stale "no content" claim Must-fix (clawgenti): usePrefixAsk makes prefixAsker the engine's only PrefixAsker on Anthropic, and that call runs detached -- so without components.PrefixCoveredAsker, the engine's own fallback is a CoversSpan check followed by a separate Ask, reading sentStash twice. A one-shot request finishing inside that window replaces the stashed entry between the two reads, and the ask then goes out over a body the check never approved: exactly the race AskCovered exists to close. sentStash.getCovered checks coverage and reads the entry under one lock; prefixAsker. AskCovered calls it instead of CoversSpan-then-Ask. A compile-time assertion pins the interface, and TestPrefixAskerAskCovered pins ErrNoPrefix, ErrStalePrefix and the covered case. Must-fix (clawgenti): CLAUDE.md said "the accountant state and the keeper hold ... no content", contradicting recordFor's Body: pctx.Body (and docs/session-api.md, which already says the keeper does hold it). Split the sentence: the accountant state holds no content, but the keeper holds the caller's credential AND the thread's last request body, both masked. Also added the upgrade note the PR body was missing: an install with no engine: key now defaults to preset: xhigh rather than balanced, which turns on model-calling components that, on Anthropic, call the model on the caller's own credential. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I reviewed only this layer, e572704...dfd0565 (#2060's head through this PR's head, 4 commits, 11 files). git range-diff against the layer from the last round (b168e08..1e32f72) shows 9c024ab and 035ae30 as =. 172d284 changed only where it absorbed the base's null-engine default and the hold-duration docs. The new commit dfd0565 fixes both must-fix findings from the last round, and the PR body now has the upgrade note:
AskCoveredis implemented correctly.sentStash.getCoveredfollows the library's ownproxy/prefixask.gosnapshotRead(context-guru v0.7.7):ErrNoPrefixfor a missing entry,ErrStalePrefixfor a short or mismatched span, andcount < 0skips the check.putnever stores an emptyforwarded, sogetCovereddoesn't need the library's extralen(e.forwarded) == 0check. Both callers now use the single-read path: the summarizer's detached call (cache_aware_summarizer.go:934) andextract_llm_sweep(extract_sweep.go:949, whenever its guard sethaveCover). The compile-time assertionvar _ cgcomponents.PrefixCoveredAsker = prefixAsker{}keeps the interface from going missing silently again.CLAUDE.mdnow says the keeper holds the masked credential and the thread's last request body, which matchesrecordFor'sBody: pctx.Body,docs/session-api.mdanddocs/laptop-service.md.- The upgrade note covers the
balancedtoxhighdefault, including an empty ornullengine:, and tells users how to opt out.
Nothing blocks. One suggestion is inline: getCovered normalizes under the stash lock, while the library and this file's own CoversSpan normalize outside it.
Still open from earlier rounds, all non-blocking and not repeated inline:
- suggestion: the dispatcher records the oauth-beta fill on a credential's first use, not on each request (
dispatcher.go:104-112). A hold that is reused never refreshesauthBeta. - suggestion: only
/v1/responsesis gated (plugin.go:161,:951). Cortex's own parser matches/responses, which includes Codex's/backend-api/codex/responses. - suggestion (huang195): take no hold when no component needs a model, put a time bound on the stash, and have
credKeyreusecredID's masking. - nit: a second
Configurereleases the old holds withoutstopSweep()(plugin.go:531-534), so the old sweep goroutine keeps running.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru: incoming_anthropic.go, plugin.go, dispatcher.go, keepalive.go, tests), docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md), checked against context-guru v0.7.7 (components/component.go, components/offload/cache_aware_summarizer.go, components/offload/extract_sweep.go, proxy/prefixask.go)
Agent/IDE config (.claude/.vscode): none (gate run over the full PR diff, renames included)
Commits: 4 in this layer, all signed off, DCO passing
CI status: DCO passes. Every other job was still pending when I posted, so I ran the checks below locally.
Verified locally on dfd0565, GOWORK=off, in core:
gofmt -l plugins/contextguruis empty, andgo vet ./plugins/contextguru/is clean.go build ./...passes, andgo vet ./...is clean incmd/cortex.go test -race -count=1 ./plugins/contextguru/...passes.go test -race -count=20 -run 'PrefixAsker|Sweep|Stash' ./plugins/contextguru/passes.- A throwaway probe (deleted afterwards) ran
getCoveredon an 8 MB, 1,800-message stashed body. Normalizing it took 162 ms, and a concurrentputfor a different session waited 134 ms on the lock (see inline).
| return nil, cgcomponents.ErrNoPrefix | ||
| } | ||
| if count >= 0 { | ||
| norm := apply.NormalizeMessages(e.provider, e.preBody) |
There was a problem hiding this comment.
suggestion: normalize outside the lock, the way CoversSpan above and the library's snapshotRead (proxy/prefixask.go:255-262) do.
getCovered holds s.mu through apply.NormalizeMessages and SpanHash of preBody, which can be up to maxStashBody (8 MB). s.mu is the one lock for the whole stash. While a detached summary or sweep ask runs this check, every put waits, and so do get and CoversSpan for every other session. put runs from stashSent in OnFinish on every main-agent request. I measured this with a throwaway probe: an 8 MB, 1,800-message body took 162 ms to normalize, and a put for an unrelated session waited 134 ms.
Releasing the lock early doesn't reopen the race. put never mutates an entry. It installs fresh slices, so the e copied out under the lock is a stable snapshot, and returning e.forwarded from that same copy still asks over exactly the body that was checked:
s.mu.Lock()
e, ok := s.m[session]
s.mu.Unlock()
if !ok {
return nil, cgcomponents.ErrNoPrefix
}
// e's slices are never mutated after put (a replacement installs new ones), so the body
// returned below is the one checked here.
if count >= 0 {
norm := apply.NormalizeMessages(e.provider, e.preBody)
...
}
return e.forwarded, nilThe function's doc comment would then say "from ONE read of the entry" rather than "under ONE lock".
dfd0565 to
bd53a64
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I re-reviewed after the stack was rebased onto #2060's new head (38f4c3d), which now includes 9e4d32f (drops the "24 minutes, background wait" hold figure). I reviewed only this layer, 38f4c3d...bd53a64. git range-diff against the layer I approved at dfd0565 shows d38eb89, f0f1611 and bd53a64 as =. cca26ec changed only in CLAUDE.md and docs/laptop-service.md, where it absorbs the base's doc fix. Outside the docs, the tree at bd53a64 is byte-identical to dfd0565: git diff dfd0565 bd53a64 touches only CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md and docs/session-api.md. Nothing in this layer blocks.
The doc merge is clean:
CLAUDE.mdanddocs/laptop-service.mdkeep this layer's additions (the incoming-model credential holds, released within 2h10m of last use, and the forwarded-body stash, up to 16 sessions and 96 MiB, with no time bound). They also carry the base's 12/16/36-minute figures and the note that the background-wait count never applies.- No "24 minutes" or "waiting on background work" hold figure is left anywhere in the tree's Markdown.
The non-blocking items from earlier rounds still stand, and I won't repeat them inline: the oauth-beta fill is recorded only on a credential's first use, only /v1/responses is gated, huang195's hold/stash/credKey suggestions, the getCovered normalize-under-lock suggestion, and a second Configure that doesn't call stopSweep().
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so treated as a maintainer)
Areas reviewed: docs (CLAUDE.md, docs/laptop-service.md, docs/context-guru-plugin.md, docs/session-api.md); Go in core/plugins/contextguru checked as unchanged from dfd0565
Agent/IDE config (.claude/.vscode): none (gate run over the full PR diff, renames included)
Commits: 4 in this layer, all signed off, DCO passing
CI status: DCO passes. Every other job was still pending when I posted, so I ran the checks below locally.
Verified locally on bd53a64, GOWORK=off, in core: gofmt -l plugins/contextguru is empty, go vet ./plugins/contextguru/ is clean, and go test -count=1 ./plugins/contextguru/... passes.
huang195
left a comment
There was a problem hiding this comment.
Summary
I reviewed this layer only (cg/07-local-default-on...cg/08-contextguru-1412-port at bd53a64b, 4 commits, 11 files). The upgrade note in the PR body closes my must-fix about the xhigh default. getCovered closes the check-then-ask race, and the CLAUDE.md "no content" text is correct again. I found no new must-fix.
These comments from earlier rounds are still open, with no reply: my 3 comments on incoming_anthropic.go (the hold when no component needs a model, the stash with no time bound, and credKey), and clawgenti's /responses suffix suggestion and the observe nit at line 383. I do not post them again. Please answer or fix each one.
Author: boazdavid (MEMBER, maintainer)
Areas reviewed: Go (core/plugins/contextguru), docs
Agent/IDE config (.claude/.vscode): none
Commits: 4 in this layer, all signed off
CI status: pending (1 pass, 35 pending, 3 skipped)
Not checked: go test (I did not build), a live Anthropic incoming-model call, and an OAuth token.
Assisted-By: Claude (Anthropic AI) [email protected]
| ping re-sends), both masked. The incoming-model holds (one per distinct host+credential, across every | ||
| session that uses it) also hold a masked credential, released on a timer at most | ||
| `holdSweepInterval` (10m) past `incomingHoldTTL` (2h) idle, whether or not any later request | ||
| arrives. The forwarded-body stash DOES hold content — the last body sent upstream, for up to 16 |
There was a problem hiding this comment.
nit: This paragraph now gives the hold and stash details (10m, 2h, 16 sessions, 96 MiB, eviction order). Every Claude Code session loads the root CLAUDE.md, and docs/session-api.md already has the same text. Please keep one clause here ("the incoming-model holds and the forwarded-body stash, which holds content") and link to docs/session-api.md#delete-v1sessions.
|
|
||
| **The request's own model (`model.source: incoming`).** A component configured with `model.source: incoming` calls the model the agent itself is using, on the agent's own credential. OpenAI Chat Completions only: through `llmclient`, on the request's endpoint and `Authorization`. On other dialects the component uses the `model` block, or degrades to deterministic. Each such call is reported to the request it was made for as a spend op (`pluginSpendMicros`). A call that returns after its request was accounted is dropped and counted in the `late_model_calls_dropped` metric. | ||
| - **OpenAI Chat Completions:** through `llmclient`, on the request's endpoint and `Authorization`. | ||
| - **Anthropic Messages** (`/v1/messages`, Claude Code's traffic): through context-guru's `cheapmodel.Anthropic`, on the request's endpoint and credential (`x-api-key` or `Authorization`). The credential is held in memory, masked, one hold per credential, and released 2 hours after its last use (on a timer, not only on the next matching request), on a config reload, or at `Shutdown`. The request's own `Anthropic-Beta` oauth-* values (`tooldefer.AuthBetas`) are held too and sent on the call when `cheapmodel` set none: a Claude subscription (OAuth) token can need one to authenticate directly against `api.anthropic.com`, and without it the call 401s — failing open, but silently, since the summarizer then does nothing that turn. It is held, not borrowed, because `cache_aware_summarizer` commissions its call in the background and the request returns first. On Anthropic the summarizer asks one question appended to the previous turn's forwarded body, so the provider's prompt cache serves the whole transcript. The plugin keeps that body in memory for the last 16 sessions (main agent only, a 200 response only, at most 8 MiB per body and 96 MiB in total). |
There was a problem hiding this comment.
nit: "released 2 hours after its last use" is not exact. The sweep runs every 10 minutes, so a hold can stay up to 2h10m. docs/laptop-service.md and docs/session-api.md say this. Please write "within 2h10m of its last use" here too.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Reviewed this layer only. Since the pass at dfd0565c, the layer's Go tree is byte-identical: git diff dfd0565 bd53a64 touches only CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md and docs/session-api.md, and the difference is the rebase absorbing the base's hold-figure correction (no "24 minutes / waiting on background work" figure remains).
I checked the corrected claim against the code rather than the prose: the keeper is built with keepalive.Options{Dispatcher: p.disp} (core/plugins/contextguru/plugin.go:471), OpenTasks is left nil by design (core/plugins/contextguru/keepalive.go:120), and recordFor writes no open-task data, so the engine's background-wait count cannot apply and the 12/16/36-minute figures are the reachable set. The doc text says exactly that, in all four files.
Nothing in this layer blocks. The non-blocking items from earlier rounds still stand and are not repeated inline (the oauth-beta fill frozen per credential, only /v1/responses gated, the getCovered lock suggestion, the second Configure not calling stopSweep(), and huang195's hold/stash/credKey suggestions).
Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Docs delta (CLAUDE.md and three docs), against the Go at head (core/plugins/contextguru/plugin.go, keepalive.go)
Agent/IDE config (.claude/.vscode): none (no matches in the PR diff or this layer's diff, renames included)
Commits: 19 in the PR, all signed off: yes (DCO passes)
CI status: queued at bd53a64b — DCO passed, 35 jobs queued, 2 skipped, 1 neutral
Not checked:
go build/go vet/go test/-raceat head — the local module cache'scontext-guru v0.7.7zip does not matchgo.sum(checksum mismatch,SECURITY ERROR), and §3.12 forbids fetching a replacement- A live Anthropic call and the Responses path end to end
Verified by: git diff dfd0565 bd53a64 (four docs files only), a read of keepalive.Options construction and keepalive.go:120 against the new doc text. The worktree was removed afterwards.
Generated by repoman github-pr-review@af425c8.
The macOS job has a 10-minute limit. It now takes 6-8 minutes on main and 9-10 minutes on PRs, so a slow runner cancels it (#2061). The cmd/agentop/tui tests took 293 s of that time with -race. The tui package has no macOS-specific code, and the Linux agentop job runs it with -race on every PR. This is the same rule that the job already uses for tlsbridge. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Stacked on: #2060
Required by: #2062
Review only this PR's change: boazdavid/cortex@cg/07-local-default-on...cg/08-contextguru-1412-port (the diff against
mainalso shows every PR below it until those merge)Part of the
[cg]series that replaces #1956, #1958 and #2053, split into reviewable layers. Merge in the order below.main, not in this series)What
Take the #1412 work into context-guru. Add the Anthropic incoming-model
path (incoming_anthropic.go): read the request's own model, cap the
markers, and default the effort to xhigh. Handle the Responses shape.
Fill the oauth-beta header in the dispatcher.
plugin.go and the dispatcher route the new incoming model; the tests
cover the Responses decode, the marker cap and the xhigh default.
Upgrade note
An install with no engine: key at all (or an empty/null one) now defaults to preset:
xhigh instead of preset: balanced. xhigh adds the model-calling components
(cache_aware_summarizer, extract_llm, extract_llm_sweep): where a model client resolves (a
cheap_model: block, or -- on Anthropic -- the request's own model through the new incoming-model
path), these call that model, on Anthropic using the caller's own credential, and each call is
billed and reported as a KindSpend op the same as any other context-guru model call. To keep the
old behaviour, set engine.preset: balanced explicitly before you upgrade.
Testing
GOWORK=off, incore,cmd/cortex(plain and with thelocalprofile tags),cmd/cortex-envoy,cmd/agentop,scripts/profile-tagsandscripts/readme-demo:gofmt -lempty,go vet ./...clean,go mod tidy -diffclean,go test ./...passes.mainalike, from the local America/Havana time-zone data:TestMidnightTransitions_EveryFixtureIsStillTheDayItClaimsToBe(core/cost/ledger),TestStartOfLocalDay_PicksTheEarlierOfTwoMidnightsandTestParseWindowSpec_TodayStartsWhereTheLocalDayStartsInEveryZone(core/cost/usage).Assisted-By: Claude (Anthropic AI) [email protected]