# Project export: Socratic

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: The AI tutor that asks, not tells.
- Devpost: https://devpost.com/software/calhacks-ule0k1
- GitHub: https://github.com/tanvi-badadare/CalHacks
- Video: https://www.youtube.com/embed/1M3TbmQvOpU?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 3 GitHub contributor(s) — Bruhati Aarushi Kuchi (13 commits), Tanvi (8 commits), Rutu Aarabhi Kuchi (3 commits)

## Devpost submission (written by the team)

### Overview

Built With Frontend (Desktop Application) Electron.js - Cross-platform desktop framework for building the native application Node.js - JavaScript runtime for the main process HTML5/CSS3 - Modern web technologies for the chat interface JavaScript (ES6+) - Client-side logic and IPC communication IPC (Inter-Process Communication) - Electron's messaging system between main and renderer processes Backend (AI Service) Python 3.13 - Core backend language FastAPI - High-performance async web framework for RESTful API Uvicorn - Lightning-fast ASGI server Pydantic - Data validation and schema modeling AI & Machine Learning Anthropic Claude API - Claude 3 Haiku model for intelligent tutoring Claude 3 Haiku - Fast, cost-effective LLM optimized for conversational AI Custom Socratic System Prompt - Professional teaching methodology implementation JSON Structured Outputs - Typed responses with classification metadata Key Libraries & Dependencies anthropic (Python) - Official Anthropic SDK for Claude API integration python-dotenv - Environment variable management Chokidar - File system watching (disabled in current version) httpx - Async HTTP client for API calls Architecture & Design Patterns RESTful API - Standard HTTP endpoints for code analysis Event-Driven Architecture - EventEmitter pattern for service communication Session State Management - In-memory tracking of tutoring sessions Observer Pattern - For monitoring user interactions Singleton Pattern - Service instances in backend Development Tools npm - Package management for Node.js pip - Python package management Git - Version control Markdown - Documentation and LaTeX support Deployment & Infrastructure localhost:8000 - Backend API server CORS middleware - Cross-origin resource sharing for security JSON API - Standardized data exchange format Special Features Safe Console Wrapper - Custom EPIPE error prevention system Cursor-Style Sidebar - Modern chat interface design Real-time Classification - SYNTAX/LOGIC/CONCEPTUAL issue detection Adaptive Memory System - Tracks repeated mistakes and learning patterns Multi-Level Hint System - Progressive disclosure of guidance (3 levels) Technology Highlights Why Claude 3 Haiku? ⚡ Fast response times (~1-2 seconds) 💰 Cost-effective for educational applications 🧠 Excellent reasoning for Socratic questioning 📊 Structured outputs with JSON mode Why Electron? 🖥️ Cross-platform (macOS, Windows, Linux) 🎨 Modern UI with web technologies 🔧 Native integrations (system tray, notifications) 💬 Cursor-style sidebar overlay capabilities Why FastAPI? 🚀 Async/await for concurrent requests 📝 Auto-generated docs (Swagger/OpenAPI) ✅ Type safety with Pydantic ⚡ High performance (comparable to Node.js) API Endpoints Tech Stack Summary Total Tech Stack: 15+ technologies integrated into a cohesive learning platform

## README (from the GitHub repository)

# SocraticCode - AI Coding Tutor

SocraticCode is an AI-powered coding tutor that teaches programming through guided hints and step-by-step problem solving. Instead of giving you the answer directly, it provides hints at three different levels to help you learn and understand the solution process.

## Features

- **Three-Level Hint System**:
  - **Level 1**: Conceptual questions to guide your thinking
  - **Level 2**: Stepwise algorithmic instructions
  - **Level 3**: Detailed pseudocode with examples

- **Progressive Learning**: Hints unlock as you progress through levels
- **Session Tracking**: Your progress is saved as you work through problems
- **Multiple Programming Languages**: Support for JavaScript, Python, Java, C++, and more
- **Problem Categories**: Algorithms, Data Structures, Arrays, Strings, Math, etc.
- **Difficulty Levels**: Beginner, Intermediate, Advanced

## Tech Stack

- **Frontend**: React with TypeScript
- **Backend**: Node.js with Express
- **Database**: MongoDB with Mongoose
- **Styling**: CSS3 with modern design

## Prerequisites

- Node.js (v14 or higher)
- MongoDB (local installation or MongoDB Atlas)
- npm or yarn

## Installation

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd CalHacks
   ```

2. **Install dependencies**
   ```bash
   # Install root dependencies
   npm install
   
   # Install backend dependencies
   cd server
   npm install
   
   # Install frontend dependencies
   cd ../client
   npm install
   ```

3. **Set up environment variables**
   
   Create a `.env` file in the `server` directory:
   ```env
   PORT=4001
   MONGODB_URI=mongodb://localhost:27017/socraticcode
   NODE_ENV=development
   ```

4. **Start MongoDB**
   
   Make sure MongoDB is running on your system:
   ```bash
   # If using local MongoDB
   mongod
   
   # Or if using MongoDB Atlas, update the MONGODB_URI in .env
   ```

5. **Seed the database**
   ```bash
   cd server
   npm run seed
   ```

6. **Start the application**
   ```bash
   # From the root directory
   npm run dev
   
   # Or start them separately:
   # Terminal 1 - Backend
   cd server && npm run dev
   
   # Terminal 2 - Frontend
   cd client && npm start
   ```

## Usage

1. **Browse Problems**: Visit `http://localhost:3000` to see available problems
2. **Filter Problems**: Use the filter options to find problems by difficulty, language, or category
3. **Start Learning**: Click "Start Problem" to begin working on a problem
4. **Request Hints**: Use the hint buttons to get guided help:
   - Start with Level 1 for conceptual guidance
   - Progress to Level 2 for algorithmic steps
   - Use Level 3 for detailed pseudocode
5. **Write Code**: Use the code editor to implement your solution
6. **Submit Solution**: Submit your code when ready

## API Endpoints

### Problems
- `GET /api/problems` - Get all problems (with optional filters)
- `GET /api/problems/:id` - Get a specific problem
- `POST /api/problems` - Create a new problem (admin)

### Hints
- `GET /api/hints/:problemId/:level` - Get hint for specific level
- `GET /api/hints/:problemId` - Get all hints for a problem

### Sessions
- `POST /api/sessions` - Create a new session
- `GET /api/sessions/:sessionId` - Get session details
- `PUT /api/sessions/:sessionId` - Update session (record hints, attempts)

## Project Structure

```
CalHacks/
├── client/                 # React frontend
│   ├── src/
│   │   ├── components/     # React components
│   │   ├── services/      # API services
│   │   ├── types/         # TypeScript types
│   │   └── ...
├── server/                 # Node.js backend
│   ├── models/            # MongoDB models
│   ├── routes/            # API routes
│   ├── middleware/        # Express middleware
│   └── ...
└── package.json           # Root package.json
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

MIT License - see LICENSE file for details

## Future Enhancements

- [ ] Code execution and testing
- [ ] User authentication and profiles
- [ ] Progress tracking and analytics
- [ ] More programming languages
- [ ] Mobile app version
- [ ] Collaborative problem solving
- [ ] AI-powered hint generation


## Detected evidence (automated analysis)

Indexed codebase: 49 recognized source files, 324 KB.
- Anthropic (technology) — detected in the code
- FastAPI (technology) — detected in the code
- Google Gemini (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- CSS (language) — claimed on Devpost, not found in the code
- Java (language) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (56 of 56)

```
.gitignore
CHANGES_SUMMARY.md
CONVERSATIONAL_AI.md
FINAL_STATUS.md
GEMINI_INTEGRATION.md
IMPLEMENTATION_SUMMARY.md
INTEGRATION_COMPLETE.md
KAIZEN_TEACHING_METHOD.md
python-backend/.env.example
python-backend/.gitignore
python-backend/agents/__init__.py
python-backend/agents/tutor_agent.py
python-backend/example_client.py
python-backend/main.py
python-backend/models/__init__.py
python-backend/README.md
python-backend/requirements.txt
python-backend/run_agent.py
python-backend/services/__init__.py
python-backend/services/claude_service.py
python-backend/services/code_analyzer.py
python-backend/utils/__init__.py
python-backend/utils/helpers.py
QUICK_START.md
README.md
REAL_SCREEN_READING.md
SCREEN_READING_GUIDE.md
SMART_HINTS_IMPLEMENTATION.md
socraticcode-desktop/browser-extension/background.js
socraticcode-desktop/browser-extension/content.js
socraticcode-desktop/browser-extension/manifest.json
socraticcode-desktop/browser-extension/popup.html
socraticcode-desktop/browser-extension/popup.js
socraticcode-desktop/browser-extension/test.html
socraticcode-desktop/eng.traineddata
socraticcode-desktop/package.json
socraticcode-desktop/README.md
socraticcode-desktop/src/main.js
socraticcode-desktop/src/overlay/index.html
socraticcode-desktop/src/renderer/index.html
socraticcode-desktop/src/services/CodeAnalyzer.js
socraticcode-desktop/src/services/CoDeiAI.js
socraticcode-desktop/src/services/FileMonitor.js
socraticcode-desktop/src/services/HintSystem.js
socraticcode-desktop/src/services/KeystrokeMonitor.js
socraticcode-desktop/src/services/RAGHintService.js
socraticcode-desktop/src/services/ScreenOverlay.js
socraticcode-desktop/src/services/ScreenReader_ENHANCED.js
socraticcode-desktop/src/services/ScreenReader.js
socraticcode-desktop/src/services/SmartHintEngine.js
socraticcode-desktop/src/services/SocraticCodeAI.js
socraticcode-desktop/src/services/UniversalCoDeiService.js
socraticcode-desktop/test-electron.js
test-personality-hints.sh
test-screen-reading.sh
TESTING_PROGRESSIVE_HINTS.md
```

### Dependencies

- python-backend/requirements.txt: anthropic@==0.71.0, fastapi@==0.104.1, httpx@==0.25.2, pydantic@==2.5.0, python-dotenv@==1.0.0, uagents@==0.22.10, uvicorn@==0.24.0
- socraticcode-desktop/package.json: @google/generative-ai@^0.24.1, @types/node@^20.10.5, axios@^1.12.2, chokidar@^3.5.3, electron@^38.4.0, electron-builder@^24.9.1, openai@^4.104.0, tesseract.js@^5.1.1, typescript@^5.3.3

### Recent commits (newest first)

- Update Claude prompt for Socratic screen awareness
- Rebrand UI from CoDei to Socratic
- Integrate Claude API with ConceptMentor prompt - Remove Groq - Add Claude service with Socratic guidance
- Add 'show' command to display what CoDei sees on screen
- Fix sidebar and indicator visibility when switching apps
- Merge popup branch - resolved conflicts in popup files
- Merge remote-tracking branch 'origin/cleanup/remove-website-files'
- Merge remote-tracking branch 'origin/fix/remove-broken-keylogger'
- popup for windows
- changes to screen overlay
- Add screen recording permission requests for universal visibility
- Make indicator and sidebar visible on all workspaces and fullscreen apps
- Add collapse button to sidebar
- Add indicator dot with sidebar toggle and hide main window on monitoring
- Make sidebar solid and non-click-through
- Style sidebar like Cursor with fixed 400px width and modern UI
- Remove website files (client, server) and add browser extension files
- Fix EPIPE error and reduce hint emission frequency
- Add screen reader service for automatic screen content detection and hint generation
- Add persistent sidebar overlay (25% width) for displaying hints

## Key source files (fetched from GitHub, selected and truncated for size)

### QUICK_START.md

```markdown
# 🚀 Quick Start Guide - Progressive Hints System

## ✅ What's New

Your screen reading system now has:
- ✅ **Progressive hints** (one at a time, not all at once)
- ✅ **4 personality modes** (Mentor, Sarcastic, Fun, Grade-Level)
- ✅ **"Need Another Hint?" button** for user-controlled disclosure
- ✅ **No more crashes** (fixed EIO write errors)
- ✅ **Beautiful UI** with color-coded hint levels

## 🎯 Start in 3 Steps

### Step 1: Start RAG Service
```bash
cd /Users/tintuk/calhacks/CalHacks/rag-service
source venv/bin/activate
python app.py
```
✅ **Wait for**: `🚀 Starting RAG Hint Service on port 5001`

### Step 2: Start Desktop App
```bash
cd /Users/tintuk/calhacks/CalHacks/socraticcode-desktop
npm start
```

### Step 3: Use It!
1. **Select personality**: Mentor / Sarcastic / Fun / Grade-Level
2. **Click**: "Start Monitoring"
3. **Open**: VS Code, Cursor, or visit leetcode.com
4. **Wait**: 5-10 seconds
5. **See hints**: In the sidebar on the right!

## 🎭 What Each Personality Does

| Personality | Style | Example |
|-------------|-------|---------|
| 👨‍🏫 **Mentor** | Patient, encouraging | "What data structure helps track elements?" |
| 😏 **Sarcastic** | Witty, clever | "Brute force? If you have all day..." |
| 🎉 **Fun** | Energetic, emojis | "🚀 Hash maps are AWESOME! ⚡" |
| 🎓 **Grade-Level** | Academic, rigorous | "Consider O(n) amortized complexity..." |

## 💡 How Hints Work

### You'll See:

1. **Topic Header** appears first:
   ```
   🎯 Topic: ARRAYS
   Problem related to arrays
   ```

2. **Hint Level 1** (Subtle) shows automatically:
   ```
   👨‍🏫 Hint Level 1
   What approach comes to mind first?
   ```

3. **"Need Another Hint?" button** appears

4. **Click button** → Hint Level 2 (Moderate) reveals

5. **Click again** → Hint Level 3 (Direct guidance)

6. **Completion message**:
   ```
   ✨ You've seen all the hints!
   Try solving it yourself now. You got this! 💪
   ```

## 🎨 Visual Guide

### Hint Levels are Color-Coded:
- **Blue border**: Level 1 (subtle, general approach)
- **Orange border**: Level 2 (specific techniques)
- **Green border**: Level 3 (direct suggestions, no code)

## 🧪 Quick Test

Run this to verify everything works:
```bash
cd /Users/tintuk/calhacks/CalHacks
./test-personality-hints.sh
```

## 🔍 How to Know It's Working

### Terminal (RAG Service) shows:
```
📚 Generating hints for topic: arrays
👤 Personality: sarcastic, Level: 1
🤖 Generating hint level 1...
🤖 Generating hint level 2...
🤖 Generating hint level 3...
```

### Terminal (Desktop App) shows:
```
📷 Capturing screen...
✅ Screenshot captured, analyzing...
🎯 Coding content detected! Topic: arrays
```

### Sidebar (On Screen) shows:
- Topic header
- First hint automatically
- "Need Another Hint?" button
- Progressive hints as you click

## 🐛 Troubleshooting

### "No hints appearing"
- Check RAG service is running: `curl http://localhost:5001/health`
- Make sure you clicked "Start Monitoring"
- Open a coding tool (VS Code, LeetCode)
- Wait 5
[truncated — 604 more characters]
```

### INTEGRATION_COMPLETE.md

```markdown
# 🎉 Integration Complete: Claude + Enhanced Screen Reading

## ✅ What You Have Now

### 1. **Claude Backend** (from origin/main)
- **Location**: `python-backend/services/claude_service.py`
- **Model**: Claude 3 Haiku (`claude-3-haiku-20240307`)
- **Prompt**: ConceptMentor - ChatGPT-like with Socratic teaching
- **Features**:
  - Natural conversation
  - Socratic questioning
  - Concept-focused teaching
  - No direct solutions unless explicitly requested

### 2. **Enhanced Screen Reading** (your work)
- **Location**: `socraticcode-desktop/src/services/ScreenReader_ENHANCED.js`
- **Features**:
  - Real screen capture every 5 seconds
  - Gemini Vision for OCR and code detection
  - Detects LeetCode/HackerRank problems
  - Extracts user code, problem description, and approach
  - Fallback to Tesseract OCR if Gemini fails

### 3. **Smart Hint Engine** (your work)
- **Location**: `socraticcode-desktop/src/services/SmartHintEngine.js`
- **Features**:
  - Detects when user is stuck (long pauses, deletions, no progress)
  - 60-second cooldown between hints
  - Only shows hints when truly needed

### 4. **Progressive Hints UI** (your work)
- **Location**: `socraticcode-desktop/src/overlay/index.html`
- **Features**:
  - 3 hint levels (Gentle, Nudge, Direct)
  - "Need Another Hint?" button
  - Hints persist until problem changes
  - Chat integration

---

## 🚀 How to Run

### Full System (Claude + Screen Reading)
```bash
# Terminal 1: Start Claude backend
cd python-backend
export ANTHROPIC_API_KEY="your_claude_key"
python main.py

# Terminal 2: Start desktop app with Gemini
cd socraticcode-desktop
export GEMINI_API_KEY="AIzaSyA_QVmMY2X4V6GYL5UvQQ7MSIXTBodlO3A"
npm start
```

---

## 🔧 How It Works

```
┌─────────────────────────────────────────────────┐
│  1. Screen Reading                               │
│     - Captures your LeetCode screen every 5s    │
│     - Gemini Vision extracts code & problem     │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│  2. Smart Hint Engine                            │
│     - Detects if you're stuck                   │
│     - Waits 60s before next hint                │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│  3. Claude Backend                               │
│     - Generates Socratic hints                  │
│     - Uses ConceptMentor prompt                 │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│  4. Overlay UI                                   │
│     - Shows hints in sidebar                    │
│     - Progressive revelation (3 levels)         │
│     - Chat for follow-up questions              │
└─────────────────────────────────────────────────┘
```

---

## 📝 Key Files

| File | Purpose |
|------|---------|
| `python-backend/services/claude_service.py` | Clau
[truncated — 856 more characters]
```

### python-backend/requirements.txt

```
fastapi==0.104.1
uvicorn==0.24.0
python-dotenv==1.0.0
uagents==0.22.10
httpx==0.25.2
pydantic==2.5.0
anthropic==0.71.0


```

### socraticcode-desktop/package.json

```
{
  "name": "codei-desktop",
  "version": "1.0.0",
  "description": "Socratic - AI Coding Tutor Desktop Application",
  "main": "src/main.js",
  "scripts": {
    "start": "electron .",
    "dev": "electron . --dev",
    "build": "electron-builder",
    "build:mac": "electron-builder --mac",
    "build:win": "electron-builder --win",
    "build:linux": "electron-builder --linux"
  },
  "keywords": [
    "coding",
    "tutor",
    "ai",
    "education",
    "desktop"
  ],
  "author": "Tanvi",
  "license": "MIT",
  "devDependencies": {
    "electron": "^38.4.0",
    "electron-builder": "^24.9.1"
  },
  "dependencies": {
    "@google/generative-ai": "^0.24.1",
    "@types/node": "^20.10.5",
    "axios": "^1.12.2",
    "chokidar": "^3.5.3",
    "openai": "^4.104.0",
    "tesseract.js": "^5.1.1",
    "typescript": "^5.3.3"
  },
  "build": {
    "appId": "com.codei.desktop",
    "productName": "Socratic",
    "directories": {
      "output": "dist"
    },
    "files": [
      "src/**/*",
      "node_modules/**/*"
    ],
    "mac": {
      "category": "public.app-category.education"
    },
    "win": {
      "target": "nsis"
    },
    "linux": {
      "target": "AppImage"
    }
  }
}

```

### python-backend/main.py

```python
"""
FastAPI backend for CoDei - Socratic Coding Tutor
Uses Fetch.ai uAgents for autonomous agent processing
"""

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
from dotenv import load_dotenv
import os
import sys

# Load environment variables
load_dotenv()

# Add services directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from services.code_analyzer import CodeAnalyzer
from services.claude_service import ClaudeService

app = FastAPI(
    title="CoDei Backend",
    description="Socratic Coding Tutor Backend with uAgents",
    version="1.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, replace with specific origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize services
code_analyzer = CodeAnalyzer()
claude_service = ClaudeService()

# Note: In production, you would start the uAgent separately:
# uagent run agents.tutor_agent:tutor_agent

class CodeUpdate(BaseModel):
    code: str
    context: Optional[str] = None
    language: Optional[str] = "python"

class Response(BaseModel):
    question: Optional[str]
    analysis: dict
    needs_conceptual_help: bool

def _looks_like_code(text: str) -> bool:
    """Check if the input looks like code"""
    if not text or len(text.strip()) < 3:
        return False
    
    code_keywords = ['def ', 'function ', 'import ', 'class ', 'const ', 'let ', 'var ',
                     'print(', 'for(', 'while(', 'if(', 'return ', '=']
    
    has_code_keyword = any(keyword in text for keyword in code_keywords)
    has_operators = any(op in text for op in ['=', '<', '>', '+', '-', '*', '/'])
    has_parens = '(' in text and ')' in text
    has_brackets = ('[' in text and ']' in text) or ('{' in text and '}' in text)
    
    # If it has code keywords, definitely code
    if has_code_keyword:
        return True
    
    # If it has operators with parens/brackets, probably code
    if has_operators and (has_parens or has_brackets):
        return True
    
    return False

@app.get("/")
async def root():
    return {
        "message": "CoDei Backend - Socratic Coding Tutor",
        "status": "active",
        "version": "1.0.0"
    }

@app.post("/api/code_update", response_model=Response)
async def code_update(update: CodeUpdate):
    """
    Receive code update, analyze it, and return Socratic question if needed.
    """
    try:
        # Step 1: Let CodeMentor intelligently handle any input (code, questions, chat, etc.)
        # No hardcoding - CodeMentor will figure it out based on the sophisticated prompt
        
        needs_conceptual_help = False
        question = None
        
        # Try to analyze if it looks like code first (optional check)
        try:
            analysis = code_analyzer.analyze(update.code, update.language)
            needs_conceptual_help = analysis.get("has_conceptual_issue", False)
            issue_type = analysis.get("issue_type", "general")
        except:
            # If analysis fails, just send everything to CodeMentor
            analysis = {"has_errors": False, "errors": []}
            issue_type = "general"
        
        # Step 2: Send to Claude
        try:
            question = await claude_service.generate_socratic_question(
                code=update.code,
                issue_type=issue_type,
                context=update.context or ""
            )
        except Exception as e:
            print(f"Error calling Claude API: {e}")
            question = "I'm here to help you learn! What can I help you with today?"
        
        return Response(
            question=question,
            analysis=analysis,
            needs_conceptual_help=needs_conceptual_help
        )
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error processing code: {str(e)}")

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "services": {
            "code_analyzer": "active",
            "claude_service": claude_service.enabled and "active" or "disabled"
        }
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


```

### socraticcode-desktop/src/main.js

```javascript
const { app, BrowserWindow, ipcMain, Menu, Tray, nativeImage, systemPreferences } = require('electron');
const path = require('path');
const FileMonitor = require('./services/FileMonitor');
const KeystrokeMonitor = require('./services/KeystrokeMonitor');
const UniversalCoDeiService = require('./services/UniversalCoDeiService');
const ScreenOverlay = require('./services/ScreenOverlay');
const ScreenReader = require('./services/ScreenReader_ENHANCED');
const RAGHintService = require('./services/RAGHintService');
const SmartHintEngine = require('./services/SmartHintEngine');

// Handle EPIPE errors specifically to prevent crashes
process.on('uncaughtException', (error) => {
  if (error.code === 'EPIPE') {
    // Silently handle EPIPE errors
    return;
  }
  // Log other errors
  console.error('Uncaught exception:', error);
});

process.stdout.on('error', (error) => {
  if (error.code === 'EPIPE') {
    // Ignore EPIPE on stdout
    return;
  }
});

process.stderr.on('error', (error) => {
  if (error.code === 'EPIPE') {
    // Ignore EPIPE on stderr
    return;
  }
});

class SocraticApp {
  constructor() {
    this.mainWindow = null;
    this.tray = null;
    this.fileMonitor = null;
    this.keystrokeMonitor = null;
    this.universalService = null;
    this.screenOverlay = null;
    this.screenReader = null;
    this.ragHintService = null;
    this.isDev = process.argv.includes('--dev');
  }

  createWindow() {
    // Create a sleek, dynamic-sized window
    this.mainWindow = new BrowserWindow({
      width: 400,
      height: 500,
      minWidth: 350,
      minHeight: 400,
      maxWidth: 500,
      maxHeight: 600,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true
      },
      icon: path.join(__dirname, '../assets/icon.png'),
      show: true,
      titleBarStyle: 'hidden', // Clean, modern look
      resizable: true, // Allow resizing within limits
      minimizable: true,
      maximizable: false, // No fullscreen/maximize
      alwaysOnTop: false,
      skipTaskbar: false,
      center: true,
      fullscreen: false,
      fullscreenable: false, // No fullscreen capability
      movable: true, // Allow moving
      frame: true // Keep frame for better UX
    });

    // Load the app
    this.mainWindow.loadFile(path.join(__dirname, 'renderer/index.html'));

    // Show window when ready
    this.mainWindow.once('ready-to-show', () => {
      this.mainWindow.show();
      
      if (this.isDev) {
        this.mainWindow.webContents.openDevTools();
      }
    });

    // Handle window closed
    this.mainWindow.on('closed', () => {
      this.mainWindow = null;
    });

    // Don't auto-hide on blur - let user control when to hide
    // this.mainWindow.on('blur', () => {
    //   this.mainWindow.hide();
    // });

    this.mainWindow.on('close', (event) => {
      // Only hide to tray, don't actually quit unless explicitly requested
      event.preventDefault();
      this.mainWindow.hide();
    });
  }

  createTray() {
    // Create a simple, visible icon for macOS menu bar
    const iconData = Buffer.from(`
      <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg">
        <rect width="16" height="16" fill="#667eea"/>
        <text x="8" y="12" font-family="Arial" font-size="10" font-weight="bold" text-anchor="middle" fill="white">S</text>
      </svg>
    `);
    
    const trayIcon = nativeImage.createFromDataURL('data:image/svg+xml;base64,' + iconData.toString('base64'));
    this.tray = new Tray(trayIcon);
    this.updateTrayIcon(false);
    
        this.tray.setToolTip('Socratic - AI Coding Tutor');
    
    this.tray.on('click', () => {
      this.mainWindow.show();
    });
  }

  updateTrayIcon(isActive) {
    // Create simple colored square with letter S
    const color = isActive ? '#27ae60' : '#667eea'; // Green when active, blue when inactive
    
    const iconData = Buffer.from(`
      <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg">
        <rect width="16" height="16" fill="${color}"/>
        <text x="8" y="12" font-family="Arial" font-size="10" font-weight="bold" text-anchor="middle" fill="white">S</text>
      </svg>
    `);
    
    const trayIcon = nativeImage.createFromDataURL('data:image/svg+xml;base64,' + iconData.toString('base64'));
    this.tray.setImage(trayIcon);
    
    // Update context menu
        const contextMenu = Menu.buildFromTemplate([
          {
            label: 'Socratic',
            enabled: false
          },
          { type: 'separator' },
          {
            label: isActive ? 'Monitoring Active' : 'Monitoring Inactive',
            enabled: false
          },
          {
            label: 'Show Controls',
            click: () => {
              this.mainWindow.show();
            }
          },
          { type: 'separator' },
          {
            label: 'Quit Socratic',
            click: () => {
              app.isQuiting = true;
              app.quit();
            }
          }
        ]);

    this.tray.setContextMenu(contextMenu);
  }

  async initializeServices() {
    // Initialize RAG Hint Service
    this.ragHintService = new RAGHintService('http://127.0.0.1:5001');
    
    // Check RAG service connection
    const isConnected = await this.ragHintService.checkConnection();
    console.log(`🤖 RAG Hint Service: ${isConnected ? 'Connected ✅' : 'Disconnected ⚠️'}`);
    
    // Initialize Screen Overlay for visual hints
    this.screenOverlay = new ScreenOverlay();
    
    // Track current personality setting
    this.currentPersonality = 'mentor';
    this.currentHintLevel = 1;
    
    // Initialize Smart Hint Engine (detects when user is stuck)
    this.smartHintEngine = new SmartHintEngine();
    this.smartHintEngine.on('user-stuck', async (data) => {
      console.log('🆘 User appears stuck:', data.reason, '- Offering hint');
      
      // Generate a contextual hint
      try {
        const hints = await
[truncated — 18008 more characters]
```

### test-screen-reading.sh

```shell
#!/bin/bash

echo "🧪 Testing SocraticCode Screen Reading"
echo "======================================"
echo ""
echo "✅ Fixed: EIO write errors (app will no longer crash on console.log)"
echo ""

# Check if RAG service is running
echo "1️⃣ Checking RAG Service..."
if curl -s http://localhost:5001/health > /dev/null 2>&1; then
    echo "   ✅ RAG Service is running on port 5001"
else
    echo "   ❌ RAG Service is NOT running"
    echo "   💡 Start it with:"
    echo "      cd /Users/tintuk/calhacks/CalHacks/rag-service"
    echo "      source venv/bin/activate"
    echo "      python app.py"
    echo ""
fi

# Check if desktop app is running
echo ""
echo "2️⃣ Checking Desktop App..."
if pgrep -f "electron.*socraticcode-desktop" > /dev/null 2>&1; then
    echo "   ✅ Desktop app appears to be running"
else
    echo "   ⚠️  Desktop app may not be running"
    echo "   💡 Start it with:"
    echo "      cd /Users/tintuk/calhacks/CalHacks/socraticcode-desktop"
    echo "      npm start"
    echo ""
fi

echo ""
echo "3️⃣ What to Look For in Terminal:"
echo "   ================================"
echo "   In the terminal where you ran 'npm start', you should see:"
echo ""
echo "   📷 Capturing screen..."
echo "   ✅ Screenshot captured, analyzing..."
echo ""
echo "   If you have a coding tool open (VS Code, LeetCode, etc):"
echo "   🎯 Coding content detected! Topic: arrays"
echo ""
echo ""
echo "4️⃣ Testing Hint Generation:"
echo "   ========================="
echo "   Testing RAG service directly..."
echo ""

curl -X POST http://localhost:5001/api/hints/generate \
  -H "Content-Type: application/json" \
  -d '{
    "code": "def reverse_string(s):\n    return s[::-1]",
    "topic": "strings",
    "num_hints": 2
  }' 2>/dev/null | python3 -m json.tool 2>/dev/null

if [ $? -eq 0 ]; then
    echo ""
    echo "   ✅ RAG service is generating hints!"
else
    echo ""
    echo "   ❌ Could not generate hints"
fi

echo ""
echo "5️⃣ Visual Indicators:"
echo "   ==================="
echo "   When monitoring is active, you should see:"
echo "   • Green dot in the top-right corner of your screen"
echo "   • Sidebar on the right side (400px wide)"
echo "   • Hints appearing in the sidebar when coding detected"
echo ""
echo "6️⃣ To Trigger Detection:"
echo "   ======================"
echo "   • Open VS Code or Cursor"
echo "   • Visit leetcode.com in your browser"
echo "   • Open any window with 'code' in the title"
echo "   • Wait 5-10 seconds for the screen reader cycle"
echo ""
echo "Done! 🎯"





```

### test-personality-hints.sh

```shell
#!/bin/bash

echo "🎭 Testing Progressive Personality-Aware Hints System"
echo "======================================================"
echo ""

# Check if RAG service is running
echo "1️⃣  Checking RAG Service..."
if curl -s http://localhost:5001/health > /dev/null 2>&1; then
    echo "   ✅ RAG Service is running"
    
    # Test hint generation with different personalities
    echo ""
    echo "2️⃣  Testing Hint Generation..."
    echo ""
    
    personalities=("mentor" "sarcastic" "fun" "grade-level")
    
    for personality in "${personalities[@]}"; do
        echo "   Testing $personality personality:"
        
        response=$(curl -s -X POST http://localhost:5001/api/hints/generate \
          -H "Content-Type: application/json" \
          -d "{
            \"code\": \"def two_sum(nums, target):\\n    # TODO: find two numbers that add up to target\\n    pass\",
            \"topic\": \"arrays\",
            \"personality\": \"$personality\",
            \"hint_level\": 1,
            \"num_hints\": 3
          }")
        
        if echo "$response" | grep -q "success.*true"; then
            echo "      ✅ Generated hints successfully"
            
            # Show first hint
            first_hint=$(echo "$response" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data['progressive_hints'][0]['hint'] if data.get('progressive_hints') else 'N/A')" 2>/dev/null)
            if [ ! -z "$first_hint" ] && [ "$first_hint" != "N/A" ]; then
                echo "      💡 Level 1 Hint: \"${first_hint:0:80}...\""
            fi
        else
            echo "      ❌ Failed to generate hints"
        fi
        echo ""
    done
    
else
    echo "   ❌ RAG Service is NOT running"
    echo ""
    echo "   💡 Start it with:"
    echo "      cd /Users/tintuk/calhacks/CalHacks/rag-service"
    echo "      source venv/bin/activate"
    echo "      python app.py"
    echo ""
    exit 1
fi

echo "3️⃣  System Status:"
echo "   ================================"
echo ""
echo "   ✅ Personality-aware prompts: IMPLEMENTED"
echo "   ✅ Progressive hints (3 levels): IMPLEMENTED"
echo "   ✅ Next Hint button: IMPLEMENTED"
echo "   ✅ Sidebar UI with color coding: IMPLEMENTED"
echo "   ✅ Screen reading integration: IMPLEMENTED"
echo ""

echo "4️⃣  How to Test Manually:"
echo "   ================================"
echo ""
echo "   1. Start the desktop app:"
echo "      cd /Users/tintuk/calhacks/CalHacks/socraticcode-desktop"
echo "      npm start"
echo ""
echo "   2. Select a personality (Mentor/Sarcastic/Fun/Grade-Level)"
echo ""
echo "   3. Click 'Start Monitoring'"
echo ""
echo "   4. Open VS Code or visit leetcode.com"
echo ""
echo "   5. Wait 5-10 seconds for detection"
echo ""
echo "   6. Check sidebar for hints"
echo ""
echo "   7. Click 'Need Another Hint?' to see progressive hints"
echo ""

echo "5️⃣  Expected Behavior:"
echo "   ================================"
echo ""
echo "   📱 Sidebar shows:"
echo "      • Topic header (e.g., 'Topic: ARRAYS')"
echo "      • First hint (Level 1 - subtle)"
echo "      • 'Need Another Hint?' button"
echo ""
echo "   🖱️  Click button:"
echo "      • Level 2 hint appears (moderate guidance)"
echo "      • Button remains for Level 3"
echo ""
echo "   🖱️  Click again:"
echo "      • Level 3 hint appears (direct suggestions)"
echo "      • Completion message: 'You've seen all the hints!'"
echo ""

echo "6️⃣  Personality Differences:"
echo "   ================================"
echo ""
echo "   👨‍🏫 Mentor: Patient, encouraging, supportive"
echo "   😏 Sarcastic: Witty, clever, humorous (but helpful)"
echo "   🎉 Fun: Energetic, emoji-filled, enthusiastic"
echo "   🎓 Grade-Level: Rigorous, theory-focused, academic"
echo ""

echo "✨ System is ready for testing!"
echo ""
echo "📖 For detailed testing instructions, see:"
echo "   /Users/tintuk/calhacks/CalHacks/TESTING_PROGRESSIVE_HINTS.md"
echo ""


```

### socraticcode-desktop/test-electron.js

```javascript
const { app } = require('electron');
console.log('app object:', typeof app);
console.log('app.whenReady:', typeof app.whenReady);

if (app && app.whenReady) {
    console.log('✅ Electron app is working!');
    app.quit();
} else {
    console.log('❌ Electron app is undefined!');
    process.exit(1);
}


```

### python-backend/run_agent.py

```python
"""
Script to run the uAgent separately
Usage: python run_agent.py
"""

import sys
import os

# Add parent directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from agents.tutor_agent import tutor_agent

if __name__ == "__main__":
    print("Starting Tutor Agent (uAgent)...")
    print(f"Agent name: {tutor_agent.name}")
    print(f"Agent address: {tutor_agent.address}")
    print("\nAgent is running... Press Ctrl+C to stop")
    
    try:
        tutor_agent.run()
    except KeyboardInterrupt:
        print("\nAgent stopped by user")


```

[38 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]