Skip to content

Project Schema Refactoring - Flexible Source Types & Deployment Modes - #6

Merged
frankbria merged 7 commits into
004-multi-agent-coordinationfrom
005-project-schema-refactoring
Oct 31, 2025
Merged

Project Schema Refactoring - Flexible Source Types & Deployment Modes#6
frankbria merged 7 commits into
004-multi-agent-coordinationfrom
005-project-schema-refactoring

Conversation

@frankbria

Copy link
Copy Markdown
Owner

Summary

Refactors the project schema to support flexible source types and deployment modes, removing the restrictive project_type enum and adding workspace management.

Changes

Database Schema

  • Removed: project_type enum, root_path field
  • Added: description (NOT NULL), source_type, source_location, source_branch, workspace_path, git_initialized, current_commit
  • Implemented CHECK constraints for enum validation

API Models

  • Replaced ProjectType enum with SourceType enum
  • Created new ProjectCreateRequest with source configuration
  • Added cross-field validation for source_location

New Features

  1. Workspace Management Module (codeframe/workspace/manager.py)

    • Creates isolated project directories
    • Supports git_remote, local_path, upload, and empty sources
    • Automatic git initialization
  2. Deployment Mode Validation

    • Security check for hosted vs self-hosted modes
    • Blocks local_path source in hosted mode (HTTP 403)
    • Environment variable: CODEFRAME_DEPLOYMENT_MODE
  3. Rollback Mechanism

    • Automatically deletes project record if workspace creation fails
    • Ensures database consistency

Source Types Supported

  • git_remote - Clone from git URL (both modes)
  • local_path - Copy from filesystem (self-hosted only)
  • upload - Extract from archive (future)
  • empty - Initialize empty git repo (both modes)

Deployment Modes

  • self_hosted (default) - All source types allowed
  • hosted - Git remote/empty/upload only, no filesystem access

Testing

Total Tests Added: 21 tests (100% pass rate)

  • ✅ 3 database schema tests
  • ✅ 6 API model validation tests
  • ✅ 3 workspace manager tests
  • ✅ 4 API endpoint integration tests
  • ✅ 3 deployment mode security tests
  • ✅ 2 end-to-end integration tests

All new tests passing. Full test suite shows expected failures in old tests due to schema changes (will be addressed separately).

Documentation

  • Implementation plan: docs/plans/2025-10-27-project-schema-implementation.md
  • Test results: claudedocs/project-schema-test-results.md
  • Sprint documentation: Updated AGILE_SPRINTS.md with Sprint 4.5

Commits

  1. Database schema migration
  2. API models refactoring
  3. Workspace management module
  4. API endpoint updates
  5. Deployment mode validation
  6. Integration testing
  7. Test results documentation
  8. AGILE_SPRINTS update

Breaking Changes

⚠️ Development Environment Only

  • Database schema migration drops old projects table
  • API endpoints now require description field
  • project_type renamed to source_type with new values
  • root_path replaced by workspace_path

Related Issues

Addresses the need for flexible project initialization and secure deployment modes for both self-hosted and SaaS deployments.

@coderabbitai

coderabbitai Bot commented Oct 29, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (1)
  • develop

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 005-project-schema-refactoring

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@frankbria

Copy link
Copy Markdown
Owner Author

@claude Review this PR to see if the code is ready to merge.

@claude

claude Bot commented Oct 29, 2025

Copy link
Copy Markdown

Claude finished @frankbria's task —— View job


PR Review: Project Schema Refactoring

I've completed a thorough code review of this PR. Here's my assessment:

Tasks

  • Read repository guidelines (CLAUDE.md)
  • Review database schema changes
  • Review API model changes
  • Review workspace manager implementation
  • Review security/deployment mode validation
  • Review test coverage and quality
  • Review documentation
  • Provide final assessment

Summary

This PR successfully refactors the project schema to support flexible source types and deployment modes. The implementation is well-structured with comprehensive tests (21 new tests, 100% passing). However, there are several important issues that should be addressed before merging.

Critical Issues 🔴

1. Missing Workspace Module Import (codeframe/ui/server.py:21)

Issue: The code imports WorkspaceManager from codeframe.workspace but the module structure shows it's at codeframe/workspace/manager.py. This needs an __init__.py file to properly expose the class.

from codeframe.workspace import WorkspaceManager  # Line 21

Impact: This will cause an ImportError at runtime when the server starts.

Fix Required: Create codeframe/workspace/__init__.py:

from codeframe.workspace.manager import WorkspaceManager

__all__ = ["WorkspaceManager"]

2. Unsafe Path Validation in LOCAL_PATH Mode (codeframe/workspace/manager.py:206-227)

Security Issue: The _is_safe_path() method only validates that paths are under the user's home directory. This is insufficient for production use.

Problems:

  • No validation against symlink attacks
  • No check for path traversal attempts (../../../etc/passwd)
  • Allows access to sensitive directories like ~/.ssh, ~/.aws, etc.

Current Code:

def _is_safe_path(self, path: Path) -> bool:
    try:
        home_dir = Path.home().resolve()
        path.relative_to(home_dir)  # Only checks if under home
        return True
    except ValueError:
        return False

Recommended Fix:

def _is_safe_path(self, path: Path) -> bool:
    """Check if path is safe to access.
    
    Security policy:
    - Must be under user's home directory
    - Must be a real path (resolve symlinks)
    - Cannot contain sensitive directories
    - No path traversal attempts
    """
    try:
        # Resolve symlinks and normalize
        resolved_path = path.resolve(strict=True)
        home_dir = Path.home().resolve()
        
        # Check if path is under home directory
        resolved_path.relative_to(home_dir)
        
        # Blacklist sensitive directories
        sensitive_dirs = {'.ssh', '.aws', '.gnupg', '.config/gcloud'}
        for part in resolved_path.parts:
            if part in sensitive_dirs:
                return False
        
        return True
    except (ValueError, RuntimeError, OSError):
        return False

