cctally 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [1.9.0] - 2026-05-19
9
+
10
+ ### Removed
11
+ - `cctally release` subcommand — maintainer-only release automation moved to private `bin/cctally-release`. End-user npm/brew installs no longer carry release tooling, and `cctally setup` no longer expects a `cctally-release` symlink (stale symlinks from prior versions are auto-cleaned by `cctally setup --install`). The actual release process is unchanged for the maintainer; see `docs/RELEASE.md`.
12
+
13
+ ### Fixed
14
+ - Maintainer-only release tooling: recovery hints in `bin/_cctally_release.py` (Phase 4 `gh auth` fallback, Phase 5 npm poll timeout, Phase 6 brew dirty-clone refusal) now tell the operator to re-run `bin/cctally-release --resume` from the cctally-dev checkout — bare `cctally-release` is not on `~/.local/bin/` after the release-command split (`cctally setup` no longer auto-symlinks it). Round 1 of the split's review accumulator updated these hints from the removed `cctally release --resume` to `cctally-release --resume`; round 3 refines them to the path-relative form so an operator following the recovery instructions verbatim doesn't hit `command not found` unless they manually created an alias. The pre-existing docs convention (bare name in `docs/RELEASE.md` / `.claude/skills/release-cctally/SKILL.md` examples with an explicit "substitute `bin/cctally-release` (or your alias)" note) is unchanged.
15
+ - `cctally setup` and `cctally setup --uninstall` retire legacy `~/.local/bin/cctally-release` symlinks left behind by pre-v1.9.0 brew/npm installs. Previously the round-2 "stale" predicate required the symlink target to be *dangling*, which preserved a maintainer's manual link to the current checkout's still-shipped `bin/cctally-release` (intentional) but also preserved a legacy auto-installed link whose target points at an OLD homebrew keg / `node_modules/cctally/` tree that lingers on disk until `brew cleanup` (unintentional — leaves the retired command on PATH across upgrades). New `_setup_symlink_is_retired` adds a foreign-install-root branch alongside the dangling branch: a target whose path contains `/Cellar/cctally/` or `/node_modules/cctally/` AND that token is NOT in the current install's `repo_root` is classified as retired and removed. Both the install-time cleanup and the read-only `--status` detection route through it (so they agree on what's stale); the uninstall site now composes `target == expected OR is_retired(...)` for symmetric coverage. A maintainer's hand-rolled link to the current cctally-dev checkout (`~/.local/bin/cctally-release -> <checkout>/bin/cctally-release`) is still preserved — that target is neither dangling nor under a foreign install root. Regression: `tests/test_setup_stale_symlinks.py` adds four new scenarios — brew-keg/npm-modules cleanup, brew-keg `--status` detection, brew-keg uninstall.
16
+
17
+ ## [1.8.2] - 2026-05-18
18
+
19
+ ### Added
20
+ - dashboard envelope: new `blocks.total_cost_usd` and `blocks.total_tokens` fields exposed alongside `blocks.rows[]` so `BlocksPanel` reads the footer total from the envelope instead of running `rows.reduce((acc, r) => acc + r.cost_usd, 0)` in JS. Additive — pre-#56 envelopes without the fields fall back to `?? 0` so first-paint stays stable. Sourced from the new `BlocksView.total_cost_usd` / `total_tokens` view-model fields populated by `build_blocks_view` at sync-thread time.
21
+
22
+ ### Changed
23
+ - view-model kernel: extend `bin/_lib_view_models.py` with `BlocksView` and two builders — `build_blocks_view(entries, …)` for the heuristic-aware path (`cmd_blocks` + dashboard Blocks panel) and `build_blocks_view_from_table_rows(rows, …)` for the API-anchored path (`cmd_five_hour_blocks` + share snapshot). Both return the same `BlocksView` dataclass (`rows: tuple[BlocksPanelRow, …]` + `aggregated: tuple` + totals + period metadata). `cmd_blocks`, `_dashboard_build_blocks_panel`, and `_build_five_hour_blocks_snapshot` now all route through the kernel; `BlocksPanelRow` moves from `bin/_cctally_tui.py` to `bin/_lib_view_models.py` alongside the other panel row dataclasses (re-exported from `_cctally_tui` for back-compat). Reset-aware totals invariant preserved (API-anchored path reads `five_hour_blocks.total_cost_usd` straight from the table — not recomputed from `session_entries`). Closes #56.
24
+ - view-model kernel: extend `bin/_lib_view_models.py` with `ForecastView` + `build_forecast_view(conn, *, now_utc, targets, skip_sync, display_tz)` wrapping the existing `_load_forecast_inputs` + `_compute_forecast` math kernel. The View carries the wrapped `ForecastOutput` plus surface fields the dashboard envelope adapter used to re-derive inline — per-method projections (`week_avg_projection_pct` / `recent_24h_projection_pct`), `verdict` (TUI design language) / `dashboard_verdict` (cap/capped/ok), `header_projection_pct` (the "pick pessimistic when verdict warns" routing so the header pct and verdict pill agree), the (100%, 90%) budget pair, and `low_confidence` / `low_confidence_reasons`. `cmd_forecast`, `_tui_build_forecast`, `snapshot_to_envelope`, and `_build_forecast_share_panel_data` now all route through the View instead of duplicating the projection / verdict / budget routing across three call sites; the legacy inline routing in `snapshot_to_envelope` is retained as a fallback for fixture snapshots that construct `DataSnapshot` positionally without populating `forecast_view`. Envelope contract unchanged — byte-stable across all 27 forecast harness scenarios + 18 dashboard scenarios + 1124 pytest tests. Closes #57.
25
+ - view-model kernel: extend `bin/_lib_view_models.py` with `CodexDailyView` / `CodexMonthlyView` / `CodexWeeklyView` / `CodexSessionView` + their four `build_codex_{daily,monthly,weekly,session}_view(entries, *, now_utc, tz_name, …)` builders, wrapping the existing `_aggregate_codex_{daily,monthly,weekly,sessions}` math kernel without changing it. The intentional Codex divergences from upstream (LiteLLM token semantics where `input_tokens` includes `cached_input_tokens` and `output_tokens` includes `reasoning_output_tokens`, the `info.total_token_usage.total_tokens` monotonic-advance dedup, `codex-session` descending-by-`last_activity` default, `--offline` no-op, and the `CODEX_LEGACY_FALLBACK_MODEL = "gpt-5"` one-shot stderr warning) are preserved end-to-end since the builders delegate to the same aggregator entrypoints. The Codex domain has no dashboard panel or share consumer, so each View carries `rows: tuple[CodexBucketUsage | CodexSessionUsage, …]` (the aggregator's typed output IS the surface) plus totals and `display_tz_label` — no parallel typed row dataclass is needed (`TrendView.rows` precedent). `cmd_codex_daily` / `cmd_codex_monthly` / `cmd_codex_weekly` / `cmd_codex_session` now route through the kernel; the `--order` reversal and per-mode no-data sentinel + JSON/table rendering paths stay in the CLI consumer. Byte-stable across all 27 codex harness scenarios (`codex-daily` 12/12, `codex-monthly` 4/4, `codex-weekly` 4/4, `codex-session` 7/7). Closes #58.
26
+ - view-model kernel: extend `TrendView` in `bin/_lib_view_models.py` with a pre-computed `median_dpp_non_current_4w: float | None` scalar — the dashboard Trend modal's "4-week median" hero KV used to derive this client-side via `median4NonCurrent` in `dashboard/web/src/modals/TrendModal.tsx`. The rule (drop the current row, keep finite dpp values, sort the last 4 ascending, take the midpoint `(s[1]+s[2])/2`, `None` when fewer than 4 valid non-current samples) now lives in `build_trend_view` so a future change ports across CLI / TUI / dashboard / share in one edit. The sync thread captures the 12-row history's `TrendView` (via new `_tui_build_weekly_history_view` sibling — same forecast-pattern wrap as `_tui_build_forecast_view`) and threads the scalar onto `DataSnapshot.trend_history_median_dpp`. `snapshot_to_envelope` adds an additive `trend.history_median_dpp` field on the envelope (additive contract — older snapshots that omit it fall back to the client-side `median4NonCurrentFallback` helper in TrendModal.tsx). All 18 dashboard harness scenarios regenerated to include the new field; rest of the suite (1004/0 + pytest PASS) unchanged. Closes #59.
27
+
8
28
  ## [1.8.1] - 2026-05-18
9
29
 
10
30
  ### Fixed
@@ -1350,13 +1350,16 @@ def _build_forecast_share_panel_data(options: dict,
1350
1350
  snap: "DataSnapshot | None") -> dict:
1351
1351
  """Forecast panel_data — projection + per-day budgets + days-to-ceiling.
1352
1352
 
1353
- Reuses `DataSnapshot.forecast` (ForecastOutput).
1354
- `projection_curve` is synthesized from `r_avg` / `r_recent` /
1355
- `inputs.p_now` the same arithmetic `snapshot_to_envelope` does for
1356
- `week_avg_projection_pct` / `recent_24h_projection_pct`, extended
1357
- across the next 7 days.
1353
+ Reuses ``DataSnapshot.forecast`` (ForecastOutput) and, when populated
1354
+ by the sync thread, ``DataSnapshot.forecast_view`` (the kernel
1355
+ wrapper from issue #57) for the (100, 90) budget pair.
1356
+ ``projection_curve`` is synthesized from ``r_avg`` / ``r_recent`` /
1357
+ ``inputs.p_now`` the same arithmetic ``snapshot_to_envelope`` does
1358
+ for ``week_avg_projection_pct`` / ``recent_24h_projection_pct``,
1359
+ extended across the next 7 days.
1358
1360
  """
1359
1361
  fc = getattr(snap, "forecast", None) if snap else None
1362
+ fc_view = getattr(snap, "forecast_view", None) if snap else None
1360
1363
  if fc is None:
1361
1364
  return {
1362
1365
  "projected_end_pct": 0.0,
@@ -1388,16 +1391,26 @@ def _build_forecast_share_panel_data(options: dict,
1388
1391
  return max(0.0, hours / 24.0)
1389
1392
  days_to_100 = _days_to_ceiling(100.0)
1390
1393
  days_to_90 = _days_to_ceiling(90.0)
1391
- # Daily budgets — pull from fc.budgets[] when present
1394
+ # Daily budgets — prefer ForecastView's pre-routed pair (issue #57)
1395
+ # when available; otherwise replay the legacy ``fc.budgets`` scan
1396
+ # inline so positionally-constructed fixture snapshots still work.
1392
1397
  budgets: dict = {"avg": 0.0, "recent_24h": 0.0,
1393
1398
  "until_90pct": 0.0, "until_100pct": 0.0}
1394
- for b in getattr(fc, "budgets", None) or []:
1395
- tp = getattr(b, "target_percent", None)
1396
- dpd = float(getattr(b, "dollars_per_day", 0.0) or 0.0)
1397
- if tp == 100:
1398
- budgets["until_100pct"] = dpd
1399
- elif tp == 90:
1400
- budgets["until_90pct"] = dpd
1399
+ if fc_view is not None:
1400
+ budgets["until_100pct"] = float(
1401
+ fc_view.budget_100_per_day_usd or 0.0,
1402
+ )
1403
+ budgets["until_90pct"] = float(
1404
+ fc_view.budget_90_per_day_usd or 0.0,
1405
+ )
1406
+ else:
1407
+ for b in getattr(fc, "budgets", None) or []:
1408
+ tp = getattr(b, "target_percent", None)
1409
+ dpd = float(getattr(b, "dollars_per_day", 0.0) or 0.0)
1410
+ if tp == 100:
1411
+ budgets["until_100pct"] = dpd
1412
+ elif tp == 90:
1413
+ budgets["until_90pct"] = dpd
1401
1414
  # avg / recent_24h: derive from dollars-per-percent × r_avg/r_recent.
1402
1415
  dpp = float(getattr(inputs, "dollars_per_percent", 0.0) or 0.0) if inputs else 0.0
1403
1416
  budgets["avg"] = dpp * r_avg * 24.0
@@ -2138,20 +2151,31 @@ def _build_block_detail(block: "Block",
2138
2151
  }
2139
2152
 
2140
2153
 
2141
- def _dashboard_build_blocks_panel(conn: "sqlite3.Connection",
2142
- now_utc: "dt.datetime",
2143
- *,
2144
- week_start_at: "dt.datetime",
2145
- week_end_at: "dt.datetime",
2146
- skip_sync: bool = False,
2147
- display_tz: "ZoneInfo | None" = None) -> "list[BlocksPanelRow]":
2148
- """Activity blocks (`is_gap=False`) inside ``[week_start_at, week_end_at)``,
2149
- newest-first.
2150
-
2151
- Mirrors the recorded-windows-widening trick used by ``cmd_blocks``: loads
2152
- recorded reset windows from ``[start - BLOCK_DURATION, end + BLOCK_DURATION]``
2153
- so a recorded reset just outside the visible window can still anchor
2154
- blocks inside it.
2154
+ def _dashboard_build_blocks_view(conn: "sqlite3.Connection",
2155
+ now_utc: "dt.datetime",
2156
+ *,
2157
+ week_start_at: "dt.datetime",
2158
+ week_end_at: "dt.datetime",
2159
+ skip_sync: bool = False,
2160
+ display_tz: "ZoneInfo | None" = None):
2161
+ """Build a ``BlocksView`` for the dashboard Blocks panel window
2162
+ ``[week_start_at, week_end_at)`` (issue #56).
2163
+
2164
+ Two-layer composition (mirrors `_dashboard_build_daily_panel`'s
2165
+ pattern):
2166
+
2167
+ 1. ``build_blocks_view`` (in ``bin/_lib_view_models.py``) is the
2168
+ data plane — `_group_entries_into_blocks` plus per-block model
2169
+ enrichment plus totals derivation.
2170
+ 2. This function is the presentation adapter — owns the
2171
+ recorded-windows-widening trick (loads reset windows from
2172
+ ``[start - BLOCK_DURATION, end + BLOCK_DURATION]`` so a recorded
2173
+ reset just outside the visible window can still anchor blocks
2174
+ inside it) and the strict-window entry filter.
2175
+
2176
+ Returning the full ``BlocksView`` (rows + totals) lets the sync
2177
+ thread populate ``DataSnapshot.blocks_total_cost_usd`` /
2178
+ ``blocks_total_tokens`` for the envelope without a second pass.
2155
2179
  """
2156
2180
  # Widen the entry window slightly so a recorded-reset window straddling
2157
2181
  # the boundary still picks up its entries.
@@ -2163,52 +2187,42 @@ def _dashboard_build_blocks_panel(conn: "sqlite3.Connection",
2163
2187
  recorded_windows, block_start_overrides = _load_recorded_five_hour_windows(
2164
2188
  fetch_start, fetch_end,
2165
2189
  )
2166
- blocks = _group_entries_into_blocks(
2167
- entries, mode="auto",
2190
+ c = _cctally()
2191
+ return c.build_blocks_view(
2192
+ entries,
2193
+ now_utc=now_utc,
2168
2194
  recorded_windows=recorded_windows,
2169
2195
  block_start_overrides=block_start_overrides,
2170
- now=now_utc,
2196
+ range_start=week_start_at,
2197
+ range_end=week_end_at,
2198
+ display_tz=display_tz,
2199
+ mode="auto",
2171
2200
  )
2172
- blocks = [b for b in blocks if not b.is_gap]
2173
- if not blocks:
2174
- return []
2175
2201
 
2176
- # Build per-block model-cost breakdown (matches _model_breakdowns_to_models
2177
- # input shape: dicts with `modelName` / `cost` keys, sorted desc by cost).
2178
- rows: list[BlocksPanelRow] = []
2179
- for b in blocks:
2180
- # Reaggregate the entries inside [b.start_time, b.end_time) for
2181
- # the model-split. _group_entries_into_blocks gives us total
2182
- # cost_usd per block but not per-model breakdown. Use
2183
- # `_calculate_entry_cost` (the single source-of-truth pricing
2184
- # path) so block per-model costs reconcile exactly with the
2185
- # block's own cost_usd.
2186
- per_model: dict[str, float] = {}
2187
- for e in entries:
2188
- if b.start_time <= e.timestamp < b.end_time:
2189
- cost = _calculate_entry_cost(
2190
- e.model, e.usage, mode="auto", cost_usd=e.cost_usd,
2191
- )
2192
- per_model[e.model] = per_model.get(e.model, 0.0) + cost
2193
- model_breakdowns = [
2194
- {"modelName": name, "cost": cost}
2195
- for name, cost in sorted(per_model.items(), key=lambda kv: -kv[1])
2196
- ]
2197
- local_label = format_display_dt(
2198
- b.start_time, display_tz, fmt="%H:%M %b %d", suffix=True,
2199
- )
2200
- rows.append(BlocksPanelRow(
2201
- start_at=b.start_time.astimezone(dt.timezone.utc).isoformat(),
2202
- end_at=b.end_time.astimezone(dt.timezone.utc).isoformat(),
2203
- anchor=b.anchor,
2204
- is_active=bool(b.is_active and b.entries_count > 0),
2205
- cost_usd=b.cost_usd,
2206
- models=_model_breakdowns_to_models(model_breakdowns, b.cost_usd),
2207
- label=local_label,
2208
- ))
2209
-
2210
- rows.sort(key=lambda r: r.start_at, reverse=True)
2211
- return rows
2202
+
2203
+ def _dashboard_build_blocks_panel(conn: "sqlite3.Connection",
2204
+ now_utc: "dt.datetime",
2205
+ *,
2206
+ week_start_at: "dt.datetime",
2207
+ week_end_at: "dt.datetime",
2208
+ skip_sync: bool = False,
2209
+ display_tz: "ZoneInfo | None" = None) -> "list[BlocksPanelRow]":
2210
+ """Activity blocks (`is_gap=False`) inside ``[week_start_at, week_end_at)``,
2211
+ newest-first.
2212
+
2213
+ Thin presentation shim over ``_dashboard_build_blocks_view`` —
2214
+ returns just ``view.rows`` so existing call sites (sync thread,
2215
+ share-data override resolver, monkeypatch surfaces) keep their
2216
+ ``list[BlocksPanelRow]`` contract.
2217
+ """
2218
+ view = _dashboard_build_blocks_view(
2219
+ conn, now_utc,
2220
+ week_start_at=week_start_at,
2221
+ week_end_at=week_end_at,
2222
+ skip_sync=skip_sync,
2223
+ display_tz=display_tz,
2224
+ )
2225
+ return list(view.rows)
2212
2226
 
2213
2227
 
2214
2228
  def _dashboard_build_daily_panel(conn: "sqlite3.Connection",
@@ -2662,6 +2676,16 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
2662
2676
  """
2663
2677
  cw = snap.current_week
2664
2678
  fc = snap.forecast
2679
+ # Issue #57 — prefer ``snap.forecast_view`` (precomputed by the
2680
+ # sync thread via ``build_forecast_view``) over re-deriving the
2681
+ # projection / verdict / header-routing / budget fields inline.
2682
+ # Falls back to the legacy inline routing below when
2683
+ # ``forecast_view`` is missing — fixture modules that construct
2684
+ # ``DataSnapshot`` positionally without the post-Bundle-1 fields
2685
+ # leave it at ``None``, and their goldens predate the View so
2686
+ # keeping the legacy path under that fallback preserves byte
2687
+ # stability.
2688
+ fc_view = getattr(snap, "forecast_view", None)
2665
2689
 
2666
2690
  # F1 fix: server-resolve the display tz to a CONCRETE IANA name and
2667
2691
  # surface it on the envelope so the browser never has to guess "local".
@@ -2690,19 +2714,35 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
2690
2714
  five_hr = getattr(cw, "five_hour_pct", None) if cw is not None else None
2691
2715
  dollar_pp = getattr(cw, "dollars_per_percent", None) if cw is not None else None
2692
2716
 
2693
- # Forecast fields: route each projection by method identity from
2694
- # r_avg / r_recent and inputs.{p_now, remaining_hours}. Don't use
2695
- # final_percent_{low,high} directly those are numerical min/max of
2696
- # the two methods, which swaps the labels on decelerating weeks
2697
- # (r_recent < r_avg). Map defensively via getattr the JS only
2698
- # needs the values, not the internal structure.
2717
+ # Forecast field routing (issue #57). ``snap.forecast_view`` is the
2718
+ # single source of truth: ``build_forecast_view`` runs the per-
2719
+ # method projection / verdict / budget routing once and stashes
2720
+ # the surface fields on the View. The legacy inline derivation
2721
+ # remains as a fallback for fixture modules that construct
2722
+ # ``DataSnapshot`` positionally without populating ``forecast_view``
2723
+ # — their goldens predate the View, and the legacy block emits
2724
+ # the same numbers so byte stability is preserved.
2699
2725
  fcast_pct: "float | None" = None
2700
2726
  recent_24h_pct: "float | None" = None
2701
2727
  verdict: "str | None" = None
2702
2728
  confidence: "str | None" = None
2703
2729
  budget_100: "float | None" = None
2704
2730
  budget_90: "float | None" = None
2705
- if fc is not None:
2731
+ if fc_view is not None:
2732
+ fcast_pct = fc_view.week_avg_projection_pct
2733
+ recent_24h_pct = fc_view.recent_24h_projection_pct
2734
+ # ForecastView.dashboard_verdict / .confidence default to
2735
+ # ``"ok"`` / ``"unknown"`` even when ``output is None``; only
2736
+ # surface non-None envelope values when there's an actual
2737
+ # ForecastOutput backing them so the existing
2738
+ # ``verdict / confidence is None when fc is None`` shape stays.
2739
+ verdict = fc_view.dashboard_verdict if fc is not None else None
2740
+ confidence = fc_view.confidence if fc is not None else None
2741
+ budget_100 = fc_view.budget_100_per_day_usd
2742
+ budget_90 = fc_view.budget_90_per_day_usd
2743
+ elif fc is not None:
2744
+ # Legacy inline routing — kept verbatim for positionally-
2745
+ # constructed fixture snapshots that don't carry ``forecast_view``.
2706
2746
  inputs = getattr(fc, "inputs", None)
2707
2747
  if inputs is not None:
2708
2748
  confidence = getattr(inputs, "confidence", None)
@@ -2715,11 +2755,8 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
2715
2755
  if (p_now is not None and rem_hrs is not None
2716
2756
  and r_recent is not None):
2717
2757
  p_final_recent = p_now + r_recent * rem_hrs
2718
- # Only emit recent_24h when the two projections diverge — if
2719
- # r_recent equals r_avg the second method added no info.
2720
2758
  if fcast_pct is None or p_final_recent != fcast_pct:
2721
2759
  recent_24h_pct = p_final_recent
2722
- # Verdict — simple mapping: "cap" if projected_cap, else "ok".
2723
2760
  if getattr(fc, "already_capped", False):
2724
2761
  verdict = "capped"
2725
2762
  elif getattr(fc, "projected_cap", False):
@@ -2773,20 +2810,23 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
2773
2810
  reset_at_utc = we
2774
2811
 
2775
2812
  # Header forecast_pct should match the projection that drove the
2776
- # verdict pill next to it. When the verdict warns (projected to
2777
- # cap or already capped) and the recent-24h projection is higher
2778
- # than the week-average path, surface the pessimistic value so
2779
- # the number and the pill tell the same story. The Forecast panel
2780
- # still exposes both `week_avg_projection_pct` and
2781
- # `recent_24h_projection_pct` unchanged.
2782
- header_fcast_pct = fcast_pct
2783
- if (
2784
- verdict in ("cap", "capped")
2785
- and recent_24h_pct is not None
2786
- and fcast_pct is not None
2787
- and recent_24h_pct > fcast_pct
2788
- ):
2789
- header_fcast_pct = recent_24h_pct
2813
+ # verdict pill next to it. The View (issue #57) carries the
2814
+ # already-routed ``header_projection_pct``; the fallback path
2815
+ # replays the legacy routing inline for fixture snapshots that
2816
+ # don't populate ``forecast_view``. The Forecast panel still
2817
+ # exposes both ``week_avg_projection_pct`` and
2818
+ # ``recent_24h_projection_pct`` unchanged.
2819
+ if fc_view is not None and fc is not None:
2820
+ header_fcast_pct = fc_view.header_projection_pct
2821
+ else:
2822
+ header_fcast_pct = fcast_pct
2823
+ if (
2824
+ verdict in ("cap", "capped")
2825
+ and recent_24h_pct is not None
2826
+ and fcast_pct is not None
2827
+ and recent_24h_pct > fcast_pct
2828
+ ):
2829
+ header_fcast_pct = recent_24h_pct
2790
2830
 
2791
2831
  # ---- weekly / monthly periods ---------------------------------
2792
2832
  def _weekly_row_to_dict(r: "WeeklyPeriodRow") -> dict:
@@ -2877,7 +2917,18 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
2877
2917
  "total_tokens": snap.monthly_total_tokens,
2878
2918
  }
2879
2919
 
2880
- blocks_env = {"rows": [_blocks_row_to_dict(r) for r in snap.blocks_panel]}
2920
+ blocks_env = {
2921
+ "rows": [_blocks_row_to_dict(r) for r in snap.blocks_panel],
2922
+ # View-model unification follow-up (issue #56): additive scalars
2923
+ # so the React BlocksPanel can stop running `rows.reduce(...)`
2924
+ # in JS. Cost is summed-over-visible-rows in
2925
+ # `_dashboard_build_blocks_view` (same structural invariant as
2926
+ # daily/weekly/monthly footers); ``total_tokens`` is sourced
2927
+ # from the same view since ``BlocksPanelRow`` doesn't carry
2928
+ # token columns and we don't want to widen that shape.
2929
+ "total_cost_usd": snap.blocks_total_cost_usd,
2930
+ "total_tokens": snap.blocks_total_tokens,
2931
+ }
2881
2932
 
2882
2933
  # Re-run helper to derive thresholds; mutates rows[*].intensity_bucket
2883
2934
  # (no-op for builder-constructed rows since values match cost_usd).
@@ -3106,11 +3157,20 @@ def snapshot_to_envelope(snap: "DataSnapshot", *,
3106
3157
  for w in (snap.weekly_history or [])
3107
3158
  ],
3108
3159
  # View-model unification (Bundle 1; spec §6.6): the
3109
- # pre-computed 3-sample $/% mean. TrendPanel can stop
3110
- # re-deriving the panel-average; TrendModal's median
3111
- # over trend.history is out of scope for this refactor
3112
- # (separate dataset, separate follow-up).
3160
+ # pre-computed 3-sample $/% mean. TrendPanel reads this
3161
+ # instead of re-deriving the panel-average.
3113
3162
  "avg_dollars_per_pct": snap.trend_avg_dollars_per_pct,
3163
+ # Issue #59 follow-up: pre-computed 4-week-median of
3164
+ # non-current ``dollars_per_percent`` over the 12-row
3165
+ # history. TrendModal.tsx's ``median4NonCurrent`` helper
3166
+ # used to compute this client-side; pre-computing on
3167
+ # ``build_trend_view`` keeps the rule
3168
+ # (``sort(last 4 non-current dpps)``, midpoint
3169
+ # ``(s[1]+s[2])/2``) in one place. ``None`` when fewer
3170
+ # than 4 valid non-current samples — modal's client-side
3171
+ # fallback handles the ``null`` case.
3172
+ "history_median_dpp":
3173
+ getattr(snap, "trend_history_median_dpp", None),
3114
3174
  },
3115
3175
 
3116
3176
  "weekly": weekly_env,