cctally 1.22.3 → 1.23.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 +19 -0
- package/bin/_cctally_alerts.py +27 -0
- package/bin/_cctally_config.py +68 -9
- package/bin/_cctally_core.py +60 -2
- package/bin/_cctally_dashboard.py +225 -60
- package/bin/_cctally_forecast.py +25 -3
- package/bin/_cctally_milestones.py +68 -0
- package/bin/_cctally_parser.py +10 -2
- package/bin/_cctally_record.py +472 -138
- package/bin/_cctally_tui.py +1 -0
- package/bin/_cctally_weekrefs.py +36 -2
- package/bin/_lib_alert_axes.py +44 -0
- package/bin/_lib_alerts_payload.py +67 -0
- package/bin/_lib_budget.py +8 -0
- package/bin/_lib_diff_kernel.py +5 -8
- package/bin/_lib_fmt.py +325 -0
- package/bin/_lib_render.py +9 -24
- package/bin/cctally +33 -273
- package/dashboard/static/assets/index-CXZDQrV3.js +18 -0
- package/dashboard/static/assets/{index-BxmaYT1y.css → index-ZHOC14y-.css} +1 -1
- package/dashboard/static/dashboard.html +2 -2
- package/package.json +3 -1
- package/dashboard/static/assets/index-CLcd-Tnm.js +0 -18
package/bin/_cctally_weekrefs.py
CHANGED
|
@@ -278,7 +278,7 @@ def _backfill_week_reset_events(conn: sqlite3.Connection) -> None:
|
|
|
278
278
|
if (
|
|
279
279
|
captured_dt < prior_end_dt
|
|
280
280
|
and prior_pct is not None and cur_pct is not None
|
|
281
|
-
and (
|
|
281
|
+
and _is_reset_drop(prior_pct, cur_pct)
|
|
282
282
|
):
|
|
283
283
|
# Floor to the hour so the display boundary lands on the
|
|
284
284
|
# natural hour mark (Anthropic's reset times are always
|
|
@@ -309,7 +309,7 @@ def _backfill_week_reset_events(conn: sqlite3.Connection) -> None:
|
|
|
309
309
|
if (
|
|
310
310
|
captured_dt < prior_end_dt
|
|
311
311
|
and prior_pct is not None and cur_pct is not None
|
|
312
|
-
and (
|
|
312
|
+
and _is_reset_drop(prior_pct, cur_pct)
|
|
313
313
|
):
|
|
314
314
|
# Pre-check on ``new_week_end_at`` (mirrors the live
|
|
315
315
|
# detection path's pre-check). Necessary because the
|
|
@@ -379,6 +379,40 @@ _RESET_PCT_DROP_THRESHOLD = 25.0
|
|
|
379
379
|
# §2.1 (Q1) for rationale.
|
|
380
380
|
_FIVE_HOUR_RESET_PCT_DROP_THRESHOLD = 5.0
|
|
381
381
|
|
|
382
|
+
# Reset-to-zero discriminator (2026-06-01 surprise-reset fix). Anthropic's
|
|
383
|
+
# weekly reset zeroes the counter mid-window, but the 25pp magnitude gate
|
|
384
|
+
# above silently masks it for any user below ~25% usage (e.g. the observed
|
|
385
|
+
# 14→0). A reset-to-zero is unambiguous REGARDLESS of magnitude: a lagging
|
|
386
|
+
# API replica reports a slightly-lower number, never a clean 0 against real
|
|
387
|
+
# usage. So the detector ALSO fires when the post value collapses to ~0
|
|
388
|
+
# (<= _RESET_ZERO_FLOOR_PCT) with a drop clearing a small min-drop floor.
|
|
389
|
+
# The floor rejects 1%→0% stale-replica jitter, which would otherwise write
|
|
390
|
+
# a spurious week_reset_events row and segment the week.
|
|
391
|
+
_RESET_ZERO_FLOOR_PCT = 1.0
|
|
392
|
+
_RESET_ZERO_MIN_DROP_PCT = 3.0
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _is_reset_drop(prior_pct: float, cur_pct: float) -> bool:
|
|
396
|
+
"""True when ``prior_pct → cur_pct`` is a genuine weekly reset/credit.
|
|
397
|
+
|
|
398
|
+
Two independent percent-shape signals (OR):
|
|
399
|
+
|
|
400
|
+
* **Partial credit** — drop ``>= _RESET_PCT_DROP_THRESHOLD`` (25pp).
|
|
401
|
+
* **Reset-to-zero** — ``cur_pct`` collapses to ~0
|
|
402
|
+
(``<= _RESET_ZERO_FLOOR_PCT``) with a drop clearing
|
|
403
|
+
``_RESET_ZERO_MIN_DROP_PCT``.
|
|
404
|
+
|
|
405
|
+
Callers retain the boundary predicates (same/advanced ``week_end_at``
|
|
406
|
+
AND ``prior_end_dt > now``); this helper owns ONLY the percent-shape
|
|
407
|
+
discrimination so all four 7d detection sites (live advance, live
|
|
408
|
+
in-place, backfill advance, backfill in-place) stay byte-identical.
|
|
409
|
+
"""
|
|
410
|
+
cur = float(cur_pct)
|
|
411
|
+
drop = float(prior_pct) - cur
|
|
412
|
+
if drop >= _RESET_PCT_DROP_THRESHOLD:
|
|
413
|
+
return True
|
|
414
|
+
return cur <= _RESET_ZERO_FLOOR_PCT and drop >= _RESET_ZERO_MIN_DROP_PCT
|
|
415
|
+
|
|
382
416
|
|
|
383
417
|
def _week_ref_has_reset_event(
|
|
384
418
|
conn: sqlite3.Connection, ref: WeekRef
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Pure kernel: alert-axis descriptors + registry + shared severity policy.
|
|
2
|
+
|
|
3
|
+
Single source of truth for axis *metadata* — id, chip/title labels (kept
|
|
4
|
+
byte-identical with dashboard/web/src/lib/alertAxis.ts), the milestone-table
|
|
5
|
+
name used by the dashboard envelope, and the axis-uniform severity policy
|
|
6
|
+
(amber <95 / red >=95). This kernel does NOT own the write/transaction path:
|
|
7
|
+
each axis keeps its own detect-and-arm code in bin/_cctally_record.py. The
|
|
8
|
+
descriptor is the metadata/render contract, not the write engine.
|
|
9
|
+
|
|
10
|
+
Stdlib-only, no I/O at import time. bin/cctally re-exports the public symbols.
|
|
11
|
+
Spec: docs/superpowers/specs/2026-06-01-alerts-axis-registry-projected-pace-design.md
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
# Severity boundary: thresholds at or above this render red, below it amber.
|
|
18
|
+
# Mirrors the legacy hardcoded amber<95 / red>=95 split (axis-uniform v1).
|
|
19
|
+
_SEVERITY_RED_FLOOR = 95
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def severity_for(threshold: int) -> str:
|
|
23
|
+
"""Map a crossed integer threshold to a severity color ('amber' | 'red')."""
|
|
24
|
+
return "red" if int(threshold) >= _SEVERITY_RED_FLOOR else "amber"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class AlertAxisDescriptor:
|
|
29
|
+
"""Axis-agnostic metadata shared by the record path + dashboard envelope."""
|
|
30
|
+
|
|
31
|
+
id: str # 'weekly' | 'five_hour' | 'budget' | 'projected'
|
|
32
|
+
chip_label: str # SHOUT form, byte-identical with alertAxis.ts AXIS_CHIP_LABEL
|
|
33
|
+
title_label: str # sentence-case form, byte-identical with AXIS_TITLE_LABEL
|
|
34
|
+
milestone_table: str # SQLite table the dashboard envelope SELECTs from
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
AXIS_REGISTRY: "tuple[AlertAxisDescriptor, ...]" = (
|
|
38
|
+
AlertAxisDescriptor("weekly", "WEEKLY", "Weekly", "percent_milestones"),
|
|
39
|
+
AlertAxisDescriptor("five_hour", "5H-BLOCK", "5h-block", "five_hour_milestones"),
|
|
40
|
+
AlertAxisDescriptor("budget", "BUDGET", "Budget", "budget_milestones"),
|
|
41
|
+
AlertAxisDescriptor("projected", "PROJECTED", "Projected", "projected_milestones"),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
AXIS_BY_ID: "dict[str, AlertAxisDescriptor]" = {d.id: d for d in AXIS_REGISTRY}
|
|
@@ -242,3 +242,70 @@ def _build_alert_payload_budget(
|
|
|
242
242
|
"consumption_pct": float(consumption_pct),
|
|
243
243
|
},
|
|
244
244
|
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _alert_text_projected(payload: dict, tz: "ZoneInfo | None") -> tuple[str, str, str]:
|
|
248
|
+
"""Build (title, subtitle, body) for a projected-pace alert (#121).
|
|
249
|
+
|
|
250
|
+
These fire on the WEEK-AVERAGE projection — what you're tracking toward at
|
|
251
|
+
the current week-average pace — NOT on an actual crossing. The text carries
|
|
252
|
+
an explicit "(projection)" / "on current pace" cue so a user never confuses
|
|
253
|
+
a projected alert with an actual-crossing one (which the weekly/budget
|
|
254
|
+
builders render). The rendered numbers come from the payload (the values
|
|
255
|
+
snapshotted at crossing), never from live config (Codex P0-4). ``tz`` is
|
|
256
|
+
accepted for signature parity with peer ``_alert_text_*`` builders and
|
|
257
|
+
intentionally unused (no instant is rendered, same as ``_alert_text_budget``).
|
|
258
|
+
"""
|
|
259
|
+
metric = payload["metric"]
|
|
260
|
+
t = int(payload["threshold"])
|
|
261
|
+
proj = float(payload["projected_value"])
|
|
262
|
+
denom = float(payload["denominator"])
|
|
263
|
+
if metric == "weekly_pct":
|
|
264
|
+
title = f"cctally - projected to reach {t}% this week"
|
|
265
|
+
subtitle = "On current pace (projection)"
|
|
266
|
+
body = f"Projected ~{proj:.0f}% of cap by reset (week-average pace)"
|
|
267
|
+
else: # budget_usd
|
|
268
|
+
title = "cctally - projected to exceed budget"
|
|
269
|
+
subtitle = f"On current pace (projection) - {t}% of budget"
|
|
270
|
+
body = (
|
|
271
|
+
f"Projected ${proj:,.2f} of ${denom:,.2f} budget "
|
|
272
|
+
f"(week-average pace)"
|
|
273
|
+
)
|
|
274
|
+
return title, subtitle, body
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _build_alert_payload_projected(
|
|
278
|
+
*,
|
|
279
|
+
metric: str,
|
|
280
|
+
threshold: int,
|
|
281
|
+
projected_value: float,
|
|
282
|
+
denominator: float,
|
|
283
|
+
week_start_at: str,
|
|
284
|
+
) -> dict:
|
|
285
|
+
"""Build the alert payload for a projected-pace threshold crossing (#121).
|
|
286
|
+
|
|
287
|
+
``axis: "projected"`` is the fourth alert axis; ``metric`` discriminates
|
|
288
|
+
``weekly_pct`` (denominator 100.0, "% of cap") from ``budget_usd``
|
|
289
|
+
(denominator = target_usd, "$ of budget"). The frontend renders context
|
|
290
|
+
FROM these row-sourced fields (``metric`` / ``projected_value`` /
|
|
291
|
+
``denominator``), not from live config that may have changed since crossing
|
|
292
|
+
(Codex P0-4). No ``crossed_at``/``alerted_at`` keys here: the projected
|
|
293
|
+
detector stamps ``alerted_at`` on the DB row itself in the same txn before
|
|
294
|
+
dispatch (set-then-dispatch), and the dashboard envelope reads it from the
|
|
295
|
+
row — mirroring ``_build_alert_payload_budget``'s context-only shape minus
|
|
296
|
+
the redundant timestamp echo.
|
|
297
|
+
"""
|
|
298
|
+
return {
|
|
299
|
+
"id": f"projected:{week_start_at}:{metric}:{int(threshold)}",
|
|
300
|
+
"axis": "projected",
|
|
301
|
+
"metric": str(metric),
|
|
302
|
+
"threshold": int(threshold),
|
|
303
|
+
"projected_value": float(projected_value),
|
|
304
|
+
"denominator": float(denominator),
|
|
305
|
+
"context": {
|
|
306
|
+
"week_start_at": week_start_at,
|
|
307
|
+
"metric": str(metric),
|
|
308
|
+
"projected_value": float(projected_value),
|
|
309
|
+
"denominator": float(denominator),
|
|
310
|
+
},
|
|
311
|
+
}
|
package/bin/_lib_budget.py
CHANGED
|
@@ -52,6 +52,7 @@ class BudgetStatus:
|
|
|
52
52
|
elapsed_fraction: float # [0, 1]
|
|
53
53
|
projected_eow_low_usd: float
|
|
54
54
|
projected_eow_high_usd: float
|
|
55
|
+
week_avg_projection_usd: float # spent + rate_avg*remaining (smooth estimator)
|
|
55
56
|
verdict: str # "ok" | "warn" | "over"
|
|
56
57
|
daily_budget_remaining_usd: float # remaining / remaining-days
|
|
57
58
|
daily_pace_usd: float # current burn $/day (week-average)
|
|
@@ -93,6 +94,12 @@ def compute_budget_status(inputs: BudgetInputs) -> BudgetStatus:
|
|
|
93
94
|
spent, remaining_hours, rate_low, rate_high
|
|
94
95
|
)
|
|
95
96
|
|
|
97
|
+
# Smooth week-average end-of-week projection (additive surface field).
|
|
98
|
+
# Distinct from the displayed band (which keys off the high end): this is
|
|
99
|
+
# the conservative week-average value the projected-pace alert axis fires
|
|
100
|
+
# on. spent + rate_avg*remaining (== project_linear collapsed to one rate).
|
|
101
|
+
week_avg_projection_usd = spent + rate_avg * remaining_hours
|
|
102
|
+
|
|
96
103
|
daily_pace_usd = rate_avg * 24.0
|
|
97
104
|
daily_budget_remaining_usd = (
|
|
98
105
|
(remaining_usd / remaining_days) if remaining_days > 0 else remaining_usd
|
|
@@ -125,6 +132,7 @@ def compute_budget_status(inputs: BudgetInputs) -> BudgetStatus:
|
|
|
125
132
|
elapsed_fraction=elapsed_fraction,
|
|
126
133
|
projected_eow_low_usd=projected_low,
|
|
127
134
|
projected_eow_high_usd=projected_high,
|
|
135
|
+
week_avg_projection_usd=week_avg_projection_usd,
|
|
128
136
|
verdict=verdict,
|
|
129
137
|
daily_budget_remaining_usd=daily_budget_remaining_usd,
|
|
130
138
|
daily_pace_usd=daily_pace_usd,
|
package/bin/_lib_diff_kernel.py
CHANGED
|
@@ -115,6 +115,11 @@ _lib_display_tz = _load_lib("_lib_display_tz")
|
|
|
115
115
|
_resolve_tz = _lib_display_tz._resolve_tz
|
|
116
116
|
format_display_dt = _lib_display_tz.format_display_dt
|
|
117
117
|
|
|
118
|
+
# fmt/color/table primitives honest-imported from _lib_fmt (#126 C11)
|
|
119
|
+
_lib_fmt = _load_lib("_lib_fmt")
|
|
120
|
+
_style_ansi = _lib_fmt._style_ansi
|
|
121
|
+
_supports_unicode_stdout = _lib_fmt._supports_unicode_stdout
|
|
122
|
+
|
|
118
123
|
|
|
119
124
|
# === Honest imports from extracted homes ===================================
|
|
120
125
|
# Spec 2026-05-17-cctally-core-kernel-extraction.md §3.3: kernel symbols
|
|
@@ -147,14 +152,6 @@ def _iso_z(*args, **kwargs):
|
|
|
147
152
|
return sys.modules["cctally"]._iso_z(*args, **kwargs)
|
|
148
153
|
|
|
149
154
|
|
|
150
|
-
def _supports_unicode_stdout(*args, **kwargs):
|
|
151
|
-
return sys.modules["cctally"]._supports_unicode_stdout(*args, **kwargs)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
def _style_ansi(*args, **kwargs):
|
|
155
|
-
return sys.modules["cctally"]._style_ansi(*args, **kwargs)
|
|
156
|
-
|
|
157
|
-
|
|
158
155
|
# Private eprint shim per spec §5.3 (pure layer does not back-import
|
|
159
156
|
# cctally for ubiquitous helpers; eprint isn't actually called by the
|
|
160
157
|
# moved code, but kept here as the canonical pure-layer pattern so
|
package/bin/_lib_fmt.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Shared fmt / color / table render primitives (pure-fn kernel).
|
|
2
|
+
|
|
3
|
+
Holds the low-level formatting primitives extracted from bin/cctally
|
|
4
|
+
(#126, C11): timestamp/week-window compaction, color/unicode capability
|
|
5
|
+
detection, ANSI styling, display-width-aware boxed tables, number
|
|
6
|
+
formatting + width-budget truncation. Pure: the only environment reads
|
|
7
|
+
(os.environ, sys.stdout.isatty(), sys.stdout.encoding) happen INSIDE the
|
|
8
|
+
functions at call time, never at import.
|
|
9
|
+
|
|
10
|
+
Imported honestly by _lib_render.py and _lib_diff_kernel.py (via their
|
|
11
|
+
_load_lib helpers); re-exported on the bin/cctally namespace for the
|
|
12
|
+
_cctally_* command siblings and _lib_view_models.py (c.X accessor) and the
|
|
13
|
+
test monkeypatch surfaces.
|
|
14
|
+
|
|
15
|
+
Spec: docs/superpowers/specs/2026-06-01-extract-fmt-color-table-primitives-design.md
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import os
|
|
21
|
+
import pathlib
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
import unicodedata
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
# parse_iso_datetime: bare import matches the established _lib_* convention
|
|
28
|
+
# (_lib_aggregators.py:86, _lib_diff_kernel.py:123 do the same).
|
|
29
|
+
from _cctally_core import parse_iso_datetime
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# format_display_dt: loaded via the file-path _load_lib helper, NOT a bare
|
|
33
|
+
# `from _lib_display_tz import …`. The repo's sibling loading deliberately
|
|
34
|
+
# bypasses sys.path (test/loader contexts may lack bin/ on the path); every
|
|
35
|
+
# _lib_* consumer of _lib_display_tz uses _load_lib (_lib_render.py:100,
|
|
36
|
+
# _lib_diff_kernel.py:114, _lib_aggregators.py:75). _lib_fmt matches them.
|
|
37
|
+
def _load_lib(name: str):
|
|
38
|
+
cached = sys.modules.get(name)
|
|
39
|
+
if cached is not None:
|
|
40
|
+
return cached
|
|
41
|
+
import importlib.util as _ilu
|
|
42
|
+
p = pathlib.Path(__file__).resolve().parent / f"{name}.py"
|
|
43
|
+
spec = _ilu.spec_from_file_location(name, p)
|
|
44
|
+
mod = _ilu.module_from_spec(spec)
|
|
45
|
+
sys.modules[name] = mod
|
|
46
|
+
spec.loader.exec_module(mod)
|
|
47
|
+
return mod
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_lib_display_tz = _load_lib("_lib_display_tz")
|
|
51
|
+
format_display_dt = _lib_display_tz.format_display_dt
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _parse_iso_datetime_optional(value: Any) -> dt.datetime | None:
|
|
55
|
+
if not isinstance(value, str) or not value.strip():
|
|
56
|
+
return None
|
|
57
|
+
try:
|
|
58
|
+
return parse_iso_datetime(value, "timestamp")
|
|
59
|
+
except ValueError:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _format_ts_compact(
|
|
64
|
+
value: str | None,
|
|
65
|
+
tz: "ZoneInfo | None" = None,
|
|
66
|
+
) -> str:
|
|
67
|
+
"""Compact ISO-instant -> "YYYY-MM-DD HH:MM" line.
|
|
68
|
+
|
|
69
|
+
F5 fix: optional ``tz`` localizes the parsed instant before strftime
|
|
70
|
+
AND appends the offset suffix via ``display_tz_label`` so the column
|
|
71
|
+
becomes unambiguous (mirrors ``format_display_dt``'s pattern). When
|
|
72
|
+
``tz`` is None, returns the legacy UTC-clock string with no suffix
|
|
73
|
+
so existing callers keep their byte-stable output.
|
|
74
|
+
"""
|
|
75
|
+
parsed = _parse_iso_datetime_optional(value)
|
|
76
|
+
if parsed is None:
|
|
77
|
+
return "n/a"
|
|
78
|
+
if tz is None:
|
|
79
|
+
# Host-local fallback / default-config path: preserve the original
|
|
80
|
+
# byte-stable host-naive strftime output (UTC-aware datetimes render
|
|
81
|
+
# UTC clock, no suffix). This branch is reachable in production for
|
|
82
|
+
# users whose ``display.tz`` resolves to None — NOT a legacy or
|
|
83
|
+
# back-compat path. The non-None branch routes through
|
|
84
|
+
# ``format_display_dt`` for tz-aware rendering.
|
|
85
|
+
return parsed.strftime("%Y-%m-%d %H:%M")
|
|
86
|
+
return format_display_dt(parsed, tz, fmt="%Y-%m-%d %H:%M", suffix=True)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _format_week_window(
|
|
90
|
+
week_start_date: str | None,
|
|
91
|
+
week_end_date: str | None,
|
|
92
|
+
week_start_at: str | None,
|
|
93
|
+
week_end_at: str | None,
|
|
94
|
+
tz: "ZoneInfo | None" = None,
|
|
95
|
+
) -> str:
|
|
96
|
+
"""Render a "<start> -> <end>" week-window column. F5 adds tz-aware
|
|
97
|
+
rendering for ISO-timestamp-bearing rows; legacy date-only rows pass
|
|
98
|
+
through unchanged. ``tz=None`` preserves byte-stable callers."""
|
|
99
|
+
if week_start_at and week_end_at:
|
|
100
|
+
return (
|
|
101
|
+
f"{_format_ts_compact(week_start_at, tz=tz)} -> "
|
|
102
|
+
f"{_format_ts_compact(week_end_at, tz=tz)}"
|
|
103
|
+
)
|
|
104
|
+
return f"{week_start_date or 'n/a'} -> {week_end_date or 'n/a'}"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _supports_color_stdout() -> bool:
|
|
108
|
+
# Matches ccusage's picocolors behavior exactly.
|
|
109
|
+
# FORCE_COLOR always enables (any value, including empty)
|
|
110
|
+
if "FORCE_COLOR" in os.environ:
|
|
111
|
+
return True
|
|
112
|
+
# NO_COLOR always disables (any value, including empty)
|
|
113
|
+
if "NO_COLOR" in os.environ:
|
|
114
|
+
return False
|
|
115
|
+
# CI environments get color
|
|
116
|
+
if "CI" in os.environ:
|
|
117
|
+
return True
|
|
118
|
+
# TTY check on stdout or stderr
|
|
119
|
+
if sys.stdout.isatty() or sys.stderr.isatty():
|
|
120
|
+
term = os.environ.get("TERM", "")
|
|
121
|
+
return term.lower() != "dumb"
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _style_ansi(text: str, code: str, enabled: bool) -> str:
|
|
126
|
+
if not enabled:
|
|
127
|
+
return text
|
|
128
|
+
return f"\033[{code}m{text}\033[0m"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _supports_unicode_stdout() -> bool:
|
|
132
|
+
encoding = (sys.stdout.encoding or "").upper()
|
|
133
|
+
return "UTF" in encoding
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _display_width(s: str) -> int:
|
|
137
|
+
"""Terminal cells consumed by ``s``.
|
|
138
|
+
|
|
139
|
+
Counts each codepoint by its East Asian Width: ``W`` / ``F`` (Wide
|
|
140
|
+
/ Fullwidth) → 2 cells; combining marks → 0; everything else → 1.
|
|
141
|
+
Ambiguous (``A``) defaults to 1, matching every non-CJK terminal
|
|
142
|
+
locale — cctally has no CJK content in cell data, and `→` / `—` /
|
|
143
|
+
`·` (all `A`) are intentionally rendered narrow.
|
|
144
|
+
|
|
145
|
+
Used by `_boxed_table` so cells containing wide glyphs (notably
|
|
146
|
+
`⚡` U+26A1 on credit-row annotations) pad to the right cell count
|
|
147
|
+
rather than the right codepoint count. Without this, `len()`-based
|
|
148
|
+
padding under-pads by one cell per wide glyph and the right border
|
|
149
|
+
drifts off-column on those rows only.
|
|
150
|
+
"""
|
|
151
|
+
width = 0
|
|
152
|
+
for ch in s:
|
|
153
|
+
if unicodedata.combining(ch):
|
|
154
|
+
continue
|
|
155
|
+
width += 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
|
|
156
|
+
return width
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _boxed_table(
|
|
160
|
+
headers: list[str],
|
|
161
|
+
rows: list[list[str]],
|
|
162
|
+
aligns: list[str] | None = None,
|
|
163
|
+
*,
|
|
164
|
+
color_header: bool = True,
|
|
165
|
+
compact: bool = False,
|
|
166
|
+
) -> str:
|
|
167
|
+
if not headers:
|
|
168
|
+
return ""
|
|
169
|
+
col_count = len(headers)
|
|
170
|
+
aligns = aligns or ["left"] * col_count
|
|
171
|
+
if len(aligns) != col_count:
|
|
172
|
+
raise ValueError("aligns length must match headers length")
|
|
173
|
+
|
|
174
|
+
sanitized_rows: list[list[str]] = []
|
|
175
|
+
for row in rows:
|
|
176
|
+
normalized = [str(cell).replace("\n", " ") for cell in row]
|
|
177
|
+
if len(normalized) != col_count:
|
|
178
|
+
raise ValueError("row length must match headers length")
|
|
179
|
+
sanitized_rows.append(normalized)
|
|
180
|
+
|
|
181
|
+
widths: list[int] = []
|
|
182
|
+
for idx, header in enumerate(headers):
|
|
183
|
+
max_cell = max((_display_width(r[idx]) for r in sanitized_rows), default=0)
|
|
184
|
+
widths.append(max(_display_width(header), max_cell))
|
|
185
|
+
|
|
186
|
+
def _pad(text: str, width: int, align: str) -> str:
|
|
187
|
+
deficit = width - _display_width(text)
|
|
188
|
+
if deficit <= 0:
|
|
189
|
+
return text
|
|
190
|
+
pad = " " * deficit
|
|
191
|
+
if align == "right":
|
|
192
|
+
return pad + text
|
|
193
|
+
if align == "center":
|
|
194
|
+
left = deficit // 2
|
|
195
|
+
return (" " * left) + text + (" " * (deficit - left))
|
|
196
|
+
return text + pad
|
|
197
|
+
|
|
198
|
+
if _supports_unicode_stdout():
|
|
199
|
+
chars = {
|
|
200
|
+
"top_left": "┌",
|
|
201
|
+
"top_mid": "┬",
|
|
202
|
+
"top_right": "┐",
|
|
203
|
+
"mid_left": "├",
|
|
204
|
+
"mid_mid": "┼",
|
|
205
|
+
"mid_right": "┤",
|
|
206
|
+
"bottom_left": "└",
|
|
207
|
+
"bottom_mid": "┴",
|
|
208
|
+
"bottom_right": "┘",
|
|
209
|
+
"h": "─",
|
|
210
|
+
"v": "│",
|
|
211
|
+
}
|
|
212
|
+
else:
|
|
213
|
+
chars = {
|
|
214
|
+
"top_left": "+",
|
|
215
|
+
"top_mid": "+",
|
|
216
|
+
"top_right": "+",
|
|
217
|
+
"mid_left": "+",
|
|
218
|
+
"mid_mid": "+",
|
|
219
|
+
"mid_right": "+",
|
|
220
|
+
"bottom_left": "+",
|
|
221
|
+
"bottom_mid": "+",
|
|
222
|
+
"bottom_right": "+",
|
|
223
|
+
"h": "-",
|
|
224
|
+
"v": "|",
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
color_enabled = _supports_color_stdout()
|
|
228
|
+
|
|
229
|
+
def _dim(s: str) -> str:
|
|
230
|
+
return _style_ansi(s, "90", color_enabled)
|
|
231
|
+
|
|
232
|
+
# Issue #91 (Shape B): ``compact`` drops the 1-space cell padding to
|
|
233
|
+
# 0 on this content-sized table (which has no proportional-width path
|
|
234
|
+
# to force). Borders and rows both key off ``pad`` so the default
|
|
235
|
+
# (``pad == 1``) reproduces the prior output byte-for-byte.
|
|
236
|
+
pad = 0 if compact else 1
|
|
237
|
+
pad_s = " " * pad
|
|
238
|
+
|
|
239
|
+
def make_border(left: str, mid: str, right: str) -> str:
|
|
240
|
+
return _dim(
|
|
241
|
+
left
|
|
242
|
+
+ mid.join(chars["h"] * (w + 2 * pad) for w in widths)
|
|
243
|
+
+ right
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
def make_row(cells: list[str], *, header: bool = False) -> str:
|
|
247
|
+
is_total = not header and cells and cells[0].strip() == "Total"
|
|
248
|
+
styled_cells: list[str] = []
|
|
249
|
+
for i, raw in enumerate(cells):
|
|
250
|
+
text = _pad(raw, widths[i], aligns[i])
|
|
251
|
+
if header and color_header:
|
|
252
|
+
text = _style_ansi(text, "36", color_enabled) # cyan text, like ccusage table head
|
|
253
|
+
elif is_total:
|
|
254
|
+
text = _style_ansi(text, "32", color_enabled) # green text for totals
|
|
255
|
+
styled_cells.append(text)
|
|
256
|
+
v = _dim(chars["v"])
|
|
257
|
+
return (
|
|
258
|
+
v
|
|
259
|
+
+ pad_s
|
|
260
|
+
+ f"{pad_s}{v}{pad_s}".join(styled_cells)
|
|
261
|
+
+ pad_s
|
|
262
|
+
+ v
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
top = make_border(chars["top_left"], chars["top_mid"], chars["top_right"])
|
|
266
|
+
mid = make_border(chars["mid_left"], chars["mid_mid"], chars["mid_right"])
|
|
267
|
+
bottom = make_border(chars["bottom_left"], chars["bottom_mid"], chars["bottom_right"])
|
|
268
|
+
|
|
269
|
+
out_lines = [top, make_row(headers, header=True), mid]
|
|
270
|
+
for idx, row in enumerate(sanitized_rows):
|
|
271
|
+
out_lines.append(make_row(row, header=False))
|
|
272
|
+
if idx < len(sanitized_rows) - 1:
|
|
273
|
+
out_lines.append(mid)
|
|
274
|
+
out_lines.append(bottom)
|
|
275
|
+
return "\n".join(out_lines)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _fmt_num(n: int) -> str:
|
|
279
|
+
"""Format integer with comma separators: 1234567 -> '1,234,567'."""
|
|
280
|
+
return f"{n:,}"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _truncate_num(formatted: str, width: int) -> str:
|
|
284
|
+
"""Truncate a formatted number to fit width, replacing tail with '…'."""
|
|
285
|
+
if len(formatted) <= width:
|
|
286
|
+
return formatted
|
|
287
|
+
return formatted[: width - 1] + "\u2026"
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
_ANSI_ESC_RE = re.compile(r"\033\[[0-9;]*m")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _truncate_display(text: str, width: int) -> str:
|
|
294
|
+
"""Truncate to `width` visible chars, preserving ANSI escape sequences.
|
|
295
|
+
|
|
296
|
+
Unlike `_truncate_num`, which slices raw string indices, this walks
|
|
297
|
+
the text treating `\\033[...m` sequences as zero-width and counts
|
|
298
|
+
printable chars toward the width budget. Used for left-aligned
|
|
299
|
+
cells that may carry a styled anomaly-glyph prefix — slicing those
|
|
300
|
+
with `_truncate_num` can cut through an ANSI escape and bleed
|
|
301
|
+
color into adjacent cells.
|
|
302
|
+
"""
|
|
303
|
+
# Fast path: no ANSI codes, fall back to raw-slice truncation.
|
|
304
|
+
if "\033" not in text:
|
|
305
|
+
return _truncate_num(text, width)
|
|
306
|
+
stripped_len = len(_ANSI_ESC_RE.sub("", text))
|
|
307
|
+
if stripped_len <= width:
|
|
308
|
+
return text
|
|
309
|
+
# Walk chars until we've emitted (width - 1) visible chars, copying
|
|
310
|
+
# ANSI sequences verbatim. Append reset + ellipsis to close any open
|
|
311
|
+
# style and preserve the fit-to-width contract.
|
|
312
|
+
out: list[str] = []
|
|
313
|
+
visible = 0
|
|
314
|
+
i = 0
|
|
315
|
+
target = width - 1
|
|
316
|
+
while i < len(text) and visible < target:
|
|
317
|
+
m = _ANSI_ESC_RE.match(text, i)
|
|
318
|
+
if m:
|
|
319
|
+
out.append(m.group(0))
|
|
320
|
+
i = m.end()
|
|
321
|
+
continue
|
|
322
|
+
out.append(text[i])
|
|
323
|
+
visible += 1
|
|
324
|
+
i += 1
|
|
325
|
+
return "".join(out) + "\033[0m\u2026"
|
package/bin/_lib_render.py
CHANGED
|
@@ -100,36 +100,21 @@ _short_model_name = _lib_pricing._short_model_name
|
|
|
100
100
|
_lib_display_tz = _load_lib("_lib_display_tz")
|
|
101
101
|
_resolve_tz = _lib_display_tz._resolve_tz
|
|
102
102
|
|
|
103
|
+
# fmt/color/table primitives honest-imported from _lib_fmt (#126 C11)
|
|
104
|
+
_lib_fmt = _load_lib("_lib_fmt")
|
|
105
|
+
_supports_color_stdout = _lib_fmt._supports_color_stdout
|
|
106
|
+
_supports_unicode_stdout = _lib_fmt._supports_unicode_stdout
|
|
107
|
+
_style_ansi = _lib_fmt._style_ansi
|
|
108
|
+
_fmt_num = _lib_fmt._fmt_num
|
|
109
|
+
_truncate_num = _lib_fmt._truncate_num
|
|
110
|
+
_boxed_table = _lib_fmt._boxed_table
|
|
111
|
+
|
|
103
112
|
|
|
104
113
|
# Module-level back-ref shims. Each shim resolves
|
|
105
114
|
# ``sys.modules['cctally'].X`` at CALL TIME (not bind time), so
|
|
106
115
|
# monkeypatches on cctally's namespace propagate into the moved code
|
|
107
116
|
# unchanged. Mirrors the precedent established in
|
|
108
117
|
# ``bin/_cctally_record.py`` / ``bin/_cctally_cache.py``.
|
|
109
|
-
def _supports_color_stdout(*args, **kwargs):
|
|
110
|
-
return sys.modules["cctally"]._supports_color_stdout(*args, **kwargs)
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
def _supports_unicode_stdout(*args, **kwargs):
|
|
114
|
-
return sys.modules["cctally"]._supports_unicode_stdout(*args, **kwargs)
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
def _style_ansi(*args, **kwargs):
|
|
118
|
-
return sys.modules["cctally"]._style_ansi(*args, **kwargs)
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def _fmt_num(*args, **kwargs):
|
|
122
|
-
return sys.modules["cctally"]._fmt_num(*args, **kwargs)
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def _truncate_num(*args, **kwargs):
|
|
126
|
-
return sys.modules["cctally"]._truncate_num(*args, **kwargs)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
def _boxed_table(*args, **kwargs):
|
|
130
|
-
return sys.modules["cctally"]._boxed_table(*args, **kwargs)
|
|
131
|
-
|
|
132
|
-
|
|
133
118
|
def _format_block_start(*args, **kwargs):
|
|
134
119
|
return sys.modules["cctally"]._format_block_start(*args, **kwargs)
|
|
135
120
|
|