Skip to content

feat(contextguru): [cg] Keep the session state on disk - #2058

Merged
huang195 merged 9 commits into
rossoctl:mainfrom
boazdavid:cg/05-contextguru-state-disk
Nov 24, 2026
Merged

huang195 merged 9 commits into
rossoctl:mainfrom
boazdavid:cg/05-contextguru-state-disk

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on: #2057
Required by: #2059
Review only this PR's change: boazdavid/cortex@cg/04-savings...cg/05-contextguru-state-disk (the diff against main also shows every PR below it until those merge)

Part of the [cg] series that replaces #1956, #1958 and #2053, split into reviewable layers. Merge in the order below.

# PR
— #2065 feat(pricing): Price 1-hour cache writes at the 1-hour rate (on main, not in this series) needed by #2055
1 #2054 feat(accounting): Add the accountant wire and facts packages and the dependency
2 #2055 feat(accounting): Host the accountant, with its config, pipeline hooks and case tests
3 #2056 feat(accounting): Report operators' context changes and model-call spend to the accountant
4 #2057 feat(accounting): Price the accountant's savings into the ledger, usage and sessions
5 #2058 feat(contextguru): Keep the session state on disk this PR
6 #2059 feat(contextguru): Keep idle sessions' caches warm through the accountant
7 #2060 feat(contextguru): Turn context-guru on by default on a local install
8 #2061 feat(contextguru): Port Responses, the Anthropic incoming model, the marker cap and xhigh from #1412
9 #2062 feat(accounting): Push the accountant's metrics to a central collector
10 #2063 feat(accounting): Add inference metrics for the time and bytes the proxy adds
— #2064 feat(central): Add the central metrics stack on OpenShift (on main alone, no Go)

What

Persist the per-session state the context-guru engine needs between turns —
the summary checkpoint, the last billed input, freeze decisions — in the
engine's session_state table, in a SQLite file (modernc.org/sqlite, pure Go).
The state survives a restart and a config reload, so the prompt prefix the
provider has cached stays valid.

On a local install the file is ~/.cortex/context-guru-state.db; otherwise it
lives in the user cache directory. It holds content, so it is mode 0600 in a
0700 directory, and a row is kept 30 days after its last write. The plugin
fails open: with no usable file it keeps the state in memory and logs one WARN.

