Reorganize documentation: move all docs to /docs subdirectories

Co-authored-by: johndoe6345789 <224850594+johndoe6345789@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-01-17 00:33:02 +00:00
parent dc73b3c3cd
commit 34ca7d2c20
49 changed files with 22 additions and 281 deletions

485
docs/reference/AGENTS.md Normal file
View File

@@ -0,0 +1,485 @@
# 🤖 CodeForge AI Agents Architecture
## Overview
CodeForge uses a sophisticated AI agent architecture powered by OpenAI's GPT models to provide intelligent code generation, explanation, optimization, and error repair across the entire application. This document describes the agent system's design, components, and integration patterns.
## Architecture Principles
### 1. Modular Design
Each AI capability is encapsulated in specialized functions within service modules, allowing for:
- Independent testing and updates
- Clear separation of concerns
- Easy addition of new AI features
- Flexible model selection per use case
### 2. Context Awareness
All AI prompts include relevant project context:
- Existing models and their relationships
- Component hierarchy and structure
- Theme configuration and variants
- File contents and dependencies
- Error context from related files
### 3. Format Specification
Prompts specify exact output formats with schemas:
- JSON mode for structured data
- TypeScript interfaces for type safety
- Python with proper indentation
- Validation and sanitization of responses
### 4. Graceful Degradation
Robust error handling ensures:
- Clear error messages for users
- Fallback to manual editing
- Retry logic for transient failures
- Rate limit awareness and handling
## Core Service Modules
### AIService (`/src/lib/ai-service.ts`)
The central orchestration layer for all AI operations.
#### Key Functions
##### `generateCompleteApp(description: string)`
Generates a complete application structure from natural language.
**Prompt Strategy:**
- Analyzes description for key entities and relationships
- Creates Prisma models with appropriate field types
- Generates React components with Material UI
- Configures theme with harmonious color palette
- Returns structured JSON with all elements
**Output:**
```typescript
{
files: ProjectFile[]
models: PrismaModel[]
theme: ThemeConfig
}
```
##### `generateModels(description: string)`
Creates Prisma models from descriptions.
**Prompt Strategy:**
- Identifies entities and their attributes
- Determines field types (String, Int, DateTime, etc.)
- Creates relations (one-to-many, many-to-many)
- Sets appropriate constraints (unique, required, default)
**Example:**
```
Input: "A blog with users, posts, and comments"
Output: User model with posts relation, Post model with author and comments, Comment model with post and author
```
##### `generateComponent(description: string, existingComponents: ComponentNode[])`
Generates React component structures.
**Prompt Strategy:**
- Includes existing components to avoid naming conflicts
- Uses Material UI component library
- Creates proper component hierarchy
- Configures props and children appropriately
**Output:**
```typescript
{
id: string
type: string (e.g., "Box", "Card", "Button")
props: Record<string, any>
children: ComponentNode[]
name: string
}
```
##### `generateTheme(description: string)`
Creates Material UI themes with color palettes.
**Prompt Strategy:**
- Applies color theory for harmonious palettes
- Ensures WCAG AA accessibility (4.5:1 contrast)
- Creates both light and dark variants
- Configures typography hierarchy
- Sets spacing and border radius
**Validation:**
- Color contrast ratios verified
- Color format validation (hex to OKLCH)
- Semantic color naming (primary, secondary, etc.)
##### `explainCode(code: string, language: string)`
Provides detailed code explanations.
**Prompt Strategy:**
- Identifies key patterns and structures
- Explains purpose and functionality
- Notes best practices or anti-patterns
- Suggests improvements if applicable
##### `improveCode(code: string, language: string)`
Optimizes code quality and performance.
**Prompt Strategy:**
- Applies framework-specific best practices
- Improves readability and maintainability
- Optimizes performance where applicable
- Maintains existing functionality
- Adds TypeScript types if missing
##### `generatePlaywrightTests(description: string)`
Creates E2E test scenarios.
**Prompt Strategy:**
- Defines user flows from description
- Creates step-by-step test actions
- Uses appropriate selectors (role, testid, text)
- Adds meaningful assertions
- Handles edge cases and error states
##### `generateStorybookStories(componentName: string, description: string)`
Generates Storybook stories.
**Prompt Strategy:**
- Creates multiple story variations
- Configures args based on prop types
- Organizes by meaningful categories
- Shows different states and edge cases
##### `generateUnitTests(description: string, testType: string)`
Creates comprehensive test suites.
**Prompt Strategy:**
- Component tests use React Testing Library
- Function tests cover edge cases
- Hook tests use renderHook utility
- Integration tests combine multiple units
- Includes setup, assertions, and teardown
### ErrorRepairService (`/src/lib/error-repair-service.ts`)
Specialized service for error detection and automated repair.
#### Key Functions
##### `detectErrors(files: ProjectFile[])`
Scans files for various error types.
**Detection Methods:**
- **Syntax Errors**: Parse errors in code structure
- **Import Errors**: Missing or incorrect imports
- **Type Errors**: TypeScript type mismatches
- **Lint Errors**: ESLint violations and code smells
**Output:**
```typescript
{
id: string
fileId: string
type: 'syntax' | 'import' | 'type' | 'lint'
severity: 'error' | 'warning'
message: string
line: number
suggestion: string
}
```
##### `repairError(error: Error, fileContent: string, relatedFiles: ProjectFile[])`
AI-powered error repair with context.
**Prompt Strategy:**
- Includes error message and stack trace
- Provides file content with line numbers
- Adds related file imports as context
- Explains the fix applied
- Preserves code structure and style
**Context Examples:**
- Import errors: Include package.json for available packages
- Type errors: Include type definition files
- Component errors: Include parent component context
##### `batchRepairErrors(errors: Error[], files: ProjectFile[])`
Repairs multiple errors efficiently.
**Strategy:**
- Groups errors by file
- Applies fixes in dependency order
- Validates fixes don't introduce new errors
- Returns repaired files and success status
### Generators (`/src/lib/generators.ts`)
Code generation utilities for project export.
#### Functions
##### `generateNextJSProject(appName: string, models: PrismaModel[], components: ComponentNode[], theme: ThemeConfig)`
Creates complete Next.js file structure.
##### `generatePrismaSchema(models: PrismaModel[])`
Converts visual models to Prisma schema syntax.
##### `generateMUITheme(theme: ThemeConfig)`
Exports Material UI theme configuration.
##### `generatePlaywrightTests(tests: PlaywrightTest[])`
Converts visual test definitions to Playwright code.
##### `generateStorybookStories(stories: StorybookStory[])`
Creates Storybook CSF3 story files.
##### `generateUnitTests(tests: UnitTest[])`
Generates Vitest test files with React Testing Library.
##### `generateFlaskApp(config: FlaskConfig)`
Creates Flask application with blueprints and routes.
## Integration Points
### Component Integration
Each designer component integrates AI through consistent patterns:
#### Model Designer
```typescript
const handleGenerateModels = async () => {
const description = prompt('Describe your data models:')
const result = await AIService.generateModels(description)
if (result) {
setModels(current => [...current, ...result])
}
}
```
#### Component Tree Builder
```typescript
const handleGenerateComponent = async () => {
const description = prompt('Describe the component:')
const result = await AIService.generateComponent(description, components)
if (result) {
setComponents(current => [...current, result])
}
}
```
#### Code Editor
```typescript
const handleExplain = async () => {
const explanation = await AIService.explainCode(currentCode, language)
setExplanation(explanation)
}
const handleImprove = async () => {
const improved = await AIService.improveCode(currentCode, language)
onFileChange(fileId, improved)
}
```
#### Error Panel
```typescript
const handleRepair = async (error: Error) => {
const file = files.find(f => f.id === error.fileId)
const relatedFiles = getRelatedFiles(file, files)
const repaired = await ErrorRepairService.repairError(
error,
file.content,
relatedFiles
)
onFileChange(file.id, repaired.content)
}
```
## Prompt Engineering Best Practices
### 1. Clear Instructions
```typescript
const prompt = `You are a Next.js expert. Generate a Prisma schema based on this description:
${description}
Return ONLY valid JSON in this format:
{
"models": [
{
"name": "ModelName",
"fields": [...]
}
]
}
Ensure:
- Use appropriate field types (String, Int, DateTime, Boolean)
- Add relations where entities reference each other
- Mark required fields with isRequired: true
- Add unique constraints where appropriate`
```
### 2. Context Inclusion
```typescript
const contextPrompt = `Existing models:
${JSON.stringify(existingModels, null, 2)}
Existing components:
${JSON.stringify(existingComponents, null, 2)}
Theme colors:
${JSON.stringify(theme.variants, null, 2)}
Now generate: ${description}`
```
### 3. Output Validation
```typescript
const result = await spark.llm(prompt, 'gpt-4', true)
const parsed = JSON.parse(result)
// Validate structure
if (!parsed.models || !Array.isArray(parsed.models)) {
throw new Error('Invalid response format')
}
// Validate fields
parsed.models.forEach(model => {
if (!model.name || !model.fields) {
throw new Error('Missing required model properties')
}
})
```
### 4. Error Recovery
```typescript
try {
const result = await spark.llm(prompt, 'gpt-4', true)
return JSON.parse(result)
} catch (error) {
if (error.message.includes('rate limit')) {
toast.error('AI service rate limited. Please try again in a moment.')
} else if (error.message.includes('invalid JSON')) {
toast.error('AI response was invalid. Please try again.')
} else {
toast.error('AI generation failed. Please try manual editing.')
}
return null
}
```
## Performance Optimization
### Caching
```typescript
const cacheKey = `ai-explanation-${hash(code)}`
const cached = await spark.kv.get(cacheKey)
if (cached) return cached
const result = await spark.llm(prompt)
await spark.kv.set(cacheKey, result)
return result
```
### Debouncing
```typescript
const debouncedExplain = useMemo(
() => debounce(async (code: string) => {
const explanation = await AIService.explainCode(code, 'typescript')
setExplanation(explanation)
}, 1000),
[]
)
```
### Streaming Responses
```typescript
// Future enhancement for long-running generations
const handleGenerateWithStreaming = async () => {
const stream = await AIService.streamGeneration(description)
for await (const chunk of stream) {
appendToOutput(chunk)
}
}
```
## Future Enhancements
### Multi-Model Support
- Claude for code review and analysis
- Gemini for multimodal design tasks
- Specialized models for different languages
### Fine-Tuned Models
- Custom models trained on Next.js patterns
- Framework-specific optimizations
- Design system adherence
### Advanced Features
- Conversational interface for iterative development
- Learning from user corrections
- Project-specific context retention
- Collaborative AI sessions
- Code review agents
- Security analysis agents
- Performance optimization agents
## Testing AI Features
### Unit Tests
```typescript
describe('AIService', () => {
it('generates valid Prisma models', async () => {
const result = await AIService.generateModels('User with name and email')
expect(result).toBeDefined()
expect(result.models).toHaveLength(1)
expect(result.models[0].name).toBe('User')
expect(result.models[0].fields).toContainEqual(
expect.objectContaining({ name: 'name', type: 'String' })
)
})
})
```
### Integration Tests
```typescript
describe('Error Repair', () => {
it('fixes import errors with context', async () => {
const file = { content: 'import { Button } from "missing-package"' }
const relatedFiles = [{ content: 'package.json content...' }]
const repaired = await ErrorRepairService.repairError(
error,
file.content,
relatedFiles
)
expect(repaired.content).toContain('@mui/material')
})
})
```
## Monitoring and Analytics
### Usage Tracking
```typescript
// Track AI feature usage
const trackAIUsage = async (feature: string, success: boolean) => {
await spark.kv.set(`ai-usage-${Date.now()}`, {
feature,
success,
timestamp: new Date().toISOString()
})
}
```
### Quality Metrics
- Generation success rate
- Error repair effectiveness
- User acceptance of AI suggestions
- API response times
- Cost per operation
---
**For more information, see the [main README](./README.md) and [PRD](./PRD.md).**

View File

@@ -0,0 +1,82 @@
# Application Status
## Current Status: ✅ LOADING
The application has been restored to a working state. The main App.tsx is now being loaded and should render correctly.
## Issues Found and Fixed:
### 1. Main App Loading
- ✅ Main.tsx correctly imports App.tsx (not the broken App.new.tsx)
- ✅ All core hooks are properly defined and exported
- ✅ TypeScript types are complete and consistent
### 2. TypeScript Errors
- ⚠️ App.new.tsx has TypeScript errors but is NOT being used (can be fixed or deleted later)
- Missing properties: `lastSaved`, `getCurrentProject`, `loadProject` from useProjectState
- Wrong hook signature for useProjectExport (takes individual params, not an object)
### 3. Core Functionality Status
#### Working ✅:
- Main App component (App.tsx)
- All organism components (AppHeader, PageHeader, NavigationMenu, etc.)
- All molecule components (SaveIndicator, AppBranding, etc.)
- All hooks (useProjectState, useFileOperations, useKeyboardShortcuts, useAutoRepair)
- All types and interfaces
- All services (AIService, ErrorRepairService, ProjectService)
- PWA components
- Feature components (CodeEditor, ModelDesigner, etc.)
#### Files with TypeScript Errors (NOT BLOCKING):
- App.new.tsx - Not being used, can be removed or fixed later
## Next Steps to Complete Functionality:
### Priority 1: Verify Runtime
1. Check that the app loads in browser
2. Test navigation between tabs
3. Test project save/load
4. Test code editor functionality
### Priority 2: Fix or Remove Unused Files
- Consider removing or fixing App.new.tsx
- Consider removing or fixing App.refactored.tsx if not needed
- Consider removing or fixing App.simple.tsx if not needed
### Priority 3: Feature Testing
1. Test AI generation features
2. Test file operations
3. Test model designer
4. Test component builder
5. Test workflow designer
6. Test all testing tools (Playwright, Storybook, Unit Tests)
## Technical Notes:
### Hook Signatures:
```typescript
// useProjectExport - CORRECT signature:
useProjectExport(
files, models, components, theme,
playwrightTests, storybookStories, unitTests,
flaskConfig, nextjsConfig, npmSettings
)
// useProjectState - returns object with setters but NOT:
// - lastSaved (should be managed separately)
// - getCurrentProject (should be a helper function)
// - loadProject (should be a helper function)
```
### Missing Functionality to Implement:
If these features are needed, they should be added as separate hooks or helper functions:
- `useLastSaved()` - Track last save timestamp
- `useProjectLoader()` - Handle project loading logic
- Helper function to build current project object from state
## Conclusion:
The application should now be loading successfully. The minimal test app confirms the React/Vite/TypeScript setup is working. The main App.tsx has all required dependencies and should render without errors.
The TypeScript errors in App.new.tsx are not blocking since that file is not being imported anywhere.

View File

@@ -0,0 +1,265 @@
# Example: Adding a New "API Tester" Page
This example demonstrates the complete process of adding a new page to CodeForge using the declarative system.
## Goal
Add an "API Tester" page that allows users to test REST API endpoints.
## Step 1: Create the Component
Create `src/components/ApiTester.tsx`:
```typescript
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
export function ApiTester() {
const [method, setMethod] = useState('GET')
const [url, setUrl] = useState('')
const [response, setResponse] = useState('')
const [loading, setLoading] = useState(false)
const handleTest = async () => {
setLoading(true)
try {
const res = await fetch(url, { method })
const data = await res.json()
setResponse(JSON.stringify(data, null, 2))
} catch (error) {
setResponse(`Error: ${error}`)
} finally {
setLoading(false)
}
}
return (
<div className="h-full flex flex-col bg-background">
<div className="flex-1 overflow-auto p-6">
<div className="max-w-6xl mx-auto space-y-6">
<div>
<h1 className="text-3xl font-bold">API Tester</h1>
<p className="text-muted-foreground mt-2">
Test REST API endpoints and inspect responses
</p>
</div>
<Card>
<CardHeader>
<CardTitle>Request</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<Select value={method} onValueChange={setMethod}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="GET">GET</SelectItem>
<SelectItem value="POST">POST</SelectItem>
<SelectItem value="PUT">PUT</SelectItem>
<SelectItem value="DELETE">DELETE</SelectItem>
</SelectContent>
</Select>
<Input
placeholder="https://api.example.com/endpoint"
value={url}
onChange={(e) => setUrl(e.target.value)}
className="flex-1"
/>
<Button onClick={handleTest} disabled={!url || loading}>
{loading ? 'Testing...' : 'Test'}
</Button>
</div>
</CardContent>
</Card>
{response && (
<Card>
<CardHeader>
<CardTitle>Response</CardTitle>
</CardHeader>
<CardContent>
<Textarea
value={response}
readOnly
className="font-mono text-sm h-96"
/>
</CardContent>
</Card>
)}
</div>
</div>
</div>
)
}
```
## Step 2: Register in Component Map
Add to `src/App.tsx` in the `componentMap`:
```typescript
const componentMap: Record<string, React.LazyExoticComponent<any>> = {
// ... existing components
ApiTester: lazy(() => import('@/components/ApiTester').then(m => ({ default: m.ApiTester }))),
}
```
## Step 3: Add to pages.json
Add to `src/config/pages.json`:
```json
{
"id": "api-tester",
"title": "API Tester",
"icon": "Cloud",
"component": "ApiTester",
"enabled": true,
"toggleKey": "apiTester",
"shortcut": "ctrl+shift+a",
"order": 21
}
```
## Step 4: Add Feature Toggle (Optional)
If you want the page to be toggleable, add to `src/types/project.ts`:
```typescript
export interface FeatureToggles {
// ... existing toggles
apiTester: boolean
}
```
And add the default in `src/hooks/use-project-state.ts`:
```typescript
const DEFAULT_FEATURE_TOGGLES: FeatureToggles = {
// ... existing toggles
apiTester: true,
}
```
## Step 5: Test It!
1. Start the dev server: `npm run dev`
2. Navigate to the new page by:
- Clicking "API Tester" in the navigation menu
- Pressing `Ctrl+Shift+A`
- Searching for "API Tester" in global search (`Ctrl+K`)
## Result
**New page is fully integrated:**
- Appears in navigation menu with Cloud icon
- Accessible via keyboard shortcut (Ctrl+Shift+A)
- Can be toggled on/off in Features page
- Searchable in global search
- Follows the same layout pattern as other pages
- Lazy-loaded for optimal performance
## Benefits of Declarative Approach
**Traditional Approach (Before):**
```typescript
// Would require:
// - 20+ lines of JSX in App.tsx
// - Manual TabsContent component
// - Hardcoded shortcut handling
// - Manual feature toggle check
// - Props wiring
```
**Declarative Approach (After):**
```json
// Just 8 lines of JSON!
{
"id": "api-tester",
"title": "API Tester",
"icon": "Cloud",
"component": "ApiTester",
"enabled": true,
"toggleKey": "apiTester",
"shortcut": "ctrl+shift+a",
"order": 21
}
```
## Advanced: With Props
If your component needs props from the app state, add to `getPropsForComponent` in `App.tsx`:
```typescript
const getPropsForComponent = (pageId: string) => {
const propsMap: Record<string, any> = {
// ... existing mappings
'ApiTester': {
savedRequests: apiRequests,
onSaveRequest: saveApiRequest,
onDeleteRequest: deleteApiRequest,
},
}
return propsMap[pageId] || {}
}
```
Then update your component to accept these props:
```typescript
interface ApiTesterProps {
savedRequests?: ApiRequest[]
onSaveRequest?: (request: ApiRequest) => void
onDeleteRequest?: (id: string) => void
}
export function ApiTester({
savedRequests = [],
onSaveRequest,
onDeleteRequest
}: ApiTesterProps) {
// Use the props
}
```
## Using the Helper Scripts
Generate boilerplate code automatically:
```bash
# Generate all boilerplate
npm run pages:generate ApiTester "API Tester" "Cloud" "apiTester" "ctrl+shift+a"
# List all pages
npm run pages:list
# Validate configuration
npm run pages:validate
```
## Summary
With the declarative system, adding a new page requires:
1. ✅ Create component (1 file)
2. ✅ Add to componentMap (1 line)
3. ✅ Add to pages.json (8 lines)
4. ✅ Optional: Add feature toggle (2 lines in 2 files)
5. ✅ Optional: Add props mapping (3 lines)
**Total: ~15 lines of code vs. 50+ lines in the traditional approach!**
The system handles:
- ✅ Navigation menu rendering
- ✅ Keyboard shortcuts
- ✅ Feature toggles
- ✅ Lazy loading
- ✅ Search integration
- ✅ Consistent layouts
- ✅ Props injection

369
docs/reference/INDEX.md Normal file
View File

@@ -0,0 +1,369 @@
# 🎯 Phase 4 Refactoring - Index
## 📚 Documentation Navigation
Welcome to the Phase 4 refactoring documentation! This index will help you find what you need quickly.
## 🚀 Start Here
### New to the Refactoring?
1. **[QUICK_REFERENCE.md](./QUICK_REFERENCE.md)** - Fast overview with code examples
2. **[ARCHITECTURE_VISUAL_GUIDE.md](./ARCHITECTURE_VISUAL_GUIDE.md)** - Visual diagrams and flows
3. **[PHASE4_IMPLEMENTATION_COMPLETE.md](./PHASE4_IMPLEMENTATION_COMPLETE.md)** - Complete summary
### Ready to Code?
1. **[COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md)** - Hook API reference
2. **[JSON_ORCHESTRATION_COMPLETE.md](../architecture/JSON_ORCHESTRATION_COMPLETE.md)** - JSON page guide
3. **[MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)** - Step-by-step migration from old to new
## 📖 Documentation Files
### Core Documentation
#### 1. **QUICK_REFERENCE.md** (6.5KB)
**Purpose:** Fast lookup guide
**Contents:**
- Hook cheat sheet
- JSON schema cheat sheet
- Common patterns
- Quick examples
- File organization
**Best for:** Daily development, quick lookups
---
#### 2. **COMPLETE_HOOK_LIBRARY.md** (8.5KB)
**Purpose:** Complete hook API documentation
**Contents:**
- All 12+ hooks documented
- Usage examples for each hook
- Composition patterns
- Best practices
- Testing guidelines
**Best for:** Learning hooks, API reference
---
#### 3. **JSON_ORCHESTRATION_COMPLETE.md** (14.8KB)
**Purpose:** Complete JSON orchestration guide
**Contents:**
- Architecture overview
- Schema specifications
- Complete examples
- Advanced patterns
- Migration strategy
- Debugging tips
**Best for:** Building JSON-driven pages
---
#### 4. **PHASE4_IMPLEMENTATION_COMPLETE.md** (11.2KB)
**Purpose:** Implementation summary and overview
**Contents:**
- What was delivered
- Architecture principles
- Success metrics
- Next steps
- File reference
**Best for:** Understanding the big picture
---
#### 5. **ARCHITECTURE_VISUAL_GUIDE.md** (12.9KB)
**Purpose:** Visual architecture documentation
**Contents:**
- System architecture diagrams
- Data flow diagrams
- Component lifecycle
- Code organization
- Migration visualization
**Best for:** Understanding system design
---
#### 6. **MIGRATION_GUIDE.md** (11.8KB)
**Purpose:** Step-by-step migration instructions
**Contents:**
- Three migration paths (hooks, split, JSON)
- Hook extraction guide
- Component splitting guide
- JSON conversion guide
- Decision matrix
- Common issues and solutions
**Best for:** Migrating existing components
---
## 🗂️ Code Organization
### Hook Library
```
src/hooks/
├── data/ # 6 hooks (~300 LOC)
│ ├── use-array.ts
│ ├── use-crud.ts
│ ├── use-search.ts
│ ├── use-debounce.ts
│ ├── use-sort.ts
│ └── use-pagination.ts
├── ui/ # 4 hooks (~120 LOC)
│ ├── use-dialog.ts
│ ├── use-tabs.ts
│ ├── use-selection.ts
│ └── use-clipboard.ts
└── forms/ # 2 hooks (~130 LOC)
├── use-form.ts
└── use-form-field.ts
```
### Orchestration Engine
```
src/config/orchestration/
├── schema.ts # TypeScript/Zod schemas
├── action-executor.ts # Action execution
├── data-source-manager.ts # Data management
├── component-registry.ts # Component lookup
├── PageRenderer.tsx # Main renderer
└── index.ts # Exports
```
### Example Pages
```
src/config/pages/
├── dashboard.json # Dashboard example
└── simple-form.json # Form example
```
## 🎓 Learning Path
### Beginner (New to the system)
1. Read **QUICK_REFERENCE.md** (15 min)
2. Browse **ARCHITECTURE_VISUAL_GUIDE.md** (10 min)
3. Try a simple hook from examples (30 min)
**Total:** ~1 hour
---
### Intermediate (Ready to build)
1. Read **COMPLETE_HOOK_LIBRARY.md** (30 min)
2. Read **JSON_ORCHESTRATION_COMPLETE.md** (45 min)
3. Build a small feature with hooks (2 hours)
4. Create a JSON page (1 hour)
**Total:** ~4 hours
---
### Advanced (Migration & patterns)
1. Read **PHASE4_IMPLEMENTATION_COMPLETE.md** (20 min)
2. Read **MIGRATION_GUIDE.md** (30 min)
3. Study existing hook implementations (1 hour)
4. Migrate a component (2-4 hours)
5. Create custom composed hooks (2-4 hours)
**Total:** ~8 hours
---
## 🔍 Finding Information
### "How do I...?"
#### Data Management
- **Store an array?** → `useArray` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#usearray)
- **Search items?** → `useSearch` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#usesearch)
- **Sort items?** → `useSort` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#usesort)
- **Paginate items?** → `usePagination` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#usepagination)
- **CRUD operations?** → `useCRUD` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#usecrud)
#### UI State
- **Modal/dialog?** → `useDialog` in [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#ui-hooks)
- **Tabs?** → `useTabs` in [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#ui-hooks)
- **Multi-select?** → `useSelection` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#useselection)
- **Copy to clipboard?** → `useClipboard` in [QUICK_REFERENCE.md](./QUICK_REFERENCE.md#ui-hooks)
#### Forms
- **Full form?** → `useForm` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#useform)
- **Single field?** → `useFormField` in [COMPLETE_HOOK_LIBRARY.md](../api/COMPLETE_HOOK_LIBRARY.md#useformfield)
#### JSON Pages
- **Create a page?** → [JSON_ORCHESTRATION_COMPLETE.md](../architecture/JSON_ORCHESTRATION_COMPLETE.md#complete-examples)
- **Define data sources?** → [JSON_ORCHESTRATION_COMPLETE.md](../architecture/JSON_ORCHESTRATION_COMPLETE.md#2-data-sources)
- **Add actions?** → [JSON_ORCHESTRATION_COMPLETE.md](../architecture/JSON_ORCHESTRATION_COMPLETE.md#3-actions)
- **Build component tree?** → [JSON_ORCHESTRATION_COMPLETE.md](../architecture/JSON_ORCHESTRATION_COMPLETE.md#4-components)
#### Architecture
- **System design?** → [ARCHITECTURE_VISUAL_GUIDE.md](./ARCHITECTURE_VISUAL_GUIDE.md)
- **Data flow?** → [ARCHITECTURE_VISUAL_GUIDE.md](./ARCHITECTURE_VISUAL_GUIDE.md#data-flow-diagram)
- **Migration path?** → [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)
- **How to migrate?** → [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md#-migration-strategy)
---
## 📋 Quick Start Checklist
### Using Hooks
- [ ] Read hook documentation
- [ ] Import the hook you need
- [ ] Use in your component
- [ ] Test the functionality
### Creating JSON Pages
- [ ] Read JSON orchestration guide
- [ ] Create JSON schema file
- [ ] Define data sources
- [ ] Build component tree
- [ ] Add actions
- [ ] Test with PageRenderer
### Migrating Components
- [ ] Identify large component
- [ ] Extract business logic to hooks
- [ ] Split into smaller components
- [ ] Create JSON schema (if applicable)
- [ ] Test thoroughly
- [ ] Remove old code
---
## 🎯 Key Concepts Summary
### Hooks
- **Purpose:** Extract and reuse business logic
- **Size:** All under 150 LOC
- **Location:** `/src/hooks/`
- **Examples:** useArray, useCRUD, useSearch, useDialog, useForm
### JSON Orchestration
- **Purpose:** Define pages without code
- **Format:** JSON schema files
- **Location:** `/src/config/pages/`
- **Benefits:** Rapid prototyping, easy testing, no rebuilds
### Component Size
- **Target:** Under 150 LOC
- **Strategy:** Extract logic to hooks
- **Focus:** Presentation only
- **Benefits:** Readable, maintainable, testable
---
## 📊 Statistics
### Code Written
- **12+ custom hooks** (~550 LOC)
- **5 orchestration files** (~325 LOC)
- **2 example JSON pages** (~120 LOC)
- **5 documentation files** (~54KB)
### Metrics
- ✅ All hooks < 150 LOC
- ✅ All orchestration files < 85 LOC
- ✅ Full type safety (TypeScript + Zod)
- ✅ Zero breaking changes
- ✅ Backward compatible
---
## 🆘 Getting Help
### Documentation Issues
1. Check this index
2. Search within specific docs
3. Review code examples
4. Check `/src/config/pages/` for examples
### Code Issues
1. Review hook implementations in `/src/hooks/`
2. Check component registry
3. Validate JSON schemas with Zod
4. Enable debug mode on PageRenderer
### Questions
1. What are you trying to do?
2. Which doc is most relevant?
3. Have you checked the examples?
4. Need a custom solution?
---
## 🔗 Related Files
### Implementation
- `/src/hooks/` - Hook implementations
- `/src/config/orchestration/` - Engine code
- `/src/config/pages/` - Example pages
### Documentation (This Section)
- `QUICK_REFERENCE.md` - Fast lookup
- `COMPLETE_HOOK_LIBRARY.md` - Hook API
- `JSON_ORCHESTRATION_COMPLETE.md` - JSON guide
- `PHASE4_IMPLEMENTATION_COMPLETE.md` - Summary
- `ARCHITECTURE_VISUAL_GUIDE.md` - Diagrams
### Legacy Documentation
- `REFACTOR_PHASE4_COMPLETE.md` - Original plan
- `HOOK_LIBRARY_DOCS.md` - Early hook docs
- `JSON_ORCHESTRATION_GUIDE.md` - Early JSON docs
---
## ✨ What's Next?
### Immediate Actions
1. ✅ Hook library created
2. ✅ Orchestration engine built
3. ✅ Documentation written
4. ✅ Examples provided
### Your Next Steps
1. 📖 Read QUICK_REFERENCE.md
2. 🔨 Try using a hook
3. 📄 Create a JSON page
4. 🔄 Migrate a component
### Future Enhancements
- Visual JSON schema editor
- More hook utilities
- Advanced patterns
- Performance profiling
- Analytics integration
---
**Last Updated:** Phase 4 Implementation
**Status:** ✅ Complete
**Version:** 4.0.0
**Breaking Changes:** None
**Migration:** Optional (gradual)
---
## 📚 Full Documentation Tree
```
Documentation/
├── INDEX.md (this file) # Navigation hub
├── QUICK_REFERENCE.md # Fast lookup guide
├── COMPLETE_HOOK_LIBRARY.md # Hook API reference
├── JSON_ORCHESTRATION_COMPLETE.md # JSON orchestration guide
├── MIGRATION_GUIDE.md # Migration instructions
├── PHASE4_IMPLEMENTATION_COMPLETE.md # Summary
└── ARCHITECTURE_VISUAL_GUIDE.md # Visual diagrams
Code/
├── src/hooks/ # Hook implementations
├── src/config/orchestration/ # Engine code
└── src/config/pages/ # Example JSON pages
```
---
**Happy Coding! 🚀**

428
docs/reference/ROADMAP.md Normal file
View File

@@ -0,0 +1,428 @@
# 🗺️ CodeForge Product Roadmap
## Vision
CodeForge aims to become the most comprehensive low-code platform for full-stack application development, combining visual design tools, direct code editing, and AI-powered generation to accelerate development while maintaining professional code quality.
## Release History
### v1.0 - Foundation (Completed)
**Release Date:** Initial Release
Core low-code platform with essential designers:
- ✅ Monaco Code Editor integration with syntax highlighting
- ✅ Multi-file editing with tabs
- ✅ Prisma Schema Designer with visual model builder
- ✅ Component Tree Builder for React hierarchies
- ✅ File Explorer with add/delete capabilities
- ✅ Project export functionality
- ✅ Auto-save to persistent storage
### v1.1 - Enhanced Theming (Completed)
**Release Date:** Week 2
Advanced theming capabilities:
- ✅ Material UI Theme Designer
- ✅ Color palette customization
- ✅ Typography configuration
- ✅ Spacing and border radius controls
- ✅ Live theme preview
### v2.0 - AI Integration (Completed)
**Release Date:** Week 3
OpenAI-powered generation across all features:
- ✅ Complete application generation from descriptions
- ✅ AI-powered model generation
- ✅ AI-powered component generation
- ✅ Code explanation feature in editor
- ✅ Code improvement suggestions
- ✅ Natural language to code translation
### v2.1 - Multi-Theme Variants (Completed)
**Release Date:** Week 4
Extended theme system:
- ✅ Multiple theme variants (light, dark, custom)
- ✅ Unlimited custom colors beyond standard palette
- ✅ Theme variant switching
- ✅ AI theme generation with accessibility checks
- ✅ WCAG contrast validation
### v3.0 - Testing Suite (Completed)
**Release Date:** Week 5
Comprehensive testing tools:
- ✅ Playwright E2E Test Designer
- ✅ Storybook Story Designer
- ✅ Unit Test Designer (components, functions, hooks, integration)
- ✅ Visual test step configuration
- ✅ AI test generation for all test types
- ✅ Test export with proper file structure
### v3.1 - Error Detection & Repair (Completed)
**Release Date:** Week 6
Automated quality assurance:
- ✅ Syntax error detection
- ✅ Import error detection
- ✅ TypeScript type error detection
- ✅ ESLint violation detection
- ✅ AI-powered error repair
- ✅ Context-aware fixes using related files
- ✅ Batch repair functionality
- ✅ Repair explanations
### v3.2 - UI Improvements (Completed)
**Release Date:** Week 7
Enhanced user experience:
- ✅ Multi-row tab support for many open features
- ✅ Responsive layout improvements
- ✅ Better error state visualization
- ✅ Improved empty states across designers
- ✅ Loading states for AI operations
### v4.0 - Full-Stack Development (Completed)
**Release Date:** Week 8
Backend and configuration tools:
- ✅ Flask Backend Designer with blueprints
- ✅ REST API endpoint configuration
- ✅ CORS and authentication settings
- ✅ Next.js settings designer
- ✅ npm package management
- ✅ Build script configuration
- ✅ Package manager selection (npm/yarn/pnpm)
- ✅ Complete project settings control
### v4.1 - Enhanced Export & Documentation (Completed)
**Release Date:** Week 9
Improved export and comprehensive documentation:
- ✅ ZIP file download for complete project export
- ✅ Auto-generated README in exported projects
- ✅ Copy all files to clipboard functionality
- ✅ Comprehensive in-app documentation system
- ✅ Sass styles guide with live examples
- ✅ Complete roadmap documentation
- ✅ AI agents architecture documentation
- ✅ Project dashboard with completion metrics
- ✅ Keyboard shortcuts for power users
- ✅ Search functionality in documentation
### v5.0 - Workflows, Lambdas & Feature Toggles (Completed)
**Release Date:** Week 10
Advanced automation and customization:
- ✅ n8n-style workflow designer with visual node editor
- ✅ Workflow nodes: triggers, actions, conditions, transforms, lambdas, API calls, database queries
- ✅ Visual workflow connections and data flow
- ✅ Lambda function designer with Monaco editor
- ✅ Multi-runtime lambda support (JavaScript, TypeScript, Python)
- ✅ Lambda triggers (HTTP, schedule, event, queue)
- ✅ Environment variable management for lambdas
- ✅ Multiple Component Trees management system
- ✅ Feature toggle system to enable/disable designers
- ✅ Customizable workspace based on user needs
### v5.1 - CI/CD Integration (Completed)
**Release Date:** Week 11
Comprehensive DevOps pipeline configuration:
- ✅ GitHub Actions workflow generator
- ✅ GitLab CI/CD pipeline configuration
- ✅ Jenkins pipeline (Jenkinsfile) generation
- ✅ CircleCI configuration
- ✅ Multi-stage builds and deployments
- ✅ Environment-specific configurations
- ✅ Automated testing in pipelines
- ✅ Docker integration in CI/CD
- ✅ Deployment strategies configuration
### v5.2 - Project Persistence (Completed)
**Release Date:** Week 12
Complete project management system:
- ✅ Save projects to Spark KV database
- ✅ Load projects from database
- ✅ Project listing with metadata (name, description, timestamps)
- ✅ Duplicate existing projects
- ✅ Delete projects from database
- ✅ Export projects as JSON files
- ✅ Import projects from JSON
- ✅ New project creation with state reset
- ✅ Current project indicator
- ✅ Complete state persistence (files, models, components, trees, workflows, lambdas, themes, tests, settings)
### v5.3 - Progressive Web App (Completed)
**Release Date:** Week 13
Full PWA capabilities for offline-first experience:
- ✅ Service Worker with intelligent caching strategies
- ✅ Web App Manifest with icons and metadata
- ✅ Install prompt for desktop and mobile
- ✅ Offline functionality with cache fallbacks
- ✅ Update notifications when new version available
- ✅ Network status indicator
- ✅ Push notification support
- ✅ App shortcuts for quick access
- ✅ Share target API integration
- ✅ Background sync capabilities
- ✅ PWA settings panel for cache management
- ✅ Installability detection and prompts
## Upcoming Releases
### v5.4 - Real-Time Preview (In Planning)
**Estimated:** Q2 2024
Live application preview:
- [ ] Embedded iframe preview pane
- [ ] Hot reload on code/config changes
- [ ] Multiple device viewport simulation
- [ ] Browser DevTools integration
- [ ] Console output capture
- [ ] Network request monitoring
**Technical Challenges:**
- Sandboxed execution environment
- Hot module replacement (HMR) configuration
- State preservation across reloads
- Error boundary implementation
### v4.3 - Data Management (In Planning)
**Estimated:** Q2 2024
Database and API integration:
- [ ] Database seeding designer
- [ ] Sample data generation with AI
- [ ] API client generator from Flask definitions
- [ ] Request/response type generation
- [ ] API testing playground
- [ ] Mock data management
**Features:**
- Visual seed data builder
- Realistic data generation with AI
- TypeScript API client with fetch/axios
- Automatic type inference from endpoints
### v4.4 - Form Builder (In Planning)
**Estimated:** Q2-Q3 2024
Visual form design:
- [ ] Drag-and-drop form builder
- [ ] Field type library (text, email, select, etc.)
- [ ] Validation rule configuration
- [ ] Conditional field visibility
- [ ] Multi-step form support
- [ ] Form submission handling
- [ ] Integration with Prisma models
**Technologies:**
- React Hook Form integration
- Zod schema validation
- Material UI form components
### v4.5 - Authentication & Security (In Planning)
**Estimated:** Q3 2024
Complete authentication system:
- [ ] Authentication strategy designer
- [ ] JWT configuration (frontend + backend)
- [ ] OAuth provider integration (Google, GitHub, etc.)
- [ ] Session management
- [ ] Role-based access control (RBAC)
- [ ] Protected route configuration
- [ ] Password reset flows
- [ ] Email verification flows
**Security Features:**
- HTTPS enforcement
- CSRF protection
- Rate limiting configuration
- Security headers (CORS, CSP, etc.)
- Input sanitization rules
**Docker & Deployment:**
- [ ] Dockerfile generation
- [ ] docker-compose configuration
- [ ] Environment variable management
- [ ] Production vs development configs
- [ ] Container orchestration templates
### v5.1 - GraphQL Support (In Planning)
**Estimated:** Q3 2024
Alternative to REST APIs:
- [ ] GraphQL schema designer
- [ ] Resolver configuration
- [ ] Query and mutation builder
- [ ] Subscription support
- [ ] Apollo Server integration
- [ ] GraphQL client generation
- [ ] Schema validation and introspection
**Features:**
- Visual schema builder with types and relations
- Automatic resolver generation from Prisma
- GraphQL Playground integration
- Type-safe client with generated hooks
### v5.2 - State Management (In Planning)
**Estimated:** Q3-Q4 2024
Advanced state patterns:
- [ ] State management strategy selector
- [ ] Redux Toolkit configuration
- [ ] Zustand store designer
- [ ] Jotai atom configuration
- [ ] Global state designer
- [ ] Action/reducer builder
- [ ] Async state management (React Query)
- [ ] State persistence configuration
**Designer Features:**
- Visual state flow diagrams
- Action dispatching visualization
- State inspection and debugging
- Performance optimization suggestions
### v5.3 - CI/CD & DevOps (In Planning)
**Estimated:** Q4 2024
Automated deployment pipelines:
- [ ] GitHub Actions workflow generator
- [ ] GitLab CI configuration
- [ ] CircleCI pipeline builder
- [ ] Automated testing in CI
- [ ] Build and deployment stages
- [ ] Environment-specific configs
- [ ] Secrets management
- [ ] Deployment notifications
**Integrations:**
- Vercel deployment
- Netlify deployment
- AWS deployment (ECS, Lambda)
- Docker registry push
- Database migration in CI
### v6.0 - Component Libraries & Design Systems (In Planning)
**Estimated:** Q4 2024
Advanced design tooling:
- [ ] Component library export as npm package
- [ ] Design token management
- [ ] Component documentation generator
- [ ] Design system designer
- [ ] Variant system configuration
- [ ] Accessibility annotations
- [ ] Component playground
**Features:**
- Automatic package.json for library
- TypeScript declaration generation
- Component prop documentation
- Usage examples generation
- Versioning and changelog
### v6.1 - Collaboration (In Planning)
**Estimated:** Q1 2025
Team development features:
- [ ] Real-time collaborative editing
- [ ] User presence indicators
- [ ] Comment system on code/designs
- [ ] Change history and versioning
- [ ] Branch/fork functionality
- [ ] Merge conflict resolution
- [ ] Team permissions and roles
**Technical Requirements:**
- WebSocket or WebRTC for real-time sync
- Operational transformation (OT) or CRDT
- User authentication and authorization
- Activity logging and audit trails
## Future Considerations (v7.0+)
### Advanced AI Features
- [ ] Conversational development interface
- [ ] AI pair programming mode
- [ ] Learning from user corrections
- [ ] Project-specific AI training
- [ ] Multi-model AI strategy (Claude, Gemini, etc.)
- [ ] AI code review agent
- [ ] Security vulnerability scanning with AI
### Platform Expansion
- [ ] Vue.js and Svelte support
- [ ] Angular application generation
- [ ] Mobile app generation (React Native)
- [ ] Desktop app generation (Electron)
- [ ] WordPress plugin generation
- [ ] Shopify theme development
### Advanced Integrations
- [ ] Database provider integration (PostgreSQL, MySQL, MongoDB)
- [ ] Cloud service integration (AWS, Azure, GCP)
- [ ] Third-party API integration designer
- [ ] Webhook configuration
- [ ] Message queue integration (RabbitMQ, Kafka)
- [ ] Caching layer configuration (Redis)
### Enterprise Features
- [ ] Self-hosted deployment option
- [ ] Single sign-on (SSO)
- [ ] Audit logging
- [ ] Compliance reporting (GDPR, SOC2)
- [ ] Custom AI model hosting
- [ ] Enterprise support and SLAs
### Community & Ecosystem
- [ ] Template marketplace
- [ ] Component marketplace
- [ ] Plugin system for custom designers
- [ ] Public project sharing
- [ ] Community themes and palettes
- [ ] Tutorial and learning platform
## Feature Prioritization
Features are prioritized based on:
1. **User Impact** - How many users benefit and how significantly
2. **Technical Feasibility** - Development complexity and dependencies
3. **Strategic Value** - Alignment with long-term product vision
4. **Resource Availability** - Team capacity and expertise
5. **Market Demand** - User requests and competitive landscape
## Feedback & Contributions
We welcome feedback on the roadmap! If you have feature requests or want to contribute to development:
1. Open an issue describing the feature request
2. Participate in roadmap discussions
3. Contribute code for planned features
4. Share use cases and requirements
## Versioning Strategy
- **Major versions (x.0)** - Significant new capabilities, potential breaking changes
- **Minor versions (x.y)** - New features, backwards compatible
- **Patch versions (x.y.z)** - Bug fixes and small improvements
## Release Cadence
- **Major releases:** Quarterly
- **Minor releases:** Monthly
- **Patch releases:** As needed
---
**Last Updated:** Current
**Next Review:** After v4.1 release
For more details on current features, see the [README](./README.md) and [PRD](./PRD.md).

View File

@@ -0,0 +1,31 @@
Thanks for helping make GitHub safe for everyone.
# Security
GitHub takes the security of our software products and services seriously, including all of the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub).
Even though [open source repositories are outside of the scope of our bug bounty program](https://bounty.github.com/index.html#scope) and therefore not eligible for bounty rewards, we will ensure that your finding gets passed along to the appropriate maintainers for remediation.
## Reporting Security Issues
If you believe you have found a security vulnerability in any GitHub-owned repository, please report it to us through coordinated disclosure.
**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
Instead, please send an email to opensource-security[@]github.com.
Please include as much of the information listed below as you can to help us better understand and resolve the issue:
* The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
## Policy
See [GitHub's Safe Harbor Policy](https://docs.github.com/en/site-policy/security-policies/github-bug-bounty-program-legal-safe-harbor#1-safe-harbor-terms)