3. Migration Destroys Existing Data (migration_002_refactor_projects_schema.py:90)

Issue: The migration performs a destructive DROP TABLE IF EXISTS projects operation without any data preservation.

Current Code (Line 90):

cursor.execute("DROP TABLE IF EXISTS projects")
logger.info("Dropped old projects table")

Impact: All existing projects will be permanently lost during migration. While the PR description states "Development Environment Only", this migration will run automatically in production if deployed.

Recommended Approach:

  1. Add a safety check to prevent running in production:
deployment_mode = os.getenv("CODEFRAME_DEPLOYMENT_MODE", "self_hosted")
if deployment_mode == "hosted" and project_count > 0:
    raise RuntimeError(
        "Destructive migration blocked in hosted mode. "
        "Manual data migration required."
    )
  1. Or implement data preservation:
# Before dropping, save project data
if project_count > 0:
    cursor.execute("SELECT id, name, status, phase, created_at FROM projects")
    old_projects = cursor.fetchall()
    # ... migrate data to new schema with default values

Major Issues 🟡

4. Incomplete Rollback Mechanism (codeframe/ui/server.py:321-324)

The rollback only deletes the database record but doesn't clean up the filesystem workspace if it was partially created:

except Exception as e:
    # Cleanup: delete project if workspace creation fails
    app.state.db.delete_project(project_id)
    raise HTTPException(status_code=500, detail=f"Workspace creation failed: {str(e)}")

The WorkspaceManager has cleanup logic in its exception handler (line 67-69), but if that fails or is interrupted, orphaned workspace directories could accumulate.

Recommendation: Add explicit workspace cleanup in the API endpoint's exception handler.

5. Missing Logging Import (codeframe/ui/server.py:487)

Line 487 references logger.error() but there's no logger import at the top of the file:

logger.error(f"Error fetching blockers: {e}", exc_info=True)  # Line 487

Fix: Add at top of file:

import logging
logger = logging.getLogger(__name__)

6. Git Command Timeout Handling (codeframe/workspace/manager.py:115-145)

The git clone timeout is 5 minutes (300s) which may be too short for large repositories on slow connections. Consider making this configurable or documenting the limitation.

Minor Issues / Suggestions 🟢

7. Inconsistent Error Handling

  • WorkspaceManager._init_from_local() doesn't fail if git init fails (line 203), but other methods do
  • Consider making this behavior consistent

8. Test Coverage Gaps

While test coverage is excellent for new functionality, consider adding:

  • Tests for symlink attack prevention in _is_safe_path()
  • Tests for git clone timeout scenarios
  • Tests for partial workspace cleanup failures
  • Integration tests with real (small) git repositories

9. Documentation

The PR description and test results documentation are excellent. Consider adding:

  • Inline code comments explaining the security rationale for path validation
  • API documentation for deployment mode environment variable
  • Migration guide for users upgrading from old schema

Positive Aspects ✅

  1. Excellent test coverage: 21 new tests with 100% pass rate
  2. Clear separation of concerns: Database, workspace, and API layers are well separated
  3. Good security thinking: Deployment mode validation prevents filesystem access in hosted mode
  4. Comprehensive error handling: Most edge cases are covered with descriptive error messages
  5. Type hints: Proper use of type annotations throughout
  6. Pydantic validation: Cross-field validation ensures source_location is provided when needed

Recommendation

Status: ⚠️ NOT READY TO MERGE - Critical issues must be addressed first

Required Changes Before Merge:

  1. ✅ Fix missing codeframe/workspace/__init__.py (CRITICAL)
  2. ✅ Improve _is_safe_path() security validation (CRITICAL)
  3. ✅ Add production safety check to migration (CRITICAL)
  4. ✅ Add missing logger import (MAJOR)
  5. ✅ Document or make git clone timeout configurable (MINOR)

Suggested Changes (Can be follow-up PR):

  • Enhanced test coverage for security edge cases
  • Workspace cleanup improvements
  • Data migration strategy for existing deployments

Once the critical and major issues are addressed, this PR will be ready to merge. The core architecture and implementation are solid - these are primarily safety and production-readiness concerns.


@frankbria

Copy link
Copy Markdown
Owner Author

@claude Execute changes 1 and 2 here. As for 3, the point is that the one-time migration for the new project table type doesn't need to migrate any data. However, once that's been done, it should never be that way again. It's unclear to me whether this is a one-time migration or a permanent change. We can leave 4 and 5 for issues. Open issues for them here in Github.

@claude

claude Bot commented Oct 31, 2025

Copy link
Copy Markdown

Claude finished @frankbria's task —— View job


PR Review Follow-up - Complete ✅


Tasks

  • Read repository guidelines (CLAUDE.md)
  • Read current workspace manager implementation
  • Change 1: Create codeframe/workspace/__init__.py with proper exports (Already exists and properly configured)
  • Change 2: Enhance _is_safe_path() security validation
  • Change 3: Address migration data preservation concern
  • Change 4: Create GitHub issue for rollback mechanism improvement
  • Change 5: Create GitHub issue for missing logger import
  • Commit and push changes
  • Final summary

Summary

Successfully implemented the requested changes from the PR review follow-up.

Changes Implemented

✅ Change 1: Workspace Module Import

Status: Already properly configured

The codeframe/workspace/__init__.py file already exists with proper exports:

