-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_postmortem.py
More file actions
714 lines (621 loc) · 29 KB
/
Copy pathrender_postmortem.py
File metadata and controls
714 lines (621 loc) · 29 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#!/usr/bin/env python3
"""Render a judged postmortem.json into an evidence-backed incident postmortem.
Pure stdlib, no LLM involved. This script does not judge root cause, category, or
severity — that's Claude's job. But unlike the pure validators elsewhere in this
portfolio, it does not just format: it independently computes every duration metric
(time to detect, time to mitigate, time to resolve, total duration) from the raw
impact timestamps, the same "script does the math" split critical-path-mapper uses
for its schedule computation. It never trusts a duration number from the model,
because postmortem.json's schema has no duration field for it to state one in.
"""
import argparse
import html
import json
import sys
from datetime import datetime
from pathlib import Path
VALID_SEVERITY = {"SEV1", "SEV2", "SEV3", "SEV4"}
VALID_PHASE = {"detection", "diagnosis", "mitigation", "resolution"}
VALID_CATEGORY = {"code", "config", "infra", "process", "third_party"}
VALID_PRIORITY = {"P0", "P1", "P2", "P3"}
SEVERITY_ORDER = {"SEV1": 0, "SEV2": 1, "SEV3": 2, "SEV4": 3}
PRIORITY_ORDER = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
BADGE = {"SEV1": "\U0001F534", "SEV2": "\U0001F7E0", "SEV3": "\U0001F7E1", "SEV4": "\U0001F7E2"}
CHIP_COLORS = {
"SEV1": ("#842029", "#f8d7da"),
"SEV2": ("#7a4a00", "#ffe5cc"),
"SEV3": ("#664d03", "#fff3cd"),
"SEV4": ("#0f5132", "#d1e7dd"),
"P0": ("#842029", "#f8d7da"),
"P1": ("#7a4a00", "#ffe5cc"),
"P2": ("#664d03", "#fff3cd"),
"P3": ("#41464b", "#e2e3e5"),
"detection": ("#41464b", "#e2e3e5"),
"diagnosis": ("#664d03", "#fff3cd"),
"mitigation": ("#7a4a00", "#ffe5cc"),
"resolution": ("#0f5132", "#d1e7dd"),
}
def fail(msg):
print(f"ERROR: {msg}", file=sys.stderr)
sys.exit(1)
def _parse_ts(s, context):
try:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except (ValueError, AttributeError):
fail(f"{context} '{s}' is not a valid ISO-8601 datetime")
def _require_nonempty(obj, field, context):
if not str(obj.get(field, "")).strip():
fail(f"{context} {field} must be non-empty")
def load_postmortem(path):
with open(path) as f:
data = json.load(f)
for field in ("service", "author", "title", "generated_at", "severity",
"severity_rationale", "summary", "impact", "timeline",
"root_causes", "action_items"):
if field not in data:
fail(f"postmortem.json missing required top-level field '{field}'")
if data["severity"] not in VALID_SEVERITY:
fail(f"severity '{data['severity']}' must be one of {sorted(VALID_SEVERITY)}")
impact = data["impact"]
for field in ("started_at", "detected_at", "mitigated_at", "resolved_at",
"affected_services", "affected_users", "business_impact", "evidence"):
if field not in impact:
fail(f"impact missing required field '{field}'")
_require_nonempty(impact, "evidence", "impact")
for i, e in enumerate(data.get("timeline", [])):
for field in ("timestamp", "phase", "description", "evidence"):
if field not in e:
fail(f"timeline[{i}] missing required field '{field}'")
if e["phase"] not in VALID_PHASE:
fail(f"timeline[{i}] phase '{e['phase']}' must be one of {sorted(VALID_PHASE)}")
_require_nonempty(e, "evidence", f"timeline[{i}]")
for i, rc in enumerate(data.get("root_causes", [])):
for field in ("id", "description", "category", "evidence"):
if field not in rc:
fail(f"root_causes[{i}] missing required field '{field}'")
if rc["category"] not in VALID_CATEGORY:
fail(f"root_causes[{i}] ('{rc['id']}') category '{rc['category']}' must be one of {sorted(VALID_CATEGORY)}")
_require_nonempty(rc, "evidence", f"root_causes[{i}] ('{rc['id']}')")
for i, cf in enumerate(data.get("contributing_factors", [])):
for field in ("id", "description", "category", "evidence"):
if field not in cf:
fail(f"contributing_factors[{i}] missing required field '{field}'")
if cf["category"] not in VALID_CATEGORY:
fail(f"contributing_factors[{i}] ('{cf['id']}') category '{cf['category']}' must be one of {sorted(VALID_CATEGORY)}")
_require_nonempty(cf, "evidence", f"contributing_factors[{i}] ('{cf['id']}')")
for i, s in enumerate(data.get("symptoms", [])):
for field in ("description", "evidence"):
if field not in s:
fail(f"symptoms[{i}] missing required field '{field}'")
for i, ai in enumerate(data.get("action_items", [])):
for field in ("id", "description", "owner", "priority", "due_date", "linked_cause"):
if field not in ai:
fail(f"action_items[{i}] missing required field '{field}'")
if ai["priority"] not in VALID_PRIORITY:
fail(f"action_items[{i}] ('{ai['id']}') priority '{ai['priority']}' must be one of {sorted(VALID_PRIORITY)}")
_require_nonempty(ai, "owner", f"action_items[{i}] ('{ai['id']}')")
return data
def validate_linked_causes(data):
cause_ids = {rc["id"] for rc in data.get("root_causes", [])} | \
{cf["id"] for cf in data.get("contributing_factors", [])}
for i, ai in enumerate(data.get("action_items", [])):
if ai["linked_cause"] not in cause_ids:
fail(f"action_items[{i}] ('{ai['id']}') linked_cause '{ai['linked_cause']}' — unknown id")
def _check_monotonic(pairs, context):
for (label_a, a), (label_b, b) in zip(pairs, pairs[1:]):
if a > b:
fail(
f"{context} must be chronologically non-decreasing — "
f"{label_a} ({a.isoformat()}) occurs after {label_b} ({b.isoformat()})"
)
def validate_timeline_monotonic(data):
pairs = [
(f"timeline[{i}] ({e['phase']})", _parse_ts(e["timestamp"], f"timeline[{i}].timestamp"))
for i, e in enumerate(data.get("timeline", []))
]
_check_monotonic(pairs, "timeline")
def validate_impact_monotonic(data):
impact = data["impact"]
pairs = [
(k, _parse_ts(impact[k], f"impact.{k}"))
for k in ("started_at", "detected_at", "mitigated_at", "resolved_at")
]
_check_monotonic(pairs, "impact timestamps")
def compute_durations(data):
impact = data["impact"]
started, detected, mitigated, resolved = (
_parse_ts(impact[k], f"impact.{k}")
for k in ("started_at", "detected_at", "mitigated_at", "resolved_at")
)
return {
"started_at": impact["started_at"],
"detected_at": impact["detected_at"],
"mitigated_at": impact["mitigated_at"],
"resolved_at": impact["resolved_at"],
"time_to_detect_min": round((detected - started).total_seconds() / 60),
"time_to_mitigate_min": round((mitigated - detected).total_seconds() / 60),
"time_to_resolve_min": round((resolved - mitigated).total_seconds() / 60),
"total_duration_min": round((resolved - started).total_seconds() / 60),
"severity": data["severity"],
}
def _fmt_duration(minutes):
if minutes < 60:
return f"{minutes}m"
h, m = divmod(minutes, 60)
return f"{h}h {m}m" if m else f"{h}h"
def _fmt_time(ts_str):
return datetime.fromisoformat(ts_str.replace("Z", "+00:00")).strftime("%H:%M")
def write_postmortem_metrics_json(durations, outdir):
(outdir / "postmortem_metrics.json").write_text(json.dumps(durations, indent=2) + "\n")
def write_postmortem_md(data, durations, outdir):
lines = []
lines.append(f"# Postmortem — {data['title']}")
lines.append("")
lines.append(f"**Service:** {data['service']} ")
lines.append(f"**Author:** {data['author']} ")
if data.get("incident_id"):
lines.append(f"**Incident:** {data['incident_id']} ")
lines.append(f"**Date:** {data['generated_at']} ")
lines.append(f"**Severity:** {BADGE[data['severity']]} {data['severity']} — {data['severity_rationale']}")
lines.append("")
lines.append(data["summary"])
lines.append("")
impact = data["impact"]
lines.append("## Impact")
lines.append("")
lines.append("| Metric | Value |")
lines.append("|---|---|")
lines.append(f"| Time to detect | {_fmt_duration(durations['time_to_detect_min'])} |")
lines.append(f"| Time to mitigate | {_fmt_duration(durations['time_to_mitigate_min'])} |")
lines.append(f"| Time to resolve | {_fmt_duration(durations['time_to_resolve_min'])} |")
lines.append(f"| **Total duration** | **{_fmt_duration(durations['total_duration_min'])}** |")
lines.append(f"| Affected services | {', '.join(impact['affected_services'])} |")
lines.append(f"| Affected users | {impact['affected_users']} |")
lines.append(f"| Business impact | {impact['business_impact']} |")
lines.append("")
timeline = sorted(data.get("timeline", []), key=lambda e: e["timestamp"])
if timeline:
lines.append("## Timeline")
lines.append("")
lines.append("| Time | Phase | Event |")
lines.append("|---|---|---|")
for e in timeline:
actor = f" ({e['actor']})" if e.get("actor") else ""
lines.append(f"| {e['timestamp']} | {e['phase'].upper()} | {e['description']}{actor} |")
lines.append("")
root_causes = data.get("root_causes", [])
if root_causes:
lines.append("## Root Causes")
lines.append("")
for rc in root_causes:
lines.append(f"- **{rc['id']}** [{rc['category']}] {rc['description']} — _{rc['evidence']}_")
lines.append("")
contributing = data.get("contributing_factors", [])
if contributing:
lines.append("## Contributing Factors")
lines.append("")
for cf in contributing:
lines.append(f"- **{cf['id']}** [{cf['category']}] {cf['description']} — _{cf['evidence']}_")
lines.append("")
symptoms = data.get("symptoms", [])
if symptoms:
lines.append("## Symptoms")
lines.append("")
for s in symptoms:
lines.append(f"- {s['description']} — _{s['evidence']}_")
lines.append("")
went_well = data.get("what_went_well", [])
if went_well:
lines.append("## What Went Well")
lines.append("")
for w in went_well:
lines.append(f"- {w}")
lines.append("")
went_wrong = data.get("what_went_wrong", [])
if went_wrong:
lines.append("## What Went Wrong")
lines.append("")
for w in went_wrong:
lines.append(f"- {w}")
lines.append("")
action_items = sorted(data.get("action_items", []), key=lambda a: PRIORITY_ORDER.get(a["priority"], 99))
if action_items:
lines.append("## Action Items")
lines.append("")
lines.append("| Priority | Action | Owner | Due | Linked Cause |")
lines.append("|---|---|---|---|---|")
for ai in action_items:
lines.append(f"| {ai['priority']} | {ai['description']} | {ai['owner']} | {ai['due_date']} | {ai['linked_cause']} |")
lines.append("")
(outdir / "postmortem.md").write_text("\n".join(lines) + "\n")
def write_postmortem_brief(data, durations, outdir):
lines = []
lines.append(f"# Postmortem Brief — {data['title']} ({data['generated_at']})")
lines.append("")
lines.append(f"{BADGE[data['severity']]} **{data['severity']}** — {data['service']}, "
f"incident duration {_fmt_duration(durations['total_duration_min'])} "
f"(mitigated in {_fmt_duration(durations['time_to_mitigate_min'])})")
lines.append("")
root_causes = data.get("root_causes", [])
if root_causes:
lines.append("**Root cause:**")
lines.append(f"- {root_causes[0]['description']}")
lines.append("")
action_items = sorted(data.get("action_items", []), key=lambda a: PRIORITY_ORDER.get(a["priority"], 99))
top = [a for a in action_items if a["priority"] in ("P0", "P1")][:3]
if top:
lines.append("**Top action items:**")
for a in top:
lines.append(f"- [{a['priority']}] {a['description']} ({a['owner']}, due {a['due_date']})")
lines.append("")
(outdir / "postmortem_brief.md").write_text("\n".join(lines) + "\n")
def _chip(label, key, size="normal"):
fg, bg = CHIP_COLORS[key]
cls = "chip chip-lg" if size == "lg" else "chip"
return f'<span class="{cls}" style="color:{fg};background:{bg};">{html.escape(label)}</span>'
def _svg_duration_bar(durations):
"""A single bar split into detect/mitigate/resolve segments, each sized
proportional to its minutes and colored from the same phase palette used
everywhere else on the page. Same technique as sprint-slippage-predictor's
_svg_forecast_range: Python computes the layout, returns a plain SVG string.
"""
width, height = 640, 70
pad, bar_y, bar_h = 4, 30, 26
plot_w = width - 2 * pad
total = max(durations["total_duration_min"], 1)
segments = [
("time_to_detect_min", "detection"),
("time_to_mitigate_min", "mitigation"),
("time_to_resolve_min", "resolution"),
]
ticks = [("Started", pad)]
rects, labels = [], []
x = float(pad)
for key, phase in segments:
minutes = durations[key]
w = minutes / total * plot_w
fg, _ = CHIP_COLORS[phase]
rects.append(f'<rect x="{x:.1f}" y="{bar_y}" width="{max(w, 0):.1f}" height="{bar_h}" fill="{fg}" />')
if w >= 34:
labels.append(
f'<text x="{x + w / 2:.1f}" y="{bar_y + bar_h / 2 + 4:.1f}" font-size="11" '
f'text-anchor="middle" fill="#fff">{html.escape(_fmt_duration(minutes))}</text>'
)
x += w
ticks += [("Detected", pad + (durations["time_to_detect_min"] / total) * plot_w),
("Mitigated", pad + ((durations["time_to_detect_min"] + durations["time_to_mitigate_min"]) / total) * plot_w),
("Resolved", pad + plot_w)]
tick_lines = "".join(
f'<line x1="{tx:.1f}" y1="{bar_y - 4}" x2="{tx:.1f}" y2="{bar_y}" stroke="#9aa0a8" />'
for _, tx in ticks
)
# A dominant segment (e.g. a multi-day detection gap next to a same-day
# mitigation) can push several milestones within a few pixels of each
# other. Rather than let their text collide, merge labels that are too
# close to render legibly side by side into one "A / B" label -- the tick
# marks above stay at each label's true position either way, so nothing
# about the underlying numbers is misrepresented, only crowded text.
def _label_width(s):
return 6.3 * len(s) + 6
clusters = []
for label, tx in ticks:
if clusters:
grp_labels, grp_positions = clusters[-1]
required_gap = max(_label_width(grp_labels[-1]), _label_width(label)) * 0.85
if tx - grp_positions[-1] < required_gap:
grp_labels.append(label)
grp_positions.append(tx)
continue
clusters.append(([label], [tx]))
label_marks = []
for grp_labels, grp_positions in clusters:
cx = sum(grp_positions) / len(grp_positions)
anchor = "start" if cx <= pad + 2 else ("end" if cx >= pad + plot_w - 2 else "middle")
label_marks.append(
f'<text x="{cx:.1f}" y="{bar_y - 8}" font-size="10" text-anchor="{anchor}" fill="#6b7280">{html.escape(" / ".join(grp_labels))}</text>'
)
return (
f'<svg viewBox="0 0 {width} {height}" width="100%" height="{height}" '
f'role="img" aria-label="Incident duration broken into detect, mitigate, and resolve segments">'
+ tick_lines + "".join(label_marks) + "".join(rects) + "".join(labels) +
"</svg>"
)
def _svg_event_axis(data, durations):
"""A horizontal axis plotting every timeline[] event by its real timestamp,
colored by phase, with a native <title> tooltip on each dot -- no JS needed
for hover text. Same x_of(dt) linear-scale-closure technique as
sprint-slippage-predictor's _svg_forecast_range, keyed on datetime instead
of date since an incident's events span minutes, not days.
"""
esc = html.escape
width, height = 640, 84
pad = 20
timeline = sorted(data.get("timeline", []), key=lambda e: e["timestamp"])
start = datetime.fromisoformat(durations["started_at"].replace("Z", "+00:00"))
end = datetime.fromisoformat(durations["resolved_at"].replace("Z", "+00:00"))
span = max((end - start).total_seconds(), 1)
def x_of(dt):
return pad + (dt - start).total_seconds() / span * (width - 2 * pad)
y = height / 2 - 6
dots = []
for e in timeline:
ts = datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00"))
x = x_of(ts)
fg, _ = CHIP_COLORS[e["phase"]]
tooltip = f'{ts.strftime("%H:%M")} · {e["phase"]}: {e["description"]}'
dots.append(
f'<circle cx="{x:.1f}" cy="{y:.1f}" r="6" fill="{fg}"><title>{esc(tooltip)}</title></circle>'
)
return (
f'<svg viewBox="0 0 {width} {height}" width="100%" height="{height}" '
f'role="img" aria-label="Timeline of {len(timeline)} incident events, hover a dot for details">'
f'<line x1="{pad}" y1="{y:.1f}" x2="{width - pad}" y2="{y:.1f}" stroke="#d7dbe0" stroke-width="3" />'
+ "".join(dots) +
f'<text x="{pad}" y="{y + 26:.1f}" font-size="10" text-anchor="start" fill="#6b7280">{esc(start.strftime("%H:%M"))}</text>'
f'<text x="{width - pad}" y="{y + 26:.1f}" font-size="10" text-anchor="end" fill="#6b7280">{esc(end.strftime("%H:%M"))}</text>'
"</svg>"
)
def write_postmortem_html(data, durations, outdir):
esc = html.escape
impact = data["impact"]
timeline = sorted(data.get("timeline", []), key=lambda e: e["timestamp"])
root_causes = data.get("root_causes", [])
contributing = data.get("contributing_factors", [])
symptoms = data.get("symptoms", [])
went_well = data.get("what_went_well", [])
went_wrong = data.get("what_went_wrong", [])
action_items = sorted(data.get("action_items", []), key=lambda a: PRIORITY_ORDER.get(a["priority"], 99))
nav_sections = [
("impact", "Impact", True),
("timeline", "Timeline", bool(timeline)),
("root-causes", "Root Causes", bool(root_causes)),
("contributing-factors", "Contributing Factors", bool(contributing)),
("symptoms", "Symptoms", bool(symptoms)),
("lessons", "What Went Well / Wrong", bool(went_well or went_wrong)),
("action-items", "Action Items", bool(action_items)),
]
nav_links = "".join(
f' <li><a href="#{sid}">{esc(label)}</a></li>\n'
for sid, label, present in nav_sections if present
)
parts = []
parts.append(f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Postmortem — {esc(data['title'])}</title>
<style>
:root {{ color-scheme: light; }}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
padding: 2.5rem 1.25rem 4rem;
background: #f6f7f9;
color: #1a1d21;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
line-height: 1.5;
}}
.container {{
max-width: 1120px;
margin: 0 auto;
display: grid;
grid-template-columns: 200px minmax(0, 1fr);
gap: 2rem;
align-items: start;
}}
.side-nav {{ position: sticky; top: 2rem; }}
.side-nav ul {{ list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.15rem; }}
.side-nav li {{ margin: 0; }}
.side-nav a {{
display: block;
color: #40454c;
text-decoration: none;
font-size: 0.85rem;
padding: 0.4rem 0.65rem;
border-radius: 6px;
border-left: 3px solid transparent;
}}
.side-nav a:hover {{ background: #eceef1; }}
.side-nav a:focus-visible {{ outline: 2px solid #40454c; outline-offset: 2px; }}
.main {{ min-width: 0; }}
.card {{
background: #fff;
border: 1px solid #e3e5e8;
border-radius: 10px;
padding: 1.5rem 1.75rem;
margin-bottom: 1.25rem;
scroll-margin-top: 1.5rem;
}}
h1 {{ font-size: 1.5rem; margin: 0 0 0.25rem; }}
h2 {{ font-size: 1.05rem; margin: 0 0 0.85rem; color: #40454c; }}
.meta-line {{ color: #6b7280; font-size: 0.9rem; margin: 0 0 0.35rem; }}
.summary {{ margin: 0.75rem 0 0; }}
.chip {{
display: inline-block;
padding: 0.2rem 0.65rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 600;
letter-spacing: 0.02em;
white-space: nowrap;
}}
.chip-lg {{ padding: 0.35rem 1rem; font-size: 0.95rem; }}
.stat-row {{ display: flex; gap: 1rem; flex-wrap: wrap; }}
.stat {{ flex: 1 1 160px; }}
.stat .label {{ font-size: 0.78rem; color: #6b7280; text-transform: uppercase; letter-spacing: 0.03em; }}
.stat .value {{ font-size: 1.15rem; font-weight: 600; margin-top: 0.15rem; font-variant-numeric: tabular-nums; }}
.duration-bar {{ margin-top: 1.1rem; overflow-x: auto; }}
.event-axis {{ margin-bottom: 1.25rem; overflow-x: auto; }}
ul {{ margin: 0; padding-left: 1.25rem; }}
li {{ margin-bottom: 0.5rem; }}
li:last-child {{ margin-bottom: 0; }}
table {{ width: 100%; border-collapse: collapse; font-size: 0.92rem; }}
th, td {{ text-align: left; padding: 0.6rem 0.5rem; border-bottom: 1px solid #eceef1; vertical-align: top; }}
th {{ color: #6b7280; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.03em; font-weight: 600; }}
tr:last-child td {{ border-bottom: none; }}
.timeline {{ list-style: none; margin: 0; padding: 0; }}
.timeline li {{
display: grid;
grid-template-columns: 44px 20px 1fr;
column-gap: 0.75rem;
padding-bottom: 1.35rem;
margin-bottom: 0;
position: relative;
}}
.timeline li:last-child {{ padding-bottom: 0; }}
.tl-time {{ color: #6b7280; font-size: 0.8rem; text-align: right; padding-top: 0.15rem; font-variant-numeric: tabular-nums; }}
.tl-marker {{ position: relative; }}
.tl-marker::before {{
content: "";
position: absolute;
top: 0.3rem;
left: 50%;
width: 10px;
height: 10px;
margin-left: -5px;
border-radius: 50%;
background: currentColor;
}}
.timeline li:not(:last-child) .tl-marker::after {{
content: "";
position: absolute;
top: 1.1rem;
left: 50%;
bottom: -1.35rem;
width: 2px;
margin-left: -1px;
background: #e3e5e8;
}}
.timeline li.detection {{ color: #41464b; }}
.timeline li.diagnosis {{ color: #997404; }}
.timeline li.mitigation {{ color: #b25a00; }}
.timeline li.resolution {{ color: #0f5132; }}
.tl-actor {{ color: #6b7280; font-size: 0.8rem; margin-left: 0.35rem; }}
.tl-desc {{ margin: 0.4rem 0 0.5rem; color: #1a1d21; }}
.tl-quote {{
display: block;
margin: 0;
padding: 0.5rem 0.75rem;
border-left: 3px solid #e3e5e8;
background: #f6f7f9;
border-radius: 0 6px 6px 0;
}}
.evidence {{ color: #6b7280; font-size: 0.85rem; }}
@media (max-width: 720px) {{
.container {{ grid-template-columns: 1fr; }}
.side-nav {{ position: static; }}
.side-nav ul {{ flex-direction: row; flex-wrap: wrap; gap: 0.4rem; background: #fff; border: 1px solid #e3e5e8; border-radius: 10px; padding: 0.75rem 0.85rem; margin-bottom: 1.25rem; }}
.side-nav a {{ border-left: none; padding: 0.3rem 0.6rem; }}
}}
@media (prefers-reduced-motion: no-preference) {{
html {{ scroll-behavior: smooth; }}
}}
</style>
</head>
<body>
<div class="container">
<nav class="side-nav" aria-label="Postmortem sections">
<ul>
{nav_links} </ul>
</nav>
<div class="main">
<div class="card">
<h1>{esc(data['title'])}</h1>
<p class="meta-line">{esc(data['service'])} · {esc(data['author'])} · {esc(data['generated_at'])}</p>
{_chip(data['severity'], data['severity'], size="lg")}
<p class="summary">{esc(data['summary'])}</p>
<p class="summary evidence">{esc(data['severity_rationale'])}</p>
</div>
<div class="card" id="impact">
<h2>Impact</h2>
<div class="stat-row">
<div class="stat"><div class="label">Time to detect</div><div class="value">{esc(_fmt_duration(durations['time_to_detect_min']))}</div></div>
<div class="stat"><div class="label">Time to mitigate</div><div class="value">{esc(_fmt_duration(durations['time_to_mitigate_min']))}</div></div>
<div class="stat"><div class="label">Time to resolve</div><div class="value">{esc(_fmt_duration(durations['time_to_resolve_min']))}</div></div>
<div class="stat"><div class="label">Total duration</div><div class="value">{esc(_fmt_duration(durations['total_duration_min']))}</div></div>
</div>
<div class="duration-bar">{_svg_duration_bar(durations)}</div>
<p class="summary">Affected: {esc(', '.join(impact['affected_services']))} — {esc(impact['affected_users'])}. {esc(impact['business_impact'])}</p>
</div>
""")
if timeline:
parts.append(f' <div class="card" id="timeline">\n <h2>Timeline</h2>\n <div class="event-axis">{_svg_event_axis(data, durations)}</div>\n <ol class="timeline">\n')
for e in timeline:
actor = f'<span class="tl-actor">{esc(e["actor"])}</span>' if e.get("actor") else ""
parts.append(
f' <li class="{esc(e["phase"])}">\n'
f' <div class="tl-time">{esc(_fmt_time(e["timestamp"]))}</div>\n'
f' <div class="tl-marker"></div>\n'
f' <div class="tl-content">\n'
f' {_chip(e["phase"].upper(), e["phase"])}{actor}\n'
f' <p class="tl-desc">{esc(e["description"])}</p>\n'
f' <blockquote class="evidence tl-quote">{esc(e["evidence"])}</blockquote>\n'
f' </div>\n'
f' </li>\n'
)
parts.append(" </ol>\n </div>\n")
if root_causes:
parts.append(' <div class="card" id="root-causes">\n <h2>Root Causes</h2>\n <ul>\n')
for rc in root_causes:
parts.append(
f" <li><strong>{esc(rc['id'])}</strong> [{esc(rc['category'])}] {esc(rc['description'])}<br>"
f"<span class=\"evidence\">{esc(rc['evidence'])}</span></li>\n"
)
parts.append(" </ul>\n </div>\n")
if contributing:
parts.append(' <div class="card" id="contributing-factors">\n <h2>Contributing Factors</h2>\n <ul>\n')
for cf in contributing:
parts.append(
f" <li><strong>{esc(cf['id'])}</strong> [{esc(cf['category'])}] {esc(cf['description'])}<br>"
f"<span class=\"evidence\">{esc(cf['evidence'])}</span></li>\n"
)
parts.append(" </ul>\n </div>\n")
if symptoms:
parts.append(' <div class="card" id="symptoms">\n <h2>Symptoms</h2>\n <ul>\n')
for s in symptoms:
parts.append(f" <li>{esc(s['description'])}<br><span class=\"evidence\">{esc(s['evidence'])}</span></li>\n")
parts.append(" </ul>\n </div>\n")
if went_well or went_wrong:
parts.append(' <div class="card" id="lessons">\n <h2>What Went Well / Wrong</h2>\n')
if went_well:
parts.append(" <p><strong>Went well</strong></p>\n <ul>\n")
for w in went_well:
parts.append(f" <li>{esc(w)}</li>\n")
parts.append(" </ul>\n")
if went_wrong:
parts.append(" <p><strong>Went wrong</strong></p>\n <ul>\n")
for w in went_wrong:
parts.append(f" <li>{esc(w)}</li>\n")
parts.append(" </ul>\n")
parts.append(" </div>\n")
if action_items:
parts.append(' <div class="card" id="action-items">\n <h2>Action Items</h2>\n <table>\n')
parts.append(" <tr><th>Priority</th><th>Action</th><th>Owner</th><th>Due</th><th>Linked Cause</th></tr>\n")
for ai in action_items:
parts.append(
f" <tr><td>{_chip(ai['priority'], ai['priority'])}</td><td>{esc(ai['description'])}</td>"
f"<td>{esc(ai['owner'])}</td><td>{esc(ai['due_date'])}</td><td>{esc(ai['linked_cause'])}</td></tr>\n"
)
parts.append(" </table>\n </div>\n")
parts.append(" </div>\n</div>\n</body>\n</html>\n")
(outdir / "postmortem.html").write_text("".join(parts))
def main():
parser = argparse.ArgumentParser(description="Render a postmortem.json into a postmortem doc, brief, and HTML page.")
parser.add_argument("postmortem_json", help="Path to postmortem.json")
parser.add_argument("--outdir", required=True, help="Output directory")
args = parser.parse_args()
data = load_postmortem(args.postmortem_json)
validate_linked_causes(data)
validate_timeline_monotonic(data)
validate_impact_monotonic(data)
durations = compute_durations(data)
outdir = Path(args.outdir)
outdir.mkdir(parents=True, exist_ok=True)
write_postmortem_metrics_json(durations, outdir)
write_postmortem_md(data, durations, outdir)
write_postmortem_brief(data, durations, outdir)
write_postmortem_html(data, durations, outdir)
print(f"Severity: {data['severity']} — total duration {_fmt_duration(durations['total_duration_min'])} — output in {outdir}")
if __name__ == "__main__":
main()