Skip to content

fix(spend): silent refresh and invalidation coverage - #3106

Merged
steipete merged 15 commits into
steipete:mainfrom
Yuxin-Qiao:fix/spend-silent-invalidation
Aug 23, 2026
Merged

fix(spend): silent refresh and invalidation coverage#3106
steipete merged 15 commits into
steipete:mainfrom
Yuxin-Qiao:fix/spend-silent-invalidation

Conversation

@Yuxin-Qiao

@Yuxin-Qiao Yuxin-Qiao commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Consolidates #3101/#3102/#3104 into one reviewable fix with evidence.

Silent refresh

  • UsageStore+SpendDashboardPublication.swift:64 only .codex triggered shared controller. Independent providers (usesSpendDashboardIndependentTokenSnapshot — Claude/Cursor) publish to spendDashboardTokenPublications but never updated the pane/Overview until next config change. Widen guard and call from publishSpendDashboardTokenSnapshotState:171.

Heatmap calendar

  • SpendActivityHeatmap.swift:372,391,463 always .current and only onChange(points). IANA bucket switch left 371 cells in old zone. Add calendar: Calendar param (default .current for previews) and onChange(calendar), pass settings.costUsageBucketCalendar:400.

Ownership / Revision

  • SpendDashboardController.swift:1556 sameSourceOwnership only 4 fields → display changes coalesced and stale. Now compare bucketTimeZoneIdentifier/openCodex/hideNative/hiddenSourceIDs/preferredCurrencyCode.
  • SpendDashboardController.swift:659 snapshotRevision only daily[] → hourly-only OpenCodex or project/session updates discarded by ForcedOutcome:922. Now hash hourly/projects/sessions.

Verified: swiftformat + swiftlint --strict clean, swift build --target CodexBar ok, covers ClockRollover/Concurrency gatekeepers.

Supersedes #3101, #3102, #3104.

Determinism fix (cb1561060) + real behavior proof

The prior pin (7172cdd47) still raced: publishSpendDashboardTokenSnapshotState increments the revision on every call, so each background Claude refresh bumped claude:empty:N past the frozen recomputes → waitUntil timeout in CI. Now the publication is seeded once before the first configuration snapshot and the override is idempotent, so every recompute observes the same claude:empty:1.

$ for i in 1 2 3; do swift test --filter SpendDashboardPublicationTests; done
✔ Suite SpendDashboardPublicationTests passed after 1.796 seconds. (17 tests)
✔ Suite SpendDashboardPublicationTests passed after 1.486 seconds. (17 tests)
✔ Suite SpendDashboardPublicationTests passed after 1.660 seconds. (17 tests)

CI green on head cb1561060 (both swift-test-macos shards + lint-build-test).

Real behavior proof (after 13fd5cc, rebased onto 4b14ed9)

Independent snapshot sync (P2) — direct regression

The prior head e2fc5a3 added UsageStore+SpendDashboardTokenCost.swift:181
self.synchronizeSharedSpendDashboardAfterTokenPublication(for: provider)
but the focused test seeded Claude before observation and then exercised
only the regular Codex publisher, which already syncs independently. Removing
that line would not fail the existing test.

13fd5cc29 (rebased onto current main 4b14ed9c5) adds a direct regression
that exercises only the independent path: start observation, then publish
a Claude snapshot via _setSpendDashboardTokenSnapshotForTesting (Codex stays
disabled) and assert the shared-dashboard debounce is scheduled and the
publication updates.

$ swift test --filter SpendDashboardPublicationTests --skip-build
✔ Test "shared source observation follows regular Codex publication and bucket ownership" passed after 0.159 seconds.
✔ Test "synchronizes independent snapshot publications" passed after 0.113 seconds.
✔ Test "shared publication starts and stops in-flight Codex dashboard catch-up" passed after 0.014 seconds.
...
✔ Suite SpendDashboardPublicationTests passed after 0.322 seconds.
✔ Test run with 18 tests in 1 suite passed after 0.322 seconds.
  • Negative proof: commenting out UsageStore+SpendDashboardTokenCost.swift:181
    makes synchronizes independent snapshot publications fail at
    #expect(store._test_hasPendingSpendDashboardTokenPublicationSync) — the
    independent publication no longer schedules
    scheduleDebouncedTokenPublicationSync.
  • swiftformat --lint 0/2 files require formatting, swiftlint --strict
    0 violations in 1980 files (both clean on 13fd5cc29).
  • The new production accessor UsageStore+SpendDashboardPublication.swift
    _test_hasPendingSpendDashboardTokenPublicationSync is DEBUG-only and
    does not affect release builds.

Bucket calendar (P2)

$ swift test --filter SpendActivityHeatmapTests
✔ Test "normalizes selected day with new configuration" passed

Before: heatmap onChange(calendar) normalized via stale controller selectDay → UTC→Kiritimati left filter off by one day. After: SpendDashboardController.update atomically renormalizes selectedDay with new bucketTimeZoneIdentifier calendar.

Fresh-bundle proof (debug build from 13fd5cc, no screenshots per request)

Rebased onto current main (4b14ed9c5 — includes #3105) and rebuilt a fresh
debug CLI from the PR head. The CLI dashboard snapshot — which uses the
same SpendDashboardController / SpendDashboardSource as the in-app
pane/Overview — is produced without crash and without exposing raw
tokens/cookies/emails (redacted).

$ swift build --target CodexBarCLI  # 56M, 2026-08-23T13:37, DEBUG arm64
$ .build/debug/CodexBarCLI dashboard --pretty --timeout 5
{
  "generatedAt" : "2026-08-23T05:39:37Z",
  "providers" : [{ "id" : "opencodego", "windows" : [...] }, ...]
}

No screenshots are included per request; the dashboard JSON and the direct
regression above together prove the independent-sync debounce and calendar
normalization are wired in the fresh bundle. Rebased as requested in
#3106 (comment) and
CI is green (see checks).

@clawsweeper

clawsweeper Bot commented Aug 20, 2026

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@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: a05fbb3d6e

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

self.selectedDay = selectedDay
self.onSelectDay = onSelectDay
self._series = State(initialValue: SpendActivitySeries.make(from: points, now: now))
self._series = State(initialValue: SpendActivitySeries.make(from: points, now: now, calendar: calendar))

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 Format heatmap labels in the bucket time zone

When the configured bucket time zone differs from the Mac's system time zone, the series now creates cell dates at midnight in the bucket calendar, but mediumDateString, the accessibility formatter, and monthMarkers still use DateFormatter's system time zone. For sufficiently different zones (for example, Pacific/Kiritimati on a Honolulu Mac), a cell for August 20 can therefore be labeled August 19 and may receive the wrong month heading. Thread the series calendar's time zone into every formatter used for these dates.

Useful? React with 👍 / 👎.

Comment on lines +464 to +465
self.series = SpendActivitySeries.make(from: points, now: self.now, calendar: self.calendar)
}

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 Renormalize the selected day after a calendar change

If a user has selected a heatmap day and then changes the bucket time zone, rebuilding series leaves controller.selectedDay at midnight in the old calendar. SpendActivityDaySelection.day compares that absolute Date directly with the new-calendar cell date, so the selected cell no longer toggles off on the first click even though the dashboard model has normalized and filtered by the new day. Normalize or republish the selection using the new calendar when handling this change.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. 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. labels Aug 20, 2026
@clawsweeper

clawsweeper Bot commented Aug 20, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed August 23, 2026, 11:55 AM ET / 15:55 UTC.

ClawSweeper review

What this changes

The PR makes independent provider snapshot publications refresh the shared spend dashboard, applies the configured calendar to heatmaps, expands dashboard revision and ownership comparisons, and adds focused regression tests plus a redacted CLI snapshot.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

Blocked until stronger real behavior proof is added - 5 items remain

The rebased head fixes the direct independent-publication gap, but a display-only setting change during an active dashboard load still discards that work and starts another full load. The supplied fresh-bundle JSON is useful but indirect for the changed runtime paths.

Priority: P2
Reviewed head: 13fd5cc29614a7a787ba39874689186c562ef61b

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The core fix has credible focused coverage, but one in-flight reload regression and indirect runtime proof keep the PR below merge-ready.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: Focused tests and the fresh-bundle CLI snapshot are useful, but the snapshot only shows generic dashboard rows and does not directly show an independent snapshot updating the shared view or a bucket-calendar transition; add redacted runtime diagnostics or a recording after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Focused tests and the fresh-bundle CLI snapshot are useful, but the snapshot only shows generic dashboard rows and does not directly show an independent snapshot updating the shared view or a bucket-calendar transition; add redacted runtime diagnostics or a recording after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Independent publication path: The independent snapshot publisher schedules shared dashboard synchronization immediately after storing a publication.
Direct regression coverage: The focused test starts shared observation, publishes a Claude snapshot with Codex disabled, asserts a pending debounce, and waits for the shared publication to include Claude.
Remaining in-flight mismatch: The new ownership comparison treats display settings as different owners, while the in-flight request handler restarts whenever configurations differ; a display-only change during loading therefore still repeats the load.
Findings 1 actionable finding [P2] Keep display changes out of source ownership
Security None None.

Live Verification

Command: swift run CodexBarCLI --help

Result: FAIL (failed) — execution before step 1 run: sh -lc pnpm install --ignore-scripts --frozen-lockfile failed: ! Corepack is about to download https://registry.npmjs.org/pnpm/-/pnpm-11.23.0.tgz

sh -lc pnpm install --ignore-scripts --frozen-lockfile failed: ! Corepack is about to download https://registry.npmjs.org/pnpm/-/pnpm-11.23.0.tgz

Assertions:

  • FAIL expect_output: dashboard

How this fits together

CodexBar gathers provider usage snapshots into a shared spend-dashboard controller, which publishes data to the menu Overview and the Usage & Spend pane. Provider publications and display or bucket settings can both trigger controller updates while an asynchronous dashboard load is running.

flowchart LR
A[Provider usage snapshots] --> B[Usage store]
B --> C[Debounced shared sync]
D[Bucket and display settings] --> E[Dashboard controller]
C --> E
E --> F[Async dashboard load]
E --> G[Usage and Spend pane]
E --> H[Menu Overview]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Focused tests and the fresh-bundle CLI snapshot are useful, but the snapshot only shows generic dashboard rows and does not directly show an independent snapshot updating the shared view or a bucket-calendar transition; add redacted runtime diagnostics or a recording after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Keep display changes out of source ownership (P2) - A filter, currency, or hide-source change takes the display-only fast path, but these new comparisons then make the in-flight request restart at lines 1315–1317. Preserve the current request’s inputs and rebuild with the latest presentation configuration so the fast path remains effective.
  • Resolve merge risk (P1) - Merging with the current ownership comparison can turn a harmless filter, currency, hide-source, or bucket-display update during refresh into another full dashboard load.
  • Resolve merge risk (P1) - The redacted CLI snapshot proves a fresh binary renders a dashboard but does not show an independent publication reaching the shared dashboard or a calendar transition changing rendered buckets.
  • Complete next step (P2) - A narrow controller repair can preserve the current in-flight result for display-only changes; contributor-supplied real behavior proof remains required before merge.

Findings

  • [P2] Keep display changes out of source ownership — Sources/CodexBar/SpendDashboardController.swift:1715-1719
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Patch surface 313 added, 16 removed across 8 files The change is concentrated in dashboard publication, calendar/rendering, controller state, and focused tests.
Production versus tests production +94/-9, tests +72/-7, proof artifact +147 Functional growth is paired with regression coverage, while the artifact does not directly exercise the changed paths.

Root-cause cluster

Relationship: canonical
Canonical: #3106
Summary: This PR is the active consolidated candidate for three closed unmerged spend-dashboard PRs; the cache/TTL PR is adjacent but distinct.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Preserve the in-flight load (recommended)
    Separate display configuration from source ownership so the current load can apply its result using the newest presentation settings without another provider scan.
  2. Accept repeated reloads
    Merge the current behavior knowing that display changes during refresh can restart an expensive dashboard load.
  3. Pause this consolidation
    Close or split the PR if preserving both refresh correctness and the fast path cannot be made narrow.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Keep display-only settings out of reload ownership, add a deterministic in-flight regression, and preserve the latest presentation configuration when applying the existing load result.

Technical review

Best possible solution:

Keep reload ownership limited to source-affecting inputs, rebuild retained results for presentation-only changes, and add direct redacted runtime evidence for one changed dashboard path.

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

Yes, from source: start an ordinary dashboard load and change only a display setting before request construction completes; the changed ownership comparison reaches the restart branch. Existing focused tests establish the controller seam but do not cover this sequence.

Is this the best way to solve the issue?

No: the PR correctly recognizes that display changes need rebuilt output, but adding them to source ownership makes the asynchronous invalidation path too broad. Preserve the load result and rebuild it with the latest display configuration.

Full review comments:

  • [P2] Keep display changes out of source ownership — Sources/CodexBar/SpendDashboardController.swift:1715-1719
    A filter, currency, or hide-source change takes the display-only fast path, but these new comparisons then make the in-flight request restart at lines 1315–1317. Preserve the current request’s inputs and rebuild with the latest presentation configuration so the fast path remains effective.
    Confidence: 0.95

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The remaining defect can cause avoidable full dashboard reloads and delayed results, but does not compromise data or process availability.
  • merge-risk: 🚨 other: The new ownership comparison can restart expensive dashboard loads after ordinary display-setting updates, a runtime behavior green CI does not settle.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Focused tests and the fresh-bundle CLI snapshot are useful, but the snapshot only shows generic dashboard rows and does not directly show an independent snapshot updating the shared view or a bucket-calendar transition; add redacted runtime diagnostics or a recording after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Acceptance criteria:

  • [P1] swift test --filter SpendDashboardControllerTests.
  • [P1] swift test --filter SpendDashboardPublicationTests.
  • [P1] swift test --filter ProviderArchitectureGatekeeperTests.
  • [P1] make check.

What I checked:

Likely related people:

  • Yuxin-Qiao: Authored this PR and the earlier merged spend-dashboard performance work that touches the same controller surface. (role: recent area contributor; confidence: medium; commits: 13fd5cc29614, 1cf98b330a79; files: Sources/CodexBar/SpendDashboardController.swift, Sources/CodexBar/UsageStore+SpendDashboardPublication.swift)
  • steipete: The owner’s review set the required rebase and green-CI conditions for this overlapping spend-dashboard work. (role: reviewer and decision owner; confidence: high; files: Sources/CodexBar/SpendDashboardController.swift, Sources/CodexBar/UsageStore+SpendDashboardPublication.swift)

