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/serialize.py ADDED
@@ -0,0 +1,340 @@
1
+ """JSON and Markdown views of a story. Same numbers as the HTML report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from ukaf import SPONSOR_LINE, SPONSOR_URL, __version__
8
+ from ukaf.dora import Dora
9
+ from ukaf.i18n import stage_label, t
10
+ from ukaf.money import money
11
+ from ukaf.recommend import Recommendation
12
+ from ukaf.reconcile import Check
13
+ from ukaf.story import STAGE_NAMES, Story
14
+ from ukaf.timeutil import fmt_duration, iso
15
+
16
+ TIER_ORDER = ("S", "M", "L", "XL")
17
+
18
+
19
+ def story_document(
20
+ story: Story,
21
+ dora: Dora,
22
+ checks: list[Check],
23
+ recommendations: list[Recommendation],
24
+ *,
25
+ lang: str,
26
+ ) -> dict:
27
+ hebrew = lang == "he"
28
+ return {
29
+ "version": __version__,
30
+ "language": lang,
31
+ "sponsorship": SPONSOR_URL,
32
+ "window": {
33
+ "start": iso(story.window_start) if story.window_start else None,
34
+ "end": iso(story.window_end) if story.window_end else None,
35
+ },
36
+ "totals": _money_block(story.events, story.tokens, story.list_micro, story.billed_micro),
37
+ "features": [_feature_json(feature, hebrew) for feature in story.features],
38
+ "overhead": {
39
+ "events": story.overhead.events,
40
+ "tokens": story.overhead.tokens,
41
+ "list_micro": story.overhead.list_micro,
42
+ "billed_micro": story.overhead.billed_micro,
43
+ "list_usd": money(story.overhead.list_micro),
44
+ "billed_usd": money(story.overhead.billed_micro),
45
+ "on_demand_events": story.overhead.on_demand_events,
46
+ "on_demand_billed_micro": story.overhead.on_demand_billed_micro,
47
+ },
48
+ "models": [
49
+ {
50
+ "model": row.model,
51
+ "priced_as": row.priced_as,
52
+ "fast": row.fast,
53
+ "events": row.events,
54
+ "tokens": row.tokens,
55
+ "list_micro": row.list_micro,
56
+ "billed_micro": row.billed_micro,
57
+ "list_usd": money(row.list_micro),
58
+ "billed_usd": money(row.billed_micro),
59
+ }
60
+ for row in story.models
61
+ ],
62
+ "tiers": _tiers(story),
63
+ "dora": {
64
+ "deploys": dora.deploys,
65
+ "deploy_source": dora.deploy_source,
66
+ "deploys_per_week": round(dora.deploys_per_week, 3),
67
+ "lead_time_us": dora.lead_time_us,
68
+ "lead_time": fmt_duration(dora.lead_time_us, hebrew=hebrew) if dora.lead_time_us is not None else None,
69
+ "lead_time_identity": "testing + deploy",
70
+ "change_failure_rate": dora.change_failure_rate,
71
+ "failed_changes": dora.failed_changes,
72
+ "shipped_changes": dora.shipped_changes,
73
+ "time_to_restore_us": dora.time_to_restore_us,
74
+ "time_to_restore": (
75
+ fmt_duration(dora.time_to_restore_us, hebrew=hebrew) if dora.time_to_restore_us is not None else None
76
+ ),
77
+ "time_to_restore_identity": "fixes stage on failed changes",
78
+ },
79
+ "recommendations": [
80
+ {
81
+ "rule_id": item.rule_id,
82
+ "action": item.action_he if hebrew else item.action_en,
83
+ "evidence": item.evidence_he if hebrew else item.evidence_en,
84
+ "impact": item.impact_he if hebrew else item.impact_en,
85
+ "billed_month_micro": item.billed_month_micro,
86
+ "list_month_micro": item.list_month_micro,
87
+ "minutes_month": item.minutes_month,
88
+ }
89
+ for item in recommendations
90
+ ],
91
+ "reconciliation": {
92
+ "ok": all(item.ok for item in checks),
93
+ "checks": [{"name": item.name, "ok": item.ok, "detail": item.detail} for item in checks],
94
+ },
95
+ "assumptions": list(story.assumptions),
96
+ }
97
+
98
+
99
+ def dumps_json(document: dict) -> str:
100
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
101
+
102
+
103
+ def render_markdown(
104
+ story: Story,
105
+ dora: Dora,
106
+ checks: list[Check],
107
+ recommendations: list[Recommendation],
108
+ *,
109
+ lang: str,
110
+ ) -> str:
111
+ hebrew = lang == "he"
112
+ ok = all(item.ok for item in checks)
113
+ lines: list[str] = [
114
+ f"# {t(lang, 'title')}",
115
+ "",
116
+ SPONSOR_LINE,
117
+ "",
118
+ _opening(story, lang),
119
+ "",
120
+ f"## {t(lang, 'waterfall')}",
121
+ "",
122
+ f"| | {t(lang, 'events')} | {t(lang, 'tokens')} | {t(lang, 'list')} | {t(lang, 'billed')} |",
123
+ "| --- | ---: | ---: | ---: | ---: |",
124
+ ]
125
+ for feature in story.features:
126
+ lines.append(
127
+ f"| {feature.repo}#{feature.number} {feature.title} | {feature.events} | "
128
+ f"{feature.tokens} | {money(feature.list_micro)} | {money(feature.billed_micro)} |"
129
+ )
130
+ lines.append(
131
+ f"| {t(lang, 'overhead')} | {story.overhead.events} | {story.overhead.tokens} | "
132
+ f"{money(story.overhead.list_micro)} | {money(story.overhead.billed_micro)} |"
133
+ )
134
+ lines.append(
135
+ f"| **{t(lang, 'total')}** | **{story.events}** | **{story.tokens}** | "
136
+ f"**{money(story.list_micro)}** | **{money(story.billed_micro)}** |"
137
+ )
138
+ lines.extend(["", f"## {t(lang, 'features_heading')}", ""])
139
+ for feature in story.features:
140
+ lines.append(f"### {feature.repo}#{feature.number} — {feature.title}")
141
+ lines.append("")
142
+ lines.append(_feature_prose(feature, lang))
143
+ lines.append("")
144
+ lines.append(f"| {t(lang, 'stage')} | {t(lang, 'duration')} | {t(lang, 'list')} | {t(lang, 'billed')} |")
145
+ lines.append("| --- | ---: | ---: | ---: |")
146
+ for stage in feature.stages:
147
+ lines.append(
148
+ f"| {stage_label(lang, stage.name)} | {fmt_duration(stage.duration_us, hebrew=hebrew)} | "
149
+ f"{money(stage.list_micro)} | {money(stage.billed_micro)} |"
150
+ )
151
+ lines.append(
152
+ f"| **{t(lang, 'total')}** | **{fmt_duration(feature.duration_us, hebrew=hebrew)}** | "
153
+ f"**{money(feature.list_micro)}** | **{money(feature.billed_micro)}** |"
154
+ )
155
+ lines.append("")
156
+ lines.append(
157
+ f"DORA lead time = {t(lang, 'testing')} + {t(lang, 'deploy')} = "
158
+ f"{fmt_duration(feature.lead_time_us, hebrew=hebrew)}."
159
+ )
160
+ lines.append("")
161
+ lines.extend(
162
+ [
163
+ f"## {t(lang, 'reconciliation')}: {t(lang, 'pass') if ok else t(lang, 'fail')}",
164
+ "",
165
+ ]
166
+ )
167
+ for item in checks:
168
+ mark = "ok" if item.ok else "FAIL"
169
+ lines.append(f"- [{mark}] {item.name}: {item.detail}")
170
+ lines.extend(["", f"## {t(lang, 'dora')}", ""])
171
+ lines.append(f"- Deploy frequency: {dora.deploys_per_week:.2f} / week ({dora.deploy_source}).")
172
+ if dora.lead_time_us is not None:
173
+ lines.append(f"- Lead time (median of testing + deploy): {fmt_duration(dora.lead_time_us, hebrew=hebrew)}.")
174
+ if dora.change_failure_rate is None:
175
+ lines.append("- Change failure rate: no shipped changes.")
176
+ else:
177
+ lines.append(
178
+ f"- Change failure rate: {dora.failed_changes}/{dora.shipped_changes} ({dora.change_failure_rate:.0%})."
179
+ )
180
+ if dora.time_to_restore_us is not None:
181
+ lines.append(
182
+ "- Time to restore (median fixes stage on failed changes): "
183
+ f"{fmt_duration(dora.time_to_restore_us, hebrew=hebrew)}."
184
+ )
185
+ lines.extend(["", f"## {t(lang, 'tiers')}", "", _rubric(lang), ""])
186
+ lines.append(f"| Tier | Features | SLOC | {t(lang, 'list')} | {t(lang, 'billed')} |")
187
+ lines.append("| --- | ---: | ---: | ---: | ---: |")
188
+ for row in _tiers(story):
189
+ lines.append(f"| {row['tier']} | {row['features']} | {row['sloc']} | {row['list_usd']} | {row['billed_usd']} |")
190
+ lines.extend(["", f"## {t(lang, 'recommendations')}", ""])
191
+ if not recommendations:
192
+ lines.append("No rule fired on this window.")
193
+ for index, item in enumerate(recommendations, start=1):
194
+ action = item.action_he if hebrew else item.action_en
195
+ evidence = item.evidence_he if hebrew else item.evidence_en
196
+ impact = item.impact_he if hebrew else item.impact_en
197
+ lines.append(f"### {index}. {action}")
198
+ lines.append("")
199
+ lines.append(f"- {t(lang, 'evidence')}: {evidence}")
200
+ lines.append(f"- {t(lang, 'impact')}: {impact}")
201
+ lines.append("")
202
+ lines.extend(["", f"## {t(lang, 'assumptions')}", ""])
203
+ for item in story.assumptions:
204
+ lines.append(f"- {item}")
205
+ lines.extend(["", "---", "", SPONSOR_LINE, ""])
206
+ return "\n".join(lines)
207
+
208
+
209
+ def _feature_json(feature, hebrew: bool) -> dict:
210
+ return {
211
+ "repo": feature.repo,
212
+ "number": feature.number,
213
+ "title": feature.title,
214
+ "url": feature.url,
215
+ "author": feature.author,
216
+ "tier": feature.tier,
217
+ "sloc": feature.sloc,
218
+ "sloc_excluded": feature.sloc_excluded,
219
+ "files_counted": feature.files_counted,
220
+ "files_excluded": feature.files_excluded,
221
+ "failed": feature.failed,
222
+ "events": feature.events,
223
+ "tokens": feature.tokens,
224
+ "list_micro": feature.list_micro,
225
+ "billed_micro": feature.billed_micro,
226
+ "list_usd": money(feature.list_micro),
227
+ "billed_usd": money(feature.billed_micro),
228
+ "duration_us": feature.duration_us,
229
+ "lead_time_us": feature.lead_time_us,
230
+ "lead_time_identity": "testing + deploy",
231
+ "stages": [
232
+ {
233
+ "name": stage.name,
234
+ "duration_us": stage.duration_us,
235
+ "duration": fmt_duration(stage.duration_us, hebrew=hebrew),
236
+ "events": stage.events,
237
+ "tokens": stage.tokens,
238
+ "list_micro": stage.list_micro,
239
+ "billed_micro": stage.billed_micro,
240
+ "list_usd": money(stage.list_micro),
241
+ "billed_usd": money(stage.billed_micro),
242
+ }
243
+ for stage in feature.stages
244
+ ],
245
+ }
246
+
247
+
248
+ def _money_block(events: int, tokens: int, list_micro: int, billed_micro: int) -> dict:
249
+ return {
250
+ "events": events,
251
+ "tokens": tokens,
252
+ "list_micro": list_micro,
253
+ "billed_micro": billed_micro,
254
+ "list_usd": money(list_micro),
255
+ "billed_usd": money(billed_micro),
256
+ }
257
+
258
+
259
+ def _tiers(story: Story) -> list[dict]:
260
+ rows = []
261
+ for tier in TIER_ORDER:
262
+ group = [feature for feature in story.features if feature.tier == tier]
263
+ list_micro = sum(feature.list_micro for feature in group)
264
+ billed_micro = sum(feature.billed_micro for feature in group)
265
+ rows.append(
266
+ {
267
+ "tier": tier,
268
+ "features": len(group),
269
+ "sloc": sum(feature.sloc for feature in group),
270
+ "list_micro": list_micro,
271
+ "billed_micro": billed_micro,
272
+ "list_usd": money(list_micro),
273
+ "billed_usd": money(billed_micro),
274
+ }
275
+ )
276
+ return rows
277
+
278
+
279
+ def _opening(story: Story, lang: str) -> str:
280
+ if lang == "he":
281
+ return (
282
+ f"בייצוא יש {story.events} אירועים. מחיר המחירון {money(story.list_micro)}. "
283
+ f"החשבונית (לפי דרישה בלבד; Included ו-Free מחויבים כאפס) היא {money(story.billed_micro)}. "
284
+ f"{len(story.features)} פיצ'רים מסבירים {money(sum(f.list_micro for f in story.features))} מחירון "
285
+ f"ו-{money(sum(f.billed_micro for f in story.features))} חיוב. "
286
+ f"התקורה היא {money(story.overhead.list_micro)} מחירון ו-{money(story.overhead.billed_micro)} חיוב. "
287
+ "סכום הפיצ'רים והתקורה שווה לייצוא."
288
+ )
289
+ return (
290
+ f"The export has {story.events} events. List price is {money(story.list_micro)}. "
291
+ f"The invoice (on-demand only; Included and Free bill as zero) is {money(story.billed_micro)}. "
292
+ f"{len(story.features)} features account for "
293
+ f"{money(sum(f.list_micro for f in story.features))} list and "
294
+ f"{money(sum(f.billed_micro for f in story.features))} billed. "
295
+ f"Overhead is {money(story.overhead.list_micro)} list and "
296
+ f"{money(story.overhead.billed_micro)} billed. "
297
+ "Feature totals plus overhead equal the export."
298
+ )
299
+
300
+
301
+ def _feature_prose(feature, lang: str) -> str:
302
+ stages = {stage.name: stage for stage in feature.stages}
303
+ hebrew = lang == "he"
304
+ bits = [fmt_duration(stages[name].duration_us, hebrew=hebrew) for name in STAGE_NAMES]
305
+ if lang == "he":
306
+ return (
307
+ f"{feature.title} ({feature.repo}#{feature.number}) הוא שינוי בדרגה {feature.tier}: "
308
+ f"{feature.sloc} שורות כתובות יד ב-{feature.files_counted} קבצים "
309
+ f"({feature.sloc_excluded} שורות בקבצי נעילה או קבצים שנוצרו לא נספרו). "
310
+ f"תכנון {bits[0]}, פיתוח {bits[1]}, בדיקות {bits[2]}, פריסה {bits[3]}, תיקונים {bits[4]}. "
311
+ f"חמשת המקטעים נפגשים קצה אל קצה ומסתכמים ב-{fmt_duration(feature.duration_us, hebrew=True)}."
312
+ )
313
+ return (
314
+ f"{feature.title} ({feature.repo}#{feature.number}) is a tier {feature.tier} change: "
315
+ f"{feature.sloc} hand-written lines across {feature.files_counted} files "
316
+ f"({feature.sloc_excluded} lines in lockfiles or generated files are not counted). "
317
+ f"Planning ran {bits[0]}, development {bits[1]}, testing {bits[2]}, "
318
+ f"deploy and acceptance {bits[3]}, fixes {bits[4]}. "
319
+ f"Those five intervals meet end to end and add up to {fmt_duration(feature.duration_us)}."
320
+ )
321
+
322
+
323
+ def _rubric(lang: str) -> str:
324
+ if lang == "he":
325
+ return (
326
+ "הדרגה היא הגבוהה מבין שני הספים. שורות כתובות יד הן הוספות ועוד מחיקות "
327
+ "בקבצים שאינם קובץ נעילה או קובץ שנוצר. "
328
+ "S: מתחת ל-50 שורות ולכל היותר 3 קבצים. "
329
+ "M: 50–299 שורות או 4–10 קבצים. "
330
+ "L: 300–999 שורות או 11–30 קבצים. "
331
+ "XL: 1000 שורות ומעלה או 31 קבצים ומעלה."
332
+ )
333
+ return (
334
+ "The tier is the higher of the two gates. Hand-written lines are additions plus deletions "
335
+ "on files that are not lockfiles or generated. "
336
+ "S: under 50 lines and at most 3 files. "
337
+ "M: 50–299 lines or 4–10 files. "
338
+ "L: 300–999 lines or 11–30 files. "
339
+ "XL: 1000 lines or more, or 31 files or more."
340
+ )