feat: Project schema refactoring with source types and workspace management - #4
Conversation
Design new project schema to support: - Minimal upfront requirements (name + description only) - Flexible source types (git, local, upload, empty) - Both deployment modes (self-hosted + hosted SaaS) - Progressive discovery via Socratic questioning - PRD generation and versioning - Git-first foundation for all projects Removes restrictive project_type enum that didn't work for monorepos. Related to future Discovery and PRD features.
…compatibility The schema refactoring added required `description` and `workspace_path` fields to the projects table, but the create_project() method signature wasn't updated, causing test failures. Changes: - Add `description` parameter with default: "Have not set a description yet. Prompt the user to complete it." - Add `workspace_path` parameter with empty string default - Update INSERT statement to include both new fields This maintains backward compatibility with existing code while supporting the new schema requirements. Fixes test failures: - test_backward_compatibility_with_existing_code - test_update_task_status_real_database - test_start_agent_creates_lead_agent_instance - All other tests using create_project()
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. 🗂️ Base branches to auto review (1)
Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the ✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
Pull Request Review: Project Schema RefactoringSummaryThis PR implements a significant refactoring of the projects schema to support multiple source types and introduces managed workspace functionality. The changes are well-structured with good test coverage and maintain backward compatibility. Positive Aspects
Critical Issues (Must Fix Before Merge)1. Destructive Schema Migration (database.py:45-47)BLOCKER: Unconditionally drops projects table on every initialization = permanent data loss in production
2. Missing Error Handling (workspace/manager.py)Invalid git URLs, non-existent branches, and network errors will crash the application
3. Arbitrary File System Access (workspace/manager.py:75-90)SECURITY RISK: LOCAL_PATH allows copying ANY readable path (/etc/passwd, private keys, etc)
4. Missing Input Validation (ui/models.py:34-39)No validation for git URL format, path traversal (..), or branch names
Major Concerns (Should Fix)5. Incomplete Upload ImplementationFunction exists but doesnt work - silently ignores upload file
6. Race ConditionTOCTOU between exists check and creation
7. Synchronous Git OperationsLarge clones will block FastAPI server for minutes
8. No Resource LimitsCould lead to disk space exhaustion
Test CoverageGood unit tests but missing:
Performance Metrics
Overall Assessment
RecommendationREQUEST CHANGES - Good architecture but P0 security and data loss issues must be fixed before merge. |
…urity This commit addresses the major issues raised in the PR review: Issue #1: Convert always-on table drop to one-time migration - Created migration_002_refactor_projects_schema.py - Removed DROP TABLE from _create_schema() - now only runs once via migration - Migration properly checks if already applied before running - Added rollback capability Issue #2: Add comprehensive error handling to WorkspaceManager - Added try-except blocks with cleanup on failure in create_workspace() - Enhanced _init_empty() with timeout and detailed error messages - Enhanced _init_from_git() with: * Input validation (git_url required) * 5-minute timeout for large repos * Specific error messages for network, repo not found, branch not found, auth failures * Shallow clone (--depth 1) for faster operations - Enhanced _init_from_local() with permission and existence checks - All subprocess calls now have timeouts and proper exception handling Issue #3: Add path validation and security for LOCAL_PATH - Added _is_safe_path() method to validate file system access - Only allows paths under user's $HOME directory - Prevents access to /etc/passwd, system files, other users' files - Checks: path existence, is directory, readable, path traversal protection - Added symlinks=False to shutil.copytree for security All tests pass (24/24): - test_workspace_manager.py: 3/3 ✓ - test_agent_factory.py: 21/21 ✓ Changes prioritize major issues per reviewer guidance, not nitpicks.
Pull Request Review: Project Schema RefactoringOverviewThis PR implements a comprehensive refactoring of the project schema to support multiple source types and managed workspaces. The implementation is well-structured and addresses the stated goals effectively. Strengths1. Architecture & Design
2. Security Improvements (Latest commit)
3. Error Handling (Latest commit)
4. Code Quality
HIGH Priority Issues1. Migration Safety Concern (migration_002_refactor_projects_schema.py:89-91)Issue: The migration drops the entire projects table unconditionally. While the PR description mentions this is for development, this pattern is dangerous. Recommendation: Add explicit guards/warnings if run in production, consider adding a backup step before dropping. 2. Missing Validation in create_project() (database.py:333-347)Issues:
Recommendation: Add proper validation with required parameters and type checking. 3. Race Condition in Workspace Creation (manager.py:47-50)Issue: TOCTOU (Time-of-check to time-of-use) race condition between the exists() check and directory creation. Recommendation: Use atomic mkdir with exist_ok=False instead of checking first. MEDIUM Priority Issues4. Incomplete Upload Implementation (manager.py:229-238)Issues: upload_filename parameter unused, no error handling, creates workspace even though feature not implemented. Recommendation: Raise NotImplementedError to clearly indicate feature is not ready. 5. Test Coverage GapsMissing test cases for GIT_REMOTE, LOCAL_PATH, error conditions, security validation, and cleanup on failure. 6. Migration Rollback Not TestedThe rollback recreates the old schema, but there is no test to verify it works correctly. Security AssessmentGood Security Practices:
Security Considerations:
Test Plan Verification
Final Verdict: Approve with ChangesThis PR represents solid foundational work with a well-thought-out architecture. The latest commit addressing security and error handling shows excellent responsiveness to feedback. Must Fix (Before Merge):
Should Fix (Soon After): Great work on this refactoring! The architecture is clean and extensible. Addressing the validation and race condition issues will make this production-ready. Review Generated by Claude Code |
Update: API Endpoints for Workspace ManagementAdded commit 5a208c8: feat(api): update project creation endpoint with workspace management This commit updates the endpoint to support the new project schema with:
The API endpoint now properly initializes workspaces based on source type during project creation. |
Update: API Endpoints for Workspace ManagementAdded commit 5a208c8: feat(api): update project creation endpoint with workspace management This commit updates the project creation endpoint to support the new project schema with:
The API endpoint now properly initializes workspaces based on source type during project creation. |
Fixed critical runtime issues in server.py (lines 586-718): 1. WebSocket Manager Reference (Issue #1) - BEFORE: Used app.state.websocket_manager (not initialized) - AFTER: Use module-level global 'manager' (line 155) - Fixed lines: 680, 691, 698 2. API Key Validation (Issue #2) - BEFORE: No validation before LeadAgent creation - AFTER: Validate ANTHROPIC_API_KEY and raise HTTPException(500) if missing - Added lines: 629-635 - Error: "ANTHROPIC_API_KEY environment variable is not set" 3. Status Key Access Adaptation (Issue #3) - BEFORE: Direct key access (status["is_complete"], etc.) - AFTER: Computed from LeadAgent.get_discovery_status() format - Computed values (lines 667-674): * is_complete = status.get("state") == "completed" * total_questions = status.get("total_required", 0) * current_question_index = answered_count * current_question_id = status.get("current_question", {}).get("id", "") * current_question_text = status.get("current_question", {}).get("question", "") 4. Import Organization (Issue #4) - BEFORE: In-function import (line 608) - AFTER: Module-scope import (lines 21-22) - Moved DiscoveryAnswer, DiscoveryAnswerResponse to top Error Handling: - Added HTTPException re-raise to preserve 400 errors - API key validation returns 500 with clear message - All WebSocket broadcast errors are non-fatal (logged warnings) Impact: - Prevents runtime AttributeError on app.state.websocket_manager - Prevents runtime TypeError on missing API key - Prevents runtime KeyError on status dict access - Cleaner import organization Related: PR #25
feat: Project schema refactoring with source types and workspace management
Fixed critical runtime issues in server.py (lines 586-718): 1. WebSocket Manager Reference (Issue #1) - BEFORE: Used app.state.websocket_manager (not initialized) - AFTER: Use module-level global 'manager' (line 155) - Fixed lines: 680, 691, 698 2. API Key Validation (Issue #2) - BEFORE: No validation before LeadAgent creation - AFTER: Validate ANTHROPIC_API_KEY and raise HTTPException(500) if missing - Added lines: 629-635 - Error: "ANTHROPIC_API_KEY environment variable is not set" 3. Status Key Access Adaptation (Issue #3) - BEFORE: Direct key access (status["is_complete"], etc.) - AFTER: Computed from LeadAgent.get_discovery_status() format - Computed values (lines 667-674): * is_complete = status.get("state") == "completed" * total_questions = status.get("total_required", 0) * current_question_index = answered_count * current_question_id = status.get("current_question", {}).get("id", "") * current_question_text = status.get("current_question", {}).get("question", "") 4. Import Organization (Issue #4) - BEFORE: In-function import (line 608) - AFTER: Module-scope import (lines 21-22) - Moved DiscoveryAnswer, DiscoveryAnswerResponse to top Error Handling: - Added HTTPException re-raise to preserve 400 errors - API key validation returns 500 with clear message - All WebSocket broadcast errors are non-fatal (logged warnings) Impact: - Prevents runtime AttributeError on app.state.websocket_manager - Prevents runtime TypeError on missing API key - Prevents runtime KeyError on status dict access - Cleaner import organization Related: PR #25
Added quality gate status and failure seeding to enable quality gate panel E2E tests. Gates are stored as columns in the tasks table (not separate table). **Implementation** (tests/e2e/seed-test-data.py, lines 651-726): - Seed quality gate results for 2 tasks (#2 and #4) - Task #2 (completed): All gates PASSED (clean state) - tests: passed (100%, 25/25) - type_check: passed (0 errors) - coverage: passed (92% > 85% threshold) - code_review: passed (score 85/100) - Task #4 (in-progress): Multiple gates FAILED - tests: passed (100%, 15/15) - type_check: FAILED (3 TypeScript errors) - coverage: passed (88%) - code_review: FAILED (2 critical security issues: XSS, token logging) **Schema** (tasks table columns): - quality_gate_status: 'pending'|'running'|'passed'|'failed' - quality_gate_failures: JSON array of QualityGateFailure objects **Failure Object Format**: { "gate": "type_check", "reason": "TypeScript compiler found 3 type errors", "details": "Full error output...", "severity": "critical"|"high"|"medium"|"low" } **Test Impact**: - Enables quality gate panel rendering tests - Provides realistic failure scenarios for UI testing - Supports severity badge and critical finding display **Error Handling**: - Graceful fallback if quality gate columns don't exist - Follows existing seeding patterns (try/except, print statements) - Idempotent (clears existing data before seeding) Refs: Phase 3, Sprint 10 quality gates feature
…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)
…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)
ISSUE #2 - POTENTIAL LOGIC ISSUE (Investigated): - Backend does not support gates_evaluated field - Current conservative logic is acceptable: * Only marks gate as passed if overall status is passed AND no failures exist * Prevents false positives without additional backend support ISSUE #3 - API ERROR HANDLING (Fixed): - Add specific error messages based on error type - Differentiate between 404, network errors, and server errors - Improves user experience with actionable error messages ISSUE #4 - MAGIC NUMBERS IN GRID LAYOUT (Fixed): - Add comment explaining hardcoded grid column count (5) - Grid layout: 2 cols mobile, 3 cols tablet, 5 cols desktop - Matches fixed gate count (tests, coverage, type-check, lint, review) ISSUE #5 - INCONSISTENT NULL HANDLING (Fixed): - Replace logical OR (||) with nullish coalescing (??) - Explicitly handles null/undefined vs falsy values - More semantically correct for optional status field CHANGES: - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Improve error handling with specific messages for 404 and network errors * Add comment explaining grid layout column count - web-ui/src/components/quality-gates/GateStatusIndicator.tsx: * Use nullish coalescing (??) instead of logical OR (||) for statusText TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing NOTES: - Issue #1 (Missing Unit Tests) tracked in Issue #56
ISSUE #1 - LOGIC LIMITATION (Documented): - Added detailed comment explaining getGateStatus() limitation - Documents potential false positives when only some gates have run - Suggests backend enhancement: add gates_evaluated field - Current workaround assumes if overall status is passed, all gates passed ISSUE #2 - USEEFFECT CLEANUP (Fixed): - Add isMounted flag to prevent state updates on unmounted component - Prevents "Can't perform React state update on unmounted component" warnings - Cleanup function sets isMounted=false on unmount ISSUE #4 - INTERFACE DOCUMENTATION (Fixed): - Add JSDoc comments to QualityGatesPanelProps interface - Document projectId for API scoping - Document tasks array filtering behavior ISSUE #5 - HARDCODED GATE TYPES (Fixed): - Created ALL_GATE_TYPES_E2E constant in qualityGates.ts - Export as readonly array with 'as const' for type safety - Import and use constant in QualityGatesPanel - Ensures gate types stay in sync across components CHANGES: - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Add TODO comment for gates_evaluated backend enhancement * Add isMounted cleanup flag in useEffect * Add JSDoc to interface * Use ALL_GATE_TYPES_E2E constant - web-ui/src/types/qualityGates.ts: * Export ALL_GATE_TYPES_E2E constant TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing NOTES: - Issue #3 (Performance - double rendering) deferred as minor optimization
* feat: Implement Quality Gates Panel in Dashboard (#43) Add comprehensive Quality Gates Panel to Dashboard with task selection and individual gate status indicators for all 5 gate types. New Components: - QualityGatesPanel: Main panel with task selection and gate overview - GateStatusIndicator: Individual gate status card with icons and badges Features: - Task selector dropdown for completed/in_progress tasks - Grid display of all 5 gate types (tests, coverage, type-check, lint, review) - Color-coded status badges (green=passed, red=failed, yellow=running, gray=pending) - Gate-specific icons and proper test IDs for E2E testing - Type mappings between E2E and backend naming conventions Changes: - Added QualityGatesPanel component with task selection - Added GateStatusIndicator component for individual gates - Added E2E ↔ Backend type mappings in qualityGates.ts - Integrated panel into Dashboard Overview tab - Removed skip decorator from E2E test Testing: - Build passes with no TypeScript errors - ESLint passing - E2E test ready (test_dashboard.spec.ts:70) Closes #43 * fix: Address code review issues for Quality Gates Panel CRITICAL FIXES: - Fix gate status logic to default to pending instead of falsely showing passed - Only mark gates as passed if explicitly confirmed by backend - Conservative approach prevents false positives HIGH PRIORITY FIXES: - Add error state management with user-visible error messages - Display errors in accessible alert component with aria-live MEDIUM PRIORITY FIXES: - Remove unused projectId prop from QualityGatesPanel interface - Consolidate duplicate types: GateTypeBackend is now alias of QualityGateType - Add documentation clarifying type usage LOW PRIORITY IMPROVEMENTS: - Add accessibility attributes (aria-labels, roles, aria-hidden) - Extract shared utilities to qualityGateUtils.ts (DRY principle) - Add proper ARIA roles for lists, status indicators, and alerts FILES CHANGED: - NEW: web-ui/src/lib/qualityGateUtils.ts (shared utilities) - MODIFIED: QualityGatesPanel.tsx (critical fix + error handling + accessibility) - MODIFIED: GateStatusIndicator.tsx (use shared utils + accessibility) - MODIFIED: qualityGates.ts (consolidate types) - MODIFIED: Dashboard.tsx (remove projectId prop) TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing * fix: Address PR review comments - projectId, code duplication, performance CRITICAL FIXES: - Add projectId back to QualityGatesPanel props (multi-project architecture requirement) - Pass projectId as query parameter to fetchQualityGateStatus API - Update fetchQualityGateStatus to accept optional projectId parameter CODE QUALITY IMPROVEMENTS: - Remove code duplication in QualityGateStatus.tsx - Use shared utilities from qualityGateUtils.ts for: * getStatusClasses() * getSeverityClasses() * getGateIcon() * getStatusIcon() - Eliminates ~65 lines of duplicate code PERFORMANCE OPTIMIZATIONS: - Add useRef to prevent unnecessary auto-selection re-runs - Only auto-select task once, not on every eligibleTasks update - Prevents excessive state updates from WebSocket task changes CHANGES: - web-ui/src/api/qualityGates.ts: Add optional projectId parameter with query string builder - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Add projectId to props interface * Pass projectId to fetchQualityGateStatus() * Add hasAutoSelectedRef useRef for optimization * Add projectId to useEffect dependencies - web-ui/src/components/quality-gates/QualityGateStatus.tsx: * Import shared utilities from qualityGateUtils.ts * Remove duplicate function implementations * Remove unused QualityGateStatusValue import - web-ui/src/components/Dashboard.tsx: Pass projectId to QualityGatesPanel GITHUB ISSUES CREATED FOR FUTURE WORK: - Issue #56: Add unit tests for Quality Gates Panel components - Issue #57: Add error boundary for Quality Gates Panel TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing * fix: Address code review feedback - duplication, edge cases, and docs MEDIUM PRIORITY FIXES: - Remove type mapping duplication in QualityGatesPanel - Use mapE2EToBackend() from types instead of inline mapping - Eliminates 8 lines of duplicate code LOW PRIORITY IMPROVEMENTS: - Fix race condition in auto-selection logic * Reset hasAutoSelectedRef when tasks become empty * Allows re-selection when tasks are re-added after deletion - Add projectId validation in API client * Only append projectId query param if > 0 * Prevents invalid API calls with negative/zero IDs - Add comprehensive JSDoc comments to all utility functions * Added @param, @returns, and @example tags * Improves IDE autocomplete and developer experience CHANGES: - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Import and use mapE2EToBackend() instead of inline mapping * Remove unused GateTypeBackend import * Add auto-selection reset logic for edge cases - web-ui/src/api/qualityGates.ts: * Add projectId > 0 validation before appending query param - web-ui/src/lib/qualityGateUtils.ts: * Add JSDoc comments to all 5 utility functions TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing RELATED ISSUES: - Issue #56 covers test coverage (high priority, tracked separately) * refactor: Improve error handling, code clarity, and null handling ISSUE #2 - POTENTIAL LOGIC ISSUE (Investigated): - Backend does not support gates_evaluated field - Current conservative logic is acceptable: * Only marks gate as passed if overall status is passed AND no failures exist * Prevents false positives without additional backend support ISSUE #3 - API ERROR HANDLING (Fixed): - Add specific error messages based on error type - Differentiate between 404, network errors, and server errors - Improves user experience with actionable error messages ISSUE #4 - MAGIC NUMBERS IN GRID LAYOUT (Fixed): - Add comment explaining hardcoded grid column count (5) - Grid layout: 2 cols mobile, 3 cols tablet, 5 cols desktop - Matches fixed gate count (tests, coverage, type-check, lint, review) ISSUE #5 - INCONSISTENT NULL HANDLING (Fixed): - Replace logical OR (||) with nullish coalescing (??) - Explicitly handles null/undefined vs falsy values - More semantically correct for optional status field CHANGES: - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Improve error handling with specific messages for 404 and network errors * Add comment explaining grid layout column count - web-ui/src/components/quality-gates/GateStatusIndicator.tsx: * Use nullish coalescing (??) instead of logical OR (||) for statusText TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing NOTES: - Issue #1 (Missing Unit Tests) tracked in Issue #56 * fix: Improve WCAG AA contrast in default status badge ACCESSIBILITY ISSUE: - Default status badge used text-gray-500 on bg-gray-100 - Contrast ratio failed WCAG AA requirement (< 4.5:1) FIX: - Changed text-gray-500 to text-gray-800 in default return - Now matches all other status badge text colors (green-800, red-800, yellow-800, gray-800) - Meets WCAG AA contrast requirement (>= 4.5:1) CHANGES: - web-ui/src/lib/qualityGateUtils.ts:83 * getStatusClasses() default case * bg-gray-100 text-gray-500 → bg-gray-100 text-gray-800 TESTING: - Build passes with no errors - Visual consistency maintained across all badge types * refactor: Improve code quality, documentation, and maintainability ISSUE #1 - LOGIC LIMITATION (Documented): - Added detailed comment explaining getGateStatus() limitation - Documents potential false positives when only some gates have run - Suggests backend enhancement: add gates_evaluated field - Current workaround assumes if overall status is passed, all gates passed ISSUE #2 - USEEFFECT CLEANUP (Fixed): - Add isMounted flag to prevent state updates on unmounted component - Prevents "Can't perform React state update on unmounted component" warnings - Cleanup function sets isMounted=false on unmount ISSUE #4 - INTERFACE DOCUMENTATION (Fixed): - Add JSDoc comments to QualityGatesPanelProps interface - Document projectId for API scoping - Document tasks array filtering behavior ISSUE #5 - HARDCODED GATE TYPES (Fixed): - Created ALL_GATE_TYPES_E2E constant in qualityGates.ts - Export as readonly array with 'as const' for type safety - Import and use constant in QualityGatesPanel - Ensures gate types stay in sync across components CHANGES: - web-ui/src/components/quality-gates/QualityGatesPanel.tsx: * Add TODO comment for gates_evaluated backend enhancement * Add isMounted cleanup flag in useEffect * Add JSDoc to interface * Use ALL_GATE_TYPES_E2E constant - web-ui/src/types/qualityGates.ts: * Export ALL_GATE_TYPES_E2E constant TESTING: - Build passes with no errors - TypeScript compilation successful - ESLint passing NOTES: - Issue #3 (Performance - double rendering) deferred as minor optimization * fix: Remove unsafe patterns and add request cancellation - Remove non-null assertion (!) with explicit type narrowing - Add AbortController to cancel in-flight requests on cleanup - Document naming conventions (kebab-case vs snake_case) - Improve type safety in fetchQualityGateStatus useEffect Addresses final critical code review feedback in PR #50
- 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).
Summary
This PR implements a comprehensive refactoring of the projects schema to support multiple project source types and managed workspaces:
source_type,source_location,source_branch,workspace_path,git_initialized, andcurrent_commitfields to projects tableProjectTypeenum withSourceTypeenum supporting git_remote, local_path, upload, and empty sources~/.codeframe/workspaces/create_project()method to maintain compatibility with existing testsTest Plan
test_agent_factory.pypassFiles Changed
codeframe/persistence/database.py- Schema and create_project method updatescodeframe/ui/models.py- ProjectType → SourceType refactoringcodeframe/workspace/manager.py- New workspace management componenttests/test_workspace_manager.py- Workspace manager test suitetests/test_database_schema.py- Schema validation testsdocs/plans/2025-10-27-project-schema-implementation.md- Implementation planBreaking Changes
None - backward compatibility maintained via default parameters.