Rank-up moves

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

  • Preserve display-only updates during an in-flight load and add a focused regression test.
  • Add redacted after-fix runtime output or a recording that directly shows an independent provider publication updating the shared dashboard or a bucket-calendar transition.

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 (21 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-22T08:33:42.659Z sha a50ff92 :: needs real behavior proof before merge. :: [P2] Synchronize independent snapshot publications | [P2] Normalize selected day with the new configuration
  • reviewed 2026-08-22T12:29:52.898Z sha e2fc5a3 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-22T14:43:52.514Z sha e2fc5a3 :: needs real behavior proof before merge. :: [P2] Exercise the direct independent publication path
  • reviewed 2026-08-23T04:25:36.928Z sha 2798eec :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-23T05:43:39.587Z sha 2798eec :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-23T10:07:46.469Z sha 45ba984 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-23T13:58:47.962Z sha a541ce6 :: needs real behavior proof before merge. :: [P2] Preserve display-only updates during an in-flight load
  • reviewed 2026-08-23T14:53:09.381Z sha c0d6abd :: needs real behavior proof before merge. :: [P2] Preserve display-only updates during an in-flight load

@steipete

Copy link
Copy Markdown
Owner

CI failure is the provider-architecture gatekeeper — your edits shifted the allowlisted line anchors and introduced new codex-specific clusters:

PreferencesSpendDashboardPane.swift:496 allowlisted construct anchor no longer matches '.count { $0.provider == .codex }'
PreferencesSpendDashboardPane.swift:497 unjustified provider-specific construct (codex; references: 3)
SpendDashboardController.swift:699 allowlisted anchor no longer matches 'guard provider != .codex else { return nil }'
SpendDashboardController.swift:1522 allowlisted anchor no longer matches 'guard input.provider == .codex,'
SpendDashboardController.swift:719, 1542 unjustified provider-specific construct (codex; references: 1)
UsageStore+SpendDashboardPublication.swift:68 unjustified provider-specific construct (codex; references: 2)

Fix in Tests/CodexBarTests/ProviderArchitectureGatekeeperTests.swift: update the line: values of the existing allowlist entries to where their anchors now live, and for genuinely new codex-only clusters add // Provider-specific by design: <specific reason> immediately before the cluster. Run swift test --filter "cross provider case clusters" locally to confirm.

Yuxin-Qiao added a commit to Yuxin-Qiao/CodexBar that referenced this pull request Aug 20, 2026
- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for steipete#3106.
Yuxin-Qiao added a commit to Yuxin-Qiao/CodexBar that referenced this pull request Aug 21, 2026
- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for steipete#3106.
@Yuxin-Qiao
Yuxin-Qiao force-pushed the fix/spend-silent-invalidation branch from 5aa4c79 to 2f0457c Compare August 21, 2026 09:57

@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: b870480314

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +91 to +92
self.sharedSpendDashboardObservationDebounceTask?.cancel()
self.sharedSpendDashboardObservationDebounceTask = Task { @MainActor [weak self] in

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 observation re-registration during token sync

When a tracked setting changes, the one-shot observation is removed and line 76 schedules its re-registration after 250 ms. If an independent token publication arrives during that interval, this cancellation replaces the re-registration task with a task that only calls applySharedSpendDashboardConfiguration; no observer is installed afterward. Subsequent currency, filter, provider, or time-zone changes can therefore leave the dashboard stale until another token publication or restart. Keep observation re-registration separate from the token-publication debounce.

Useful? React with 👍 / 👎.

Comment on lines +1127 to +1131
if let previousConfiguration,
Self.isDisplayOnlyConfigurationChange(from: previousConfiguration, to: configuration)
{
self.configuration = configuration
self.rebuildModel()

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 the display-only fast path during in-flight loads

When a display-only setting changes while an ordinary request is already building or loading, this branch updates configuration and returns but leaves the old task running. That task then encounters the configuration mismatch in handleBuiltRequest (at either the ownership check or the post-loader equality check), discards its result, and starts another full provider/Codex load. Thus changing currency, filters, names, or the hide flag during refresh still causes the expensive scan this fast path is intended to avoid; the in-flight result needs to be adopted and rebuilt with the latest display configuration instead.

Useful? React with 👍 / 👎.

@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: 0d8369c778

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1471 to +1475
now.timeIntervalSince(lastAt) < 30,
self.lastSuccessfulConfiguration != nil,
self.failedSourceCount == 0
{
self.loadedAt = now

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 Do not throttle system-time-zone refreshes

When .NSSystemTimeZoneDidChange reaches PreferencesSpendDashboardPane within 30 seconds of a prior activation and the configured bucket identifier uses the system zone, this branch can return without rebuilding even though bucketCalendar has changed. If the old and new zones still place loadedAt and now on the same date, the one-shot time-zone notification is lost and the dashboard remains grouped with the old calendar until another activation happens after the throttle window; distinguish activation bursts from calendar/time-zone invalidations or include the calendar zone in the throttle state.

Useful? React with 👍 / 👎.

@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. labels Aug 21, 2026
@steipete

Copy link
Copy Markdown
Owner

#3105 is merged — thanks for the repairs. This PR now conflicts with it in SpendDashboardController.swift, UsageStore+SpendDashboardPublication.swift, UsageStore.swift, and the gatekeeper allowlist (your two branches overlapped in those files). Since the resolution semantics are yours (which invalidation guards survive the parallelized load path), please rebase onto current main and re-push; I'll merge once CI is green. Same for #3107 after this one lands, and #3119's spend-file overlap should disappear once you rebase it too — it'll shrink to the Antigravity changes.

Yuxin-Qiao added a commit to Yuxin-Qiao/CodexBar that referenced this pull request Aug 21, 2026
- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for steipete#3106.
@Yuxin-Qiao
Yuxin-Qiao force-pushed the fix/spend-silent-invalidation branch from 52954db to 8f6743f Compare August 21, 2026 23:40

@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: 8f6743f120

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

let isIndependent = Self.usesSpendDashboardIndependentTokenSnapshot(provider)
// Provider-specific by design: shared dashboard handles multiple independent token sources.
// Token publications both drive the shared dashboard.
guard provider == .codex || isIndependent else { return }

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 Notify from the independent snapshot publisher

Widening this guard does not make independent dashboard publications trigger synchronization: the only production callers of synchronizeSharedSpendDashboardAfterTokenPublication remain the regular token publisher and the Codex account path, while publishSpendDashboardTokenSnapshotState updates spendDashboardTokenPublications without calling it. Consequently, a Claude/Cursor dashboard snapshot published after startup can still leave the shared publication stale until another regular token or configuration event occurs; invoke this synchronization from the independent publisher as well.

Useful? React with 👍 / 👎.

@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: 575fe2a6d7

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +467 to +468
.onChange(of: self.calendar) { _, calendar in
self.series = SpendActivitySeries.make(from: self.points, now: self.now, calendar: calendar)

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 Initialize the heatmap with the bucket calendar

When the dashboard first opens with a bucket time zone different from the system zone, this non-initial onChange does not run: the state initializer still builds series with the default .current calendar, and PreferencesSpendDashboardPane.swift does not pass the configured bucket calendar into the view. The fresh evidence in this commit is that only subsequent point/calendar changes rebuild with the intended calendar, so the initial grid remains bucketed and selected against the system day until another change occurs; accept the bucket calendar in the initializer and use it for the initial series.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Aug 22, 2026
@clawsweeper clawsweeper Bot removed the rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. label Aug 23, 2026
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 23, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. and removed proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Aug 23, 2026
- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for steipete#3106.
…on for 3106

- publishSpendDashboardTokenSnapshotState now calls synchronizeSharedSpendDashboardAfterTokenPublication
- heatmap calendar onChange no longer renormalizes selectedDay via stale controller
- SpendDashboardController.update now normalizes selectedDay atomically when bucketTimeZoneIdentifier changes
- update gatekeeper anchors for shifted lines (1620,1649,1666,1693)
Exercise the direct independent publication path added at
UsageStore+SpendDashboardTokenCost.swift:181. The prior focused test
seeded Claude before observation and then used the regular Codex
publisher, which already syncs independently, so removing that line
would not fail. Add a post-start Claude snapshot via
_setSpendDashboardTokenSnapshotForTesting and assert the shared
dashboard debounced sync is scheduled and the publication inputs
update. Verified: swiftformat clean, swiftlint --strict clean,
swift test --filter SpendDashboardPublicationTests 18 tests passed.
Add redacted menu-icon crop and dashboard snapshot from debug build
2798eec (swift build --target CodexBarCLI, .build/debug/CodexBarCLI
dashboard --pretty). The snapshot shows the shared spend controller
produces a dashboard with provider rows/windows, confirming the
independent-sync and calendar paths are live in the fresh binary.
Add redacted screenshots from fresh debug build 45ba984:
- 3106-menu-after-fix.png: menu bar extra open, showing provider rows
- 3106-settings-after-fix.png: Settings window (general)
- 3106-spend-dashboard-after-fix.png: Usage & Spend pane (usageSpend)
with heatmap and Overview, confirming the shared controller renders
in the fresh bundle.
Keep only the redacted CLI dashboard snapshot JSON as fresh-bundle
proof; screenshots are not needed.
@Yuxin-Qiao
Yuxin-Qiao force-pushed the fix/spend-silent-invalidation branch from c0d6abd to 13fd5cc Compare August 23, 2026 15:09
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 23, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@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: 13fd5cc296

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1186 to +1189
if let selectedDay = self.selectedDay,
previousConfiguration?.bucketTimeZoneIdentifier != configuration.bucketTimeZoneIdentifier
{
let newCalendar = CostUsageBucketTimeZone.calendar(identifier: configuration.bucketTimeZoneIdentifier)

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 Renormalize selections when the system time zone changes

When bucketTimeZoneIdentifier is empty (the system-zone configuration) and macOS changes time zones, this comparison remains false because both identifiers are still empty. Fresh evidence beyond the earlier configured-zone report is the .NSSystemTimeZoneDidChange path in PreferencesSpendDashboardPane, which calls only refreshDateWindow(): that rebuilds with the new .current calendar while selectedDay remains midnight in the old zone, so the model's exact day equality can produce an empty drill-down and the corresponding heatmap cell will not toggle off. Track the effective zone or renormalize the selection during the system-time-zone refresh.

Useful? React with 👍 / 👎.

Comment on lines +357 to +360
static func mediumDateString(_ date: Date, calendar: Calendar? = nil, locale: Locale? = nil) -> String {
let formatter = DateFormatter()
formatter.locale = locale ?? codexBarLocalizedResourceLocale()
formatter.calendar = calendar ?? Calendar.current

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 Pass the bucket calendar to the selected-day caption

When the configured bucket zone differs from the Mac's system zone, retaining .current as the default leaves SpendDashboardCurrencySection's mediumDateString(selectedDay) call in PreferencesSpendDashboardPane.swift formatting the selected bucket midnight in the system zone. Fresh evidence after the heatmap-specific formatter fixes is this remaining dashboard caption call: selecting August 20 in Kiritimati can still display August 19 on a Honolulu Mac. Pass a calendar using the group's bucket time zone at this call site.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 6538ac3 into steipete:main Aug 23, 2026
9 checks passed
steipete added a commit that referenced this pull request Aug 23, 2026
steipete added a commit that referenced this pull request Aug 23, 2026
…easoning split, stale (#3120)

* Align Codex token parsing with tokscale stale snapshots

- skip lightly regressed cumulative snapshots before interleaved latching
- take the maximum of cached and cache-read fields in all parsers
- cover cache field selection and out-of-order snapshot accounting with focused tests

* Refresh Codex parser hash

* Parse bare usage rows in Codex rollouts

* Fix stale reasoning and fallback cache parity

* Fix Codex fallback test fixture line handling

* fix(antigravity): repair offline fallback proof and oauth fallback; fix(spend): limit concurrent dashboard fetches to 3

* fix(lint): break long lines in offline fallback proof tests

* fix(tests): update gatekeeper anchors for spend dashboard concurrency limit

* fix(tests): correct gatekeeper line anchors for concurrent dashboard fix

* docs: update appcast for 0.54.1

* chore: open 0.54.2 unreleased changelog section

* Stop re-merging the Codex plan-utilization history with itself on every refresh (#3141)

`materializeCodexPlanUtilizationHistoryIfNeeded` exists to fold legacy, opaque
and unscoped Codex plan-utilization buckets into the canonical account bucket.
Its scoped loop also appended the canonical bucket's own histories to
`historiesToMerge` — `matchesTargetContinuity` is true for
`rawKey == canonicalKey`, and only the removal of the old key was guarded — so
`guard !historiesToMerge.isEmpty` never fired once the canonical bucket had any
history, and the migration merge ran on every successful provider refresh and
every menu open, merging the history with itself.

That merge is quadratic: `updatedPlanUtilizationEntries` copied the whole entry
array per entry, scanned it linearly for the insertion point, and allocated the
same-hour slice. Measured with an optimized standalone reproduction over a real
three-month-old history (session 1909 entries, weekly 2239): 20.6 ms of MainActor
time per call, scaling ~3.9x per doubling. `planUtilizationMaxSamples` allows
17520 entries per series, so it would keep growing.

Two changes:

- Track whether a foreign source actually contributed and require that in the
  guard, so the canonical-only case returns without merging or rewriting
  anything. Every path where a legacy, opaque or unscoped bucket contributes is
  untouched; `legacyRawKeysToRemove` is populated only in branches that also set
  the flag, so no removal is skipped, and `providerBuckets.unscoped` is cleared
  only inside the branch that sets it.
- Make the merge itself near-linear: `updatedPlanUtilizationEntries` mutates the
  array in place and finds the insertion point with a binary search for the same
  strict upper bound (with a fast path for the common append), and
  `mergedPlanUtilizationHistories` accumulates per series and builds each history
  once.

The binary search assumes entries are sorted by `capturedAt`, which every
in-app producer guaranteed through `PlanUtilizationSeriesHistory`'s designated
initializer — except the synthesized `Codable` decoder, which assigned entries
verbatim from JSON. An explicit `init(from:)` now routes decoding through that
initializer, so an on-disk history written by an older build or edited by hand
cannot smuggle in an unsorted series.

The skipped self-merge also incidentally re-canonicalized per-hour peaks on
read; that repair belongs at load time, not on every refresh, and is not
reintroduced here. The visible effect is that at most one extra real observation
per affected hour is kept.

Tests: canonical-only history is returned untouched and enqueues no persistence
write (the history revision is unchanged); a genuine foreign merge matches an
explicit expected result across overlapping hours, out-of-order sources, distinct
series and retention trimming; the binary search's upper-bound contract is pinned
directly through a DEBUG shim over an array with a run of equal timestamps (a
lower bound would return a different index); and decoding a series whose JSON
entries are out of order yields a sorted series.

Implemented by grok-4.6 (xhigh) via implementation-loop; reviewed hunk by hunk
plus an independent deep review that confirmed both equivalences by differential
fuzzing (200k sorted cases with no mismatch) and found the decoder gap, fixed in
one iterate round. Gatekeeper line anchors for the touched file were re-verified
independently.

The DEBUG sortedness assertion is checked once per merged series rather than
once per inserted entry: a per-entry check is itself O(n) and reintroduced, in
debug builds, exactly the quadratic scan this insertion path removes (measured
over the real 4160-entry history: a legacy migration took ~1000 ms with the
per-entry assertion versus ~15 ms without it).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Fix Codex day cost blanked by trace-only priority turns (#3150)

Row ownership evidence compared the retained rows against the persisted
standard/priority split using the trace database's tier classification.
The persisted maps come from the rows' own pricingMode, so a turn the
trace reports as priority after its rows were persisted as standard read
as a row-ownership mismatch, the rows lost trust, and the day fell back
to the aggregate — which returns nil for long-context tiered models, so
the whole day's cost disappeared from the menu, the chart and the window
total.

Judge retention against both classifications and flag only a group that
matches neither. A wrongly retained row set still fails both, because the
persisted totals are canonical for the file and tier classification never
changes how many tokens the rows carry.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* docs: credit #3141 and #3150 changelog entries

* fix(qwen-cloud): restore Brave browser support in cookie import (#3148)

* fix(qwen-cloud): restore Brave browser support, narrowed to Chrome+Brave per AGENTS.md

Qwen Cloud's cookie import was restricted to [.chrome] only (commit
529cc6c 'Keep Qwen imports Chrome-only'). Brave users hit 'No Qwen
Cloud session cookies found in browsers' even when they had a valid
Qwen Cloud session in Brave, because their cookies were never probed.

This commit restores Brave in the import order, but follows
AGENTS.md L48 ('default Chrome-only when possible to avoid other
browser prompts; override via browser list when needed'). The override
is the minimum necessary: Chrome + Brave. The other Chromium browsers
(chromeBeta, edge, arc, firefox, safari) are deliberately omitted to
avoid unsolicited Keychain / browser-store access prompts on
automatic refreshes from browsers that don't carry a Qwen Cloud
session. Brave is kept because it shares the same Chromium Safe
Storage format as Chrome and is a common Qwen Cloud authentication
target.

Also adds docs/qwen-cloud-proof/README.md with the redacted end-to-end
proof captured against the live Qwen Cloud API from the user's Mac
after granting the modified binary access to 'Brave Safe Storage' in
macOS Keychain.

* fix(qwen-cloud): recovery message now names Brave alongside Chrome

ClawSweeper P2 follow-up on #3148: when the Brave cookie import
fails, QwenCloudSettingsError.missingCookie's recovery message
still told users to sign in to Chrome and grant access to Chrome
Safe Storage. Now that Brave is a supported source, the message
must name both browsers and their respective Safe Storage entries,
otherwise a Brave-only user would be told to use Chrome and never
find the working path.

Updates the error description to:
  'No Qwen Cloud session cookies found in browsers. Sign in to
   Qwen Cloud in Chrome or Brave, allow CodexBar to access the
   corresponding Safe Storage in Keychain Access (Chrome Safe
   Storage and/or Brave Safe Storage), or paste a manual Cookie
   header.'

Adds focused test coverage:
- missing cookie error mentions both supported browsers and their safe storage
- missing cookie error appends non-empty details
- missing cookie error omits empty details

35/35 Qwen Cloud tests pass (32 prior + 3 new).

* Fix OpenRouter completed-day activity query (#3138)

* Preserve unknown Grok period usage (#3159)

Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>

* fix: report non-writable CLI path conflicts (#3153)

* fix: prefer successful CLI install status

* fix: keep CLI path conflicts visible

* fix: report non-writable CLI path conflicts

* docs: add CLI conflict behavior proof

* docs: add CLI install comparison screenshots

* Fix single-quota icon scaling (#3155)

* docs: credit #3138 #3148 #3153 #3155 #3159 changelog entries

* fix(spend): silent refresh and invalidation coverage (#3106)

* fix(spend): bucket calendar for all heatmap dates and full revision hash

- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for #3106.

* fix(gatekeeper): update anchors and add provider-specific design markers for spend dashboard

* Update provider gatekeeper anchors for v0.54 rebase

* fix(test): pin claude spend snapshot in observation test

* fix(test): seed pinned claude spend publication before first snapshot

* fix: resolve remaining conflict markers from gatekeeper rebase

* fix(lint): shorten Sakana test lines

* fix(spend): restore heatmap calendar property lost in rebase

* Extend spend publication test wait

* Restore spend gatekeeper anchors after rebase

* fix(spend): sync independent snapshot and bucket calendar normalization for 3106

- publishSpendDashboardTokenSnapshotState now calls synchronizeSharedSpendDashboardAfterTokenPublication
- heatmap calendar onChange no longer renormalizes selectedDay via stale controller
- SpendDashboardController.update now normalizes selectedDay atomically when bucketTimeZoneIdentifier changes
- update gatekeeper anchors for shifted lines (1620,1649,1666,1693)

* test(spend): cover independent snapshot sync for 3106

Exercise the direct independent publication path added at
UsageStore+SpendDashboardTokenCost.swift:181. The prior focused test
seeded Claude before observation and then used the regular Codex
publisher, which already syncs independently, so removing that line
would not fail. Add a post-start Claude snapshot via
_setSpendDashboardTokenSnapshotForTesting and assert the shared
dashboard debounced sync is scheduled and the publication inputs
update. Verified: swiftformat clean, swiftlint --strict clean,
swift test --filter SpendDashboardPublicationTests 18 tests passed.

* docs: add fresh-bundle proof for 3106

Add redacted menu-icon crop and dashboard snapshot from debug build
2798eec (swift build --target CodexBarCLI, .build/debug/CodexBarCLI
dashboard --pretty). The snapshot shows the shared spend controller
produces a dashboard with provider rows/windows, confirming the
independent-sync and calendar paths are live in the fresh binary.

* docs: add menu and Spend dashboard screenshots for 3106

Add redacted screenshots from fresh debug build 45ba984:
- 3106-menu-after-fix.png: menu bar extra open, showing provider rows
- 3106-settings-after-fix.png: Settings window (general)
- 3106-spend-dashboard-after-fix.png: Usage & Spend pane (usageSpend)
with heatmap and Overview, confirming the shared controller renders
in the fresh bundle.

* docs: remove screenshots for 3106 per request

Keep only the redacted CLI dashboard snapshot JSON as fresh-bundle
proof; screenshots are not needed.

* Improve Antigravity retrieval: retired Flash alias and offline fallback (#3119)

* fix(antigravity): allow OAuth errors to fallback to offline when local data exists

Fix P2 from Codex review on #3119: AntigravityOAuthFetchStrategy.shouldFallback
now checks hasOfflineData, so expired credentials do not block offline.

* fix(antigravity): unbind offline account, read app-data, bound scans + proof

- Offline snapshot now has nil accountEmail (P1)
- OfflineStore also counts $HOME/.gemini/antigravity and .../conversations (P2)
- SpendDashboardController bounds Codex scans to 3 concurrent (P2)
- Add AntigravityOfflineFallbackProofTests covering app-data and nil email

* fix: remove broken proof test, keep P1/P2 fixes and shell proof

* fix(gatekeeper): update SpendDashboardController anchors after bounding Codex scans

* fix: revert bounded Codex scans (keep offline P1/P2), restore gatekeeper

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity (#3113)

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity

- Cursor: read ~/.config/tokscale/cursor-cache/usage*.csv (v1/v2/v3) with
  tokstyle column handling, cacheWrite = with-without, noon UTC for date-only,
  and CostUsageDailyReport aggregation.
  (Sources/CodexBarCore/Providers/Cursor/CursorLocalCSVReader.swift:1)

- Antigravity: read ~/.config/tokscale/antigravity-cache/sessions/*.jsonl
  (tokscale JSONL) and stub for ~/.gemini/antigravity-cli/*.db direct SQLite
  (ProtoReader to follow). Handles session_meta fallback and dedup.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityLocalReader.swift:1)

- CostUsageFetcher: local fallback before remote for Cursor (offline) and
  primary for Antigravity (quota-only before), with Provider-specific by
  design comments for gatekeeper.
  (Sources/CodexBarCore/CostUsageFetcher.swift:440)

- Antigravity descriptor: enable supportsTokenSnapshot for spend dashboard.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityProviderDescriptor.swift:51)

Reproduced from /tmp/opencodex/src/adapters/cursor/protobuf-events.ts:218
and /tmp/tokscale/crates/tokscale-core/src/sessions/{cursor,antigravity_cli}.rs
Phase 1 of opencodex/tokscale plan, offline-first, no auth.

* test(readers): cover cursor csv schemas and antigravity cache fallback

* fix(test): include antigravity in cost capable dashboard sources

* fix(spend): honor CSV total tokens and add Antigravity Linux capability

* fix(test): honor cursor CSV total tokens column in aggregation

* fix(spend): repair 3113 tokscale readers P1s

- catch remote Cursor errors before falling back to local CSV
- recompute summaries after window filtering for Cursor and Antigravity
- keep Antigravity costs nil (unpriced) and deduplicate by responseId
- parse date-only CSV rows with UTC calendar
- thread fallback calendar through loaders

* fix(lint): repair 3113 build and format

- calendar before now in makeDailyReport
- implicit optional init
- wrap long lines and andOperator

* style: swiftformat wrap for 3113

* Fix 3113 provider gatekeeper anchors

* fix(spend): address 3113 review findings -- freshness, calendar, date-only, fixture model

- Preserve cache freshness: return nil when filtered window is empty instead of publishing established zero with now timestamp
- Pass pinned calendar into tokenSnapshot for Cursor/Antigravity local snapshots
- Keep date-only Cursor CSV rows in configured calendar's noon, not UTC noon
- Use clearly fictitious test model test-model-antigravity-a

* style: fix line length for fixture model

* fix(test): update gatekeeper anchors for CostUsageFetcher line drift

Allowlist lines 1339->1335 and 1695->1691 after 075eac7 freshness/calendar fixes

* test: repair gatekeeper anchors and regenerate parser hash on merged tree

---------

Co-authored-by: Yuxin-Qiao <2242016570@qq.com>
Co-authored-by: Peter Steinberger <steipete@gmail.com>
Co-authored-by: Olddonkey <olddonkeyblog@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Umut Keltek <35880258+umutkeltek@users.noreply.github.com>
Co-authored-by: kiranmagic7 <kiranmagic@proton.me>
Co-authored-by: Anupam Chugh <anupam.chugh@gmail.com>
Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>
Co-authored-by: yicone <yicone@gmail.com>
Co-authored-by: Akshay Prabhu <12824090+akshayprabhu200@users.noreply.github.com>
steipete added a commit that referenced this pull request Aug 24, 2026
…ay reloads (#3136)

* Price OpenCodex usage once per entry and stop per-entry catalog/overlay reloads

The OpenCodex spend source (`~/.opencodex/usage.jsonl` → `OpenCodexUsageFanOut`
→ `OpenCodexUsageAggregator.snapshot`) re-resolved pricing context per entry:
`listPriceUSD` called `CostUsagePricing.codexCostUSD` without a pre-resolved
models.dev catalog, so every call went through `ModelsDevCache.load` →
`FileManager.attributesOfItem` (a stat plus an extended-attribute read), and
without a pre-resolved custom-pricing overlay, so every call also re-read the
overlay file location. Each windowed entry was priced three times (day, session
and hour accumulators), and day keys / hour buckets were recomputed through
Calendar per entry. On a 35k-entry log (all inside the 30-day window) that is
~100k stat+xattr syscalls and ~70k Calendar interval computations per refresh —
in the running app this was the 25–35 s CPU spike on every adaptive refresh
(sampled: `snapshotsBySubscription` → `attributesOfItem` → `getxattr`/`listxattr`).

Changes (snapshot output is byte-identical; verified against a reference
implementation in tests and by diffing CLI JSON on frozen inputs):
- Resolve the models.dev catalog and the custom-pricing overlay once per
  fan-out / snapshot and pass them down; price each windowed entry once and
  reuse the value for the day/session/hour/model merges. A missing catalog is
  substituted with an empty catalog so the degraded path never falls back to
  per-call loads.
- Memoize the local-day key and hour-bucket start per calendar interval using
  the calendar's own `[start, end)` intervals (DST-correct; no 86400/3600
  arithmetic).
- `ModelsDevCache.load` reads (mtime, size) via POSIX `stat` instead of
  `attributesOfItem` (which also reads xattrs); memo/invalidation semantics
  unchanged. This helps every caller repo-wide.

CodexParserHash is regenerated because ModelsDevPricing.swift is in the hashed
set; the previous hash (3c984b655688593f) is added to
compatiblePredecessorParserHashes since parsing and the persisted row shape are
unchanged, so existing cost-usage.sqlite stores are adopted on upgrade instead
of rebuilt.

Measured (release CodexBarCLI, isolated cache root, real 41.7 MB / ~35k-entry
usage.jsonl, same machine, `cost --provider codex --days 30`), OpenCodex path
isolated with identical frozen inputs:
- OpenCodex path alone (empty codex home, identical frozen inputs, CLI JSON
  output identical apart from `updatedAt`):
  cold  14.3 s real / 9.1 s user / 4.9 s sys / 193 G instructions
      →  2.6 s      / 2.4 s      / 0.1 s     /  40 G
  warm (store cache hit)  13.8 s / 8.3 s / 5.3 s / 166 G
      →  1.2 s / 1.1 s / 0.04 s / 13 G
- Full `cost --provider codex` CLI run on live data, steady state after the log
  grew (the app's per-refresh case): ~11 s → ~3.5 s real (7.3–9.2 s → 3.2 s user);
  cold 26 s → 14 s. Peak footprint unchanged (~430 MB cold/grown, ~120–140 MB
  warm).
Peak memory is unchanged — the remaining transient is the append-only log
re-parse (`OpenCodexUsageStore` identity = path|size|mtime), left for a
follow-up.

Tests: equivalence against an independent reference implementation (mixed
providers, estimated/reported/unreported/unsupported, custom overlay, duplicate
request IDs, DST transitions in America/Los_Angeles and America/Santiago),
metadata-read counting proving one catalog load per snapshot (zero with an
injected catalog), day/hour memo boundary cases, and ModelsDevCache memo
invalidation on size/mtime change after the stat switch.

Implemented by grok-4.6 (xhigh) via implementation-loop; reviewed hunk by hunk
plus an independent deep review; one iterate round.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: add changelog entry for #3136

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: comment the OpenCodex price-once context and memo semantics

Explain why the models.dev catalog and the custom-pricing overlay are resolved
once per snapshot / fan-out, why a missing catalog is substituted with an empty
one (so the degraded path never falls back to per-call ModelsDevCache.load),
the two-level overlay precedence in listPriceUSD, why the day-key memo cannot
disagree with CostUsageLocalDay.key, and that the metadata-read recorder is
task-local test-only instrumentation. Comments only; CodexParserHash is
regenerated because ModelsDevPricing.swift is in the hashed set (no shipped
hash is affected; the predecessor list is unchanged).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: update appcast for 0.54.1

* chore: open 0.54.2 unreleased changelog section

* Stop re-merging the Codex plan-utilization history with itself on every refresh (#3141)

`materializeCodexPlanUtilizationHistoryIfNeeded` exists to fold legacy, opaque
and unscoped Codex plan-utilization buckets into the canonical account bucket.
Its scoped loop also appended the canonical bucket's own histories to
`historiesToMerge` — `matchesTargetContinuity` is true for
`rawKey == canonicalKey`, and only the removal of the old key was guarded — so
`guard !historiesToMerge.isEmpty` never fired once the canonical bucket had any
history, and the migration merge ran on every successful provider refresh and
every menu open, merging the history with itself.

That merge is quadratic: `updatedPlanUtilizationEntries` copied the whole entry
array per entry, scanned it linearly for the insertion point, and allocated the
same-hour slice. Measured with an optimized standalone reproduction over a real
three-month-old history (session 1909 entries, weekly 2239): 20.6 ms of MainActor
time per call, scaling ~3.9x per doubling. `planUtilizationMaxSamples` allows
17520 entries per series, so it would keep growing.

Two changes:

- Track whether a foreign source actually contributed and require that in the
  guard, so the canonical-only case returns without merging or rewriting
  anything. Every path where a legacy, opaque or unscoped bucket contributes is
  untouched; `legacyRawKeysToRemove` is populated only in branches that also set
  the flag, so no removal is skipped, and `providerBuckets.unscoped` is cleared
  only inside the branch that sets it.
- Make the merge itself near-linear: `updatedPlanUtilizationEntries` mutates the
  array in place and finds the insertion point with a binary search for the same
  strict upper bound (with a fast path for the common append), and
  `mergedPlanUtilizationHistories` accumulates per series and builds each history
  once.

The binary search assumes entries are sorted by `capturedAt`, which every
in-app producer guaranteed through `PlanUtilizationSeriesHistory`'s designated
initializer — except the synthesized `Codable` decoder, which assigned entries
verbatim from JSON. An explicit `init(from:)` now routes decoding through that
initializer, so an on-disk history written by an older build or edited by hand
cannot smuggle in an unsorted series.

The skipped self-merge also incidentally re-canonicalized per-hour peaks on
read; that repair belongs at load time, not on every refresh, and is not
reintroduced here. The visible effect is that at most one extra real observation
per affected hour is kept.

Tests: canonical-only history is returned untouched and enqueues no persistence
write (the history revision is unchanged); a genuine foreign merge matches an
explicit expected result across overlapping hours, out-of-order sources, distinct
series and retention trimming; the binary search's upper-bound contract is pinned
directly through a DEBUG shim over an array with a run of equal timestamps (a
lower bound would return a different index); and decoding a series whose JSON
entries are out of order yields a sorted series.

Implemented by grok-4.6 (xhigh) via implementation-loop; reviewed hunk by hunk
plus an independent deep review that confirmed both equivalences by differential
fuzzing (200k sorted cases with no mismatch) and found the decoder gap, fixed in
one iterate round. Gatekeeper line anchors for the touched file were re-verified
independently.

The DEBUG sortedness assertion is checked once per merged series rather than
once per inserted entry: a per-entry check is itself O(n) and reintroduced, in
debug builds, exactly the quadratic scan this insertion path removes (measured
over the real 4160-entry history: a legacy migration took ~1000 ms with the
per-entry assertion versus ~15 ms without it).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Fix Codex day cost blanked by trace-only priority turns (#3150)

Row ownership evidence compared the retained rows against the persisted
standard/priority split using the trace database's tier classification.
The persisted maps come from the rows' own pricingMode, so a turn the
trace reports as priority after its rows were persisted as standard read
as a row-ownership mismatch, the rows lost trust, and the day fell back
to the aggregate — which returns nil for long-context tiered models, so
the whole day's cost disappeared from the menu, the chart and the window
total.

Judge retention against both classifications and flag only a group that
matches neither. A wrongly retained row set still fails both, because the
persisted totals are canonical for the file and tier classification never
changes how many tokens the rows carry.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* docs: credit #3141 and #3150 changelog entries

* fix(qwen-cloud): restore Brave browser support in cookie import (#3148)

* fix(qwen-cloud): restore Brave browser support, narrowed to Chrome+Brave per AGENTS.md

Qwen Cloud's cookie import was restricted to [.chrome] only (commit
529cc6c 'Keep Qwen imports Chrome-only'). Brave users hit 'No Qwen
Cloud session cookies found in browsers' even when they had a valid
Qwen Cloud session in Brave, because their cookies were never probed.

This commit restores Brave in the import order, but follows
AGENTS.md L48 ('default Chrome-only when possible to avoid other
browser prompts; override via browser list when needed'). The override
is the minimum necessary: Chrome + Brave. The other Chromium browsers
(chromeBeta, edge, arc, firefox, safari) are deliberately omitted to
avoid unsolicited Keychain / browser-store access prompts on
automatic refreshes from browsers that don't carry a Qwen Cloud
session. Brave is kept because it shares the same Chromium Safe
Storage format as Chrome and is a common Qwen Cloud authentication
target.

Also adds docs/qwen-cloud-proof/README.md with the redacted end-to-end
proof captured against the live Qwen Cloud API from the user's Mac
after granting the modified binary access to 'Brave Safe Storage' in
macOS Keychain.

* fix(qwen-cloud): recovery message now names Brave alongside Chrome

ClawSweeper P2 follow-up on #3148: when the Brave cookie import
fails, QwenCloudSettingsError.missingCookie's recovery message
still told users to sign in to Chrome and grant access to Chrome
Safe Storage. Now that Brave is a supported source, the message
must name both browsers and their respective Safe Storage entries,
otherwise a Brave-only user would be told to use Chrome and never
find the working path.

Updates the error description to:
  'No Qwen Cloud session cookies found in browsers. Sign in to
   Qwen Cloud in Chrome or Brave, allow CodexBar to access the
   corresponding Safe Storage in Keychain Access (Chrome Safe
   Storage and/or Brave Safe Storage), or paste a manual Cookie
   header.'

Adds focused test coverage:
- missing cookie error mentions both supported browsers and their safe storage
- missing cookie error appends non-empty details
- missing cookie error omits empty details

35/35 Qwen Cloud tests pass (32 prior + 3 new).

* Fix OpenRouter completed-day activity query (#3138)

* Preserve unknown Grok period usage (#3159)

Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>

* fix: report non-writable CLI path conflicts (#3153)

* fix: prefer successful CLI install status

* fix: keep CLI path conflicts visible

* fix: report non-writable CLI path conflicts

* docs: add CLI conflict behavior proof

* docs: add CLI install comparison screenshots

* Fix single-quota icon scaling (#3155)

* docs: credit #3138 #3148 #3153 #3155 #3159 changelog entries

* fix(spend): silent refresh and invalidation coverage (#3106)

* fix(spend): bucket calendar for all heatmap dates and full revision hash

- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for #3106.

* fix(gatekeeper): update anchors and add provider-specific design markers for spend dashboard

* Update provider gatekeeper anchors for v0.54 rebase

* fix(test): pin claude spend snapshot in observation test

* fix(test): seed pinned claude spend publication before first snapshot

* fix: resolve remaining conflict markers from gatekeeper rebase

* fix(lint): shorten Sakana test lines

* fix(spend): restore heatmap calendar property lost in rebase

* Extend spend publication test wait

* Restore spend gatekeeper anchors after rebase

* fix(spend): sync independent snapshot and bucket calendar normalization for 3106

- publishSpendDashboardTokenSnapshotState now calls synchronizeSharedSpendDashboardAfterTokenPublication
- heatmap calendar onChange no longer renormalizes selectedDay via stale controller
- SpendDashboardController.update now normalizes selectedDay atomically when bucketTimeZoneIdentifier changes
- update gatekeeper anchors for shifted lines (1620,1649,1666,1693)

* test(spend): cover independent snapshot sync for 3106

Exercise the direct independent publication path added at
UsageStore+SpendDashboardTokenCost.swift:181. The prior focused test
seeded Claude before observation and then used the regular Codex
publisher, which already syncs independently, so removing that line
would not fail. Add a post-start Claude snapshot via
_setSpendDashboardTokenSnapshotForTesting and assert the shared
dashboard debounced sync is scheduled and the publication inputs
update. Verified: swiftformat clean, swiftlint --strict clean,
swift test --filter SpendDashboardPublicationTests 18 tests passed.

* docs: add fresh-bundle proof for 3106

Add redacted menu-icon crop and dashboard snapshot from debug build
2798eec (swift build --target CodexBarCLI, .build/debug/CodexBarCLI
dashboard --pretty). The snapshot shows the shared spend controller
produces a dashboard with provider rows/windows, confirming the
independent-sync and calendar paths are live in the fresh binary.

* docs: add menu and Spend dashboard screenshots for 3106

Add redacted screenshots from fresh debug build 45ba984:
- 3106-menu-after-fix.png: menu bar extra open, showing provider rows
- 3106-settings-after-fix.png: Settings window (general)
- 3106-spend-dashboard-after-fix.png: Usage & Spend pane (usageSpend)
with heatmap and Overview, confirming the shared controller renders
in the fresh bundle.

* docs: remove screenshots for 3106 per request

Keep only the redacted CLI dashboard snapshot JSON as fresh-bundle
proof; screenshots are not needed.

* Improve Antigravity retrieval: retired Flash alias and offline fallback (#3119)

* fix(antigravity): allow OAuth errors to fallback to offline when local data exists

Fix P2 from Codex review on #3119: AntigravityOAuthFetchStrategy.shouldFallback
now checks hasOfflineData, so expired credentials do not block offline.

* fix(antigravity): unbind offline account, read app-data, bound scans + proof

- Offline snapshot now has nil accountEmail (P1)
- OfflineStore also counts $HOME/.gemini/antigravity and .../conversations (P2)
- SpendDashboardController bounds Codex scans to 3 concurrent (P2)
- Add AntigravityOfflineFallbackProofTests covering app-data and nil email

* fix: remove broken proof test, keep P1/P2 fixes and shell proof

* fix(gatekeeper): update SpendDashboardController anchors after bounding Codex scans

* fix: revert bounded Codex scans (keep offline P1/P2), restore gatekeeper

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity (#3113)

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity

- Cursor: read ~/.config/tokscale/cursor-cache/usage*.csv (v1/v2/v3) with
  tokstyle column handling, cacheWrite = with-without, noon UTC for date-only,
  and CostUsageDailyReport aggregation.
  (Sources/CodexBarCore/Providers/Cursor/CursorLocalCSVReader.swift:1)

- Antigravity: read ~/.config/tokscale/antigravity-cache/sessions/*.jsonl
  (tokscale JSONL) and stub for ~/.gemini/antigravity-cli/*.db direct SQLite
  (ProtoReader to follow). Handles session_meta fallback and dedup.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityLocalReader.swift:1)

- CostUsageFetcher: local fallback before remote for Cursor (offline) and
  primary for Antigravity (quota-only before), with Provider-specific by
  design comments for gatekeeper.
  (Sources/CodexBarCore/CostUsageFetcher.swift:440)

- Antigravity descriptor: enable supportsTokenSnapshot for spend dashboard.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityProviderDescriptor.swift:51)

Reproduced from /tmp/opencodex/src/adapters/cursor/protobuf-events.ts:218
and /tmp/tokscale/crates/tokscale-core/src/sessions/{cursor,antigravity_cli}.rs
Phase 1 of opencodex/tokscale plan, offline-first, no auth.

* test(readers): cover cursor csv schemas and antigravity cache fallback

* fix(test): include antigravity in cost capable dashboard sources

* fix(spend): honor CSV total tokens and add Antigravity Linux capability

* fix(test): honor cursor CSV total tokens column in aggregation

* fix(spend): repair 3113 tokscale readers P1s

- catch remote Cursor errors before falling back to local CSV
- recompute summaries after window filtering for Cursor and Antigravity
- keep Antigravity costs nil (unpriced) and deduplicate by responseId
- parse date-only CSV rows with UTC calendar
- thread fallback calendar through loaders

* fix(lint): repair 3113 build and format

- calendar before now in makeDailyReport
- implicit optional init
- wrap long lines and andOperator

* style: swiftformat wrap for 3113

* Fix 3113 provider gatekeeper anchors

* fix(spend): address 3113 review findings -- freshness, calendar, date-only, fixture model

- Preserve cache freshness: return nil when filtered window is empty instead of publishing established zero with now timestamp
- Pass pinned calendar into tokenSnapshot for Cursor/Antigravity local snapshots
- Keep date-only Cursor CSV rows in configured calendar's noon, not UTC noon
- Use clearly fictitious test model test-model-antigravity-a

* style: fix line length for fixture model

* fix(test): update gatekeeper anchors for CostUsageFetcher line drift

Allowlist lines 1339->1335 and 1695->1691 after 075eac7 freshness/calendar fixes

* docs: credit #3106 #3113 #3119 changelog entries

* feat: add CHF display currency (#3149)

* test: fix currency fixtures after CHF became supported

* fix(codex): tokscale parity for token counts - max cached, clamped, reasoning split, stale (#3120)

* Align Codex token parsing with tokscale stale snapshots

- skip lightly regressed cumulative snapshots before interleaved latching
- take the maximum of cached and cache-read fields in all parsers
- cover cache field selection and out-of-order snapshot accounting with focused tests

* Refresh Codex parser hash

* Parse bare usage rows in Codex rollouts

* Fix stale reasoning and fallback cache parity

* Fix Codex fallback test fixture line handling

* fix(antigravity): repair offline fallback proof and oauth fallback; fix(spend): limit concurrent dashboard fetches to 3

* fix(lint): break long lines in offline fallback proof tests

* fix(tests): update gatekeeper anchors for spend dashboard concurrency limit

* fix(tests): correct gatekeeper line anchors for concurrent dashboard fix

* docs: update appcast for 0.54.1

* chore: open 0.54.2 unreleased changelog section

* Stop re-merging the Codex plan-utilization history with itself on every refresh (#3141)

`materializeCodexPlanUtilizationHistoryIfNeeded` exists to fold legacy, opaque
and unscoped Codex plan-utilization buckets into the canonical account bucket.
Its scoped loop also appended the canonical bucket's own histories to
`historiesToMerge` — `matchesTargetContinuity` is true for
`rawKey == canonicalKey`, and only the removal of the old key was guarded — so
`guard !historiesToMerge.isEmpty` never fired once the canonical bucket had any
history, and the migration merge ran on every successful provider refresh and
every menu open, merging the history with itself.

That merge is quadratic: `updatedPlanUtilizationEntries` copied the whole entry
array per entry, scanned it linearly for the insertion point, and allocated the
same-hour slice. Measured with an optimized standalone reproduction over a real
three-month-old history (session 1909 entries, weekly 2239): 20.6 ms of MainActor
time per call, scaling ~3.9x per doubling. `planUtilizationMaxSamples` allows
17520 entries per series, so it would keep growing.

Two changes:

- Track whether a foreign source actually contributed and require that in the
  guard, so the canonical-only case returns without merging or rewriting
  anything. Every path where a legacy, opaque or unscoped bucket contributes is
  untouched; `legacyRawKeysToRemove` is populated only in branches that also set
  the flag, so no removal is skipped, and `providerBuckets.unscoped` is cleared
  only inside the branch that sets it.
- Make the merge itself near-linear: `updatedPlanUtilizationEntries` mutates the
  array in place and finds the insertion point with a binary search for the same
  strict upper bound (with a fast path for the common append), and
  `mergedPlanUtilizationHistories` accumulates per series and builds each history
  once.

The binary search assumes entries are sorted by `capturedAt`, which every
in-app producer guaranteed through `PlanUtilizationSeriesHistory`'s designated
initializer — except the synthesized `Codable` decoder, which assigned entries
verbatim from JSON. An explicit `init(from:)` now routes decoding through that
initializer, so an on-disk history written by an older build or edited by hand
cannot smuggle in an unsorted series.

The skipped self-merge also incidentally re-canonicalized per-hour peaks on
read; that repair belongs at load time, not on every refresh, and is not
reintroduced here. The visible effect is that at most one extra real observation
per affected hour is kept.

Tests: canonical-only history is returned untouched and enqueues no persistence
write (the history revision is unchanged); a genuine foreign merge matches an
explicit expected result across overlapping hours, out-of-order sources, distinct
series and retention trimming; the binary search's upper-bound contract is pinned
directly through a DEBUG shim over an array with a run of equal timestamps (a
lower bound would return a different index); and decoding a series whose JSON
entries are out of order yields a sorted series.

Implemented by grok-4.6 (xhigh) via implementation-loop; reviewed hunk by hunk
plus an independent deep review that confirmed both equivalences by differential
fuzzing (200k sorted cases with no mismatch) and found the decoder gap, fixed in
one iterate round. Gatekeeper line anchors for the touched file were re-verified
independently.

The DEBUG sortedness assertion is checked once per merged series rather than
once per inserted entry: a per-entry check is itself O(n) and reintroduced, in
debug builds, exactly the quadratic scan this insertion path removes (measured
over the real 4160-entry history: a legacy migration took ~1000 ms with the
per-entry assertion versus ~15 ms without it).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Fix Codex day cost blanked by trace-only priority turns (#3150)

Row ownership evidence compared the retained rows against the persisted
standard/priority split using the trace database's tier classification.
The persisted maps come from the rows' own pricingMode, so a turn the
trace reports as priority after its rows were persisted as standard read
as a row-ownership mismatch, the rows lost trust, and the day fell back
to the aggregate — which returns nil for long-context tiered models, so
the whole day's cost disappeared from the menu, the chart and the window
total.

Judge retention against both classifications and flag only a group that
matches neither. A wrongly retained row set still fails both, because the
persisted totals are canonical for the file and tier classification never
changes how many tokens the rows carry.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* docs: credit #3141 and #3150 changelog entries

* fix(qwen-cloud): restore Brave browser support in cookie import (#3148)

* fix(qwen-cloud): restore Brave browser support, narrowed to Chrome+Brave per AGENTS.md

Qwen Cloud's cookie import was restricted to [.chrome] only (commit
529cc6c 'Keep Qwen imports Chrome-only'). Brave users hit 'No Qwen
Cloud session cookies found in browsers' even when they had a valid
Qwen Cloud session in Brave, because their cookies were never probed.

This commit restores Brave in the import order, but follows
AGENTS.md L48 ('default Chrome-only when possible to avoid other
browser prompts; override via browser list when needed'). The override
is the minimum necessary: Chrome + Brave. The other Chromium browsers
(chromeBeta, edge, arc, firefox, safari) are deliberately omitted to
avoid unsolicited Keychain / browser-store access prompts on
automatic refreshes from browsers that don't carry a Qwen Cloud
session. Brave is kept because it shares the same Chromium Safe
Storage format as Chrome and is a common Qwen Cloud authentication
target.

Also adds docs/qwen-cloud-proof/README.md with the redacted end-to-end
proof captured against the live Qwen Cloud API from the user's Mac
after granting the modified binary access to 'Brave Safe Storage' in
macOS Keychain.

* fix(qwen-cloud): recovery message now names Brave alongside Chrome

ClawSweeper P2 follow-up on #3148: when the Brave cookie import
fails, QwenCloudSettingsError.missingCookie's recovery message
still told users to sign in to Chrome and grant access to Chrome
Safe Storage. Now that Brave is a supported source, the message
must name both browsers and their respective Safe Storage entries,
otherwise a Brave-only user would be told to use Chrome and never
find the working path.

Updates the error description to:
  'No Qwen Cloud session cookies found in browsers. Sign in to
   Qwen Cloud in Chrome or Brave, allow CodexBar to access the
   corresponding Safe Storage in Keychain Access (Chrome Safe
   Storage and/or Brave Safe Storage), or paste a manual Cookie
   header.'

Adds focused test coverage:
- missing cookie error mentions both supported browsers and their safe storage
- missing cookie error appends non-empty details
- missing cookie error omits empty details

35/35 Qwen Cloud tests pass (32 prior + 3 new).

* Fix OpenRouter completed-day activity query (#3138)

* Preserve unknown Grok period usage (#3159)

Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>

* fix: report non-writable CLI path conflicts (#3153)

* fix: prefer successful CLI install status

* fix: keep CLI path conflicts visible

* fix: report non-writable CLI path conflicts

* docs: add CLI conflict behavior proof

* docs: add CLI install comparison screenshots

* Fix single-quota icon scaling (#3155)

* docs: credit #3138 #3148 #3153 #3155 #3159 changelog entries

* fix(spend): silent refresh and invalidation coverage (#3106)

* fix(spend): bucket calendar for all heatmap dates and full revision hash

- SpendActivityDateFormatting.mediumDateString now takes calendar/timeZone, monthMarkers uses series.calendar, tooltips and accessibility use bucket calendar.
- selectedDay renormalized on calendar change to keep toggle correct.
- snapshotRevision now hashes all project daily costs/tokens and session lastActivity/model breakdowns, not just counts.

Fixes ClawSweeper P2 for #3106.

* fix(gatekeeper): update anchors and add provider-specific design markers for spend dashboard

* Update provider gatekeeper anchors for v0.54 rebase

* fix(test): pin claude spend snapshot in observation test

* fix(test): seed pinned claude spend publication before first snapshot

* fix: resolve remaining conflict markers from gatekeeper rebase

* fix(lint): shorten Sakana test lines

* fix(spend): restore heatmap calendar property lost in rebase

* Extend spend publication test wait

* Restore spend gatekeeper anchors after rebase

* fix(spend): sync independent snapshot and bucket calendar normalization for 3106

- publishSpendDashboardTokenSnapshotState now calls synchronizeSharedSpendDashboardAfterTokenPublication
- heatmap calendar onChange no longer renormalizes selectedDay via stale controller
- SpendDashboardController.update now normalizes selectedDay atomically when bucketTimeZoneIdentifier changes
- update gatekeeper anchors for shifted lines (1620,1649,1666,1693)

* test(spend): cover independent snapshot sync for 3106

Exercise the direct independent publication path added at
UsageStore+SpendDashboardTokenCost.swift:181. The prior focused test
seeded Claude before observation and then used the regular Codex
publisher, which already syncs independently, so removing that line
would not fail. Add a post-start Claude snapshot via
_setSpendDashboardTokenSnapshotForTesting and assert the shared
dashboard debounced sync is scheduled and the publication inputs
update. Verified: swiftformat clean, swiftlint --strict clean,
swift test --filter SpendDashboardPublicationTests 18 tests passed.

* docs: add fresh-bundle proof for 3106

Add redacted menu-icon crop and dashboard snapshot from debug build
2798eec (swift build --target CodexBarCLI, .build/debug/CodexBarCLI
dashboard --pretty). The snapshot shows the shared spend controller
produces a dashboard with provider rows/windows, confirming the
independent-sync and calendar paths are live in the fresh binary.

* docs: add menu and Spend dashboard screenshots for 3106

Add redacted screenshots from fresh debug build 45ba984:
- 3106-menu-after-fix.png: menu bar extra open, showing provider rows
- 3106-settings-after-fix.png: Settings window (general)
- 3106-spend-dashboard-after-fix.png: Usage & Spend pane (usageSpend)
with heatmap and Overview, confirming the shared controller renders
in the fresh bundle.

* docs: remove screenshots for 3106 per request

Keep only the redacted CLI dashboard snapshot JSON as fresh-bundle
proof; screenshots are not needed.

* Improve Antigravity retrieval: retired Flash alias and offline fallback (#3119)

* fix(antigravity): allow OAuth errors to fallback to offline when local data exists

Fix P2 from Codex review on #3119: AntigravityOAuthFetchStrategy.shouldFallback
now checks hasOfflineData, so expired credentials do not block offline.

* fix(antigravity): unbind offline account, read app-data, bound scans + proof

- Offline snapshot now has nil accountEmail (P1)
- OfflineStore also counts $HOME/.gemini/antigravity and .../conversations (P2)
- SpendDashboardController bounds Codex scans to 3 concurrent (P2)
- Add AntigravityOfflineFallbackProofTests covering app-data and nil email

* fix: remove broken proof test, keep P1/P2 fixes and shell proof

* fix(gatekeeper): update SpendDashboardController anchors after bounding Codex scans

* fix: revert bounded Codex scans (keep offline P1/P2), restore gatekeeper

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity (#3113)

* feat(spend): add tokscale-compatible local readers for Cursor and Antigravity

- Cursor: read ~/.config/tokscale/cursor-cache/usage*.csv (v1/v2/v3) with
  tokstyle column handling, cacheWrite = with-without, noon UTC for date-only,
  and CostUsageDailyReport aggregation.
  (Sources/CodexBarCore/Providers/Cursor/CursorLocalCSVReader.swift:1)

- Antigravity: read ~/.config/tokscale/antigravity-cache/sessions/*.jsonl
  (tokscale JSONL) and stub for ~/.gemini/antigravity-cli/*.db direct SQLite
  (ProtoReader to follow). Handles session_meta fallback and dedup.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityLocalReader.swift:1)

- CostUsageFetcher: local fallback before remote for Cursor (offline) and
  primary for Antigravity (quota-only before), with Provider-specific by
  design comments for gatekeeper.
  (Sources/CodexBarCore/CostUsageFetcher.swift:440)

- Antigravity descriptor: enable supportsTokenSnapshot for spend dashboard.
  (Sources/CodexBarCore/Providers/Antigravity/AntigravityProviderDescriptor.swift:51)

Reproduced from /tmp/opencodex/src/adapters/cursor/protobuf-events.ts:218
and /tmp/tokscale/crates/tokscale-core/src/sessions/{cursor,antigravity_cli}.rs
Phase 1 of opencodex/tokscale plan, offline-first, no auth.

* test(readers): cover cursor csv schemas and antigravity cache fallback

* fix(test): include antigravity in cost capable dashboard sources

* fix(spend): honor CSV total tokens and add Antigravity Linux capability

* fix(test): honor cursor CSV total tokens column in aggregation

* fix(spend): repair 3113 tokscale readers P1s

- catch remote Cursor errors before falling back to local CSV
- recompute summaries after window filtering for Cursor and Antigravity
- keep Antigravity costs nil (unpriced) and deduplicate by responseId
- parse date-only CSV rows with UTC calendar
- thread fallback calendar through loaders

* fix(lint): repair 3113 build and format

- calendar before now in makeDailyReport
- implicit optional init
- wrap long lines and andOperator

* style: swiftformat wrap for 3113

* Fix 3113 provider gatekeeper anchors

* fix(spend): address 3113 review findings -- freshness, calendar, date-only, fixture model

- Preserve cache freshness: return nil when filtered window is empty instead of publishing established zero with now timestamp
- Pass pinned calendar into tokenSnapshot for Cursor/Antigravity local snapshots
- Keep date-only Cursor CSV rows in configured calendar's noon, not UTC noon
- Use clearly fictitious test model test-model-antigravity-a

* style: fix line length for fixture model

* fix(test): update gatekeeper anchors for CostUsageFetcher line drift

Allowlist lines 1339->1335 and 1695->1691 after 075eac7 freshness/calendar fixes

* test: repair gatekeeper anchors and regenerate parser hash on merged tree

---------

Co-authored-by: Yuxin-Qiao <2242016570@qq.com>
Co-authored-by: Peter Steinberger <steipete@gmail.com>
Co-authored-by: Olddonkey <olddonkeyblog@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Umut Keltek <35880258+umutkeltek@users.noreply.github.com>
Co-authored-by: kiranmagic7 <kiranmagic@proton.me>
Co-authored-by: Anupam Chugh <anupam.chugh@gmail.com>
Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>
Co-authored-by: yicone <yicone@gmail.com>
Co-authored-by: Akshay Prabhu <12824090+akshayprabhu200@users.noreply.github.com>

* docs: credit #3120 changelog entry

* test: fix remaining CHF unconvertible fixtures after #3149

* fix: detect ChatGPT-hosted Codex activity (#3163)

* fix(antigravity): reuse signed-in agy for quota refresh (#3161)

* docs: credit #3161 and #3163 changelog entries

* Fix Claude web cookie refresh (#3162)

* docs: credit #3162 changelog entry

* chore: regenerate parser hash on merged tree

* test: include 0.54.2 parity hash in predecessor list

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Peter Steinberger <steipete@gmail.com>
Co-authored-by: Umut Keltek <35880258+umutkeltek@users.noreply.github.com>
Co-authored-by: kiranmagic7 <kiranmagic@proton.me>
Co-authored-by: Anupam Chugh <anupam.chugh@gmail.com>
Co-authored-by: anupamchugh <8416306+anupamchugh@users.noreply.github.com>
Co-authored-by: yicone <yicone@gmail.com>
Co-authored-by: Akshay Prabhu <12824090+akshayprabhu200@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <104957188+Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin-Qiao <2242016570@qq.com>
Co-authored-by: Zihao Qi <35388022+Zihao-Qi@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal priority bug or improvement with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants