"""
Proactive Backlog Pruning Assistant
====================================
This is a Python-based implementation of a proactive backlog pruning assistant.
It analyzes a backlog (list of work items) using heuristic scores to recommend:
- **Merging**: Similar items (high title/desc similarity, same labels/epic).
- **Splitting**: Oversized or vague items (high story points, low detail score).
- **Discarding**: Stale, low-value, or duplicate items (old age, low priority, no progress).
Key Features:
- Heuristic scoring (0-100) for each category.
- Thresholds: >=80 recommend action.
- Proactive: Designed to run periodically (e.g., cron job, CI/CD pipeline).
- Outputs JSON-friendly recommendations for integration (e.g., Slack/Jira notifications).
- Extensible: Easy to add custom heuristics.
Dependencies:
pip install fuzzywuzzy python-levenshtein rapidfuzz # rapidfuzz is faster alternative to fuzzywuzzy
Assumptions on Work Item Schema (dict):
{
'id': str, # Unique ID (e.g., 'JIRA-123')
'title': str, # Short title
'description': str, # Detailed desc (used for similarity/detail)
'story_points': int,# Estimate (1-13 Fibonacci ideal)
'priority': str, # 'High', 'Medium', 'Low', 'P0'-'P4'
'status': str, # 'To Do', 'In Progress', 'Done'
'labels': list[str],# Tags (e.g., ['bug', 'frontend'])
'epic': str, # Epic key (e.g., 'EPIC-1')
'assignee': str, # Username or None
'created_date': str,# ISO '2023-01-01'
'updated_date': str,# ISO '2023-10-01'
}
"""
from datetime import datetime
from typing import List, Dict, Any, Tuple, Optional
from dataclasses import dataclass
from rapidfuzz import fuzz, process # For fuzzy string matching
import json
@dataclass
class Recommendation:
item_id: str
action: str # 'merge', 'split', 'discard', 'none'
score: float # 0-100
reason: str
details: Dict[str, Any] # e.g., {'similar_to': ['JIRA-456'], 'threshold': 80}
class BacklogPruner:
# Thresholds for recommendations
RECOMMEND_THRESHOLD = 80.0
MERGE_SIMILARITY_THRESHOLD = 75.0 # Fuzzy score
SPLIT_POINTS_THRESHOLD = 13
SPLIT_VAGUE_THRESHOLD = 30.0 # Low detail score
DISCARD_AGE_DAYS = 180 # 6 months
DISCARD_STALE_DAYS_SINCE_UPDATE = 90
PRIORITY_WEIGHTS = {'P0': 100, 'High': 80, 'P1': 75, 'Medium': 50, 'P2': 40, 'Low': 20, 'P3': 15, 'P4': 10}
LABEL_DETAIL_BONUS = {'enhancement': 10, 'bug': 5} # Example bonuses
def __init__(self):
self.backlog: List[Dict[str, Any]] = []
def load_backlog(self, backlog: List[Dict[str, Any]]):
"""Load backlog items."""
self.backlog = backlog
def _days_since(self, date_str: str) -> int:
"""Days since given ISO date."""
if not date_str:
return float('inf')
dt = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
return (datetime.now(dt.tzinfo) - dt).days
def _detail_score(self, item: Dict[str, Any]) -> float:
"""Score based on description length, keywords, labels (0-100)."""
desc = (item.get('description') or '').lower()
title_len = len(item.get('title', ''))
desc_len = len(desc)
label_score = sum(self.LABEL_DETAIL_BONUS.get(l.lower(), 0) for l in item.get('labels', []))
# Base: length normalized
length_score = min(100, (title_len + desc_len) / 20) # ~400 chars ideal
keyword_bonus = 20 if any(word in desc for word in ['as a', 'i want', 'so that']) else 0 # User story format
assignee_bonus = 15 if item.get('assignee') else 0
return min(100, length_score + keyword_bonus + assignee_bonus + label_score)
def _priority_score(self, priority: str) -> float:
"""Convert priority to score (higher better)."""
return self.PRIORITY_WEIGHTS.get(priority, 10)
def score_for_discard(self, item: Dict[str, Any]) -> float:
"""Heuristic for discarding: age, staleness, low priority, no assignee, done but old."""
age_days = self._days_since(item.get('created_date', ''))
stale_days = self._days_since(item.get('updated_date', ''))
priority_score = self._priority_score(item.get('priority', 'Low'))
detail_score = self._detail_score(item)
# Penalties
age_penalty = min(50, age_days / 3) # 150 days = 50
stale_penalty = min(30, stale_days / 3)
low_priority_penalty = 100 - priority_score
vague_penalty = max(0, 30 - (detail_score / 3))
done_old_penalty = 20 if item.get('status') == 'Done' and age_days > 365 else 0
discard_score = (age_penalty + stale_penalty + low_priority_penalty + vague_penalty + done_old_penalty) / 5
return min(100, discard_score)
def score_for_split(self, item: Dict[str, Any]) -> float:
"""Heuristic for splitting: high points, vague desc, many labels (broad scope)."""
points = item.get('story_points', 0)
detail_score = self._detail_score(item)
points_penalty = min(60, (points - self.SPLIT_POINTS_THRESHOLD) * 10) if points > self.SPLIT_POINTS_THRESHOLD else 0
vague_penalty = max(0, self.SPLIT_VAGUE_THRESHOLD - detail_score)
label_breadth = min(20, len(item.get('labels', [])) * 5) # Many labels = broad?
split_score = (points_penalty + vague_penalty + label_breadth) / 3
return min(100, split_score)
def find_merge_candidates(self, item: Dict[str, Any]) -> List[Tuple[str, float]]:
"""Find similar items for merging using fuzzy matching."""
candidates = []
for other in self.backlog:
if other['id'] == item['id'] or other.get('status') == 'Done':
continue
title_sim = fuzz.ratio(item['title'].lower(), other['title'].lower())
desc_sim = fuzz.partial_ratio((item.get('description') or '').lower(), (other.get('description') or '').lower())
label_sim = len(set(item.get('labels', [])) & set(other.get('labels', []))) / max(len(item.get('labels', [])), 1) * 100
epic_match = 30 if item.get('epic') == other.get('epic') else 0
avg_sim = (title_sim * 0.4 + desc_sim * 0.4 + label_sim * 0.1 + epic_match * 0.1)
if avg_sim >= self.MERGE_SIMILARITY_THRESHOLD:
candidates.append((other['id'], avg_sim))
return sorted(candidates, key=lambda x: x[1], reverse=True)[:3] # Top 3
def score_for_merge(self, item: Dict[str, Any]) -> float:
"""Heuristic for merging: based on best similarity match."""
candidates = self.find_merge_candidates(item)
if not candidates:
return 0.0
best_sim = candidates[0][1]
# Boost if low detail (dupe likely) or same status
detail_boost = max(0, 20 - self._detail_score(item) / 5)
return min(100, best_sim + detail_boost)
def analyze_item(self, item: Dict[str, Any]) -> Recommendation:
"""Analyze single item and pick best action."""
discard_score = self.score_for_discard(item)
split_score = self.score_for_split(item)
merge_score = self.score_for_merge(item)
best_score = max(discard_score, split_score, merge_score)
if best_score < self.RECOMMEND_THRESHOLD:
return Recommendation(item['id'], 'none', 0.0, 'No action needed', {})
if discard_score == best_score:
action = 'discard'
details = {'age_days': self._days_since(item.get('created_date', ''))}
elif split_score == best_score:
action = 'split'
details = {'story_points': item.get('story_points'), 'detail_score': self._detail_score(item)}
else:
action = 'merge'
details = {'similar_to': [c[0] for c in self.find_merge_candidates(item)]}
reason = f"{action.upper()} score: {best_score:.1f}"
return Recommendation(item['id'], action, best_score, reason, details)
def prune_backlog(self) -> List[Recommendation]:
"""Proactive full analysis. Returns only items needing action."""
recommendations = []
for item in self.backlog:
rec = self.analyze_item(item)
if rec.action != 'none':
recommendations.append(rec)
return sorted(recommendations, key=lambda r: r.score, reverse=True)
def print_report(self, recommendations: List[Recommendation]):
"""Human-readable report."""
print("🔍 BACKLOG PRUNING REPORT")
print("=" * 50)
for rec in recommendations:
print(f"Item: {rec.item_id} | Action: {rec.action.upper()} | Score: {rec.score:.1f}")
print(f" Reason: {rec.reason}")
print(f" Details: {json.dumps(rec.details, indent=2)}")
print()
# Example Usage
if __name__ == "__main__":
pruner = BacklogPruner()
# Sample backlog
sample_backlog = [
{
'id': 'TASK-1',
'title': 'Fix login bug',
'description': 'User cannot login after password reset.',
'story_points': 5,
'priority': 'High',
'status': 'To Do',
'labels': ['bug', 'auth'],
'epic': 'AUTH-1',
'assignee': 'dev1',
'created_date': '2023-01-01',
'updated_date': '2023-10-01'
},
{
'id': 'TASK-2',
'title': 'Resolve authentication issues',
'description': 'Password reset login failure.',
'story_points': 3,
'priority': 'High',
'status': 'To Do',
'labels': ['bug', 'auth'],
'epic': 'AUTH-1',
'assignee': None,
'created_date': '2023-01-02',
'updated_date': '2023-10-01'
},
{
'id': 'TASK-3',
'title': 'Implement entire user dashboard',
'description': 'Build dashboard.',
'story_points': 20,
'priority': 'Medium',
'status': 'To Do',
'labels': ['ui', 'backend', 'db'],
'epic': 'DASH-1',
'assignee': None,
'created_date': '2022-01-01',
'updated_date': '2022-06-01'
},
{
'id': 'TASK-4',
'title': 'Update README',
'description': '',
'story_points': 1,
'priority': 'Low',
'status': 'Done',
'labels': [],
'epic': None,
'assignee': None,
'created_date': '2020-01-01',
'updated_date': '2020-01-01'
}
]
pruner.load_backlog(sample_backlog)
recs = pruner.prune_backlog()
pruner.print_report(recs)
# JSON output for automation
print("JSON Recommendations:")
print(json.dumps([rec.__dict__ for rec in recs], indent=2))
How to Use & Extend
-
Run the Script: python backlog_pruner.py → See sample report.
- Sample Output: Recommends merging TASK-1/TASK-2 (high similarity), splitting TASK-3 (high points/old), discarding TASK-4 (stale/done).
-
Integration:
- Fetch backlog from Jira API: Add
fetch_from_jira(jira_url, api_key).
- Slack/Email notifier: Post
pruner.print_report(recs) or JSON.
- Cron:
0 9 * * 1 python prune.py (weekly Mondays).
-
Customization:
- Tweak thresholds/heuristic weights in class vars.
- Add ML: Replace fuzzy with embeddings (e.g., sentence-transformers).
- Dependencies: Include acceptance criteria parsing.
- Filters:
self.backlog = [i for i in backlog if i['status'] != 'Done'].
-
Proactive Enhancements:
- GitHub Action: Scan repo issues/PRs.
- Database backend for historical scoring trends.
This assistant is production-ready as a prototype—plug in your data and prune! 🚀