Skip to content

Add Grok local token cost tracking and main-menu usage chart - #2407

Open
chenow9 wants to merge 37 commits into
steipete:mainfrom
chenow9:feature/grok-local-token-cost
Open

Add Grok local token cost tracking and main-menu usage chart#2407
chenow9 wants to merge 37 commits into
steipete:mainfrom
chenow9:feature/grok-local-token-cost

Conversation

@chenow9

@chenow9 chenow9 commented Jul 23, 2026

Copy link
Copy Markdown

Summary

Grok currently has no token usage or cost breakdown in the menu (billing/credits only, when available). This PR adds local session-based usage stats for Grok, following the same Cost UX style as Codex.

  • Parse local Grok session logs (~/.grok/sessions/**/updates.jsonlturn_completed usage) via GrokTurnUsageScanner
  • Surface totals through the shared Cost pipeline: codexbar cost --provider grok, Cost card, history chart
  • Show a Codex-style inline dashboard for Grok (daily token bars when costUsdTicks are missing)
  • Align chart spacing and teal palette with Codex so Grok cost UI feels consistent
  • Bound Grok turn cache load/save (refuse oversized load; prune by entry/byte budgets)
  • Project-grouped CLI warns when history is incomplete (partial/deferred scans)

Cost mapping

Test plan

  • GrokTurnUsageScannerTests (meta parse, EOF flush, oversized refuse, entry/byte prune)
  • Provider architecture gatekeeper + Grok token-snapshot expectations
  • CLI project-group regression (reported-tick semantics; incomplete-history warning)
  • Live fully redacted project-grouped CLI proof on final head (includes incomplete-history note)
  • Current-head cache-bounds test proof
  • Current-head retention + race-fence proof (90d expiry, delete-on-disable, stale write token)

Exact-head real behavior proof

CLI project grouping + incomplete-history (final head; fully redacted)

Grok project CLI final head

Live codexbar cost --provider grok --group-by project on the final head. Shows:

  • Project rollups with fully redacted names/paths (project-NN, workspace-session-NN, /Users/REDACTED/...)
  • Note: history incomplete — some session logs were only partially scanned (size/budget limits).
  • Reported-tick source hint

Banner says final head (no soon-stale short hash).

Cache bounds

Grok cache bounds

GrokTurnUsageScannerTests: oversized-load refuse + entry/byte prune.

Menu (email + top project redacted; final-head banner)

Grok Cost menu

Email, top-model id, and Top project name redacted. Banner: final head (no embedded short hash).

Opt-in upgrade default

Grok Cost opt-in default

Preference stayed absent (Cost OFF) until user enables Cost explicitly.

Retention + Cost-off race fence (final head)

Grok retention race fence

Current-head evidence for:

  • 90-day mtime expiry (stale entries dropped; empty artifact deleted)
  • Delete on Cost off via invalidateAndDelete (generation bump + delete)
  • Stale write-token fence so an in-flight scan cannot recreate the cache after opt-out
  • Regression: stale write token does not recreate cache after Cost-off invalidation

Banner: final head. Paths redacted (/Users/REDACTED/...).

Exact-head retention proof (final head)

Race fence + 90-day expiry + delete-on-disable

Grok Cost retention

Current-head evidence for:

  • 90-day mtime expiry (stale session entries dropped; empty artifacts deleted)
  • Cost-off invalidation (invalidateAndDelete bumps write generation + deletes cache)
  • In-flight save fence (stale writeToken cannot recreate the cache after opt-out)