Testing

  • Built and tested on its own (this PR's tree), with GOWORK=off, in core, cmd/cortex (plain and with the local profile tags), cmd/cortex-envoy, cmd/agentop, scripts/profile-tags and scripts/readme-demo: gofmt -l empty, go vet ./... clean, go mod tidy -diff clean, go test ./... passes.
  • 3 tests fail here and on main alike, from the local America/Havana time-zone data: TestMidnightTransitions_EveryFixtureIsStillTheDayItClaimsToBe (core/cost/ledger), TestStartOfLocalDay_PicksTheEarlierOfTwoMidnights and TestParseWindowSpec_TodayStartsWhereTheLocalDayStartsInEveryZone (core/cost/usage).

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

@boazdavid
boazdavid requested a review from a team as a code owner November 22, 2026 13:55
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Too many files!

This PR contains 102 files, which is 2 over the limit of 100.

To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch.

Upgrade to a paid plan to raise the limit.

This review couldn't start because sufficient usage credits or metered capacity aren't available. Add credits or update usage-based reviews in the billing tab, then retry.

Check out review usage here.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 23ac731f-1066-4a13-b5ee-a033fca96ea7
Commits

Reviewing files that changed from the base of the PR and between 82bfb96 and 8c164cb.

Files ignored due to path filters: 5

  • cmd/agentop/go.sum is excluded by !**/*.sum
  • cmd/cortex-envoy/go.sum is excluded by !**/*.sum
  • cmd/cortex/go.sum is excluded by !**/*.sum
  • core/go.sum is excluded by !**/*.sum
  • scripts/readme-demo/go.sum is excluded by !**/*.sum
Files selected for processing: 102

  • CLAUDE.md
  • cmd/agentop/cmd_cost.go
  • cmd/agentop/cmd_cost_test.go
  • cmd/agentop/go.mod
  • cmd/agentop/money/savings.go
  • cmd/agentop/money/savings_test.go
  • cmd/agentop/tui/cost_event.go
  • cmd/agentop/tui/cost_event_test.go
  • cmd/agentop/tui/events_column_sizing_test.go
  • cmd/agentop/tui/events_exchange_test.go
  • cmd/agentop/tui/events_pane.go
  • cmd/agentop/tui/events_rebuild_bench_test.go
  • cmd/agentop/tui/header_align_test.go
  • cmd/agentop/tui/linked.go
  • cmd/agentop/tui/local_preview_test.go
  • cmd/agentop/tui/prune_saving.go
  • cmd/agentop/tui/row_saving_test.go
  • cmd/agentop/tui/sessions_money_test.go
  • cmd/agentop/tui/sessions_pane.go
  • cmd/agentop/tui/sessions_server_test.go
  • cmd/agentop/tui/spend.go
  • cmd/agentop/tui/spend_drawer.go
  • cmd/agentop/tui/spend_drawer_test.go
  • cmd/agentop/tui/spend_test.go
  • cmd/cortex-envoy/go.mod
  • cmd/cortex-envoy/main.go
  • cmd/cortex/accounting.go
  • cmd/cortex/go.mod
  • cmd/cortex/main.go
  • core/accounting/host.go
  • core/accounting/host_test.go
  • core/accounting/options.go
  • core/accounting/options_test.go
  • core/accounting/price.go
  • core/accounting/price_test.go
  • core/accounting/savings.go
  • core/accounting/savings_agree_test.go
  • core/accounting/savings_test.go
  • core/config/accounting.go
  • core/config/accounting_test.go
  • core/cost/event/event.go
  • core/cost/event/event_test.go
  • core/cost/ledger/admission_test.go
  • core/cost/ledger/currency_test.go
  • core/cost/ledger/figures_test.go
  • core/cost/ledger/query.go
  • core/cost/ledger/writer.go
  • core/cost/pricing/cost.go
  • core/cost/pricing/cost_test.go
  • core/cost/pricing/estimate.go
  • core/cost/pricing/estimate_test.go
  • core/cost/settle/avoided.go
  • core/cost/settle/bound_agreement_test.go
  • core/cost/settle/decode.go
  • core/cost/settle/settle.go
  • core/cost/settle/settle_test.go
  • core/cost/usage/currency_test.go
  • core/cost/usage/pricing_test.go
  • core/cost/usage/rekey_test.go
  • core/cost/usage/replay_test.go
  • core/cost/usage/snapshot_test.go
  • core/cost/usage/usage.go
  • core/cost/usage/usage_test.go
  • core/go.mod
  • core/listener/forwardproxy/chainedwriters_test.go
  • core/plugins/contextguru/envelope.go
  • core/plugins/contextguru/envelope_test.go
  • core/plugins/contextguru/main_test.go
  • core/plugins/contextguru/modelclient.go
  • core/plugins/contextguru/modelclient_test.go
  • core/plugins/contextguru/plugin.go
  • core/plugins/contextguru/plugin_test.go
  • core/plugins/contextguru/statedb.go
  • core/plugins/contextguru/statedb_test.go
  • core/plugins/inferenceparser/accounting.go
  • core/plugins/inferenceparser/accounting_test.go
  • core/plugins/inferenceparser/cost.go
  • core/plugins/litellm_budgettrack/plugin_test.go
  • core/plugins/toolprune/accounting_test.go
  • core/plugins/toolprune/event.go
  • core/plugins/toolprune/plugin.go
  • core/plugins/toolprune/plugin_test.go
  • core/reloader/reloader.go
  • core/reloader/reloader_test.go
  • core/session/currencies_test.go
  • core/session/figures.go
  • core/session/fold.go
  • core/session/fold_test.go
  • core/session/history.go
  • core/session/store.go
  • core/session/store_test.go
  • core/session/summary.go
  • core/sessionapi/summary_test.go
  • docs/configuration.md
  • docs/context-guru-plugin.md
  • docs/laptop-service.md
  • docs/laptop-token-savings.md
  • docs/pricing.md
  • docs/proxy-contract.md
  • docs/session-api.md
  • docs/tool-prune-plugin.md
  • scripts/readme-demo/go.mod

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@boazdavid boazdavid changed the title [cg] feat(contextguru): Keep the session state on disk feat(contextguru): [cg] Keep the session state on disk Nov 22, 2026
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 974cb8b to b483799 Compare November 22, 2026 14:04
@github-actions github-actions Bot added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 22, 2026
Comment thread core/accounting/savings.go Fixed

@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

I reviewed only what this PR adds on top of cg/04-savings (#2057). The session state goes to a SQLite session_state table through context-guru v0.7.3's store.Disk. There is one shared *sql.DB per path, fail-open attach, and Shutdown flushes. I checked that against the library: Memory.AttachDisk, LoadSession (called by apply before every request), Disk.Close (idempotent, flushes), and the 30-day retention sweep. The wiring is correct. BuildWithDeps calls SetLocalInstall before Configure, and configuredPlugin forwards Shutdown, so the ~/.cortex path and the flush on drain both work. Locally, go vet and go test -race ./plugins/contextguru/ pass on this head, and gofmt is clean.

No blocking issues. Inline: two suggestions (a disk flusher that is never closed on failed builds or reloads, and DELETE routes that could actually erase the new on-disk content) and two nits.

Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (modernc.org/sqlite v1.56.0 and its deps, the same versions context-guru v0.7.3 pins), Docs
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes
CI status: Go CI (all jobs), tidy, CodeQL analyses, Dependency Review and Trivy all pass. Two failures don't come from this PR's change. Pre-commit fails in check-doc-links on two missing anchors (docs/pricing.md → context-guru-plugin.md#where-its-own-model-calls-go, docs/configuration.md → laptop-service.md#the-metrics_push-configuration), and I reproduced the same failure on main and on cg/04-savings. The CodeQL gate's one high alert is in core/accounting/savings.go:413, which comes from #2057 and is not touched here.

Comment thread core/plugins/contextguru/plugin.go Resolved
Comment thread docs/session-api.md Resolved
Comment thread core/plugins/contextguru/plugin.go Resolved
Comment thread core/plugins/contextguru/statedb.go Resolved
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from b483799 to ce97be9 Compare November 22, 2026 15:53
@boazdavid
boazdavid changed the base branch from main to cg/04-savings November 22, 2026 16:11

@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

The base is main, so the diff includes all of #2054–#2057 (and #2065). I reviewed only the commit unique to this PR, ce97be9 ("Keep the session state on disk"), against cg/04-savings (#2057 head f088aee). This head is a restack: ce97be9 is byte-for-byte the same change as b483799, which I approved earlier. The interdiff of the two commits is empty. My four earlier inline comments (the disk flusher leak on failed builds or reloads, DELETE routes that could call store.DeleteSessionState, the 24h TTL comment on the fail-open path, and Disk.Errors() in Metrics()) are still attached to this head and still apply. I haven't repeated them here.

New in this pass: one suggestion inline. The SQLite DSN is built from the raw path, so a # in the home or cache path sends the database to a different file with umask permissions. I reproduced this.

Re-verified on this head: go test -race and go vet in core/plugins/contextguru pass, and gofmt is clean. go mod tidy -diff is clean in core, cmd/cortex and cmd/cortex-envoy. Builds with include_plugin_contextguru succeed on Linux and on GOOS=windows for cmd/cortex. With HOME/XDG_CACHE_HOME pointed at a scratch dir, the tagged core config/plugins/pipeline/listener tests write no context-guru-state.db outside their temp dirs.

Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (modernc.org/sqlite v1.56.0 and deps, the versions context-guru v0.7.3 pins), Docs
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes (DCO passes)
CI status: Several Go CI jobs (core, authbridge cortex, authbridge cortex-envoy) were still queued or running when I posted. I covered that ground with the local runs above. None of the failures comes from this commit:

  • Pre-commit fails check-doc-links on docs/pricing.md → context-guru-plugin.md#where-its-own-model-calls-go and docs/configuration.md → laptop-service.md#the-metrics_push-configuration. Both links come from lower in the stack, and cg/04-savings fails the same way. main passes.
  • CodeQL's one high alert is core/accounting/savings.go:413, from #2057.
  • Rust (praxis) is green but hides cargo test failed (does not block: no praxis-mode changes). The same annotation appears on every PR from #2065 up, and #2065 changes core/pipeline/testdata/session-event.golden.json, so that is likely the source. Worth fixing in #2065, not here.

Comment thread core/plugins/contextguru/statedb.go Resolved
boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…Lite path

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

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

I re-reviewed the fix commit 0c4aea3 against ce97be9, which I approved earlier. Four of my five earlier comments are fixed, and each fix does what the replies say. The fifth (DELETE routes calling store.DeleteSessionState) is deferred to a follow-up, which is fine.

  • Disk flusher leak: Configure now opens only the shared *sql.DB and starts no goroutine. Init starts the store.Disk. I traced both failure paths. Reloader.reloadOnce returns on validateReloadable/validateAccounting before any Start, and newOut.Start failing at index N unwinds only [0..N-1], so a plugin whose Init never ran holds nothing. configuredPlugin forwards Init, and cmd/cortex and cmd/cortex-envoy both Start their pipelines. The atomic.Pointer swap makes a repeated Init/Shutdown safe, and so is Metrics() reading it concurrently.
  • SQLite URI escaping: with the old "file:"+path put back, TestStateDB_PathWithURICharacters fails all three subtests: a#b and a?b write elsewhere (a, a-wal, a-shm beside the directory), and a%41b fails to open. With sqliteURI they all pass. The ? that is now escaped no longer collides with modernc's own ?_pragma= split.
  • 24h TTL only with a database: fixed for the path where no file can be opened. One leftover case: if stateDBFor opens the file but OpenDisk then fails in Init (an unusable table), the 24h memory lifetime is already set while there is no disk copy. The pin cap bounds it and the case is rare, so I'm noting it here and not blocking on it.
  • state_db_errors metric: added, documented and tested.

Verified locally on this head (GOWORK=off): go test -race ./plugins/contextguru/ passes. go vet is clean, gofmt -l is empty and go mod tidy -diff is clean in core. cmd/cortex and cmd/cortex-envoy build with include_plugin_contextguru. The tagged core plugins/..., pipeline/... and reloader/... tests pass, with HOME/XDG_CACHE_HOME pointed at a scratch dir, and they write no context-guru-state.db there. The one exception is plugins/tokenbroker/client, which hit the 10-minute test timeout in a network read in my sandbox. This PR doesn't touch it.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo admin, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes (DCO passes)
CI status: Because the base is now cg/04-savings, only PR Verifier and DCO ran, and both pass. Go CI, pre-commit and CodeQL did not run on this head, so the local runs above stand in for them. The CodeQL alert at core/accounting/savings.go:413 belongs to #2057, as you noted.

@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 0c4aea3 to fa760c8 Compare November 23, 2026 07:59

@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

This head restacks the PR onto the new cg/04-savings head (e11a7d2, previously f088aee). I diffed f088aee..0c4aea3, which I approved, against e11a7d2..fa760c8. Ignoring index lines and hunk offsets the two are identical, so the change itself is the same one I approved before. All my earlier findings still hold as resolved: the flusher starts in Init, sqliteURI escapes the path, the 24h TTL applies only with a database, and state_db_errors is reported. The DELETE follow-up is still deferred, as agreed.

The base delta touches core/plugins/contextguru/plugin.go: cgModel now holds a pipeline.OpReporter in place of pctx/dryRun. That code is separate from the state-disk code (struct fields, Configure's store setup, Init/Shutdown, Metrics), and the PR applies to it without conflict.

Verified locally on fa760c8 (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):

  • go test -race ./plugins/contextguru/ passes in core. go vet is clean, gofmt -l is empty, and go mod tidy -diff is clean.
  • With include_plugin_contextguru, these core tests pass: plugins/contextguru/..., plugins/all/..., pipeline/..., reloader/..., config/... and accounting/.... The tagged cmd/cortex ./... tests pass too.
  • cmd/cortex and cmd/cortex-envoy are tidy, and both build and vet cleanly with the tag.
  • The tests wrote no context-guru-state.db to the scratch home.

The one leftover I noted last time is unchanged and still not blocking: if the file opens but OpenDisk fails in Init, the 24h memory TTL is already set.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo admin, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes (DCO passes)
CI status: On this base only DCO ran (it passes), and CodeRabbit skipped. Go CI, pre-commit and CodeQL did not run, so the local runs above stand in for them.

boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…Lite path

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from fa760c8 to 4c2e6e1 Compare November 23, 2026 09:45

@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

This head restacks the PR onto the new cg/04-savings head (4b6bdee, previously e11a7d2). The base now has its own localInstall field and SetLocalInstall (used for the HTTPS_PROXY bypass), so this PR drops its separate local field and reuses that one: stateDBFor(p.localInstall), with the field and setter comments merged. I compared e11a7d2..fa760c8, which I approved, with 4b6bdee..4c2e6e1, ignoring index lines and hunk offsets. Besides that change, the only differences are doc paragraphs (CLAUDE.md, docs/context-guru-plugin.md, docs/session-api.md) reflowed around text the base changed. The state-disk logic (statedb.go, Configure/Init/Shutdown, Metrics) and its tests are unchanged. BuildWithDeps still calls SetLocalInstall before Configure (core/plugins/deps.go:136), so the ~/.cortex path still applies on a local install.

No blocking issues. My earlier findings stay resolved. The DELETE follow-up is still deferred, as agreed, and the leftover I noted earlier (24h memory TTL when OpenDisk fails in Init) hasn't changed and is harmless.

The PR targets cg/04-savings, so Go CI, CodeQL and the security scans did not run (they trigger only on PRs to main). I ran the checks locally on 4c2e6e1 (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):

  • In core: go test -race ./plugins/contextguru/ passes, go vet is clean, gofmt -l is empty and go mod tidy -diff is clean.
  • With include_plugin_contextguru, the core tests for plugins/..., pipeline/..., reloader/..., config/... and accounting/... pass, and so do the cmd/cortex ./... tests. One exception: plugins/tokenbroker/client TestClient_AcquireToken_DNSFailure hangs in my sandbox because of its egress proxy. This PR doesn't touch that package.
  • cmd/cortex and cmd/cortex-envoy are tidy and vet cleanly with the tag.
  • The tests wrote no context-guru-state.db to the scratch home.

Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (unchanged from the approved head), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: DCO and the PR-title check pass. Go CI and the scans don't run on a stacked base, so I ran the checks locally (above).

@boazdavid
boazdavid changed the base branch from cg/04-savings to main November 23, 2026 14:28
boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…Lite path

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 4c2e6e1 to 466929f Compare November 23, 2026 14:48
Comment thread core/accounting/host.go Fixed

@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

This head is a re-push of 4c2e6e1, which I approved earlier. The tree is the same (f307bc6), the parent is the same (10dafd4 on 4b6bdee), and only the committer date changed. So the state-disk change itself is the one I reviewed before, and nothing in it needs fixing. The one thing that's new is the base: the PR now targets main, so the full CI ran for the first time. Two red results come from the layers below this PR, not from its own commits. Both are already fixed in the newer heads of those PRs, so a restack clears them:

  • Go CI (core) fails. On the merge ref (f438c6e), core/audits TestTransportsSetIdleConnectionPool fails with core/plugins/contextguru/modelclient.go:19:9 builds an http.Transport without MaxIdleConnsPerHost. The test passes on main. The literal comes from #2057, and #2057's current head 31ceb90 ("Include MaxIdleConnsPerHost in the fallback transport literal") adds the field. This PR still sits on the older 4b6bdee. I couldn't download the CI log because the log host timed out from my sandbox, but this is the only failure I get locally that main doesn't also have. The other local failures (the America/Havana tzdata tests you list, tokenbroker/client DNS, and session/archive TestWriteSession_FailedEraseKeepsNumbering) fail the same way on main in my sandbox. They come from the environment (root user, egress proxy).
  • Rust (praxis) is green, but it hides cargo test failed (does not block: no praxis-mode changes). Locally, every_go_inference_field_is_set_or_listed fails with Go fields the Rust model does not give: ["inference.cacheWrite1hTokens"]. The stack still carries the old 589feae/f1a440b pricing commits, which add the Go field but not its Rust side. #2065's current head (69c7eac/0edbfcb) adds the praxis model, usage and parsed-request.fields changes, and its praxis job passes. I said in an earlier review that this came from #2065; to be precise, it comes from the stale copy of #2065 inside this stack.

So once this PR is restacked onto the current #2057 head (which carries the current #2065), both should go green. Neither is blocking for this PR's own change.

Other CI notes:

  • Go CI (core peerproc, macOS) failed on proxy.golang.org i/o timeouts while downloading modules. That's a runner network flake, so a re-run should fix it.
  • CodeQL: the high alert at core/accounting/savings.go:418 and the new medium one at core/accounting/host.go:245 (log injection on pctx.Path) are both in #2055/#2057 code that this PR doesn't touch. The host.go one looks like a false positive: slog key/value attributes are quoted by the handler, so a path can't forge a log line.
  • Every other job passes, including Go CI (authbridge cortex), (authbridge cortex-envoy), (authbridge agentop), (plugin profiles), Verify module graph is tidy and Pre-commit Checks. The check-doc-links failure I noted earlier is gone.

Verified locally on this head (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir): go test -race ./plugins/contextguru/ passes, go vet is clean and gofmt -l is empty. The merge ref merges cleanly with main. The tests wrote no context-guru-state.db to the scratch home. My earlier findings stay resolved, and the DELETE follow-up is still deferred, as agreed.

Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs, CI (core and praxis failures traced to lower layers)
Agent/IDE config (.claude/.vscode): none, in this PR's change or in the full diff against main
Commits: 22 commits against main (2 of them this PR's own), all signed-off: yes (DCO passes)
CI status: failing. Go CI (core) and Rust (praxis) fail because of the stale lower layers (see above), CodeQL flags lower-layer code, and macOS failed on a network flake. Everything else passes.

boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…Lite path

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 466929f to 1070d8e Compare November 23, 2026 17:08

@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

This head restacks the PR's two commits onto the current #2057 head (f2ae82e). git range-diff 4b6bdee..466929f f2ae82e..1070d8e reports both patches identical (=) to 466929f, which I approved. So the state-disk change (statedb.go, Configure/Init/Shutdown, Metrics, the tests and docs) is the code I reviewed before. My earlier findings stay resolved, the DELETE follow-up is still deferred as agreed, and nothing in this PR's own change needs fixing.

I said last time that the two red CI results would clear on this restack, and they did:

  • Go CI (core) passes. core/audits TestTransportsSetIdleConnectionPool passes now that 415e825 (MaxIdleConnsPerHost) is in the base. I also ran it locally.
  • Rust (praxis): cargo test passes, so the inference.cacheWrite1hTokens parity failure is gone.

CI notes:

  • Rust (praxis) is green, but its annotations say praxis end-to-end tests failed (does not block: no praxis-mode changes). This doesn't look related to this PR. The e2e test builds cmd/cortex with the local profile tags, which don't include include_plugin_contextguru, so none of this PR's code is linked into it. The go.mod changes only add new indirect modules and don't bump any existing ones. The same job on #2057's head f2ae82e passes with no annotations. I couldn't download the CI log because the log host timed out from my sandbox. Locally, I built cortex-gateway and ran TestPraxisE2E on the merge ref f784e80 as a non-root user, and it passes. A re-run of the job should confirm this was a flake.
  • CodeQL fails on two alerts: core/accounting/savings.go:419 (clear-text logging) and core/accounting/host.go:245 (log injection). Both are in #2057's code, the same two alerts are open on #2057's merge ref, and this PR doesn't touch core/accounting.
  • Dependency Review passes, with a warning that github.com/remyoudompheng/bigfft has an OpenSSF Scorecard of 2.9, below the threshold of 3. It's a transitive dependency of modernc.org/libc (and already of context-guru v0.7.3), brought in by the SQLite driver. This is for information only, not something to act on.
  • Every other job passes, including Windows, macOS peerproc, the authbridge builds, plugin profiles, module tidy and pre-commit.

Verified locally on 1070d8e (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):

  • In core: go test -race ./plugins/contextguru/ ./audits/... passes, go vet is clean, gofmt -l is empty and go mod tidy -diff is clean.
  • With include_plugin_contextguru, these core tests pass: plugins/contextguru/..., plugins/all/..., pipeline/..., reloader/..., config/..., accounting/..., plugins/inferenceparser/... and plugins/toolprune/.... The tagged cmd/cortex ./... tests pass too.
  • cmd/cortex and cmd/cortex-envoy are tidy and vet cleanly with the tag.
  • The tests wrote no context-guru-state.db to the scratch home.

Author: boazdavid (repo admin; GitHub association CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs, CI (praxis e2e, CodeQL, Dependency Review)
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits against main (2 of them this PR's own), all signed-off: yes (DCO passes)
CI status: everything passes except CodeQL, whose two alerts are in #2057's code. Rust (praxis) has a non-blocking e2e failure that I couldn't reproduce locally.

boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…Lite path

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 1070d8e to 6ea82c3 Compare November 23, 2026 18:08
Comment thread core/accounting/savings.go Fixed
Comment thread core/accounting/host.go Fixed

@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

I reviewed only this layer's change (cg/04-savings...6ea82c3): statedb.go, the Init/Shutdown lifecycle in plugin.go, the tests, docs and module updates. The design holds up. The shared *sql.DB is opened in Configure and starts no goroutine. The flusher starts in Init and is closed (flushed) in Shutdown, so the pipeline's Start/unwind/Stop contract owns it. configuredPlugin forwards both hooks, and the reloader calls Start on the new pipeline and Stop on the drained one. The stated fix works end to end: context-guru v0.7.3's apply.BodyOpts calls loadSessionState -> Memory.LoadSession before the pipeline reads the store, so a restarted or reloaded instance restores the session from the file. The file: URI escaping is correct for modernc v1.56.0. With the file: prefix, newConn passes the whole DSN to sqlite3_open_v2 with SQLITE_OPEN_URI. Because the path's ? is escaped to %3f, the first ? it splits on is the pragma query. I found no blocking issues. There are two non-blocking notes inline.

Out of scope for this layer: CodeQL's two open alerts (core/accounting/savings.go:422, core/accounting/host.go:247) come from #2057's code, not this diff.

Author: boazdavid (admin, author_association CONTRIBUTOR - maintainer)
Areas reviewed: Go (contextguru plugin, pipeline lifecycle, reloader interaction), go.mod/go.sum (modernc.org/sqlite and transitive deps), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 7 commits, all signed-off: yes
CI status: Go CI jobs passing, no failure annotations; CodeQL failing on #2057's alerts; macOS peerproc pending. Locally: go vet clean, gofmt -l empty, go test -race ./plugins/contextguru/ passes.

Comment thread docs/session-api.md Resolved
Comment thread core/plugins/contextguru/plugin.go Resolved
…ge and sessions

Record the accountant's savings and the context operators' own model-call
spend in the cost ledger, /v1/usage, the sessions API and agentop, each split
by billing basis so only a true-dollar (API-key) figure is summed as money; a
subscription login's saving is valued in usage-limit units, and an
unknown-billing one is shown apart. Plugin model-call spend is kept out of
cost_usd so the existing spend totals keep their meaning.

Add core/accounting/{savings,price} and the savings-agreement tests that replay
every accountant case through Cortex's own conversion, core/cost/event, and the
savings parts of settle, usage and ledger (removing the old avoided/decode and
estimate paths). agentop shows the net, the penalty, the units and the spend,
each named.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
- Move the CodeQL suppression above the slog.Debug call in logTokens, where CodeQL reads it.
- Log one DEBUG line when an operator reported ops on a path wire.FormatOf cannot read, and pin
  with a test that a saving on /chat/completions (no /v1) is recorded.
- Keep HTTPS_PROXY for context-guru's own model calls outside a local install; pin it off only
  on a local install, where it points back into Cortex.
- Count a row whose only accountant figure is a negative net, or is in units, in
  ledger.CurrenciesIn, as the ring does.
- Say why Saving.TokensAvoided and operatorTokens count cache-effect tokens differently.
- Drop the metrics_push docs (rossoctl#2062) and the keep-alive purpose row and agentop label (rossoctl#2059).
- Add the context-guru-plugin.md section the pricing.md link points to.
- Restore the session-api.md and CLAUDE.md paragraph a rebase duplicated.
- Document how the billing basis is chosen from the client's credential (follow-up: rossoctl#2074).

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

core/audits TestTransportsSetIdleConnectionPool checks the composite
literal itself, not a later field assignment, so the fallback branch
(http.DefaultTransport not an *http.Transport) failed the audit.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…ier value

pricing.Tier has no TierCacheWrite1h constant — see pricing.Tier's own doc: the
1h premium is a subset of CacheWrite and is priced through
pricing.Rates.CacheWrite1hRate, not a fifth tier slot. price.go and savings.go
still referenced the old, pre-rossoctl#2065-rewrite constant, which no longer exists,
so this layer did not build. USD1h prices those tokens directly, and
largestTier names the 1h case as a literal "cache_write_1h" string instead of
going through pricing.Tier.String().

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…, correct

Four real review findings on this layer:

- OpenAI chat tools store their name in function.name, not the top-level name
  envelopeOps read. A removal among them matched nothing, fell back to the
  no-saving path, and lost the saving entirely. toolsOps now falls back to
  function.name before assigning the unnamed key.

- A zero prompt-tier total (an error status with no prompt usage, or a
  context-guru call billed before an inference-router resend) dropped a
  completed operator spend along with the never-priced savings, because the
  gate in InferenceParser.accountant looked only at the prompt counters.
  Spend does not depend on them — each record prices from its own operator
  call. The gate now also asks when the request has a reported op.

- One layer deeper: Host.Compute can refuse the whole request (a rejected
  status, or more than one upstream round) independent of the prompt total,
  which discarded the spend the same way. Host.Savings now reads the raw
  reported ops directly and prices any completed spend without going through
  Compute at all when it refuses — which also means a multi-round request's
  mismatched usage/body pair still cannot corrupt the thread's persisted
  cache-effect state for later requests, the actual reason Compute refuses.

- A spend record carried no currency, so an operator's call to a different,
  differently-priced host (a credits-billed gateway beside a USD-endpoint
  call) was summed into the primary request's total as if it were the same
  unit. SpendRecord now carries Currency, SpendPrice returns it, and
  event.Figures skips a spend whose currency does not match the record's own
  rather than mixing units.

Also dismissed 2 code-scanning alerts (clear-text-logging on the session id
this package logs, log-injection on a request path it logs) as false
positives, matching the repo's own precedent for the identical pattern
(alerts rossoctl#359 and rossoctl#334 on main): the session id is validated before it is
accepted, not a credential, and slog's TextHandler already quotes a value
before it reaches the log.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…known, and fix a real regression in the zero-prompt-total gate

Two more findings from clawgenti's re-review:

- The currency fix only gated PluginSpendMicros (basis usd). PluginSpendUnknownMicros
  is "not money", but it is still one number, and a USD figure and a differently-
  priced currency's figure summed into it is just as mixed. Same gate now applies there.

- The zero-prompt-total gate in InferenceParser.accountant asked whenever
  pctx.ReportedOps() was non-empty, reasoning that the pass before any data arrives
  has no ops either. That was wrong: a structural op (tool-prune's removal, say)
  reports during OnRequest, before the response exists, so that pass's ops list is
  not empty either — and asking there calls Host.Compute with an inference extension
  that is still all zeros, which Compute latches forever, so the real counts that
  arrive on a later pass are never priced at all. Reproduced by clawgenti; fixed by
  gating on pctx.StatusCode (set once, when the response is read) instead of on
  ReportedOps. Added a regression test pinning the exact two-pass sequence.

Also dismissed the same 2 alerts' re-raised instances (rossoctl#365, rossoctl#370) after they shifted
line following the rebase onto main — the earlier dismissal (rossoctl#372, rossoctl#373) stopped
applying once that commit was superseded.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…tream broke

clawgenti's re-review: the StatusCode-based gate in InferenceParser.accountant
dropped a completed operator spend when a stream broke mid-body, because
forwardproxy's classifyBrokenStream resets pctx.StatusCode to 0 there, same as
a response that was never read — specifically so the outcome is not misread
as a 200. That is right for the outcome, but a context-guru call already
billed on the request is not undone by the break.

The gate now also asks when pctx.ResponseDelivered() is true: every listener
marks that once bytes actually reached the client, before a mid-stream break
can zero StatusCode, so it is set and stays set in exactly the situation
StatusCode alone could no longer tell apart. Added a test for the broken-
stream case.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Persist the per-session state the context-guru engine needs between turns —
the summary checkpoint, the last billed input, freeze decisions — in the
engine's session_state table, in a SQLite file (modernc.org/sqlite, pure Go).
The state survives a restart and a config reload, so the prompt prefix the
provider has cached stays valid.

On a local install the file is ~/.cortex/context-guru-state.db; otherwise it
lives in the user cache directory. It holds content, so it is mode 0600 in a
0700 directory, and a row is kept 30 days after its last write. The plugin
fails open: with no usable file it keeps the state in memory and logs one WARN.

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

Review fixes for rossoctl#2058:

- Open the shared *sql.DB in Configure, and start the store.Disk (its
  flusher goroutine) in Init. A pipeline that a failed build or reload
  drops is never started, so it no longer leaks a flusher.
- Set the 24h state-key lifetime only when the database opened. On the
  fail-open path the engine's default stays.
- Report Disk.Errors() as the state_db_errors metric.
- Escape '%', '#' and '?' in the file: URI. A '#' in the path made
  SQLite open another file, with the umask's mode, outside the 0700
  directory.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from 6ea82c3 to 8c164cb Compare November 24, 2026 10:45

@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

This layer (cbf36f5 + 8c164cb, reviewed against cg/04-savings) backs the context-guru store.Memory with context-guru's own store.Disk on a SQLite file. It opens a shared *sql.DB per path in Configure, starts the flusher in Init, flushes it in Shutdown, and fails open to memory. I verified the lifecycle against pipeline.Start/Stop and the reloader (a dropped build is never started, so it leaks no flusher), and checked that apply.BodyOpts calls LoadSession on the request path, so state written to disk really is reloaded after a restart. The file: URI escaping is correct for modernc: with a file: prefix the whole DSN goes to sqlite3_open_v2 with SQLITE_OPEN_URI. The -wal/-shm files inherit the 0600 mode. The file and its session_state table are both new, so no older on-disk format needs to stay compatible, and CREATE TABLE IF NOT EXISTS keeps an existing file. I found no must-fix issues, and the two suggestions below can go in a follow-up.

Locally at head 8c164cb (GOWORK=off):

  • go test ./plugins/contextguru/ passes, and so do -tags include_plugin_contextguru runs of plugins/all, config, pipeline, accounting/... and reloader. None of these tests left a state file in $HOME or $XDG_CACHE_HOME.
  • go mod tidy -diff is clean in core, cmd/cortex, cmd/cortex-envoy and cmd/agentop.
  • go build -tags include_plugin_contextguru of cmd/cortex succeeds, and so does GOOS=windows go vet of the plugin.

Author: boazdavid (CONTRIBUTOR association, admin repo permission, so a maintainer)
Areas reviewed: Go (plugin, state DB, lifecycle), go.mod/go.sum, docs, CLAUDE.md
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this layer, all signed off: yes
CI status: still pending (queued) when I posted; nothing has failed yet

Comment thread core/plugins/contextguru/plugin.go Resolved
Comment thread docs/session-api.md Resolved

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

I reviewed only this PR's own 2 commits (cbf36f5, 8c164cb). I found no must-fix problem. I checked these points and they are correct:

  • Disk.Close flushes the writes but does not close the shared *sql.DB, so a draining instance and a new instance can use the same handle.
  • The engine calls LoadSession (apply.go:1397).
  • Init and Shutdown go through configuredPlugin.
  • ~/.cortex is 0700.
  • No test outside the package builds the real plugin, so tests do not write to the user's real directories.

Four earlier comments still have no answer: TTL when OpenDisk fails (plugin.go:304), lost writes on a reload (plugin.go:359), and two about erase (session-api.md:422, :424). I agree that they are suggestions and not blockers. Before this PR, a reload lost all of the state, so the PR makes it better.

Author: boazdavid (MEMBER — maintainer)
Areas reviewed: Go, go.mod dependencies (modernc.org/sqlite, pure Go), docs, CLAUDE.md
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes
CI status: passing

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

}
db, err := openStateDB(path)
if err != nil {
slog.Warn("context-guru: session state stays in memory; its database could not be opened",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: The AuthBridge image runs as uid 1001 with no home directory, so $HOME is /. Then os.UserCacheDir gives /.cache and MkdirAll fails. Each sidecar that turns on context-guru logs this WARN at start and again at each config reload, because each Configure tries again. The feature cannot work in that pod, so a WARN each time is noise. You could log at INFO when localInstall is false, or remember the failure for each path.

@huang195
huang195 merged commit e2645ea into rossoctl:main Nov 24, 2026
41 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants