Integrate QualityTracker with workflow system - #151
Conversation
- Add QualityTracker initialization to WorkerAgent with lazy loading - Record quality metrics after quality gates run in complete_task() - Check for quality degradation before allowing task completion - Create blockers when quality degrades >10% from peak - Add should_recommend_context_reset() method for proactive monitoring - Integrate quality stats into checkpoint metadata - Add 14 comprehensive integration tests This enables continuous quality tracking across AI sessions, detecting degradation patterns and recommending context resets when quality drops significantly.
WalkthroughThis PR integrates quality tracking into WorkerAgent by adding response counting, quality metrics recording, and degradation detection. Task completion now triggers quality gate evaluation and blocker creation when degradation exceeds thresholds. CheckpointMetadata is extended with quality statistics and trends, and a comprehensive integration test suite validates the end-to-end workflow. Changes
Sequence DiagramsequenceDiagram
autonumber
actor User
participant WorkerAgent
participant Database
participant QualityTracker
participant BlockerService
User->>WorkerAgent: complete_task(task)
activate WorkerAgent
Note over WorkerAgent: Execute LLM interactions<br/>(increment response_count)
WorkerAgent->>WorkerAgent: response_count += 1
Note over WorkerAgent: Run quality gates
WorkerAgent->>WorkerAgent: quality_result = run_quality_gates()
WorkerAgent->>WorkerAgent: _ensure_quality_tracker()
WorkerAgent->>Database: Query project_id, workspace_path
activate Database
Database-->>WorkerAgent: workspace_path
deactivate Database
WorkerAgent->>QualityTracker: Initialize with workspace_path
activate QualityTracker
WorkerAgent->>WorkerAgent: _record_quality_metrics(quality_result)
WorkerAgent->>QualityTracker: Record test_pass_rate, coverage
deactivate QualityTracker
WorkerAgent->>WorkerAgent: degradation = _check_quality_degradation()
activate QualityTracker
QualityTracker-->>WorkerAgent: Compare against threshold
deactivate QualityTracker
alt Degradation Detected
WorkerAgent->>WorkerAgent: _create_degradation_blocker(task, degradation)
WorkerAgent->>BlockerService: Create SYNC blocker
activate BlockerService
BlockerService->>Database: Persist blocker record
Database-->>BlockerService: blocker_id
deactivate BlockerService
BlockerService-->>WorkerAgent: blocker_id
WorkerAgent-->>User: Return blocked result
else No Degradation
WorkerAgent-->>User: Return success result
end
deactivate WorkerAgent
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
PR Review: Integrate QualityTracker with workflow systemThis is a well-structured integration that adds continuous quality tracking to the WorkerAgent. The implementation demonstrates good software engineering practices with comprehensive testing and thoughtful design. Here's my detailed review: ✅ Strengths1. Architecture & Design
2. Code Quality
3. Testing
|
Greptile SummaryThis PR successfully integrates QualityTracker into the WorkerAgent workflow to enable continuous quality monitoring and degradation detection across AI sessions. Key Changes:
Implementation Quality:
Minor Issues Found:
Confidence Score: 4/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant Agent as WorkerAgent
participant Gates as QualityGates
participant Tracker as QualityTracker
participant DB as Database
participant FS as FileSystem
Note over Agent: Task Execution
Agent->>Agent: execute_task()
Agent->>Agent: response_count++
Agent->>Agent: Call LLM
Note over Agent: Task Completion Flow
Agent->>Agent: complete_task(task)
Agent->>Agent: _ensure_quality_tracker()
alt Tracker not initialized
Agent->>DB: Get workspace_path
DB-->>Agent: workspace_path
Agent->>Tracker: new QualityTracker(project_path)
Tracker->>FS: Setup .codeframe/quality_history.json
end
Agent->>Gates: run_all_gates(task)
Gates-->>Agent: QualityGateResult
Note over Agent: Record Quality Metrics
Agent->>Agent: _record_quality_metrics()
Agent->>Agent: Parse test/coverage from failures
Agent->>Agent: Detect language with LanguageDetector
Agent->>Tracker: record(QualityMetrics)
Tracker->>FS: Append to quality_history.json
Note over Agent: Check Degradation
Agent->>Agent: _check_quality_degradation()
Agent->>Tracker: check_degradation(threshold=10%)
Tracker->>Tracker: Compare current vs peak metrics
Tracker-->>Agent: degradation result
alt Quality degraded >10%
Agent->>Agent: _create_degradation_blocker()
Agent->>DB: create_blocker(SYNC)
DB-->>Agent: blocker_id
Agent-->>Agent: Return blocked status
else Quality OK and gates passed
Agent->>DB: UPDATE task status=completed
Agent-->>Agent: Return success
else Quality OK but gates failed
Agent->>DB: create_blocker() via gates
Agent-->>Agent: Return blocked status
end
Note over Agent: Checkpoint Creation
Agent->>Agent: CheckpointManager.create_checkpoint()
Agent->>Tracker: get_stats()
Tracker->>FS: Load quality_history.json
Tracker-->>Agent: quality_stats + trend
Agent->>DB: Store checkpoint with quality metadata
|
| # Extract test counts from failure | ||
| reason = getattr(failure, "reason", "") | ||
| # Parse patterns like "3 tests failed" or "Pytest failed: 5 failed" | ||
| import re |
There was a problem hiding this comment.
style: import re inside function body
| import re | |
| import re |
Move to top-level imports (around line 3-7) per Python style conventions
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Prompt To Fix With AI
This is a comment left during a code review.
Path: codeframe/agents/worker_agent.py
Line: 1124:1124
Comment:
**style:** `import re` inside function body
```suggestion
import re
```
Move to top-level imports (around line 3-7) per Python style conventions
<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>
How can I resolve this? If you propose a fix, please make it concise.| # If no failures, assume perfect scores | ||
| if not quality_result.failures: | ||
| test_pass_rate = 100.0 | ||
| # Try to get coverage from other sources if available | ||
| coverage_percentage = 100.0 # Assume passed coverage check |
There was a problem hiding this comment.
style: Assuming 100% pass rate and coverage when gates pass may be inaccurate - quality gates might have different thresholds (e.g. 80% coverage requirement), so passing gates doesn't guarantee 100% metrics. Consider tracking actual metrics from quality gate results or setting these to None when actual values unavailable
Prompt To Fix With AI
This is a comment left during a code review.
Path: codeframe/agents/worker_agent.py
Line: 1144:1148
Comment:
**style:** Assuming 100% pass rate and coverage when gates pass may be inaccurate - quality gates might have different thresholds (e.g. 80% coverage requirement), so passing gates doesn't guarantee 100% metrics. Consider tracking actual metrics from quality gate results or setting these to `None` when actual values unavailable
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
codeframe/lib/checkpoint_manager.py (1)
425-444: Minor inconsistency in quality_trend default handling.When
stats.get("has_data")is falsy,quality_trendremainsNone. However, whenhas_datais truthy buttrendis missing, it defaults to"insufficient_data". This means the same semantic state ("no trend available") can be represented as eitherNoneor"insufficient_data".🔎 Optional refactor for consistency
try: from codeframe.enforcement.quality_tracker import QualityTracker tracker = QualityTracker(project_path=str(self.project_root)) stats = tracker.get_stats() if stats.get("has_data"): quality_stats = { "current": stats.get("current"), "peak": stats.get("peak"), "average": stats.get("average"), "total_checkpoints": stats.get("total_checkpoints"), } quality_trend = stats.get("trend", "insufficient_data") + else: + # Explicitly set trend when no data available for consistency + quality_trend = "insufficient_data" except Exception as e: logger.debug(f"Failed to get quality stats for checkpoint: {e}")codeframe/agents/worker_agent.py (1)
1082-1183: Brittle parsing of quality gate failure messages.Lines 1122-1142 use regex to extract test counts and coverage from failure reason strings (e.g.,
"(\d+)\s*failed"). This approach is fragile because:
- Format dependency: Changes to failure message formatting in quality gates will break metric extraction
- Silent failures: If regex doesn't match, metrics default to zero without warning
- Assumption at line 1148: When no failures exist, coverage is assumed to be 100%, which may not reflect actual coverage if tests passed with low coverage
Consider having
QualityGateResultexpose structured metrics (test counts, coverage percentage) as first-class fields instead of embedding them in failure messages. This would eliminate parsing fragility.Alternatively, add validation to warn when metrics cannot be extracted:
if total_tests == 0 and quality_result.failures: logger.warning("Could not extract test metrics from quality gate failures")
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
codeframe/agents/worker_agent.pycodeframe/core/models.pycodeframe/lib/checkpoint_manager.pytests/integration/test_quality_tracker_integration.py
🧰 Additional context used
📓 Path-based instructions (5)
**/*.py
📄 CodeRabbit inference engine (CLAUDE.md)
Use Python 3.11+ with type hints and async/await for backend development
Files:
codeframe/lib/checkpoint_manager.pycodeframe/core/models.pytests/integration/test_quality_tracker_integration.pycodeframe/agents/worker_agent.py
codeframe/**/*.py
📄 CodeRabbit inference engine (CLAUDE.md)
codeframe/**/*.py: Use FastAPI with AsyncAnthropic for backend API development
Use SQLite with aiosqlite for async database operations
Use tiktoken for token counting in the backend
Use ruff for Python code linting and formatting
Use tiered memory system (HOT/WARM/COLD) for context management to achieve 30-50% token reduction
Implement session lifecycle management with file-based storage in .codeframe/session_state.json for CLI auto-save/restore
Files:
codeframe/lib/checkpoint_manager.pycodeframe/core/models.pycodeframe/agents/worker_agent.py
{codeframe/**/*.py,web-ui/src/**/*.{ts,tsx}}
📄 CodeRabbit inference engine (CLAUDE.md)
{codeframe/**/*.py,web-ui/src/**/*.{ts,tsx}}: Use WebSockets for real-time updates between frontend and backend
Use last-write-wins strategy with backend timestamps for timestamp conflict resolution in multi-agent scenarios
Files:
codeframe/lib/checkpoint_manager.pycodeframe/core/models.pycodeframe/agents/worker_agent.py
tests/**/*.{py,ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use TestSprite and Playwright for E2E testing of workflows
Files:
tests/integration/test_quality_tracker_integration.py
tests/**/*.py
📄 CodeRabbit inference engine (CLAUDE.md)
Run pytest with coverage tracking for Python backend tests
Files:
tests/integration/test_quality_tracker_integration.py
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
Repo: frankbria/codeframe PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-24T04:24:43.804Z
Learning: Applies to scripts/quality-ratchet.py : Track quality metrics using scripts/quality-ratchet.py with auto-reset triggers when quality degrades >10%
📚 Learning: 2025-12-24T04:24:43.804Z
Learnt from: CR
Repo: frankbria/codeframe PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-24T04:24:43.804Z
Learning: Applies to scripts/quality-ratchet.py : Track quality metrics using scripts/quality-ratchet.py with auto-reset triggers when quality degrades >10%
Applied to files:
codeframe/lib/checkpoint_manager.pycodeframe/agents/worker_agent.py
📚 Learning: 2025-12-17T19:21:40.014Z
Learnt from: frankbria
Repo: frankbria/codeframe PR: 128
File: tests/agents/test_bottleneck_detection.py:486-500
Timestamp: 2025-12-17T19:21:40.014Z
Learning: In tests/agents/test_bottleneck_detection.py, test_skip_agents_below_threshold should be async and mock _get_agent_workload to return workload below AGENT_OVERLOAD_THRESHOLD (5) while providing non-empty tasks list to prevent early return in detect_bottlenecks().
Applied to files:
tests/integration/test_quality_tracker_integration.py
🧬 Code graph analysis (2)
codeframe/lib/checkpoint_manager.py (2)
codeframe/enforcement/quality_tracker.py (1)
get_stats(179-205)tests/lib/test_metrics_tracker.py (1)
tracker(31-33)
tests/integration/test_quality_tracker_integration.py (4)
codeframe/agents/worker_agent.py (2)
WorkerAgent(39-1309)_ensure_quality_tracker(111-154)codeframe/enforcement/quality_tracker.py (4)
QualityTracker(37-323)QualityMetrics(23-34)check_degradation(110-177)should_reset_context(285-323)tests/lib/test_checkpoint_manager.py (1)
checkpoint_manager(60-74)codeframe/core/models.py (6)
Task(257-305)TaskStatus(10-18)project_id(234-235)id(230-231)status(246-247)QualityGateResult(906-923)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Frontend Unit Tests
- GitHub Check: Backend Unit Tests
- GitHub Check: Greptile Review
- GitHub Check: E2E Smoke Tests (Chromium)
- GitHub Check: claude-review
🔇 Additional comments (15)
codeframe/core/models.py (1)
937-939: LGTM! Backward-compatible quality tracking fields added correctly.The optional fields with
Nonedefaults ensure existing checkpoints remain valid. The flexible types (Dict[str, Any]andstr) appropriately accommodate evolving quality metrics without requiring schema migrations.codeframe/lib/checkpoint_manager.py (1)
454-455: LGTM! Quality fields properly passed to checkpoint metadata.The fields are correctly included in the
CheckpointMetadataconstruction, maintaining consistency with the schema changes.codeframe/agents/worker_agent.py (6)
111-154: LGTM! Lazy initialization pattern implemented correctly.The method properly checks for cached instances, validates prerequisites, and handles errors gracefully. The workspace path lookup and tracker initialization logic is sound.
482-487: LGTM! Response count tracking added correctly.The counter is incremented after successful LLM calls and includes useful debug logging for monitoring conversation length.
942-963: LGTM! Quality degradation detection integrated into task completion.The workflow correctly records metrics, checks for degradation, and creates blocking issues when quality drops significantly. The early return pattern prevents task completion when degradation is detected, ensuring quality standards are maintained.
1184-1206: LGTM! Degradation check safely delegates to tracker.Proper error handling and fallback to
Nonewhen the tracker is unavailable or encounters errors.
1208-1259: LGTM! Degradation blocker creation follows established patterns.The method formats degradation details into a user-friendly blocker question and correctly limits the number of issues displayed (line 1231:
[:5]) to prevent overwhelming messages.
1261-1309: LGTM! Context reset recommendation includes proper fallback.The fallback behavior (lines 1284-1295) ensures the feature remains functional even when the quality tracker is unavailable, gracefully degrading to response count checks only.
tests/integration/test_quality_tracker_integration.py (7)
25-59: LGTM! Comprehensive fixture setup for integration testing.The
project_rootfixture creates a realistic project structure including.codeframedirectory, source/test directories, andpyproject.tomlfor language detection. This properly mimics the real environment.
114-171: LGTM! Metrics recording tests properly verify integration.The tests appropriately mock external dependencies (quality gates, LLM calls) while testing the actual integration logic. The API key mocking on line 165 prevents accidental real API calls.
176-220: LGTM! Degradation detection test validates blocker creation workflow.The test correctly simulates a scenario where quality gates pass but degradation is detected, verifying that the blocker creation path works as expected.
222-283: LGTM! Context reset recommendation tests cover key scenarios.The test suite validates both the fallback behavior (when tracker is unavailable) and the full integration path, ensuring the feature works correctly in various states.
288-323: LGTM! Checkpoint test verifies quality metadata propagation.The test properly mocks git operations (line 312) to avoid signing issues while testing the real quality tracking integration. The assertions confirm that quality stats flow through to checkpoint metadata as expected.
329-373: LGTM! Tracker initialization tests validate lazy loading.The tests comprehensively cover edge cases (no DB, no task, successful init, caching) and verify the lazy initialization pattern works correctly.
378-464: LGTM! Real tracker tests validate end-to-end behavior.These integration tests use the real
QualityTrackerwithout mocking, verifying that:
- History files are created correctly
- Degradation detection works with real data
- Stable quality scenarios are handled properly
This provides confidence in the complete integration workflow.
This enables continuous quality tracking across AI sessions, detecting degradation patterns and recommending context resets when quality drops significantly.
Closing Issue #110
Summary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.