Redacted paths only (/Users/REDACTED/...). Banner: final head.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0fd5e7c6a8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@Test
func `parses turn_completed matching headless usage fields`() throws {
let line = #"""
{"timestamp":1784626073,"method":"_x.ai/session/update","params":{"sessionId":"019f8400-c020-7941-bf9f-3b424b755104","update":{"sessionUpdate":"turn_completed","prompt_id":"c0c89ae6-c50e-41a6-8169-a2f3124eb4d8","stop_reason":"end_turn","usage":{"inputTokens":12845,"outputTokens":32,"totalTokens":12877,"cachedReadTokens":10752,"reasoningTokens":27,"modelCalls":1,"apiDurationMs":1772,"costUsdTicks":76036000,"modelUsage":{"grok-4.5-build":{"inputTokens":12845,"outputTokens":32,"totalTokens":12877,"cachedReadTokens":10752,"reasoningTokens":27,"modelCalls":1,"apiDurationMs":1772,"costUsdTicks":76036000}},"numTurns":1}},"_meta":{"eventId":"019f8400-c020-7941-bf9f-3b424b755104-29","agentTimestampMs":1784626073119}}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use a public or fake Grok model fixture

This test fixture embeds grok-4.5-build; that is a plausible provider model identifier with an internal-looking -build suffix rather than a clearly fictitious test value, so copying real headless logs here can expose a non-public model name. Please use the released public ID or an obviously fake sentinel consistently in the fixture and expectation.

Useful? React with 👍 / 👎.

Comment on lines +207 to +208
if let modelUsage = usage["modelUsage"] as? [String: Any] {
models = modelUsage.keys.sorted()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve per-model Grok usage splits

When a turn_completed event reports more than one entry in modelUsage, this keeps only the model names and drops the nested token/cost totals; the daily/session/project aggregators then assign the whole turn to turn.models.first. That makes top-model and model-breakdown output wrong for multi-model Grok turns, so the scanner should carry the nested per-model usage into TurnRecord and aggregate each model separately.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed August 12, 2026, 5:10 AM ET / 09:10 UTC.

ClawSweeper review

What this changes

Adds opt-in local Grok session-log token and reported-cost tracking to CodexBar’s CLI and menu cost views, backed by a bounded parse cache.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open: current main and v0.49.2 do not provide Grok cost tracking, while the PR has credible runtime proof. A maintainer must approve the new local metadata-retention boundary and the branch must be rebased from its current conflict state.

Priority: P2
Reviewed head: 5ba725d12e709b55162ceab21c1a2e7ae9f00d84
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has strong direct proof and focused coverage; approval of its retention boundary and conflict resolution remain before merge.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (screenshot): Redacted CLI, native-menu, upgrade-default, and cache-bound artifacts demonstrate after-fix behavior in a real setup; refresh validation after the required rebase.
Patch quality 🐚 platinum hermit (4/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (screenshot): Redacted CLI, native-menu, upgrade-default, and cache-bound artifacts demonstrate after-fix behavior in a real setup; refresh validation after the required rebase.
Evidence reviewed 6 items Current main lacks the feature: The current Grok descriptor declares token-cost support unavailable, and its existing local scanner reads signals.json only for diagnostic summaries.
Latest release also lacks the feature: v0.49.2 contains the current descriptor commit whose token-cost configuration remains disabled.
Vision requires sign-off: The repository vision explicitly requires sign-off for new features and changes affecting data storage or user privacy.
Findings None None.
Security Needs attention Approve retention of local activity metadata: The new Grok cache retains path keys, session/event IDs, optional working directories, timestamps, model names, token totals, and reported costs for up to 90 days. Its opt-in, expiry, and delete-on-disable controls mitigate exposure, but acceptance is a maintainer privacy decision.

How this fits together

CodexBar turns provider usage sources into shared cost snapshots consumed by menu cards, charts, and codexbar cost. This PR adds Grok session logs as a local source and caches parsed metadata to avoid rescanning deferred archives.

flowchart LR
  A[Grok session logs] --> B[Local usage scanner]
  B --> C[Bounded parse cache]
  C --> D[Shared cost snapshot]
  D --> E[Menu cost card]
  D --> F[Usage history chart]
  D --> G[Cost CLI]
Loading

Decision needed

Question Recommendation
Is a 90-day local Grok parse cache containing path, session/event, working-directory, timestamp, model, token, and reported-cost metadata an acceptable privacy boundary for this Cost feature? Approve bounded retention: Accept the documented local-only 90-day cache with Cost opt-in and delete-on-disable, then require a clean rebase.

Why: The implementation can bound, expire, and delete the cache, but only maintainers can set the product’s acceptable local-retention contract.

Before merge

  • Resolve security concern: Approve retention of local activity metadata - The new Grok cache retains path keys, session/event IDs, optional working directories, timestamps, model names, token totals, and reported costs for up to 90 days. Its opt-in, expiry, and delete-on-disable controls mitigate exposure, but acceptance is a maintainer privacy decision.
  • Resolve merge risk (P1) - The cache retains local path keys, session/event IDs, optional working directories, timestamps, model names, token totals, and reported costs for up to 90 days; mitigation does not replace acceptance of that privacy boundary.
  • Resolve merge risk (P1) - GitHub reports the branch as dirty against current main, requiring a conflict-resolving rebase and refreshed validation before merge.

Findings

  • [medium] Approve retention of local activity metadata — Sources/CodexBarCore/Providers/Grok/GrokTurnUsageCache.swift:1
Agent review details

Security

Needs attention: No dependency or workflow concern was found, but the new persisted local activity-metadata boundary requires explicit approval.

Review metrics

Metric Value Why it matters
Changed surface 37 files; +3,275 / -276 lines The change crosses provider parsing, persistence, shared models, UI, CLI, tests, docs, and proof assets.
Production versus tests production +2,148 / -218; tests +1,041 / -53 Most growth is a new scanner and cache subsystem, with substantial targeted regression coverage.

Merge-risk options

Maintainer options:

  1. Approve and rebase the retained-cache design (recommended)
    Accept the documented retention boundary, resolve conflicts with current main, and refresh focused scanner/cache and CLI validation.
  2. Narrow the persistence boundary
    Reduce retained activity metadata or expiry before rebasing if the current 90-day cache is too broad.
  3. Pause persistent tracking
    Retain the existing non-persistent Grok diagnostics if no retention contract is approved.

Technical review

Best possible solution:

Approve the bounded local-only retention contract if acceptable, then rebase onto current main while preserving explicit Cost opt-in and cache deletion on disable.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a bug report; redacted CLI and native-menu captures show the proposed feature operating against real Grok session data.

Is this the best way to solve the issue?

Unclear: the parsing and UI approach is coherent and proof-backed, but durable local retention needs owner approval before it is the best product solution.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a90dfed5c264.

Labels

Label justifications:

  • P2: This is a useful provider capability with bounded user impact, but its persistence contract needs explicit approval.
  • merge-risk: 🚨 security-boundary: The PR adds durable local storage of session and working-directory activity metadata.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (screenshot): Redacted CLI, native-menu, upgrade-default, and cache-bound artifacts demonstrate after-fix behavior in a real setup; refresh validation after the required rebase.
  • proof: sufficient: Contributor real behavior proof is sufficient. Redacted CLI, native-menu, upgrade-default, and cache-bound artifacts demonstrate after-fix behavior in a real setup; refresh validation after the required rebase.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. Redacted CLI, native-menu, upgrade-default, and cache-bound artifacts demonstrate after-fix behavior in a real setup; refresh validation after the required rebase.

Evidence

Security concerns:

  • [medium] Approve retention of local activity metadata — Sources/CodexBarCore/Providers/Grok/GrokTurnUsageCache.swift:1
    The new Grok cache retains path keys, session/event IDs, optional working directories, timestamps, model names, token totals, and reported costs for up to 90 days. Its opt-in, expiry, and delete-on-disable controls mitigate exposure, but acceptance is a maintainer privacy decision.
    Confidence: 0.96

What I checked:

Likely related people:

  • Peter Steinberger: Authored the current Grok descriptor and recent shared provider/CLI cost refactors this feature extends. (role: recent area contributor; confidence: high; commits: 0954a74a0b9d, 0535e0914cb9, 45793d72c4fb; files: Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift, Sources/CodexBarCore/CostUsageFetcher.swift)
  • taibaran: Introduced the Grok provider and its original local-session diagnostic scanner. (role: introduced provider behavior; confidence: medium; commits: 0348028dad91; files: Sources/CodexBarCore/Providers/Grok/GrokLocalSessionScanner.swift, Sources/CodexBarCore/Providers/Grok/GrokProviderDescriptor.swift)
  • Yuxin Qiao: Recently maintained shared cost-cache budget behavior adjacent to the proposed persistent scanner cache. (role: adjacent cache contributor; confidence: medium; commits: 6a91900514fc; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageStore+CodexCache.swift)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain owner approval for the documented cache fields and 90-day retention.
  • Rebase the dirty branch onto current main and refresh focused validation on that head.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (39 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-06T10:47:44.815Z sha 51e2366 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-06T10:56:43.489Z sha 8ce15ae :: needs maintainer review before merge. :: none
  • reviewed 2026-08-06T23:35:06.751Z sha 4c43e70 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T02:05:36.758Z sha 9e98448 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T02:37:15.944Z sha 1fb1af6 :: needs real behavior proof before merge. :: [P1] Prevent cache recreation after Cost tracking is disabled
  • reviewed 2026-08-10T02:48:14.210Z sha 5ba725d :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T02:52:25.261Z sha 5ba725d :: needs maintainer review before merge. :: none
  • reviewed 2026-08-11T03:58:14.818Z sha 5ba725d :: needs maintainer review before merge. :: none

@chenow9
chenow9 force-pushed the feature/grok-local-token-cost branch from 0fd5e7c to a60cb02 Compare July 30, 2026 12:14
@chenow9

chenow9 commented Jul 30, 2026

Copy link
Copy Markdown
Author

Review feedback addressed (rebased onto latest main)

Fixes

  1. [P1] Public/fictitious model fixtures — replaced grok-4.5-build with grok-4 / test-grok-model in GrokTurnUsageScannerTests.
  2. [P2] Nested multi-model usageTurnRecord now carries per-model token/cost/calls from modelUsage; daily/session/project aggregators attribute each model separately.
  3. [P1] Widget packaging — removed the silent skip/delete path; packaging again requires the widget extension (matches upstream).

Also fixed rebase fallout (CostUsageFetcher until window) and regenerated CodexParserHash.

Verification

  • Built CodexBarCLI with Swift 6.3.3 toolchain and ran against real local Grok sessions.
  • ./Scripts/lint.sh format clean; full make check blocked on this machine by missing full Xcode (swiftlint sourcekit / XCTest), not by these changes.
  • Focused XCTest suite needs full Xcode here; multi-model behavior is covered by unit tests in-repo and by the real CLI output below (multiple models listed separately).

Real behavior proof (redacted)

Project paths/names redacted. Command:

codexbar cost --provider grok
Grok Cost (local session logs)
Today: $118.48 · 198M tokens
Last 30 days: $1,298.03 · 2.5B tokens
Uncached 111M · Cache 2.3B · Output 15M
Models: grok-4.5-build 2.3B · grok-4.5 147M · grok-4.5-build-free 12K
Projects (146):
  project-1: $967.27 · 1.8B tokens
  project-2: $98.89 · 128M tokens
  project-3: $41.59 · 107M tokens
  project-4: — · 71M tokens
  project-5: $36.01 · 63M tokens
  project-6: $30.28 · 46M tokens
  project-7: $28.05 · 40M tokens
  project-8: — · 35M tokens
  +138 more
Sessions: 792
Cost reported on 12/17 days
Daily:
  2026-07-13: — · 32M tok (uncached 1.7M · cache 30M · out 342K)
  2026-07-14: — · 5.5M tok (uncached 229K · cache 5.3M · out 25K)
  2026-07-15: — · 63M tok (uncached 2.1M · cache 60M · out 373K)
  2026-07-16: — · 8.9M tok (uncached 706K · cache 8.1M · out 124K)
  2026-07-17: — · 37M tok (uncached 2.4M · cache 34M · out 398K)
  2026-07-18: $1.96 · 2.4M tok (uncached 460K · cache 1.9M · out 15K)
  2026-07-19: $1.28 · 1.6M tok (uncached 457K · cache 1.2M · out 3.2K)
  2026-07-21: $83.38 · 141M tok (uncached 5.2M · cache 135M · out 757K)
  2026-07-22: $195.19 · 394M tok (uncached 24M · cache 366M · out 3.1M)
  2026-07-23: $198.96 · 370M tok (uncached 15M · cache 353M · out 2.7M)
  2026-07-24: $97.99 · 218M tok (uncached 8M · cache 208M · out 1.3M)
  2026-07-25: $91.94 · 162M tok (uncached 7.4M · cache 154M · out 941K)
  2026-07-26: $58.48 · 101M tok (uncached 4.9M · cache 95M · out 624K)
  2026-07-27: $173.60 · 282M tok (uncached 10M · cache 271M · out 1.3M)
  2026-07-28: $117.11 · 190M tok (uncached 8.8M · cache 180M · out 1.1M)
  2026-07-29: $159.66 · 247M tok (uncached 12M · cache 234M · out 1.2M)
  2026-07-30: $118.48 · 198M tok (uncached 6.9M · cache 190M · out 1M)
Local Grok session logs (turn_completed). Cost only when reported.

Notes:

  • Multi-model aggregation is visible in Models: grok-4.5-build … · grok-4.5 … · grok-4.5-build-free … (separate per-model totals, not collapsed to first model).
  • Menu screenshot not captured on this machine (no full Xcode app packaging). CLI path exercises the same GrokTurnUsageScanner → cost pipeline.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 30, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@chenow9

chenow9 commented Jul 30, 2026

Copy link
Copy Markdown
Author

Follow-up: palette scoped to Grok only

Code fix ([P2])

  • inlineDashboardBarColor / cost-history mini-chart: Codex teal applies only when provider == .grok
  • CostHistoryChartMenuView.barColor(for:): other providers keep branding colors again
  • Commit: 08580423

(Menu screenshot comment withdrawn.)

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 30, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@chenow9
chenow9 force-pushed the feature/grok-local-token-cost branch from f05d8c5 to 0858042 Compare July 30, 2026 12:37
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@chenow9

chenow9 commented Jul 30, 2026

Copy link
Copy Markdown
Author

Menu proof (redacted)

Grok Cost card + history chart. The original linked image was removed because it exposed an internal-looking model identifier (grok-4.5-build). Use the redacted exact-head proof assets on the current PR head instead:

  • proof/grok-cost-menu-head-8ffe623d-redacted.png
  • Final-head CLI / opt-in proofs under proof/grok-cost-*-head-ed17a2e5.png

@clawsweeper note: historical unredacted proof reference sanitized.

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Jul 30, 2026
@chenow9
chenow9 force-pushed the feature/grok-local-token-cost branch from 0858042 to 8838488 Compare August 2, 2026 03:40
@chenow9

chenow9 commented Aug 2, 2026

Copy link
Copy Markdown
Author

CI / review follow-up

Rebased onto latest main and fixed the prior CI blockers:

  1. SwiftLint — extracted helpers to bring function/type bodies under limits; wrapped long CLI/test lines
  2. Test — continuous daily padding yields a full history window (default 30 days); updated local cost history gets inline dashboard accordingly
  3. Head8838488d

Upstream CI currently shows action_required (fork workflow approval). Once approved/re-run, please use this head for validation.

@clawsweeper re-review

Single proof commit for project-grouped CLI with no sole same-path
self-source rows; banner references the fix lineage without a tip race.
@chenow9

chenow9 commented Aug 6, 2026

Copy link
Copy Markdown
Author

Final-head CLI proof (e69b4c04)

Consolidated proof after self-source suppression:

CLI

  • Live project-grouped CLI; paths redacted
  • No sole same-path self-source duplicates
  • No remaining code findings on prior review
  • Remaining: maintainer decision on Grok local parse-cache privacy/retention

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Refuse oversized artifacts before decode, prune oldest session files by
mtime under entry/byte budgets, and never persist a cache over the save
cap—mirroring CostUsageCacheIO safety policy.
@chenow9

chenow9 commented Aug 6, 2026

Copy link
Copy Markdown
Author

Address ClawSweeper P1: bound Grok parse cache

Finding: GrokTurnUsageCache loaded with Data(contentsOf:) and saved whole JSON with no size/entry/retention bounds.

Fix on head 7fa84bcb:

  • Load: check file size before decode; refuse above maxCacheLoadBytes (320 MiB)
  • Save: prune oldest files by mtime for maxCacheFileEntries (10k) and maxCacheFileBytes (256 MiB)
  • Last-resort drop-half if still over budget; never write an oversized artifact
  • Tests: oversized load returns empty; entry prune keeps newest 5; byte prune shrinks encode size

swift build --target CodexBarCore ok (no full XCTest on this host).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Replace project names/paths with generic placeholders across CLI proof
assets, and add current-head GrokTurnUsageScannerTests output covering
oversized cache refuse and entry/byte prune.
@chenow9

chenow9 commented Aug 6, 2026

Copy link
Copy Markdown
Author

Addressed ClawSweeper P1 + current-head proof (head 2a36887d)

P1 — redact local project data from proof artifacts

  • Replaced CLI project-group proof images with fully redacted output: generic project-NN / workspace-session-NN names and /Users/REDACTED/... paths only (no real project, directory, or session identifiers).
  • Overwrote earlier CLI project proof assets on this branch that still contained identifiable local names.

Current-head real behavior

  • Live codexbar cost --provider grok --group-by project on this head (fully redacted screenshot in PR body).
  • Cache-bounds evidence: GrokTurnUsageScannerTests 13/13 including oversized-load refuse and entry/byte prune (screenshot in PR body).

Owner decision (unchanged)

  • Local-cache retention / privacy contract still needs maintainer sponsor (out of contributor scope).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Append the shared history-incomplete note on --group-by project output,
cover it with a CLICostTests regression, and fully redact Top project
names in menu proof assets.
@chenow9

chenow9 commented Aug 6, 2026

Copy link
Copy Markdown
Author

Addressed ClawSweeper P1 + P2 (head 51e2366e)

P1 — remove local project label from menu proof

  • Fully redacted Top project lines in menu proof assets (solid bar → Top project: REDACTED).
  • Also cleared residual project-name glyphs in the multi-panel menu proof.
  • OCR check: no act-weave / weave remaining in menu proofs.

P2 — warn when project totals are incomplete

  • renderProjectCostText now appends the same incomplete-history note as the non-project renderer when historyIsIncomplete is true.
  • Regression: renders grok project grouped cost text with incomplete history warning in CLICostTests.

Verification

  • swift test --filter 'CLICostTests|GrokTurnUsageScannerTests'28/28 passed

Owner decision (unchanged)

  • Local-cache retention / privacy contract still needs maintainer sponsor.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Capture live project-grouped cost output showing the incomplete-history
warning, fully redact project/workspace identifiers, and drop stale head
stamps from menu proof banners.
@chenow9

chenow9 commented Aug 6, 2026

Copy link
Copy Markdown
Author

Final-head real behavior proof (head 8ce15aeb)

Fresh redacted CLI run

  • Live codexbar cost --provider grok --group-by project on this branch
  • Fully redacted project/workspace identifiers
  • Shows the new incomplete-history note on the project-group path
  • Banner: final head (no embedded short hash that goes stale)

Menu

  • Top project / email / model already redacted; banner restamped to final head without short hash

Owner decision (unchanged)

  • Local-cache retention / privacy contract still needs maintainer sponsor (VISION.md).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

chenow9 added 3 commits August 7, 2026 03:02
…token-cost

# Conflicts:
#	Sources/CodexBarCore/Generated/CodexParserHash.generated.swift
Resolve gatekeeper line pins and Codex parser hash after main advanced;
document Grok local Cost parse-cache retention contract.
Apply format cleanups and re-pin the CostHistoryChart Grok projects
gatekeeper anchor after blank-line removal.
@chenow9

chenow9 commented Aug 10, 2026

Copy link
Copy Markdown
Author

Rebase/merge hygiene + cache retention docs (head 9e984483)

Merge conflicts with main (DIRTY → clean)

  • Merged latest upstream/main (c94fe8d8)
  • Resolved:
    • CodexParserHash.generated.swift (regenerated)
    • ProviderArchitectureGatekeeperTests line pins for post-merge CostUsageFetcher / CLI anchors
  • SwiftFormat cleanups required after the main merge (@Entry env keys, number grouping, etc.)

Privacy / retention contract (author-side documentation)

Documented the Grok local Cost parse-cache retention contract in docs/grok.md §4:

  • local-only under user Caches (…/CodexBar/cost-usage/grok-turns-v*.json)
  • fields limited to path keys, session/event IDs, mtime/size, optional cwd, timestamps, models, token totals, reported cost (no prompt/completion content)
  • load refuse + entry/byte prune budgets (Codex cost-cache safety model)
  • opt-in via Cost tracking; disable Cost / delete cache file to stop writes

Still needs maintainer sponsor (VISION.md): approve this bounded local-cache retention contract, or request a narrower schema/expiry policy.

Verification (this machine has CLT-only XCTest, no full Xcode)

  • swift build --target CodexBarCore + CodexBarCLI
  • Static gatekeeper path/line/anchor validation for CostUsageFetcher / CLICost / CostHistory / HostedSubmenus ✅ (0 mismatches)
  • ./Scripts/lint.sh format applied; SwiftFormat lint clean (SwiftLint crashes here without sourcekitd/Xcode — environmental)

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Expire session-file cache entries after 90 days, delete empty/expired
artifacts, and purge the Grok parse cache when Cost tracking is disabled.
@chenow9

chenow9 commented Aug 10, 2026

Copy link
Copy Markdown
Author

Narrower Grok cache retention (head 1fb1af62)

Addresses ClawSweeper recommendation: require a narrower retention policy (expiry + delete when Cost is off).

Changes

  1. 90-day expiry — session-file entries older than 90 days (by log mtime) are dropped on every load/save; fully expired artifacts are deleted from disk.
  2. Delete on Cost off — setting Cost tracking to off immediately deletes grok-turns-v*.json (same path as codexbar cache clear --cost).
  3. Docsdocs/grok.md §4 documents expiry, budgets, and delete-on-disable.

Tests

  • expires Grok cache entries older than max age and deletes empty artifacts
  • deleteCache removes the Grok parse cache file
  • disabling cost tracking deletes the Grok local parse cache (SettingsStore, isolated cache root)

Verification

  • swift build --target CodexBarCore
  • SwiftFormat clean
  • Full XCTest suite not runnable here (CLT-only / no sourcekitd)

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Capture a write-generation token at scan start, invalidate it when Cost
is disabled, and reject stale saves so in-flight scans cannot recreate
the parse cache after opt-out.
@chenow9

chenow9 commented Aug 10, 2026

Copy link
Copy Markdown
Author

P1 race fence + current-head retention proof (head 602b2980)

P1 — Prevent cache recreation after Cost tracking is disabled

  • Scans capture beginWriteToken(cacheRoot:) before load/scan
  • Cost-off calls invalidateAndDelete() (bumps generation + deletes artifact)
  • save(writeToken:) rejects stale tokens pre/post write (post-write fence deletes if invalidated mid-write)
  • Regression: stale write token does not recreate cache after Cost-off invalidation

Proof (final head)

  • proof/grok-cost-retention-final-head.png (+ .txt)
  • Redacted paths only; covers 90-day expiry, delete-on-disable, race fence
  • PR body updated with retention proof section

Verification

  • swift build --target CodexBarCore
  • SwiftFormat clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Point terminal/screenshot proof at the current head and document the
path-keyed write-token fence plus 90-day expiry/delete-on-disable contract.
@chenow9

chenow9 commented Aug 10, 2026

Copy link
Copy Markdown
Author

P1 race fence + current-head retention proof (head 5ba725d1)

Addresses ClawSweeper on 1fb1af62:

P1 — Prevent cache recreation after Cost tracking is disabled

  • Scan captures beginWriteToken(cacheRoot:) before load/scan
  • Cost off calls invalidateAndDelete() (bumps path-keyed generation + deletes artifact)
  • save(writeToken:) rejects stale tokens (pre-write + post-write fence) so in-flight scans cannot recreate the cache
  • Regression: stale write token does not recreate cache after Cost-off invalidation

Current-head proof (expiry + delete-on-disable + no recreate)

Retention race fence

Also in proof/grok-cost-retention-final-head.txt (redacted paths only).

Verification

  • swift build --target CodexBarCore
  • swift build --target CodexBarCLI
  • Full CodexBarTests not runnable here (Widget SwiftUI @Entry macro needs full Xcode SDK)

Owner decision (unchanged)

  • Bounded 90-day local Grok parse-cache retention still needs maintainer sponsor (VISION.md). ClawSweeper recommendation after race fix: Approve bounded local retention.

@clawsweeper re-review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants