We are going to create a post-incident automation backlog generator.
The idea is to take the output from a post-incident review (like a timeline, actions, etc.) and automatically generate a backlog of tasks (stories/bugs) that need to be addressed to prevent recurrence or improve processes.
Steps:
We assume we have a list of actions or findings from the incident. Each action/finding might have:
A description of what happened or what needs to be fixed.
The person or team that is likely responsible (owner).
A priority (which we might derive from the incident impact or a classification).
We want to classify the actions into categories (like: code fix, process improvement, training, infrastructure, etc.)
We can use a set of keywords or a machine learning classifier, but for simplicity and given the context, let's assume we have a rule-based classifier.
We want to assign an owner. We might have a mapping from categories to teams/owners, but also we might have the owner mentioned in the text.
We want to calculate an aging (how urgent) based on:
The incident severity (if we have that) or
The category (some categories are more urgent) or
The time since the incident.
We output a list of backlog items (with title, description, owner, category, aging, and maybe a due date based on aging).
However, note: the problem says "automation backlog generator", so we are generating tasks automatically from incident data.
Let's design:
Input:
incident_data: a dictionary or a list of dictionaries, each representing an action/finding from the incident.
Example structure:
{
"id": 1,
"description": "We found that the database connection pool was too small during the incident.",
"impact": "high", # or we might have a separate incident severity
"suggested_by": "John Doe",
"timestamp": "2023-10-01T12:00:00Z"
}
We might also have incident metadata: severity, date, etc.
Output:
A list of backlog items (tasks) in a structured format (maybe JSON or a list of dictionaries) that can be imported into a backlog tool (like Jira, GitHub Issues, etc.)
Steps in code:
For each action/finding in the incident_data:
a. Classify the action into a category (using a rule-based approach with keywords, or if we have a trained model, use that).
b. Determine the owner:
- If the description mentions a team or person, extract that? Or we have a mapping from category to default owner.
- Alternatively, we can have a configuration that maps categories to owners, and if the description mentions a specific person, we can override?
- For simplicity, let's have a default owner per category and also allow an explicit owner in the action data if provided.
c. Calculate aging:
- We can set a base aging based on the incident severity and category.
- Also, if the action has been open for a while (if we have a created date for the action and current date) we adjust.
d. Generate a title: maybe the first sentence or a summary of the description.
e. Generate a description: the original description plus maybe some context (like incident id, date, etc.)
We might also want to group similar actions? But the problem says "backlog generator", so we are generating one task per action.
If no keywords match, we can have a default category: "Other" and default owner: "Engineering Manager"
Aging calculation:
Let's define a base aging (in days) for each category and incident severity.
code
We can have:
severity_levels: "critical", "high", "medium", "low"
For each category, we assign a base aging factor (multiplier) and then adjust by severity.
Alternatively, we can set a target resolution time (in days) for each combination.
Let's define a dictionary for target days by severity and category:
Example:
target_days = {
"critical": {
"Infrastructure": 1,
"Code Bug": 1,
"Process Improvement": 3,
"Training": 7,
"Monitoring": 1,
"Security": 1,
"Other": 3
},
"high": {
"Infrastructure": 3,
"Code Bug": 3,
"Process Improvement": 7,
"Training": 14,
"Monitoring": 3,
"Security": 3,
"Other": 7
},
"medium": {
"Infrastructure": 7,
"Code Bug": 7,
"Process Improvement": 14,
"Training": 30,
"Monitoring": 7,
"Security": 7,
"Other": 14
},
"low": {
"Infrastructure": 14,
"Code Bug": 14,
"Process Improvement": 30,
"Training": 60,
"Monitoring": 14,
"Security": 14,
"Other": 30
}
}
Then, for each action:
- We need to know the incident severity (from incident metadata) and the category of the action.
- The aging (due in X days) = target_days[severity][category]
But note: the action might have been created some time after the incident? We are generating the backlog now, so we set the due date as today + target_days.
3. We assume the incident has a severity and a date.
We also might want to set the backlog item's priority based on the same target days? Or we can set priority as:
if target_days <= 3: "critical"
elif target_days <= 7: "high"
elif target_days <= 14: "medium"
else: "low"
But note: the incident severity already implies a priority. We can set the backlog priority to the same as incident severity?
However, note that the category might adjust. But in our target_days we are already adjusting by severity and category.
Alternatively, we can set the priority of the backlog item to the incident severity? But that might not be fine-grained.
Let's keep it simple: we set the backlog item's priority as the incident severity?
But then we are not using the category to adjust.
We can do:
priority = incident_severity # but then we lose the category adjustment.
Alternatively, we can map the target_days to a priority:
Then we take the target_days and map to the closest in the map?
However, note that the target_days are discrete per severity and category.
Let me re-think: the incident severity is the overall severity of the incident. But each action might have a different urgency.
Actually, in the incident, the overall severity is known. We are generating actions that are required to prevent recurrence.
The urgency of each action might be based on the incident severity and the category.
So I think using the target_days (which is based on both) is a good way to set the due date, and then we can set the priority of the backlog item as:
This way, we are using the combined severity and category to set the priority.
We also need to generate a unique id for the backlog item? Maybe we can use the action id and incident id.
We output a list of dictionaries with:
title
description (including incident context: incident id, date, severity, and the original description)
category
owner
due_date (calculated from today + target_days)
priority (derived from target_days as above)
labels: maybe we add the category and incident id as labels?
Let's code accordingly.
Steps for each action:
Classify:
For each category, check if any keyword in the action's description (lowercased) is present.
If multiple categories match, we can take the first? Or the one with the most keywords?
Let's do: we count the number of keywords from each category that appear in the description, and pick the category with the highest count.
If tie, pick the first one in the list of categories (order of categories as defined above).
If none match, use "Other".
Owner:
We have a mapping from category to default_owner (as above).
But if the action has an explicit owner (maybe from the data, if we have an 'owner' field), we use that.
Target days:
We have incident_severity (from incident metadata) and the category we found.
Then target_days = target_days_dict[incident_severity][category]
Title: we can take the first 50 characters of the description, or if the description is long, we can summarize?
Let's just take the first sentence (until the first period) and if that's too short, take first 50 chars.
Description:
We can format as:
Incident: [incident_id] ([incident_date], Severity: [incident_severity])
Action: [original description]
where incident_data is a list of actions (each action is a dict with at least 'description' and maybe 'owner' if explicit)
incident_metadata is a dict with at least 'id', 'date', 'severity'
Returns a list of backlog items (dicts) with keys:
'title', 'description', 'category', 'owner', 'due_date', 'priority', 'labels'
We assume the incident_metadata has:
'id': string or int,
'date': string in ISO format or datetime,
'severity': one of the keys in target_days_dict.
We also assume the actions in incident_data might have:
'id': optional, if not we generate one as action index?
'description': string,
'owner': optional string.
Steps:
code
However, note: we might have duplicate actions? We are not deduplicating.
Also, note: the due_date is calculated from today. But if we are generating the backlog later, we might want to set the due_date relative to the incident date?
But the problem says "aging", which might mean how urgent it is now. So using today is fine.
But what if the incident was a week ago? Then the due date should be sooner?
Actually, the target_days are meant to be the total time from the incident to fix?
Or from now?
Let's clarify: the incident happened on incident_date. We are generating the backlog on today.
The target_days we set is the total time we want to fix the action after the incident?
Or the time from now?
Since we are generating the backlog now, we want the due date to be in the future.
If we set the due date as incident_date + target_days, then if the incident was a week ago and target_days is 3, then we are already late.
So we have two options:
code
Option 1: due_date = incident_date + target_days -> then we are setting a fixed deadline from the incident.
Option 2: due_date = today + remaining_days, where remaining_days = max(0, target_days - days_since_incident)
Which one is more common? In post-incident, we usually set a deadline relative to the incident date.
But if we are late, we might want to adjust.
However, the problem says "aging", which might mean we are looking at how old the action is?
So we might want to set the due date as incident_date + target_days, and then if today is past that, it's overdue.
But in the backlog, we want to set the due date as the date by which we plan to complete.
If the incident was a week ago and the target was 3 days, then we are already 4 days overdue.
We might want to set the due date to yesterday? Or we set the due date to the original target and mark it as overdue.
That way, if we are already past the original target, we set the due date to today? That doesn't make sense.
Actually, in backlog items, the due date is the date we plan to complete.
If we are already late, we should set the due date to a time in the past? But that might not be useful.
Maybe we don't set a due date but set an "aging" field that says how many days overdue?
Let's change: instead of due_date, we can have:
code
created_date: today (when we generate the backlog)
due_date: incident_date + target_days [this is the original deadline]
days_overdue: max(0, (today - (incident_date + target_days)).days)
But then the backlog tool might not use days_overdue.
Alternatively, we can set the due date as the original deadline and let the tool show it as overdue if passed.
Then we don't use today in the due_date calculation.
However, if we are generating the backlog a long time after the incident, we might have missed the due date.
But that's the reality: we are generating tasks that are already overdue? Then we should set the due date in the past and let the team know they are late.
Then the priority we set based on target_days might not match the actual urgency now?
But the target_days are set based on the incident severity and category, and we are using the same target_days to set due_date.
So the priority is based on the original target_days, not on how overdue it is.
Alternatively, we can adjust the priority if it's overdue? But let's keep it simple.
And then we calculate the days overdue as (today - due_date).days if positive, else 0? But we don't have that in the backlog item.
We can add an 'overdue' boolean? Or we can just set the due date and let the tool handle it.
Given the problem says "aging", we might want to include the age of the action?
Actually, the aging might be the number of days since the incident until now?
But the problem says: "classifying actions, owners, and aging."
Aging might be the time that has passed since the incident? Or the time left until due date?
I think aging in backlog terms is how old the task is (since creation) or how long it's been open?
But we are generating the backlog now, so the task is just being created. The aging might be the time since the incident?
Let's define:
code
aging = (today - incident_date).days
But that would be the same for all tasks in the same incident?
Alternatively, we can have:
code
aging = (today - due_date).days # which would be negative if not due, positive if overdue.
But the problem says "aging", which typically means how old the task is. Since we are creating the task now, the task's age is 0?
I think we are misinterpreting. The post-incident backlog generator is for actions that need to be taken after the incident.
The aging might refer to the urgency (like how soon we need to do it) which we are capturing in due_date and priority.
Let me re-read: "Implement a post-incident automation backlog generator: classifying actions, owners, and aging."
Maybe "aging" means we categorize how urgent the action is (like the target days) and we call that aging?
In some contexts, "aging" means the time that has passed since the incident for which the action is required.
But in backlog, we usually have due dates and priorities.
Since the problem says "aging", let's output:
code
aging = target_days # the number of days we have to complete the action from the incident date?
And then we can set the priority based on days_until_due?
But we already set priority based on target_days (which is fixed per category and severity).
Let's stick to:
code
due_date = incident_date + timedelta(days=target_days)
priority = based on target_days (as above)
And we can also output:
code
days_until_due = (due_date - today).days # can be negative
But the problem says "aging", so maybe we want to show how many days have passed since the incident?
I think we should clarify: in the context of post-incident, the actions are generated from the incident and we want to know how soon we must act.
So I think "aging" here is the target resolution time (target_days) or the due date.
Since the problem says "aging", let's output:
code
aging = target_days # the number of days we have to complete the action from the incident.
But then it's not aging, it's a time budget.
Given the ambiguity, let's output:
code
due_date (as above)
and also an 'aging' field which is the target_days (so we know the original time budget).
Alternatively, we can output:
code
'aging': (today - incident_date).days # days since the incident
But then for a new incident, aging is 0, for an old incident, aging is high.
That might be useful to see which incident's actions are getting old.
But note: we are generating for one incident. So all actions in this backlog generation will have the same incident_date.
So aging by incident would be the same for all. So that doesn't help.
So I think aging is per action? But the incident date is the same.
Maybe we want to show how many days have passed since the action was identified?
But we don't have an action identification date, we are generating now.
Therefore, I think we should not include an aging field, but we have due_date and priority.
However, the problem explicitly says "aging". So let's include:
code
aging = target_days # as the time we have to fix, but that's not aging.
This way, if we have 2 days left, it's high, if 10 days left, it's low.
But note: the original target_days might be 30 for a low category, but if we are 20 days in, then aging=10, which is medium?
But the category might be low, so we are giving it a higher priority because we are running out of time.
That might be acceptable.
Alternatively, we can combine:
code
base_priority from target_days, then if aging is negative, bump to critical.
Let's do:
code
base_priority = ... from target_days (as originally)
if aging < 0:
priority = "critical"
else:
priority = base_priority
That way, we don't change the priority if we are not overdue, even if we are close to the due date.
But then a task due tomorrow (aging=1) and a task due in 10 days (aging=10) would have the same priority if they have the same base_priority?
That might not reflect the current urgency.
Given the trade-offs, I think we should use aging (days until due) to set the priority, because that reflects the current urgency.
So let's set priority based on aging (days until due) as above.
But then we lose the original severity and category?
Actually, the original target_days are already factored into aging (because due_date = incident_date + target_days).
So if the incident was severe and the category critical, target_days is small, so aging (if today is close to incident_date) is small.
But if the incident was a long time ago, then even if target_days is small, aging might be negative (overdue) or small positive.
So using aging (days until due) is a good measure of current urgency.
We calculate:
incident_date = parse incident_metadata['date']
due_date = incident_date + timedelta(days=target_days)
aging = (due_date - today).days
Then set priority based on aging.
But note: the target_days are based on incident severity and category. So if the incident was critical and category infrastructure, target_days=1, so due_date is incident_date+1.
If the incident was 10 days ago, then aging = (incident_date+1 - today) = (incident_date+1) - (incident_date+10) = -9, so critical (overdue).
That makes sense.
Let's code accordingly.
We'll adjust the code.
Also, note: we are using the category to get the target_days. But what if the category is "Other"? We have a target for "Other" in each severity.
We'll assume the target_days_dict has all categories.
Let's code the function.
We assume the incident_metadata has:
'id': any,
'date': string in ISO format (YYYY-MM-DD or with time, we take the date part),
'severity': string, one of: 'critical', 'high', 'medium', 'low'
If the severity is not in target_days_dict, we default to 'medium'.
If the category is not in the severity dict, we default to 'Other'.
Let's code accordingly.
We'll also note: the incident_date might have time, but we only need the date.
Example: incident_metadata['date'] = "2023-10-01T12:00:00Z"
We can do:
incident_date = datetime.fromisoformat(incident_metadata['date']).date()
But note: fromisoformat might not work for 'Z'? We can use:
code
from datetime import datetime
import dateutil.parser
incident_date = dateutil.parser.parse(incident_metadata['date']).date()
But to avoid extra dependency, if we are sure it's ISO 8601, we can use:
However, let's use dateutil if allowed? Or we can use:
code
from datetime import datetime
import re
# Remove the Z and replace with +00:00 if needed
date_str = incident_metadata['date']
if date_str.endswith('Z'):
date_str = date_str[:-1] + '+00:00'
incident_date = datetime.fromisoformat(date_str).date()
But let's assume the date string is in a format that fromisoformat can handle (Python 3.7+). We'll just try.
if 'Z' in incident_metadata['date']:
# Replace Z with +00:00
date_str = incident_metadata['date'].replace('Z', '+00:00')
incident_date = datetime.fromisoformat(date_str).date()
else:
incident_date = datetime.fromisoformat(incident_metadata['date']).date()
Let's code accordingly.
I'll help you implement a post-incident automation backlog generator that classifies actions, assigns owners, and calculates aging for follow-up tasks. This solution includes classification logic, ownership mapping, and aging calculations.
python
This implementation provides:
Key Features:
1. Classification Engine
Rule-based keyword matching across 8 categories
Customizable keyword lists per category
Automatic fallback to "Other" category
2. Owner Assignment
Default mapping by category
Support for explicit owner specification
Configurable team assignments
3. Aging Calculations
Days since detection
Days until target resolution
Overdue detection
Aging status (Overdue/Urgent/Due Soon/On Track)
4. Priority Determination
Based on incident severity + category criticality
Auto-escalation for overdue items
Adjusts for security/critical code bugs
5. Target Resolution Matrix
Configurable days based on severity/category combinations
Different timeboxes for different action types
Example: Security issues in critical incidents: 1 day
# Run daily to generate aging reports
report = analyzer.get_aging_report()
send_report_to_slack(report)
Jira/GitHub Integration:
python
for item in backlog_items:
create_jira_ticket(
summary=item.title,
description=item.description,
assignee=item.owner,
priority=item.priority,
labels=[item.category.value, f"incident-{item.incident_id}"]
)
Custom Classification:
python
# Extend with ML classification
def enhanced_classify(description):
# First try rule-based
category = analyzer.classify_action(description)
# Then ML model for uncertain cases
if category == ActionCategory.OTHER:
category = ml_model.predict(description)
return category
Configuration Options:
Modify keyword lists in CATEGORY_KEYWORDS
Adjust owner mapping in OWNER_MAPPING
Customize target days in TARGET_DAYS_MATRIX
Change aging thresholds in _get_aging_status()
Add new categories by extending ActionCategory enum
Extensibility Points:
Add new classification methods (regex patterns, ML models)
Integrate with CMDB for dynamic owner assignment
Add SLA calculations based on business hours
Include effort estimates (story points/hours)
Add risk scoring based on incident impact
Support multiple incident sources (PagerDuty, Opsgenie, etc.)
This solution provides a production-ready foundation that can be integrated into your incident management workflow, with clear separation between classification logic, ownership assignment, and aging calculations.
target_days_dict = { ... } as above.
category_keywords = {
"Infrastructure": ["server", "database", "network", "connection pool", "disk", "memory", "cpu", "load balancer"],
"Code Bug": ["bug", "error", "exception", "null pointer", "fix", "code change", "patch"],
"Process Improvement": ["process", "procedure", "documentation", "runbook", "playbook", "on-call", "escalation"],
"Training": ["train", "training", "knowledge", "session", "workshop"],
"Monitoring": ["monitor", "alert", "metric", "dashboard", "threshold"],
"Security": ["security", "vulnerability", "penetration", "access control", "auth", "authentication"]
}
default_owner_by_category = {
"Infrastructure": "Infrastructure Team",
"Code Bug": "Development Team",
"Process Improvement": "Operations Team",
"Training": "People Operations",
"Monitoring": "Monitoring Team",
"Security": "Security Team",
"Other": "Engineering Manager"
}
For each action in incident_data:
# Classify
desc_lower = action['description'].lower()
category_scores = {cat: 0 for cat in category_keywords}
for cat, keywords in category_keywords.items():
for kw in keywords:
if kw in desc_lower:
category_scores[cat] += 1
# If no keywords matched, we set category to "Other"
if max(category_scores.values()) == 0:
category = "Other"
else:
# Get the category with the highest score, if tie, pick the first one with that score (we'll sort by score and then by the order of categories in category_keywords)
# But note: we want to preserve the order of categories as in category_keywords for ties?
# Let's get the max score and then among the categories with that score, pick the first one in the order of category_keywords.
max_score = max(category_scores.values())
for cat in category_keywords: # This order is the order we defined
if category_scores[cat] == max_score:
category = cat
break
# Owner
if 'owner' in action and action['owner']:
owner = action['owner']
else:
owner = default_owner_by_category[category]
# Target days
severity = incident_metadata['severity']
if severity not in target_days_dict:
# Default to 'medium' if severity not found?
severity = 'medium'
if category not in target_days_dict[severity]:
# Use 'Other' if category not found in that severity? But we have all categories in the dict.
category_for_target = 'Other'
else:
category_for_target = category
target_days = target_days_dict[severity][category_for_target]
# Due date
from datetime import datetime, timedelta
today = datetime.now().date()
due_date = today + timedelta(days=target_days)
# Priority
if target_days <= 1:
priority = "critical"
elif target_days <= 3:
priority = "high"
elif target_days <= 7:
priority = "medium"
else:
priority = "low"
# Title
# Take the first sentence or first 50 chars
first_sentence = action['description'].split('.')[0]
if len(first_sentence) > 50:
title = first_sentence[:50] + "..."
else:
title = first_sentence
# Description
incident_id = incident_metadata['id']
incident_date = incident_metadata['date']
description = f"Incident: {incident_id} ({incident_date}, Severity: {severity})\n\nAction: {action['description']}"
# Labels
labels = [category, f"incident-{incident_id}"]
backlog_item = {
'title': title,
'description': description,
'category': category,
'owner': owner,
'due_date': due_date.isoformat(), # string in ISO format
'priority': priority,
'labels': labels
}
# If the action has an id, we can include it? Maybe as an external id?
if 'id' in action:
backlog_item['external_id'] = action['id']
Return the list of backlog items.
"""
Post-Incident Automation Backlog Generator
Automatically generates actionable backlog items from incident retrospectives
"""
import json
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
from enum import Enum
import re
class ActionCategory(Enum):
"""Classification categories for incident actions"""
INFRASTRUCTURE = "Infrastructure"
CODE_BUG = "Code Bug"
PROCESS_IMPROVEMENT = "Process Improvement"
TRAINING = "Training"
MONITORING = "Monitoring"
SECURITY = "Security"
DOCUMENTATION = "Documentation"
CAPACITY_PLANNING = "Capacity Planning"
OTHER = "Other"
class Priority(Enum):
"""Priority levels for backlog items"""
CRITICAL = "Critical"
HIGH = "High"
MEDIUM = "Medium"
LOW = "Low"
class BacklogItem:
"""Represents a single backlog item generated from incident actions"""
def __init__(
self,
title: str,
description: str,
category: ActionCategory,
owner: str,
incident_id: str,
incident_severity: str,
detected_date: datetime,
target_resolution_days: int,
dependencies: List[str] = None
):
self.title = title
self.description = description
self.category = category
self.owner = owner
self.incident_id = incident_id
self.incident_severity = incident_severity
self.detected_date = detected_date
self.target_resolution_days = target_resolution_days
self.dependencies = dependencies or []
def calculate_aging(self, reference_date: datetime = None) -> Dict[str, Any]:
"""Calculate aging metrics for the backlog item"""
if reference_date is None:
reference_date = datetime.now()
days_since_detected = (reference_date - self.detected_date).days
days_until_target = max(0, self.target_resolution_days - days_since_detected)
is_overdue = days_since_detected > self.target_resolution_days
return {
"days_since_detected": days_since_detected,
"days_until_target": days_until_target,
"is_overdue": is_overdue,
"aging_status": self._get_aging_status(days_until_target, is_overdue)
}
def _get_aging_status(self, days_until_target: int, is_overdue: bool) -> str:
"""Determine aging status based on days remaining"""
if is_overdue:
return "Overdue"
elif days_until_target <= 3:
return "Urgent"
elif days_until_target <= 7:
return "Due Soon"
else:
return "On Track"
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
aging = self.calculate_aging()
return {
"title": self.title,
"description": self.description,
"category": self.category.value,
"owner": self.owner,
"incident_id": self.incident_id,
"incident_severity": self.incident_severity,
"detected_date": self.detected_date.isoformat(),
"target_resolution_date": (
self.detected_date + timedelta(days=self.target_resolution_days)
).isoformat(),
"target_resolution_days": self.target_resolution_days,
"aging": aging,
"dependencies": self.dependencies,
"priority": self._determine_priority()
}
def _determine_priority(self) -> str:
"""Determine priority based on incident severity and category"""
aging = self.calculate_aging()
# Base priority from incident severity
severity_priority_map = {
"critical": Priority.CRITICAL,
"high": Priority.HIGH,
"medium": Priority.MEDIUM,
"low": Priority.LOW
}
base_priority = severity_priority_map.get(
self.incident_severity.lower(), Priority.MEDIUM
)
# Adjust for overdue items
if aging["is_overdue"]:
return Priority.CRITICAL.value
# Adjust for critical categories regardless of incident severity
critical_categories = [
ActionCategory.SECURITY,
ActionCategory.CODE_BUG
]
if self.category in critical_categories and base_priority != Priority.CRITICAL:
return Priority.HIGH.value
return base_priority.value
class IncidentActionAnalyzer:
"""Analyzes incident actions and generates backlog items"""
# Keywords for category classification
CATEGORY_KEYWORDS = {
ActionCategory.INFRASTRUCTURE: [
"server", "database", "network", "connection pool", "disk",
"memory", "cpu", "load balancer", "vm", "container", "kubernetes",
"aws", "azure", "gcp", "infrastructure", "cluster"
],
ActionCategory.CODE_BUG: [
"bug", "error", "exception", "null pointer", "fix",
"code change", "patch", "defect", "debug", "race condition",
"memory leak", "timeout"
],
ActionCategory.PROCESS_IMPROVEMENT: [
"process", "procedure", "documentation", "runbook",
"playbook", "on-call", "escalation", "workflow", "sop",
"standard operating", "handover"
],
ActionCategory.TRAINING: [
"train", "training", "knowledge", "session", "workshop",
"education", "learn", "mentor", "shadow", "onboarding"
],
ActionCategory.MONITORING: [
"monitor", "alert", "metric", "dashboard", "threshold",
"visibility", "observability", "log", "tracing", "proactive"
],
ActionCategory.SECURITY: [
"security", "vulnerability", "penetration", "access control",
"auth", "authentication", "authorization", "encryption",
"firewall", "compliance", "audit", "secret", "credential"
],
ActionCategory.DOCUMENTATION: [
"doc", "document", "wiki", "readme", "confluence",
"knowledge base", "instruction", "guide", "manual"
],
ActionCategory.CAPACITY_PLANNING: [
"capacity", "scale", "load test", "stress test", "performance",
"throughput", "qps", "tps", "headroom", "overprovision"
]
}
# Owner mapping based on category and team structure
OWNER_MAPPING = {
ActionCategory.INFRASTRUCTURE: "Platform Engineering",
ActionCategory.CODE_BUG: "Development Team",
ActionCategory.PROCESS_IMPROVEMENT: "SRE/Operations",
ActionCategory.TRAINING: "People Operations",
ActionCategory.MONITORING: "Observability Team",
ActionCategory.SECURITY: "Security Team",
ActionCategory.DOCUMENTATION: "Technical Writing",
ActionCategory.CAPACITY_PLANNING: "Platform Engineering",
ActionCategory.OTHER: "Engineering Manager"
}
# Target resolution days based on severity and category
TARGET_DAYS_MATRIX = {
# category: {severity: days}
ActionCategory.INFRASTRUCTURE: {
"critical": 3, "high": 7, "medium": 14, "low": 30
},
ActionCategory.CODE_BUG: {
"critical": 1, "high": 3, "medium": 7, "low": 14
},
ActionCategory.PROCESS_IMPROVEMENT: {
"critical": 7, "high": 14, "medium": 30, "low": 60
},
ActionCategory.SECURITY: {
"critical": 1, "high": 3, "medium": 7, "low": 14
},
ActionCategory.MONITORING: {
"critical": 3, "high": 7, "medium": 14, "low": 30
},
# Default for other categories
"default": {
"critical": 5, "high": 10, "medium": 20, "low": 40
}
}
def __init__(self):
self.backlog_items: List[BacklogItem] = []
def classify_action(self, description: str) -> ActionCategory:
"""Classify action description into category using keyword matching"""
description_lower = description.lower()
# Score each category based on keyword matches
category_scores = {category: 0 for category in ActionCategory}
for category, keywords in self.CATEGORY_KEYWORDS.items():
for keyword in keywords:
if keyword in description_lower:
category_scores[category] += 1
# Find category with highest score
best_category = max(category_scores, key=category_scores.get)
# If no keywords matched, return OTHER
if category_scores[best_category] == 0:
return ActionCategory.OTHER
return best_category
def extract_owner(self, action: Dict[str, Any], category: ActionCategory) -> str:
"""Extract or assign owner for an action"""
# Check if explicit owner is provided
if "owner" in action and action["owner"]:
return action["owner"]
# Use category-based default owner
return self.OWNER_MAPPING.get(category, "Engineering Manager")
def calculate_target_days(
self,
category: ActionCategory,
severity: str
) -> int:
"""Calculate target resolution days based on category and severity"""
severity = severity.lower()
# Get matrix for category or use default
category_matrix = self.TARGET_DAYS_MATRIX.get(
category,
self.TARGET_DAYS_MATRIX["default"]
)
return category_matrix.get(severity, 20) # Default to 20 days
def generate_title(self, description: str, max_length: int = 80) -> str:
"""Generate concise title from description"""
# Take first sentence or truncate
first_sentence = description.split('.')[0].strip()
if len(first_sentence) <= max_length:
return first_sentence
# Truncate and add ellipsis
return first_sentence[:max_length-3] + "..."
def parse_date(self, date_str: str) -> datetime:
"""Parse various date formats"""
formats = [
"%Y-%m-%d",
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%dT%H:%M:%S.%fZ",
"%Y-%m-%d %H:%M:%S"
]
for fmt in formats:
try:
return datetime.strptime(date_str, fmt)
except ValueError:
continue
# Fallback to current time if parsing fails
return datetime.now()
def generate_backlog_items(
self,
incident_data: Dict[str, Any],
actions: List[Dict[str, Any]]
) -> List[BacklogItem]:
"""
Generate backlog items from incident data and actions
Args:
incident_data: Dictionary with incident metadata
- id: Incident identifier
- severity: Incident severity level
- date: Incident date (ISO format)
- title: Incident title
actions: List of action dictionaries
- description: Action description
- owner: (optional) Explicit owner
- dependencies: (optional) List of dependent action IDs
- detected_date: (optional) When action was identified
Returns:
List of BacklogItem objects
"""
self.backlog_items = []
incident_id = incident_data.get("id", "INC-Unknown")
incident_severity = incident_data.get("severity", "medium")
incident_date = self.parse_date(incident_data.get("date", datetime.now().isoformat()))
for idx, action in enumerate(actions):
description = action.get("description", "")
if not description:
continue
# Classify the action
category = self.classify_action(description)
# Determine owner
owner = self.extract_owner(action, category)
# Calculate target days
target_days = self.calculate_target_days(category, incident_severity)
# Determine detection date
if "detected_date" in action:
detected_date = self.parse_date(action["detected_date"])
else:
detected_date = incident_date
# Generate title
title = self.generate_title(description)
# Get dependencies
dependencies = action.get("dependencies", [])
# Create backlog item
item = BacklogItem(
title=title,
description=f"From incident {incident_id} ({incident_date.date()}):\n{description}",
category=category,
owner=owner,
incident_id=incident_id,
incident_severity=incident_severity,
detected_date=detected_date,
target_resolution_days=target_days,
dependencies=dependencies
)
self.backlog_items.append(item)
return self.backlog_items
def get_aging_report(self, reference_date: datetime = None) -> Dict[str, Any]:
"""Generate aging report for all backlog items"""
if reference_date is None:
reference_date = datetime.now()
report = {
"generated_at": reference_date.isoformat(),
"total_items": len(self.backlog_items),
"by_category": {},
"by_owner": {},
"by_aging_status": {
"Overdue": 0,
"Urgent": 0,
"Due Soon": 0,
"On Track": 0
},
"overdue_items": []
}
for item in self.backlog_items:
aging = item.calculate_aging(reference_date)
# Update category counts
category = item.category.value
report["by_category"].setdefault(category, {"count": 0, "items": []})
report["by_category"][category]["count"] += 1
report["by_category"][category]["items"].append({
"title": item.title,
"owner": item.owner,
"aging": aging
})
# Update owner counts
owner = item.owner
report["by_owner"].setdefault(owner, {"count": 0, "items": []})
report["by_owner"][owner]["count"] += 1
# Update aging status counts
status = aging["aging_status"]
report["by_aging_status"][status] += 1
# Track overdue items
if aging["is_overdue"]:
report["overdue_items"].append({
"title": item.title,
"owner": item.owner,
"days_overdue": aging["days_since_detected"] - item.target_resolution_days,
"incident_id": item.incident_id
})
return report
def generate_post_incident_backlog(
incident_data: Dict[str, Any],
actions: List[Dict[str, Any]],
output_format: str = "json"
) -> str:
"""
Main function to generate backlog from incident data
Args:
incident_data: Incident metadata
actions: List of action items from retrospective
output_format: 'json' or 'dict'
Returns:
JSON string or dictionary with backlog items and aging report
"""
analyzer = IncidentActionAnalyzer()
backlog_items = analyzer.generate_backlog_items(incident_data, actions)
aging_report = analyzer.get_aging_report()
result = {
"backlog_items": [item.to_dict() for item in backlog_items],
"aging_report": aging_report,
"metadata": {
"incident_id": incident_data.get("id"),
"incident_title": incident_data.get("title"),
"incident_severity": incident_data.get("severity"),
"total_actions": len(actions),
"generated_at": datetime.now().isoformat(),
"classification_rules_version": "1.0"
}
}
if output_format == "dict":
return result
return json.dumps(result, indent=2)
# Example usage
if __name__ == "__main__":
# Example incident data
incident = {
"id": "INC-2024-001",
"title": "API Gateway Timeout Issues",
"severity": "high",
"date": "2024-01-15T14:30:00Z"
}
# Example actions from post-incident review
actions = [
{
"description": "Increase database connection pool size from 50 to 200",
"detected_date": "2024-01-15"
},
{
"description": "Add circuit breaker pattern to external API calls",
"owner": "Backend Team"
},
{
"description": "Create runbook for database connection pool troubleshooting",
"dependencies": ["db-connection-doc"]
},
{
"description": "Conduct training session on observability tools for on-call engineers",
"detected_date": "2024-01-16"
},
{
"description": "Implement automated alerts for connection pool utilization > 80%",
"dependencies": ["monitoring-setup"]
},
{
"description": "Review and update security credentials rotation policy",
"detected_date": "2024-01-14"
}
]
# Generate backlog
backlog_json = generate_post_incident_backlog(incident, actions)
print("Generated Backlog:")
print(backlog_json)
# Get aging report separately
result = json.loads(backlog_json)
print("\nAging Report Summary:")
print(f"Total items: {result['aging_report']['total_items']}")
print("By category:")
for category, data in result['aging_report']['by_category'].items():
print(f" {category}: {data['count']} items")
print("\nOverdue items:")
for item in result['aging_report']['overdue_items']:
print(f" - {item['title']} (Owner: {item['owner']}, Overdue by {item['days_overdue']} days)")