-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·673 lines (549 loc) · 23.4 KB
/
run.py
File metadata and controls
executable file
·673 lines (549 loc) · 23.4 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
#!/usr/bin/env python3
"""
STRATO Fix All The Things - Main Entry Point
Usage:
./run.py <issue_numbers...>
./run.py 1234 5678 9012
Environment:
GITHUB_TOKEN - GitHub personal access token
GITHUB_REPO - Repository (default: blockapps/strato-platform)
PROJECT_DIR - Path to local repository clone
BASE_BRANCH - Base branch for PRs (default: develop)
"""
import argparse
import json
import re
import sys
from datetime import datetime
from pathlib import Path
from src.config import Config
from src.git_ops import GitOps, GitError
from src.github_client import GitHubClient, GitHubError
from src.models import PipelineStatus
from src.pipeline import Pipeline
MENTION_PATTERN = re.compile(r"@([A-Za-z0-9_.-]+)")
SUPPORTED_MENTION_HANDLES = {"claude", "sfatt", "strato-all-the-things", "fix-all"}
def is_valid_comment_invocation(comment_body: str) -> bool:
"""Return True when the comment contains a supported bot mention/invocation."""
normalized = comment_body.lower()
mentions = {m.lower() for m in MENTION_PATTERN.findall(comment_body)}
if mentions.intersection(SUPPORTED_MENTION_HANDLES):
return True
return any(
phrase in normalized
for phrase in (
"strato-all-the-things",
"fix all the things",
"sfatt",
"please fix",
)
)
def main() -> int:
"""Main entry point."""
parser = argparse.ArgumentParser(description="Auto-fix GitHub issues using AI agents")
parser.add_argument("issues", nargs="+", type=int, help="Issue numbers to process")
parser.add_argument("--env", type=Path, help="Path to .env file")
parser.add_argument(
"--issue-comment-id",
type=int,
help="Issue comment id that invoked this run (for @-mention routing)",
)
parser.add_argument(
"--skip-comment-validation",
action="store_true",
help="Run even if issue comment does not contain a supported invocation",
)
args = parser.parse_args()
# Load configuration
script_dir = Path(__file__).parent.resolve()
env_file = args.env or script_dir / ".env"
try:
config = Config.load(env_file)
except ValueError as e:
print(f"[ERROR] Configuration error: {e}")
return 1
print("=" * 50)
print(" STRATO Fix All The Things - Multi-Agent Pipeline")
print("=" * 50)
print(f"[INFO] Repository: {config.github_repo}")
print(f"[INFO] Project: {config.project_dir}")
print(f"[INFO] Issues to process: {len(args.issues)}")
# Initialize clients
github = GitHubClient(config.github_repo)
git = GitOps(config.project_dir)
# Optional issue-comment intake mode
if args.issue_comment_id:
if len(args.issues) != 1:
print("[ERROR] --issue-comment-id requires exactly one issue number")
return 1
target_issue = args.issues[0]
try:
issue_comment = github.get_issue_comment(args.issue_comment_id)
except GitHubError as e:
print(f"[ERROR] Could not fetch issue comment {args.issue_comment_id}: {e}")
return 1
if issue_comment.issue_number != target_issue:
print(
f"[ERROR] Comment #{args.issue_comment_id} belongs to "
f"issue #{issue_comment.issue_number}, not #{target_issue}"
)
return 1
if not args.skip_comment_validation and not is_valid_comment_invocation(issue_comment.body):
print(
f"[INFO] Comment #{args.issue_comment_id} does not contain a supported @-invocation. "
"Skipping run."
)
return 0
github.add_issue_comment(
target_issue,
(
"🤖 **SFATT Acknowledged**\n\n"
f"Invocation received from @{issue_comment.author or 'unknown-user'} "
f"(comment `{issue_comment.id}`). Starting triage/research/fix/review for this issue now.\n\n"
"---\n"
"*Generated by [STRATO Fix All The Things]"
"(https://github.com/strato-net/strato-fix-all-the-things)*"
),
)
print(
f"[INFO] Accepted invocation from comment #{issue_comment.id} "
f"by @{issue_comment.author or 'unknown-user'}"
)
# Ensure runs directory exists
config.runs_dir.mkdir(exist_ok=True)
# Track results
results = {"success": [], "failed": [], "skipped": []}
for i, issue_num in enumerate(args.issues, 1):
print()
print("=" * 50)
print(f" Issue #{issue_num} ({i}/{len(args.issues)})")
print("=" * 50)
try:
result = process_issue(config, github, git, issue_num)
if result == PipelineStatus.SUCCESS:
results["success"].append(issue_num)
elif result == PipelineStatus.SKIPPED:
results["skipped"].append(issue_num)
else:
results["failed"].append(issue_num)
except Exception as e:
print(f"[ERROR] Unexpected error processing #{issue_num}: {e}")
results["failed"].append(issue_num)
# Print summary
print()
print("=" * 50)
print(" Summary")
print("=" * 50)
if results["success"]:
print(f"[SUCCESS] Completed ({len(results['success'])}): {', '.join(map(str, results['success']))}")
if results["skipped"]:
print(f"[WARNING] Skipped ({len(results['skipped'])}): {', '.join(map(str, results['skipped']))}")
if results["failed"]:
print(f"[ERROR] Failed ({len(results['failed'])}): {', '.join(map(str, results['failed']))}")
print()
print(f"[INFO] Total: {len(args.issues)} issues processed")
print(f"[INFO] Run logs: {config.runs_dir}")
return 0 if not results["failed"] else 1
def cleanup_git_state(git: GitOps, base_branch: str, feature_branch: str) -> None:
"""Clean up git state - discard changes and return to base branch."""
try:
# Discard any uncommitted changes
git._run("checkout", "--", ".", check=False)
git._run("clean", "-fd", check=False)
# Return to base branch
git._run("checkout", base_branch, check=False)
# Delete feature branch
git.delete_branch(feature_branch, force=True)
except Exception:
pass # Best effort cleanup
def process_issue(config: Config, github: GitHubClient, git: GitOps, issue_num: int) -> PipelineStatus:
"""Process a single issue through the pipeline."""
# Fetch issue details
print(f"[INFO] Fetching issue #{issue_num}...")
try:
issue = github.get_issue(issue_num)
except GitHubError as e:
print(f"[ERROR] Failed to fetch issue: {e}")
return PipelineStatus.FAILED
print(f"[SUCCESS] Issue: {issue.title}")
print(f"[INFO] Labels: {', '.join(issue.labels) if issue.labels else 'none'}")
# Create run directory
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
run_dir = config.runs_dir / f"{timestamp}-issue-{issue_num}"
run_dir.mkdir(parents=True, exist_ok=True)
# Save issue data
with open(run_dir / "issue.json", "w") as f:
json.dump({
"number": issue.number,
"title": issue.title,
"body": issue.body,
"labels": issue.labels,
"url": issue.url,
}, f, indent=2)
# Prepare git branch
branch_name = f"claude-auto-fix-{issue_num}"
print(f"[INFO] Preparing git branch...")
try:
# Ensure clean state before starting
if git.is_dirty():
print("[ERROR] Working tree has uncommitted changes. Please commit or stash them.")
return PipelineStatus.FAILED
# Fetch latest and hard reset to ensure we're at latest base branch
print(f"[INFO] Fetching latest from origin...")
git.fetch("origin")
# Force checkout to base branch (in case we're on a different branch)
git._run("checkout", "-f", config.base_branch, check=True)
# Hard reset to match remote exactly (discards any local commits)
git.reset_hard(f"origin/{config.base_branch}")
print(f"[SUCCESS] Reset to origin/{config.base_branch}")
# Close existing PR if any
existing_pr = github.find_open_pr(branch_name)
if existing_pr:
print(f"[WARNING] Closing existing PR #{existing_pr.number}...")
github.close_pr(existing_pr.number)
# Delete existing branch
git.delete_branch(branch_name, force=True)
git.delete_remote_branch(branch_name)
# Create new branch
git.create_branch(branch_name)
print(f"[SUCCESS] Created branch {branch_name}")
except GitError as e:
print(f"[ERROR] Git error: {e}")
return PipelineStatus.FAILED
# Run pipeline with cleanup on any failure
try:
print(f"[INFO] Starting multi-agent pipeline...")
pipeline = Pipeline(config, issue, run_dir)
state = pipeline.run()
# Handle results
if state.status == PipelineStatus.SUCCESS:
return handle_success(config, github, git, issue, branch_name, state, run_dir)
elif state.status == PipelineStatus.SKIPPED:
cleanup_git_state(git, config.base_branch, branch_name)
return handle_skip(github, issue, state, run_dir)
else:
return handle_failure(github, git, issue, branch_name, state, config.base_branch, run_dir)
except Exception as e:
# Unexpected error - clean up and re-raise
print(f"[ERROR] Unexpected error: {e}")
cleanup_git_state(git, config.base_branch, branch_name)
raise
def handle_success(
config: Config,
github: GitHubClient,
git: GitOps,
issue,
branch_name: str,
state,
run_dir: Path,
) -> PipelineStatus:
"""Handle successful pipeline completion."""
print(f"[INFO] Pipeline succeeded, creating PR...")
try:
# Standard title format for commit and PR
fix_title = f"Claude Fix #{issue.number}: {issue.title}"
confidence = state.aggregate_confidence
# Load fix state to get details
files_changed = []
caveats = []
testing_notes = []
fix_state_file = run_dir / "fix.state.json"
if fix_state_file.exists():
try:
with open(fix_state_file) as f:
fix_data = json.load(f)
files_changed = fix_data.get("files_changed", [])
full_result = fix_data.get("full_result", {})
caveats = full_result.get("caveats", [])
testing_notes = full_result.get("testing_notes", [])
except (json.JSONDecodeError, KeyError):
pass
# Load research state to get root cause
root_cause = ""
research_state_file = run_dir / "research.state.json"
if research_state_file.exists():
try:
with open(research_state_file) as f:
research_data = json.load(f)
rc = research_data.get("root_cause", {})
if isinstance(rc, dict):
root_cause = rc.get("description", "")
else:
root_cause = str(rc) if rc else ""
except (json.JSONDecodeError, KeyError):
pass
# Build the detailed body (used for commit, PR, and issue comment)
files_list = ", ".join(f"`{f}`" for f in files_changed[:5]) if files_changed else "See changes"
detail_body = f"**Files changed:** {files_list}\n"
if root_cause:
detail_body += f"\n**Root cause:** {root_cause}\n"
if caveats:
detail_body += "\n**Caveats:**\n"
for caveat in caveats[:3]:
detail_body += f"- {caveat}\n"
if testing_notes:
detail_body += "\n**Testing notes:**\n"
for note in testing_notes[:3]:
detail_body += f"- {note}\n"
detail_body += f"\n**Confidence:** {confidence:.0%}"
# Build commit message with full details
commit_body = f"""{fix_title}
Fixes #{issue.number}
{detail_body}
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"""
# Commit any uncommitted changes (fix agent may or may not have committed)
if git.has_changes():
git.add(exclude_patterns=[".env", "*.env"])
git.commit(commit_body)
# Check if there are commits to push
if not git.has_unpushed_commits("origin", branch_name):
print("[WARNING] No commits to push")
github.add_issue_comment(
issue.number,
f"Pipeline completed but no code changes were made.\n\n"
f"Aggregate confidence: {state.aggregate_confidence}"
)
return PipelineStatus.SKIPPED
# Push
git.push("origin", branch_name, set_upstream=True)
print(f"[SUCCESS] Pushed to origin/{branch_name}")
# Build PR body with full details
pr_body = f"""## Summary
Auto-generated fix for issue #{issue.number}
{detail_body}
## Confidence Breakdown
{json.dumps(state.confidence_breakdown, indent=2)}
## Test Plan
- [ ] Review the changes
- [ ] Run tests
- [ ] Verify fix addresses the issue
---
*Generated by [STRATO Fix All The Things](https://github.com/strato-net/strato-fix-all-the-things)*"""
pr = github.create_pr(
title=fix_title,
body=pr_body,
head=branch_name,
base=config.base_branch,
draft=True,
)
print(f"[SUCCESS] Created PR: {pr.url}")
# Build issue comment
comment = f"""🤖 **Automated Fix Created**
**PR:** {pr.url}
{detail_body}
Please review the PR before merging.
---
*Generated by [STRATO Fix All The Things](https://github.com/strato-net/strato-fix-all-the-things)*"""
github.add_issue_comment(issue.number, comment)
return PipelineStatus.SUCCESS
except (GitError, GitHubError) as e:
print(f"[ERROR] Failed to create PR: {e}")
return PipelineStatus.FAILED
def handle_fix_no_changes(github: GitHubClient, issue, run_dir: Path) -> PipelineStatus:
"""Handle case where fix agent completed but made no changes."""
print(f"[WARNING] Fix agent made no code changes")
# Load research and triage data for context
research_summary = ""
triage_summary = ""
triage_state_file = run_dir / "triage.state.json"
if triage_state_file.exists():
try:
with open(triage_state_file) as f:
triage_data = json.load(f)
full_analysis = triage_data.get("full_analysis", {})
triage_summary = full_analysis.get("summary", triage_data.get("summary", ""))
except (json.JSONDecodeError, KeyError):
pass
research_state_file = run_dir / "research.state.json"
if research_state_file.exists():
try:
with open(research_state_file) as f:
research_data = json.load(f)
research_summary = research_data.get("summary", "")
except (json.JSONDecodeError, KeyError):
pass
# Build informative comment
comment_parts = [
"🤖 **Auto-Fix Analysis Complete**\n",
"The issue was analyzed and deemed fixable, but the fix agent was unable to make any code changes.\n",
]
if triage_summary:
comment_parts.append(f"\n## Triage Analysis\n{triage_summary}\n")
if research_summary:
comment_parts.append(f"\n## Research Findings\n{research_summary}\n")
comment_parts.append(
"\n## Next Steps\n"
"- A human developer should review this issue\n"
"- The automated analysis above may provide useful context\n"
"- Consider if the issue requires architectural changes beyond simple fixes\n"
)
comment_parts.append(
"\n---\n"
"*Generated by [STRATO Fix All The Things](https://github.com/strato-net/strato-fix-all-the-things)*"
)
try:
github.add_issue_comment(issue.number, "".join(comment_parts))
except GitHubError as e:
print(f"[WARNING] Failed to comment on issue: {e}")
return PipelineStatus.SKIPPED
def handle_skip(github: GitHubClient, issue, state, run_dir: Path) -> PipelineStatus:
"""Handle skipped pipeline."""
print(f"[WARNING] Pipeline skipped: {state.failure_reason}")
# Check if skip happened at fix stage (no changes made)
fix_state_file = run_dir / "fix.state.json"
if fix_state_file.exists() and "no changes" in state.failure_reason.lower():
return handle_fix_no_changes(github, issue, run_dir)
# Load triage analysis for detailed comment
triage_state_file = run_dir / "triage.state.json"
classification = ""
analysis_summary = ""
if triage_state_file.exists():
try:
with open(triage_state_file) as f:
triage_data = json.load(f)
classification = triage_data.get("classification", "")
full_analysis = triage_data.get("full_analysis", {})
summary = full_analysis.get("summary", triage_data.get("summary", ""))
reasoning = full_analysis.get("reasoning", "")
risks = full_analysis.get("risks", [])
suggested_approach = full_analysis.get("suggested_approach", "")
questions = full_analysis.get("questions_if_unclear", [])
analysis_summary = f"""
## Analysis Summary
**Summary:** {summary}
**Reasoning:** {reasoning}
"""
# Add classification-specific sections
if classification == "NEEDS_HUMAN":
if risks:
analysis_summary += f"""
**Risks:**
{chr(10).join(f"- {r}" for r in risks)}
"""
if suggested_approach:
analysis_summary += f"""
**Suggested Approach:** {suggested_approach}
"""
if questions:
analysis_summary += f"""
**Questions for Clarification:**
{chr(10).join(f"- {q}" for q in questions)}
"""
elif classification == "NEEDS_CLARIFICATION":
if questions:
analysis_summary += f"""
**Please provide clarification on:**
{chr(10).join(f"- {q}" for q in questions)}
"""
elif classification == "OUT_OF_SCOPE":
analysis_summary += """
**Why this is out of scope:** This issue does not appear to be a bug or configuration issue that can be addressed through code changes. It may be a feature request, documentation issue, or external dependency problem.
"""
elif classification == "DUPLICATE":
analysis_summary += """
**Note:** This issue appears to be a duplicate. Please check for related issues that may already address this problem.
"""
except (json.JSONDecodeError, KeyError):
pass
# Build classification-specific intro message
intro_messages = {
"NEEDS_HUMAN": "This issue requires human review due to its complexity or risk level.",
"NEEDS_CLARIFICATION": "This issue needs more information before it can be addressed.",
"OUT_OF_SCOPE": "This issue is outside the scope of automated fixes.",
"DUPLICATE": "This issue appears to be a duplicate of an existing issue.",
}
intro = intro_messages.get(classification, "This issue was analyzed but cannot be auto-fixed.")
try:
github.add_issue_comment(
issue.number,
f"🤖 **Auto-Fix Analysis Complete**\n\n"
f"{intro}\n\n"
f"**Classification:** `{classification}`\n"
f"{analysis_summary}\n"
f"---\n"
f"*Generated by [STRATO Fix All The Things](https://github.com/strato-net/strato-fix-all-the-things)*"
)
except GitHubError as e:
print(f"[WARNING] Failed to comment on issue: {e}")
return PipelineStatus.SKIPPED
def handle_failure(github: GitHubClient, git: GitOps, issue, branch_name: str, state, base_branch: str, run_dir: Path) -> PipelineStatus:
"""Handle failed or blocked pipeline."""
print(f"[ERROR] Pipeline failed: {state.failure_reason}")
cleanup_git_state(git, base_branch, branch_name)
# Build informative comment about the failure
status_emoji = "🚫" if state.status == PipelineStatus.BLOCKED else "❌"
status_label = "Blocked" if state.status == PipelineStatus.BLOCKED else "Failed"
# Check which stage we got to
agents_completed = state.agents_completed if hasattr(state, 'agents_completed') else []
got_to_fix = any("fix" in a for a in agents_completed)
got_to_review = any("review" in a for a in agents_completed)
# Build the comment
comment_parts = [
f"{status_emoji} **Auto-Fix {status_label}**\n",
f"**Reason:** {state.failure_reason}\n",
]
# If we got to fix/review, include more context
if got_to_fix or got_to_review:
comment_parts.append("\n## What Happened\n")
# Load fix state for context
fix_state_file = run_dir / "fix.state.json"
if fix_state_file.exists():
try:
with open(fix_state_file) as f:
fix_data = json.load(f)
files_changed = fix_data.get("files_changed", [])
if files_changed:
comment_parts.append(f"**Files attempted:** {', '.join(f'`{f}`' for f in files_changed[:5])}\n")
except (json.JSONDecodeError, KeyError):
pass
# Load review state for context
review_state_file = run_dir / "review.state.json"
if review_state_file.exists():
try:
with open(review_state_file) as f:
review_data = json.load(f)
verdict = review_data.get("verdict", "")
concerns = review_data.get("concerns", [])
suggestions = review_data.get("suggestions", [])
if verdict:
comment_parts.append(f"\n**Review verdict:** `{verdict}`\n")
if concerns:
comment_parts.append("\n**Concerns:**\n")
for c in concerns[:3]:
comment_parts.append(f"- {c}\n")
if suggestions:
comment_parts.append("\n**Suggestions:**\n")
for s in suggestions[:3]:
comment_parts.append(f"- {s}\n")
except (json.JSONDecodeError, KeyError):
pass
# Check for revision attempts
revision_count = sum(1 for a in agents_completed if "fix-revision" in a)
if revision_count > 0:
comment_parts.append(f"\n**Revision attempts:** {revision_count}\n")
# Load research for root cause context
research_state_file = run_dir / "research.state.json"
if research_state_file.exists():
try:
with open(research_state_file) as f:
research_data = json.load(f)
rc = research_data.get("root_cause", {})
if isinstance(rc, dict):
root_cause = rc.get("description", "")
else:
root_cause = str(rc) if rc else ""
if root_cause:
comment_parts.append(f"\n**Identified root cause:** {root_cause[:500]}{'...' if len(root_cause) > 500 else ''}\n")
except (json.JSONDecodeError, KeyError):
pass
comment_parts.append(
"\n---\n"
"*Generated by [STRATO Fix All The Things](https://github.com/strato-net/strato-fix-all-the-things)*"
)
try:
github.add_issue_comment(issue.number, "".join(comment_parts))
except GitHubError as e:
print(f"[WARNING] Failed to comment on issue: {e}")
return PipelineStatus.FAILED
if __name__ == "__main__":
sys.exit(main())