ukaf-cli 0.1.0__py3-none-any.whl

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.
ukaf/render_html.py ADDED
@@ -0,0 +1,584 @@
1
+ """One self-contained HTML file. Charts are inline SVG, so the page works offline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from decimal import Decimal
7
+ from statistics import median
8
+
9
+ from ukaf import SPONSOR_LINE, SPONSOR_URL
10
+ from ukaf.dora import Dora
11
+ from ukaf.i18n import stage_label, t
12
+ from ukaf.money import MICRO, money, mul_div_half_even
13
+ from ukaf.recommend import Recommendation
14
+ from ukaf.reconcile import Check
15
+ from ukaf.serialize import _feature_prose, _opening, _rubric, _tiers
16
+ from ukaf.story import STAGE_NAMES, Feature, Story
17
+ from ukaf.timeutil import fmt_duration
18
+
19
+ # Stage colors stay consistent across charts and tables.
20
+ COLORS = {
21
+ "planning": "#7C9CFF",
22
+ "development": "#4FD1C5",
23
+ "testing": "#F6C453",
24
+ "deploy": "#A78BFA",
25
+ "fixes": "#F87171",
26
+ "overhead": "#8A94B8",
27
+ }
28
+
29
+
30
+ def render_html(
31
+ story: Story,
32
+ dora: Dora,
33
+ checks: list[Check],
34
+ recommendations: list[Recommendation],
35
+ *,
36
+ lang: str,
37
+ ) -> str:
38
+ hebrew = lang == "he"
39
+ ok = all(item.ok for item in checks)
40
+ status = t(lang, "pass") if ok else t(lang, "fail")
41
+ status_class = "pass" if ok else "fail"
42
+ parts = [
43
+ "<!DOCTYPE html>",
44
+ f'<html lang="{t(lang, "lang")}" dir="{t(lang, "dir")}">',
45
+ "<head>",
46
+ '<meta charset="utf-8">',
47
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
48
+ f"<title>{html.escape(t(lang, 'title'))}</title>",
49
+ f"<style>{_CSS}</style>",
50
+ "</head>",
51
+ "<body>",
52
+ '<header class="top">',
53
+ f'<p class="kicker">{html.escape(t(lang, "kicker"))}</p>',
54
+ f"<h1>{t(lang, 'hero_first')} <em>{t(lang, 'hero_last')}</em></h1>",
55
+ _headlines(story, lang),
56
+ f'<p class="lede">{html.escape(_opening(story, lang))}</p>',
57
+ f'<p class="sponsor"><a href="{SPONSOR_URL}">{html.escape(t(lang, "sponsor"))}</a></p>',
58
+ "</header>",
59
+ "<main>",
60
+ f'<section class="banner {status_class}">',
61
+ f"<strong>{html.escape(t(lang, 'reconciliation'))}: {html.escape(status)}</strong>",
62
+ f"<span>{len(checks)} {t(lang, 'checks')}. "
63
+ + (
64
+ "Every stage adds up to its feature, and every feature plus overhead adds up to the export."
65
+ if not hebrew
66
+ else "כל שלב מסתכם לפיצ'ר שלו, וכל הפיצ'רים ועוד התקורה מסתכמים לייצוא."
67
+ )
68
+ + "</span>",
69
+ "</section>",
70
+ _card("waterfall", t(lang, "stage_story"), _waterfall(story, lang)),
71
+ _card("tiers", t(lang, "tier_story"), _tier_breakdown(story, lang)),
72
+ _card("daily", t(lang, "priciest_day"), _daily(story, lang)),
73
+ _card("recommendations", t(lang, "recommendations"), _recs(recommendations, lang, hebrew)),
74
+ _card("delivery", t(lang, "dora"), _dora_block(dora, lang, hebrew)),
75
+ ]
76
+ details = [
77
+ _details(t(lang, "models"), _model_table(story, lang)),
78
+ _details(
79
+ t(lang, "reconciliation"),
80
+ "<ul class='checks'>"
81
+ + "".join(
82
+ f"<li class='{('ok' if item.ok else 'bad')}'><code>{'OK' if item.ok else 'FAIL'}</code> "
83
+ f"{html.escape(item.name)} — {html.escape(item.detail)}</li>"
84
+ for item in checks
85
+ )
86
+ + "</ul>",
87
+ ),
88
+ _details(
89
+ t(lang, "assumptions"),
90
+ "<ul>" + "".join(f"<li>{html.escape(item)}</li>" for item in story.assumptions) + "</ul>",
91
+ ),
92
+ ]
93
+ if story.features:
94
+ details.append(
95
+ _details(
96
+ t(lang, "features_heading"),
97
+ "".join(_feature_section(feature, lang, hebrew) for feature in story.features),
98
+ )
99
+ )
100
+ parts.append(_card("details", t(lang, "report_details"), "".join(details)))
101
+ parts.append("</main>")
102
+ parts.append(f"<footer>{html.escape(SPONSOR_LINE)}</footer>")
103
+ parts.append("</body></html>")
104
+ return "\n".join(parts) + "\n"
105
+
106
+
107
+ def _feature_section(feature: Feature, lang: str, hebrew: bool) -> str:
108
+ rows = []
109
+ for stage in feature.stages:
110
+ rows.append(
111
+ "<tr>"
112
+ f"<td><span class='swatch' style='background:{COLORS[stage.name]}'></span>"
113
+ f"{html.escape(stage_label(lang, stage.name))}</td>"
114
+ f"<td>{html.escape(fmt_duration(stage.duration_us, hebrew=hebrew))}</td>"
115
+ f"<td>{stage.events}</td>"
116
+ f"<td>{money(stage.list_micro)}</td>"
117
+ f"<td>{money(stage.billed_micro)}</td>"
118
+ "</tr>"
119
+ )
120
+ rows.append(
121
+ "<tr class='sum'>"
122
+ f"<td>{html.escape(t(lang, 'total'))}</td>"
123
+ f"<td>{html.escape(fmt_duration(feature.duration_us, hebrew=hebrew))}</td>"
124
+ f"<td>{feature.events}</td>"
125
+ f"<td>{money(feature.list_micro)}</td>"
126
+ f"<td>{money(feature.billed_micro)}</td>"
127
+ "</tr>"
128
+ )
129
+ failed = ""
130
+ if feature.failed:
131
+ failed = " · failed change" if lang != "he" else " · שינוי שנכשל"
132
+ return (
133
+ "<article class='feature'>"
134
+ f"<h3><a href='{html.escape(feature.url)}'>{html.escape(feature.repo)}#{feature.number}</a> "
135
+ f"{html.escape(feature.title)}</h3>"
136
+ f"<p class='meta'>tier {html.escape(feature.tier)} · {feature.sloc} SLOC · "
137
+ f"{html.escape(feature.author)}{failed}</p>"
138
+ f"<p>{html.escape(_feature_prose(feature, lang))}</p>"
139
+ f"{_stacked(feature)}"
140
+ "<table><thead><tr>"
141
+ f"<th>{html.escape(t(lang, 'stage'))}</th>"
142
+ f"<th>{html.escape(t(lang, 'duration'))}</th>"
143
+ f"<th>{html.escape(t(lang, 'events'))}</th>"
144
+ f"<th>{html.escape(t(lang, 'list'))}</th>"
145
+ f"<th>{html.escape(t(lang, 'billed'))}</th>"
146
+ "</tr></thead><tbody>" + "".join(rows) + "</tbody></table>"
147
+ f"<p class='identity'>Lead time = testing + deploy = "
148
+ f"{html.escape(fmt_duration(feature.lead_time_us, hebrew=hebrew))}.</p>"
149
+ "</article>"
150
+ )
151
+
152
+
153
+ def _stacked(feature: Feature) -> str:
154
+ total = feature.duration_us or 1
155
+ x = 0.0
156
+ rects = []
157
+ for stage in feature.stages:
158
+ width = 100.0 * stage.duration_us / total
159
+ rects.append(
160
+ f"<rect x='{x:.4f}' y='0' width='{width:.4f}' height='18' "
161
+ f"fill='{COLORS[stage.name]}'><title>{html.escape(stage.name)}</title></rect>"
162
+ )
163
+ x += width
164
+ return f"<svg class='bar' viewBox='0 0 100 18' role='img' aria-hidden='true'>{''.join(rects)}</svg>"
165
+
166
+
167
+ def _model_table(story: Story, lang: str) -> str:
168
+ body = []
169
+ for row in story.models:
170
+ body.append(
171
+ "<tr>"
172
+ f"<td>{html.escape(row.model)}</td>"
173
+ f"<td>{html.escape(row.priced_as)}</td>"
174
+ f"<td>{row.events}</td>"
175
+ f"<td>{money(row.list_micro)}</td>"
176
+ f"<td>{money(row.billed_micro)}</td>"
177
+ "</tr>"
178
+ )
179
+ body.append(
180
+ "<tr class='sum'>"
181
+ f"<td colspan='2'>{html.escape(t(lang, 'total'))}</td>"
182
+ f"<td>{story.events}</td>"
183
+ f"<td>{money(story.list_micro)}</td>"
184
+ f"<td>{money(story.billed_micro)}</td>"
185
+ "</tr>"
186
+ )
187
+ return (
188
+ "<table><thead><tr><th>Model</th><th>Priced as</th>"
189
+ f"<th>{html.escape(t(lang, 'events'))}</th>"
190
+ f"<th>{html.escape(t(lang, 'list'))}</th>"
191
+ f"<th>{html.escape(t(lang, 'billed'))}</th>"
192
+ "</tr></thead><tbody>" + "".join(body) + "</tbody></table>"
193
+ )
194
+
195
+
196
+ def _tier_table(story: Story, lang: str) -> str:
197
+ body = []
198
+ list_sum = 0
199
+ billed_sum = 0
200
+ for row in _tiers(story):
201
+ list_sum += row["list_micro"]
202
+ billed_sum += row["billed_micro"]
203
+ per = "—"
204
+ if row["sloc"]:
205
+ per = money(int(row["list_micro"] / row["sloc"] * 100))
206
+ body.append(
207
+ "<tr>"
208
+ f"<td>{row['tier']}</td>"
209
+ f"<td>{row['features']}</td>"
210
+ f"<td>{row['sloc']}</td>"
211
+ f"<td>{per}</td>"
212
+ f"<td>{row['list_usd']}</td>"
213
+ f"<td>{row['billed_usd']}</td>"
214
+ "</tr>"
215
+ )
216
+ body.append(
217
+ "<tr class='sum'>"
218
+ f"<td>{html.escape(t(lang, 'features_heading'))}</td><td></td><td></td><td></td>"
219
+ f"<td>{money(list_sum)}</td><td>{money(billed_sum)}</td></tr>"
220
+ )
221
+ body.append(
222
+ "<tr>"
223
+ f"<td>{html.escape(t(lang, 'overhead'))}</td><td></td><td></td><td></td>"
224
+ f"<td>{money(story.overhead.list_micro)}</td><td>{money(story.overhead.billed_micro)}</td></tr>"
225
+ )
226
+ body.append(
227
+ "<tr class='sum'>"
228
+ f"<td>{html.escape(t(lang, 'total'))}</td><td></td><td></td><td></td>"
229
+ f"<td>{money(list_sum + story.overhead.list_micro)}</td>"
230
+ f"<td>{money(billed_sum + story.overhead.billed_micro)}</td></tr>"
231
+ )
232
+ per_header = "List / 100 SLOC" if lang != "he" else "מחירון / 100 שורות"
233
+ return (
234
+ "<table><thead><tr><th>Tier</th><th>Features</th><th>SLOC</th>"
235
+ f"<th>{html.escape(per_header)}</th>"
236
+ f"<th>{html.escape(t(lang, 'list'))}</th>"
237
+ f"<th>{html.escape(t(lang, 'billed'))}</th>"
238
+ "</tr></thead><tbody>" + "".join(body) + "</tbody></table>"
239
+ )
240
+
241
+
242
+ def _dora_block(dora: Dora, lang: str, hebrew: bool) -> str:
243
+ lead = fmt_duration(dora.lead_time_us, hebrew=hebrew) if dora.lead_time_us is not None else "—"
244
+ restore = fmt_duration(dora.time_to_restore_us, hebrew=hebrew) if dora.time_to_restore_us is not None else "—"
245
+ cfr = "—" if dora.change_failure_rate is None else f"{dora.change_failure_rate:.0%}"
246
+ note = (
247
+ "Lead time is the median of (testing + deploy) across shipped changes. "
248
+ "Time to restore is the median fixes stage on failed changes. "
249
+ "Neither number is a second timeline beside the stages above."
250
+ if lang != "he"
251
+ else "זמן ההובלה הוא החציון של (בדיקות + פריסה) על שינויים שנמסרו. "
252
+ "הזמן לשיקום הוא חציון שלב התיקונים בשינויים שנכשלו. "
253
+ "אף אחד מהמספרים אינו ציר זמן שני לצד השלבים למעלה."
254
+ )
255
+ return (
256
+ f"<p>{html.escape(note)}</p>"
257
+ "<div class='metrics'>"
258
+ f"<div><span>{dora.deploys_per_week:.2f}</span><small>deploys / week</small>"
259
+ f"<small>{html.escape(dora.deploy_source)}</small></div>"
260
+ f"<div><span>{html.escape(lead)}</span><small>lead time</small></div>"
261
+ f"<div><span>{html.escape(cfr)}</span><small>change failure rate "
262
+ f"({dora.failed_changes}/{dora.shipped_changes})</small></div>"
263
+ f"<div><span>{html.escape(restore)}</span><small>time to restore</small></div>"
264
+ "</div>"
265
+ )
266
+
267
+
268
+ def _recs(recommendations: list[Recommendation], lang: str, hebrew: bool) -> str:
269
+ if not recommendations:
270
+ empty = "No rule fired on this window." if lang != "he" else "אף כלל לא הופעל בחלון הזה."
271
+ return f"<p>{html.escape(empty)}</p>"
272
+ blocks = []
273
+ for item in recommendations:
274
+ action = item.action_he if hebrew else item.action_en
275
+ evidence = item.evidence_he if hebrew else item.evidence_en
276
+ impact = item.impact_he if hebrew else item.impact_en
277
+ blocks.append(
278
+ "<article class='rec'>"
279
+ f"<h3>{html.escape(action)}</h3>"
280
+ f"<p><strong>{html.escape(t(lang, 'evidence'))}.</strong> {html.escape(evidence)}</p>"
281
+ f"<p><strong>{html.escape(t(lang, 'impact'))}.</strong> {html.escape(impact)}</p>"
282
+ "</article>"
283
+ )
284
+ return "".join(blocks)
285
+
286
+
287
+ def _display_money(micro: int) -> str:
288
+ if 0 < abs(micro) < MICRO // 100:
289
+ return money(micro)
290
+ return f"${Decimal(micro) / MICRO:,.2f}" if micro >= 0 else f"-${Decimal(-micro) / MICRO:,.2f}"
291
+
292
+
293
+ def _card(section_id: str, title: str, body: str) -> str:
294
+ return f"<section class='card' id='{section_id}'><h2>{html.escape(title)}</h2>{body}</section>"
295
+
296
+
297
+ def _details(label: str, body: str) -> str:
298
+ return f"<details><summary>{html.escape(label)}</summary>{body}</details>"
299
+
300
+
301
+ def _tile(label: str, value: str, color: str = "") -> str:
302
+ return f"<div class='card'><small>{label}</small><strong class='{color}'><bdi>{value}</bdi></strong></div>"
303
+
304
+
305
+ def _headlines(story: Story, lang: str) -> str:
306
+ count = len(story.features)
307
+ attributed = story.list_micro - story.overhead.list_micro
308
+ average = _display_money(mul_div_half_even(attributed, 1, count)) if count else "—"
309
+ return (
310
+ "<div class='metrics headline'>"
311
+ + _tile(t(lang, "export_list"), _display_money(story.list_micro), "list")
312
+ + _tile(t(lang, "export_billed"), _display_money(story.billed_micro), "billed")
313
+ + _tile(t(lang, "per_feature"), average)
314
+ + _tile(t(lang, "features_heading"), str(count))
315
+ + "</div>"
316
+ )
317
+
318
+
319
+ def _rect(x: float, width: float, y1: float, y2: float, color: str, label: str) -> str:
320
+ return (
321
+ f"<rect x='{x:.2f}' y='{min(y1, y2):.2f}' width='{width:.2f}' height='{abs(y1 - y2):.2f}' "
322
+ f"rx='5' fill='{color}'><title>{html.escape(label)}</title></rect>"
323
+ )
324
+
325
+
326
+ def _cost_table(rows: list[tuple[str, int, int, str]], header: str, lang: str) -> str:
327
+ return (
328
+ f"<table><thead><tr><th>{html.escape(header)}</th><th>{t(lang, 'list')}</th>"
329
+ f"<th>{t(lang, 'billed')}</th></tr></thead><tbody>"
330
+ + "".join(
331
+ f"<tr><th scope='row'><span class='swatch' style='background:{color}'></span>{html.escape(label)}</th>"
332
+ f"<td>{money(listed)}</td><td>{money(billed)}</td></tr>"
333
+ for label, listed, billed, color in rows
334
+ )
335
+ + "</tbody></table>"
336
+ )
337
+
338
+
339
+ def _waterfall(story: Story, lang: str) -> str:
340
+ stages = {name: [0, 0] for name in STAGE_NAMES}
341
+ for feature in story.features:
342
+ for stage in feature.stages:
343
+ stages[stage.name][0] += stage.list_micro
344
+ stages[stage.name][1] += stage.billed_micro
345
+ rows = [(t(lang, name), *stages[name], COLORS[name]) for name in STAGE_NAMES]
346
+ overhead = (t(lang, "overhead"), story.overhead.list_micro, story.overhead.billed_micro, COLORS["overhead"])
347
+ total = (t(lang, "total"), story.list_micro, story.billed_micro, "#E8ECF8")
348
+ rows.extend((overhead, total))
349
+
350
+ steps = []
351
+ cumulative = 0
352
+ for _, listed, _, _ in rows[:-1]:
353
+ steps.append((cumulative, cumulative + listed))
354
+ cumulative += listed
355
+ steps.append((0, story.list_micro))
356
+ low = min(min(step) for step in steps)
357
+ high = max(max(step) for step in steps)
358
+
359
+ def y(value: int) -> float:
360
+ return 203 - 166 * (value - low) / (high - low or 1)
361
+
362
+ svg = [
363
+ "<svg class='chart' viewBox='0 0 840 214' role='img' "
364
+ f"aria-label='{t(lang, 'stage_story')} · {t(lang, 'list')}'>"
365
+ ]
366
+ for tick in range(5):
367
+ grid_y = 37 + tick * 166 / 4
368
+ svg.append(f"<path class='gridline' d='M0 {grid_y}H840'/>")
369
+ svg.append(f"<path class='baseline' d='M0 {y(0):.2f}H840'/>")
370
+ for index, ((label, listed, _, color), (start, end)) in enumerate(zip(rows, steps, strict=True)):
371
+ x = index * 120 + 23
372
+ svg.append(_rect(x, 74, y(start), y(end), color, f"{label} · {money(listed)}"))
373
+ if index < len(steps) - 1:
374
+ svg.append(f"<path class='connector' d='M{x + 74} {y(end):.2f}h46'/>")
375
+ svg.append(
376
+ f"<text x='{x + 37}' y='{min(y(start), y(end)) - 10:.2f}' text-anchor='middle' "
377
+ f"class='chart-value' direction='ltr'>{_display_money(listed)}</text>"
378
+ )
379
+ svg.append("</svg>")
380
+ labels = (
381
+ "<div class='chart-labels'>"
382
+ + "".join(f"<span dir='auto'>{html.escape(label)}</span>" for label, *_ in rows)
383
+ + "</div>"
384
+ )
385
+ features = [
386
+ (f"{feature.repo}#{feature.number}", feature.list_micro, feature.billed_micro, COLORS["development"])
387
+ for feature in story.features
388
+ ]
389
+ return (
390
+ f"<p>{t(lang, 'stage_caption')}</p>"
391
+ f"<div class='chart-scroll' dir='ltr'><div class='waterfall'>{''.join(svg)}{labels}</div></div>"
392
+ + _cost_table(rows, t(lang, "stage"), lang)
393
+ + _details(
394
+ t(lang, "features_heading") + " + " + t(lang, "overhead"),
395
+ _cost_table([*features, overhead, total], t(lang, "feature"), lang)
396
+ + f"<p>{t(lang, 'overhead')} · {story.overhead.events} {t(lang, 'events')} · "
397
+ f"{story.overhead.tokens} {t(lang, 'tokens')}</p>",
398
+ )
399
+ )
400
+
401
+
402
+ def _tier_breakdown(story: Story, lang: str) -> str:
403
+ rows = _tiers(story)
404
+ averages = [mul_div_half_even(row["list_micro"], 1, row["features"]) if row["features"] else 0 for row in rows]
405
+ peak = max(map(abs, averages)) or 1
406
+ bars = "".join(
407
+ f"<div class='tier-row'><strong class='tier-badge'>{row['tier']}</strong><div>"
408
+ f"<div class='tier-meta'><span>{row['features']} {t(lang, 'features_heading')} · {row['sloc']} SLOC</span>"
409
+ f"<span>{t(lang, 'list')} <bdi>{_display_money(row['list_micro'])}</bdi> · "
410
+ f"{t(lang, 'billed')} <bdi>{_display_money(row['billed_micro'])}</bdi></span></div>"
411
+ f"<div class='tier-bar' aria-hidden='true'><span style='width:{abs(average) / peak:.4%}'></span></div></div>"
412
+ f"<strong><bdi>{_display_money(average) if row['features'] else '—'}</bdi>"
413
+ f"<small>{t(lang, 'per_feature')}</small></strong></div>"
414
+ for row, average in zip(rows, averages, strict=True)
415
+ )
416
+ return f"<p>{html.escape(_rubric(lang))}</p>{bars}" + _details(t(lang, "tiers"), _tier_table(story, lang))
417
+
418
+
419
+ def _daily(story: Story, lang: str) -> str:
420
+ days = story.daily_spend
421
+ if not days:
422
+ return f"<p>{t(lang, 'no_daily')}</p>"
423
+ priciest = max(days, key=lambda row: row.list_micro)
424
+ typical = round(median(Decimal(row.list_micro) for row in days))
425
+ bases = [row.list_micro - row.fast_list_micro for row in days]
426
+ totals = [row.list_micro for row in days]
427
+ low = min(0, min(bases), min(totals))
428
+ high = max(0, max(bases), max(totals))
429
+
430
+ def y(value: int) -> float:
431
+ return 172 - 145 * (value - low) / (high - low or 1)
432
+
433
+ width = max(640, len(days) * 42)
434
+ gap = width / len(days)
435
+ bar_width = min(gap * 0.66, 78)
436
+ svg = [
437
+ f"<svg class='chart' style='min-width:{width * 0.72:.0f}px' viewBox='0 0 {width} 210' role='img' "
438
+ f"aria-label='{t(lang, 'daily_caption')}'>",
439
+ f"<path class='baseline' d='M0 {y(0):.2f}H{width}'/>",
440
+ ]
441
+ for index, (row, base) in enumerate(zip(days, bases, strict=True)):
442
+ center = gap * (index + 0.5)
443
+ x = center - bar_width / 2
444
+ svg.append(_rect(x, bar_width, y(0), y(base), COLORS["planning"], f"{row.day} · {money(base)}"))
445
+ if row.fast_list_micro:
446
+ svg.append(
447
+ _rect(
448
+ x,
449
+ bar_width,
450
+ y(base),
451
+ y(row.list_micro),
452
+ COLORS["fixes"],
453
+ f"{row.day} · Fast {money(row.fast_list_micro)}",
454
+ )
455
+ )
456
+ highlight = " class='peak-date'" if row is priciest else ""
457
+ svg.append(
458
+ f"<text x='{center:.2f}' y='197' text-anchor='middle' direction='ltr'{highlight}>{row.day:%m-%d}</text>"
459
+ )
460
+ svg.append(f"<path class='median' d='M0 {y(typical):.2f}H{width}'/></svg>")
461
+ table = (
462
+ f"<table><thead><tr><th>UTC</th><th>{t(lang, 'list')}</th><th>{t(lang, 'billed')}</th>"
463
+ "<th>Fast</th></tr></thead><tbody>"
464
+ + "".join(
465
+ f"<tr><th scope='row'><bdi>{row.day}</bdi></th><td>{money(row.list_micro)}</td>"
466
+ f"<td>{money(row.billed_micro)}</td><td>{money(row.fast_list_micro)}</td></tr>"
467
+ for row in days
468
+ )
469
+ + "</tbody></table>"
470
+ )
471
+ return (
472
+ f"<p>{t(lang, 'daily_caption')}</p><div class='metrics daily-metrics'>"
473
+ + _tile(f"<bdi>{priciest.day}</bdi> · {t(lang, 'list')}", _display_money(priciest.list_micro), "list")
474
+ + _tile(t(lang, "billed"), _display_money(priciest.billed_micro), "billed")
475
+ + _tile(t(lang, "fast_on_peak"), _display_money(priciest.fast_list_micro), "fast")
476
+ + f"</div><div class='chart-scroll' dir='ltr'>{''.join(svg)}</div>"
477
+ f"<p class='legend'><span class='swatch list-swatch'></span>{t(lang, 'standard_spend')} · "
478
+ f"<span class='swatch fast-swatch'></span>Fast · "
479
+ f"<span class='median-key'></span>{t(lang, 'daily_baseline')} <bdi>{_display_money(typical)}</bdi></p>"
480
+ + _details(t(lang, "daily_details"), table)
481
+ )
482
+
483
+
484
+ _CSS = """
485
+ :root {
486
+ color-scheme: dark;
487
+ --paper: #0b1020;
488
+ --card: #141b33;
489
+ --line: #2e3a62;
490
+ --ink: #e8ecf8;
491
+ --muted: #a9b3d6;
492
+ --blue: #7c9cff;
493
+ --teal: #4fd1c5;
494
+ --gold: #f6c453;
495
+ --red: #f87171;
496
+ }
497
+ * { box-sizing: border-box; }
498
+ body {
499
+ margin: 0;
500
+ padding: clamp(1rem, 4vw, 3.5rem);
501
+ min-height: 100vh;
502
+ background: radial-gradient(1100px 620px at 85% -140px, #24306b, transparent 75%), var(--paper);
503
+ color: var(--ink);
504
+ font: 1rem/1.55 system-ui, sans-serif;
505
+ }
506
+ .top, main, footer { max-width: 1080px; margin-inline: auto; }
507
+ h1, h2, h3, p { margin-block: 0; }
508
+ h1, h2, h3 { line-height: 1.12; }
509
+ h1 { max-width: 16ch; font-size: clamp(2.5rem, 6.4vw, 4.6rem); letter-spacing: -.045em; margin-block: 1rem 1.5rem; }
510
+ h2 { font-size: clamp(1.55rem, 3.3vw, 2.45rem); letter-spacing: -.035em; margin-bottom: .6rem; }
511
+ h3 { font-size: 1.13rem; }
512
+ h1 em { color: var(--teal); font-style: normal; }
513
+ p { color: var(--muted); margin-block: .6rem; }
514
+ a { color: #a9beff; text-underline-offset: .2em; }
515
+ .kicker {
516
+ display: inline-block; margin: 0; padding: .25rem .8rem;
517
+ border: 1px solid var(--line); border-radius: 999px; background: var(--card); color: var(--ink);
518
+ }
519
+ .sponsor { font-size: .85rem; }
520
+ .lede { max-width: 86ch; overflow-wrap: anywhere; }
521
+ .card {
522
+ min-width: 0; padding: clamp(.85rem, 2.5vw, 1.65rem);
523
+ border: 1px solid var(--line); border-radius: 1.25rem; background: var(--card);
524
+ }
525
+ main > .card, .banner { margin-block: 1rem; }
526
+ .banner {
527
+ display: flex; flex-wrap: wrap; gap: .25rem 1rem; padding: .7rem 1rem;
528
+ border: 1px solid var(--line); border-radius: .75rem; color: var(--muted);
529
+ }
530
+ .banner.pass strong, .billed { color: var(--teal); }
531
+ .banner.fail strong, .fast, .checks .bad { color: var(--red); }
532
+ .list { color: var(--blue); }
533
+ .metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .7rem; }
534
+ .metrics small, .tier-row small { display: block; color: var(--muted); font-weight: 500; }
535
+ .metrics strong, .metrics div > span {
536
+ display: block; font-size: clamp(1.4rem, 3.5vw, 2.65rem);
537
+ line-height: 1.16; font-weight: 800; letter-spacing: -.04em;
538
+ font-variant-numeric: tabular-nums; overflow-wrap: anywhere;
539
+ }
540
+ #delivery .metrics div, .daily-metrics .card { padding: .8rem; border-radius: .8rem; background: #10162c; }
541
+ .daily-metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); margin-block: 1rem; }
542
+ .chart-scroll { overflow-x: auto; }
543
+ .chart { display: block; width: 100%; height: auto; font: 15px system-ui, sans-serif; fill: var(--muted); }
544
+ .chart-value, .peak-date { fill: var(--ink); font-weight: 800; }
545
+ .chart-value { font-size: 17px; }
546
+ .waterfall { min-width: 570px; }
547
+ .chart-labels { display: grid; grid-template-columns: repeat(7, 1fr); text-align: center; font-size: .8rem; color: var(--muted); }
548
+ .chart-labels span { padding-inline: .25rem; }
549
+ .gridline { stroke: var(--line); opacity: .55; }
550
+ .baseline, .connector { stroke: #8794bb; }
551
+ .connector, .median { stroke-dasharray: 5 5; }
552
+ .median { stroke: var(--gold); stroke-width: 1.5px; }
553
+ .median-key { display: inline-block; width: 1rem; border-top: 2px dashed var(--gold); vertical-align: middle; }
554
+ table { width: 100%; border-collapse: collapse; font-size: .87rem; margin-block: .6rem; font-variant-numeric: tabular-nums; }
555
+ th, td { text-align: start; padding: .38rem .45rem; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
556
+ th { font-weight: 650; }
557
+ thead, .meta, .identity, .legend { color: var(--muted); font-size: .86rem; }
558
+ tr.sum, #waterfall > table tr:last-child { background: #1e2850; font-weight: 700; }
559
+ .swatch { display: inline-block; width: .65rem; height: .65rem; border-radius: .15rem; margin-inline-end: .4rem; }
560
+ .list-swatch { background: var(--blue); }
561
+ .fast-swatch { background: var(--red); }
562
+ .bar { width: 100%; height: 14px; display: block; border-radius: 6px; margin-block: .8rem; }
563
+ details { overflow-x: auto; margin-top: .8rem; padding-top: .65rem; border-top: 1px solid var(--line); }
564
+ summary { cursor: pointer; color: #cad3f4; font-weight: 650; }
565
+ .feature { padding-block: 1rem; border-bottom: 1px solid var(--line); }
566
+ .tier-row { display: grid; grid-template-columns: 3rem minmax(0, 1fr) minmax(6rem, auto); gap: .8rem; align-items: center; margin-block: 1rem; }
567
+ .tier-badge { border-radius: .65rem; padding: .5rem 0; background: #1e2850; color: var(--gold); text-align: center; font-size: 1.2rem; }
568
+ .tier-meta { display: flex; justify-content: space-between; flex-wrap: wrap; gap: .1rem .7rem; color: var(--muted); font-size: .82rem; }
569
+ .tier-bar { height: .8rem; margin-top: .35rem; border-radius: 999px; background: #222c51; overflow: hidden; }
570
+ .tier-bar span { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, var(--blue), #a78bfa); }
571
+ .rec { padding: .9rem 1rem; border: 1px solid var(--line); border-radius: .8rem; margin-top: .7rem; background: #10162c; }
572
+ .rec:first-of-type { border-color: var(--teal); }
573
+ .rec p { margin-bottom: 0; }
574
+ .rec p strong { color: var(--gold); }
575
+ .rec p:last-child strong { color: var(--teal); }
576
+ footer { margin-top: 2rem; color: var(--muted); font-size: .85rem; }
577
+ @media (max-width: 680px) {
578
+ .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
579
+ .tier-row { grid-template-columns: 2.3rem minmax(0, 1fr); gap: .4rem .7rem; }
580
+ .tier-row > strong:last-child { grid-column: 2; }
581
+ table { min-width: 275px; }
582
+ .card { overflow-x: auto; }
583
+ }
584
+ """
ukaf/reporting.py ADDED
@@ -0,0 +1,50 @@
1
+ """Shared report analysis and output for the CLI and MCP server."""
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from ukaf.delivery import Pull
7
+ from ukaf.dora import Dora, dora_for
8
+ from ukaf.pricing import default_pricing_path, load_pricing
9
+ from ukaf.recommend import Recommendation, recommend
10
+ from ukaf.reconcile import Check, assert_reconciled
11
+ from ukaf.render_html import render_html
12
+ from ukaf.serialize import dumps_json, render_markdown, story_document
13
+ from ukaf.story import Story, build_story
14
+ from ukaf.usage import UsageEvent, load_usage
15
+
16
+
17
+ @dataclass
18
+ class Analysis:
19
+ story: Story
20
+ dora: Dora
21
+ checks: list[Check]
22
+ recommendations: list[Recommendation]
23
+
24
+ def document(self, *, lang: str) -> dict:
25
+ return story_document(self.story, self.dora, self.checks, self.recommendations, lang=lang)
26
+
27
+
28
+ def load_events(usage: Path, pricing: Path | None = None, *, team_token_rate: bool = False) -> list[UsageEvent]:
29
+ card = load_pricing(pricing or default_pricing_path())
30
+ return load_usage(usage, card, team_token_rate=team_token_rate)
31
+
32
+
33
+ def analyze(events: list[UsageEvent], pulls: list[Pull]) -> Analysis:
34
+ story = build_story(events, pulls)
35
+ dora = dora_for(story)
36
+ checks = assert_reconciled(story, dora)
37
+ return Analysis(story, dora, checks, recommend(story, dora))
38
+
39
+
40
+ def write_report(analysis: Analysis, out: Path, *, lang: str) -> tuple[dict[str, Path], dict]:
41
+ document = analysis.document(lang=lang)
42
+ args = (analysis.story, analysis.dora, analysis.checks, analysis.recommendations)
43
+ html = render_html(*args, lang=lang)
44
+ markdown = render_markdown(*args, lang=lang)
45
+ paths = {extension: out / f"report.{extension}" for extension in ("html", "json", "md")}
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ paths["html"].write_text(html, encoding="utf-8")
48
+ paths["json"].write_text(dumps_json(document), encoding="utf-8")
49
+ paths["md"].write_text(markdown, encoding="utf-8")
50
+ return paths, document