* POC: TanStack Query implementation with conditional devtools - Replace manual useState polling with TanStack Query for projects/tasks - Add comprehensive query key factories for cache management - Implement optimistic updates with automatic rollback - Create progress polling hooks with smart completion detection - Add VITE_SHOW_DEVTOOLS environment variable for conditional devtools - Remove legacy hooks: useDatabaseMutation, usePolling, useProjectMutation - Update components to use mutation hooks directly (reduce prop drilling) - Enhanced QueryClient with optimized polling and caching settings 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: Remove unused DataTab component and PRP templates from DocsTab - Delete unused DataTab.tsx (956 lines) - no imports found in codebase - Remove PRP template system from DocsTab.tsx (424 lines removed) - Simplify document templates to basic markdown and meeting notes - Reduce DocsTab from 1,494 to 1,070 lines * feat: Add vertical slice architecture foundation for projects feature - Create features/projects/ directory structure - Add barrel exports and documentation for components, hooks, services, types, utils - Prepare for migrating 8,300+ lines of project-related code - Enable future feature flagging and modular architecture * remove: Delete entire PRP directory (4,611 lines) - Remove PRPViewer component and all related files - Delete 29 PRP-related files including sections, renderers, utilities - Clean up unused complex document rendering system - Simplifies codebase by removing over-engineered flip card viewer Files removed: - PRPViewer.tsx/css - Main component - sections/ - 13 specialized section components - components/ - 5 rendering components - utils/ - 6 utility files - renderers/ - Section rendering logic - types/ - PRP type definitions Part of frontend vertical slice refactoring effort. * refactor: Replace DraggableTaskCard with simplified vertical slice components - Remove complex DraggableTaskCard.tsx (268 lines) - Create TaskCard.tsx (87 lines) with glassmorphism styling preserved - Create TaskCardActions.tsx (83 lines) for separated action buttons - Move to features/projects/components/tasks/ vertical slice architecture Changes: - Remove flip animation complexity (100+ lines removed) - Preserve beautiful glassmorphism effects and hover states - Maintain drag-and-drop, selection, priority indicators - Fix card height issues and column stacking - Add visible task descriptions (no tooltip needed) - Update TaskBoardView and TaskTableView imports - Add lint:files npm script for targeted linting Result: 68% code reduction (268→87 lines) while preserving visual design All linting errors resolved, zero warnings on new components. * refactor: Remove PRP templates and PRPViewer from DocsTab - Remove PRP template system from DOCUMENT_TEMPLATES (424 lines) - Remove PRPViewer import and usage in beautiful view mode - Simplify document templates to basic markdown and meeting notes - Replace PRPViewer with temporary unavailable message - Reduce DocsTab from 1,494 to 1,070 lines Templates removed: - Complex PRP templates with structured sections - Over-engineered document generation logic - Unused template complexity Keeps essential functionality: - Basic markdown document template - Meeting notes template - Document creation and management - Template modal and selection Part of frontend cleanup removing unused PRP functionality. * refactor: Migrate to vertical slice architecture with Radix primitives - Migrated TasksTab, BoardView, TableView to features/projects/tasks - Created new UI primitives layer with Radix components - Replaced custom components with Radix primitives - Added MDXEditor to replace Milkdown - Removed Milkdown dependencies - Fixed all TypeScript errors in features directory - Established vertical slice pattern for features * refactor: Complete migration to vertical slice architecture - Migrated DocsTab to features/projects/documents - Replaced Milkdown with MDXEditor for markdown editing - Removed all crawling logic from DocsTab (documents only) - Migrated VersionHistoryModal to use Radix primitives - Removed old components/project-tasks directory - Fixed all TypeScript errors in features directory - Removed Milkdown dependencies from package.json * refactor: Align document system with backend JSONB storage reality - Create proper document hooks using project updates (not individual endpoints) - Refactor DocsTab to use TanStack Query for all data fetching - Remove non-existent document API endpoints from projectService - Implement optimistic updates for document operations - Fix document deletion to work with JSONB array structure Documents are stored as JSONB array in project.docs field, not as separate database records. This refactor aligns the frontend with this backend reality. 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * fix: Simplify DocumentEditor and improve Documents sidebar styling - Use MDXEditor with out-of-the-box settings (no hacky overrides) - Update Documents sidebar with Tron-like glassmorphism theme - Fix document content extraction for JSONB structure - Improve empty state and search input styling - Add proper icons and hover effects to match app theme 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * Complete migration to vertical slice architecture with TanStack Query + Radix This completes the project refactoring with no backwards compatibility, making the migration fully complete as requested. ## Core Architecture Changes - Migrated all types from centralized src/types/ to feature-based architecture - Completed vertical slice organization with projects/tasks/documents hierarchy - Full TanStack Query integration across all data operations - Radix UI primitives integrated throughout feature components ## Type Safety & Error Handling (Alpha Principles) - Eliminated all unsafe 'any' types with proper TypeScript unions - Added comprehensive error boundaries with detailed error context - Implemented detailed error logging with variable context following alpha principles - Added optimistic updates with proper rollback patterns across all mutations ## Smart Data Management - Created smart polling system that respects page visibility/focus state - Optimized query invalidation strategy to prevent cascade invalidations - Added proper JSONB type unions for database fields (ProjectPRD, ProjectDocs, etc.) - Fixed task ordering with integer precision to avoid float precision issues ## Files Changed - Moved src/types/project.ts → src/features/projects/types/ - Updated all 60+ files with new import paths and type references - Added FeatureErrorBoundary.tsx for granular error handling - Created useSmartPolling.ts hook for intelligent polling behavior - Added comprehensive task ordering utilities with proper limits - Removed deprecated utility files (debounce.ts, taskOrdering.ts) ## Breaking Changes (No Backwards Compatibility) - Removed centralized types directory completely - Changed TaskPriority from "urgent" to "critical" - All components now use feature-scoped types and hooks - Full migration to TanStack Query patterns with no legacy fallbacks Fixes all critical issues from code review and completes the refactoring milestone. * Fix remaining centralized type imports in project components Updated all project feature components to use the new vertical slice type imports from '../types' instead of '../../../types/project'. This completes the final step of the migration with no backwards compatibility remaining: - ProjectsView.tsx - ProjectList.tsx - NewProjectModal.tsx - ProjectCard.tsx - useProjectQueries.ts All project-related code now uses feature-scoped types exclusively. * refactor: Complete vertical slice service architecture migration Breaks down monolithic projectService (558 lines) into focused, feature-scoped services following true vertical slice architecture with no backwards compatibility. ## Service Architecture Changes - projectService.ts → src/features/projects/services/projectService.ts (Project CRUD) - → src/features/projects/tasks/services/taskService.ts (Task management) - → src/features/projects/documents/services/documentService.ts (Document versioning) - → src/features/projects/shared/api.ts (Common utilities & error handling) ## Benefits Achieved - True vertical slice: Each feature owns its complete service stack - Better separation: Task operations isolated from project operations - Easier testing: Individual services can be mocked independently - Team scalability: Features can be developed independently - Code splitting: Better tree-shaking and bundle optimization - Clearer dependencies: Services import only what they need ## Files Changed - Created 4 new focused service files with proper separation of concerns - Updated 5+ hook files to use feature-scoped service imports - Removed monolithic src/services/projectService.ts (17KB) - Updated VersionHistoryModal to use documentService instead of commented TODOs - All service index files properly export their focused services ## Validation - Build passes successfully confirming all imports are correct - All existing functionality preserved with no breaking changes - Error handling patterns maintained across all new services - No remaining references to old monolithic service This completes the final step of vertical slice architecture migration. * feat: Add Biome linter for /features directory - Replace ESLint with Biome for 35x faster linting - Configure Biome for AI-friendly JSON output - Fix all auto-fixable issues (formatting, imports) - Add targeted suppressions for legitimate ARIA roles - Set practical formatting rules (120 char line width) - Add npm scripts for various Biome operations - Document Biome usage for AI assistants * chore: Configure IDE settings for Biome/ESLint separation - Add .zed/settings.json for Zed IDE configuration - Configure ESLint to ignore /src/features (handled by Biome) - Add .zed to .gitignore - Enable Biome LSP for features, ESLint for legacy code - Configure Ruff for Python files * fix: Resolve critical TypeScript errors in features directory - Fix property access errors with proper type narrowing - Move TaskCounts to tasks types (vertical slice architecture) - Add formatZodErrors helper for validation error handling - Fix query return types with explicit typing - Remove unused _githubRepoId variable - Resolve ambiguous exports between modules - Reduced TypeScript errors from 40 to 28 * fix: resolve final TypeScript error in features directory - Update UseTaskEditorReturn interface to properly type projectFeatures - Change from unknown[] to explicit shape with id, label, type, and color properties - All TypeScript errors in /src/features now resolved * docs: improve CLAUDE.md with comprehensive development commands and architecture details - Add detailed frontend and backend development commands - Document vertical slice architecture with folder structure - Include TanStack Query patterns and code examples - Add backend service layer and error handling patterns - Document smart polling hooks and HTTP polling architecture - Include specific commands for TypeScript checking and linting - Add MCP tools documentation and debugging steps * fix: Correct Radix UI Select disabled prop usage and drag-drop bounds - Move disabled prop from Select root to SelectTrigger for proper functionality - Remove redundant manual disabled styling (opacity-50, cursor-not-allowed) - Add aria-disabled for enhanced accessibility compliance - Fix TasksTab bounds check to allow dropping at end of columns - Components: TaskPriority, TaskAssignee, TasksTab 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * fix: Improve API reliability and task management - Fix DELETE operations by handling 204 No Content responses in both callAPI and apiRequest - Replace custom calculateReorderPosition with battle-tested getReorderTaskOrder utility - Fix DeleteConfirmModal default open prop to prevent unexpected modal visibility - Add SSR guards to useSmartPolling hook to prevent crashes in non-browser environments 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * feat: Add review task count support with clean UI design - Add review field to TaskCounts interface for type consistency - Update backend to return separate review counts instead of mapping to doing - Enhance ProjectCard to display review tasks in clean 3-column layout - Combine doing+review counts in project cards for optimal visual design - Maintain granular data for detailed views (Kanban board still shows separate review column) Resolves CodeRabbit suggestion about missing review status while preserving clean UI 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * Enhance FeatureErrorBoundary with TanStack Query integration - Add onReset callback prop for external reset handlers - Fix getDerivedStateFromError TypeScript return type - Gate console logging to development/test environments only - Add accessibility attributes (role=alert, aria-live, aria-hidden) - Integrate QueryErrorResetBoundary in ProjectsViewWithBoundary 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: improve code formatting and consistency - Fix line breaks and formatting in TasksTab.tsx task reordering - Clean up import formatting in ProjectsView.tsx - Standardize quote usage in useSmartPolling.ts 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * feat: Migrate toast notifications to Radix UI primitives in features directory - Add @radix-ui/react-toast dependency - Create toast.tsx primitive with glassmorphism styling - Implement useToast hook matching legacy API - Add ToastProvider component wrapping Radix primitives - Update all 13 feature files to use new toast system - Maintain dual toast systems (legacy for non-features, new for features) - Fix biome linting issues with auto-formatting This migration establishes Radix UI as the foundation for the features vertical slice architecture while maintaining backward compatibility. Co-Authored-By: Claude <noreply@anthropic.com> * chore: Remove accidentally committed PRP file PRP files are for local development planning only and should not be in version control * refactor: simplify documents feature to read-only viewer - Remove MDXEditor and all editing capabilities due to persistent state issues - Add DocumentViewer component for reliable read-only display - Add migration warning banner clarifying project documents will be lost - Remove all mutation hooks, services, and components - Clean up unused types and dead code - Fix linting issues (SVG accessibility, array keys) - Simplify to display existing JSONB documents from project.docs field This temporary read-only state allows users to view existing documents while the feature undergoes migration to a more robust storage solution. * fix: eliminate duplicate toast notifications and React key warnings - Remove duplicate toast calls from component callbacks (TasksTab, useTaskActions, etc) - Keep toast notifications only in mutation definitions for single source of truth - Add success toast for task status changes in useTaskQueries - Improve toast ID generation with timestamp + random string to prevent duplicates - Remove unused useToast imports from components This fixes the 'Encountered two children with the same key' warning by ensuring only one toast is created per action instead of multiple simultaneous toasts. * feat: add optimistic updates for task and project creation - Implement optimistic updates for useCreateTask mutation - Tasks now appear instantly with temporary ID - Replaced with real task from server on success - Rollback on error with proper error handling - Implement optimistic updates for useCreateProject mutation - Projects appear immediately in the list - Temporary ID replaced with real one on success - Proper rollback on failure - Both mutations follow existing patterns from update/delete operations - Provides instant visual feedback improving perceived performance - Eliminates 2-3 second delay before items appear in UI * style: apply Biome formatting and remove unused dependencies - Format code with Biome standards - Remove unused showToast from useCallback dependencies in TasksTab - Minor formatting adjustments for better readability * fix: remove unused showToast import from TasksTab - Remove unused useToast hook import and usage - Fixes Biome noUnusedVariables error * fix: sort projects by creation date instead of alphabetically - Change project list sorting to: pinned first, then newest first - Ensures new projects appear on the left (after pinned) as expected - Maintains chronological order instead of alphabetical - Better UX for seeing recently created projects * optimize: adjust polling intervals for better performance - Projects: 20s polling (was 10s), 15s stale time (was 3s) - Tasks: 5s polling (was 8s) for faster MCP updates, 10s stale time (was 2s) - Background: 60s for all (was 24-30s) when tab not focused - Hidden tabs: Polling disabled (unchanged) Benefits: - Tasks update faster (5s) to reflect MCP server changes quickly - Projects poll less frequently (20s) as they change less often - Longer stale times reduce unnecessary refetches during navigation - Background polling reduced to save resources when not actively using app * feat: Add ETag support to reduce bandwidth by 70-90% - Created ETag-aware API client (apiWithEtag.ts) with caching - Integrated with TanStack Query for seamless cache management - Updated all services to use ETag-aware API calls - Added cache invalidation after mutations - Handles 304 Not Modified responses efficiently - Includes colored console logging for debugging - Works with 5-second task polling and 20-second project polling * fix: TanStack Query improvements from CodeRabbit review - Fixed concurrent project creation bug by tracking specific temp IDs - Unified task counts query keys to fix cache invalidation - Added TypeScript generics to getQueryData calls for type safety - Added return type to useTaskCounts hook - Prevented double refetch with refetchOnWindowFocus: false - Improved cache cleanup with exact: false on removeQueries 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * feat: improve ProjectList animations, sorting, and accessibility - Added initial/animate props to fix Framer Motion animations - Made sort deterministic with invalid date guards and ID tie-breaker - Added ARIA roles for better screen reader support: - role=status for loading state - role=alert for error state - role=list for project container - role=listitem for ProjectCard - Improved robustness against malformed date strings 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * fix: use consistent ORDER_INCREMENT value for task ordering - Fixed bug where TasksTab used 100 while utils used 1000 for increments - Exported ORDER_INCREMENT constant from task-ordering utils - Updated TasksTab to import and use the shared constant - Ensures consistent task ordering behavior across the application 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * fix: improve type safety and correctness in task mutations - Changed error handling to throw Error objects instead of strings - Added TypeScript generics to delete mutation for better type safety - Fixed incorrect Task shape by removing non-existent fields (deleted_at, subtasks) - Track specific tempId for optimistic updates to avoid replacing wrong tasks 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * Delete report.md * fix: address CodeRabbit review feedback for TanStack Query implementation - Enable refetchOnWindowFocus for immediate data refresh when returning to tab - Add proper TypeScript generics to useUpdateTask mutation for server response merge - Normalize HTTP methods to uppercase in ETag cache to prevent cache key mismatches - Add ETAG_DEBUG flag to control console logging (only in dev mode) - Fix 304 cache miss handling with proper error and ETag cleanup - Update outdated comments and add explicit type annotations - Rename getETagCacheStats property from 'endpoints' to 'keys' for accuracy --------- Co-authored-by: Claude <noreply@anthropic.com>
16 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Alpha Development Guidelines
Local-only deployment - each user runs their own instance.
Core Principles
- No backwards compatibility - remove deprecated code immediately
- Detailed errors over graceful failures - we want to identify and fix issues fast
- Break things to improve them - alpha is for rapid iteration
Error Handling
Core Principle: In alpha, we need to intelligently decide when to fail hard and fast to quickly address issues, and when to allow processes to complete in critical services despite failures. Read below carefully and make intelligent decisions on a case-by-case basis.
When to Fail Fast and Loud (Let it Crash!)
These errors should stop execution and bubble up immediately: (except for crawling flows)
- Service startup failures - If credentials, database, or any service can't initialize, the system should crash with a clear error
- Missing configuration - Missing environment variables or invalid settings should stop the system
- Database connection failures - Don't hide connection issues, expose them
- Authentication/authorization failures - Security errors must be visible and halt the operation
- Data corruption or validation errors - Never silently accept bad data, Pydantic should raise
- Critical dependencies unavailable - If a required service is down, fail immediately
- Invalid data that would corrupt state - Never store zero embeddings, null foreign keys, or malformed JSON
When to Complete but Log Detailed Errors
These operations should continue but track and report failures clearly:
- Batch processing - When crawling websites or processing documents, complete what you can and report detailed failures for each item
- Background tasks - Embedding generation, async jobs should finish the queue but log failures
- WebSocket events - Don't crash on a single event failure, log it and continue serving other clients
- Optional features - If projects/tasks are disabled, log and skip rather than crash
- External API calls - Retry with exponential backoff, then fail with a clear message about what service failed and why
Critical Nuance: Never Accept Corrupted Data
When a process should continue despite failures, it must skip the failed item entirely rather than storing corrupted data:
❌ WRONG - Silent Corruption:
try:
embedding = create_embedding(text)
except Exception as e:
embedding = [0.0] * 1536 # NEVER DO THIS - corrupts database
store_document(doc, embedding)
✅ CORRECT - Skip Failed Items:
try:
embedding = create_embedding(text)
store_document(doc, embedding) # Only store on success
except Exception as e:
failed_items.append({'doc': doc, 'error': str(e)})
logger.error(f"Skipping document {doc.id}: {e}")
# Continue with next document, don't store anything
✅ CORRECT - Batch Processing with Failure Tracking:
def process_batch(items):
results = {'succeeded': [], 'failed': []}
for item in items:
try:
result = process_item(item)
results['succeeded'].append(result)
except Exception as e:
results['failed'].append({
'item': item,
'error': str(e),
'traceback': traceback.format_exc()
})
logger.error(f"Failed to process {item.id}: {e}")
# Always return both successes and failures
return results
Error Message Guidelines
- Include context about what was being attempted when the error occurred
- Preserve full stack traces with
exc_info=Truein Python logging - Use specific exception types, not generic Exception catching
- Include relevant IDs, URLs, or data that helps debug the issue
- Never return None/null to indicate failure - raise an exception with details
- For batch operations, always report both success count and detailed failure list
Code Quality
- Remove dead code immediately rather than maintaining it - no backward compatibility or legacy functions
- Prioritize functionality over production-ready patterns
- Focus on user experience and feature completeness
- When updating code, don't reference what is changing (avoid keywords like LEGACY, CHANGED, REMOVED), instead focus on comments that document just the functionality of the code
Development Commands
Frontend (archon-ui-main/)
npm run dev # Start development server on port 3737
npm run build # Build for production
npm run lint # Run ESLint on legacy code (excludes /features)
npm run lint:files path/to/file.tsx # Lint specific files
# Biome for /src/features directory only
npm run biome # Check features directory
npm run biome:fix # Auto-fix issues
npm run biome:format # Format code (120 char lines)
npm run biome:ai # Machine-readable JSON output for AI
npm run biome:ai-fix # Auto-fix with JSON output
# Testing
npm run test # Run all tests in watch mode
npm run test:ui # Run with Vitest UI interface
npm run test:coverage:stream # Run once with streaming output
vitest run src/features/projects # Test specific directory
# TypeScript
npx tsc --noEmit # Check all TypeScript errors
npx tsc --noEmit 2>&1 | grep "src/features" # Check features only
Backend (python/)
# Using uv package manager (preferred)
uv sync --group all # Install all dependencies
uv run python -m src.server.main # Run server locally on 8181
uv run pytest # Run all tests
uv run pytest tests/test_api_essentials.py -v # Run specific test
uv run ruff check # Run linter
uv run ruff check --fix # Auto-fix linting issues
uv run mypy src/ # Type check
# Docker operations
docker compose up --build -d # Start all services
docker compose --profile backend up -d # Backend only (for hybrid dev)
docker compose logs -f archon-server # View server logs
docker compose logs -f archon-mcp # View MCP server logs
docker compose restart archon-server # Restart after code changes
docker compose down # Stop all services
docker compose down -v # Stop and remove volumes
Quick Workflows
# Hybrid development (recommended) - backend in Docker, frontend local
make dev # Or manually: docker compose --profile backend up -d && cd archon-ui-main && npm run dev
# Full Docker mode
make dev-docker # Or: docker compose up --build -d
# Run linters before committing
make lint # Runs both frontend and backend linters
make lint-fe # Frontend only (ESLint + Biome)
make lint-be # Backend only (Ruff + MyPy)
# Testing
make test # Run all tests
make test-fe # Frontend tests only
make test-be # Backend tests only
Architecture Overview
Archon V2 Alpha is a microservices-based knowledge management system with MCP (Model Context Protocol) integration:
Service Architecture
-
Frontend (port 3737): React + TypeScript + Vite + TailwindCSS
- Dual UI Strategy:
/features- Modern vertical slice with Radix UI primitives + TanStack Query/components- Legacy custom components (being migrated)
- State Management: TanStack Query for all data fetching (no prop drilling)
- Styling: Tron-inspired glassmorphism with Tailwind CSS
- Linting: Biome for
/features, ESLint for legacy code
- Dual UI Strategy:
-
Main Server (port 8181): FastAPI with HTTP polling for updates
- Handles all business logic, database operations, and external API calls
- WebSocket support removed in favor of HTTP polling with ETag caching
-
MCP Server (port 8051): Lightweight HTTP-based MCP protocol server
- Provides tools for AI assistants (Claude, Cursor, Windsurf)
- Exposes knowledge search, task management, and project operations
-
Agents Service (port 8052): PydanticAI agents for AI/ML operations
- Handles complex AI workflows and document processing
-
Database: Supabase (PostgreSQL + pgvector for embeddings)
- Cloud or local Supabase both supported
- pgvector for semantic search capabilities
Frontend Architecture Details
Vertical Slice Architecture (/features)
Features are organized by domain hierarchy with self-contained modules:
src/features/
├── ui/
│ ├── primitives/ # Radix UI base components
│ ├── hooks/ # Shared UI hooks (useSmartPolling, etc)
│ └── types/ # UI type definitions
├── projects/
│ ├── components/ # Project UI components
│ ├── hooks/ # Project hooks (useProjectQueries, etc)
│ ├── services/ # Project API services
│ ├── types/ # Project type definitions
│ ├── tasks/ # Tasks sub-feature (nested under projects)
│ │ ├── components/
│ │ ├── hooks/ # Task-specific hooks
│ │ ├── services/ # Task API services
│ │ └── types/
│ └── documents/ # Documents sub-feature
│ ├── components/
│ ├── services/
│ └── types/
TanStack Query Patterns
All data fetching uses TanStack Query with consistent patterns:
// Query keys factory pattern
export const projectKeys = {
all: ["projects"] as const,
lists: () => [...projectKeys.all, "list"] as const,
detail: (id: string) => [...projectKeys.all, "detail", id] as const,
};
// Smart polling with visibility awareness
const { refetchInterval } = useSmartPolling(10000); // Pauses when tab inactive
// Optimistic updates with rollback
useMutation({
onMutate: async (data) => {
await queryClient.cancelQueries(key);
const previous = queryClient.getQueryData(key);
queryClient.setQueryData(key, optimisticData);
return { previous };
},
onError: (err, vars, context) => {
if (context?.previous) {
queryClient.setQueryData(key, context.previous);
}
},
});
Backend Architecture Details
Service Layer Pattern
# API Route -> Service -> Database
# src/server/api_routes/projects.py
@router.get("/{project_id}")
async def get_project(project_id: str):
return await project_service.get_project(project_id)
# src/server/services/project_service.py
async def get_project(project_id: str):
# Business logic here
return await db.fetch_project(project_id)
Error Handling Patterns
# Use specific exceptions
class ProjectNotFoundError(Exception): pass
class ValidationError(Exception): pass
# Rich error responses
@app.exception_handler(ProjectNotFoundError)
async def handle_not_found(request, exc):
return JSONResponse(
status_code=404,
content={"detail": str(exc), "type": "not_found"}
)
Polling Architecture
HTTP Polling (replaced Socket.IO)
- Polling intervals: 1-2s for active operations, 5-10s for background data
- ETag caching: Reduces bandwidth by ~70% via 304 Not Modified responses
- Smart pausing: Stops polling when browser tab is inactive
- Progress endpoints:
/api/progress/{id}for operation tracking
Key Polling Hooks
useSmartPolling- Adjusts interval based on page visibility/focususeCrawlProgressPolling- Specialized for crawl progress with auto-cleanupuseProjectTasks- Smart polling for task lists
Database Schema
Key tables in Supabase:
sources- Crawled websites and uploaded documents- Stores metadata, crawl status, and configuration
documents- Processed document chunks with embeddings- Text chunks with vector embeddings for semantic search
projects- Project management (optional feature)- Contains features array, documents, and metadata
tasks- Task tracking linked to projects- Status: todo, doing, review, done
- Assignee: User, Archon, AI IDE Agent
code_examples- Extracted code snippets- Language, summary, and relevance metadata
API Naming Conventions
Task Status Values
Use database values directly (no UI mapping):
todo,doing,review,done
Service Method Patterns
get[Resource]sByProject(projectId)- Scoped queriesget[Resource](id)- Single resourcecreate[Resource](data)- Create operationsupdate[Resource](id, updates)- Updatesdelete[Resource](id)- Soft deletes
State Naming
is[Action]ing- Loading states (e.g.,isSwitchingProject)[resource]Error- Error messagesselected[Resource]- Current selection
Environment Variables
Required in .env:
SUPABASE_URL=https://your-project.supabase.co # Or http://host.docker.internal:8000 for local
SUPABASE_SERVICE_KEY=your-service-key-here # Use legacy key format for cloud Supabase
Optional:
LOGFIRE_TOKEN=your-logfire-token # For observability
LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR
ARCHON_SERVER_PORT=8181 # Server port
ARCHON_MCP_PORT=8051 # MCP server port
ARCHON_UI_PORT=3737 # Frontend port
Common Development Tasks
Add a new API endpoint
- Create route handler in
python/src/server/api_routes/ - Add service logic in
python/src/server/services/ - Include router in
python/src/server/main.py - Update frontend service in
archon-ui-main/src/features/[feature]/services/
Add a new UI component in features directory
- Use Radix UI primitives from
src/features/ui/primitives/ - Create component in relevant feature folder under
src/features/[feature]/components/ - Define types in
src/features/[feature]/types/ - Use TanStack Query hook from
src/features/[feature]/hooks/ - Apply Tron-inspired glassmorphism styling with Tailwind
Debug MCP connection issues
- Check MCP health:
curl http://localhost:8051/health - View MCP logs:
docker compose logs archon-mcp - Test tool execution via UI MCP page
- Verify Supabase connection and credentials
Fix TypeScript/Linting Issues
# TypeScript errors in features
npx tsc --noEmit 2>&1 | grep "src/features"
# Biome auto-fix for features
npm run biome:fix
# ESLint for legacy code
npm run lint:files src/components/SomeComponent.tsx
Code Quality Standards
Frontend
- TypeScript: Strict mode enabled, no implicit any
- Biome for
/src/features/: 120 char lines, double quotes, trailing commas - ESLint for legacy code: Standard React rules
- Testing: Vitest with React Testing Library
Backend
- Python 3.12 with 120 character line length
- Ruff for linting - checks for errors, warnings, unused imports
- Mypy for type checking - ensures type safety
- Pytest for testing with async support
MCP Tools Available
When connected to Client/Cursor/Windsurf:
archon:perform_rag_query- Search knowledge basearchon:search_code_examples- Find code snippetsarchon:create_project- Create new projectarchon:list_projects- List all projectsarchon:create_task- Create task in projectarchon:list_tasks- List and filter tasksarchon:update_task- Update task status/detailsarchon:get_available_sources- List knowledge sources
Important Notes
- Projects feature is optional - toggle in Settings UI
- All services communicate via HTTP, not gRPC
- HTTP polling handles all updates
- Frontend uses Vite proxy for API calls in development
- Python backend uses
uvfor dependency management - Docker Compose handles service orchestration
- TanStack Query for all data fetching - NO PROP DRILLING
- Vertical slice architecture in
/features- features own their sub-features