1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Pacing math — encodes claudebar's `calc_pacing` (claudebar:279-321) and
//! `pace_color_for` (claudebar:212-219) as pure functions.
//!
//! Two parallel notions of "pacing":
//! - **Ratio** — `actual_pct / elapsed_pct`, with a tolerance band (`PACE_TOLERANCE`).
//! Used for the `{*_pace}` and `{*_pace_pct}` placeholders. Capped at 999%.
//! - **Point delta** — `actual_pct - elapsed_pct`, a signed integer.
//! Used for `{*_pace_indicator}`, `{*_pace_pts}`, `{*_pace_delta}`. No tolerance.
//!
//! Both are computed in one shot and returned as a `Pacing` struct so the
//! caller can pick whichever placeholder it needs without re-running the math.
use chrono::{DateTime, Utc};
/// Default tolerance band (in percentage points) for the ratio-based pacing
/// icon. Mirrors claudebar's default `PACE_TOLERANCE=5`.
pub const DEFAULT_TOLERANCE: u32 = 5;
/// A small enum captures the three visual pace states. Keeping the icon out
/// of strings lets the TUI render `Style`-colored chars and the widget render
/// raw glyphs without any string parsing on the other end.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pace {
Ahead,
OnTrack,
Under,
}
impl Pace {
/// Single-char glyph used in claudebar's `{*_pace*}` placeholders.
pub fn glyph(self) -> &'static str {
match self {
Pace::Ahead => "↑",
Pace::OnTrack => "→",
Pace::Under => "↓",
}
}
}
/// Result of `calc_pacing` — all fields the caller might want to render.
///
/// Field naming mirrors the placeholders so the format-substitution layer is
/// a trivial mapping.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pacing {
/// `{*_elapsed}` — integer percent of the window that has elapsed (0..=100).
pub elapsed_pct: i32,
/// `{*_pace}` — ratio-based icon, honors `tolerance`.
pub ratio_pace: Pace,
/// `{*_pace_indicator}` — point-based icon, no tolerance.
pub point_pace: Pace,
/// `{*_pace_delta}` — signed integer `usage_pct - elapsed_pct`.
pub delta: i32,
/// `{*_pace_pct}` — ratio-based label ("12% ahead" / "5% under" / "on track").
pub ratio_label: String,
/// `{*_pace_pts}` — point-based label ("12pts ahead" / "5pts under" / "on track").
pub point_label: String,
}
impl Pacing {
/// Neutral pacing for windows with no `resets_at` (e.g. vendors that don't
/// expose one). Matches claudebar's early-return value.
pub fn neutral() -> Self {
Self {
elapsed_pct: 0,
ratio_pace: Pace::OnTrack,
point_pace: Pace::OnTrack,
delta: 0,
ratio_label: "on track".into(),
point_label: "on track".into(),
}
}
}
/// Compute pacing for a usage window.
///
/// `usage_pct` is the vendor-reported utilization (0..=100, integer to match
/// Claude's `utilization` field). `reset` is when the window rolls over;
/// `now` is the reference time (passed in for testability). `window` is the
/// window's total duration. `tolerance` is the ratio-tolerance band in
/// percentage points (e.g. `5` for ±5%).
pub fn calc(
usage_pct: i32,
reset: Option<DateTime<Utc>>,
now: DateTime<Utc>,
window: chrono::Duration,
tolerance: u32,
) -> Pacing {
let Some(reset) = reset else {
return Pacing::neutral();
};
if window.num_seconds() <= 0 {
return Pacing::neutral();
}
let remaining = reset.signed_duration_since(now).num_seconds();
let total = window.num_seconds();
let mut elapsed_pct = (((total - remaining) * 100) / total) as i32;
elapsed_pct = elapsed_pct.clamp(0, 100);
// Point-based delta and label.
let delta = usage_pct - elapsed_pct;
let (point_pace, point_label) = if delta > 0 {
(Pace::Ahead, format!("{delta}pts ahead"))
} else if delta < 0 {
(Pace::Under, format!("{}pts under", -delta))
} else {
(Pace::OnTrack, "on track".to_string())
};
// Ratio-based icon and label (only meaningful once any time has elapsed).
let (ratio_pace, ratio_label) = if elapsed_pct > 0 {
let pacing_x100 = (usage_pct * 100) / elapsed_pct;
let tol = tolerance as i32;
if pacing_x100 > 100 + tol {
let dev = (pacing_x100 - 100).min(999);
(Pace::Ahead, format!("{dev}% ahead"))
} else if pacing_x100 < 100 - tol {
let dev = (100 - pacing_x100).min(999);
(Pace::Under, format!("{dev}% under"))
} else {
(Pace::OnTrack, "on track".to_string())
}
} else {
(Pace::OnTrack, "on track".to_string())
};
Pacing {
elapsed_pct,
ratio_pace,
point_pace,
delta,
ratio_label,
point_label,
}
}
/// Color band keyed on signed point delta. Mirrors claudebar's
/// `pace_color_for` (claudebar:212-219). Returns one of the four severity
/// tiers; the caller maps to a theme color.
///
/// `delta <= -10` → low (green); `-10..=0` → mid (yellow);
/// `1..=9` → high (orange); `>= 10` → critical (red).
/// The variants are declared least to most severe, and the derived `Ord`
/// follows that order — so `a.max(b)` is "whichever of the two is worse", which
/// is how a row with two independent severity sources (a money tier and a
/// percentage tier) picks the one to paint with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PaceSeverity {
Low,
Mid,
High,
Critical,
}
impl PaceSeverity {
/// Stable lowercase token used by JSON/CSS-facing presentation layers.
pub const fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
Self::Mid => "mid",
Self::High => "high",
Self::Critical => "critical",
}
}
}
pub fn pace_severity(delta: i32) -> PaceSeverity {
if delta >= 10 {
PaceSeverity::Critical
} else if delta > 0 {
PaceSeverity::High
} else if delta >= -10 {
PaceSeverity::Mid
} else {
PaceSeverity::Low
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn at(h: u32, m: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 5, 23, h, m, 0).unwrap()
}
const FIVE_H: chrono::Duration = chrono::Duration::hours(5);
#[test]
fn missing_reset_returns_neutral() {
let p = calc(50, None, at(12, 0), FIVE_H, DEFAULT_TOLERANCE);
assert_eq!(p, Pacing::neutral());
}
#[test]
fn zero_window_returns_neutral() {
let p = calc(50, Some(at(12, 0)), at(12, 0), chrono::Duration::zero(), 5);
assert_eq!(p, Pacing::neutral());
}
#[test]
fn elapsed_clamps_to_zero_when_future_reset_beyond_window() {
// Reset is 6h away but window is 5h → "remaining > total" → negative
// elapsed → clamped to 0.
let now = at(12, 0);
let reset = now + chrono::Duration::hours(6);
let p = calc(10, Some(reset), now, FIVE_H, 5);
assert_eq!(p.elapsed_pct, 0);
}
#[test]
fn elapsed_clamps_to_hundred_when_past_reset() {
let now = at(12, 0);
let reset = now - chrono::Duration::hours(1);
let p = calc(50, Some(reset), now, FIVE_H, 5);
assert_eq!(p.elapsed_pct, 100);
}
#[test]
fn perfectly_even_pacing_is_on_track() {
// 50% elapsed, 50% usage → both metrics on track.
let now = at(12, 0);
let reset = now + chrono::Duration::minutes(150); // 2.5h remain of 5h
let p = calc(50, Some(reset), now, FIVE_H, DEFAULT_TOLERANCE);
assert_eq!(p.elapsed_pct, 50);
assert_eq!(p.delta, 0);
assert_eq!(p.ratio_pace, Pace::OnTrack);
assert_eq!(p.point_pace, Pace::OnTrack);
assert_eq!(p.ratio_label, "on track");
assert_eq!(p.point_label, "on track");
}
#[test]
fn ahead_of_pace_above_tolerance() {
// 50% elapsed, 70% usage → delta 20, ratio 140% → "40% ahead".
let now = at(12, 0);
let reset = now + chrono::Duration::minutes(150);
let p = calc(70, Some(reset), now, FIVE_H, 5);
assert_eq!(p.delta, 20);
assert_eq!(p.point_pace, Pace::Ahead);
assert_eq!(p.point_label, "20pts ahead");
assert_eq!(p.ratio_pace, Pace::Ahead);
assert_eq!(p.ratio_label, "40% ahead");
}
#[test]
fn under_pace_below_tolerance() {
// 50% elapsed, 30% usage → delta -20, ratio 60% → "40% under".
let now = at(12, 0);
let reset = now + chrono::Duration::minutes(150);
let p = calc(30, Some(reset), now, FIVE_H, 5);
assert_eq!(p.delta, -20);
assert_eq!(p.point_pace, Pace::Under);
assert_eq!(p.point_label, "20pts under");
assert_eq!(p.ratio_pace, Pace::Under);
assert_eq!(p.ratio_label, "40% under");
}
#[test]
fn within_tolerance_band_is_on_track_ratio_but_point_diverges() {
// 50% elapsed, 52% usage → ratio 104% (within ±5) → on track,
// BUT point delta is 2 → point_pace = Ahead, point_label "2pts ahead".
let now = at(12, 0);
let reset = now + chrono::Duration::minutes(150);
let p = calc(52, Some(reset), now, FIVE_H, DEFAULT_TOLERANCE);
assert_eq!(p.ratio_pace, Pace::OnTrack);
assert_eq!(p.ratio_label, "on track");
assert_eq!(p.point_pace, Pace::Ahead);
assert_eq!(p.point_label, "2pts ahead");
}
#[test]
fn ratio_clamps_at_999() {
// 1% elapsed, 60% usage → pacing_x100 = 6000, dev = 5900 → clamped to 999.
let now = at(12, 0);
let reset = now + chrono::Duration::minutes(297); // ~99% remaining → 1% elapsed
let p = calc(60, Some(reset), now, FIVE_H, 5);
assert_eq!(p.elapsed_pct, 1);
assert_eq!(p.ratio_label, "999% ahead");
}
#[test]
fn elapsed_zero_skips_ratio() {
// 0% elapsed → ratio code is skipped; ratio defaults to on track.
let now = at(12, 0);
let reset = now + FIVE_H; // full window remains
let p = calc(20, Some(reset), now, FIVE_H, 5);
assert_eq!(p.elapsed_pct, 0);
assert_eq!(p.ratio_pace, Pace::OnTrack);
// But point math still runs: delta = 20.
assert_eq!(p.delta, 20);
assert_eq!(p.point_pace, Pace::Ahead);
}
#[test]
fn severity_boundaries_match_claudebar() {
// claudebar: <= -10 green, -10..=0 yellow, 1..9 orange, >= 10 red
assert_eq!(pace_severity(-100), PaceSeverity::Low);
assert_eq!(pace_severity(-10), PaceSeverity::Mid); // -10 is in -10..=0 band
assert_eq!(pace_severity(-1), PaceSeverity::Mid);
assert_eq!(pace_severity(0), PaceSeverity::Mid);
assert_eq!(pace_severity(1), PaceSeverity::High);
assert_eq!(pace_severity(9), PaceSeverity::High);
assert_eq!(pace_severity(10), PaceSeverity::Critical);
assert_eq!(pace_severity(100), PaceSeverity::Critical);
}
#[test]
fn severity_tokens_are_stable_for_external_presenters() {
assert_eq!(PaceSeverity::Low.as_str(), "low");
assert_eq!(PaceSeverity::Mid.as_str(), "mid");
assert_eq!(PaceSeverity::High.as_str(), "high");
assert_eq!(PaceSeverity::Critical.as_str(), "critical");
}
#[test]
fn neutral_constructor_matches_default_state() {
let n = Pacing::neutral();
assert_eq!(n.elapsed_pct, 0);
assert_eq!(n.delta, 0);
assert_eq!(n.ratio_pace, Pace::OnTrack);
assert_eq!(n.point_pace, Pace::OnTrack);
assert_eq!(n.ratio_label, "on track");
assert_eq!(n.point_label, "on track");
}
}