Repository navigation
feat: hosted TLS service, and survive the agent's own context compaction - #67
Merged
Merged
Conversation
added 6 commits
August 16, 2026 07:47
Claude Code and Bob both compact their own conversation when context fills.
Both compute the trigger from the API response's usage rather than a local
count of their transcript, so our reduction already delays it — but three
things went wrong when it fired.
We compacted the compactor. The pipeline ran on the agent's own
summarization request, so the summarizer was asked for verbatim fidelity
("full code snippets", "preserved verbatim") over text we had already
replaced with <<cg:HASH>> stubs. Unrecoverable, because the agent then
discards the pre-compaction history. Detect it on the LAST user message only
and forward byte-identical; last-message scoping is what stops the phrase
latching for the rest of the session.
We could disable Claude Code's auto-compact for a whole session. The expand
tool was advertised whenever a request carried tools, including the
compaction request, so an unresolvable call made the summary read as empty —
and three failures trip a circuit breaker that turns auto-compact off, after
which the agent walks into the upstream's hard prompt_too_long. Advertising
and interception are now one condition: both require markers.
One conversation showed up as two sessions, because the derived session id is
sha256(system+firstUser) and compaction changes the first user message. Read
the id the agents already send — metadata.user_id for Claude Code (a JSON
object needing session_id unwrapped, not a bare uuid), metadata.taskId for
Bob — ahead of the derived fallback.
That last fix then exposed a worse bug: the cached-prefix boundary only ever
grew, so with a stable id a transcript shrinking 50 messages to 5 left
maxCachedIdx at 49 and froze the whole new transcript permanently. Route both
boundary paths through modes.Boundary, which restarts the prefix on any
shrink. Frozen decisions and result caches are content-hash keyed and stay
valid, so history remains readable and expandable; only the position-encoded
boundary resets. Surfaced as compaction_resets on /stats.
A bypassed turn now records its length too. The provider caches whatever we
forward, so skipping the record left the next turn rewriting messages the
provider had just cached and paying a full cache-write — the cost of a
false-positive bypass was never confined to the bypassed request.
Signed-off-by: Osher-Elhadad <[email protected]>
… end created Adds the hosted control plane: token-authenticated tenants, per-tenant pipelines and stores, an upstream allow-list (names only — a user never supplies a URL, which is the difference between a proxy and an unauthenticated forwarder), per-tenant spend caps, rate limits and a Prometheus exporter. Off unless --upstreams is given, so single-tenant deployments and the benchmark harnesses are unchanged. Two things only became wrong once nginx terminated TLS in front, and both were found by probing the deployed service rather than by reading code. /stats and /metrics were readable by anyone on the network. They are service-wide aggregates over every tenant, gated on the caller being on this host — but behind a reverse proxy EVERY request has a loopback peer, so the gate stopped meaning anything the moment it was deployed. Observed live: an unauthenticated GET /stats returned the full rollup. A loopback peer is now trusted only when it did not relay someone else, using the forwarded headers as the tell; that direction is safe because a remote caller cannot forge a loopback RemoteAddr. Fails closed: a front end that sets none of those headers loses /stats rather than silently exposing it. Local ops and the Prometheus job on 127.0.0.1:4000 send no forwarded headers and keep working, and MetricsToken still allows a remote scrape. The 502 body echoed err.Error(), which for http.Client is a *url.Error stringifying as `Post "<full upstream URL>": ...`. That handed every caller the operator's upstream address, and would have handed them a credential too: checkBaseURL rejects userinfo for hosted upstreams, but the single-tenant --anthropic-upstream/--openai-upstream flags are not validated. The caller now gets a fixed string; the detail stays in the operator's log line. Signed-off-by: Osher-Elhadad <[email protected]>
…sfires extract_llm could send a prompt larger than its extraction model's window. The upstream 400'd, the error was discarded, and the output stayed verbatim — so it cost a round trip every turn and reported nothing. Pre-flight the shown-body token count against a per-model limit, reserve room for the reply, and decline with an over_model_context gate rather than putting an oversized request on the wire. No message is dropped and no user turn is touched: the component works one tool output at a time, so "shed older messages" had nothing to act on here. toon joins the codesmart default, and now refuses ambiguous arrays instead of silently changing their meaning — it was typed lossless while being lossy. failed_run's markers are anchored to line starts. Unanchored, they matched "FAILED" anywhere in a body, so ordinary source files were mislabelled as superseded test runs and dropped. cmdfilter's goal text is clipped on rune boundaries, not bytes. Signed-off-by: Osher-Elhadad <[email protected]>
Per-tenant scoping on every /api/* handler (set, never merged, so a crafted ?tenant= cannot widen it), per-tenant SSE topics, disk-pressure eviction with hysteresis, spend accounting, and migration of old sessions to cold storage so retention is bounded by the remote rather than this filesystem. The before/after diff is the point of the thing, so it is per request and per session, with exact ordered per-component attribution and the JSON path each change landed on. Cold content is fetched lazily — opening a session costs no remote call, clicking one costs exactly one. Two filter bugs made search unusable rather than merely awkward. State was rebuilt from the DOM, so the session filter was sticky and invisible and a manager's tenant filter was silently dropped; and each facet was scoped by its own column, which turned every dropdown into a one-way door that only Clear could undo. Both fixed at both layers. Also: a real race between /stats and the observe workers, which handed out the live gate histogram while it was being written; and several places where the dashboard asserted something false rather than admitting a gap — a "Messages rewritten: 0" that contradicted its own table, and an empty-state that deleted the evidence contradicting it. Signed-off-by: Osher-Elhadad <[email protected]>
…not lie deploy/service/ is the whole deployment: a cg system user, systemd units with credentials loaded from disk rather than the unit file, nginx terminating TLS, an optional Prometheus + Grafana pair, and cold-storage setup. nginx has deliberately NO port 80 block. Every request carries the user's token in a header, and a 301 to https arrives after the client has already put that credential on the wire in cleartext — a redirect cannot retract it. So a mistyped http:// must fail to connect, which is also what the granted firewall exception allows. install.sh now reports anything listening on 80, because the distro nginx.conf ships a default server there and a package upgrade can put it back. install.sh verifies the certificate rather than the existence of two files: it checks the key matches, that fullchain carries its intermediate (without it, browsers that cached the intermediate elsewhere succeed while every agent fails), and that expiry is more than 21 days out. Its subcommands now exit non-zero when they print a failure — `install.sh nginx && echo deployed` used to report success on a box with a broken chain and an open port 80. tls-smoke.sh checks the public path end to end, and every negative assertion goes through a reachability probe first. A check of the form "this request failed, therefore the server refused it" passes just as happily when the box is powered off, and an all-clear produced by the absence of a service is the worst output a smoke test can give. Both benchmark harnesses take CG_BENCH_PORT and refuse to start when the port is taken. The hosted service now owns 4000 permanently; when that clashed the harness proxy never started, every container got "Connection refused", and the summary reported solved=0 — indistinguishable from a model failure. Signed-off-by: Osher-Elhadad <[email protected]>
…loy the service Adds tenant/: the control database (tenants, tokens, per-tenant config, audit), token minting where only sha256(token) plus an 8-character display prefix is ever stored, and browser sessions. A new tenant TRACKS the server default rather than being stamped with a copy of it — copying froze every account on the default as it stood on their registration day, and there was no way to ask for "just follow the default". The default is deterministic codesmart: no cheap-model calls, so a new account adds no upstream spend and no latency to anyone else's agent. Transcript capture is on by default so the diff view works on the first request, and a tenant can turn it off; content is visible only to the tenant that produced it, never to a manager. Docs: a new "Connect to the IBM service" page — registration, the once-shown token, adding the internal root CA on a machine that does not already trust it, and the three agent setup blocks. Then the part people need day to day: turning the proxy on and off for ONE session without editing any config file, for both Claude Code and Bob, keeping the metrics while skipping the compaction, and a way to prove it is really on. That last part is not paranoia. An env block in ~/.claude/settings.json silently overrides an exported ANTHROPIC_BASE_URL, and the failure looks exactly like success: Claude Code answers normally, nothing errors, and the only symptom is an empty dashboard and zero savings because the traffic never arrived. The honest test is to point the client somewhere unroutable and confirm it FAILS. docs/how-to/agent-compaction.md records what the two agents actually do, with citations into the shipped clients, and is explicit about the two things the guard does NOT cover — an earlier draft described detection the code does not implement, which a reader would fairly have taken as shipped behaviour. It also states plainly that suppressing compaction by under-reporting usage would work, and that we refuse to, because those same fields feed the user's own cost display and the client's hard-limit check. Deployment steps are derived from the scripts rather than remembered, and include what to change outside IBM: certificate authority, firewall exception, registration policy, spend caps. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
pushed a commit
that referenced
this pull request
Aug 17, 2026
main carries #67 as a single SQUASHED commit, so the same changes exist here as their original commits with no shared ancestry - git reads them as independent edits to the same lines and reports 68 conflicted files. This branch already contains all of #67, so main's tree is the duplicate, not ours. That is only safe because main also had one commit we do NOT have (#65, fix(summarize)), and it is cherry-picked on top of this merge rather than resolved into it, so its content is auditable as its own commit instead of disappearing into a 68-file conflict resolution.
OsherElhadad
added a commit
that referenced
this pull request
Aug 17, 2026
…servability (#79) Lands the nine reviewed PRs (#69, #78, #71-#77) on main. Caller-pays credentials: each request's own provider key is forwarded upstream and a request without one is refused, so no account spends the operator's credential. The per-tenant spend cap goes with it. Email+password accounts with a mailed second factor, 14 confirmed security findings fixed with a failing test each, the rewrite path down from 15.6ms to 6.85ms per request with byte-identical output over 1,868 real captured requests, structured logging with credential scrubbing into Loki, request metadata and a Usage view, a redesigned dashboard, user feedback, full manager control over accounts, and Bob working through the proxy for the first time. Squashed because main carries #67 the same way, and because the nine merge commits GitHub generated for the stack carry no sign-off of their own; every authored commit in them does. The per-PR history stays on feat/hosted-tls-and-agent-compaction and in #69/#78/#71-#77. Signed-off-by: Osher-Elhadad <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this is
Turns context-guru into a hosted multi-tenant service — one instance, one hostname,
self-serve accounts, per-user dashboards — and makes it survive the agent's own context
compaction, which it previously did not.
Deployed and verified live behind TLS on 443 with an internally-issued certificate.
The headline finding
Claude Code and Bob both compute their auto-compaction trigger from the API response's
usage, not from a local count of their own transcript. Claude Code sumsinput_tokens + cache_creation + cache_read + outputoff the last assistant message(
eC/w0e); Bob readsusage.prompt_tokensintolastPromptTokenCount. Consequence:every token context-guru removes delays the agent's own compaction, honestly, with no
cooperation and nothing misreported. That was an unclaimed feature.
The evidence, with citations into both shipped clients, is in
docs/how-to/agent-compaction.md.Two things that page is deliberately blunt about:
Math.min. Bob'scan (
model.compressionThreshold, unclamped).usagewould work — Claude Code validatesit not at all — and we refuse to. Those same fields feed the user's
/cost, thestatusline, and the client's own hard-limit check; lying means the user gets
prompt_too_longinstead of a summary, with the safety check disabled. It is recorded asrefused because it is the obvious shortcut.
Bugs fixed, each found by probing rather than by reading
We compacted the compactor. The pipeline ran on the agent's own summarization request,
so the summarizer was asked for verbatim fidelity over text already replaced with
<<cg:HASH>>stubs — unrecoverable, since the agent then discards the original history.Fired on every compaction.
We could disable Claude Code's auto-compact for a whole session. The expand tool was
advertised on the compaction request; an unresolvable call made the summary read as empty,
and three failures trip a circuit breaker that turns auto-compact off, after which the
agent walks into
prompt_too_long./statsand/metricswere public. They are service-wide aggregates over everytenant, gated on the caller being on this host — but behind nginx every request has a
loopback peer, so the gate stopped meaning anything the moment TLS was terminated in front.
Observed live: an unauthenticated
GET /statsreturned the full rollup.A cache-write regression I introduced and then caught. Making the session id stable
across compaction (so one conversation is one session in the UI) exposed that the
cached-prefix boundary only ever grows: a transcript shrinking 50 messages to 5 left
maxCachedIdxat 49 and froze the entire new transcript permanently. Both boundarypaths now reset on a shrink, surfaced as
compaction_resetson/stats.The 502 body echoed the upstream URL — and would have echoed a credential with it, since
the single-tenant upstream flags are not validated for userinfo.
Two traps documented because they cost real time
envblock in~/.claude/settings.jsonsilently overrides an exportedANTHROPIC_BASE_URL. The failure looks exactly like success: Claude Code answersnormally, nothing errors, and the only symptom is an empty dashboard and zero savings,
because the traffic never arrived. The honest test is to point the client somewhere
unroutable and confirm it fails.
port died with
bind: address already in use, every container gotConnection refused,and the summary reported
solved: 0— indistinguishable from a model failure. Bothharnesses now take
CG_BENCH_PORTand refuse to start when the port is held.Benchmark result, stated honestly
Three-arm Terminal-Bench smoke (3 tasks): baseline
$2.9396,codesmart$4.109,codesmart_llm$3.1721. Compaction did not reduce cost on this workload, and thereason is structural:
258 fresh input tokens out of ~9.06M — 99.997% of input is already served from cache at
0.1×. The tokens available to remove are the cheapest in the bill, and removing them dirties
a prefix that re-bills at 12.5×. In the step-controlled arm (44.0 vs 45.3 steps) the
economics come out 5.7× underwater.
extract_llmmade 0 calls across 136 runs(
cached_prefixgate); forced past that guard it spent 14.7s and $0.0076 to save zerotokens.
Token reduction and provider prompt-caching are in direct competition, and on warm Claude
Code sessions the cache wins. A full 89-task run is not recommended.
Verification
gofmt/go vetclean;go test -race ./...green across 23 packagesmkdocs build --strictcleandeploy/service/tls-smoke.sh: 19/19 against the live serviceSecure+HttpOnlyon thesession cookie, SSE streaming through nginx
(403), rate limited, malformed input 400 with no partial tenant created
real multi-turn coding tasks
cg_live_fixture asserting rejection, no keymaterial, no provider keys
Breaking / operational notes
feat(proxy)!— hosted mode is off unless--upstreamsis given, so single-tenantdeployments and
deploy/harbor/*are unchanged./statsin single-tenant mode keeps itsexisting open posture.
upstream spend or latency for anyone else) and transcript capture on, so the diff view
works on the first request. Content is visible only to the tenant that produced it —
a manager sees everyone's metrics and nobody's transcripts.
sent in cleartext.
Known gaps, not fixed here
<<cg:HASH>>markers — it sends notoolsarray and parses toolcalls as XML from streamed text, so an injected tool is ignored while still costing a cache
prefix miss. Any lossy component mints permanently dead markers for Bob, and
docs/integrations.md' recommendation to addmaskfor long Bob sessions is wrong.summarizer) are still compacted.
observemode a bypassed request is not measured and its counter lands in thehypothetical namespace.
extract_llm's context guard defaults to a 32k budget, so it cannot fire on a genuinely8k-window extraction model without an explicit
model_max_input_tokens.