Skip to content

feat: hosted TLS service, and survive the agent's own context compaction - #67

Merged
OsherElhadad merged 6 commits into
mainfrom
feat/hosted-tls-and-agent-compaction
Aug 16, 2026
Merged

OsherElhadad merged 6 commits into
mainfrom
feat/hosted-tls-and-agent-compaction

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

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 sums
input_tokens + cache_creation + cache_read + output off the last assistant message
(eC/w0e); Bob reads usage.prompt_tokens into lastPromptTokenCount. 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:

  • Claude Code's threshold cannot be raised — every knob goes through Math.min. Bob's
    can (model.compressionThreshold, unclamped).
  • Suppressing compaction by under-reporting usage would work — Claude Code validates
    it not at all — and we refuse to. Those same fields feed the user's /cost, the
    statusline, and the client's own hard-limit check; lying means the user gets
    prompt_too_long instead of a summary, with the safety check disabled. It is recorded as
    refused 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.

/stats and /metrics were public. They are service-wide aggregates over every
tenant, 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 /stats returned 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
maxCachedIdx at 49 and froze the entire new transcript permanently. Both boundary
paths now reset on a shrink, surfaced as compaction_resets on /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

  • An env block in ~/.claude/settings.json silently overrides an exported
    ANTHROPIC_BASE_URL.
    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.
  • Port 4000 is now permanently owned by the service, so the benchmark harnesses' hardcoded
    port died with bind: address already in use, every container got Connection refused,
    and the summary reported solved: 0 — indistinguishable from a model failure. Both
    harnesses now take CG_BENCH_PORT and 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 the
reason is structural:

total_cache_read   8,856,812
total_cache_write    202,685
total_fresh_input        258

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_llm made 0 calls across 136 runs
(cached_prefix gate); forced past that guard it spent 14.7s and $0.0076 to save zero
tokens.

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 vet clean; go test -race ./... green across 23 packages
  • mkdocs build --strict clean
  • deploy/service/tls-smoke.sh: 19/19 against the live service
  • Chain verifies to the internal root CA, TLS 1.3 + HTTP/2, Secure + HttpOnly on the
    session cookie, SSE streaming through nginx
  • Registration attack-tested: manager email unclaimable (409), lookalike domain rejected
    (403), rate limited, malformed input 400 with no partial tenant created
  • Full new-user flow end to end: register → token → Claude Code → savings → diffs, with
    real multi-turn coding tasks
  • No credential in the tree: one synthetic cg_live_ fixture asserting rejection, no key
    material, no provider keys

Breaking / operational notes

  • feat(proxy)! — hosted mode is off unless --upstreams is given, so single-tenant
    deployments and deploy/harbor/* are unchanged. /stats in single-tenant mode keeps its
    existing open posture.
  • New tenants default to deterministic codesmart (no cheap-model calls, so no added
    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.
  • nginx has no port 80 block, deliberately: a redirect cannot retract a token already
    sent in cleartext.

Known gaps, not fixed here

  • Bob can never expand <<cg:HASH>> markers — it sends no tools array and parses tool
    calls 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 add mask for long Bob sessions is wrong.
  • Bob's other same-endpoint side-prompts (shell-safety judge, PR description, web-fetch
    summarizer) are still compacted.
  • In observe mode a bypassed request is not measured and its counter lands in the
    hypothetical namespace.
  • extract_llm's context guard defaults to a 32k budget, so it cannot fire on a genuinely
    8k-window extraction model without an explicit model_max_input_tokens.

Osher-Elhadad 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
OsherElhadad merged commit 3fabf51 into main Aug 16, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 16, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant