# Scriba Demo - Project State Documentation

## Executive Summary

**Project Name:** Scriba Demo  
**Status:** Semi-functional Prototype  
**Last Updated:** April 2026  
**Purpose:** Interactive demo showcasing legacy-to-modern code migration workflow

---

## What Scriba Is

Scriba is a conceptual AI-powered platform for automated legacy code migration. The demo application showcases a complete user journey from project creation through deployment, with a focus on the banking/financial services domain (COBOL → Java migrations).

**Key Value Proposition:**
- Automated analysis of legacy codebases
- AI-driven code translation with business logic preservation
- Comprehensive verification and testing
- Enterprise-grade migration workflow

---

## Current Implementation Status

### ✅ Fully Functional (Real Persistence)

| Component | Status | Notes |
|-----------|--------|-------|
| **Database Layer** | ✅ Real | PostgreSQL with `pg`, connection pooling, persistent storage |
| **Authentication** | ✅ Real | Better Auth with email/password, session management |
| **User Management** | ✅ Real | User accounts with project isolation |
| **Project CRUD** | ✅ Real | Create, read, update, delete projects via API |
| **Step Progress Tracking** | ✅ Real | `maxReachedStep` persisted per project |
| **User Navigation State** | ✅ Real | Progress survives page refreshes |
| **API Routes** | ✅ Real | Next.js App Router handlers for all operations |
| **JSONB Support** | ✅ Real | Native JSON storage in PostgreSQL for team, tags, activity |

### ⚠️ Simulated (Mock Data & Actions)

| Component | Status | Notes |
|-----------|--------|-------|
| **Code Conversion** | ❌ Mock | COBOL → Java translation is simulated (setTimeout) |
| **Test Generation** | ❌ Mock | Unit/integration tests are static samples |
| **Verification Metrics** | ❌ Mock | All scores/percentages are hardcoded |
| **Repository Connection** | ❌ Mock | Git integration is simulated |
| **Deployment** | ❌ Mock | Export/deploy actions are UI-only |

---

## Architecture Overview

### Frontend Stack
- **Framework:** Next.js 14 (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS + custom glass morphism design system
- **Animations:** Framer Motion
- **Icons:** Lucide React
- **Code Highlighting:** react-syntax-highlighter

### Backend Stack
- **Runtime:** Node.js
- **Database:** PostgreSQL (production-grade relational database)
- **API:** Next.js API Routes (REST)
- **ORM:** Drizzle ORM with TypeScript-first schema definition
- **Authentication:** Better Auth with email/password and session management

### Data Flow

```
User Action → Component → API Client → API Route → PostgreSQL → Response
                ↓                                            ↓
            State Update ← Response ← JSON Parsing ← Query Result
```

---

## File Structure

```
scriba-demo/
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   └── projects/
│   │   │       ├── route.ts              # GET (list), POST (create)
│   │   │       ├── [id]/
│   │   │       │   └── route.ts          # GET, PUT, DELETE single project
│   │   │       └── [id]/
│   │   │           └── step/
│   │   │               └── route.ts      # GET, POST step progress
│   │   ├── page.tsx                       # Entry point (ScribaAppNew)
│   │   ├── layout.tsx                     # Root layout
│   │   └── globals.css                    # Global styles
│   ├── components/
│   │   ├── ScribaAppNew.tsx              # Main app component
│   │   ├── SidebarNew.tsx                # Navigation sidebar
│   │   ├── TopBar.tsx                    # Header
│   │   ├── GlobalDashboard.tsx           # Landing page
│   │   ├── ProjectsHub.tsx               # Project list
│   │   ├── NewProjectWizardExpanded.tsx  # Project creation wizard
│   │   ├── ProjectDashboard.tsx          # Project overview
│   │   ├── ProjectStepTracker.tsx        # Progress indicator
│   │   ├── Repository.tsx                # Git connection (mock)
│   │   ├── PreAnalysisDashboard.tsx      # Code analysis display
│   │   ├── MigrationFlow.tsx             # Conversion pipeline (simulated)
│   │   ├── CodeComparison.tsx            # Side-by-side diff view
│   │   ├── VerificationDashboard.tsx      # QA metrics display
│   │   ├── Validation.tsx                # Validation step
│   │   ├── Artifacts.tsx                 # Generated docs/tests
│   │   ├── Export.tsx                    # Download/deploy
│   │   └── Settings.tsx                  # Settings page
│   ├── lib/
│   │   ├── db.ts                         # Drizzle ORM connection & helpers
│   │   ├── schema.ts                     # Drizzle schema definitions
│   │   ├── auth.ts                       # Better Auth configuration
│   │   ├── api.ts                        # API client functions
│   │   └── seed.ts                       # Database initialization
│   ├── components/
│   │   ├── Auth.tsx                      # Login/Signup component
│   │   ├── ScribaAppNew.tsx              # Main app component
│   │   ├── SidebarNew.tsx                # Navigation sidebar
│   │   ├── TopBar.tsx                    # Header
│   │   ├── GlobalDashboard.tsx           # Landing page
│   │   ├── ProjectsHub.tsx               # Project list
│   │   ├── NewProjectWizardExpanded.tsx  # Project creation wizard
│   │   ├── ProjectDashboard.tsx          # Project overview
│   │   ├── ProjectStepTracker.tsx        # Progress indicator
│   │   ├── Repository.tsx                # Git connection (mock)
│   │   ├── PreAnalysisDashboard.tsx      # Code analysis display
│   │   ├── MigrationFlow.tsx             # Conversion pipeline (simulated)
│   │   ├── CodeComparison.tsx            # Side-by-side diff view
│   │   ├── VerificationDashboard.tsx      # QA metrics display
│   │   ├── Validation.tsx                # Validation step
│   │   ├── Artifacts.tsx                 # Generated docs/tests
│   │   ├── Export.tsx                    # Download/deploy
│   │   └── Settings.tsx                  # Settings page
│   └── data/
│       ├── projectsData.ts               # Project type definitions
│       └── mockData.ts                   # Mock data (code samples, metrics)
├── drizzle.config.ts                     # Drizzle ORM configuration
├── .env                                  # PostgreSQL connection config
├── package.json
├── tsconfig.json
└── next.config.ts
```

---

## User Journey Flow

### 1. Landing (Global Dashboard)
- View project statistics (total projects, converted LOC, accuracy)
- Browse existing projects
- Create new project via CTA

### 2. Project Creation (NewProjectWizardExpanded)
- **Step 1 - Info:** Name, domain, priority, deadline
- **Step 2 - Source:** Select legacy language (COBOL, PL/I, RPG...)
- **Step 3 - Target:** Select target language (Java, C#, Python...)
- **Step 4 - Repository:** Connect Git repo (simulated)
- **Step 5 - Team:** Add team members
- **Step 6 - Review:** Confirm and create

**Real Action:** Project persisted to SQLite database

### 3. Project Overview (ProjectDashboard)
- View project status and progress
- Navigate to next step
- **Enhanced:** If `maxReachedStep >= 2`, shows analysis data (47 files, 12.3 complexity)

### 4. Repository Ingestion (Repository)
- Connect GitHub/GitLab/Bitbucket
- Analyze repository structure
- **Enhanced:** Shows explicit "Analysis Complete" panel with metrics
- CTA button to proceed (no auto-redirect)

### 5. Pre-Analysis (PreAnalysisDashboard)
- View code complexity metrics
- Dependency graph visualization
- Risk assessment
- Language breakdown

**Data Consistency:** 47 files, 12.3 avg complexity (aligned with Repository)

### 6. Migration Flow (MigrationFlow)
- **Simplified:** Linear flow only (removed Pause/Resume/Rollback)
- 4-phase pipeline: Discovery → AI Analysis → Conversion → Validation
- Real-time log simulation
- Progress tracking

**Simulated:** All conversion steps are `setTimeout` based

### 7. Code Comparison (CodeComparison)
- Side-by-side COBOL → Java view
- Confidence heatmap
- Business rules extraction

**Mock Data:** Realistic COBOL snippets (PERFORM, EVALUATE, MOVE, COMP-3) mapped to idiomatic Java

### 8. Verification (VerificationDashboard)
- Quality metrics (98.5% overall score)
- Functional parity, security, performance
- Test coverage
- **CTA:** Navigate to Artifacts

### 9. Artifacts (Artifacts)
- Generated unit tests (Java JUnit samples)
- Integration tests
- API documentation
- Architecture docs
- **CTA:** Navigate to Export

### 10. Export (Export)
- Download converted project
- Push to Git (simulated)
- Deploy to staging (simulated)

---

## Database Schema

### User Table (Drizzle Schema)
```typescript
export const users = pgTable('user', {
  id: text('id').primaryKey(),
  email: text('email').notNull().unique(),
  emailVerified: boolean('email_verified').default(false),
  name: text('name'),
  image: text('image'),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
});
```

### Session Table (Drizzle Schema)
```typescript
export const sessions = pgTable('session', {
  id: text('id').primaryKey(),
  userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  expiresAt: timestamp('expires_at').notNull(),
  ipAddress: text('ip_address'),
  userAgent: text('user_agent'),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
});
```

### Projects Table (Drizzle Schema)
```typescript
export const projects = pgTable('projects', {
  id: text('id').primaryKey(),
  name: text('name').notNull(),
  description: text('description'),
  status: text('status').default('draft'),
  repoUrl: text('repo_url'),
  sourceLanguage: text('source_language'),
  targetLanguage: text('target_language'),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
  completedAt: timestamp('completed_at'),
  totalFiles: integer('total_files').default(0),
  totalLines: integer('total_lines').default(0),
  convertedFiles: integer('converted_files').default(0),
  accuracy: real('accuracy').default(0),
  testCoverage: real('test_coverage').default(0),
  riskScore: real('risk_score').default(0),
  estimatedTime: text('estimated_time'),
  elapsedTime: text('elapsed_time'),
  team: jsonb('team').$type<any[]>().default([]),
  tags: jsonb('tags').$type<string[]>().default([]),
  activity: jsonb('activity').$type<any[]>().default([]),
  maxReachedStep: integer('max_reached_step').default(0),
  currentStep: integer('current_step').default(0),
  userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }),
});
```

### Project Steps Table (Drizzle Schema)
```typescript
export const projectSteps = pgTable('project_steps', {
  id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
  projectId: text('project_id').notNull().references(() => projects.id, { onDelete: 'cascade' }),
  stepNumber: integer('step_number').notNull(),
  stepName: text('step_name').notNull(),
  status: text('status').default('pending'),
  startedAt: timestamp('started_at'),
  completedAt: timestamp('completed_at'),
  metadata: jsonb('metadata').$type<any>().default({}),
});
```

---

## API Endpoints

### Authentication Endpoints
- `POST /api/auth/sign-in/email-password` - Email/password sign in
- `POST /api/auth/sign-up/email-password` - Email/password sign up
- `POST /api/auth/sign-out` - Sign out
- `GET /api/auth/session` - Get current session

### `GET /api/projects`
- Returns all projects for authenticated user
- Requires valid session
- Auto-seeds database if empty

### `POST /api/projects`
- Creates new project
- Body: `{ id, name, description, sourceLanguage, targetLanguage, tags, team }`

### `GET /api/projects/[id]`
- Returns single project by ID

### `PUT /api/projects/[id]`
- Updates project (status, activity, etc.)

### `DELETE /api/projects/[id]`
- Deletes project and associated steps

### `GET /api/projects/[id]/step`
- Returns step progress for project

### `POST /api/projects/[id]/step`
- Records step completion
- Body: `{ stepNumber, stepName }`

---

## Data Consistency (Recent Improvements)

All mock data now uses consistent metrics:

| Metric | Value | Where Used |
|--------|-------|------------|
| Total Files | 47 | Repository, Pre-Analysis, Project Overview |
| COBOL Files | 31 | Pre-Analysis language breakdown |
| Lines of Code | 12,480 | Repository, Pre-Analysis |
| Avg Complexity | 12.3 | Repository, Pre-Analysis, Project Overview |
| Max Complexity | 45 | Pre-Analysis |
| High Risk Files | 3 | Pre-Analysis |

This ensures the "story" told across the application is coherent - users see the same numbers throughout the journey.

---

## Known Limitations

### Technical
1. **No Real Code Translation:** The core value proposition (AI code conversion) is not implemented
2. **No Git Integration:** Repository connection is purely UI simulation
3. **No Real Testing:** All test generation is static mock data
4. **Single User:** No authentication or multi-user support
5. **No File Upload:** Cannot upload actual COBOL files for analysis

### UX/Design
1. **Linear Flow Only:** Removed Pause/Resume/Rollback for simplicity
2. **No Undo:** Cannot undo step progression
3. **Limited Error Handling:** Most error cases are not properly handled
4. **No Validation:** Form inputs have minimal validation

---

## Recent Improvements (April 2026)

1. **Repository → Pre-Analysis UX**
   - Removed automatic 2.5s redirect
   - Added explicit "Analysis Complete" panel with metrics
   - CTA button for user control

2. **Migration Flow Simplification**
   - Removed Pause/Resume/Rollback controls
   - Linear flow only with clear status messaging
   - Reduced cognitive load for demo viewers

3. **Project Overview Enhancement**
   - Now shows analysis data when `maxReachedStep >= 2`
   - No longer appears "empty" for projects with connected repos
   - Shows "Analysis Complete" state instead of blank draft

4. **Data Consistency**
   - Aligned all metrics across components (47 files, 12.3 complexity)
   - Ensures coherent storytelling across user journey

5. **Code Cleanup**
   - Removed duplicate/obsolete components (Sidebar, Dashboard, NewProjectWizard, ScribaApp, Pipeline)
   - Fixed broken imports (AccountDashboard in Artifacts)
   - TypeScript compilation passes without errors

---

## Technical Debt

1. **Component Duplication:** Some components may have overlapping responsibilities
2. **Type Safety:** Some `any` types remain in API response handling
3. **Error Handling:** Minimal try-catch blocks throughout
4. **Testing:** No unit tests or integration tests
5. **Documentation:** Limited inline code comments

---

## Next Steps (Roadmap)

### Phase 1: Core Functionality (Real Implementation)
1. Integrate actual LLM for code translation (Claude/GPT)
2. Implement real file parsing for COBOL/PL/I
3. Connect to actual Git repositories
4. Generate real unit tests based on code analysis

### Phase 2: Enterprise Features
1. Multi-user authentication
2. Project collaboration
3. Role-based access control
4. Audit logging

### Phase 3: Advanced Capabilities
1. Incremental migration support
2. Rollback mechanisms
3. A/B testing of translations
4. Custom rule engines

---

## Deployment Notes

### Development
```bash
npm install
npm run dev
```
Runs on http://localhost:3000

### Database
- PostgreSQL connection configured via `.env` file
- Requires running PostgreSQL server (default: localhost:5432)
- Auto-creates tables on first run
- Auto-seeds with sample project on first API call
- No migration system (manual schema changes)

### Environment Variables
```env
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=scriba
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
```

### Default User
The application auto-seeds a default user on first run:
- Email: `demo@scriba.ai`
- Password: Set via sign-up (not pre-configured for security)
- Use this account to test the application

### Production Considerations
- PostgreSQL is production-ready and suitable for high-concurrency
- Use managed PostgreSQL (AWS RDS, Google Cloud SQL, Azure Database) for production
- Configure connection pooling based on expected load
- File uploads need proper storage (S3, etc.)
- LLM API calls need rate limiting and cost management

---

## Conclusion

Scriba Demo is a **semi-functional prototype** with:
- ✅ **Real persistence layer** (PostgreSQL with connection pooling)
- ✅ **Authentication system** (Better Auth with email/password, session management)
- ✅ **User management** (User accounts with project isolation)
- ✅ **Real state management** (progress tracking)
- ✅ **Coherent mock data** (consistent metrics)
- ✅ **Polished UX** (smooth animations, clear feedback)
- ❌ **Simulated core value** (AI translation is fake)

The application successfully demonstrates the user journey and workflow for legacy code migration, making it an effective sales/demo tool. The data consistency improvements ensure the "illusion" of a working system remains intact throughout the user experience.

**Status:** Ready for demos and stakeholder presentations. Not production-ready (core AI features are simulated).
