-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathissue-generator.py
More file actions
executable file
·486 lines (409 loc) · 16.2 KB
/
issue-generator.py
File metadata and controls
executable file
·486 lines (409 loc) · 16.2 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
#!/usr/bin/env python3
"""
AI Issue Generation Tool
Generates Kanban-optimized work items from high-level requirements using AI assistance.
Focuses on 4-8 hour tasks for continuous flow and rapid feedback cycles.
"""
import json
import argparse
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
class KanbanIssueGenerator:
def __init__(self):
self.max_task_hours = 8
self.min_task_hours = 2
self.templates_dir = Path("kanban-templates")
def generate_feature_issues(self, feature_description: str, platform: str = "github") -> list[dict[str, Any]]:
"""
Generate Kanban-ready issues for a feature request.
Args:
feature_description: High-level feature description
platform: Target platform (github, jira, azure)
Returns:
List of issue dictionaries ready for API submission
"""
print(f"🎯 Generating Kanban issues for: {feature_description}")
# In a real implementation, this would call an AI service
# For this example, we'll use templated logic
issues = []
# Epic level issue
epic = self._create_epic_issue(feature_description, platform)
issues.append(epic)
# Break down into Kanban-sized stories
stories = self._break_down_feature(feature_description, platform)
issues.extend(stories)
# Add technical tasks
tech_tasks = self._generate_technical_tasks(feature_description, platform)
issues.extend(tech_tasks)
return issues
def _create_epic_issue(self, feature_description: str, platform: str) -> dict[str, Any]:
"""Create an epic-level issue for the feature."""
template = self._load_template("epic", platform)
epic = {
"title": f"Epic: {feature_description}",
"body": f"""## Epic Overview
{feature_description}
## Success Criteria
- [ ] All user stories completed
- [ ] Acceptance criteria satisfied
- [ ] Integration tests passing
- [ ] Performance requirements met
## Definition of Done
- [ ] Code reviewed and approved
- [ ] Tests written and passing (>90% coverage)
- [ ] Documentation updated
- [ ] Deployed to production
## Estimated Cycle Time
Target: 2-3 weeks with 4-6 parallel stories
Generated: {datetime.now().isoformat()}
""",
"labels": ["epic", "feature", "kanban"],
"milestone": "Sprint Planning",
"type": "epic"
}
return self._apply_platform_format(epic, platform)
def _break_down_feature(self, feature_description: str, platform: str) -> list[dict[str, Any]]:
"""Break down feature into Kanban-optimized stories (4-8 hours each)."""
# Example breakdown for "Password reset via email"
if "password reset" in feature_description.lower():
return self._password_reset_breakdown(platform)
elif "dashboard" in feature_description.lower():
return self._dashboard_breakdown(platform)
else:
return self._generic_breakdown(feature_description, platform)
def _password_reset_breakdown(self, platform: str) -> list[dict[str, Any]]:
"""Specific breakdown for password reset feature."""
stories = [
{
"title": "Backend: Password reset token generation",
"body": """## Acceptance Criteria
- [ ] Generate secure reset tokens (UUID4 + timestamp)
- [ ] Set 15-minute expiration time
- [ ] Store tokens in Redis with TTL
- [ ] Handle token collision edge cases
## Technical Notes
- Use `secrets.token_urlsafe()` for cryptographically secure tokens
- Implement rate limiting: max 3 requests per email per hour
- Clean up expired tokens automatically
## Cycle Time Target
6-8 hours (includes testing)
## Dependencies
None - can start immediately
""",
"labels": ["backend", "security", "kanban-ready"],
"estimate": "8 hours",
"priority": "high"
},
{
"title": "Backend: Email service integration",
"body": """## Acceptance Criteria
- [ ] Integrate with SendGrid/AWS SES
- [ ] Create password reset email template
- [ ] Handle email delivery failures gracefully
- [ ] Log email sending events for debugging
## Technical Notes
- Use environment variables for API keys
- Implement retry logic with exponential backoff
- Track email delivery status
## Cycle Time Target
4-6 hours
## Dependencies
None - parallel with token generation
""",
"labels": ["backend", "email", "kanban-ready"],
"estimate": "6 hours",
"priority": "high"
},
{
"title": "Frontend: Password reset form",
"body": """## Acceptance Criteria
- [ ] Create responsive reset request form
- [ ] Add email validation
- [ ] Show success/error messages
- [ ] Implement loading states
## Technical Notes
- Use existing form components
- Add client-side validation
- Follow design system guidelines
## Cycle Time Target
4-5 hours
## Dependencies
None - can develop independently
""",
"labels": ["frontend", "ui", "kanban-ready"],
"estimate": "5 hours",
"priority": "medium"
},
{
"title": "Integration: Complete password reset flow",
"body": """## Acceptance Criteria
- [ ] Connect frontend form to backend API
- [ ] Test complete user journey
- [ ] Add error handling for edge cases
- [ ] Verify email delivery end-to-end
## Technical Notes
- Integration testing required
- Cross-browser compatibility check
- Performance testing with realistic load
## Cycle Time Target
3-4 hours
## Dependencies
- Backend token generation complete
- Email service integration complete
- Frontend form complete
""",
"labels": ["integration", "testing", "kanban-ready"],
"estimate": "4 hours",
"priority": "high"
}
]
return [self._apply_platform_format(story, platform) for story in stories]
def _dashboard_breakdown(self, platform: str) -> list[dict[str, Any]]:
"""Breakdown for dashboard features."""
stories = [
{
"title": "Backend: User metrics API endpoint",
"body": """## Acceptance Criteria
- [ ] Create /api/users/metrics endpoint
- [ ] Return user activity data (last 30 days)
- [ ] Implement pagination (limit 100 records)
- [ ] Add response caching (5-minute TTL)
## Cycle Time Target
6-7 hours
## Dependencies
None
""",
"labels": ["backend", "api", "kanban-ready"],
"estimate": "7 hours",
"priority": "high"
},
{
"title": "Frontend: Metrics dashboard component",
"body": """## Acceptance Criteria
- [ ] Create reusable dashboard grid component
- [ ] Add chart visualization (using Chart.js)
- [ ] Implement responsive design
- [ ] Add loading and error states
## Cycle Time Target
8 hours
## Dependencies
None - can use mock data initially
""",
"labels": ["frontend", "dashboard", "kanban-ready"],
"estimate": "8 hours",
"priority": "medium"
}
]
return [self._apply_platform_format(story, platform) for story in stories]
def _generic_breakdown(self, feature_description: str, platform: str) -> list[dict[str, Any]]:
"""Generic breakdown for unknown features."""
stories = [
{
"title": f"Backend: Core logic for {feature_description}",
"body": f"""## Acceptance Criteria
- [ ] Implement main business logic
- [ ] Add input validation
- [ ] Create unit tests (>90% coverage)
- [ ] Add error handling
## Feature Context
{feature_description}
## Cycle Time Target
6-8 hours
## Dependencies
To be determined during planning
""",
"labels": ["backend", "feature", "kanban-ready"],
"estimate": "8 hours",
"priority": "high"
},
{
"title": f"Frontend: UI for {feature_description}",
"body": f"""## Acceptance Criteria
- [ ] Create user interface components
- [ ] Implement user interactions
- [ ] Add responsive design
- [ ] Test across browsers
## Feature Context
{feature_description}
## Cycle Time Target
6-8 hours
## Dependencies
Backend API completion recommended
""",
"labels": ["frontend", "ui", "kanban-ready"],
"estimate": "8 hours",
"priority": "medium"
}
]
return [self._apply_platform_format(story, platform) for story in stories]
def _generate_technical_tasks(self, feature_description: str, platform: str) -> list[dict[str, Any]]:
"""Generate supporting technical tasks."""
tasks = [
{
"title": "Testing: Integration test suite",
"body": f"""## Acceptance Criteria
- [ ] End-to-end test scenarios
- [ ] API integration tests
- [ ] Performance test baseline
- [ ] Security test cases
## Feature Context
{feature_description}
## Cycle Time Target
4-6 hours
## Dependencies
All feature development complete
""",
"labels": ["testing", "qa", "kanban-ready"],
"estimate": "6 hours",
"priority": "medium"
},
{
"title": "Documentation: Feature documentation",
"body": f"""## Acceptance Criteria
- [ ] API documentation updated
- [ ] User guide sections added
- [ ] Architecture decision records
- [ ] Deployment notes
## Feature Context
{feature_description}
## Cycle Time Target
2-3 hours
## Dependencies
Feature implementation complete
""",
"labels": ["documentation", "kanban-ready"],
"estimate": "3 hours",
"priority": "low"
}
]
return [self._apply_platform_format(task, platform) for task in tasks]
def _apply_platform_format(self, issue: dict[str, Any], platform: str) -> dict[str, Any]:
"""Apply platform-specific formatting."""
if platform == "github":
return self._format_for_github(issue)
elif platform == "jira":
return self._format_for_jira(issue)
elif platform == "azure":
return self._format_for_azure(issue)
else:
return issue
def _format_for_github(self, issue: dict[str, Any]) -> dict[str, Any]:
"""Format issue for GitHub Issues API."""
github_issue = {
"title": issue["title"],
"body": issue["body"],
"labels": issue.get("labels", []),
"milestone": issue.get("milestone"),
"assignees": issue.get("assignees", [])
}
# Add cycle time estimate to body
if "estimate" in issue:
github_issue["body"] += f"\n\n**Estimate**: {issue['estimate']}"
return github_issue
def _format_for_jira(self, issue: dict[str, Any]) -> dict[str, Any]:
"""Format issue for JIRA API."""
return {
"fields": {
"project": {"key": "PROJ"},
"summary": issue["title"],
"description": issue["body"],
"issuetype": {"name": issue.get("type", "Story")},
"priority": {"name": issue.get("priority", "Medium")},
"labels": issue.get("labels", []),
"timetracking": {
"originalEstimate": issue.get("estimate", "8h")
}
}
}
def _format_for_azure(self, issue: dict[str, Any]) -> dict[str, Any]:
"""Format issue for Azure DevOps API."""
return {
"op": "add",
"path": "/fields/System.Title",
"value": issue["title"],
"fields": {
"System.Description": issue["body"],
"System.Tags": "; ".join(issue.get("labels", [])),
"Microsoft.VSTS.Scheduling.OriginalEstimate":
issue.get("estimate", "8").split()[0] # Extract number
}
}
def _load_template(self, template_type: str, platform: str) -> dict[str, Any]:
"""Load issue template from file."""
template_file = self.templates_dir / f"{template_type}-template.json"
if template_file.exists():
with open(template_file) as f:
return json.load(f)
return {}
def validate_kanban_readiness(self, issues: list[dict[str, Any]]) -> list[str]:
"""Validate that issues meet Kanban flow criteria."""
warnings = []
for i, issue in enumerate(issues):
# Check cycle time estimates
if "estimate" in issue:
try:
hours = int(issue["estimate"].split()[0])
if hours > self.max_task_hours:
warnings.append(f"Issue {i+1}: Estimate {hours}h exceeds max {self.max_task_hours}h")
elif hours < self.min_task_hours:
warnings.append(f"Issue {i+1}: Estimate {hours}h below min {self.min_task_hours}h")
except ValueError:
warnings.append(f"Issue {i+1}: Invalid time estimate format")
# Check for clear acceptance criteria
if "body" in issue and "Acceptance Criteria" not in issue["body"]:
warnings.append(f"Issue {i+1}: Missing acceptance criteria")
# Check for dependencies documentation
if "body" in issue and "Dependencies" not in issue["body"]:
warnings.append(f"Issue {i+1}: Dependencies not documented")
return warnings
def main():
parser = argparse.ArgumentParser(description="Generate Kanban-optimized work items using AI")
parser.add_argument("--feature", help="Feature description to break down")
parser.add_argument("--epic", help="Epic to decompose into stories")
parser.add_argument("--bug", help="Bug report to create issues for")
parser.add_argument("--platform", choices=["github", "jira", "azure"],
default="github", help="Target platform")
parser.add_argument("--max-hours", type=int, default=8,
help="Maximum hours per task")
parser.add_argument("--output", help="Output file for generated issues")
parser.add_argument("--validate", action="store_true",
help="Validate Kanban readiness")
args = parser.parse_args()
if not any([args.feature, args.epic, args.bug]):
print("Error: Must specify --feature, --epic, or --bug")
sys.exit(1)
generator = KanbanIssueGenerator()
generator.max_task_hours = args.max_hours
# Generate issues based on input type
if args.feature:
issues = generator.generate_feature_issues(args.feature, args.platform)
elif args.epic:
issues = generator.generate_feature_issues(args.epic, args.platform)
elif args.bug:
# Bug handling would be implemented here
print("Bug issue generation not yet implemented")
sys.exit(1)
# Validate Kanban readiness
if args.validate:
warnings = generator.validate_kanban_readiness(issues)
if warnings:
print("⚠️ Kanban Readiness Warnings:")
for warning in warnings:
print(f" - {warning}")
print()
# Output results
if args.output:
with open(args.output, 'w') as f:
json.dump(issues, f, indent=2)
print(f"✅ Generated {len(issues)} issues saved to {args.output}")
else:
print(f"✅ Generated {len(issues)} Kanban-ready issues:")
for i, issue in enumerate(issues, 1):
print(f"\n{i}. {issue['title']}")
if 'estimate' in issue:
print(f" Estimate: {issue.get('estimate', 'TBD')}")
print(f" Labels: {', '.join(issue.get('labels', []))}")
if __name__ == "__main__":
main()