AI Engineer Mastery Terminal — RAG, embeddings, LLMs, agents, production AI. Next.js 15 + TypeScript + Prisma + Gemini 3.1 Pro Preview.
0
stars
0
commits
TypeScript
primary language
Jun 2, 2026
updated
An engineering-terminal learning platform for senior AI engineers. Six modules · forty-eight lessons · interview simulator · AI-graded code labs.
Live demo · Features · Architecture · Quick start · API surface · Security
Most AI-engineering content stops at "what is RAG". NeuralPath goes the other way: production-grade trade-offs first, code labs that ask you to implement, an interview simulator that scores you on correctness, depth, and clarity, and an in-browser Python runtime so you actually run the code you write.
Built as a personal mastery tool for top-tier AI engineer interviews while working on production AI systems at IBM. Single-user, local-first, deployable to a free Vercel + Neon stack in under three minutes.
The aesthetic is intentional — deep charcoal, electric cyan, terminal-grid backgrounds. Bloomberg meets sci-fi mission control, not another purple-gradient AI dashboard.
| 48 lessons across 6 modules | RAG (naïve → CRAG → eval), embeddings (with tokenization + transformer forward-pass internals), LLM models (transformer architecture + inference internals), agents, production AI (with HNSW internals), enterprise patterns. Each lesson: theory body, animated diagram, decision card, interview gotchas, scored quiz. |
| Three-mode hands-on labs | Walkthrough reveals code section by section with key-points and "what to notice" callouts. Practice gives you starter-code stubs and AI-graded verification. Experiment is a free Monaco editor with a Gemini code-explainer. Optional Pyodide Web Worker actually runs your Python in the browser. |
| Interview simulator | Conceptual / system-design / coding / behavioral modes × three difficulties × three company types. Each answer scored on correctness, depth, and clarity, with a written critique and ideal answer. Sessions persist; history feeds the readiness score. |
| AI tutor chat | Streaming responses, lesson-aware context, persistent history. |
| Animated SVG diagrams | RAG pipeline, embedding space, chunking comparison, model decision tree, agent loop, LangGraph state machine, hybrid-search RRF, RAGAS eval radar. |
| Concept glossary | ~130 terms with high/medium/low frequency badges, lesson cross-links, and on-demand Gemini "Simplify" explanations. |
| Progress telemetry | Recharts module-mastery bar chart, score-trajectory line chart with 5-session moving average, quiz-score scatter, recent-sessions log. |
| Layer | Choice | Why |
|---|---|---|
| Framework | Next.js 15 App Router | RSC + streaming for the tutor; Node runtime for API routes; built-in middleware for CSRF + rate limit |
| Language | TypeScript strict mode | Type safety from prompt schemas to UI |
| Styling | Tailwind CSS 3.4 | Custom dark engineering-terminal tokens |
| Motion | Framer Motion 11 | Page transitions, diagram animations, panel reveals |
| Editor | Monaco (@monaco-editor/react) | Same editor as VS Code; lazy-loaded |
| Python runtime | Pyodide 0.26 | Real CPython + NumPy in a Web Worker |
| Charts | Recharts | Dark-themed analytics |
| ORM / DB | Prisma 5 + Postgres (Neon) | Single schema swaps to SQLite for local dev |
| LLM | @google/generative-ai · gemini-3.1-pro-preview | Server-side only — key never reaches the browser |
| Validation | Zod | Per-route request schemas + env validation |
| Markdown | react-markdown + remark-gfm | No dangerouslySetInnerHTML anywhere |
┌────────────────────────────────────────────────────────────────┐
│ Browser │
│ • App Router pages (RSC) — dashboard, lessons, glossary, │
│ progress, interview, tutor, playground │
│ • Client islands — Monaco, Recharts, Framer Motion, streaming │
│ chat, Pyodide Web Worker │
└──────────────────────────┬─────────────────────────────────────┘
│ fetch (same-origin, rate-limited)
┌──────────────────────────▼─────────────────────────────────────┐
│ middleware.ts │
│ • per-IP token-bucket rate limit (120 req/min) │
│ • same-origin enforcement on POST/PUT/PATCH/DELETE │
└──────────────────────────┬─────────────────────────────────────┘
│
┌──────────────────────────▼─────────────────────────────────────┐
│ Next.js 15 — Node runtime API routes │
│ │
│ /api/health env + db probe │
│ /api/chat streaming Gemini tutor │
│ /api/interview/* session, generate, evaluate, log │
│ /api/explain code walkthrough on demand │
│ /api/walkthrough lab walkthrough generation │
│ /api/verify AI-graded lab task verification │
│ /api/simplify ELI-junior helper │
│ /api/harder escalate interview question │
│ /api/progress lesson progress + readiness │
│ /api/note per-lesson notes │
│ │
│ Each route: │
│ • validates input via Zod (lib/validation.ts) │
│ • wraps Gemini calls in retry-with-backoff (lib/retry.ts) │
│ • emits structured JSON logs (lib/logger.ts) │
└──────────┬─────────────────────────────────────────┬───────────┘
│ │
┌───────▼─────────┐ ┌───────▼─────────┐
│ Prisma · Neon │ │ Gemini API │
│ Postgres │ │ 3.1 Pro │
│ │ │ preview │
│ Users │ │ │
│ LessonProgress │ │ Server-side │
│ InterviewSession │ only — key │
│ InterviewQuestion │ never reaches │
│ CodeSubmission │ │ the browser │
│ Note · Badge │ └─────────────────┘
│ ChatMessage │
└─────────────────┘
git clone git@github.com:mdSHash/NueralPath.git
cd NueralPath
# 1. install
npm install --legacy-peer-deps
# 2. configure
cp .env.example .env
# then edit .env and set GEMINI_API_KEY + DATABASE_URL
# 3. database
npm run db:push # creates the schema in your Postgres
npm run db:seed # creates the default user
# 4. dev server
npm run dev
Open http://localhost:3000.
For local development without Postgres, flip provider = "sqlite" in prisma/schema.prisma and use DATABASE_URL=file:./dev.db.
Cloning to a fresh stack takes about three minutes:
mdSHash/NueralPath in the Vercel dashboard).GEMINI_API_KEY — from Google AI StudioDATABASE_URL — your Neon pooled URLnpm run vercel-build, which regenerates the Prisma client, pushes the schema, and builds Next.js — the database is initialised automatically.<your-url>/api/health to verify.| # | Module | Focus | Lessons |
|---|---|---|---|
| 1 | RAG | Naive → Advanced → Modular → Agentic → GraphRAG → Multimodal → CRAG → Eval | 10 |
| 2 | Embeddings | Models, chunking, vector DBs, hybrid search, multilingual, tokenization, encoder forward pass | 9 |
| 3 | LLM Models | Selection, OS vs proprietary, watsonx, routing, transformer architecture, inference internals | 10 |
| 4 | Agents & Orchestration | ReAct, LangGraph, multi-agent, tool design, memory, eval | 6 |
| 5 | Production AI | Observability, evals, guardrails, latency, cost, CI/CD, HNSW internals | 8 |
| 6 | Enterprise / IBM | Multi-tenant RAG, MQ integration, Azure OpenAI, responsible AI, ROI | 5 |
Each lesson includes: theory body (Markdown) · animated SVG diagram (where applicable) · key takeaways · decision card (when-to-use / not / trade-offs) · interview gotchas · scored quiz · optional code lab.
app/
page.tsx dashboard
learn/ curriculum index + lesson viewer
playground/ standalone Monaco labs
interview/ interview simulator
chat/ AI tutor
glossary/ searchable term dictionary
progress/ charts + recent sessions
api/ 12 endpoints — Gemini + persistence + health
components/
ui/ design-system primitives
layout/ sidebar, topbar shell
dashboard/ hero, learning map, readiness, next lesson
lesson/
LessonClient.tsx viewer shell
KeyTakeaways · DecisionCard · Gotchas · Quiz · DiagramSlot
lab/
LabTabs.tsx walkthrough / practice / experiment switch
WalkthroughLab.tsx sections with reveal pacing
PracticeLab.tsx editor + verify + reference solution
ExperimentLab.tsx free editor + AI explainer
PyodideRunner.tsx Web-Worker Python runtime panel
interview/ setup, runner, summary
diagrams/ eight animated SVG concept diagrams
hooks/
usePyodide.ts worker lifecycle + run helper
lib/
curriculum/ six module files + glossary + interview seed
gemini.ts server-only SDK wrapper with retries
env.ts Zod-validated process.env
validation.ts per-route + lab request schemas
logger.ts structured JSON logger
retry.ts exponential-backoff helper
db.ts Prisma client singleton
public/
pyodide-worker.js Web Worker that hosts Pyodide
prisma/
schema.prisma Postgres schema
seed.ts default user + starter progress
middleware.ts rate limit + same-origin enforcement
next.config.ts security headers + CSP
All routes live at /api/*, run on the Node runtime, validate request bodies with Zod, and emit structured logs on failure.
| Method · Route | Body / params | Returns |
|---|---|---|
GET /api/health | — | { status, model, db, time } |
POST /api/chat | { message, moduleId?, lessonId?, history? } | streamed text/plain (Gemini tokens) |
GET /api/chat | — | { messages[] } recent tutor history |
POST /api/interview/session | { mode, companyType, role, difficulty, module? } | { sessionId } |
GET /api/interview/session | — | { sessions[] } |
POST /api/interview/generate | { mode, companyType, role, difficulty, module?, count? } | { questions[], source } |
POST /api/interview/evaluate | { question, userAnswer, role, difficulty, mode } | { scoreCorrectness, scoreDepth, scoreClarity, feedback, idealAnswer, missingConcepts[] } |
POST /api/interview/question | full per-question record | { id } |
POST /api/explain | { code, language? } | { explanation } |
POST /api/walkthrough | { labTitle, language, starterCode, expectedConcepts? } | { sections[] } |
POST /api/verify | { taskPrompt, taskDescription, language, userCode, referenceSolution? } | { passed, score, feedback, hints[] } |
POST /api/simplify | { concept } | { explanation } |
POST /api/harder | { question, mode? } | { question } |
GET /api/progress | — | aggregate readiness telemetry |
POST /api/progress | { moduleId, lessonId, status?, quizScore?, addTime? } | updated LessonProgress row |
GET /api/note?moduleId&lessonId | — | { notes[] } |
POST /api/note | { moduleId, lessonId, body } | { note } |
DELETE /api/note | { id } | { ok } |
Mutating routes require Origin === Host. Cross-origin → 403. Rate-limited at 120 req/min per IP.
| Name | Required | Default | Purpose |
|---|---|---|---|
GEMINI_API_KEY | yes | — | Server-side Google Generative AI key. Never sent to the browser. |
GEMINI_MODEL | no | gemini-3.1-pro-preview | Override the model name. |
DATABASE_URL | yes | — | Prisma datasource. Postgres connection string (Neon, Supabase, Vercel Postgres). For SQLite dev, set provider = "sqlite" in prisma/schema.prisma and use file:./dev.db. |
NODE_ENV | no | development | production enables HSTS. |
.env is gitignored. Use .env.example as the template and never commit a real key.
The app ships the controls a public-facing Next.js app should have, even though it's designed for single-user use.
| Layer | Control |
|---|---|
| Network | TLS-only via Vercel; HSTS in production builds (Strict-Transport-Security: max-age=63072000; includeSubDomains; preload) |
| Browser | Strict CSP (default-src 'self'; Gemini connect-src restricted), frame-ancestors 'none', X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Resource-Policy: same-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), X-Powered-By removed |
| Edge | middleware.ts enforces same-origin on every mutating /api/* request and applies a per-IP token bucket (120 req/min) |
| App | Zod request-body validation on every API route; Zod-validated process.env at startup; exponential-backoff retry around every Gemini call; structured JSON logging |
| Data | Prisma parameterised queries throughout; no raw SQL; react-markdown + remark-gfm everywhere — no dangerouslySetInnerHTML |
| Secrets | Gemini SDK imported only inside app/api/** and lib/gemini.ts; no NEXT_PUBLIC_* keys; .env gitignored |
| Runtime isolation | Pyodide runs inside a Web Worker, sandboxed away from the main thread |
npm audit is clean against direct dependencies. Next.js is pinned to 15.5.19+ which patches the critical RCE in the React Flight protocol (GHSA-9qr9-h5gf-34mp) and the middleware authorization-bypass (GHSA-f82v-jwr5-mffw) that affected earlier 15.x.
user_default is auto-created. To go multi-tenant: add NextAuth, key Prisma queries on session.user.id, tighten the CSRF check.| Script | What it does |
|---|---|
npm run dev | Next.js dev server on :3000 |
npm run build | Production build (no DB migration — for local builds) |
npm run vercel-build | What Vercel runs: prisma generate && prisma db push --accept-data-loss && next build |
npm run start | Start the production build |
npm run lint | ESLint via next lint |
npm run db:push | Push the Prisma schema to your DB |
npm run db:generate | Regenerate the Prisma client |
npm run db:seed | Seed the default user + starter progress |
Could not resolve dependency on npm install. Some peers want React 19. Rerun with npm install --legacy-peer-deps.
/api/health returns db: "fail". Prisma can't reach your DB. Check DATABASE_URL. For Neon, use the pooled connection string (the URL with -pooler in the host).
Chat / interview / explain returns 502. Either GEMINI_API_KEY is missing or the model returned an error. Check the dev-server console — lib/logger.ts emits a structured line with the failing route.
Monaco fails to load. Loaded via next/dynamic with ssr: false. Ensure JavaScript is enabled and the CSP shipped here isn't being overridden by your platform.
Pyodide takes 10–20 s to start. Expected on first use — it downloads ~10 MB from cdn.jsdelivr.net and initialises a Web Worker. Subsequent runs are instant.
429 rate limit exceeded. You hit the 120 req/min cap. Wait 30 seconds (the Retry-After header tells you exactly) or raise RATE_LIMIT_PER_MIN in middleware.ts.
403 cross-origin request blocked. Mutating requests must be same-origin. If you legitimately need a different origin during dev, allow it in middleware.ts's sameOrigin check.
softmax(QK^T/√d_head)V from first principles, multi-head, GQA, FFN/SwiGLU, RoPE, RMSNorm, residual stream framing, KV cache memory math.M/ef_construction/ef_search knobs, IVF-PQ contrast, ~50-line HNSW-from-scratch lab.Built by Mostafa Ayman (@mdSHash).
MIT — adapt freely.
TypeScript
99.1%
AI Engineer Mastery Terminal — RAG, embeddings, LLMs, agents, production AI. Next.js 15 + TypeScript + Prisma + Gemini 3.1 Pro Preview.
0
stars
0
commits
TypeScript
primary language
Jun 2, 2026
updated
An engineering-terminal learning platform for senior AI engineers. Six modules · forty-eight lessons · interview simulator · AI-graded code labs.
Live demo · Features · Architecture · Quick start · API surface · Security
Most AI-engineering content stops at "what is RAG". NeuralPath goes the other way: production-grade trade-offs first, code labs that ask you to implement, an interview simulator that scores you on correctness, depth, and clarity, and an in-browser Python runtime so you actually run the code you write.
Built as a personal mastery tool for top-tier AI engineer interviews while working on production AI systems at IBM. Single-user, local-first, deployable to a free Vercel + Neon stack in under three minutes.
The aesthetic is intentional — deep charcoal, electric cyan, terminal-grid backgrounds. Bloomberg meets sci-fi mission control, not another purple-gradient AI dashboard.
| 48 lessons across 6 modules | RAG (naïve → CRAG → eval), embeddings (with tokenization + transformer forward-pass internals), LLM models (transformer architecture + inference internals), agents, production AI (with HNSW internals), enterprise patterns. Each lesson: theory body, animated diagram, decision card, interview gotchas, scored quiz. |
| Three-mode hands-on labs | Walkthrough reveals code section by section with key-points and "what to notice" callouts. Practice gives you starter-code stubs and AI-graded verification. Experiment is a free Monaco editor with a Gemini code-explainer. Optional Pyodide Web Worker actually runs your Python in the browser. |
| Interview simulator | Conceptual / system-design / coding / behavioral modes × three difficulties × three company types. Each answer scored on correctness, depth, and clarity, with a written critique and ideal answer. Sessions persist; history feeds the readiness score. |
| AI tutor chat | Streaming responses, lesson-aware context, persistent history. |
| Animated SVG diagrams | RAG pipeline, embedding space, chunking comparison, model decision tree, agent loop, LangGraph state machine, hybrid-search RRF, RAGAS eval radar. |
| Concept glossary | ~130 terms with high/medium/low frequency badges, lesson cross-links, and on-demand Gemini "Simplify" explanations. |
| Progress telemetry | Recharts module-mastery bar chart, score-trajectory line chart with 5-session moving average, quiz-score scatter, recent-sessions log. |
| Layer | Choice | Why |
|---|---|---|
| Framework | Next.js 15 App Router | RSC + streaming for the tutor; Node runtime for API routes; built-in middleware for CSRF + rate limit |
| Language | TypeScript strict mode | Type safety from prompt schemas to UI |
| Styling | Tailwind CSS 3.4 | Custom dark engineering-terminal tokens |
| Motion | Framer Motion 11 | Page transitions, diagram animations, panel reveals |
| Editor | Monaco (@monaco-editor/react) | Same editor as VS Code; lazy-loaded |
| Python runtime | Pyodide 0.26 | Real CPython + NumPy in a Web Worker |
| Charts | Recharts | Dark-themed analytics |
| ORM / DB | Prisma 5 + Postgres (Neon) | Single schema swaps to SQLite for local dev |
| LLM | @google/generative-ai · gemini-3.1-pro-preview | Server-side only — key never reaches the browser |
| Validation | Zod | Per-route request schemas + env validation |
| Markdown | react-markdown + remark-gfm | No dangerouslySetInnerHTML anywhere |
┌────────────────────────────────────────────────────────────────┐
│ Browser │
│ • App Router pages (RSC) — dashboard, lessons, glossary, │
│ progress, interview, tutor, playground │
│ • Client islands — Monaco, Recharts, Framer Motion, streaming │
│ chat, Pyodide Web Worker │
└──────────────────────────┬─────────────────────────────────────┘
│ fetch (same-origin, rate-limited)
┌──────────────────────────▼─────────────────────────────────────┐
│ middleware.ts │
│ • per-IP token-bucket rate limit (120 req/min) │
│ • same-origin enforcement on POST/PUT/PATCH/DELETE │
└──────────────────────────┬─────────────────────────────────────┘
│
┌──────────────────────────▼─────────────────────────────────────┐
│ Next.js 15 — Node runtime API routes │
│ │
│ /api/health env + db probe │
│ /api/chat streaming Gemini tutor │
│ /api/interview/* session, generate, evaluate, log │
│ /api/explain code walkthrough on demand │
│ /api/walkthrough lab walkthrough generation │
│ /api/verify AI-graded lab task verification │
│ /api/simplify ELI-junior helper │
│ /api/harder escalate interview question │
│ /api/progress lesson progress + readiness │
│ /api/note per-lesson notes │
│ │
│ Each route: │
│ • validates input via Zod (lib/validation.ts) │
│ • wraps Gemini calls in retry-with-backoff (lib/retry.ts) │
│ • emits structured JSON logs (lib/logger.ts) │
└──────────┬─────────────────────────────────────────┬───────────┘
│ │
┌───────▼─────────┐ ┌───────▼─────────┐
│ Prisma · Neon │ │ Gemini API │
│ Postgres │ │ 3.1 Pro │
│ │ │ preview │
│ Users │ │ │
│ LessonProgress │ │ Server-side │
│ InterviewSession │ only — key │
│ InterviewQuestion │ never reaches │
│ CodeSubmission │ │ the browser │
│ Note · Badge │ └─────────────────┘
│ ChatMessage │
└─────────────────┘
git clone git@github.com:mdSHash/NueralPath.git
cd NueralPath
# 1. install
npm install --legacy-peer-deps
# 2. configure
cp .env.example .env
# then edit .env and set GEMINI_API_KEY + DATABASE_URL
# 3. database
npm run db:push # creates the schema in your Postgres
npm run db:seed # creates the default user
# 4. dev server
npm run dev
Open http://localhost:3000.
For local development without Postgres, flip provider = "sqlite" in prisma/schema.prisma and use DATABASE_URL=file:./dev.db.
Cloning to a fresh stack takes about three minutes:
mdSHash/NueralPath in the Vercel dashboard).GEMINI_API_KEY — from Google AI StudioDATABASE_URL — your Neon pooled URLnpm run vercel-build, which regenerates the Prisma client, pushes the schema, and builds Next.js — the database is initialised automatically.<your-url>/api/health to verify.| # | Module | Focus | Lessons |
|---|---|---|---|
| 1 | RAG | Naive → Advanced → Modular → Agentic → GraphRAG → Multimodal → CRAG → Eval | 10 |
| 2 | Embeddings | Models, chunking, vector DBs, hybrid search, multilingual, tokenization, encoder forward pass | 9 |
| 3 | LLM Models | Selection, OS vs proprietary, watsonx, routing, transformer architecture, inference internals | 10 |
| 4 | Agents & Orchestration | ReAct, LangGraph, multi-agent, tool design, memory, eval | 6 |
| 5 | Production AI | Observability, evals, guardrails, latency, cost, CI/CD, HNSW internals | 8 |
| 6 | Enterprise / IBM | Multi-tenant RAG, MQ integration, Azure OpenAI, responsible AI, ROI | 5 |
Each lesson includes: theory body (Markdown) · animated SVG diagram (where applicable) · key takeaways · decision card (when-to-use / not / trade-offs) · interview gotchas · scored quiz · optional code lab.
app/
page.tsx dashboard
learn/ curriculum index + lesson viewer
playground/ standalone Monaco labs
interview/ interview simulator
chat/ AI tutor
glossary/ searchable term dictionary
progress/ charts + recent sessions
api/ 12 endpoints — Gemini + persistence + health
components/
ui/ design-system primitives
layout/ sidebar, topbar shell
dashboard/ hero, learning map, readiness, next lesson
lesson/
LessonClient.tsx viewer shell
KeyTakeaways · DecisionCard · Gotchas · Quiz · DiagramSlot
lab/
LabTabs.tsx walkthrough / practice / experiment switch
WalkthroughLab.tsx sections with reveal pacing
PracticeLab.tsx editor + verify + reference solution
ExperimentLab.tsx free editor + AI explainer
PyodideRunner.tsx Web-Worker Python runtime panel
interview/ setup, runner, summary
diagrams/ eight animated SVG concept diagrams
hooks/
usePyodide.ts worker lifecycle + run helper
lib/
curriculum/ six module files + glossary + interview seed
gemini.ts server-only SDK wrapper with retries
env.ts Zod-validated process.env
validation.ts per-route + lab request schemas
logger.ts structured JSON logger
retry.ts exponential-backoff helper
db.ts Prisma client singleton
public/
pyodide-worker.js Web Worker that hosts Pyodide
prisma/
schema.prisma Postgres schema
seed.ts default user + starter progress
middleware.ts rate limit + same-origin enforcement
next.config.ts security headers + CSP
All routes live at /api/*, run on the Node runtime, validate request bodies with Zod, and emit structured logs on failure.
| Method · Route | Body / params | Returns |
|---|---|---|
GET /api/health | — | { status, model, db, time } |
POST /api/chat | { message, moduleId?, lessonId?, history? } | streamed text/plain (Gemini tokens) |
GET /api/chat | — | { messages[] } recent tutor history |
POST /api/interview/session | { mode, companyType, role, difficulty, module? } | { sessionId } |
GET /api/interview/session | — | { sessions[] } |
POST /api/interview/generate | { mode, companyType, role, difficulty, module?, count? } | { questions[], source } |
POST /api/interview/evaluate | { question, userAnswer, role, difficulty, mode } | { scoreCorrectness, scoreDepth, scoreClarity, feedback, idealAnswer, missingConcepts[] } |
POST /api/interview/question | full per-question record | { id } |
POST /api/explain | { code, language? } | { explanation } |
POST /api/walkthrough | { labTitle, language, starterCode, expectedConcepts? } | { sections[] } |
POST /api/verify | { taskPrompt, taskDescription, language, userCode, referenceSolution? } | { passed, score, feedback, hints[] } |
POST /api/simplify | { concept } | { explanation } |
POST /api/harder | { question, mode? } | { question } |
GET /api/progress | — | aggregate readiness telemetry |
POST /api/progress | { moduleId, lessonId, status?, quizScore?, addTime? } | updated LessonProgress row |
GET /api/note?moduleId&lessonId | — | { notes[] } |
POST /api/note | { moduleId, lessonId, body } | { note } |
DELETE /api/note | { id } | { ok } |
Mutating routes require Origin === Host. Cross-origin → 403. Rate-limited at 120 req/min per IP.
| Name | Required | Default | Purpose |
|---|---|---|---|
GEMINI_API_KEY | yes | — | Server-side Google Generative AI key. Never sent to the browser. |
GEMINI_MODEL | no | gemini-3.1-pro-preview | Override the model name. |
DATABASE_URL | yes | — | Prisma datasource. Postgres connection string (Neon, Supabase, Vercel Postgres). For SQLite dev, set provider = "sqlite" in prisma/schema.prisma and use file:./dev.db. |
NODE_ENV | no | development | production enables HSTS. |
.env is gitignored. Use .env.example as the template and never commit a real key.
The app ships the controls a public-facing Next.js app should have, even though it's designed for single-user use.
| Layer | Control |
|---|---|
| Network | TLS-only via Vercel; HSTS in production builds (Strict-Transport-Security: max-age=63072000; includeSubDomains; preload) |
| Browser | Strict CSP (default-src 'self'; Gemini connect-src restricted), frame-ancestors 'none', X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Resource-Policy: same-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), X-Powered-By removed |
| Edge | middleware.ts enforces same-origin on every mutating /api/* request and applies a per-IP token bucket (120 req/min) |
| App | Zod request-body validation on every API route; Zod-validated process.env at startup; exponential-backoff retry around every Gemini call; structured JSON logging |
| Data | Prisma parameterised queries throughout; no raw SQL; react-markdown + remark-gfm everywhere — no dangerouslySetInnerHTML |
| Secrets | Gemini SDK imported only inside app/api/** and lib/gemini.ts; no NEXT_PUBLIC_* keys; .env gitignored |
| Runtime isolation | Pyodide runs inside a Web Worker, sandboxed away from the main thread |
npm audit is clean against direct dependencies. Next.js is pinned to 15.5.19+ which patches the critical RCE in the React Flight protocol (GHSA-9qr9-h5gf-34mp) and the middleware authorization-bypass (GHSA-f82v-jwr5-mffw) that affected earlier 15.x.
user_default is auto-created. To go multi-tenant: add NextAuth, key Prisma queries on session.user.id, tighten the CSRF check.| Script | What it does |
|---|---|
npm run dev | Next.js dev server on :3000 |
npm run build | Production build (no DB migration — for local builds) |
npm run vercel-build | What Vercel runs: prisma generate && prisma db push --accept-data-loss && next build |
npm run start | Start the production build |
npm run lint | ESLint via next lint |
npm run db:push | Push the Prisma schema to your DB |
npm run db:generate | Regenerate the Prisma client |
npm run db:seed | Seed the default user + starter progress |
Could not resolve dependency on npm install. Some peers want React 19. Rerun with npm install --legacy-peer-deps.
/api/health returns db: "fail". Prisma can't reach your DB. Check DATABASE_URL. For Neon, use the pooled connection string (the URL with -pooler in the host).
Chat / interview / explain returns 502. Either GEMINI_API_KEY is missing or the model returned an error. Check the dev-server console — lib/logger.ts emits a structured line with the failing route.
Monaco fails to load. Loaded via next/dynamic with ssr: false. Ensure JavaScript is enabled and the CSP shipped here isn't being overridden by your platform.
Pyodide takes 10–20 s to start. Expected on first use — it downloads ~10 MB from cdn.jsdelivr.net and initialises a Web Worker. Subsequent runs are instant.
429 rate limit exceeded. You hit the 120 req/min cap. Wait 30 seconds (the Retry-After header tells you exactly) or raise RATE_LIMIT_PER_MIN in middleware.ts.
403 cross-origin request blocked. Mutating requests must be same-origin. If you legitimately need a different origin during dev, allow it in middleware.ts's sameOrigin check.
softmax(QK^T/√d_head)V from first principles, multi-head, GQA, FFN/SwiGLU, RoPE, RMSNorm, residual stream framing, KV cache memory math.M/ef_construction/ef_search knobs, IVF-PQ contrast, ~50-line HNSW-from-scratch lab.Built by Mostafa Ayman (@mdSHash).
MIT — adapt freely.
TypeScript
99.1%