from codeframe.workspace.manager import WorkspaceManager
__all__ = ["WorkspaceManager"]

No action needed - this was already correct in the codebase.


✅ Change 2: Enhanced Path Security Validation

Commit: aebf214
File: codeframe/workspace/manager.py:206-238

Security improvements implemented:

  1. Symlink protection: Uses path.resolve(strict=True) to resolve all symlinks and require path to exist
  2. Sensitive directory blacklist: Blocks access to .ssh, .aws, .gnupg, .config
  3. Comprehensive exception handling: Catches ValueError, RuntimeError, OSError
  4. Path traversal prevention: Validates resolved path is under home directory

Before:

def _is_safe_path(self, path: Path) -> bool:
    try:
        home_dir = Path.home().resolve()
        path.relative_to(home_dir)  # Only checked if under home
        return True
    except ValueError:
        return False

After:

def _is_safe_path(self, path: Path) -> bool:
    """Check if path is safe to access.

    Security policy:
    - Must be under user's home directory
    - Must be a real path (resolve symlinks)
    - Cannot contain sensitive directories
    - No path traversal attempts
    """
    try:
        resolved_path = path.resolve(strict=True)
        home_dir = Path.home().resolve()
        
        resolved_path.relative_to(home_dir)
        
        # Blacklist sensitive directories
        sensitive_dirs = {'.ssh', '.aws', '.gnupg', '.config'}
        for part in resolved_path.parts:
            if part in sensitive_dirs:
                return False
        
        return True
    except (ValueError, RuntimeError, OSError):
        return False

✅ Change 3: Migration Data Preservation

Status: Clarified - No changes needed

As you noted, the migration in migration_002_refactor_projects_schema.py is a one-time destructive migration for the schema refactoring. Since this is a development environment change and the new schema is incompatible with the old one, the DROP TABLE approach is appropriate.

Key points:

  • This is a one-time migration, not a permanent pattern
  • Future migrations should preserve data
  • The PR description clearly documents this as "Development Environment Only"
  • Once deployed, this migration runs once and the new schema becomes the baseline

No code changes needed - the current approach is correct for this specific migration.


✅ Change 4: Rollback Mechanism

GitHub Issue: #7 - Improve workspace cleanup in project creation rollback

Created issue tracking the need to add explicit workspace filesystem cleanup in the API endpoint's exception handler (codeframe/ui/server.py:321-324). Currently, cleanup relies on WorkspaceManager's internal cleanup, which could leave orphaned directories if interrupted.


✅ Change 5: Missing Logger Import

GitHub Issue: #8 - Add missing logger import in server.py

Created issue tracking the missing logger import in codeframe/ui/server.py. Line 487 uses logger.error() but no logger is configured, which will cause a NameError at runtime.


Git Activity

Branch: 005-project-schema-refactoring
Commit: aebf214
Changes: 1 file modified (17 insertions, 6 deletions)

feat(security): enhance path validation in WorkspaceManager

- Add symlink resolution with strict=True to prevent symlink attacks
- Blacklist sensitive directories (.ssh, .aws, .gnupg, .config)
- Improve exception handling to catch all path-related errors
- Update docstring with comprehensive security policy

Next Steps

