Skip to content

feat: context-guru. Integrate the accountant library for consistent savings pricing - #1956

Closed
boazdavid wants to merge 50 commits into
rossoctl:mainfrom
boazdavid:feat/accountant-integration
Closed

boazdavid wants to merge 50 commits into
rossoctl:mainfrom
boazdavid:feat/accountant-integration

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Abstract

Cortex can make an agent's LLM requests smaller: tool-prune removes tool definitions the agent does not use, and context-guru compacts the conversation. Until now, Cortex reported what this saved with a rough byte ratio, and that figure did not match the context-guru proxy's figure for the same traffic.

This PR makes Cortex count savings the same way the proxy does. Both now use one shared library, accountant. Each saving is priced from real cache and token facts, and it is booked as dollars for an API key or as usage-limit units for a subscription. The figure appears in the ledger, /v1/usage, the sessions list and agentop. It can also be pushed to the central metrics collector. Model calls that context-guru makes, and keep-alive pings that keep an idle session's cache warm, are booked as spend, so the net saving is honest.

The PR also turns context-guru on by default for a new local install (preset xhigh).

Why this PR is big

Against main it has 46 commits and 203 files, with +20,189 / −1,073 lines. Most of that is not production code:

Part Lines added Note
Tests (*_test.go) ~9,200 Includes the replay of all 163 accountant cases, none skipped
Production Go ~7,100 core/accounting (new package) is most of it
scripts/dev ~2,400 Dev-only harnesses: savings comparison, LiteLLM integration, keep-alive check. Not shipped
Docs, specs, plans ~1,300 Design and plan in docs/superpowers/, plus user docs

