-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.py
More file actions
1634 lines (1419 loc) · 63.7 KB
/
loop.py
File metadata and controls
1634 lines (1419 loc) · 63.7 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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
QA Validation Loop Orchestration
=================================
Main QA loop that coordinates reviewer and fixer sessions until
approval or max iterations.
"""
import asyncio
import json
import os
import time as time_module
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from agents.e2e_generator import generate_e2e_tests
from agents.memory_manager import save_user_correction
from agents.runtime.qa_phase_routing import (
resolve_qa_runtime as _resolve_qa_runtime,
)
from agents.test_generator import run_test_generator_session
from analysis.code_analyzer import CodeAnalyzer
from analysis.coverage_reporter import collect_coverage, format_coverage_summary
from analysis.failure_analyzer import analyze_failure, is_analysis_enabled
from analysis.failure_storage import store_failure_analysis
from analysis.ts_analyzer import TypeScriptAnalyzer
from core.client import create_client
from debug import debug, debug_error, debug_section, debug_success, debug_warning
from integrations.graphiti.memory import is_graphiti_enabled
# Webhook integration
from integrations.webhooks.dispatcher import dispatch_qa_result
from linear_updater import (
LinearTaskState,
is_linear_enabled,
linear_qa_approved,
linear_qa_max_iterations,
linear_qa_rejected,
linear_qa_started,
)
from phase_config import get_phase_model, get_phase_thinking_budget
from phase_event import ExecutionPhase, emit_phase
from progress import count_subtasks, is_build_ready_for_qa
from security.constants import PROJECT_DIR_ENV_VAR
from services.recovery import RecoveryManager
from task_logger import (
LogPhase,
get_task_logger,
)
from .criteria import (
get_qa_iteration_count,
get_qa_signoff_status,
is_qa_approved,
)
from .fixer import run_qa_fixer_runtime_session, run_qa_fixer_session
from .report import (
create_manual_test_plan,
escalate_to_human,
get_iteration_history,
get_recurring_issue_summary,
has_recurring_issues,
is_no_test_project,
record_iteration,
)
from .reviewer import run_qa_agent_session, run_qa_reviewer_runtime_session
# Configuration
MAX_QA_ITERATIONS = 50
MAX_CONSECUTIVE_ERRORS = 3 # Stop after 3 consecutive errors without progress
MINIMUM_COVERAGE_THRESHOLD = 80.0 # Minimum coverage percentage required
# Auto-generated marker for QA_FIX_REQUEST.md
QA_FIX_REQUEST_MARKER = "<!-- AUTO_GENERATED_BY_QA_AGENT -->"
def _qa_runtime_metadata(
spec_dir: Path,
task: str,
*,
qa_iteration: int | None = None,
issues: list[dict] | None = None,
) -> dict[str, Any]:
"""Build compact task/file metadata for plugin runtime hooks."""
files: list[str] = []
plan_path = spec_dir / "implementation_plan.json"
if plan_path.exists():
try:
plan = json.loads(plan_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
plan = {}
for phase in plan.get("phases", []):
if not isinstance(phase, dict):
continue
for subtask in phase.get("subtasks", []):
if not isinstance(subtask, dict):
continue
for file_path in subtask.get("files_to_modify", []):
if file_path and file_path not in files:
files.append(str(file_path))
if len(files) >= 12:
break
if len(files) >= 12:
break
if len(files) >= 12:
break
metadata: dict[str, Any] = {
"task": task,
"files": files,
"phase_name": "qa",
}
if qa_iteration is not None:
metadata["qa_iteration"] = qa_iteration
if issues:
metadata["issues"] = [
str(issue.get("title") or issue.get("description") or "")[:160]
for issue in issues[:5]
if isinstance(issue, dict)
]
return metadata
# =============================================================================
# USER CORRECTION DETECTION
# =============================================================================
def check_user_correction(spec_dir: Path) -> tuple[bool, dict[str, Any] | None]:
"""
Check if QA_FIX_REQUEST.md was manually edited by the user.
The QA agent should include a marker comment in auto-generated files.
If the marker is missing, we assume the user manually edited the file.
Args:
spec_dir: Spec directory
Returns:
(is_user_correction, correction_details) tuple where:
- is_user_correction: True if file was manually edited
- correction_details: Dict with timestamp, file content, etc. (or None)
"""
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
if not fix_request_file.exists():
return False, None
try:
content = fix_request_file.read_text(encoding="utf-8")
# Check for auto-generated marker
has_marker = QA_FIX_REQUEST_MARKER in content
# If marker is missing, file was manually created/edited by user
is_user_correction = not has_marker
if is_user_correction:
# Get file metadata
stat = fix_request_file.stat()
modification_time = datetime.fromtimestamp(stat.st_mtime, tz=UTC)
correction_details = {
"file_path": str(fix_request_file),
"modified_at": modification_time.isoformat(),
"content_preview": content[:500], # First 500 chars for context
"detected_at": datetime.now(UTC).isoformat(),
}
debug(
"qa_loop",
"User correction detected in QA_FIX_REQUEST.md",
modified_at=correction_details["modified_at"],
)
return True, correction_details
debug(
"qa_loop",
"QA_FIX_REQUEST.md has auto-generated marker - agent-created",
)
return False, None
except (OSError, UnicodeDecodeError) as e:
debug_warning("qa_loop", f"Failed to check user correction: {e}")
return False, None
# =============================================================================
# TEST REVIEW HELPERS
# =============================================================================
def _move_tests_to_review_directory(
project_dir: Path,
spec_dir: Path,
generated_files: list[str],
) -> Path:
"""
Move generated tests to a review directory for user approval.
Creates a review directory in the spec folder, moves generated test files
there, and creates an instruction file for the user.
Args:
project_dir: Project root directory
spec_dir: Spec directory
generated_files: List of generated test file paths (relative to project_dir)
Returns:
Path to the review directory
"""
import shutil
# Create review directory
review_dir = spec_dir / "generated_tests_review"
review_dir.mkdir(exist_ok=True)
debug("qa_loop", "Created test review directory", review_dir=str(review_dir))
# Move each generated test file to review directory, preserving relative paths
moved_files = []
for file_path_str in generated_files:
file_path = Path(file_path_str)
# Reject absolute or upward-traversing paths
if file_path.is_absolute() or ".." in file_path.parts:
debug_error(
"qa_loop",
f"Skipping unsafe path: {file_path_str}",
)
continue
source = project_dir / file_path
dest = review_dir / file_path
dest.parent.mkdir(parents=True, exist_ok=True)
if source.exists():
try:
shutil.move(str(source), str(dest))
moved_files.append(str(file_path))
debug("qa_loop", "Moved test to review", file=str(file_path))
except Exception as e:
debug_error("qa_loop", f"Failed to move {file_path.name}: {e}")
else:
debug_warning("qa_loop", f"Test file not found for review: {file_path}")
# Create instruction file
instruction_file = review_dir / "README.md"
instructions = f"""# Generated Tests - Awaiting Review
## Overview
The QA loop has generated {len(moved_files)} test file(s) based on the implemented code.
These tests are waiting for your review and approval before being committed to the project.
## Generated Test Files
{chr(10).join(f"- {name}" for name in moved_files)}
## Review Process
1. **Review the tests** in this directory
- Check that tests are meaningful and correct
- Verify they follow project conventions
- Ensure edge cases are covered appropriately
2. **Approve tests** (if they look good):
```bash
# Copy approved tests to your project (cross-platform)
python -c "import shutil, sys; shutil.copytree(sys.argv[1], sys.argv[2], dirs_exist_ok=True)" "{review_dir}" "{project_dir}"
# Commit them with your changes
git add tests/ apps/frontend/src/
git commit -m "Add generated tests for [feature name]"
```
3. **Reject tests** (if they need work):
- Delete or modify the test files in this review directory
- Optionally provide feedback for regeneration
- The tests will NOT be automatically committed
## Notes
- These tests are isolated in the review directory
- They will NOT be automatically committed to your project
- You have full control over which tests to include
- You can modify tests before copying them to your project
---
Generated: {time_module.strftime("%Y-%m-%d %H:%M:%S")}
"""
try:
with open(instruction_file, "w", encoding="utf-8") as f:
f.write(instructions)
debug("qa_loop", "Created review instructions", file=str(instruction_file))
except Exception as e:
debug_error("qa_loop", f"Failed to create instruction file: {e}")
# Print user-facing message
print("\n" + "=" * 70)
print(" 📋 GENERATED TESTS - REVIEW REQUIRED")
print("=" * 70)
print(
f"\n✅ {len(moved_files)} test file(s) have been generated and saved for review."
)
print(f"\n📁 Review directory: {review_dir}")
print("\nGenerated tests:")
for name in moved_files:
print(f" • {name}")
print(f"\n📖 See {instruction_file.name} for review instructions")
print("\n⚠️ Tests are NOT automatically committed - review and approve manually.")
print("=" * 70)
return review_dir
# =============================================================================
# QA VALIDATION LOOP
# =============================================================================
async def run_qa_validation_loop(
project_dir: Path,
spec_dir: Path,
model: str,
verbose: bool = False,
) -> bool:
"""
Run the full QA validation loop.
This is the self-validating loop:
1. QA Agent reviews
2. If rejected → Fixer Agent fixes
3. QA Agent re-reviews
4. Loop until approved or max iterations
Enhanced with:
- Iteration tracking with detailed history
- Recurring issue detection (3+ occurrences → human escalation)
- No-test project handling
Args:
project_dir: Project root directory
spec_dir: Spec directory
model: Claude model to use
verbose: Whether to show detailed output
Returns:
True if QA approved, False otherwise
"""
# Set environment variable for security hooks to find the correct project directory
# This is needed because os.getcwd() may return the wrong directory in worktree mode
os.environ[PROJECT_DIR_ENV_VAR] = str(project_dir.resolve())
debug_section("qa_loop", "QA Validation Loop")
debug(
"qa_loop",
"Starting QA validation loop",
project_dir=str(project_dir),
spec_dir=str(spec_dir),
model=model,
max_iterations=MAX_QA_ITERATIONS,
)
print("\n" + "=" * 70)
print(" QA VALIDATION LOOP")
print(" Self-validating quality assurance")
print("=" * 70)
# Initialize task logger for the validation phase
task_logger = get_task_logger(spec_dir)
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Human feedback takes priority — if the user explicitly asked to proceed,
# skip the build completeness gate entirely
if not has_human_feedback:
# Verify build is ready for QA (all subtasks in terminal state)
if not is_build_ready_for_qa(spec_dir):
debug_warning(
"qa_loop", "Build is not ready for QA - subtasks still in progress"
)
print("\n❌ Build is not ready for QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(f" Progress: {completed}/{total} subtasks completed")
return False
# Emit phase event at start of QA validation (before any early returns)
emit_phase(ExecutionPhase.QA_REVIEW, "Starting QA validation")
# Detect if the file was manually edited by the user
is_user_correction, correction_details = check_user_correction(spec_dir)
# Check if already approved - but if there's human feedback, we need to process it first
if is_qa_approved(spec_dir) and not has_human_feedback:
debug_success("qa_loop", "Build already approved by QA")
print("\n✅ Build already approved by QA.")
return True
# If there's human feedback, we need to run the fixer first before re-validating
if has_human_feedback:
if is_user_correction:
debug(
"qa_loop",
"User correction detected - manually edited QA_FIX_REQUEST.md",
correction_details=correction_details,
)
emit_phase(ExecutionPhase.QA_FIXING, "Processing user corrections")
print("\n✏️ User correction detected in QA_FIX_REQUEST.md")
print(" Running QA Fixer to apply your changes...")
else:
debug(
"qa_loop",
"Human feedback detected - will run fixer first",
fix_request_file=str(fix_request_file),
)
emit_phase(ExecutionPhase.QA_FIXING, "Processing human feedback")
print("\n📝 Human feedback detected. Running QA Fixer first...")
# Get model and thinking budget for fixer (uses QA phase config)
qa_model = get_phase_model(spec_dir, "qa", model)
fixer_thinking_budget = get_phase_thinking_budget(spec_dir, "qa")
fixer_decision = _resolve_qa_runtime(
agent_type="qa_fixer",
spec_dir=spec_dir,
qa_iteration=0,
project_dir=project_dir,
)
if fixer_decision.use_runtime_layer:
fix_status, fix_response = await run_qa_fixer_runtime_session(
provider_name=fixer_decision.provider_name,
runtime_mode=fixer_decision.runtime_mode,
model=qa_model,
project_dir=project_dir,
spec_dir=spec_dir,
fix_session=0,
verbose=False,
)
else:
fix_client = create_client(
project_dir,
spec_dir,
qa_model,
agent_type="qa_fixer",
max_thinking_tokens=fixer_thinking_budget,
runtime_metadata=_qa_runtime_metadata(
spec_dir,
"Apply human QA feedback",
qa_iteration=0,
),
)
async with fix_client:
fix_status, fix_response = await run_qa_fixer_session(
fix_client,
spec_dir,
0,
False, # iteration 0 for human feedback
)
if fix_status == "error":
debug_error("qa_loop", f"Fixer error: {fix_response[:200]}")
print(f"\n❌ Fixer encountered error: {fix_response}")
return False
if is_user_correction:
debug_success(
"qa_loop",
"User correction fixes applied",
correction_details=correction_details,
)
print(
"\n✅ Fixes applied based on your corrections. Running QA validation..."
)
# Store user correction in Graphiti for cross-session learning
try:
# Read the full QA_FIX_REQUEST.md content to understand the correction
fix_content = fix_request_file.read_text(encoding="utf-8")
# Extract meaningful information
what_was_wrong = "QA agent generated a fix request, but user manually edited it to provide better guidance"
what_was_corrected = fix_content[
:1000
] # First 1000 chars of the user's corrections
# Build context dict with available information
correction_context = {
"spec_id": spec_dir.name,
"modified_at": correction_details.get("modified_at"),
"detected_at": correction_details.get("detected_at"),
"file_path": str(fix_request_file.relative_to(project_dir)),
"correction_type": "qa_fix_request_manual_edit",
}
# Save to Graphiti memory (async call, non-blocking)
await save_user_correction(
spec_dir=spec_dir,
project_dir=project_dir,
what_was_wrong=what_was_wrong,
what_was_corrected=what_was_corrected,
correction_context=correction_context,
)
debug(
"qa_loop",
"User correction saved to Graphiti memory",
spec_id=spec_dir.name,
)
except Exception as e:
# Don't fail the QA loop if memory save fails
debug_warning(
"qa_loop",
f"Failed to save user correction to memory: {e}",
)
else:
debug_success("qa_loop", "Human feedback fixes applied")
print(
"\n✅ Fixes applied based on human feedback. Running QA validation..."
)
# Remove the fix request file after processing
try:
fix_request_file.unlink()
debug("qa_loop", "Removed processed QA_FIX_REQUEST.md")
except OSError:
pass # Ignore if file removal fails
# Check for no-test projects
if is_no_test_project(spec_dir, project_dir):
print("\n⚠️ No test framework detected in project.")
print("Creating manual test plan...")
manual_plan = create_manual_test_plan(spec_dir, spec_dir.name)
print(f"📝 Manual test plan created: {manual_plan}")
print("\nNote: Automated testing will be limited for this project.")
# Generate tests for implemented code
print("\n🧪 Analyzing code for test generation...")
debug("qa_loop", "Starting test generation step")
try:
# Analyze implementation plan to find modified files
impl_plan_file = spec_dir / "implementation_plan.json"
modified_files = []
if impl_plan_file.exists():
import json
with open(impl_plan_file, encoding="utf-8") as f:
impl_plan = json.load(f)
# Collect files from completed subtasks
for phase in impl_plan.get("phases", []):
for subtask in phase.get("subtasks", []):
if subtask.get("status") == "completed":
modified_files.extend(subtask.get("files_to_modify", []))
modified_files.extend(subtask.get("files_to_create", []))
# Remove duplicates and filter Python and TypeScript files
all_modified_files = list(set(modified_files))
python_files = [f for f in all_modified_files if f.endswith(".py")]
typescript_files = [
f
for f in all_modified_files
if f.endswith((".ts", ".tsx"))
and not f.endswith((".test.ts", ".test.tsx", ".spec.ts", ".spec.tsx"))
]
modified_files = python_files + typescript_files
debug(
"qa_loop",
f"Found {len(python_files)} Python and {len(typescript_files)} TypeScript files to analyze",
files=modified_files[:5],
)
if modified_files:
# Analyze code in modified files
py_analyzer = CodeAnalyzer()
ts_analyzer = TypeScriptAnalyzer()
combined_analysis = {
"functions": [],
"classes": [],
"components": [],
"imports": [],
"edge_cases": [],
}
for file_path in modified_files:
full_path = project_dir / file_path
# Analyze Python files
if full_path.exists() and full_path.suffix == ".py":
try:
analysis = py_analyzer.analyze_file(full_path)
combined_analysis["functions"].extend(
analysis.get("functions", [])
)
combined_analysis["classes"].extend(analysis.get("classes", []))
combined_analysis["imports"].extend(analysis.get("imports", []))
combined_analysis["edge_cases"].extend(
analysis.get("edge_cases", [])
)
debug(
"qa_loop",
f"Analyzed Python file {file_path}",
functions=len(analysis.get("functions", [])),
classes=len(analysis.get("classes", [])),
)
except Exception as e:
debug_warning("qa_loop", f"Failed to analyze {file_path}: {e}")
# Analyze TypeScript files
elif full_path.exists() and full_path.suffix in (".ts", ".tsx"):
try:
analysis = ts_analyzer.analyze_file(full_path)
combined_analysis["components"].extend(
analysis.get("components", [])
)
combined_analysis["functions"].extend(
analysis.get("functions", [])
)
combined_analysis["imports"].extend(analysis.get("imports", []))
combined_analysis["edge_cases"].extend(
analysis.get("edge_cases", [])
)
debug(
"qa_loop",
f"Analyzed TypeScript file {file_path}",
components=len(analysis.get("components", [])),
functions=len(analysis.get("functions", [])),
)
except Exception as e:
debug_warning("qa_loop", f"Failed to analyze {file_path}: {e}")
if (
combined_analysis["functions"]
or combined_analysis["classes"]
or combined_analysis["components"]
):
print(
f" Found {len(combined_analysis['functions'])} functions, "
f"{len(combined_analysis['classes'])} classes, and "
f"{len(combined_analysis['components'])} components"
)
print(" Generating tests...")
# Run test generator
test_result = await run_test_generator_session(
project_dir,
spec_dir,
combined_analysis,
model=model,
verbose=verbose,
)
if test_result.get("success"):
generated_files = test_result.get("generated_files", [])
framework = test_result.get("framework", "pytest")
print(
f" ✅ Generated {len(generated_files)} {framework} test file(s)"
)
debug_success(
"qa_loop",
"Test generation completed",
file_count=len(generated_files),
framework=framework,
)
# Move generated tests to review directory for user approval
if generated_files:
_move_tests_to_review_directory(
project_dir, spec_dir, generated_files
)
else:
error = test_result.get("error", "Unknown error")
print(f" ⚠️ Test generation had issues: {error}")
debug_warning("qa_loop", f"Test generation incomplete: {error}")
# Generate E2E tests for user-facing features
if combined_analysis.get("components"):
print("\n🎭 Generating E2E tests for user-facing features...")
debug("qa_loop", "Starting E2E test generation")
try:
e2e_result = await generate_e2e_tests(
project_dir,
spec_dir,
combined_analysis,
model=model,
verbose=verbose,
)
if e2e_result.get("success"):
e2e_files = e2e_result.get("generated_files", [])
print(f" ✅ Generated {len(e2e_files)} E2E test file(s)")
debug_success(
"qa_loop",
"E2E test generation completed",
file_count=len(e2e_files),
)
# Move E2E tests to review directory
if e2e_files:
_move_tests_to_review_directory(
project_dir, spec_dir, e2e_files
)
else:
error = e2e_result.get("error", "Unknown error")
print(f" ⚠️ E2E test generation had issues: {error}")
debug_warning(
"qa_loop", f"E2E test generation incomplete: {error}"
)
except Exception as e:
debug_error("qa_loop", f"E2E test generation failed: {e}")
print(f" ⚠️ E2E test generation failed: {e}")
else:
print(" No testable functions or classes found")
debug("qa_loop", "No testable code found in modified files")
else:
print(" No modified Python files to analyze")
debug("qa_loop", "No modified files found in implementation plan")
# Collect and report test coverage
print("\n📊 Collecting test coverage reports...")
debug("qa_loop", "Starting coverage collection")
try:
coverage_report = collect_coverage(project_dir, framework=None)
if coverage_report:
coverage_summary = format_coverage_summary(coverage_report)
print("\n" + coverage_summary)
debug_success(
"qa_loop",
"Coverage collection completed",
overall_coverage=coverage_report.overall_coverage,
framework=coverage_report.framework,
)
# Save coverage report to spec directory
coverage_file = spec_dir / "coverage_report.json"
import json
coverage_data = {
"overall_coverage": coverage_report.overall_coverage,
"lines_total": coverage_report.lines_total,
"lines_covered": coverage_report.lines_covered,
"lines_missed": coverage_report.lines_missed,
"framework": coverage_report.framework,
"files": [
{
"file_path": f.file_path,
"coverage_percentage": f.coverage_percentage,
"lines_total": f.lines_total,
"lines_covered": f.lines_covered,
"lines_missed": f.lines_missed,
}
for f in coverage_report.files[:20] # Top 20 files
],
"uncovered_files": coverage_report.uncovered_files[
:10
], # Top 10 uncovered
}
coverage_json = json.dumps(coverage_data, indent=2)
await asyncio.to_thread(
coverage_file.write_text, coverage_json, encoding="utf-8"
)
debug("qa_loop", f"Saved coverage report to {coverage_file}")
else:
print(" ⚠️ No coverage reports found")
print(" Run tests with coverage enabled to generate reports")
debug("qa_loop", "No coverage reports available")
except Exception as e:
debug_error("qa_loop", f"Coverage collection failed: {e}")
print(f" ⚠️ Coverage collection failed: {e}")
except Exception as e:
debug_error("qa_loop", f"Test generation failed: {e}")
print(f"\n⚠️ Test generation failed: {e}")
print(" Continuing with QA validation...")
# ==============================================================================
# COVERAGE ENFORCEMENT
# ==============================================================================
# Check if coverage meets minimum threshold before proceeding with QA
if coverage_report and hasattr(coverage_report, "overall_coverage"):
coverage_percentage = (
coverage_report.overall_coverage
) # Already a percentage (0-100) from coverage parsers
if coverage_percentage < MINIMUM_COVERAGE_THRESHOLD:
# Coverage too low - fail validation immediately
coverage_shortfall = MINIMUM_COVERAGE_THRESHOLD - coverage_percentage
debug_error(
"qa_loop",
"Coverage below minimum threshold",
coverage=f"{coverage_percentage:.1f}%",
required=f"{MINIMUM_COVERAGE_THRESHOLD:.1f}%",
shortfall=f"{coverage_shortfall:.1f}%",
)
print("\n❌ COVERAGE REQUIREMENT NOT MET")
print(f" Current Coverage: {coverage_percentage:.1f}%")
print(f" Required Coverage: {MINIMUM_COVERAGE_THRESHOLD:.1f}%")
print(f" Shortfall: {coverage_shortfall:.1f}%")
print("\n Build REJECTED due to insufficient test coverage.")
print(
f" Please add tests to achieve at least {MINIMUM_COVERAGE_THRESHOLD:.1f}% coverage."
)
# Create QA_FIX_REQUEST.md with coverage issue
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
# Get uncovered files for the report
uncovered_files_list = []
if hasattr(coverage_report, "files"):
# Sort files by coverage (lowest first)
low_coverage_files = sorted(
[
f
for f in coverage_report.files
if f.coverage_percentage < MINIMUM_COVERAGE_THRESHOLD
],
key=lambda f: f.coverage_percentage,
)[:10] # Top 10 files needing coverage
uncovered_files_list = [
{
"file_path": f.file_path,
"coverage_percent": f.coverage_percentage,
"lines_missed": f.lines_missed,
"lines_total": f.lines_total,
}
for f in low_coverage_files
]
import json
fix_request_content = f"""# QA Fix Request - Coverage Below Threshold
{QA_FIX_REQUEST_MARKER}
**Generated**: {datetime.now(UTC).isoformat()}
**Status**: REJECTED
**Reason**: Test coverage below minimum requirement
## Coverage Summary
- **Current Coverage**: {coverage_percentage:.1f}%
- **Required Coverage**: {MINIMUM_COVERAGE_THRESHOLD:.1f}%
- **Shortfall**: {coverage_shortfall:.1f}%
- **Lines Covered**: {coverage_report.lines_covered:,} / {coverage_report.lines_total:,}
## Files Requiring Additional Tests
The following files need more test coverage to meet the minimum threshold:
"""
for i, file_info in enumerate(uncovered_files_list, 1):
file_path = file_info["file_path"]
file_coverage = file_info["coverage_percent"]
lines_missed = file_info["lines_missed"]
lines_total = file_info["lines_total"]
lines_covered = lines_total - lines_missed
fix_request_content += f"""### {i}. `{file_path}`
- **Coverage**: {file_coverage:.1f}% ({lines_covered:,}/{lines_total:,} lines)
- **Lines Missing Coverage**: {lines_missed:,}
"""
fix_request_content += """## Required Actions
1. **Add unit tests** for the uncovered code paths
2. **Add integration tests** for API endpoints and service interactions
3. **Add edge case tests** for error conditions and boundary values
4. **Re-run tests** with coverage enabled: `pytest --cov=your_module --cov-report=json`
5. **Re-submit** for QA validation
## Coverage Details
See `coverage_report.json` in the spec directory for detailed coverage information.
To view coverage by file:
```bash
# View coverage report
coverage report -m
# Generate HTML coverage report
coverage html
# Open htmlcov/index.html in your browser
```
## Priority Files
Focus on files with the lowest coverage first for maximum impact.
"""
# Write fix request file
await asyncio.to_thread(
fix_request_file.write_text, fix_request_content, encoding="utf-8"
)
debug("qa_loop", f"Created coverage fix request: {fix_request_file}")
# Record rejection in iteration history
qa_iteration = get_qa_iteration_count(spec_dir)
coverage_issue = {
"type": "critical",
"title": f"Test coverage ({coverage_percentage:.1f}%) below minimum threshold ({MINIMUM_COVERAGE_THRESHOLD:.1f}%)",
"description": f"Build has {coverage_percentage:.1f}% coverage but requires {MINIMUM_COVERAGE_THRESHOLD:.1f}%. Shortfall: {coverage_shortfall:.1f}%",
"file": "N/A",
"line": None,
"coverage_shortfall": coverage_shortfall,
"current_coverage": coverage_percentage,
"required_coverage": MINIMUM_COVERAGE_THRESHOLD,
}
record_iteration(
spec_dir, qa_iteration + 1, "rejected", [coverage_issue], 0.0
)
# Dispatch webhook for coverage failure
try:
dispatch_qa_result(
spec_dir,
spec_id=spec_dir.name,
passed=False,
qa_iteration=qa_iteration + 1,
duration_seconds=0.0,
issues_count=1,
issues=[coverage_issue],
)
debug("qa_loop", "Dispatched qa_failed webhook event (coverage)")
except Exception as e:
debug_warning("qa_loop", f"Failed to dispatch qa_failed webhook: {e}")
# End validation phase with coverage failure
if task_logger:
task_logger.end_phase(
LogPhase.VALIDATION,
success=False,
message=f"Coverage {coverage_percentage:.1f}% below minimum {MINIMUM_COVERAGE_THRESHOLD:.1f}%",
)
return False
else:
debug_success(
"qa_loop",
"Coverage meets minimum threshold",
coverage=f"{coverage_percentage:.1f}%",
required=f"{MINIMUM_COVERAGE_THRESHOLD:.1f}%",
)
# Start validation phase in task logger
if task_logger:
task_logger.start_phase(LogPhase.VALIDATION, "Starting QA validation...")
# Check Linear integration status
linear_task = None
if is_linear_enabled():
linear_task = LinearTaskState.load(spec_dir)
if linear_task and linear_task.task_id:
print(f"Linear task: {linear_task.task_id}")
# Update Linear to "In Review" when QA starts
await linear_qa_started(spec_dir)
print("Linear task moved to 'In Review'")
qa_iteration = get_qa_iteration_count(spec_dir)
consecutive_errors = 0
last_error_context = None # Track error for self-correction feedback
while qa_iteration < MAX_QA_ITERATIONS:
qa_iteration += 1
iteration_start = time_module.time()
debug_section("qa_loop", f"QA Iteration {qa_iteration}")
debug(
"qa_loop",
f"Starting iteration {qa_iteration}/{MAX_QA_ITERATIONS}",
iteration=qa_iteration,
max_iterations=MAX_QA_ITERATIONS,
)
print(f"\n--- QA Iteration {qa_iteration}/{MAX_QA_ITERATIONS} ---")
emit_phase(
ExecutionPhase.QA_REVIEW, f"Running QA review iteration {qa_iteration}"
)
# Run QA reviewer with phase-specific model and thinking budget
qa_model = get_phase_model(spec_dir, "qa", model)
qa_thinking_budget = get_phase_thinking_budget(spec_dir, "qa")
debug(
"qa_loop",
"Creating client for QA reviewer session...",