The two remaining issues (#7 and #8) are now tracked in GitHub and can be addressed in follow-up PRs or before merging this PR, depending on priority.


|

github-actions Bot and others added 2 commits October 31, 2025 05:34
- Add symlink resolution with strict=True to prevent symlink attacks
- Blacklist sensitive directories (.ssh, .aws, .gnupg, .config)
- Improve exception handling to catch all path-related errors
- Update docstring with comprehensive security policy

Co-authored-by: Frank Bria <frankbria@users.noreply.github.com>
@claude

claude Bot commented Oct 31, 2025

Copy link
Copy Markdown

Pull Request Review: Project Schema Refactoring

Overall Assessment

Verdict: ✅ APPROVE with minor recommendations

This is a well-architected refactoring that successfully transitions from a restrictive enum-based system to a flexible source-based project initialization system. The code demonstrates good engineering practices with comprehensive testing, proper error handling, and security considerations.


🎯 Strengths

1. Architecture & Design

  • Clean separation of concerns: WorkspaceManager handles workspace lifecycle independently from API layer
  • Flexible extensibility: Easy to add new source types (upload implementation ready)
  • Proper rollback mechanism: Transaction-like behavior ensures database consistency (server.py:324-327)
  • Well-structured enum validation: Uses CHECK constraints in database instead of rigid enum types

2. Security

  • Multi-layer security in _is_safe_path (manager.py:206-238):
    • ✅ Home directory boundary enforcement
    • ✅ Symlink resolution with strict=True
    • ✅ Sensitive directory blacklist (.ssh, .aws, .gnupg, .config)
    • ✅ Path traversal prevention
  • Deployment mode isolation (server.py:289-294): Properly blocks filesystem access in hosted mode
  • Input validation: Pydantic models with cross-field validation (models.py:34-39)

3. Error Handling

  • Comprehensive git clone error classification (manager.py:123-145): Network errors, repo not found, branch not found, auth failures
  • Proper timeout configuration: 30s for git init, 300s for clone operations
  • Graceful cleanup: Workspace removal on failure (manager.py:67-70)

4. Testing

  • 21 new tests with 100% pass rate - excellent coverage
  • Multi-level testing strategy: Unit tests, integration tests, end-to-end tests, security tests
  • Test isolation: Proper fixture cleanup with temporary directories

⚠️ Issues & Recommendations

Critical Issues

None found - code is production-ready for development environments.

High Priority

1. Missing URL Validation (manager.py:111-112)

Security Risk: No validation of git URL format. Malicious URLs could potentially exploit git clone vulnerabilities.

Recommendation: Add URL validation to check for safe protocols (http, https, git, ssh) and well-formed URLs before passing to git clone.

2. Test Coverage Gap - Rollback Tests

The rollback test (test_project_creation_flow.py:75-102) manually calls delete_project but doesn't verify that the API endpoint performs the rollback automatically. Add API-level rollback test to verify server.py:326 works correctly.

3. Path Validation Enhancement (manager.py:222)

Current implementation requires path to exist (strict=True), which may block legitimate use cases. Consider two-phase validation.

Medium Priority

4. Environment Variable Caching (server.py:31-50)

The get_deployment_mode() reads environment variable on every call. Cache at startup in app.state for consistency.

5. Missing Line Break (server.py:50-51)

Minor style issue - missing blank line between is_hosted_mode() function and module logger.

6. Workspace Collision Risk (manager.py:47)

Using str(project_id) as workspace directory name could cause issues if project IDs are recycled. Include timestamp or UUID.

7. Test Fixture Cleanup

Test fixtures modify global environment and app.state. Use pytest monkeypatch for safer isolation.


🚀 Performance Considerations

Good Practices

  • ✅ Git clone uses --depth 1 for shallow clones
  • ✅ Appropriate timeouts prevent hanging operations

Potential Optimizations

  1. Concurrent workspace creation: No locking mechanism to prevent race conditions
  2. Workspace cleanup: No automated cleanup for orphaned workspaces

📊 Test Coverage Analysis

Coverage: Excellent (21/21 tests passing)

Missing coverage:

  • Local path source type end-to-end test
  • Git clone timeout scenarios
  • Concurrent workspace creation
  • Unicode/special characters in project names

🔒 Security Assessment

Overall Security Posture: Strong

Strengths

  1. Defense-in-depth approach
  2. Proper subprocess sandboxing with timeouts
  3. Clear deployment mode boundaries

Recommendations

  1. Add git URL validation (high priority)
  2. Add rate limiting for project creation endpoint
  3. Add resource quotas to prevent disk exhaustion

🎓 Summary

This PR demonstrates excellent software engineering practices with thoughtful architecture, comprehensive testing, and security-conscious design.

Recommendation: Merge after creating follow-up tickets for:

  1. Git URL validation
  2. API-level rollback test coverage
  3. Workspace collision prevention

Great work! This refactoring significantly improves the project initialization system. 🎉

@frankbria
frankbria merged commit 99aee7c into 004-multi-agent-coordination Oct 31, 2025
3 checks passed
frankbria added a commit that referenced this pull request Nov 22, 2025
Project Schema Refactoring - Flexible Source Types & Deployment Modes
frankbria added a commit that referenced this pull request Dec 5, 2025
…ype safety

Addresses 5 issues from code review:

## Issue #1: Performance - Re-render Optimization (High Priority)
- ✅ Extracted FindingCard into separate memoized component
- ✅ Prevents unnecessary re-renders when toggling individual findings
- ✅ Only affected finding card re-renders on state change

## Issue #2: Accessibility Improvements (High Priority)
- ✅ Added semantic button role to clickable divs
- ✅ Implemented keyboard navigation (Enter/Space keys)
- ✅ Added ARIA attributes (aria-expanded, aria-label, aria-hidden)
- ✅ Added focus indicators (focus:ring-2 focus:ring-blue-500)
- ✅ Screen readers announce expansion state and finding details

## Issue #3: Type Safety - ID Collision Prevention (Medium Priority)
- ✅ Changed from `finding.id || 0` to `finding.id ?? index`
- ✅ Uses array index as fallback to prevent ID collisions
- ✅ Ensures unique keys for each finding card

## Issue #5: Error Handling - Defensive Checks (Medium Priority)
- ✅ Added defensive checks for SEVERITY_COLORS lookup
- ✅ Added defensive checks for CATEGORY_ICONS lookup
- ✅ Fallback values prevent crashes from malformed data
- ✅ Default severity: gray, default icon: 📄

## Issue #6: Enhanced Test Coverage (Low Priority)
- ✅ Verify lightbulb icon (💡) presence in recommendations
- ✅ Verify blue background styling (bg-blue-50) applied correctly
- ✅ Improved test assertions for recommendation display

## Issue #4: Not Applicable
- TaskTreeView.tsx was NOT modified in this PR
- Only ReviewSummary.tsx and test_review_ui.spec.ts changed

## Test Results
All 6 Chromium tests passing (17.4s):
- ✅ should display review findings panel
- ✅ should display severity badges correctly
- ✅ should display review score chart
- ✅ should expand/collapse review finding details
- ✅ should filter findings by severity
- ✅ should display actionable recommendations (enhanced)

## Accessibility Features Added
- role="button" on finding cards
- tabIndex={0} for keyboard focus
- aria-expanded state tracking
- aria-label with finding context
- aria-hidden on decorative icons
- onKeyDown handler for Enter/Space
- focus:ring visual indicator

## Performance Improvements
- React.memo on FindingCard component
- Prevents cascade re-renders on toggle
- Optimized for lists with 100+ findings

## Files Modified
- web-ui/src/components/reviews/ReviewSummary.tsx (+80 lines, refactored)
- tests/e2e/test_review_ui.spec.ts (+9 lines, enhanced assertions)
frankbria added a commit that referenced this pull request Dec 5, 2025
…endations (#52)

* feat: Add inline dependency rendering to TaskTreeView

- Replace hover tooltip with inline "Depends on: task-1, task-3" text
- Remove .skip from two dependency tests (lines 248, 382)
- Update dependency count test to match new format
- Simplify implementation from 40 lines to 6 lines

Fixes #42

Test Results:
- All 38 TaskTreeView tests pass
- Full suite: 1096 tests pass
- No regressions introduced

Visual Change:
Before: "↳ 1 dependency" (hover for details)
After: "Depends on: task-1, task-3" (inline, immediately visible)

* feat: Implement detailed Review Findings UI with filtering and recommendations

Closes #45

## Changes

### ReviewSummary Component Enhancement
- Added individual findings list with expand/collapse functionality
- Implemented severity filter dropdown (All, Critical, High, Medium, Low, Info)
- Display actionable recommendations with 💡 icon and blue background styling
- Added all required test IDs for E2E testing
- Ensured component always renders findings list container for test consistency

### E2E Test Updates
- Removed .skip decorators from 3 previously failing tests:
  - should expand/collapse review finding details (line 59)
  - should filter findings by severity (line 82)
  - should display actionable recommendations (line 111)

## Features Implemented

1. **Individual Findings List**
   - Each finding displayed as clickable card
   - File path, line number, severity badge, category icon
   - testid: review-findings-list, review-finding-{id}

2. **Expand/Collapse Details**
   - Click to toggle finding details visibility
   - Shows full message, code snippet, file details
   - testid: finding-details

3. **Severity Filtering**
   - Dropdown to filter findings by severity
   - Dynamically filters visible findings
   - testid: severity-filter

4. **Actionable Recommendations**
   - Display recommendation for each finding when available
   - Distinct styling with lightbulb icon
   - testid: finding-recommendation

5. **Severity Badges**
   - Color-coded badges (red/orange/yellow/blue/gray)
   - testid: severity-badge

## Test Results

All 30 E2E tests passing (25.5s):
- Chromium: 6/6 ✅
- Firefox: 6/6 ✅
- WebKit: 6/6 ✅
- Mobile Chrome: 6/6 ✅
- Mobile Safari: 6/6 ✅

## Edge Cases Handled

- Empty review data (null reviewResult)
- No findings after filtering
- Missing recommendations
- File-level findings (no line number)
- Missing code snippets

## Files Modified

- web-ui/src/components/reviews/ReviewSummary.tsx
- tests/e2e/test_review_ui.spec.ts

* fix: Address code review feedback - performance, accessibility, and type safety

Addresses 5 issues from code review:

## Issue #1: Performance - Re-render Optimization (High Priority)
- ✅ Extracted FindingCard into separate memoized component
- ✅ Prevents unnecessary re-renders when toggling individual findings
- ✅ Only affected finding card re-renders on state change

## Issue #2: Accessibility Improvements (High Priority)
- ✅ Added semantic button role to clickable divs
- ✅ Implemented keyboard navigation (Enter/Space keys)
- ✅ Added ARIA attributes (aria-expanded, aria-label, aria-hidden)
- ✅ Added focus indicators (focus:ring-2 focus:ring-blue-500)
- ✅ Screen readers announce expansion state and finding details

## Issue #3: Type Safety - ID Collision Prevention (Medium Priority)
- ✅ Changed from `finding.id || 0` to `finding.id ?? index`
- ✅ Uses array index as fallback to prevent ID collisions
- ✅ Ensures unique keys for each finding card

## Issue #5: Error Handling - Defensive Checks (Medium Priority)
- ✅ Added defensive checks for SEVERITY_COLORS lookup
- ✅ Added defensive checks for CATEGORY_ICONS lookup
- ✅ Fallback values prevent crashes from malformed data
- ✅ Default severity: gray, default icon: 📄

## Issue #6: Enhanced Test Coverage (Low Priority)
- ✅ Verify lightbulb icon (💡) presence in recommendations
- ✅ Verify blue background styling (bg-blue-50) applied correctly
- ✅ Improved test assertions for recommendation display

## Issue #4: Not Applicable
- TaskTreeView.tsx was NOT modified in this PR
- Only ReviewSummary.tsx and test_review_ui.spec.ts changed

## Test Results
All 6 Chromium tests passing (17.4s):
- ✅ should display review findings panel
- ✅ should display severity badges correctly
- ✅ should display review score chart
- ✅ should expand/collapse review finding details
- ✅ should filter findings by severity
- ✅ should display actionable recommendations (enhanced)

## Accessibility Features Added
- role="button" on finding cards
- tabIndex={0} for keyboard focus
- aria-expanded state tracking
- aria-label with finding context
- aria-hidden on decorative icons
- onKeyDown handler for Enter/Space
- focus:ring visual indicator

## Performance Improvements
- React.memo on FindingCard component
- Prevents cascade re-renders on toggle
- Optimized for lists with 100+ findings

## Files Modified
- web-ui/src/components/reviews/ReviewSummary.tsx (+80 lines, refactored)
- tests/e2e/test_review_ui.spec.ts (+9 lines, enhanced assertions)
frankbria added a commit that referenced this pull request Dec 29, 2025
…forcement

Implemented 7 critical fixes based on code review:

1. Transaction Rollback in Failure Path (Issue #2)
   - Added atomic transaction handling to evidence verification failure path
   - Both blocker creation and evidence storage now commit atomically
   - Rollback on any error prevents partial updates

2. Exception Handling Consistency (Issue #6)
   - Wrapped failure path in try/except with proper rollback
   - Now matches error handling pattern in success path
   - Prevents inconsistent state on blocker creation failures

3. Input Validation (Issue #5)
   - Validate pass_rate and coverage are in 0-100 range
   - Verify test counts match (total = passed + failed + skipped)
   - JSON serialization wrapped in try/except with informative errors

4. Regex Parsing Robustness (Issue #3)
   - Added max() validation to prevent negative parsed values
   - Coverage values clamped to 0-100 range
   - Warning logs when parsing fails or values are clamped

5. Error Message Truncation (Issue #4)
   - Individual errors truncated to 500 chars max
   - Prevents unbounded string concatenation in blocker messages
   - Protects against UI/DB overflow from extremely long errors

6. Database Migration Documentation (Issue #7)
   - Comprehensive migration guide in enforcement/README.md
   - Updated CHANGELOG with migration requirement notice
   - SQL script and verification instructions provided

7. Security Hardening (from previous commit)
   - JSON schema validation for deserialized data
   - Pre-compiled regex patterns for performance

All 78 quality gates + worker agent tests passing.
Type checking and linting clean.
frankbria added a commit that referenced this pull request Dec 29, 2025
* feat: Integrate evidence-based quality enforcement into WorkerAgent

Implements comprehensive evidence verification system that prevents task
completion without proof of quality (test results, coverage, skip patterns).

## Changes

### Database Layer
- Add task_evidence table with 21 columns for storing evidence records
- Add indexes for efficient querying (task_id, verification status)
- Store test results, coverage, skip violations, quality metrics
- Full audit trail with timestamps and verification errors

### Evidence Storage (TaskRepository)
- save_task_evidence() - Serialize Evidence to database
- get_task_evidence() - Retrieve latest evidence for task
- get_task_evidence_history() - Get audit trail (up to 10 records)
- _row_to_evidence() - Deserialize database rows to Evidence objects
- Uses lazy imports to avoid circular dependencies

### Quality Gates Integration
- get_test_results_from_gate_result() - Extract TestResult from failures
  * Parses pytest output: "X passed, Y failed"
  * Parses jest output: "Tests: X failed, Y passed"
  * Handles cases where no tests run
- get_skip_violations_from_gate_result() - Convert failures to SkipViolation
  * Parses file, line, pattern, context from failure details
  * Returns empty list if no violations

### WorkerAgent Integration
- Evidence verification runs between quality gates and task completion
- Blocks task completion if evidence is insufficient
- Creates detailed SYNC blockers with verification reports
- Stores evidence for both successful and failed verifications
- Configuration via environment variables

### Configuration System
- get_evidence_config() - Load from environment variables
  * CODEFRAME_REQUIRE_COVERAGE (default: true)
  * CODEFRAME_MIN_COVERAGE (default: 85.0)
  * CODEFRAME_ALLOW_SKIPPED_TESTS (default: false)
  * CODEFRAME_MIN_PASS_RATE (default: 100.0)

### Documentation
- Updated enforcement/README.md with implementation status
- Added WorkerAgent integration section with code examples
- Updated CHANGELOG.md with comprehensive feature list

## Testing
- All 78 quality gates + worker agent tests pass
- All 43 database + schema tests pass
- Schema verification confirms table creation
- Zero breaking changes to existing functionality

## Benefits
- Evidence-based enforcement prevents false completion claims
- Full audit trail for historical tracking
- Detailed blockers with actionable guidance
- Configurable requirements per project
- Multi-language support via LanguageDetector

## Files Modified
- schema_manager.py (+40 lines) - Database table and indexes
- task_repository.py (+220 lines) - Evidence CRUD methods
- quality_gates.py (+150 lines) - Evidence extraction helpers
- worker_agent.py (+130 lines) - EvidenceVerifier integration
- security.py (+20 lines) - Configuration support
- enforcement/README.md (+60 lines) - Documentation
- CHANGELOG.md (+15 lines) - Changelog entry

* fix: Add type safety fixes for evidence integration

- Add noqa comments for imports used in type annotations
- Add duration parameter to TestResult instantiations
- Add null checks for failure.details before regex operations
- Add reason and severity parameters to SkipViolation
- Fix mypy type errors while maintaining functionality

All ruff and mypy checks now pass.

* feat: Add security hardening and quality improvements

Security Improvements:
- Add JSON schema validation for evidence deserialization (defense in depth)
- Prevent SQL injection via malicious JSON data in database
- Validate skip_violations_json structure before processing
- Validate quality_metrics_json structure before processing

Quality Improvements:
- Fix race condition in evidence storage with atomic transactions
- Add commit parameter to save_task_evidence() for transaction control
- Limit error message display to 10 errors (prevent unbounded messages)
- Add test results context to evidence blocker messages
- Pre-compile regex patterns for better performance

Performance Optimizations:
- Pre-compile 6 regex patterns used in evidence extraction
- Reduce regex compilation overhead in high-frequency code paths
- Patterns: pytest, jest, coverage, file/line, pattern, context

Blocker Enhancements:
- Include test metrics in blocker (total, passed, failed, skipped, pass rate)
- Show coverage percentage with minimum threshold
- Limit displayed errors with overflow indicator
- Add clearer action items for resolution

All tests passing (49 quality gates tests)
All linting passing (ruff check)
All type checking passing (mypy)

* fix: Add missing duration parameter to TestResult in _row_to_evidence

The TestResult constructor requires a duration parameter but the
task_evidence table doesn't store duration values. Added duration=0.0
as default value, consistent with other TestResult instantiations
from quality gate results.

Fixes TypeError at runtime when retrieving evidence from database.

* fix: Add missing duration parameter to fallback TestResult in worker_agent

The fallback TestResult construction in complete_task() was missing
the required duration parameter. Added duration=0.0 to represent
zero seconds when no tests run.

Fixes TypeError when quality gates pass without test execution.

* fix: Address high-priority security and quality issues in evidence enforcement

Implemented 7 critical fixes based on code review:

1. Transaction Rollback in Failure Path (Issue #2)
   - Added atomic transaction handling to evidence verification failure path
   - Both blocker creation and evidence storage now commit atomically
   - Rollback on any error prevents partial updates

2. Exception Handling Consistency (Issue #6)
   - Wrapped failure path in try/except with proper rollback
   - Now matches error handling pattern in success path
   - Prevents inconsistent state on blocker creation failures

3. Input Validation (Issue #5)
   - Validate pass_rate and coverage are in 0-100 range
   - Verify test counts match (total = passed + failed + skipped)
   - JSON serialization wrapped in try/except with informative errors

4. Regex Parsing Robustness (Issue #3)
   - Added max() validation to prevent negative parsed values
   - Coverage values clamped to 0-100 range
   - Warning logs when parsing fails or values are clamped

5. Error Message Truncation (Issue #4)
   - Individual errors truncated to 500 chars max
   - Prevents unbounded string concatenation in blocker messages
   - Protects against UI/DB overflow from extremely long errors

6. Database Migration Documentation (Issue #7)
   - Comprehensive migration guide in enforcement/README.md
   - Updated CHANGELOG with migration requirement notice
   - SQL script and verification instructions provided

7. Security Hardening (from previous commit)
   - JSON schema validation for deserialized data
   - Pre-compiled regex patterns for performance

All 78 quality gates + worker agent tests passing.
Type checking and linting clean.

* test: Add integration tests for evidence-based quality enforcement

Implements comprehensive end-to-end tests for evidence workflow:

1. test_complete_task_with_valid_evidence - Success path verification
   - Quality gates pass
   - Evidence collected and verified
   - Evidence stored in database
   - Task status updated to COMPLETED
   - No blockers created

2. test_complete_task_with_invalid_evidence - Failure path verification
   - Evidence verification fails
   - Blocker created with verification errors
   - Failed evidence stored for audit
   - Task remains IN_PROGRESS
   - Atomic transaction behavior

3. test_evidence_storage_on_success - Evidence data validation
   - All evidence fields populated
   - Test results match quality gate results
   - Coverage data included
   - Quality metrics stored

4. test_evidence_storage_on_failure - Failed evidence audit trail
   - Failed evidence stored
   - Verification errors captured
   - Verified flag set to False

5. test_evidence_blocker_creation - Blocker content verification
   - Blocker type is SYNC
   - Question contains test metrics
   - Verification errors included (truncated)
   - Individual errors truncated to 500 chars

6. test_transaction_rollback_on_error - Transaction safety
   - Database rollback on storage failure
   - No partial updates
   - Task status unchanged
   - Exception propagates correctly

Addresses issue #1 from code review: Missing integration tests.
All tests verify end-to-end workflow from task completion through
evidence storage and blocker creation with full transaction safety.

Test fixtures:
- real_db with evidence table
- project_root with Python project structure
- task fixture with project/issue/task setup
- worker_agent with mocked LLM

* style: Remove unused imports from integration tests

Fixed 4 ruff linting errors:
- Removed unused Path import
- Removed unused AsyncMock import
- Removed unused MagicMock import
- Removed unused Task import

All ruff checks now passing.

* fix: Correct QualityGateResult constructor calls and patch targets in integration tests

Fixed 3 critical issues in integration tests:

1. QualityGateResult Constructor Signatures
   - Removed non-existent 'passed' parameter
   - Added required task_id (int) parameter
   - Added required execution_time_seconds (float) parameter
   - Changed passed=True/False to status='passed'/'failed'
   - Removed non-existent fields: critical_failures, warnings, gates_run
   - Replaced Mock() instances with proper QualityGateFailure objects

2. Patch Method Names
   - Changed all patch.object(QualityGates, 'run', ...) to
     patch.object(QualityGates, 'run_all_gates', ...)
   - WorkerAgent.complete_task() calls run_all_gates, not run
   - This fixes all 6 test methods to intercept the actual call

3. Transaction Rollback Test Patch Targets
   - Changed QualityGates.run to QualityGates.run_all_gates
   - Changed db.tasks.save_task_evidence to db.task_repository.save_task_evidence
   - Now correctly tests the actual code path for transaction rollback

All tests now use correct model signatures and patch the actual methods
called by WorkerAgent, ensuring integration tests verify real behavior.

Imports cleaned up: Added QualityGateFailure and Severity to top-level
imports, removed duplicate in-method imports, removed unused Mock import.

* fix: Add backward compatibility properties and fix test fixtures

Two critical fixes for integration tests:

1. Database Backward Compatibility Properties
   - Added task_repository property -> returns self.tasks
   - Added blocker_repository property -> returns self.blockers
   - Maintains 100% backward compatibility for code using old naming
   - WorkerAgent uses db.task_repository.save_task_evidence()

2. Test Fixture Corrections (test_evidence_integration.py)
   - Fixed issue status: 'open' -> 'pending' (valid status)
   - Added required issue fields: priority, workflow_step
   - Fixed task retrieval: db.get_task_by_id() -> db.get_task()
   - Updated all assertions: db.tasks.get_by_id() -> db.get_task()

Fixes 6 CHECK constraint errors and 2 AttributeErrors in integration tests.
Database refactoring maintains backward compatibility via properties.

* fix: Resolve integration test failures with proper task creation and evidence mocking

Fixed 8 failing integration tests:

1. Evidence Integration Tests (6 errors fixed)
   - Issue: Used db.create_task() with dict, but TaskRepository expects Task object
   - Fix: Use db.create_task_with_issue() with individual parameters
   - Added all required fields: project_id, task_number, parent_issue_number, etc.
   - Changed status from string to TaskStatus enum

2. Quality Tracker Integration Tests (2 failures fixed)
   - Issue: Evidence verification now runs in complete_task(), blocking tests
   - Tests were written before evidence verification feature existed
   - Evidence verification fails with 'Coverage data missing'
   - Fix: Mock EvidenceVerifier.verify() to return True in these tests
   - Maintains test isolation - tests focus on quality tracker, not evidence

★ Key Learning:
- Repository pattern type safety: Some methods accept dicts, others require domain objects
- Integration of new features can break existing tests that don't expect the dependency
- Test isolation: Mock out features not being tested to maintain focused test coverage
- Use db.create_task_with_issue() for test fixtures, not db.create_task()

All tests now properly isolated and use correct Database API methods.

* fix: Complete integration test fixes for evidence-based quality enforcement

Fixed all remaining integration test issues:

1. Task Creation API:
   - Changed from create_task() to create_task_with_issue()
   - Fixed parameters: task_number and parent_issue_number as strings
   - Added required can_parallelize parameter
   - Removed unsupported assigned_agent parameter

2. Severity Enum:
   - Changed Severity.ERROR to Severity.CRITICAL (correct enum value)
   - Updated 4 test methods with proper severity values

3. Blocker Repository API:
   - Replaced get_active_blockers_for_task() with list_blockers()
   - Filter blockers by task_id in Python after retrieval
   - Access blocker fields as dict keys instead of object attributes

4. Evidence Verification Mocking:
   - Added EvidenceVerifier.verify() mock to test_complete_task_with_valid_evidence
   - Updated test assertions to check result['evidence_verified'] instead of evidence.verified
   - Fixed variable naming conflicts (result vs blockers_result)

5. Transaction Rollback Test:
   - Updated to reflect actual behavior (exception is raised, blocker created before exception)
   - Changed from expecting no blocker to expecting blocker creation
   - Wrapped in pytest.raises() to properly handle exception

Test Results:
- All 20 integration tests now passing (6 evidence + 14 quality tracker)
- 100% pass rate for tests/integration/test_evidence_integration.py
- 100% pass rate for tests/integration/test_quality_tracker_integration.py

Related: PR #156
frankbria pushed a commit that referenced this pull request Jan 27, 2026
1. Clear intervention_context after task completion (critical lifecycle bug)
2. Re-fetch task_dict after intervention so workers get updated context
3. Add retry count limit (max 3) to prevent infinite intervention loops
4. Track workspace state from worker agent execute_task results
5. Document SDK mode intervention limitation
6. Replace silent auto-convert with FileExistsError for proper supervisor flow

Updates test to match new FileExistsError behavior (issue #6).
frankbria added a commit that referenced this pull request Jan 27, 2026
…ing (#302)

* feat(agents): add tactical pattern supervisor for file conflict handling

Implements a supervisor/tactical pattern system that enables the LeadAgent
to detect and recover from file conflict errors during batch resume scenarios.

Components:
- TacticalPatternMatcher: Regex-based pattern detection for known error types
- Workspace state tracking: Tracks files created/modified per task
- Intervention context: Persisted recovery strategy passed to worker agents
- Worker agent modifications: Handle intervention_context for graceful recovery

Strategies implemented:
- CONVERT_CREATE_TO_EDIT: Convert "create" to "modify" for existing files
- SKIP_FILE_CREATION: Skip creation and preserve existing content
- CREATE_BACKUP: Create backup before overwriting (handler prepared)
- RETRY_WITH_CONTEXT: Retry with additional context about existing files

Test coverage: 64 new tests covering pattern matching, database operations,
workspace tracking, supervisor intervention, and agent handling.

* fix: remove unused imports and variables (ruff)

* fix(agents): address PR review issues for tactical pattern supervisor

1. Clear intervention_context after task completion (critical lifecycle bug)
2. Re-fetch task_dict after intervention so workers get updated context
3. Add retry count limit (max 3) to prevent infinite intervention loops
4. Track workspace state from worker agent execute_task results
5. Document SDK mode intervention limitation
6. Replace silent auto-convert with FileExistsError for proper supervisor flow

Updates test to match new FileExistsError behavior (issue #6).

* fix(persistence): populate intervention_context in _row_to_task()

_row_to_task() was not reading the intervention_context column, so
db.get_task() always returned Task objects with intervention_context=None.
This broke the re-fetch in LeadAgent after intervention was applied.

Adds JSON deserialization with the same backward-compat try/except pattern
used for effort estimation fields. Adds 2 round-trip tests verifying
get_task() returns populated and None intervention_context correctly.

* fix: add intervention_context migration and v2 test markers

- Add _add_column_if_not_exists migration for intervention_context so
  existing databases get the column on next initialization
- Add pytestmark = pytest.mark.v2 to all 5 new test files so they
  appear in `pytest -m v2` runs

---------

Co-authored-by: Test User <test@example.com>
frankbria pushed a commit that referenced this pull request May 30, 2026
- Replace assert in upsert with RuntimeError so the dict-return contract holds
  under python -O (claude review #1).
- Surface failed DELETE in WorkspaceSelector via console.warn instead of a fully
  silent catch (claude review #3).
- Add NOT NULL to workspaces_registry created_at/last_opened_at (always written;
  brand-new table, no migration impact) (claude review #8).
- Comment the per-entry path_exists stat() tradeoff in the async list handler (#2).
- Clean up confusing makeItem test id default (#7).

Skipped: UUID-in-upsert (#4, required in single-statement INSERT...ON CONFLICT
VALUES), shared column constant (#5, polish), and removing 'void localVersion'
(#6/CodeRabbit nitpick — removal reintroduces the eslint exhaustive-deps warning).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant