Skip to content

Conversation

@shivanathd
Copy link

@shivanathd shivanathd commented Jan 5, 2026

Summary

  • Add "Reset Project" button to header (disabled while agent is running)
  • Implement ResetProjectModal with two reset options:
    • Quick Reset: Clears features and history but keeps app spec and prompts
    • Full Reset: Deletes everything including prompts directory, triggers setup wizard
  • Add ProjectSetupRequired component shown after full reset when has_spec === false
  • Backend POST /api/projects/{name}/reset?full_reset=true endpoint
  • Keyboard shortcut: Escape closes the modal

Features

  • Visual feedback showing what will be deleted vs preserved
  • Full reset now triggers the setup wizard (same as new project creation)
  • User can choose "Create with Claude" or "Edit Templates Manually" after full reset

Test plan

  • Select a project and verify Reset button appears in header
  • Verify Reset button is disabled when agent is running
  • Test Quick Reset: features cleared, prompts preserved
  • Test Full Reset: everything deleted, setup wizard appears
  • Test "Create with Claude" option in setup wizard
  • Test "Edit Templates Manually" option
  • Verify Escape key closes the modal

Summary by CodeRabbit

Release Notes

  • New Features
    • Added project reset functionality with two modes: quick reset (clears cached data) and full reset (includes prompts and settings).
    • Introduced guided setup workflow for new projects, offering options to create specs with AI assistance or manually configure templates.
    • Enabled automatic Python virtual environment activation on application startup.

✏️ Tip: You can customize this high-level summary in your review settings.

Allow users to reset a project to its initial state without having to
re-register it. This is useful when a project initialization fails or
when users want to start fresh.

Changes:
- Add POST /api/projects/{name}/reset endpoint
- Add ResetProjectModal component with confirmation dialog
- Add useResetProject hook for React Query integration
- Add Reset button in header (keyboard shortcut: R)
- Disable reset while agent is running

The reset clears features.db, assistant.db, and settings files while
preserving the prompts directory with app_spec.txt and templates.
- Backend: Add full_reset query parameter to POST /api/projects/{name}/reset
  - When full_reset=true, also deletes prompts/ directory
  - Allows starting completely fresh with setup wizard
- Frontend: Enhanced ResetProjectModal with two options:
  - Quick Reset: Clear features/history, keep prompts
  - Full Reset: Delete everything including prompts
- Removed R keyboard shortcut for reset modal
- Updated API client and hooks to support fullReset parameter
The script was failing with 'ModuleNotFoundError: No module named dotenv'
because it wasn't activating the virtual environment before running Python.

Now checks for and activates venv/bin/activate if the venv directory exists.
When a project's spec files are deleted via full reset, the UI now
displays the ProjectSetupRequired component which offers:
- "Create with Claude" for interactive spec generation
- "Edit Templates Manually" for direct file editing

Changes:
- Add ProjectSetupRequired component for projects without specs
- Update App.tsx to check has_spec and conditionally render setup UI
- Refetch projects after setup completes to update UI state
@leonvanzyl
Copy link
Owner

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

📝 Walkthrough

Walkthrough

This PR introduces a project reset feature enabling users to clear project state selectively. It adds a backend POST endpoint for project reset with file deletion logic, new frontend components for reset modals and setup prompts, integrates reset-related hooks and API calls, and activates virtual environment support in the startup script.

Changes

Cohort / File(s) Summary
Backend Reset Endpoint
server/routers/projects.py
Adds ResetOptions class and new POST /{name}/reset endpoint (reset_project) that validates project existence, prevents reset during agent execution, deletes predefined database/config files, optionally deletes prompts directory when full reset is requested, aggregates deletion errors, and returns summary of deleted files.
Frontend Reset UI Components
ui/src/components/ResetProjectModal.tsx, ui/src/components/ProjectSetupRequired.tsx
Introduces ResetProjectModal component offering Quick Reset and Full Reset modes with error handling and loading state; adds ProjectSetupRequired component guiding users through project initialization via SpecCreationChat or manual template editing.
Frontend Integration
ui/src/App.tsx
Integrates reset modal state, adds Reset button to header, captures needsSetup flag from project spec, conditionally renders setup prompt and reset modal, extends keydown handler and dependencies for new modal state.
Frontend Hooks & API
ui/src/hooks/useProjects.ts, ui/src/lib/api.ts
Adds useResetProject() hook exposing project reset mutation with query invalidation for projects, features, and project-specific data; adds resetProject() API method with ResetProjectResponse type.
Build Metadata
ui/tsconfig.tsbuildinfo
Updates TypeScript build information to include new ResetProjectModal component in tracked sources.
Startup Script
start_ui.sh
Adds virtual environment activation step that sources venv/bin/activate when venv directory exists adjacent to script.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant App as App.tsx
    participant Modal as ResetProjectModal
    participant Hook as useResetProject
    participant API as api.ts
    participant Backend as /projects/{name}/reset
    participant FS as Filesystem

    User->>App: Click Reset Button
    App->>App: Show Reset Modal
    activate Modal
    User->>Modal: Select Reset Type & Confirm
    Modal->>Hook: mutate(projectName, fullReset)
    activate Hook
    Hook->>API: resetProject(name, fullReset)
    activate API
    API->>Backend: POST /projects/{name}/reset
    deactivate API
    activate Backend
    Backend->>Backend: Validate project exists
    Backend->>Backend: Check agent not running
    Backend->>FS: Delete features.db, assistant.db, settings
    Backend->>FS: Delete prompts/ if fullReset=true
    FS-->>Backend: Deletion complete
    Backend-->>Backend: Aggregate results
    Backend-->>API: ResetProjectResponse
    deactivate Backend
    activate API
    API-->>Hook: Response
    deactivate API
    Hook->>Hook: Invalidate queries
    Hook-->>Modal: Success
    deactivate Hook
    Modal->>App: onClose & onReset callbacks
    deactivate Modal
    App->>App: Update state, refresh UI
    User->>User: Project reset complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A hop through history, files swept clean,
The reset button makes projects pristine,
Quick or full—the choice is yours to make,
Fresh starts bloom wherever we awake! 🌱

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: Add project reset functionality' accurately and concisely describes the main change across the changeset, covering the primary feature addition of project reset capabilities.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
start_ui.sh (1)

14-18: Consider adding error handling for activation failure.

While the venv activation is a good addition, consider adding error handling in case the activation fails:

 # Activate virtual environment if it exists
 if [ -d "$SCRIPT_DIR/venv" ]; then
     echo "Activating virtual environment..."
-    source "$SCRIPT_DIR/venv/bin/activate"
+    if ! source "$SCRIPT_DIR/venv/bin/activate"; then
+        echo "WARNING: Failed to activate virtual environment"
+        echo "Continuing with system Python..."
+    fi
 fi

This ensures the script continues gracefully if activation fails for any reason.

ui/src/hooks/useProjects.ts (1)

51-64: Consider invalidating agent status query.

The invalidation strategy covers the main affected queries. However, since the reset operation might affect the agent's state (especially in a full reset), consider also invalidating the agent status query:

     onSuccess: (_, { name }) => {
       // Invalidate both projects and features queries
       queryClient.invalidateQueries({ queryKey: ['projects'] })
       queryClient.invalidateQueries({ queryKey: ['features', name] })
       queryClient.invalidateQueries({ queryKey: ['project', name] })
+      queryClient.invalidateQueries({ queryKey: ['agent-status', name] })
     },

This ensures the UI reflects any agent state changes that occur during reset.

server/routers/projects.py (2)

262-264: Remove unused ResetOptions class.

The ResetOptions class is defined but never instantiated or used. The endpoint uses the full_reset parameter directly instead of this class.

🧹 Proposed fix
-class ResetOptions:
-    """Options for project reset."""
-    delete_prompts: bool = False
-
-
 @router.post("/{name}/reset")

300-301: Remove unnecessary f-string prefix.

The f-string on Line 301 contains no placeholders.

📝 Proposed fix
-    if not project_dir.exists():
-        raise HTTPException(status_code=404, detail=f"Project directory not found")
+    if not project_dir.exists():
+        raise HTTPException(status_code=404, detail="Project directory not found")
ui/src/App.tsx (1)

123-123: Consider removing wsState.agentStatus from dependencies.

The wsState.agentStatus value is not used in the keyboard handler (lines 80-119). Including it in the dependencies will cause the effect to re-register event listeners whenever the agent status changes, which is unnecessary.

♻️ Proposed fix
-  }, [selectedProject, showAddFeature, selectedFeature, debugOpen, assistantOpen, showResetModal, wsState.agentStatus])
+  }, [selectedProject, showAddFeature, selectedFeature, debugOpen, assistantOpen, showResetModal])
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9087543 and db2a280.

📒 Files selected for processing (8)
  • server/routers/projects.py
  • start_ui.sh
  • ui/src/App.tsx
  • ui/src/components/ProjectSetupRequired.tsx
  • ui/src/components/ResetProjectModal.tsx
  • ui/src/hooks/useProjects.ts
  • ui/src/lib/api.ts
  • ui/tsconfig.tsbuildinfo
🧰 Additional context used
🧬 Code graph analysis (3)
ui/src/components/ResetProjectModal.tsx (2)
ui/src/lib/api.ts (1)
  • resetProject (76-81)
ui/src/hooks/useProjects.ts (1)
  • useResetProject (51-64)
server/routers/projects.py (5)
registry.py (1)
  • get_project_path (195-213)
server/routers/spec_creation.py (1)
  • validate_project_name (46-48)
server/routers/agent.py (1)
  • validate_project_name (35-42)
server/routers/features.py (1)
  • validate_project_name (57-64)
server/websocket.py (1)
  • validate_project_name (107-109)
ui/src/App.tsx (4)
ui/src/hooks/useProjects.ts (3)
  • useProjects (13-18)
  • useFeatures (70-77)
  • useAgentStatus (116-123)
ui/src/hooks/useWebSocket.ts (1)
  • useProjectWebSocket (22-163)
ui/src/components/ProjectSetupRequired.tsx (1)
  • ProjectSetupRequired (20-175)
ui/src/components/ResetProjectModal.tsx (1)
  • ResetProjectModal (11-175)
🪛 Ruff (0.14.10)
server/routers/projects.py

301-301: f-string without any placeholders

Remove extraneous f prefix

(F541)


328-328: Do not catch blind exception: Exception

(BLE001)


338-338: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (21)
ui/src/components/ProjectSetupRequired.tsx (6)

36-46: LGTM! Clean async error handling.

The function correctly manages state transitions and error handling for the agent initialization flow.


63-77: LGTM! Clean full-screen overlay pattern.

The chat overlay is properly structured with appropriate z-index and callbacks.


79-152: LGTM! Well-structured UI with clear options.

The two-option layout is clear and accessible. The visual design aligns with the neo-brutalism theme used throughout the app.


154-172: LGTM! Clear status feedback.

The loading and error states provide good user feedback with appropriate retry functionality.


24-24: LGTM! State correctly preserves yolo mode for retry.

The yoloModeSelected state ensures retry attempts use the same mode as the original request.


48-52: No action needed — retry logic is correct.

handleSpecComplete only retries the startAgent call, which is appropriate. Spec creation happens within the SpecCreationChat component and completes before handleSpecComplete is invoked. Spec creation errors are handled by SpecCreationChat itself, not by this retry mechanism.

ui/src/lib/api.ts (2)

69-74: LGTM! Well-structured response type.

The interface clearly communicates the reset operation results, including which files were deleted.


76-81: LGTM! Safe defaults and proper encoding.

The function correctly defaults to a non-destructive quick reset and properly encodes the project name.

ui/tsconfig.tsbuildinfo (1)

1-1: Build metadata correctly updated.

This generated file reflects the addition of the new resetprojectmodal.tsx component.

server/routers/projects.py (4)

303-309: LGTM! Proper concurrency control.

The lock file check correctly prevents project reset while the agent is running, avoiding potential data corruption or race conditions.


311-330: LGTM! Good error collection pattern.

The deletion loop properly collects all errors before reporting them, which provides better user feedback than failing on the first error. The broad exception catching here is appropriate for error collection.


331-339: LGTM! Full reset logic is correct.

The prompts directory deletion is properly conditional on full_reset=True, and the error handling follows the same collection pattern as file deletions. The prompts are intentionally not re-scaffolded here, as the setup wizard handles that flow.


341-353: LGTM! Comprehensive response structure.

The error handling properly aggregates deletion failures and returns a 500 status with details. The success response provides useful feedback including the list of deleted files and reset type.

ui/src/App.tsx (4)

19-21: LGTM! Clean state and hook integration.

The new imports, state management, and needsSetup computation are properly integrated. The refetch capability from useProjects will correctly update the project list after setup completion.

Also applies to: 39-39, 41-41, 46-50


107-109: LGTM! Correct Escape key priority.

The reset modal is properly prioritized as the first modal to close on Escape, which prevents unintended dismissal of other UI elements when the user wants to cancel the reset operation.


174-182: LGTM! Proper button state management.

The Reset button correctly disables when the agent is running, preventing concurrent operations and matching the backend's lock file check. The visual styling and placement are appropriate.


210-217: LGTM! Correct conditional rendering flow.

The setup wizard properly displays when needsSetup is true, and the refetch callback ensures the project list updates after setup completion. The reset modal rendering is properly gated by both showResetModal and selectedProject.

Also applies to: 277-283

ui/src/components/ResetProjectModal.tsx (4)

1-14: LGTM! Well-structured component setup.

The imports, props interface, and state management are clean and appropriate. The onReset callback is optional, allowing flexibility in how parent components respond to reset completion.


16-25: LGTM! Robust error handling and callback flow.

The handleReset function properly clears errors before attempting the reset, awaits the mutation, and calls callbacks in the correct order. Error handling gracefully sets local state for user feedback.


27-109: LGTM! Excellent UX with clear visual distinction.

The modal structure properly handles click propagation to prevent accidental closure. The reset type toggle provides clear visual feedback with appropriate color coding: Quick Reset uses the progress color while Full Reset uses the danger color, helping users understand the severity of each option.


111-170: LGTM! Transparent and informative user interface.

The deletion and preservation lists clearly communicate what will happen during the reset, with content dynamically adapting to the selected reset type. The color-coded sections (warning for deletions, success for preservation) and the contextual note about the setup wizard provide excellent transparency for users making this decision.

pRizz added a commit to pRizz/autocoder that referenced this pull request Jan 21, 2026
- Add users table schema with id, username, passwordHash, email, role fields
- Add tokens table schema for session management
- Create UserRepository with login, create, getByUsername methods
- Add authentication error types (InvalidCredentialsError, UserNotFoundError, UserAlreadyExistsError)
- Implement POST /api/auth/login endpoint with username/password validation
- Implement POST /api/auth/register endpoint for user registration
- Password hashing with SHA-256 + salt
- Token generation for authenticated sessions

Tested via browser automation:
- User registration: 201 Created with user data
- Login with valid credentials: 200 OK with user + token
- Login with invalid credentials: 401 Unauthorized

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
pRizz added a commit to pRizz/autocoder that referenced this pull request Jan 21, 2026
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
devxalted added a commit to devxalted/autocoder that referenced this pull request Jan 23, 2026
* feat: add git_workflow.py module for core git operations

Implements subprocess-based git operations for the Autocoder agent:
- _run_git(): safe git execution with timeout and error handling
- is_git_repo(), get_main_branch(): repo detection
- generate_branch_name(): slugify feature names for branches
- create_branch(), checkout_branch(), get_current_branch(): branch management
- commit_changes(), push_branch(): commit and push operations
- create_pr(), get_pr_status(): PR operations using gh CLI
- delete_remote_branch(): cleanup operations

Includes additional utilities:
- branch_exists(), create_and_checkout_branch()
- get_commit_sha(), has_uncommitted_changes()

Feature leonvanzyl#3 - git_workflow.py module

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: add progress tracking file

Track implementation progress for git workflow features.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add git workflow columns to Feature model

Add 8 new columns for git workflow integration:
- branch_name (indexed): git branch name for this feature
- branch_type: type of branch (feature/bugfix)
- worktree_path: path to git worktree for parallel agent isolation
- commit_sha: SHA of completion commit
- pr_number (indexed): GitHub PR number
- pr_url: full URL to the GitHub PR
- pr_status: current PR status (open/merged/closed)
- merged_at: timestamp when PR was merged

All columns are nullable for backwards compatibility with existing databases.
Includes migration function _migrate_add_git_columns() that safely adds
columns to existing databases using ALTER TABLE.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature #1 git columns complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add worktree_manager.py module for parallel agent isolation

Implements git worktree management for running multiple agents concurrently:
- _get_worktrees_dir(): Returns worktrees directory path pattern
- create_worktree(): Creates worktree with branch for feature
- remove_worktree(): Removes worktree with shutil fallback
- list_worktrees(): Parses 'git worktree list --porcelain' output
- cleanup_stale_worktrees(): Removes worktrees for passing features

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#4 worktree_manager complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add git workflow Pydantic schemas

Add Pydantic schemas for git-related API endpoints:
- GitConfig, GitConfigUpdate: Git workflow configuration
- GitStatusResponse: Repository status (is_git_repo, current_branch, etc.)
- GitBranchInfo, GitBranchListResponse: Branch information
- GitWorktreeInfo, GitWorktreeListResponse: Worktree information
- GitPRInfo, GitPRListResponse: Pull request information
- Updated FeatureResponse with git fields (branch_name, branch_type,
  worktree_path, commit_sha, pr_number, pr_url, pr_status, merged_at)

Feature leonvanzyl#5 - Git Pydantic schemas

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#5 git schemas complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add git config helpers to project_config.py

Add GitConfig TypedDict and helper functions for managing git workflow
configuration in projects. This enables per-project git workflow settings
stored in .autocoder/config.json.

- Add GitConfig TypedDict with fields: enabled, auto_branch, auto_commit,
  auto_pr, pr_target_branch
- Add DEFAULT_GIT_CONFIG with sensible defaults (enabled=False, auto_branch=True,
  auto_commit=True, auto_pr=False, pr_target_branch="main")
- Add get_git_config(project_dir) function to load git settings with defaults
- Add set_git_config(project_dir, config) function to save git settings

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#2 git config helpers complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add Git REST API router for git workflow operations

Implements server/routers/git.py with 7 REST endpoints:
- GET /status: Returns git repo status (branch, uncommitted changes, remote)
- GET /config: Returns git workflow configuration
- PUT /config: Updates git workflow configuration (partial updates)
- GET /branches: Lists all local branches with tracking info
- GET /worktrees: Lists all worktrees with feature IDs
- DELETE /worktrees/{feature_id}: Removes worktree for a feature
- GET /prs: Lists pull requests from features.db

Follows existing router patterns from features.py with:
- Lazy imports to avoid circular dependencies
- Project path resolution via registry
- Database session context manager
- Proper error handling with HTTPException

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#6 git router complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add PR watcher service for monitoring merged PRs

Implements background service that polls GitHub for merged PRs every
5 minutes (configurable). On merge detection:
- Updates feature.merged_at in database
- Removes git worktree
- Deletes remote branch

Key components:
- PRWatcher class with configurable poll_interval (default 300s)
- Async _check_merged_prs() queries features via gh CLI
- Async _watcher_loop() runs periodic checks
- start()/stop() for lifespan integration
- Module-level singleton with get_watcher() and cleanup_watcher()

Marks feature leonvanzyl#9 as passing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#9 PR watcher service complete

Progress: 7/10 features passing (70%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add Git MCP tools for agent git operations

- Add git_create_feature_branch(feature_id, branch_type='feature')
  Creates branch using generate_branch_name() and updates feature.branch_name, feature.branch_type

- Add git_commit_feature(feature_id, message)
  Commits changes in feature's worktree (or project dir) and updates feature.commit_sha

- Add git_create_pr(feature_id, title, target_branch='main')
  Pushes branch, creates PR via gh CLI, updates feature.pr_number, pr_url, pr_status

All tools follow existing MCP patterns with proper session handling,
error handling, and JSON return values.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#8 Git MCP tools complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add git workflow integration to parallel orchestrator

- Add imports for git_workflow, worktree_manager, and project_config
- Load git config in __init__ with fallback to disabled config on error
- Add _update_feature_git_info() helper to update Feature git fields
- Modify _spawn_coding_agent() to create branch/worktree if git enabled
- Add _finalize_git_for_feature() to commit/push/PR after feature passes
- Modify _on_agent_complete() to call git finalization for passed features

Feature leonvanzyl#7: Orchestrator git hooks

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: register git router and PR watcher service

- Add git_router export to server/routers/__init__.py
- Import and include git_router in server/main.py
- Start PR watcher service in lifespan startup
- Stop PR watcher service in lifespan shutdown

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress - Feature leonvanzyl#10 server registration complete

All 10/10 features now passing (100%)! Git workflow implementation is complete.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: security and reliability improvements from code review

- Add branch name validation (is_valid_branch_name) to prevent command injection
- Add feature_id type validation in worktree functions to prevent path traversal
- Replace deprecated asyncio.get_event_loop() with get_running_loop()
- Add thread-safe singleton pattern for PR watcher
- Add try-finally to MCP server lifespan for proper cleanup
- Add validation for pr_target_branch in schemas

Security improvements:
- Branch names now validated against [a-zA-Z0-9/_-]+ pattern
- Path traversal prevented by validating feature_id is positive integer
- Input validation added to all functions that accept user-provided branch names

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Admin <admin@localhost>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
devxalted added a commit to devxalted/autocoder that referenced this pull request Jan 23, 2026
* feat: add refinement config helpers to project_config.py

- Add RefinementPassesConfig TypedDict for pass settings (code_quality,
  edge_cases, performance, security, ux)
- Add RefinementConfig TypedDict with enabled, auto_transition, passes
- Add DEFAULT_REFINEMENT_CONFIG constant with all features enabled
- Add get_refinement_config() to load and merge config with defaults
- Add set_refinement_config() to validate and save refinement settings

Implements Feature leonvanzyl#2: Refinement config helpers

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add refinement tracking columns to Feature model

- Added 5 new columns to Feature model for MVP/Refinement workflow:
  - refinement_state: String(30), default='pending', indexed
    Values: pending, draft, refined_code, refined_edge, refined_perf, refined_security, polished
  - refinement_iterations: Integer, default=0
  - last_refined_at: DateTime, nullable
  - time_spent_drafting_ms: Integer, nullable
  - time_spent_refining_ms: Integer, nullable
- Updated to_dict() method to include all refinement fields
- Created _migrate_add_refinement_columns() migration function
- Registered migration in create_database() after _migrate_add_git_columns()

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add refinement Pydantic schemas

- Add RefinementPassesConfig for pass configuration (code_quality, edge_cases, etc.)
- Add RefinementConfig matching TypedDict from project_config
- Add RefinementConfigUpdate for partial updates (all fields Optional)
- Add RefinementPassInfo for pass metadata (name, enabled, description)
- Add RefinementStatusResponse with current_phase, total_features, draft_count, by_state
- Add RefinementTransitionRequest/Response for phase transitions
- Update FeatureResponse with refinement fields (refinement_state, iterations, times)

Implements Feature leonvanzyl#3: Refinement Pydantic schemas

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add refinement REST API router

Create server/routers/refinement.py with REST endpoints for refinement
workflow management:

- GET /status: Returns refinement status with phase, counts, passes
- POST /transition: Switch between MVP and refinement phases
- GET /config: Returns refinement configuration
- PUT /config: Updates refinement config (partial updates supported)
- POST /features/{id}/refine: Trigger refinement pass for feature

Includes helper functions for phase calculation, state counting, and
database access following existing router patterns from features.py.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: register refinement router in FastAPI app

- Add refinement_router import to server/routers/__init__.py
- Export refinement_router in __all__ list
- Import refinement_router in server/main.py
- Include refinement_router in app router registration

Implements Feature leonvanzyl#7: Server registration for refinement

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add refinement React hooks for UI

- Create useRefinement.ts with React Query hooks:
  - useRefinementStatus: GET /refinement/status
  - useRefinementConfig: GET /refinement/config
  - useUpdateRefinementConfig: PUT /refinement/config
  - useTransitionPhase: POST /refinement/transition
  - useTriggerRefinement: POST /refinement/features/{id}/refine
- Add type definitions to types.ts:
  - RefinementConfig, RefinementStatus, RefinementPassInfo
  - RefinementPassesConfig, RefinementConfigUpdate
  - RefinementPhase, RefinementTransitionRequest/Response
  - TriggerRefinementRequest/Response
- Add API functions to api.ts for all refinement endpoints
- All hooks use queryClient.invalidateQueries for cache updates
- Lint and TypeScript build pass

Implements Feature leonvanzyl#8: Refinement React hooks

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add refinement MCP tools for workflow management

Add 4 new MCP tools for the refinement workflow:

- feature_mark_draft: Mark feature as draft (MVP complete)
- feature_complete_refinement_pass: Complete a refinement pass on a feature
  - Supports pass_types: code_quality, edge_cases, performance, security, ux
  - State transitions: draft -> refined_code -> refined_edge -> refined_perf -> refined_security -> polished
- feature_get_for_refinement: Get features ready for a specific refinement pass
- feature_get_refinement_status: Get overall refinement progress

Also updated the module docstring to document all MCP tools including
Git tools and the new Refinement tools.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: integrate refinement workflow into orchestrator

Feature leonvanzyl#6: Orchestrator refinement integration

- Import get_refinement_config from project_config
- Load refinement config in __init__ with sensible defaults
- Add self.phase to track current development phase (mvp/refinement)
- Add _determine_phase() method to calculate phase based on feature states
- Add _check_mvp_complete() to check if all features have drafts
- Add _auto_transition_to_refinement() for automatic phase transition
- Add _mark_feature_draft() to mark features as draft when passing in MVP
- Modify _on_agent_complete() to handle MVP draft marking and auto-transition
- Add phase info to get_status() for WebSocket progress messages
- Add phase info to startup logs and debug output

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress notes for Feature leonvanzyl#6

- Documented orchestrator refinement integration implementation
- Added session summary for 2026-01-23
- 8/10 features now passing (80%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add PhaseIndicator component for MVP/Refinement phase display

- Create PhaseIndicator.tsx showing current development phase
- MVP phase: yellow/amber badge with Zap (lightning) icon
- Refinement phase: purple badge with Sparkles icon
- Display progress percentage for each phase
- Tooltip with detailed state breakdown and progress bar
- Integrate into App.tsx header section after ProjectSelector

Feature leonvanzyl#9 complete.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add RefinementDashboard component for phase progress and controls

- Create ui/src/components/RefinementDashboard.tsx with:
  - Phase toggle button (MVP <-> Refinement) using useTransitionPhase
  - Progress bars for each refinement state with color coding
  - Feature counts per state and summary statistics
  - Time tracking display placeholders
  - Auto-transition toggle from config
  - Collapsible pass settings section
- Integrate into App.tsx with 'R' keyboard shortcut
- Update KeyboardShortcutsHelp to include 'R' shortcut
- Wire up to useRefinementStatus and useRefinementConfig hooks
- Follow neobrutalism design patterns (neo-card, neo-btn, neo-badge)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update progress notes for Feature leonvanzyl#10

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: address code review issues for refinement workflow

Security:
- Add column name validation against allowlist in database migrations
  to prevent SQL injection patterns (api/database.py)

Reliability:
- Add explicit rollback on exception in db session context manager
- Add Path validation (ge=1) for feature_id in REST endpoint
- Add null check for config.passes in RefinementDashboard

Code Quality:
- Create shared api/refinement_constants.py to eliminate duplicate
  REFINEMENT_STATES and PASS_STATE_TRANSITIONS definitions
- Import shared constants in MCP tools and REST router
- Remove unused time tracking UI (placeholder showing "--")
- Comment out formatDuration function for future use

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: address medium priority code review issues

Performance:
- Reduce refetchInterval from 5s to 15s in useRefinementStatus
  to lower API load and improve mobile battery life

Security:
- Add XSS sanitization in PhaseIndicator.formatStateName()
  for unknown state names from API responses

Reliability:
- Add periodic phase refresh (every 10 iterations) in orchestrator
  main loop to catch external state changes via API

Code Quality:
- Add Field with description and example for by_state in schemas
- Clarify intentional graceful degradation in project_config.py
  error handling with improved comments

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Admin <admin@localhost>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
devxalted pushed a commit to devxalted/autocoder that referenced this pull request Jan 23, 2026
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
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.

2 participants