It also carries several features that depend on each other, and three of them came in from #1412, which this PR supersedes:

  1. The accountant host code and pricing (core/accounting, core/cost).
  2. Reporting from the context operators (tool-prune, context-guru) and the pipeline hooks.
  3. Keep-alive pings for idle sessions (from Feat/contextguru keepalive #1412).
  4. context-guru on OpenAI Responses and Anthropic incoming models, the marker cap and preset xhigh (from Feat/contextguru keepalive #1412).
  5. The metrics_push OTLP export.
  6. context-guru on by default for a local install.

If a smaller review unit is wanted, items 3–6 can each move to a follow-up PR on top of 1–2.

Design

What changes

  • core/accounting: Cortex's own host code. It parses the wire body, holds the cache facts, the W6.1 skip rules and the threads, and keeps one Trackers per process (with a laptop snapshot, capped at 20 MiB). It also holds the pricing, the conversion of results to savings, keep-alive ping accounting, the metrics sink and the OTLP push. A boundary test keeps context-guru out of its imports. Accounting does not depend on context-guru: it works with tool-prune only, or with no context operator.
  • Pipeline: adds pctx.ReportOps and the client body as received. Pipeline.Run calls a request start and end hook, so no listener changes. Hashing runs off the request goroutine. Accounting fails open.
  • Context operators: tool-prune reports one operation per removed tool, including a moved cache_control mark. context-guru reports its engine operations, its envelope (tools and system) operations and its model-call spends.
  • Keep-alive (from Feat/contextguru keepalive #1412): each ping goes through PingOps and ComputeStandalone. Its spend gets its own ledger columns, and its rescue is credited on the next request. Session state is kept on disk.
  • context-guru engine (from Feat/contextguru keepalive #1412, 8606e3d3): compacts OpenAI Responses requests (/v1/responses is a default path). On Anthropic traffic, model.source: incoming components get the request's own model (cheapmodel.Anthropic on the held credential, with the summarizer's prefix ask), and each call is a KindSpend op. marker_mode is capped at summary. The engine default is preset: xhigh.
  • context-guru on by default (79024c3c): the --local config lists context-guru after tool-prune, with on_error: enforce and preset: xhigh. contextguru moves into the local, full and fullcpex build profiles, because a binary that cannot load a plugin its config names refuses to start. lite, envoy and cpex still leave it out.
  • Billing mode comes from accountant.BillingFrom, read on the client's credential header before any plugin rewrites it. Each saving gets a basis (usd, subscriptionEquivalent or unknown) under accountant design §7.1. Money totals count only usd. A subscription saving is also shown in usage-limit units, with the API-equivalent dollars beside it.
  • 1-hour cache writes are priced at the 1-hour rate.
  • Ledger, /v1/usage and agentop switch to the accountant figure. New columns: penalty, units, unknown, plugin spend and keep-alive. The old byte-ratio pricing for tool-prune is removed.
  • metrics_push pushes OTLP over HTTP to the collector's Cortex receiver. Nothing is sent without a URL. A URL with credentials in it is refused.
  • docs/accounting-differences.json lists every known difference from the proxy, with a reason and the spec section that covers it.

Dependencies

  • github.com/rossoctl/accountant v0.5.0 in every module. v0.4.0 added PingWindowID, the active operation count and age in Result, and typed CheckFailure numbers, and it fixed in-place position mapping after added content. v0.5.0 adds Provider.ReadSetsTTL and EntryFacts.PingTTL, opt-in support for a provider where a read sets the TTL of the cache part it reads. Cortex sets neither, so the v0.5.0 bump does not change behaviour. No replace lines are left.
  • github.com/rossoctl/accountant/metrics has no tag upstream. It is pinned to the pseudo-version for commit 6085d4661624 (2026-11-11), which is the reviewed code.
  • github.com/rossoctl/context-guru v0.7.4-beta.1. Against v0.7.3, context-guru/proxy does not compile with the new accountant. v0.7.4 is now tagged upstream, so the pin should move to it before merge.
  • modernc.org/sqlite v1.56.0 and its modernc.org/* toolchain are linked, since 9d8ad9e0 (context-guru session state on disk): core/plugins/contextguru/statedb.go imports it directly, core/go.mod requires it directly, and go version -m on a local-tagged cortex binary lists it. It is pure Go, so it builds fine under CGO_ENABLED=0. (Corrected from an earlier, stale claim in this body that it was in go.sum only.)

Behaviour changes

  • A new local install runs context-guru with preset xhigh. It rewrites request bodies, and its LLM steps make extra model calls on the agent's own endpoint and key. Set on_error: observe to measure without changing any bytes. An existing ~/.cortex/config.yaml is not rewritten.
  • The local, full and fullcpex binaries grow by about 16 MiB (a local build is about 60 MB, a full build about 83 MB).
  • With accounting.enabled: false (or in praxis mode), tool-prune records no saving. The old byte-ratio settle.Avoided path is gone (docs/tool-prune-plugin.md).
  • With an accountant on a chain, that chain buffers every inference request body, within the listener's existing cap (1 MiB on extproc and the reverse proxy, 32 MiB on the forward proxy).
  • A reload that turns accounting on when the proxy started with it off is refused. Under enabled: auto, that is adding the first context operator. A reload that turns it off (for example on_error: off on the only operator) is accepted.
  • Release note: if you downgrade to a version before this one, it reads the keep-alive ping records this version wrote as ordinary requests.

Before merge

  • Move context-guru from v0.7.4-beta.1 to v0.7.4.
  • Run scripts/dev/verify-contextguru-keepalive.sh.
  • Run the cmd/agentop root-package tests with the laptop service stopped.
  • Optional: run scripts/dev/compare-contextguru-savings.py, the Cortex / proxy / control harness.

Testing

  • Every package passes, with and without the workspace. The exception is three America/Havana DST tests in core/cost/ledger and core/cost/usage, which also fail on main.
  • The concurrent packages pass with -race.
  • All 163 accountant test cases (cases.All() at v0.5.0) pass, with no case skipped or deferred. TestAccountantCases checks the library Result. TestSavingsAgreesWithTheAccountantCases checks Cortex's dollar conversion (SavingsBilled) on top of it. docs/accounting-differences.json documents differences from the proxy. It is not a skip list.
  • scripts/profile-tags and cmd/cortex (built with the local tags) pass after the default-enable change. A fresh local binary started on a config from --write-config lists context-guru with preset: xhigh in /v1/pipeline and logs no error.
  • gofmt, vet and go mod tidy -diff are clean.

Review round 1

Two independent reviewers found 3 blocking defects, now fixed:

  1. Negative net savings floored to 0 (core/cost/event/event.go): AvoidedAPIEquivalentMicros and AvoidedUnknownMicros ran through pricing.MicrosOrZero, which refuses any negative input by design. A request whose cache penalty exceeded its saving booked 0 instead of a negative net, overstating every total. Fixed with a new pricing.SignedMicrosOrZero, which preserves the sign; added TestFigures_NegativeNetIsNegative and TestSignedMicrosOrZero.
  2. Held Anthropic credential had no time-bound release (core/plugins/contextguru/incoming_anthropic.go): an expired hold was only released on a later matching request, so on a quiet install it could stay held for the life of the process. Fixed with a holdSweepInterval (10m) ticker, started in Init and stopped in Shutdown; added tests for the sweep itself and for Init/Shutdown wiring. Documented the hold (and the already-bounded forwarded-body stash) in the three DELETE /v1/sessions retention texts (CLAUDE.md, docs/laptop-service.md, docs/session-api.md).
  3. Received body paired across requests, not per request (core/plugins/contextguru/plugin.go, incoming_anthropic.go): the pending body was kept in a sync.Map keyed by session id. Claude Code's one-shot calls share the main turn's session id, so two overlapping requests could clobber each other's entry, pairing one request's received body with a different request's forwarded body. Fixed by keeping it on the request's own pctx (pipeline.SetState), which is single-threaded per request; added TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession, confirmed to fail against the old logic and pass with the fix.

Also fixed: docs/pricing.md and docs/context-guru-plugin.md described these two figures as gross and the plugin as opt-in-at-build-time; both corrected. cmd/agentop/tui/sessions_pane.go's stale "gross" comment fixed too.

Assisted-By: Claude (Anthropic AI) [email protected]

Cortex hosts the accountant library to compute context savings with the
same rules as the context-guru proxy, records them in the ledger, and
pushes the llm.savings counters to the central collector. Accounting
works without context-guru. Keep-alive from PR rossoctl#1412 comes in the same PR.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
core/accounting/wire, facts, skip.go and thread.go are the W6/W5.2 host
obligations from accountant/docs/cortex-wiring.md, ported from the
context-guru proxy's accParse and entryFacts: wire.Parse splits an
inference body into the sections and breakpoints accountant.NewBody
wants; facts.Classify and facts.For give a provider's cache facts;
SkipReason says when not to call Compute; ThreadOf gives the default
accountant.Thread. No caller wires these in yet (task 2+).

cases_test.go plays every github.com/rossoctl/accountant/test/cases
case through the library and compares to Expected, the way the
library's own case runner does; all 160 pass with no entries needed in
the new docs/accounting-differences.json. boundary_test.go pins that
core/accounting never depends on context-guru.

core/go.mod now requires accountant v0.2.0 directly; cmd/cortex and
cmd/cortex-envoy pick up the same version indirectly via go mod tidy.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…y test

Review round 1 on the accountant host code:

- facts.For now matches the context-guru proxy's entryFacts exactly
  (G6): it sets only TTL and Lifetime, never MinCacheable or
  Provider.{ReadGranularity,TTLs}, which the proxy's own entryFacts
  never sets either. The Anthropic 1h rule is now "every raw
  cache_control mark asks 1h" (apply.AllBreakpointsAskExtendedTTL),
  not "any merged breakpoint does" — a position can merge a 5m and a
  1h mark into one Breakpoint{TTL:"1h"}, which would read wrongly
  under the old rule. This needed information the merged
  []accountant.Breakpoint slice cannot carry, so For's signature
  changes to take an allMarksAsk1h bool (from the new
  wire.AllMarksAsk1h) instead of the breakpoints slice. OpenAI now
  gets the proxy's model-aware gate too: GPT-5.6+ is
  LifetimeMinimum/30m (modelinfo.OpenAI30MinuteCache), everything else
  stays LifetimeUnknown/5m.
- wire.Parse's section detection now matches the proxy's accScan and
  responsesSections verbatim: it reads the body's own shape (does it
  have a messages array, or an input array/string instead) rather
  than branching on the Format argument, prefers an explicit system
  field over instructions when a body has both, and reads a body
  shaped like Responses the same way regardless of which Format the
  caller passed.
- facts.Classify no longer falls back to a host-substring guess; an
  unrecognized path is ProviderUnknown even on a host named
  "anthropic" or "openai", matching the proxy's path-only rule.
- boundary_test.go is now an allowlist (stdlib, accountant, OTel,
  core/..., tidwall) rather than a context-guru denylist, so an
  unreviewed dependency of any kind fails loudly.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
… changes

Add the pipeline surface for the accountant: pctx.ReportOps, the client
body, a thread override, and a RequestStart/RequestEnd hook that
Pipeline.Run calls when it is built WithAccountant. RequestEnd is not
called on a Reject or a cancel.

core/accounting gains Host, one per process and shared by every pipeline
a reload builds. RequestEnd parses both bodies and opens and ends the
library record on a goroutine of its own. Compute waits at most 2s, runs
under recover, and is latched per request. The Tracker state is saved as
a snapshot on a local install, and a snapshot older than 1h is refused.

The top-level accounting.enabled (auto | true | false) decides whether
the Host is built. auto turns it on when the outbound chain has
context-guru or tool-prune. A reload that changes the resolved answer is
refused, as for mtls.*.

tool-prune reports one rewrite op per removed tool, with a ChangeID that
is stable across turns. inference-parser asks the Host for the Result
once and logs it at DEBUG. No figure is written yet.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…the accountant

Switches the plugin from apply.BodyWithModel to apply.BodyOpts so Result.Trace
reaches it, then:

- reports the engine's own context operations (res.Trace.Ops) to the accountant
  via pctx.ReportOps, which stamps DryRun under on_error: observe;
- names the request's accounting thread from res.Trace.Thread, falling back to
  core/accounting.ThreadOf's "main" default when the engine resolved none (no
  Opts.ThreadOf is wired yet, so this is currently always the fallback);
- wraps cgModel so each in-request call through the plugin's static or
  reconstructed-incoming model reports a KindSpend op with the call's billed
  usage, via a pctx captured at call time (the static model is a template
  shared across requests; OnRequest copies it per request).

Ports ChatUsage/PromptTokenDetails/CachedTokens (and their test) from PR rossoctl#1412
on feat/contextguru-keepalive into core/llmclient so cgModel can read a call's
token usage off the response.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…y basis

The user chose BillingFrom in the accountant library and the full
recording of accountant design 7.1: a basis on each saving, usage-limit
units for subscription savings, and money totals that count only usd.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
… spend test

Review fix round 1 on the context-guru accounting commit:

- Extract OnRequest's accounting side into reportResult(pctx, res) so it is
  testable against a hand-built apply.Result without re-running the engine
  (a second apply.BodyOpts call would observe already-mutated store state).
  Add TestReportResult_ForwardsOpsUnchanged, which deep-equals pctx.ReportedOps()
  against two hand-built ops with distinct Kind/ChangeID/At/Spans/SizeBefore/
  SizeAfter, and checks SizeBefore.Bytes > SizeAfter.Bytes on the rewrite op.
  Tighten the existing end-to-end TestPlugin_ReportsEngineOps to an exact op
  count and the same size check, instead of only a non-empty check.
- Assert op.Operator == "context-guru" in TestPlugin_ModelCallIsSpendOp.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…type

RequestStart now reads the client's x-api-key / Authorization header, before
any plugin (token-exchange) can rewrite it, and stores the accountant.Billing
it implies via accountant.BillingFrom (design §5.7, accountant branch
feat/billing-from). RequestEnd uses that mode for RequestMeta.Billing instead
of the Task 2 BillingAPI placeholder, and Host now keeps the last mode seen
per (session, thread) via the new ThreadBilling method, for a later task's
keep-alive pings. Only the resulting mode is ever stored; the header value
itself is never kept, copied into an event, or logged.

Adds a dev-only replace of github.com/rossoctl/accountant at the local
billing-from worktree in every go.mod that requires it (core, cmd/cortex,
cmd/cortex-envoy, cmd/agentop), to be dropped once accountant v0.3.0 is
tagged. Adds a contract test that feeds accountant's own TestBillingFrom
table through Host.RequestStart. Documents in accounting-differences.json
that the standalone context-guru proxy still hard-codes BillingAPI.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Host.threadBilling grew by one entry per (session, thread) pair for the life
of the process. Bound it the same way accountant.Trackers bounds its own
thread map (library internal/engine/state.go:47-114, maxThreads = 10000,
trimmed to 9000 oldest-first): add threadBillingCap/threadBillingTrimTo,
stamp each entry with lastSeen, and trim once setThreadBilling pushes the
map over the cap.

Also note in docs/accounting-differences.json's proxy.billing-mode-hardcoded
entry that it should be removed once the context-guru proxy adopts
accountant.BillingFrom.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
… the accountant

Bring PR rossoctl#1412's keeper into the context-guru plugin (keepalive.go,
dispatcher.go, windows.go, mask.go and their tests, build_test.go, the
verify script), merged by hand into the current plugin.go. Its spend
path (core/cost/spend, Deps.Costs, spend.LogRecorder, saving/unique/
spend.go and the 82cd72b pricer) is not taken.

Each ping now goes through core/accounting: the plugin's pingEmitter
converts the KeepAliveReport to an accountant.Ping (wiring W4.6) and
calls the new Host.Ping. The host refuses a ping with no window, a
non-2xx status or no usage, prices it with PingOps and
ComputeStandalone under the thread's last billing mode, writes its
spend to the cost recorders as a Source "keep-alive" record priced by
settle.SettleInput (never through the session store), and keeps its
PingFacts for the thread's next priced request, which credits the
rescue under the ping's ChangeID. A manual ping keeps no facts.

context-guru moves to v0.7.4-beta.1. Its rossoctl#776 rule (a plain ping after
an Anthropic text turn) is why the substitute test's fixture now ends
at a tool_result turn. Pings now carry the plugin's per-process
sentinel, and their transport raises MaxIdleConnsPerHost.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…t's session

Review round 1 of the keep-alive task.

- A ping's cost record keeps Source and Provenance as settle set them
  and carries a new additive event.Event field, Purpose
  (event.PurposeKeepAlive). Overwriting Source lost how the cost was
  arrived at. The plugin doc now says the ledger and /v1/usage do not
  read Purpose yet and fold ping spend into the agent's rows.
- cgSessions is bounded (10,000, trimmed by age to 9,000), the same
  pattern as the accountant host's per-thread maps.
- A ping is accounted only under pctx.SessionID, the key
  Host.RequestEnd uses. A ping tracked under the caller's identity is
  only logged, not accounted with BillingUnknown and facts no request
  reads.
- A test pins that two concurrent requests reading the same ping facts
  credit one rescue: the library's thread-state replace (R53) prices the
  second against the first.
- The structural "no session store" guarantee is a comment, not an
  assertion that could not fail.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Adds the 1h cache-write tier the pricing package's own doc used to call
deliberately absent. TierCacheWrite1h addresses it through Rates.For
(falls back to the 5m write rate) and the new Rates.CacheWrite1hRate,
which derives 2x input for an Anthropic-shaped table with no explicit
rate and marks a non-Anthropic fallback estimated. settle.modelledCost
adds the delta for the 1h subset on top of CostByTier's existing 5m
pricing, since Usage.CacheWrite1h is a subset of Usage.CacheWrite and
folding it into the generic per-tier loop would double-bill it.

Parses usage.cache_creation.ephemeral_1h_input_tokens into
InferenceExtension.CacheWrite1hTokens (a subset of CacheWriteTokens),
threaded through parsercommon.TokenUsage so every provider path shares
one Fill. core/accounting's Host.Compute and Ping.recordPing (task 6's
keep-alive path) now fill accountant.Usage.CacheWrite1h the same way,
so a 1h ping write prices at the 1h rate too.

Task 7 of 10, accountant-integration (2026-11-17).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…ng test

TestPing_ConcurrentRequestsCreditOneRescue did not always create the race
it tests: the second record could peek the ping facts after the first
request was priced and had dropped them (2 of 15 runs). Both records now
wait at a two-party barrier in factsHook, after the peek and before the
record is ended, so neither can be priced until both have read the same
facts. With the race forced, the library still credits one rescue, so
the Host's peek-then-drop stays as it is.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Fix round 1 for the 1h cache-write tier (task 7): the output-only half of
SettleInput zeroed Input/CacheWrite/CacheRead but left CacheWrite1h set, so
modelledCost's 1h-vs-5m delta landed a second time on a figure that carries
no cache-write tokens at all. outputOnly now zeroes CacheWrite1h too.

CacheWrite1hDeltaMicros now returns Rates.CacheWrite1hRate's own estimated
alongside the delta, threaded through modelledCost's new estimated1h return
and published on Settled via the existing Incomplete/ModelledIncomplete
fields under a new ReasonCacheWrite1hRateEstimated, rather than a parallel
field — spec: "price at the 5m rate and mark the figure estimated."

PlausibleUsage now also refuses a negative CacheWrite1h, one past
maxPlausibleTokens, or one exceeding CacheWrite itself — Usage.tokens()
excludes CacheWrite1h (it is a subset, not a sibling tier), so none of
those were checked before.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Task 7 added InferenceExtension.CacheWrite1hTokens without updating the three
guards that pin the extension's fields, so core/pipeline and core/sessionapi
failed at 80ada88: the parsed-request field list, the session event golden
file, the session-api.md field docs, and summarizeEvent's field count. The
count is a token figure a row's cost is priced from, so it is timeline data
and summarizeEvent keeps it; the test now asserts that.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…current figure

core/accounting gains the one pricing function of the accountant's figures
(USD, TierUSD: the process rate table at the request's endpoint, model and
prompt total, with the 1h cache-write tier and its estimated fallback) and
the conversion from an accountant.Result to one event.Saving per operator
(Savings, SavingsBilled, Host.Savings), following wiring W7.1: Saved priced
plus positive effects in USD, Caused plus each attributed break's net cost
plus the operator's own model calls in PenaltyUSD, a rescue to the keeper,
InBaseline effects skipped, unowned breaks in UnattributedBreakUSD. The
basis follows the client's billing mode (usd, subscriptionEquivalent,
unknown); a subscription saving is also valued in usage-limit units with
accounting.subscription_weights (defaults 1, 1.25, 2, 0.1, 5, each >= 0; a
reload that changes them is refused).

event.Saving gains PenaltyUSD, Operator, OpsVersion, Basis, Units and
PenaltyUnits, and event.Event gains UnattributedBreakUSD and Thread, all
omitempty and read by nothing yet. TotalAvoidedUSD is unchanged.

inference-parser now computes the accountant's savings beside
settle.Avoided's, still publishes the old figure, and logs each component
whose net figure differs by more than $0.000001 at INFO ("accounting:
shadow"), counted in two plugin metrics. Host.Savings also writes one DEBUG
"accounting: tokens" line per operator for the cross-host harness.

tool-prune reports the cache mark it moves from a pruned tool to the last
survivor as a rewrite in place of the survivor, so the library's sum check
holds and the request is priced.

The Cortex / context-guru proxy / control harness and the LiteLLM
integration test come from feat/contextguru-keepalive; P1 now compares the
accountant's tokens per operator with the proxy dashboard's per component.
docs/accounting-differences.json lists the expected shadow and cross-host
differences.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Review round 1 of the accountant pricing and shadow commit.

- The context-guru plugin reports the tools and system changes apply makes
  without an op (cachesplit, toolfilter, toolschema, headttl) by diffing its
  own input and output, ported from the proxy's envelopeOps, so those
  requests pass the library's sum check and are priced.
- A spend op (an operator's model call) is no longer inside a Saving: it is
  one event.SpendRecord in Extras.Spends and the new Event.Spends field,
  priced with its output and at its own prompt size.
- An operator's dry-run ops make their own projected saving instead of
  adding to its applied figure.
- The shadow logs operators only the accountant prices at DEBUG and counts
  them apart, so the INFO line and "differed" mean a real difference.
- Every differences entry names its section; UnattributedBreakUSD's doc says
  it holds every unowned effect.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…and agentop

The cost record's savings are now the accountant's figure, end to end. The
shadow comparison and the old tool-prune pricing are gone.

- inference-parser publishes Host.Savings as event.Event.Avoided, with the
  request's Thread, UnattributedBreakUSD and Spends. A spend alone publishes
  a record. The shadow log lines and their three plugin metrics are removed.
  Host.Savings sets each saving's Provenance from the rate table.
- Money totals count only basis "usd": TotalAvoidedUSD (gross, not floored)
  and the new TotalPenaltyUSD/TotalPenaltyMicros. event.Event.Figures splits
  a record by basis for every aggregate.
- usage.Counts, ledger rows, /v1/usage and the sessions list gain
  penaltyMicros, avoidedUnits, penaltyUnits (milli-units),
  avoidedApiEquivalentMicros, avoidedUnknownMicros, pluginSpendMicros,
  pluginSpendUnits, pluginSpendUnknownMicros, and (ledger, /v1/usage)
  keepAliveMicros and keepAlivePings. Plugin spend is kept out of
  costMicros. A keep-alive ping counts in no request, token, cost, coverage
  or latency figure. Old ledger rows read the new fields as 0.
- agentop: the events table sums every operator's saving net of its
  penalty, not floored (rowSavingFor, from rossoctl#1412). The sessions SAVED
  column is the net and may be negative. `agentop cost` and the spend
  drawer show saved, penalty and net, usage-limit units with their API
  equivalent, unknown billing apart, plugin model calls and keep-alive.
- Deleted: core/cost/settle/avoided.go, settle/decode.go,
  core/cost/pricing/estimate.go (EstimateTokensFromBytes, AvoidedUsage)
  and their tests. tool-prune's event keeps its fields; its pane counts
  dollars only for a usd saving.
- docs/accounting-differences.json: the envelope-op tool indexes after
  tool-prune, multi-round requests, accounting off and legacy savings with
  no basis; the shadow entries now describe the switch.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…s, add UNITS

Review round 1 of the switch to the accountant figure.

- An empty Saving.Basis is usd (Saving.EffectiveBasis): settle.Avoided's
  savings were dollars and the ledger counts them, so the replayed ring,
  the archive re-fold and agentop now count them too.
- The accountant is not asked when settle refused the token report, and
  Host.Compute refuses counts that fail pricing.PlausibleUsage, as the old
  saving did.
- agentop's sessions table gains an optional UNITS column after SAVED for
  usage-limit savings; its full text carries the API equivalent.
- A keep-alive ping creates and refreshes no per-session usage ring.
- The context-guru plugin's model calls never use HTTPS_PROXY, so a call
  cannot loop back through Cortex and count as both agent and plugin spend.
- The window's unit for every accountant line, CurrenciesIn counts the API
  equivalent, the dead SavedUSD fields are gone, and comments, the
  integration script and CLAUDE.md are brought up to date.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The accountant host now hands each computed request's Result (once, as
Compute is latched) and each keep-alive ping's standalone Result (empty
RequestID) to accountant/metrics, off the request goroutine and under a
recover. The pricer is bound to one request under Sink.mu and prices
through accounting.USD, so the pushed llm.savings.saved.usd equals the
ledger's saving to the micro.

core/accounting/push builds the OTel MeterProvider: OTLP/HTTP to
<url>/v1/metrics, cumulative, Authorization: Bearer <token>, resource
service.instance.id (~/.cortex/machine-id on a local install, per
process in a cluster), service.version and service.name=cortex. A failed
export increments llm.proxy.export_failures and WARNs at most once a
minute; it never reaches a request.

Config: a top-level metrics_push block (enabled, url, token, interval;
METRICS_PUSH* env overrides). No default URL, so nothing is sent until a
user sets one. https only, except loopback. A reload that changes it is
refused. Docs cover metrics_push and accounting, including
subscription_weights.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…tials out of logs

Review round 1 of the metrics push:

- The sink binds each model the library prices to its own endpoint and
  prompt total: the request's model to the request's, each spend's call
  model to the call's host and own prompt size (CallUSD, now shared
  with Host.Savings). Pushed spend dollars equal the ledger's spends[]
  to the micro. A model collision falls back to the request's binding;
  documented and tested.
- SafeURL strips user info, query and fragment from metrics_push.url
  wherever it reaches an error, a log or the exporter's endpoint.
- The export-failure counter is an atomic pointer: the periodic reader
  can export before Start stores it (a race the new test found).
- Tests that subscription and unknown billing move tokens, never USD.
- Docs: the exact pricing binding and the four remaining differences
  (CostUSD, collisions, dry-run/refused spends, cache-effect
  attribution); where a bad block is caught (config.Load) and where
  the env is (a WARN, no push). cortex-envoy's version gap is
  documented in a comment.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Review round 2: the ledger summed every operator model call into
PluginSpendMicros/Units/UnknownMicros, including a dry run's (an
operator under on_error: observe) and one the accountant refused to
price. The metrics sink books neither (accountant R12; metrics.md rules
1 and 3), so the two outputs disagreed.

SpendRecord gains Projected (op.DryRun) and Refused (op listed in
Result.Unpriced), both omitempty. SavingsBilled sets them and keeps the
records visible in Event.Spends; Event.Figures leaves them out of every
spend total (SpendRecord.Counted). The wire pin test covers the two new
keys. pricing.md drops this from the remaining-differences list and
says why both outputs exclude them.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…oroutine

context-guru calls Model.Complete concurrently (six goroutines in its extract
stage) and after OnRequest returns (summarize_async, cache_aware_async), and
cgModel reported through pctx.ReportOps, which appended to an unguarded slice
and read the plugin being dispatched.

- pipeline.Context guards its op list with a mutex. ReportOpsAs records ops
  with an operator and dry-run state the caller captured, and reads no
  dispatch state. Run seals the list right before RequestEnd; an op reported
  after that is dropped, logged at DEBUG and counted (LateOpsDropped).
- cgModel captures the plugin's observe state when OnRequest builds it and
  reports as context-guru through ReportOpsAs. A late call is also counted in
  the plugin's late_model_calls_dropped metric.
- Host.Compute releases the request's handle on a timeout, as on every other
  no-figure path.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…asis

Every ping was priced into KeepAliveMicros whatever the credential, while
the metrics sink moved no dollars for a subscription or unknown login, so
the ledger and the push disagreed and API-equivalent dollars reached a
money total.

- A ping's cost record carries the basis of Host.ThreadBilling (usd,
  subscriptionEquivalent, unknown), Estimated on every non-usd basis, and
  on a subscription its usage-limit units from the configured weights,
  output included.
- event.Figures splits a ping's spend like a plugin's: KeepAliveMicros
  (usd only), KeepAliveUnits (milli-units), KeepAliveAPIEquivalentMicros
  (not money) and KeepAliveUnknownMicros. KeepAlivePings counts every ping.
  The ledger, the usage ring and /v1/usage book them through it; agentop's
  keep-alive line shows each part.
- The ledger's keep-alive branch adds the record's figures once, after the
  branch decision, instead of twice.
- docs: the keep-alive spend paragraph and the plugin's schema text now say
  what the ledger does; pricing.md has the split and the spend formula, and
  says budgets see neither plugin nor keep-alive spend.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…nstall

Two defaults were right for a laptop and wrong for a pod.

- context_window.model_info defaulted to litellm everywhere, so every pod
  fetched the LiteLLM model map from the public internet on its first
  gated request and again per hot reload. It now defaults to litellm only
  on a local install and to off elsewhere; an explicit model_info always
  wins, and a model_info_url with model_info unset turns the map on.
- The plugin's model calls and keep-alive pings pinned Proxy: nil. On a
  laptop HTTPS_PROXY points at Cortex itself, so the pin stops a double
  count; in a cluster it is the egress proxy, and ignoring it breaks calls
  where egress is mandatory. The pin now applies only on a local install;
  elsewhere the clients keep ProxyFromEnvironment. The ping client's pin
  came from PR rossoctl#1412 and gets the same rule. The plugin learns the install
  through plugins.LocalInstallConsumer.
- docs: the model_info default, and a section on where the plugin's own
  calls go, with the caveat for a pod whose HTTPS_PROXY is its own sidecar.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…t an erase keeps

- MetricsPushConfig.Validate refuses a URL with user info or a query
  string, which the exporter drops on the way out (the collector then
  answers 401). The error quotes only SafeURL and points to token. In the
  file it fails startup; in METRICS_PUSH_URL it WARNs and turns the push
  off, as any refused METRICS_PUSH_URL does.
- docs/accounting-differences.json: threadBilling and pingFacts are not in
  the snapshot, so the first ping after a restart is BillingUnknown and a
  pending rescue is lost.
- CLAUDE.md, docs/session-api.md and docs/laptop-service.md: neither
  DELETE route clears the accountant's per-session state, what that state
  holds, and how it ages out.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid requested a review from a team as a code owner November 18, 2026 06:02

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 79024c3c1bbf blocking

Verdict: blocking

Scope note: the base SHA in the review request (7821df67) is an old origin/main of the fork. Diffed against it, the PR shows 1,830 files, because most of that is main's own history. I reviewed the PR's own change: git diff 49aa57ac..79024c3c (the merge base with upstream/main). That is 203 files, +20,189 / −1,073, which matches the PR body.

Findings

  1. core/cost/event/event.go:590-591 — a negative net "API equivalent" or "unknown" saving becomes 0, so these figures read too high

    • What fails: Figures computes equivSaved and unknownSaved as net figures (s.USD - s.PenaltyUSD, lines 564 and 568). The field docs say "May be negative" (event.go Figures; usage.go AvoidedUnknownMicros). But both go through pricing.MicrosOrZero, and MicrosFromUSD returns (0, false) for any usd < 0 (pricing/cost.go:166). Take a subscription request whose context-guru rewrite broke the cache: USD 0.10, PenaltyUSD 0.40. Its AvoidedAPIEquivalentMicros is 0, not −300,000. In a session with records +$0.50 and −$0.30 net, the session total is $0.50, not $0.20. The clamp is per record, before any sum, so every surface overstates the figure: the ledger, /v1/usage, the sessions list, agentop cost ("API equivalent net"), and the sessions UNITS text. The units net on the same line (AvoidedUnits − PenaltyUnits) can go negative, so on one line the two figures disagree in sign. A subscription login is the normal laptop case (Claude Code OAuth), and xhigh on by default makes penalties common.
    • Proof: event.go:564/568 subtract. Then cost.go:320 MicrosOrZero → cost.go:166 if usd < 0 { return 0, false }. No test covers a net below zero: TestFigures_SplitsByBasis uses only positive nets (2 − 1).
    • Fix: convert these two fields with a signed conversion (round usd*1e6 and keep the sign, with the same NaN/Inf/bound checks). Add a Figures test with a negative net for both bases. figureSum and Counts.addInto already accept negatives (AddSat).
  2. core/plugins/contextguru/incoming_anthropic.go:62-79 — a held caller credential is not released 2 h after its last use, and it can stay in memory with no time limit

    • What fails: credHolds.hold releases expired holds only inside hold, so only when a later Anthropic request arrives. Nothing else (no timer, no sweep) calls Release except releaseAll at Configure and Shutdown. So with the new default config, the last Claude Code credential stays held, masked, until the next gated Anthropic request or a restart or reload. On a laptop service that runs for days, that can be days. anthropicIncoming takes the hold on every gated Anthropic request that carries a credential and a model, whether or not a component uses the incoming model (modelsFor, plugin.go:740).
    • Proof: grep incomingHoldTTL finds only the comparison at line 67. docs/context-guru-plugin.md:24 says the credential is "released 2 hours after its last use, on a config reload, or at Shutdown". Also, docs/session-api.md:388 and docs/laptop-service.md:682 list the credential a DELETE leaves in memory as only the keeper's (about 13.5 minutes). They do not name this hold. With keep-alive off, which is the default, this hold is the only credential retention.
    • Fix: add a periodic sweep (for example from Init, stopped in Shutdown), or release on a timer for each hold. Then name this hold in the session-api.md and laptop-service.md lists of what an erase keeps.
  3. core/plugins/contextguru/plugin.go:495 with incoming_anthropic.go:294 — the "received" body is keyed by session, so two concurrent main-role requests can stash one request's input beside another's output

    • What fails: p.pending.Store(sid, pctx.Body) keys by session id, and stashSent takes it with LoadAndDelete(sid). Then it stores it as preBody beside this request's pctx.Body as forwarded. Claude Code sends one-shot completions (title, permission monitor) under the same session id, and these are not subagent-role (core/parse/inference/subagent.go:24-28). Interleaving: one-shot B starts (Store B). Main turn A starts (Store A, which overwrites B). B finishes first and gets A's body. The stash now holds preBody = A and forwarded = B. A finishes and finds nothing, so it does not stash. CoversSpan normalizes preBody (A), so the span check passes. But Ask appends the summarizer's question to forwarded (B, the one-shot). The summary can then describe the wrong body, and cache_aware_summarizer splices it into the main conversation. That is silent context loss, and it is now on by default.
    • Proof: plugin.go:492-496 (Store by sid, gated only by !isSubagent); incoming_anthropic.go:293-304 (LoadAndDelete(sid), put(key, provider, pre, pctx.Body)); incoming_anthropic.go:275-286 (CoversSpan reads preBody); incoming_anthropic.go:312-318 (Ask reads forwarded). I traced this by reading the code. I did not run it, because live tests are not approved.
    • Fix: keep the received body on the request itself (pipeline.SetState(pctx, …)), not in a map keyed by session, so OnFinish always pairs a request's own two bodies. Add a test that interleaves two requests on one session.
  4. docs/pricing.md:718-719 and docs/context-guru-plugin.md:7-9 — two docs disagree with the code

    • What fails: pricing.md says avoidedApiEquivalentMicros is "the usd of those same savings" and avoidedUnknownMicros is "the usd of savings with basis unknown", which reads as gross. The code puts the net there (USD − PenaltyUSD, event.go:564/568), and the agentop line labels it "API equivalent net". context-guru-plugin.md still says the plugin is "Opt-in at build time (-tags include_plugin_contextguru)". This PR puts it in the local, full and fullcpex profiles and turns it on in the --local config, and that doc does not say so.
    • Proof: the lines cited. Compare scripts/profile-tags/profiles.go membership and cmd/cortex/local.go:349-358.
    • Fix: say "net of their penalty" in both pricing.md rows (after finding 1, also say that it can be negative). In context-guru-plugin.md, say which profiles carry the plugin and that a local install runs it with preset: xhigh by default.

Non-blocking

  • Observe mode still spends real money and reports none of it in any total. Under on_error: observe, apply.BodyOpts still gets the static and incoming models. So xhigh's model-calling components make billed calls on the user's own credential. Those spends are Projected and are left out of every pluginSpend* total (pricing.md documents this). The keep-alive code refuses to hold under observe for this exact reason ("a ping is real, billed spend — the opposite of a shadow run"). The engine's model calls do not follow the same rule. local.go:353 and plugin-catalog.md suggest observe "to measure without changing any bytes". Think about not passing models under observe, or say plainly in both places that observe still makes billed calls.
  • The inference-router interacts with the incoming model. agentop server add puts the router after context-guru. So the incoming Anthropic hold is taken on the client's original host and credential (before the redirect and setKey). But the stashed forwarded body is the routed body that went to the other server. A prefix ask then sends the routed body (possibly with the routed model name) to the original host. Please check that this works, or turn off the prefix ask when pctx.Redirected().
  • Stale comments that say a reload which turns accounting off is refused: core/config/accounting.go:31-33 and cmd/cortex/main.go:544-547. The code accepts it (validateAccounting). Also CLAUDE.md:299 says "Both blocks need a restart", but turning accounting off reloads (CLAUDE.md:314-316).
  • PR body, Dependencies: it says modernc.org/sqlite is "in go.sum only" and is not linked. Since 9d8ad9e0, core/plugins/contextguru/statedb.go imports _ "modernc.org/sqlite", and core/go.mod requires it directly. So the local, full and fullcpex binaries link it. The size figures in the body may also be out of date.
  • cmd/agentop/tui/sessions_pane.go:574: the comment says "API-equivalent dollars of the gross saving", but the field is net.
  • scripts/dev/integration-contextguru-litellm.py:54: the default LITELLM_BASE is an internal hostname (ete-litellm.ai-models.vpc.res.ibm.com) in a public repo. The A1-ping-spend and A2 INFO texts are out of date: pings now reach a cost recorder, and a PrefixAsker exists. --shared rewrites the live ~/.cortex/config.yaml.
  • scripts/dev/compare-contextguru-savings.py:40: the usage line shows --keep, but argparse defines no --keep, so that command line fails.
  • Tests: three America/Havana DST tests fail in core/cost/usage (and the PR says core/cost/ledger too). The PR says they fail on main too. I did not check them on main.

What I checked

  • I read CLAUDE.md and core/plugins/CLAUDE.md. I read the design (§5.3, §5.3a, §5.4) and searched the plan for the reload and observe rules. I also read the accountant v0.4.0 docs I needed (spec R29, R25, R27; BillingFrom; the persist format for the snapshot trim).
  • I read every production file in full: core/accounting/* (host, ping, savings, price, metrics, push, snapshot, snapshot_trim, skip, thread, options, wire, facts), core/pipeline/accounting.go, context.go, pipeline.go, core/plugins/deps.go, the whole contextguru plugin (plugin, incoming_anthropic, dispatcher, envelope, keepalive, ping, mask, modelclient, statedb, windows), toolprune, inferenceparser, config/accounting.go, validate.go, reloader.go, cost/event, pricing (rates, cost, inference, multiplier), settle, ledger writer and query, usage, session (figures, fold, history, store, summary), llmclient, parse/inference/anthropic.go, parsercommon, cmd/cortex (main, accounting, local), cmd/cortex-envoy/main.go, the Dockerfiles, build.yaml, profile-tags, and the agentop money, cost and tui changes.
  • I read every changed doc: CLAUDE.md, architecture, configuration, context-guru-plugin, laptop-service, laptop-token-savings, plugin-catalog, pricing, proxy-contract, session-api, session-budget-plugin, tool-prune-plugin, accounting-differences.json. I read the shell harness in full and both Python harnesses.
  • I read the test diffs that change existing tests (forwardproxy chainedwriters, settle bound_agreement, ledger admission, usage tests, litellm_budgettrack, session currencies) to check that no assertion was weakened without reason. I skimmed the new test files where they bear on a finding (event_test TestFigures_SplitsByBasis).
  • Traces: the extproc response pctx is the request-body pctx, so the pending handle reaches Compute. The billing snapshot is taken before any plugin. Ops are sealed before RequestEnd. Resends do not re-run Run. Redirect updates pctx.Host, so keep-alive holds pair host and credential. Positions per operator are in the space of that operator's own input (R29). The 1h cache-write delta is added once, and it is zeroed on the output half.
  • I ran: go vet on core (with no tags and with the local tags), on cmd/cortex (local), on cmd/cortex-envoy (envoy) and on cmd/agentop. All are clean. go test: core accounting, pipeline, plugins, toolprune, inferenceparser, contextguru and all (with include_plugin_contextguru), cost (all but the Havana DST tests), session, sessionapi, reloader, config, parse and llmclient all pass. cmd/cortex (local tags) passes. cmd/agentop money and tui pass. I did not run the full cmd/agentop root package, go mod tidy -diff, or any live test.

Two independent reviewers (offload-review, round 1) found 3 blocking
defects:

- core/cost/event/event.go: AvoidedAPIEquivalentMicros and
  AvoidedUnknownMicros are net figures (saved minus penalty) but were
  converted with pricing.MicrosOrZero, which refuses any negative
  input. A request whose penalty exceeded its saving booked 0 instead
  of a negative net, overstating every total that includes it (the
  ledger, /v1/usage, the sessions list, agentop). Add
  pricing.SignedMicrosOrZero, which preserves the sign through the
  same NaN/Inf/bound guards, and use it for both fields.

- core/plugins/contextguru/incoming_anthropic.go: an incoming-model
  credential hold past incomingHoldTTL was released only when a later
  matching request called hold() again. On an installation with no
  such later request, the masked credential stayed held for the life
  of the process. Add a holdSweepInterval (10m) ticker, started in
  Init and stopped (and waited on) in Shutdown, so a hold is released
  within one interval of its TTL regardless of traffic.

- core/plugins/contextguru/plugin.go, incoming_anthropic.go: the body
  a request received was kept in a sync.Map keyed by session id, for
  OnFinish to stash beside the body that went upstream. Claude Code's
  one-shot calls (title, permission monitor) share the main turn's
  session id, so two requests in flight on one session could clobber
  each other's entry: OnFinish could then pair one request's received
  body with a DIFFERENT request's forwarded body, and the summarizer's
  prefix ask would splice the mismatched pair into the conversation.
  Keep the body on the request's own pctx (pipeline.SetState) instead,
  which is single-threaded per request, so the pairing is exact by
  construction.

Also: docs/pricing.md and docs/context-guru-plugin.md described the
two net figures as gross and the plugin as opt-in-at-build-time; both
now match the code. cmd/agentop/tui/sessions_pane.go's stale "gross"
comment is fixed too. The three DELETE /v1/sessions retention texts
(CLAUDE.md, docs/laptop-service.md, docs/session-api.md) now name the
incoming-model hold and the forwarded-body stash.

Tests: TestFigures_NegativeNetIsNegative, TestSignedMicrosOrZero,
TestStartSweepReleasesAlreadyExpiredHoldWithNoRequest,
TestStopSweepWithoutStartIsANoop,
TestInitStartsAndShutdownStopsTheHoldSweep,
TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession (the
last confirmed to fail against the reverted old logic and pass with
the fix). core/plugins/contextguru passes with -race. gofmt clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This replies to both reviewers' finding 1 (negative net savings floored to 0).

Fixed in c2c07ac.

AvoidedAPIEquivalentMicros and AvoidedUnknownMicros are net figures (saved
minus penalty). They went through pricing.MicrosOrZero, which refuses a
negative input by design (that helper is for a charge, which cannot be
negative). A penalty bigger than the saving floored to 0 instead of a
negative net.

Fix: a new pricing.SignedMicrosOrZero keeps the sign through the same
NaN/Inf/bound checks, and event.Figures now uses it for both fields.

Tests: TestFigures_NegativeNetIsNegative asserts -300000 for both fields on
reviewer 1's exact example (USD 0.10, PenaltyUSD 0.40). TestSignedMicrosOrZero
covers the boundary cases (negative zero, NaN, Inf, the MaxCostMicros bound).

Also fixed docs/pricing.md, which called these two columns gross.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This replies to both reviewers' finding 2 (held credential had no time-bound
release).

Fixed in c2c07ac.

An incoming-model credential hold past incomingHoldTTL (2h) was released
only when a later request on the same credential called hold() again. On a
quiet installation with no such request, the masked credential (and the
forwarded-body stash beside it) stayed held for the life of the process.

Fix: credHolds now runs a holdSweepInterval (10m) ticker, started in Init
and stopped (with a wait on its exit) in Shutdown. It releases every expired
hold on its own, whether or not a request arrives.

Tests: TestStartSweepReleasesAlreadyExpiredHoldWithNoRequest (an already-
expired hold is released within 2s of startSweep, with zero requests).
TestStopSweepWithoutStartIsANoop (a credHolds built without Init, as the
existing tests do via configured(), does not block on stopSweep).
TestInitStartsAndShutdownStopsTheHoldSweep (the plugin's own lifecycle
wiring). core/plugins/contextguru passes with -race.

Also named this hold, and the already size-bounded forwarded-body stash,
in the 3 DELETE /v1/sessions retention texts (CLAUDE.md,
docs/laptop-service.md, docs/session-api.md), and tightened the claim in
docs/context-guru-plugin.md to say the release is on a timer.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This replies to reviewer 1's finding 3 (received body paired across
requests, not per request).

Fixed in c2c07ac.

The body a request received was kept in a sync.Map keyed by session id,
for OnFinish to stash beside the body that went upstream. Claude Code's
one-shot calls (title, permission monitor) share the main turn's session
id, so two requests in flight on one session could overlap: a later
Store() on the same key overwrote an earlier one, so OnFinish could pair
one request's received body with a DIFFERENT request's forwarded body.

Fix: the body is now kept on the request's own pctx (pipeline.SetState),
which is single-threaded per request, so the pairing is exact by
construction regardless of what else is in flight on the same session.

Test: TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession
reproduces the exact interleaving (one-shot B starts, main turn A starts
on the same session before B finishes, B finishes first). I confirmed it
fails against the reverted old session-keyed logic (got A's body where
B's was wanted) and passes with the fix.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This replies to both reviewers' finding 4 / non-blocking notes about stale
docs.

Fixed in c2c07ac:

  • docs/pricing.md: avoidedApiEquivalentMicros and avoidedUnknownMicros now
    say "net of its penalty... may be negative", not "the usd of" (gross).
  • docs/context-guru-plugin.md: no longer says "Opt-in at build time". Now
    says it ships in local, full and fullcpex, and names lite/envoy/cpex as
    the profiles that leave it out.
  • docs/context-guru-plugin.md: the credential-release sentence now says
    "on a timer, not only on the next matching request", matching the
    finding-2 fix.
  • cmd/agentop/tui/sessions_pane.go: the comment calling the API-equivalent
    figure "of the gross saving" now says "of the NET saving (may be
    negative)".

The PR body's Dependencies section also had a stale claim that
modernc.org/sqlite was in go.sum only. I confirmed it is linked (go
version -m on a local-tagged binary lists modernc.org/sqlite v1.56.0) and
corrected the body.

Not changed in this round: the open_error:observe billed-model-calls point,
the possible OAuth beta-header gap on subscription credentials, and the
inference-router/incoming-model interaction. These are real points but are
behavioral questions for @boazdavid to weigh in on, not findings I can fix
unilaterally without a product decision.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Thanks @boazdavid. I re-reviewed the one commit since 79024c3: c2c07ac (Fix 3 blocking review findings on the accountant PR). I also re-checked the open items from earlier rounds.

The three fixes in c2c07ac work as described:

  • Negative net savings. pricing.SignedMicrosOrZero keeps the sign through the same NaN/Inf/bound guards, and event.Figures uses it for AvoidedAPIEquivalentMicros and AvoidedUnknownMicros. The places that add these figures (Counts.addInto through event.AddSat, session/figures.go, ledger.CurrenciesIn's != 0 test, agentop's Signed) already accept negatives. docs/pricing.md now says "net".
  • Credential-hold sweep. startSweep runs from Init and stopSweep runs before releaseAll in Shutdown. Pipeline.Start unwinds with Shutdown when a later plugin's Init fails, so the goroutine does not leak on that path. The three DELETE retention texts now name the hold and the stash.
  • Received body per request. The received body is now stored with pipeline.SetState on the request's own pctx, so two requests that overlap on one session can no longer swap bodies.

Still blocking:

  1. The stale_prefix must-fix from the 8606e3d round is not fixed. Moving the received body onto pctx fixes the mix-up between two overlapping requests. It does not stop a one-shot from replacing the main conversation's stash entry. I re-ran the probe on this head. It is inline.
  2. New: the Rust (praxis) tests fail. inference.cacheWrite1hTokens was added to core/pipeline/testdata/parsed-request.fields, but the Rust model does not have it. The CI job turned green only because its step says "cargo test failed (does not block: no praxis-mode changes)". It is inline.
  3. CodeQL alert #365 (go/clear-text-logging, core/accounting/savings.go:430) is still open and has not been dismissed (see the existing thread).
  4. CI has not run on this head. The PR still conflicts with main (3847526e) in the same four files: core/reloader/reloader_test.go, core/session/fold.go, docs/session-api.md and scripts/profile-tags/profiles_test.go. Only DCO (pass) and CodeRabbit (skipped) reported.

Not blocking, still open: the on_error: observe model-call suggestion (cmd/cortex/local.go:353). Your reply says this needs a product decision, and I agree. The context-guru v0.7.4-beta.1 → v0.7.4 pin also has to move before merge.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru incoming_anthropic.go and plugin.go, core/cost/event, core/cost/pricing, and the consumers of the two signed fields in core/cost/usage, core/cost/ledger, core/session and cmd/agentop), docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md, docs/pricing.md), and the praxis field-parity test. I reviewed the delta since 79024c3 and re-checked the earlier open threads against the whole PR.
Agent/IDE config (.claude/.vscode): none
Commits: 47 commits. DCO passes. Only the upstream merge commit caceb14 has no sign-off.
CI status: not run on this head (merge conflicts). On the last head where CI ran (9a12e46), Rust (praxis) showed green, but its annotation says cargo test failed.
Verified by: go test -race -tags include_plugin_contextguru passes on plugins/contextguru, cost/event, cost/pricing, session, pipeline and accounting/.... In cost/usage and cost/ledger, only the known America/Havana DST tests fail. go vet and gofmt -l are clean. cargo test -p cortex-praxis-filters --lib (Rust 1.96.0): 142 pass, 1 fails (below). I also re-ran the one-shot probe described inline.

Generated by RepoMan github-pr-review.

// is still pctx.Body, so the stash matches what upstream cached in that case too.
func (p *ContextGuru) stashSent(pctx *pipeline.Context, sid string) {
pre := pipeline.GetState[pendingBody](pctx, pendingBodyStateKey)
if pre == nil || p.stash == nil || isSubagent(pctx) || pctx.StatusCode != 200 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix (still open from the 8606e3d round): this guard still lets a Claude Code one-shot replace the main conversation's stash entry. c2c07ac fixed the overlap case (two requests in flight). It did not fix the sequential case that this thread was about.

A one-shot (title, permission monitor, auto-mode classifier) declares role main and has a 200 status. It now has its own pendingBody on its pctx, so it passes every condition here. p.cgSessions.get(sid) returns the same engine key as the main turn, so put replaces the main turn's entry.

Probe on c2c07ac. Using configured, anthropicPctx, invokeReq and OnFinish, on session s1:

  1. A main turn (3 messages, Extensions.Inference.Tools = [Bash]) finishes with 200. p.stash.CoversSpan(key, 2, SpanHash(NormalizeMessages(mainBody)[:2])) is true.
  2. A one-shot (claude-haiku-4-5, 1 message, no tools) on the same session finishes with 200. The same CoversSpan is now false.

So on the next main turn, cache_aware_summarizer and extract_llm_sweep still decline with ErrStalePrefix on any turn that follows a one-shot. With 79024c3 that is the default path on a local install. The new TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession shows the same thing: it expects the one-shot B to be stashed for s1.

Suggested fix (as before): stash only requests that carry a tool manifest. That is the filter model.PromptContextOf uses: inf := pctx.Extensions.Inference; inf == nil || len(inf.Tools) == 0. Apply it here and at the pipeline.SetState in OnRequest. Please add a test with a main turn, then a one-shot, then CoversSpan for the main turn's span.

inference.agentRole string
inference.anthropicBeta string
inference.cacheReadTokens number
inference.cacheWrite1hTokens number

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix (CI hides this failure): this line makes the praxis parity test fail. praxis/filters/src/parse/model.rs every_go_inference_field_is_set_or_listed reads this file. It requires every inference.* field either to be set by the Rust model or to be listed in NOT_SET_IN_PRAXIS_MODE. cacheWrite1hTokens is neither:

---- parse::model::tests::every_go_inference_field_is_set_or_listed stdout ----
panicked at filters/src/parse/model.rs:511:9:
Go fields the Rust model does not give: ["inference.cacheWrite1hTokens"]
test result: FAILED. 142 passed; 1 failed

(cargo test -p cortex-praxis-filters --lib on c2c07ac with Rust 1.96.0. On main, Rust (praxis) passes with no failure annotation.)

The Rust (praxis) job showed green on 9a12e46, the last head where CI ran, only because its step reports "cargo test failed (does not block: no praxis-mode changes)". The job's annotations show this. After the rebase it will look green again while this test fails.

Either fix works:

  1. Add cache_write_1h_tokens to the Rust InferenceExtension, and fill it from usage.cache_creation.ephemeral_1h_input_tokens in praxis/filters/src/parse/inference/anthropic.rs (next to cache_creation_input_tokens). Praxis-mode records then carry the 1h tier as Go's do.
  2. Add "inference.cacheWrite1hTokens" to NOT_SET_IN_PRAXIS_MODE, with a comment that praxis mode does not split the 1-hour tier yet.

boazdavid and others added 2 commits November 22, 2026 09:01
v0.5.0 adds Provider.ReadSetsTTL and EntryFacts.PingTTL, opt-in support
for a provider (AWS Bedrock, per upstream) where a read sets the TTL
of the cache part it reads, so a keep-alive ping's return read gets
credited its rescue. A host that sets neither sees no change: Cortex's
host does not set ReadSetsTTL, so this bump is behavior-neutral here.

Every module now pins v0.5.0.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…t PR

Round 1 of the offload review raised 3 non-blocking points beyond the
3 blocking findings already fixed. All 3 are now closed:

- Under on_error: observe, modelsFor still built the static and
  incoming models, so cgModel.Complete and meteredDispatcher sent the
  real HTTP call regardless of dryRun, which only changed how the
  resulting op is REPORTED (Projected, left out of every total). A
  shadow pass is supposed to change nothing, the same line the
  keep-alive keeper already holds ("UNDER on_error: observe NOTHING
  IS HELD... that ping is real, billed spend"). modelsFor now returns
  an empty ModelSpec under observe, so every model-backed component
  degrades to deterministic/no-op and no credential hold is taken.

- A Claude subscription (OAuth) token can need an oauth-* Anthropic-
  Beta value to authenticate directly against api.anthropic.com, and
  cheapmodel.Anthropic's own headers never set one. Without it, an
  incoming-model call on a subscription credential could 401 --
  failing open, but silently (the summarizer does nothing that turn).
  cortexDispatcher now holds the request's own oauth-* betas
  (tooldefer.AuthBetas) alongside the credential and fills them in on
  a call that set none, without overriding a caller that set its own
  (tooldefer.RunProbeBeta's own beta argument).

- inference-router always runs after context-guru (agentop server add
  appends it last), so the incoming-model hold is taken on the host
  and credential the client named, before any redirect -- but
  pctx.Body by OnFinish can be the redirected server's own rewrite.
  Stashing it would have the next turn's prefix ask send that body, in
  whatever shape the OTHER server expects, to the client's original
  host. stashSent now skips a redirected request. Whether the incoming
  model should instead follow the redirect is a product question this
  does not answer; it only removes the concrete risk.

Tests: TestModelsForBuildsNeitherModelUnderObserve (both dialects, and
that no hold is taken), TestDoFillsTheRequestsOwnAuthBetaWhenTheCallerSetNone,
TestDoDoesNotOverrideACallerSetAuthBeta, TestDoSendsNoAuthBetaWhenTheRequestHadNone,
TestStashSentSkipsARedirectedRequest. Each confirmed to fail against
the reverted fix and pass with it. core/plugins/contextguru passes
with -race. cmd/cortex (local tags) builds and passes. gofmt and go
mod tidy -diff clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This replies to the 3 non-blocking points from round 1 (observe-mode
billed calls, the possible OAuth beta-header gap, the inference-router
interaction).

Fixed in 864a3f0, after a decision from @boazdavid to close all 3 now
rather than defer them.

  1. Observe-mode billed calls: modelsFor now returns an empty ModelSpec
    under on_error: observe, so every model-backed component degrades to
    deterministic/no-op and no incoming-model credential hold is taken.
    Test: TestModelsForBuildsNeitherModelUnderObserve (both dialects).

  2. OAuth beta-header gap: cortexDispatcher now holds the request's own
    oauth-* Anthropic-Beta values (tooldefer.AuthBetas) alongside the
    credential, and fills them in on a call that set none, without
    overriding a caller that set its own. Tests:
    TestDoFillsTheRequestsOwnAuthBetaWhenTheCallerSetNone,
    TestDoDoesNotOverrideACallerSetAuthBeta,
    TestDoSendsNoAuthBetaWhenTheRequestHadNone.

  3. inference-router interaction: stashSent now skips a redirected
    request, so a prefix ask never sends a possibly-routed body to the
    client's original host. Whether the incoming model should instead
    follow the redirect is a separate product question this does not
    answer; it only removes the concrete risk you flagged. Test:
    TestStashSentSkipsARedirectedRequest.

Each new test is confirmed to fail against its fix reverted and pass
with it. core/plugins/contextguru passes with -race.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Thanks @boazdavid. I re-reviewed the two commits since c2c07ac: 6ab835d (accountant v0.5.0) and 864a3f0 (the 3 non-blocking points). I also re-checked the blocking items from the last round.

The three fixes in 864a3f0 work as described:

  • Observe makes no model calls. modelsFor returns an empty ModelSpec when pctx.Observing(), so anthropicIncoming is never called and no credential is held. The comment in cmd/cortex/local.go and the text in docs/plugin-catalog.md / docs/context-guru-plugin.md now say so.
  • OAuth beta. heldTarget.authBeta carries only the oauth-* values (tooldefer.AuthBetas), and Do fills it in only when the caller set no Anthropic-Beta. One small gap is noted inline (nit).
  • Redirected requests. stashSent now skips a request where pctx.Redirected() is true.

The accountant v0.5.0 bump builds in every module, and the accountant cases still pass through the host code.

Still blocking (no change and no reply since the last round):

  1. One-shot replaces the main turn's stash (thread). 864a3f0 only adds the Redirected() check to stashSent. I re-ran the probe on 864a3f0. A main turn on s1 (with tools, 3 messages) finishes with 200, so the stash holds its body. Then a claude-haiku-4-5 one-shot (1 message, no tools, role main) on s1 finishes with 200. After that, the stash's preBody is the one-shot's body. So cache_aware_summarizer and extract_llm_sweep will still decline with ErrStalePrefix on the main turn that follows any one-shot. This is the default path on a local install. The suggested filter (stash only when pctx.Extensions.Inference.Tools is non-empty, in both OnRequest and stashSent) and a main → one-shot → CoversSpan test still apply.
  2. The Rust (praxis) parity test fails (thread). core/pipeline/testdata/parsed-request.fields:18 still lists inference.cacheWrite1hTokens. Nothing under praxis/ changed, so every_go_inference_field_is_set_or_listed still fails. CI will hide this, because the job's step says "does not block".
  3. CodeQL alert #365 (go/clear-text-logging, core/accounting/savings.go:430) is still open and has not been dismissed (thread).
  4. The PR still conflicts with main (mergeable: CONFLICTING). CI has not run on this head: only DCO (pass) and CodeRabbit (skipped) reported.

Before merge, still open (not blocking): move context-guru v0.7.4-beta.1 to v0.7.4.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru dispatcher.go, incoming_anthropic.go and plugin.go with their tests, cmd/cortex/local.go), the go.mod/go.sum bumps in all modules, and docs (docs/context-guru-plugin.md, docs/plugin-catalog.md). I reviewed the delta since c2c07ac and re-checked the open blocking threads against the head.
Agent/IDE config (.claude/.vscode): none
Commits: 49 commits. DCO passes.
CI status: not run on this head (merge conflicts).
Verified by: these all pass on 864a3f0 with GOWORK=off. In core: go build -tags include_plugin_contextguru ./..., go test -race -tags include_plugin_contextguru on plugins/contextguru, accounting/..., cost/event, cost/pricing and pipeline, plus go vet and gofmt -l. cmd/cortex builds and tests with the local profile tags. cmd/agentop (money, tui) and cmd/cortex-envoy build and test. I re-ran the one-shot stash probe as a throwaway test, and it fails as described in item 1.

Generated by RepoMan github-pr-review.

auth = append(auth, heldHeader{name: name, val: b})
}
}
authBeta := tooldefer.AuthBetas(reqHeaders.Values("Anthropic-Beta"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: the held authBeta is fixed by the first request that creates a hold. credHolds.hold (incoming_anthropic.go:113-118) reuses the existing ref for a known credKey, and credKey hashes only the scheme, the host and authHeaderNames, not Anthropic-Beta. Each matching request also refreshes lastUsed, so that ref can live for the whole process.

Two cases follow from this:

  • The first request on an OAuth credential has no oauth-* beta (an older client, or a call type that leaves it out). Every later incoming-model call on that credential then goes out without the beta, even after the client starts sending it, and gets the silent 401 this change is meant to fix.
  • The client changes its oauth-* beta version. The old value is still sent.

Two cheap fixes: add tooldefer.AuthBetas(pctx.Headers.Values("Anthropic-Beta")) to credKey, or update the held authBeta on each hold hit.

TestAccountantCases and TestSavingsAgreesWithTheAccountantCases could
skip a case listed as "differs" in docs/accounting-differences.json.
No listed id matched a real case id, so nothing was skipped, but the
mechanism let a failing case be listed away instead of fixed.

Remove it. Both tests now run every case in cases.All() (163 at
accountant v0.5.0), and a case Cortex cannot meet fails. The
differences file stays as documentation of Cortex-level differences
from the proxy; no test reads it. The design spec now says every case
must pass.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Thanks @boazdavid. I re-reviewed the one commit since 864a3f0: b3851e5 (run every accountant case with no skips). It works as described. loadDifferences, skipDifference and logSkipped are gone. TestAccountantCases and TestSavingsAgreesWithTheAccountantCases now run every case in cases.All(). On b3851e5 with accountant v0.5.0, both pass with 163 subtests each (326 total), and none is skipped. Nothing in Go reads docs/accounting-differences.json any more. One stale sentence in that file is noted inline (nit).

Still blocking. This commit changes only tests and the spec, so none of the earlier blocking items has moved. None of their threads has a reply.

  1. A one-shot replaces the main turn's stash (thread). Nothing under core/plugins/contextguru changed since 864a3f0, where the main → one-shot probe showed the stash holding the one-shot's body. So on a local install, which runs this path by default, cache_aware_summarizer and extract_llm_sweep still decline with ErrStalePrefix on the main turn after any one-shot. The fix suggested in that thread still applies: stash only when pctx.Extensions.Inference.Tools is non-empty, in both OnRequest and stashSent, and add a main → one-shot → CoversSpan test.
  2. The Rust (praxis) parity test fails (thread). core/pipeline/testdata/parsed-request.fields:18 lists inference.cacheWrite1hTokens. praxis/filters/src/parse/model.rs has no such field, and it is not in NOT_SET_IN_PRAXIS_MODE, so every_go_inference_field_is_set_or_listed fails. The PR changes nothing under praxis/. CI will not flag this, because that job's step says "does not block". Either add cache_write_1h_tokens to the Rust InferenceExtension (and full_sample), or list the field in NOT_SET_IN_PRAXIS_MODE with a reason.
  3. CodeQL alert #365 (go/clear-text-logging, core/accounting/savings.go:430) is still open and has not been dismissed (thread).
  4. The PR still conflicts with main (mergeable: CONFLICTING). As a result, CI has not run on this head: only DCO (pass) and CodeRabbit (skipped) reported.

Before merge, still open (not blocking): move context-guru v0.7.4-beta.1 to v0.7.4.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go tests (core/accounting/cases_test.go, core/accounting/savings_agree_test.go), docs (docs/superpowers/specs/2026-11-17-accountant-integration-design.md, docs/accounting-differences.json). I reviewed the delta since 864a3f0 and re-checked the open blocking threads against this head.
Agent/IDE config (.claude/.vscode): none
Commits: 50 commits. DCO passes.
CI status: not run on this head (merge conflicts).
Verified by: on b3851e5 with GOWORK=off in core: go test -count=1 -tags include_plugin_contextguru ./accounting/... passes, a -v run of the two case tests shows 326 PASS subtests and no SKIP, and go vet ./accounting/ and gofmt -l accounting/ are clean. I checked the praxis parity gap by reading the code: the field list against model.rs and NOT_SET_IN_PRAXIS_MODE.

Generated by RepoMan github-pr-review.

{
"id": "proxy.billing-mode-hardcoded",
"kind": "notCovered",
"reason": "The standalone context-guru proxy still hard-codes Billing{Mode: BillingAPI} for every request; it does not call accountant.BillingFrom yet (Cortex spec \u00a75.7). Remove this entry once the context-guru proxy calls accountant.BillingFrom. Not a case in github.com/rossoctl/accountant/test/cases, so this is a documentation-only note rather than a skip for TestAccountantCases."

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: this note, and the same sentence at line 82, still says the entry is "a documentation-only note rather than a skip for TestAccountantCases". Since b3851e5, no test reads this file, and no entry of either kind is a skip. Consider dropping the "rather than a skip…" part from both notes. The same goes for the kind field's skip meaning, if you keep that field. Then nobody reading the file will think it still controls which cases run.

@boazdavid

Copy link
Copy Markdown
Contributor Author

Closing: this PR is split into smaller [cg] PRs.

Part of this PR Now in
1-hour cache-write price (70bcaa9e, 80ada888, a74b8d07) branch cg/pricing-1h (no PR yet)
accountant v0.5.0, core/accounting/wire, core/accounting/facts #2054
accountant host, config, pipeline hooks, reloader rule, the 163-case agreement test #2055
tool-prune, inference-parser and context-guru report to the accountant #2056
savings in the ledger, /v1/usage, sessions API and agentop #2057
context-guru session state on disk #2058
keep-alive pings accounted through the accountant #2059
context-guru on by default on a local install #2060
Responses, Anthropic incoming model, marker cap, xhigh (from #1412) #2061
llm.savings.* metrics push #2062

Merge order: branch cg/pricing-1h (1-hour cache-write price) → #2054 → #2055 → #2056 → #2057 → #2058 → #2059 → #2060 → #2061 → #2062 → #2063. #2064 (central stack, no Go) depends only on main. Each PR body says what it is stacked on and what needs it.

The split was built from one source tree: this work merged with current main (8 conflicts resolved), minus the 3 dev harnesses in scripts/dev, docs/accounting-differences.json and the 3 implementation plans, which were removed. The last stacked PR's tree equals that source, except the central stack (in #2064) and 2 cross-links between docs/laptop-service.md and deploy/central/README.md, to be restored after both sides merge.

Assisted-By: Claude (Anthropic AI) [email protected]

@boazdavid boazdavid closed this Nov 22, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 22, 2026
@boazdavid

Copy link
Copy Markdown
Contributor Author

Update: the 1-hour cache-write price now has its own PR, #2065, on main. #2054 now also depends only on main. New order: #2054 and #2065 (either order) → #2055 → #2056 → … → #2063. #2064 depends only on main.

Assisted-By: Claude (Anthropic AI) [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.

3 participants