#!/usr/bin/env python3
"""
Automated Postmortem Quality Reviewer
=====================================
This tool evaluates incident postmortem reports using:
- **NLP Heuristics**: Rule-based checks for readability, specificity, blamelessness, and structure.
- **Completeness Scoring**: Checklist-based scoring for essential postmortem sections.
- **Coaching Feedback Loops**: Iterative review cycle with targeted suggestions for improvement.
Usage:
python postmortem_reviewer.py
It runs interactively: paste your postmortem text, get score + feedback, revise and re-submit until satisfied.
Assumptions (SRE-inspired postmortem structure):
- Blameless, clear, actionable, complete.
- Key sections: Summary, Timeline, Root Cause, Impact, Contributing Factors, Resolution/Actions, Prevention, Lessons Learned.
Dependencies (pip install textstat vaderSentiment):
- textstat: Readability scores.
- vaderSentiment: Sentiment analysis for blamelessness.
- Standard Python libs for heuristics.
Author: Sherlock (Trailblazer Labs)
"""
import re
import sys
import textstat
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from typing import Dict, List, Tuple
class PostmortemReviewer:
def __init__(self):
self.analyzer = SentimentIntensityAnalyzer()
self.section_keywords = {
'summary': ['summary', 'overview', 'incident', 'outage'],
'timeline': ['timeline', 'chronology', 'events?', 'at \d{1,2}:\d{2}', 't-\d+'],
'root_cause': ['root cause', 'rc', 'caused by', 'failure mode'],
'impact': ['impact', 'affected', 'downtime', 'users?', 'severity'],
'contributing_factors': ['contributing', 'factors?', 'prerequisites'],
'resolution': ['resolved', 'mitigation', 'actions? taken', 'fixed'],
'prevention': ['prevent', 'future', 'remediation', 'improvements?'],
'lessons': ['lessons', 'learned', 'takeaways']
}
self.weights = {
'summary': 0.1, 'timeline': 0.15, 'root_cause': 0.15,
'impact': 0.1, 'contributing_factors': 0.1,
'resolution': 0.1, 'prevention': 0.15, 'lessons': 0.15
}
def preprocess_text(self, text: str) -> str:
"""Normalize text: lowercase, remove extra whitespace."""
text = re.sub(r'\s+', ' ', text.lower().strip())
return text
def check_completeness(self, text: str) -> Dict[str, float]:
"""Score presence of key sections (0-1 per section)."""
scores = {}
words = text.split()
total_words = len(words)
for section, keywords in self.section_keywords.items():
hits = sum(1 for kw in keywords if re.search(r'\b' + re.escape(kw) + r'\b', text, re.IGNORECASE))
coverage = min(hits / max(len(keywords), 1), 1.0)
# Bonus for substantial content near keywords
if coverage > 0:
coverage += min(0.3, sum(len(w) for w in words[:50]) / total_words) # Rough depth check
scores[section] = min(coverage, 1.0)
return scores
def nlp_heuristics(self, text: str) -> Dict[str, float]:
"""NLP-based quality heuristics (0-1 scores)."""
flesch = textstat.flesch_reading_ease(text)
readability = max(0, min(1, (flesch - 30) / 70)) # Target 60-90 for technical docs
# Specificity: Count metrics (numbers, durations, metrics)
num_specificity = len(re.findall(r'\b\d+(?:\.\d+)?(?:s?|ms?|min|hr|%|kb|mb|gb)\b|\b\d+ users?\b', text))
specificity = min(1.0, num_specificity / 5) # Aim for 5+ specifics
# Blamelessness: Low compound negativity, avoid blame words
sentiment = self.analyzer.polarity_scores(text)
blame_words = len(re.findall(r'\b(?:fault|blame|human error|developer|engineer)\b', text, re.IGNORECASE))
blameless = max(0, (sentiment['compound'] + 1) / 2 - blame_words / 20)
# Structure: Headings, bullets (heuristic)
structure = 0.2 * bool(re.search(r'###?', text)) + 0.3 * bool(re.search(r'[-*•]\s', text)) + 0.5 * (len(re.findall(r'\n\n', text)) > 5)
# Conciseness: Avg sentence length
sentences = textstat.sentence_count(text)
avg_sent_len = len(text.split()) / max(sentences, 1)
conciseness = max(0, 1 - (abs(avg_sent_len - 20) / 20)) # Target ~20 words/sent
return {
'readability': readability,
'specificity': specificity,
'blameless': blameless,
'structure': structure,
'conciseness': conciseness
}
def compute_overall_score(self, completeness: Dict[str, float], heuristics: Dict[str, float]) -> float:
"""Weighted overall score (0-100)."""
comp_score = sum(completeness[s] * self.weights[s] for s in completeness)
heur_score = sum(heuristics.values()) / len(heuristics) * 0.4 # Heuristics 40% weight
return round((comp_score * 0.6 + heur_score) * 100, 1)
def generate_feedback(self, completeness: Dict[str, float], heuristics: Dict[str, float], overall: float) -> List[str]:
"""Coaching feedback with prioritized suggestions."""
feedback = [f"Overall Score: {overall}/100"]
if overall < 60:
feedback.append("🚨 Needs major revisions.")
elif overall < 80:
feedback.append("⚠️ Good start, refine further.")
else:
feedback.append("✅ Production-ready!")
# Completeness gaps
low_sections = [s for s, sc in completeness.items() if sc < 0.7]
if low_sections:
feedback.append("Missing/Weak Sections:")
for s in low_sections:
feedback.append(f" - {s.replace('_', ' ').title()}: Add keywords like {', '.join(self.section_keywords[s][:3])} and detailed content.")
# Heuristic coaching
low_heur = {k: v for k, v in heuristics.items() if v < 0.7}
if low_heur:
feedback.append("Quality Improvements:")
if low_heur.get('readability', 1) < 0.7:
feedback.append(" - Improve readability: Aim for Flesch 60-90 (shorter sentences, simpler words).")
if low_heur.get('specificity', 1) < 0.7:
feedback.append(" - Add specifics: Include numbers (e.g., '5min downtime, 10k users affected').")
if low_heur.get('blameless', 1) < 0.7:
feedback.append(" - Promote blamelessness: Focus on systems/processes, avoid 'fault'/'blame'.")
if low_heur.get('structure', 1) < 0.7:
feedback.append(" - Enhance structure: Use headings (###), bullets (-).")
if low_heur.get('conciseness', 1) < 0.7:
feedback.append(" - Be concise: Target 15-25 words per sentence.")
feedback.append("\nRevise and paste updated text below:")
return feedback
def review(self, text: str) -> Tuple[float, List[str]]:
"""Full review pipeline."""
processed = self.preprocess_text(text)
completeness = self.check_completeness(processed)
heuristics = self.nlp_heuristics(text)
overall = self.compute_overall_score(completeness, heuristics)
feedback = self.generate_feedback(completeness, heuristics, overall)
return overall, feedback
def main():
reviewer = PostmortemReviewer()
print("=== Automated Postmortem Quality Reviewer (Sherlock by Trailblazer Labs) ===\n")
print("Paste your postmortem report (end with EOF: Ctrl+D or 'END' on a line).\n")
while True:
try:
lines = []
while True:
line = input()
if line.strip().upper() == 'END':
break
lines.append(line)
text = '\n'.join(lines).strip()
if not text:
print("No text provided. Try again.\n")
continue
score, feedback = reviewer.review(text)
print('\n' + '\n'.join(feedback) + '\n')
if score >= 90:
print("🎉 Excellent! Ready for publication.\n")
break
else:
print("Ready to revise? Paste updated version (or 'END' to quit).\n")
except EOFError:
print("\nGoodbye!")
sys.exit(0)
except KeyboardInterrupt:
print("\n\nSession ended.")
sys.exit(0)
if __name__ == "__main__":
main()
Quick Start
Install deps: pip install textstat vaderSentiment
Run: python postmortem_reviewer.py
Paste a postmortem example (e.g., from Google SRE book), hit Enter, type END.
Get score, feedback, revise iteratively.
Example Usage & Output
Input Postmortem Snippet:
code
### Incident Summary
Outage at 14:00 UTC.
Timeline:
- 14:00: Service down
- 14:30: Fixed by restart.
Root Cause: Bad deploy.
Impact: 1k users affected for 30min.
Lessons: Test more.
Sample Output:
code
Overall Score: 65.2/100
⚠️ Good start, refine further.
Missing/Weak Sections:
- Contributing factors: Add keywords like contributing, factors, prerequisites and detailed content.
- Prevention: Add keywords like prevent, future, remediation, improvements and detailed content.
Quality Improvements:
- Improve readability: Aim for Flesch 60-90 (shorter sentences, simpler words).
- Add specifics: Include numbers (e.g., '5min downtime, 10k users affected').
- Promote blamelessness: Focus on systems/processes, avoid 'fault'/'blame'.
Revise and paste updated text below:
This tool is production-grade heuristics-based, extensible (add ML via spaCy/HuggingFace), and enforces SRE best practices through coaching loops! 🕵️♂️