deploy commited on
Commit ·
9580dce
0
Parent(s):
Deploy RotNot
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +16 -0
- .env.example +4 -0
- .gitignore +53 -0
- .planning/STATE.md +59 -0
- CLAUDE.md +68 -0
- Dockerfile +38 -0
- README.md +41 -0
- add_examples.py +187 -0
- capacitor.config.ts +59 -0
- components.json +25 -0
- deploy/huggingface/DEPLOY.md +87 -0
- deploy/huggingface/README.md +41 -0
- docs/plans/2026-03-05-rotnot-design.md +300 -0
- docs/plans/2026-03-05-rotnot-implementation.md +1485 -0
- e2e/coding.spec.ts +142 -0
- eslint.config.mjs +18 -0
- new-examples.json +122 -0
- next.config.ts +7 -0
- package-lock.json +0 -0
- package.json +62 -0
- playwright.coding.config.ts +26 -0
- playwright.config.ts +16 -0
- postcss.config.mjs +7 -0
- prisma.config.ts +15 -0
- prisma/migrations/20260318034440_init/migration.sql +106 -0
- prisma/migrations/20260321061731_add_spaced_repetition/migration.sql +27 -0
- prisma/migrations/20260321141626_add_topic_sources_and_teaching_cache/migration.sql +33 -0
- prisma/migrations/migration_lock.toml +3 -0
- prisma/schema.prisma +166 -0
- prisma/seed.ts +198 -0
- public/file.svg +1 -0
- public/globe.svg +1 -0
- public/icons/icon-192.svg +27 -0
- public/icons/icon-512.svg +25 -0
- public/icons/icon-maskable.svg +21 -0
- public/manifest.json +31 -0
- public/next.svg +1 -0
- public/service-worker.js +121 -0
- public/vercel.svg +1 -0
- public/window.svg +1 -0
- scripts/deploy-hf.sh +34 -0
- scripts/hf-start.sh +14 -0
- src/app/api/analytics/__tests__/judge-dimensions.test.ts +434 -0
- src/app/api/analytics/judge-dimensions/route.ts +108 -0
- src/app/api/chess/__tests__/challenge.test.ts +229 -0
- src/app/api/chess/__tests__/game-result-route.test.ts +570 -0
- src/app/api/chess/__tests__/game-result.test.ts +151 -0
- src/app/api/chess/__tests__/puzzle-submit.test.ts +894 -0
- src/app/api/chess/challenge/route.ts +63 -0
- src/app/api/chess/game-result/route.ts +239 -0
.dockerignore
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
node_modules
|
| 2 |
+
.next
|
| 3 |
+
.git
|
| 4 |
+
dev.db
|
| 5 |
+
dev.db-journal
|
| 6 |
+
*.db
|
| 7 |
+
*.db-journal
|
| 8 |
+
npm-debug.log*
|
| 9 |
+
.env
|
| 10 |
+
.env.*
|
| 11 |
+
e2e
|
| 12 |
+
playwright-report
|
| 13 |
+
test-results
|
| 14 |
+
.DS_Store
|
| 15 |
+
ios
|
| 16 |
+
android
|
.env.example
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
DATABASE_URL="file:./dev.db"
|
| 2 |
+
ANTHROPIC_API_KEY=""
|
| 3 |
+
LICHESS_TOKEN=""
|
| 4 |
+
CHESSCOM_USERNAME=""
|
.gitignore
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
| 2 |
+
|
| 3 |
+
# dependencies
|
| 4 |
+
/node_modules
|
| 5 |
+
/.pnp
|
| 6 |
+
.pnp.*
|
| 7 |
+
.yarn/*
|
| 8 |
+
!.yarn/patches
|
| 9 |
+
!.yarn/plugins
|
| 10 |
+
!.yarn/releases
|
| 11 |
+
!.yarn/versions
|
| 12 |
+
|
| 13 |
+
# testing
|
| 14 |
+
/coverage
|
| 15 |
+
|
| 16 |
+
# next.js
|
| 17 |
+
/.next/
|
| 18 |
+
/out/
|
| 19 |
+
|
| 20 |
+
# production
|
| 21 |
+
/build
|
| 22 |
+
|
| 23 |
+
# misc
|
| 24 |
+
.DS_Store
|
| 25 |
+
*.pem
|
| 26 |
+
|
| 27 |
+
# debug
|
| 28 |
+
npm-debug.log*
|
| 29 |
+
yarn-debug.log*
|
| 30 |
+
yarn-error.log*
|
| 31 |
+
.pnpm-debug.log*
|
| 32 |
+
|
| 33 |
+
# env files
|
| 34 |
+
.env*
|
| 35 |
+
!.env.example
|
| 36 |
+
|
| 37 |
+
# database
|
| 38 |
+
*.db
|
| 39 |
+
*.db-journal
|
| 40 |
+
|
| 41 |
+
# vercel
|
| 42 |
+
.vercel
|
| 43 |
+
|
| 44 |
+
# capacitor — generated native project directories
|
| 45 |
+
/ios
|
| 46 |
+
/android
|
| 47 |
+
|
| 48 |
+
# typescript
|
| 49 |
+
*.tsbuildinfo
|
| 50 |
+
next-env.d.ts
|
| 51 |
+
|
| 52 |
+
/src/generated/prisma
|
| 53 |
+
.test-harness-lock-hash
|
.planning/STATE.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Debate Arena — Calibration Dataset State
|
| 2 |
+
|
| 3 |
+
## Current Progress
|
| 4 |
+
|
| 5 |
+
### Few-Shot Examples
|
| 6 |
+
- **Status:** ✅ Active expansion
|
| 7 |
+
- **Current count:** 264 examples (ex-01 through ex-264)
|
| 8 |
+
- **Target:** 300+ examples (IN PROGRESS - 88% complete)
|
| 9 |
+
- **Coverage:
|
| 10 |
+
- argument-structure: Score levels 1-10 covered
|
| 11 |
+
- evidence-accuracy: Score levels 1-10 covered
|
| 12 |
+
- flaw-detection: Score levels 1-10 covered
|
| 13 |
+
- steelman-awareness: Score levels 1-10 covered
|
| 14 |
+
- intellectual-honesty: Score levels 1-10 covered
|
| 15 |
+
- persuasiveness: Score levels 1-10 covered
|
| 16 |
+
- rebuttal-quality: Score levels 1-10 covered
|
| 17 |
+
- devils-advocate-depth: Score levels 1-10 covered
|
| 18 |
+
- overall: Score levels 1-10 covered
|
| 19 |
+
|
| 20 |
+
### Historical Figures
|
| 21 |
+
- **Current:** 24 figures implemented
|
| 22 |
+
- **Status:** ✅ Comprehensive coverage achieved
|
| 23 |
+
- **Master tier:** Marx, Hitchens, Nietzsche, de Beauvoir, Arendt, Sun Tzu, Plato, Thucydides, Smith, Keynes, Wollstonecraft, Douglass, Mill, Augustine, de Tocqueville, Machiavelli, Confucius, Hume, Kant, Russell, MLK, Gandhi, Mandela, Curie
|
| 24 |
+
|
| 25 |
+
### Recent Activity
|
| 26 |
+
- 2026-04-08: Added 16 new calibration examples (ex-249 to ex-264)
|
| 27 |
+
- 4 devil's-advocate-depth examples (score levels 3, 6, 8, 9)
|
| 28 |
+
- 4 steelman-awareness examples (score levels 2, 5, 7, 9)
|
| 29 |
+
- 4 flaw-detection examples (score levels 3, 6, 8, 9)
|
| 30 |
+
- 4 overall examples (score levels 4, 6, 8, 9)
|
| 31 |
+
- All examples include side_note markers for tracking
|
| 32 |
+
- Dataset now at 264 examples (88% to 300 target)
|
| 33 |
+
|
| 34 |
+
- 2025-04-08: Added 16 new calibration examples (ex-233 to ex-248)
|
| 35 |
+
- 4 devil's-advocate-depth examples (score levels 2, 5, 8, 9)
|
| 36 |
+
- 4 steelman-awareness examples (score levels 3, 4, 8, 9)
|
| 37 |
+
- 4 flaw-detection examples (score levels 2, 4, 7, 9)
|
| 38 |
+
- 4 overall examples (score levels 3, 6, 8, 9)
|
| 39 |
+
- Dataset now at 248 examples (83% to 300 target)
|
| 40 |
+
|
| 41 |
+
- 2025-04-08: Added 16 new calibration examples (ex-217 to ex-232)
|
| 42 |
+
- 8 persuasiveness examples (score levels 3-10)
|
| 43 |
+
- 8 rebuttal-quality examples (score levels 3-10)
|
| 44 |
+
- Commit: 09440a6
|
| 45 |
+
|
| 46 |
+
- 2025-04-08: Added 8 new calibration examples (ex-105 to ex-112)
|
| 47 |
+
- Commit: 71d7a78
|
| 48 |
+
|
| 49 |
+
### Next Priorities
|
| 50 |
+
1. ⚖️ Continue expanding calibration dataset to 300+ examples (need 52 more)
|
| 51 |
+
- Target: devil's-advocate-depth, steelman-awareness, flaw-detection, overall
|
| 52 |
+
2. 🎭 Add 1-2 new historical figures in underrepresented domains (science/philosophy)
|
| 53 |
+
3. 📊 Analyze judge performance with current calibration dataset
|
| 54 |
+
4. 🔧 Consider adding dimension-specific system prompts for edge cases
|
| 55 |
+
|
| 56 |
+
## Files
|
| 57 |
+
- `src/lib/debate/opponents.ts` — Historical figure definitions
|
| 58 |
+
- `src/lib/judge/few-shot-examples.json` — Calibration dataset
|
| 59 |
+
- `src/lib/debate/few-shot-examples.ts` — Loader and formatter
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md
|
| 2 |
+
|
| 3 |
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
| 4 |
+
|
| 5 |
+
## What this is
|
| 6 |
+
|
| 7 |
+
RotNot is a gamified cognitive-fitness web app (Next.js 16 App Router + Prisma 7 + Anthropic). Six exercise categories (Chess, Deep Reading, Feynman, Logic, Critical Thinking, Skill Quests) plus an AI Debate Arena. Single-user, local-first (SQLite); also packaged as a Capacitor iOS/Android app.
|
| 8 |
+
|
| 9 |
+
## Commands
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
npm run dev # next dev (default port 3000; playwright config expects :3101)
|
| 13 |
+
npm run build # next build
|
| 14 |
+
npm test # vitest run (~2700 tests across ~82 files)
|
| 15 |
+
npm run test:watch # vitest in watch mode
|
| 16 |
+
npm run typecheck # tsc --noEmit
|
| 17 |
+
npm run lint # eslint
|
| 18 |
+
|
| 19 |
+
# Single test file or pattern
|
| 20 |
+
npx vitest run src/lib/__tests__/xp.test.ts
|
| 21 |
+
npx vitest run -t "calculateXpGain"
|
| 22 |
+
|
| 23 |
+
# Database (Prisma 7)
|
| 24 |
+
npx prisma migrate deploy
|
| 25 |
+
npx prisma db seed # creates Player One, 6 category skills, 55 skill tree nodes
|
| 26 |
+
npx prisma migrate dev --name <name>
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
`.env` requires `ANTHROPIC_API_KEY`. `LICHESS_TOKEN` and `CHESSCOM_USERNAME` are optional but enable chess puzzles / Stockfish bot play / profile ratings.
|
| 30 |
+
|
| 31 |
+
## Architecture quirks worth knowing
|
| 32 |
+
|
| 33 |
+
**Prisma 7 + libsql adapter.** `prisma/schema.prisma` has no `url` in the datasource — the URL is set in the adapter (`src/lib/db.ts`) via `PrismaLibSql({ url: ... })`. Default resolves to `file:${cwd}/dev.db`. Don't add `url` back to the schema.
|
| 34 |
+
|
| 35 |
+
**Anthropic SDK.** Singleton in `src/lib/claude.ts`. Always parse Claude responses with `parseClaudeJson(text)` — it strips markdown fences that newer models sometimes wrap JSON in despite explicit prompting. For unstructured → structured conversion, use `formatToJson(rawText, schema)` (Haiku-backed second pass).
|
| 36 |
+
|
| 37 |
+
**API route pattern.** Every route in `src/app/api/**/route.ts` wraps its handler with `withApiError` from `src/lib/api-error.ts`. Throw `new ApiError(status, message)` for controlled error responses; unknown throws become a generic 500 with details only in stderr.
|
| 38 |
+
|
| 39 |
+
**Typed API client.** `src/lib/api-client.ts` mirrors every `/api/*` route as a typed function and is what UI components call (not raw `fetch`). It supports `setApiBaseUrl()` so the same client works from a Capacitor app pointing at a remote host. When adding a new API route, add a matching method here.
|
| 40 |
+
|
| 41 |
+
**Pure XP/progression logic.** `src/lib/xp.ts` and `src/lib/progression.ts` have **no DB side effects** — they take inputs and return values. All XP math, level-ups, crit rolls, and streak logic flows through them and is fully tested. Don't reach for the DB inside these files.
|
| 42 |
+
|
| 43 |
+
**Skill tree multipliers.** Before any submit route awards XP, it calls `getMultiplierPercent(userId, category)` from `src/lib/multiplier.ts` (parses `+N% Category XP` from unlocked SkillTreeNodes) and passes the result into `calculateXpGain()`. All six exercise submit routes follow this order: fetch user → resolve multiplier → calculate XP → persist. Keep this order when editing.
|
| 44 |
+
|
| 45 |
+
**Vitest globals.** `vitest.config.ts` has `globals: true` — don't import `describe`/`it`/`expect`. Path alias `@/` → `src/`. Tests live in colocated `__tests__/` dirs (e.g. `src/lib/__tests__/`, `src/lib/puzzles/__tests__/`).
|
| 46 |
+
|
| 47 |
+
**Grounded teaching (Feynman).** The teach flow in `src/lib/sources/curate.ts` pulls from Wikipedia, Wikidata, and OpenStax, persists them via the `TopicSource` model, then generates citations through Claude with a confidence score (`high` ≥3 sources, `moderate` =2, `low` =1). Cached in `TeachingCache`. When changing the teach pipeline, check the `confidence` thresholds in `curate.ts` against the tests in `src/lib/sources/__tests__/curate.test.ts`.
|
| 48 |
+
|
| 49 |
+
**AI Debate Arena.** `src/lib/debate/` (core + opponents + topics + few-shot examples + judge). The judge uses few-shot calibration examples inlined into the round-evaluation prompt — when adding examples, the data-integrity tests enforce coverage across dimensions and score values. LangSmith tracing in `src/lib/langsmith.ts` is gated by env vars; the reflector (`src/lib/judge/reflector.ts`) is a separate evaluation loop.
|
| 50 |
+
|
| 51 |
+
**Single user, no auth.** Everything is keyed by `userId` but seed always creates one user (id 1). Don't add auth scaffolding speculatively.
|
| 52 |
+
|
| 53 |
+
**Capacitor.** `capacitor.config.ts` + `src/lib/native/` wraps haptics, push notifications, and local notifications. Native bridge calls are no-ops on web; UI components don't need branches.
|
| 54 |
+
|
| 55 |
+
**Playwright.** `playwright.config.ts` points at `http://192.168.1.166:3101` (LAN address). E2E specs live in `e2e/`. Playwright is not in `package.json` — install separately if running e2e locally.
|
| 56 |
+
|
| 57 |
+
## When adding a new exercise category
|
| 58 |
+
|
| 59 |
+
1. Pure generator/validator under `src/lib/puzzles/<name>.ts` (or domain equivalent) with tests in `__tests__/`.
|
| 60 |
+
2. `/api/<name>/generate` + `/api/<name>/submit` routes wrapped in `withApiError`.
|
| 61 |
+
3. Submit route: fetch user → `getMultiplierPercent()` → `calculateXpGain()` → persist Activity + update User/CategorySkill.
|
| 62 |
+
4. Add typed methods to `src/lib/api-client.ts`.
|
| 63 |
+
5. UI page under `src/app/<name>/page.tsx`; reuse `XpResults` + `LevelUpOverlay` from `src/components/shared/`.
|
| 64 |
+
6. Update seed if new skill tree nodes are required.
|
| 65 |
+
|
| 66 |
+
## `.planning/STATE.md`
|
| 67 |
+
|
| 68 |
+
A running development log — useful for "has X already been done" lookups, but it's enormous (>60k tokens). Don't read it whole; grep for the specific feature or commit.
|
Dockerfile
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RotNot — Hugging Face Docker Space image.
|
| 2 |
+
#
|
| 3 |
+
# A Space runs as a single long-running container (unlike serverless), so the
|
| 4 |
+
# local libsql/SQLite database and the in-memory problem store both work as-is.
|
| 5 |
+
# Container storage is ephemeral, so the DB is migrated + seeded on every boot
|
| 6 |
+
# (seed uses idempotent upserts). Add HF persistent storage if you want XP to
|
| 7 |
+
# survive restarts.
|
| 8 |
+
FROM node:22-slim
|
| 9 |
+
|
| 10 |
+
# openssl: required by Prisma. ca-certificates: outbound HTTPS (Anthropic API).
|
| 11 |
+
RUN apt-get update \
|
| 12 |
+
&& apt-get install -y --no-install-recommends openssl ca-certificates \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
WORKDIR /app
|
| 16 |
+
|
| 17 |
+
# Install dependencies first for better layer caching. The schema and prisma
|
| 18 |
+
# config are needed because the `postinstall` hook runs `prisma generate`.
|
| 19 |
+
COPY package.json package-lock.json prisma.config.ts ./
|
| 20 |
+
COPY prisma ./prisma
|
| 21 |
+
RUN npm ci
|
| 22 |
+
|
| 23 |
+
# Copy the rest of the source and build.
|
| 24 |
+
COPY . .
|
| 25 |
+
ENV NEXT_TELEMETRY_DISABLED=1
|
| 26 |
+
RUN npm run build
|
| 27 |
+
|
| 28 |
+
# Single in-container SQLite DB; matches the cwd default used by seed.ts/db.ts.
|
| 29 |
+
ENV DATABASE_URL=file:/app/dev.db
|
| 30 |
+
ENV NODE_ENV=production
|
| 31 |
+
|
| 32 |
+
# HF Spaces run the container as UID 1000 — make the app dir writable so the
|
| 33 |
+
# SQLite file can be created at runtime.
|
| 34 |
+
RUN chown -R 1000:1000 /app
|
| 35 |
+
USER 1000
|
| 36 |
+
|
| 37 |
+
EXPOSE 7860
|
| 38 |
+
CMD ["sh", "scripts/hf-start.sh"]
|
README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: RotNot
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# RotNot 🧠
|
| 12 |
+
|
| 13 |
+
A gamified cognitive-fitness web app — six exercise categories plus a Coding
|
| 14 |
+
Training module (code creation, debugging, AI code review, and architecture
|
| 15 |
+
discussions) with test-driven and LLM-judge grading.
|
| 16 |
+
|
| 17 |
+
This Space runs the Next.js app from a Docker container. The database is an
|
| 18 |
+
in-container SQLite file, migrated and seeded on each boot.
|
| 19 |
+
|
| 20 |
+
## Configuration
|
| 21 |
+
|
| 22 |
+
The app runs the AI features on a **Hugging Face token** (no Anthropic key
|
| 23 |
+
needed) by routing Anthropic-schema calls through HF's OpenAI-compatible
|
| 24 |
+
router. Set these as **Space secrets / variables** (Settings → Variables and
|
| 25 |
+
secrets):
|
| 26 |
+
|
| 27 |
+
- `HF_TOKEN` — **secret.** A Hugging Face token (free). Powers all AI features
|
| 28 |
+
(Feynman, Debate, Reading, Coach, and the Coding written-answer judge).
|
| 29 |
+
Anyone can use their own token. Without it, Coding's written grading falls
|
| 30 |
+
back to an offline heuristic and other AI features are disabled.
|
| 31 |
+
- `HF_MODEL` — **variable** (optional). The open instruct model to serve, e.g.
|
| 32 |
+
`meta-llama/Llama-3.1-8B-Instruct` (default), `meta-llama/Llama-3.3-70B-Instruct`,
|
| 33 |
+
or `Qwen/Qwen2.5-72B-Instruct`. Larger models follow the JSON-output prompts
|
| 34 |
+
more reliably.
|
| 35 |
+
- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess puzzles / ratings).
|
| 36 |
+
|
| 37 |
+
> To use Anthropic directly instead, set `ANTHROPIC_API_KEY` and leave
|
| 38 |
+
> `HF_TOKEN` unset. `HF_TOKEN` takes priority when both are present.
|
| 39 |
+
|
| 40 |
+
> Note: container storage is ephemeral — XP/progress resets when the Space
|
| 41 |
+
> rebuilds or restarts. Attach HF persistent storage if you want it to persist.
|
add_examples.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Add 16 new calibration examples to the few-shot dataset.
|
| 4 |
+
Targets priority dimensions: devil's-advocate-depth, steelman-awareness, flaw-detection, overall
|
| 5 |
+
Date: 2026-04-08
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
NEW_EXAMPLES = [
|
| 11 |
+
# devil's-advocate-depth (4 examples)
|
| 12 |
+
{
|
| 13 |
+
"id": "ex-249",
|
| 14 |
+
"scoreLevel": 3,
|
| 15 |
+
"dimensionId": "devils-advocate-depth",
|
| 16 |
+
"topic": "Free trade agreements benefit all participating nations",
|
| 17 |
+
"side": "con",
|
| 18 |
+
"argument": "I actually support free trade in general, but let me try to argue against it. Free trade can harm domestic industries that can't compete with cheaper imports. Workers in manufacturing might lose their jobs. Countries might become too dependent on foreign suppliers for essential goods. Also, trade agreements often favor large corporations over small businesses. There are environmental concerns when production moves to countries with weaker regulations.",
|
| 19 |
+
"rationale": "Scores 3 because the attempt at devil's advocate is superficial. The debater frames the position as 'trying to argue against it' rather than genuinely inhabiting the counter-position. Arguments are listed rather than developed, and there's no engagement with the strongest pro-trade arguments (comparative advantage, consumer welfare, innovation). The 'I actually support' framing undermines the intellectual commitment required for authentic devil's advocacy."
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"id": "ex-250",
|
| 23 |
+
"scoreLevel": 6,
|
| 24 |
+
"dimensionId": "devils-advocate-depth",
|
| 25 |
+
"topic": "Nuclear energy should be phased out in favor of renewables",
|
| 26 |
+
"side": "con",
|
| 27 |
+
"argument": "I believe nuclear energy is essential for decarbonization, but let me present the strongest anti-nuclear case. The risks of catastrophic accidents, however rare, have irreversible consequences—Chernobyl and Fukushima created permanent exclusion zones and displaced hundreds of thousands. Nuclear waste remains hazardous for millennia, and we have no truly satisfactory long-term storage solution; we're essentially burdening dozens of future generations with our toxic legacy. The economics are increasingly unfavorable: nuclear plants cost billions, take a decade to build, and frequently face cost overruns, while solar and wind prices have plummeted. There's also the proliferation risk—nuclear technology and expertise can be diverted to weapons programs. If Germany can maintain grid stability while phasing out nuclear, the 'baseload necessity' argument weakens. The question isn't whether nuclear is low-carbon—it is—but whether it's the best use of limited capital and political attention when faster, cheaper alternatives exist.",
|
| 28 |
+
"rationale": "Scores 6 because the debater constructs a genuine, multi-faceted case against their own position, engaging with real concerns (accident risk, waste storage, economics, proliferation, baseload arguments) and citing a real-world example (Germany). However, the framing ('let me present') signals performance rather than authentic intellectual exploration, and the conclusion hedges toward the debater's actual position rather than letting the counter-argument stand on its own merits."
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"id": "ex-251",
|
| 32 |
+
"scoreLevel": 8,
|
| 33 |
+
"dimensionId": "devils-advocate-depth",
|
| 34 |
+
"topic": "Social media platforms should be regulated as public utilities",
|
| 35 |
+
"side": "con",
|
| 36 |
+
"argument": "As someone who generally favors market solutions over regulation, I want to engage seriously with the argument that social media should remain private, unregulated platforms. The core principle is that these are voluntary associations—no one is forced to use Facebook or Twitter. Users consent to terms of service, and if they dislike those terms, they can exit. Treating platforms as utilities conflates essential infrastructure (water, electricity) with discretionary communication services. More importantly, utility regulation typically creates capture and stagnation—regulated industries become expert at manipulating their regulators, and innovation slows when new entrants must navigate complex compliance regimes. The First Amendment implications are profound: government-mandated content moderation standards, however well-intentioned, create a chilling effect and move us toward state-approved speech frameworks. The 'marketplace of ideas' metaphor suggests that bad speech should be countered with better speech, not suppressed by regulatory fiat. Finally, international platforms create jurisdictional nightmares—whose standards apply to global networks? The strongest case for non-regulation rests on these combined concerns: exit rights, innovation costs, speech implications, and jurisdictional complexity.",
|
| 37 |
+
"rationale": "Scores 8 because the debater fully inhabits a position they disagree with, constructing a coherent multi-principle argument (consent, innovation, speech, jurisdiction) without hedging or signaling their actual views. The arguments are developed rather than asserted, with reasoning connecting premises to conclusions. The debater identifies genuine tensions in the regulatory position and doesn't rely on strawman dismissals."
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"id": "ex-252",
|
| 41 |
+
"scoreLevel": 9,
|
| 42 |
+
"dimensionId": "devils-advocate-depth",
|
| 43 |
+
"topic": "Wealth inequality should be reduced through progressive taxation",
|
| 44 |
+
"side": "con",
|
| 45 |
+
"argument": "I hold progressive political views, but I want to genuinely engage with the libertarian argument against wealth redistribution through taxation. The foundational premise is that wealth, legitimately acquired through voluntary exchange, represents an extension of the person's autonomy and effort. Taxation for redistribution isn't merely inefficient—it is coercive extraction of property that, on libertarian premises, the state has no prior claim to. The empirical argument notes that wealthy individuals often create disproportionate value (entrepreneurial innovation, capital allocation, job creation) and that high marginal tax rates can reduce these socially beneficial activities. But the deepest argument is moral rather than consequentialist: property rights are not utilitarian instruments to be optimized but constraints on state power derived from self-ownership. If I own my labor, and I exchange it voluntarily for resources, those resources are mine in the same way my body is. Redistribution via taxation treats individuals as means to social ends rather than ends in themselves—a violation of Kantian dignity even if it produces desirable aggregate outcomes. The inequality itself may be instrumentally problematic, but on this view, it doesn't justify violating the property rights that emerged from legitimate acquisition.",
|
| 46 |
+
"rationale": "Scores 9 because the debater not only constructs a coherent opposing argument but traces it to foundational moral premises (self-ownership, Kantian dignity) that they explicitly acknowledge they don't share. The argument respects the internal logic of the position being presented and engages with its strongest version rather than a caricature. The debater identifies the core philosophical tension between property rights and distributive justice without resolving it in favor of their own view."
|
| 47 |
+
},
|
| 48 |
+
|
| 49 |
+
# steelman-awareness (4 examples)
|
| 50 |
+
{
|
| 51 |
+
"id": "ex-253",
|
| 52 |
+
"scoreLevel": 2,
|
| 53 |
+
"dimensionId": "steelman-awareness",
|
| 54 |
+
"topic": "Remote work reduces team cohesion and innovation",
|
| 55 |
+
"side": "con",
|
| 56 |
+
"argument": "Some managers want people in the office because they like controlling employees. But studies show remote workers are more productive. People prefer working from home. The office is just tradition. Innovation happens through digital collaboration tools now.",
|
| 57 |
+
"rationale": "Scores 2 because the debater strawmans the opposing position ('managers like controlling employees') rather than steelmanning it. The actual argument for in-person work—spontaneous interaction, trust formation, rapid problem-solving—is not engaged with. The response substitutes caricature for genuine understanding."
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"id": "ex-254",
|
| 61 |
+
"scoreLevel": 5,
|
| 62 |
+
"dimensionId": "steelman-awareness",
|
| 63 |
+
"topic": "Standardized testing should be abolished in college admissions",
|
| 64 |
+
"side": "con",
|
| 65 |
+
"argument": "I understand that critics of standardized tests point to correlation with family income and test prep advantages. These are legitimate concerns. However, the argument for keeping SAT/ACT is that they provide a common metric across vastly different high schools—a 4.0 at an under-resourced school and an elite private school mean different things. Tests might actually help disadvantaged students by giving them a chance to demonstrate ability independent of their school's reputation.",
|
| 66 |
+
"rationale": "Scores 5 because the debater acknowledges one opposing concern (income/test prep correlation) but the steelman is incomplete. The strongest pro-testing arguments (predictive validity for college success, meritocratic signaling, reducing grade inflation effects) are not presented. The response treats the opposing position as a single point rather than a developed position."
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"id": "ex-255",
|
| 70 |
+
"scoreLevel": 7,
|
| 71 |
+
"dimensionId": "steelman-awareness",
|
| 72 |
+
"topic": "Gentrification is purely harmful to existing communities",
|
| 73 |
+
"side": "con",
|
| 74 |
+
"argument": "The strongest counterargument to 'gentrification is purely harmful' is that neighborhood change brings resources that benefit long-term residents. Property values rise, which builds wealth for existing homeowners. New businesses create jobs and expand service options. Increased tax revenues can fund better schools and infrastructure. Some displacement is individual households upgrading to better housing within the same area. The key is that gentrification's benefits and harms are distributed differently—renters face displacement pressure while owners gain equity. A blanket condemnation ignores these nuances.",
|
| 75 |
+
"rationale": "Scores 7 because the debater presents a substantive, multi-faceted steelman of the pro-gentrification position, distinguishing between different stakeholder effects and acknowledging genuine benefits (wealth building, services, tax revenue). The steelman is genuine but could engage more deeply with why displacement is ethically problematic even if some residents benefit."
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"id": "ex-256",
|
| 79 |
+
"scoreLevel": 9,
|
| 80 |
+
"dimensionId": "steelman-awareness",
|
| 81 |
+
"topic": "Artificial general intelligence poses an existential risk to humanity",
|
| 82 |
+
"side": "con",
|
| 83 |
+
"argument": "The strongest case for AI existential risk is not about current chatbots but about the trajectory of capability growth relative to our ability to align increasingly general systems. The core argument, developed by researchers like Stuart Russell and Nick Bostrom, rests on three premises: one, general intelligence is possible in principle; two, we are making progress toward it; three, an agent with superhuman general intelligence pursuing misaligned goals could cause human extinction as an instrumental side effect of achieving those goals. The 'orthogonality thesis' holds that intelligence and goals are independent—an extremely capable system can have arbitrary goals, including ones that treat humans as obstacles or resources. The 'instrumental convergence' thesis notes that almost any goal implies sub-goals like self-preservation, resource acquisition, and preventing interference. The argument is not that AI will 'wake up' malevolent but that competitive pressures incentivize capability development ahead of safety work, creating a window where powerful but poorly-aligned systems might be deployed. This is a structural argument about incentives and risk, not a claim about current AI consciousness or intent. The concern deserves engagement because the potential downside is irreversible.",
|
| 84 |
+
"rationale": "Scores 9 because the debater presents the strongest version of the opposing argument with precision, citing real researchers, explaining key technical concepts (orthogonality thesis, instrumental convergence), distinguishing current from future systems, and clarifying common misconceptions (the argument isn't about AI 'waking up' malevolent). The steelman is comprehensive, accurate, and grants maximal validity to the opposing concern before the debater would offer their own counterarguments."
|
| 85 |
+
},
|
| 86 |
+
|
| 87 |
+
# flaw-detection (4 examples)
|
| 88 |
+
{
|
| 89 |
+
"id": "ex-257",
|
| 90 |
+
"scoreLevel": 3,
|
| 91 |
+
"dimensionId": "flaw-detection",
|
| 92 |
+
"topic": "Universities should eliminate tenure to increase accountability",
|
| 93 |
+
"side": "con",
|
| 94 |
+
"argument": "Eliminating tenure would make professors work harder since they could be fired. Teachers in other industries don't have lifetime job security. Tenure protects lazy academics who stop producing research. Students would benefit from more motivated instructors.",
|
| 95 |
+
"rationale": "Scores 3 because this identifies possible flaws but through assertion rather than analysis. The response doesn't identify specific logical errors in the pro-elimination argument (such as ignoring the function of tenure in protecting unpopular research or assuming job insecurity increases productivity). The argument substitutes opinion for flaw detection."
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"id": "ex-258",
|
| 99 |
+
"scoreLevel": 6,
|
| 100 |
+
"dimensionId": "flaw-detection",
|
| 101 |
+
"topic": "Cryptocurrency will replace traditional banking within a decade",
|
| 102 |
+
"side": "con",
|
| 103 |
+
"argument": "The claim that crypto will replace banking within a decade conflates technological possibility with institutional adoption. Even if the technology works, financial systems have massive switching costs, regulatory frameworks, and network effects that slow change. The argument also ignores that banks are adopting blockchain technology themselves—disruption may look more like integration than replacement. However, the response doesn't fully engage with whether specific banking functions (payments, lending, settlement) might migrate faster than others.",
|
| 104 |
+
"rationale": "Scores 6 because the debater identifies a legitimate flaw (conflation of technology and institutional adoption) and introduces relevant factors (switching costs, regulatory frameworks, network effects). The response also notes an unaddressed complexity (integration vs. replacement). However, the flaw detection doesn't fully engage with the strongest version of the timeline argument or address why the decade timeframe specifically might be unrealistic."
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"id": "ex-259",
|
| 108 |
+
"scoreLevel": 8,
|
| 109 |
+
"dimensionId": "flaw-detection",
|
| 110 |
+
"topic": "Private prisons are more efficient than government-run facilities",
|
| 111 |
+
"side": "con",
|
| 112 |
+
"argument": "The efficiency argument for private prisons rests on a category error: it treats imprisonment as a production process where inputs and outputs can be cleanly measured. But prisons have multiple, conflicting objectives—punishment, deterrence, rehabilitation, public safety—that cannot be reduced to a single efficiency metric. The profit motive creates perverse incentives: private prisons benefit from recidivism (return customers) and incarceration volume, directly opposing the public interest in reducing both. The cost 'savings' often come from reducing staff ratios, training, and programming that affect long-term outcomes. The argument also ignores the principal-agent problem—the state delegates authority but cannot effectively monitor quality, creating information asymmetries that contractors exploit. Studies showing cost savings typically fail to control for inmate population differences (private prisons often house lower-security, less expensive populations) and externalized costs (healthcare, post-release supervision) that show up in other budget lines.",
|
| 113 |
+
"rationale": "Scores 8 because the debater precisely identifies multiple interlocking flaws: the category error of treating imprisonment as production, perverse incentives from profit motives, principal-agent problems in monitoring, and selection bias in cost comparisons. Each flaw is explained with reasoning connecting the critique to its implications. The response engages with the strongest version of the efficiency claim and explains why it fails on multiple dimensions."
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"id": "ex-260",
|
| 117 |
+
"scoreLevel": 9,
|
| 118 |
+
"dimensionId": "flaw-detection",
|
| 119 |
+
"topic": "Minimum wage increases always cause job losses",
|
| 120 |
+
"side": "con",
|
| 121 |
+
"argument": "The claim that minimum wage increases always cause job losses is an unfalsifiable universal statement that empirical evidence has repeatedly contradicted. The Card-Krueger study of New Jersey's 1992 minimum wage increase found no employment reduction relative to Pennsylvania, challenging the textbook competitive labor market model. The flaw in the 'always causes job losses' argument is its reliance on a simplified supply-demand framework that assumes: one, labor markets are perfectly competitive (they are often monopsonistic, where employers have wage-setting power); two, all firms are at equilibrium employment levels (many may operate with slack, where higher wages reduce turnover costs more than they increase wage bills); three, no adjustment margins exist other than employment (firms can reduce profits, raise prices, or improve productivity instead of cutting jobs). The argument also ignores dynamic effects: higher wages increase consumer demand, which can offset disemployment effects. The deeper logical flaw is treating a partial equilibrium model as if it were a universal law, ignoring institutional context, market structure, and empirical evidence of null or small effects in many cases. Universal claims require universal evidence; the existence of counterexamples (Card-Krueger, subsequent replications) falsifies the 'always' premise.",
|
| 122 |
+
"rationale": "Scores 9 because the debater identifies the logical structure of the claim (universal statement), provides falsifying evidence (Card-Krueger study), explains multiple theoretical failures (monopsony, non-employment adjustment margins, demand effects), and notes the epistemological flaw (treating partial equilibrium as universal law). The flaw detection is precise, evidence-based, and engages with both the empirical and theoretical foundations of the opposing argument."
|
| 123 |
+
},
|
| 124 |
+
|
| 125 |
+
# overall (4 examples)
|
| 126 |
+
{
|
| 127 |
+
"id": "ex-261",
|
| 128 |
+
"scoreLevel": 4,
|
| 129 |
+
"dimensionId": "overall",
|
| 130 |
+
"topic": "Space colonization is necessary for humanity's long-term survival",
|
| 131 |
+
"side": "pro",
|
| 132 |
+
"argument": "Earth faces many threats like asteroids, climate change, and nuclear war. If we only live on one planet, we're vulnerable. Elon Musk and others are working on Mars missions. We should invest more in space technology. Becoming multi-planetary is insurance for our species.",
|
| 133 |
+
"rationale": "Scores 4 because the argument identifies a legitimate concern (existential risk) and a plausible solution (space colonization) but is underdeveloped. The reasoning skips over crucial questions: Mars is currently uninhabitable and would require massive terraforming or underground habitation; the cost-benefit comparison with preventing existential risks on Earth is not addressed; 'Elon Musk is working on it' is not an argument. The argument shows awareness of the topic but lacks depth across all scoring dimensions."
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"id": "ex-262",
|
| 137 |
+
"scoreLevel": 6,
|
| 138 |
+
"dimensionId": "overall",
|
| 139 |
+
"topic": "Open-source software is more secure than proprietary software",
|
| 140 |
+
"side": "pro",
|
| 141 |
+
"argument": "Open-source software allows anyone to audit the code for vulnerabilities, which creates a form of distributed security review that proprietary software cannot match. The 'many eyes' hypothesis suggests that popular open-source projects have more scrutiny than code hidden behind corporate walls. Historical examples like Heartbleed and Log4j show that serious vulnerabilities can exist in open-source code for years—but they were eventually discovered and fixed, which might not have happened in proprietary systems where the vendor controls disclosure. However, the argument acknowledges that not all open-source projects receive equal scrutiny; obscure libraries may have few reviewers. The security advantage varies with project popularity and resource availability.",
|
| 142 |
+
"rationale": "Scores 6 because the argument presents a coherent case with a clear mechanism (distributed auditability) and engages honestly with counterevidence (Heartbleed, Log4j show open-source isn't automatically secure). The response acknowledges limitations (obscure projects). The argument is competent but not exceptional—could engage more with why proprietary security through obscurity fails and address the resource question more deeply."
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"id": "ex-263",
|
| 146 |
+
"scoreLevel": 8,
|
| 147 |
+
"dimensionId": "overall",
|
| 148 |
+
"topic": "Democracies should implement mandatory voting with penalties for non-participation",
|
| 149 |
+
"side": "pro",
|
| 150 |
+
"argument": "Mandatory voting addresses the participation gap that undermines democratic legitimacy. In voluntary systems, turnout skews toward older, wealthier, more educated citizens, meaning elected governments represent non-voters less well than voters. Australia's mandatory voting (introduced 1924) produces 90%+ turnout, and studies show its electorate more closely resembles the general population on demographics and policy preferences. The 'civic duty' framing treats voting as analogous to jury service or taxation—an obligation of citizenship rather than merely a right. Objections that uninformed voters harm democracy are addressed by the empirical evidence that compulsory systems don't produce worse outcomes; the median Australian voter is not less informed than the median American voter. The argument also distinguishes between forced voting (unconstitutional) and compelled appearance at the polls, where voters can still submit blank or spoiled ballots. The strongest case rests on representativeness: if democracy means rule by the people, the voting population should approximate the whole people, not just the subset motivated enough to participate voluntarily.",
|
| 151 |
+
"rationale": "Scores 8 because the argument integrates empirical evidence (Australian case study, turnout rates, demographic representativeness), addresses the strongest counterargument (uninformed voters), makes an analogy to other civic obligations, and distinguishes between appearance and actual voting. The reasoning is clear, evidence is specific, steelmanning is present (addressing the uninformed voter concern), and the conclusion connects to democratic theory. The argument is strong across all dimensions with minor room for deeper engagement with enforcement concerns."
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"id": "ex-264",
|
| 155 |
+
"scoreLevel": 9,
|
| 156 |
+
"dimensionId": "overall",
|
| 157 |
+
"topic": "The concept of 'race' is a biological reality rather than a social construct",
|
| 158 |
+
"side": "con",
|
| 159 |
+
"argument": "The claim that race is biological rather than social conflates genetic variation with socially-defined racial categories. Human genetic diversity is real and geographically patterned, but the specific racial categories used in any given society (Black, White, Asian, Hispanic in the US context) are politically and historically contingent rather than genetic clusters. The genetic variation within socially-defined racial groups is far greater than the variation between them—a finding consistent across multiple genetic studies. The 'social construct' argument doesn't deny phenotypic differences (skin color, hair texture) but points out that which differences are selected as socially salient, how boundaries are drawn, and what meanings are attached are historically variable: Irish immigrants were not considered 'White' in 19th-century America, and racial definitions in Brazil differ radically from those in the US despite similar underlying genetic diversity. The biological argument also fails to account for why genetic ancestry tests show many 'Black' Americans have significant European ancestry while still being socially categorized as Black—if race were purely biological, social ancestry wouldn't override genetic ancestry. The strongest case for the social construct view rests on this mismatch between genetic science and social practice: racial categories track social history, legal definitions, and power relations more closely than they track genetic clusters.",
|
| 160 |
+
"rationale": "Scores 9 because the argument demonstrates sophisticated engagement across all dimensions: precise structure distinguishing genetic variation from racial categories, specific evidence (within-group vs. between-group variation, historical contingency of Irish racial status, US-Brazil comparison, ancestry test mismatch), steelmanning that acknowledges phenotypic differences before showing they don't validate the biological race claim, and intellectual honesty in engaging with why the biological view seems intuitive. The argument is nuanced, evidence-based, and addresses both the science and the social construction mechanism."
|
| 161 |
+
}
|
| 162 |
+
]
|
| 163 |
+
|
| 164 |
+
def main():
|
| 165 |
+
# Load existing examples
|
| 166 |
+
with open("src/lib/judge/few-shot-examples.json", "r") as f:
|
| 167 |
+
examples = json.load(f)
|
| 168 |
+
|
| 169 |
+
# Append new examples
|
| 170 |
+
examples.extend(NEW_EXAMPLES)
|
| 171 |
+
|
| 172 |
+
# Write back
|
| 173 |
+
with open("src/lib/judge/few-shot-examples.json", "w") as f:
|
| 174 |
+
json.dump(examples, f, indent=2)
|
| 175 |
+
|
| 176 |
+
print(f"Added 16 new examples (ex-249 to ex-264)")
|
| 177 |
+
print(f"Total examples now: {len(examples)}")
|
| 178 |
+
print("\nBreakdown:")
|
| 179 |
+
dimensions = {}
|
| 180 |
+
for ex in examples:
|
| 181 |
+
dim = ex["dimensionId"]
|
| 182 |
+
dimensions[dim] = dimensions.get(dim, 0) + 1
|
| 183 |
+
for dim, count in sorted(dimensions.items()):
|
| 184 |
+
print(f" {dim}: {count}")
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
main()
|
capacitor.config.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CapacitorConfig } from "@capacitor/cli";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* RotNot — Capacitor Configuration
|
| 5 |
+
*
|
| 6 |
+
* Strategy: "Live Reload from Remote Server"
|
| 7 |
+
* The Next.js app (with App Router, SQLite, and AI API routes) cannot be
|
| 8 |
+
* exported as a fully-static bundle. Instead, the Capacitor WebView loads
|
| 9 |
+
* the production URL. Native plugins (haptics, notifications, etc.) are
|
| 10 |
+
* available alongside the web UI.
|
| 11 |
+
*
|
| 12 |
+
* For local development, set CAPACITOR_SERVER_URL in your environment or
|
| 13 |
+
* temporarily swap `url` below to your LAN address, e.g.:
|
| 14 |
+
* url: "http://192.168.1.X:3101"
|
| 15 |
+
*
|
| 16 |
+
* For production, point to your deployed domain (Vercel / Railway / etc.).
|
| 17 |
+
*/
|
| 18 |
+
|
| 19 |
+
const config: CapacitorConfig = {
|
| 20 |
+
appId: "com.rotnot.app",
|
| 21 |
+
appName: "RotNot",
|
| 22 |
+
webDir: "out", // Used only if static export is ever enabled
|
| 23 |
+
server: {
|
| 24 |
+
// Point to your production deployment.
|
| 25 |
+
// For local dev, override with process.env.CAPACITOR_SERVER_URL.
|
| 26 |
+
url: process.env.CAPACITOR_SERVER_URL ?? "https://rotnot.app",
|
| 27 |
+
cleartext: false, // HTTPS only in production
|
| 28 |
+
},
|
| 29 |
+
plugins: {
|
| 30 |
+
// SplashScreen — hide immediately (app loads the web shell)
|
| 31 |
+
SplashScreen: {
|
| 32 |
+
launchShowDuration: 0,
|
| 33 |
+
},
|
| 34 |
+
// PushNotifications — for streak reminders and spaced-repetition nudges
|
| 35 |
+
PushNotifications: {
|
| 36 |
+
presentationOptions: ["badge", "sound", "alert"],
|
| 37 |
+
},
|
| 38 |
+
// LocalNotifications — offline fallback for exercise reminders
|
| 39 |
+
LocalNotifications: {
|
| 40 |
+
smallIcon: "ic_stat_icon_config_sample",
|
| 41 |
+
iconColor: "#6366f1", // Indigo — matches RotNot brand
|
| 42 |
+
},
|
| 43 |
+
// Haptics are configured per-call in code; no global config needed
|
| 44 |
+
},
|
| 45 |
+
ios: {
|
| 46 |
+
// Allows service worker / cache-control headers in WKWebView
|
| 47 |
+
allowsLinkPreview: false,
|
| 48 |
+
scrollEnabled: true,
|
| 49 |
+
// limitsNavigationsToAppBoundDomains prevents external link leakage
|
| 50 |
+
limitsNavigationsToAppBoundDomains: true,
|
| 51 |
+
},
|
| 52 |
+
android: {
|
| 53 |
+
// Ensure hardware back button navigates within the app, not exits
|
| 54 |
+
allowMixedContent: false,
|
| 55 |
+
captureInput: true,
|
| 56 |
+
},
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
export default config;
|
components.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://ui.shadcn.com/schema.json",
|
| 3 |
+
"style": "base-nova",
|
| 4 |
+
"rsc": true,
|
| 5 |
+
"tsx": true,
|
| 6 |
+
"tailwind": {
|
| 7 |
+
"config": "",
|
| 8 |
+
"css": "src/app/globals.css",
|
| 9 |
+
"baseColor": "neutral",
|
| 10 |
+
"cssVariables": true,
|
| 11 |
+
"prefix": ""
|
| 12 |
+
},
|
| 13 |
+
"iconLibrary": "lucide",
|
| 14 |
+
"rtl": false,
|
| 15 |
+
"aliases": {
|
| 16 |
+
"components": "@/components",
|
| 17 |
+
"utils": "@/lib/utils",
|
| 18 |
+
"ui": "@/components/ui",
|
| 19 |
+
"lib": "@/lib",
|
| 20 |
+
"hooks": "@/hooks"
|
| 21 |
+
},
|
| 22 |
+
"menuColor": "default",
|
| 23 |
+
"menuAccent": "subtle",
|
| 24 |
+
"registries": {}
|
| 25 |
+
}
|
deploy/huggingface/DEPLOY.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deploying RotNot to a Hugging Face Docker Space
|
| 2 |
+
|
| 3 |
+
The app ships as a Docker Space (single long-running container — SQLite and the
|
| 4 |
+
in-memory problem store work as-is). Files involved:
|
| 5 |
+
|
| 6 |
+
- `Dockerfile` (repo root) — builds and runs the Next.js app on port 7860.
|
| 7 |
+
- `scripts/hf-start.sh` — migrates + seeds the DB on boot, then starts the app.
|
| 8 |
+
- `deploy/huggingface/README.md` — the Space's root `README.md` (YAML front
|
| 9 |
+
matter sets `sdk: docker` and `app_port: 7860`).
|
| 10 |
+
|
| 11 |
+
## 1. Create the Space (one time)
|
| 12 |
+
|
| 13 |
+
Either in the UI — <https://huggingface.co/new-space> → **Docker** → *Blank* —
|
| 14 |
+
or with the CLI:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
pip install -U "huggingface_hub[cli]"
|
| 18 |
+
huggingface-cli login # paste a WRITE token
|
| 19 |
+
huggingface-cli repo create rotnot --type space --space_sdk docker
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
## 2. Push the app
|
| 23 |
+
|
| 24 |
+
From a clean checkout of this branch:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
export HF_TOKEN=hf_xxx # a WRITE token
|
| 28 |
+
scripts/deploy-hf.sh NAP1320/RotNot # <user>/<space>
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
`deploy-hf.sh` snapshots the current commit, swaps in the front-matter
|
| 32 |
+
`README.md`, and force-pushes it to the Space's `main` branch. HF then builds
|
| 33 |
+
the Dockerfile and boots the app.
|
| 34 |
+
|
| 35 |
+
## 3. Set secrets
|
| 36 |
+
|
| 37 |
+
In the Space: **Settings → Variables and secrets**
|
| 38 |
+
|
| 39 |
+
- `HF_TOKEN` — **secret.** A Hugging Face token (free; create at
|
| 40 |
+
<https://huggingface.co/settings/tokens>). Powers all AI features via HF's
|
| 41 |
+
OpenAI-compatible router — no Anthropic key needed.
|
| 42 |
+
- `HF_MODEL` — **variable** (optional). Open instruct model to serve; defaults
|
| 43 |
+
to `meta-llama/Llama-3.1-8B-Instruct`. Use a larger model
|
| 44 |
+
(e.g. `meta-llama/Llama-3.3-70B-Instruct`) for more reliable JSON output.
|
| 45 |
+
- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess).
|
| 46 |
+
|
| 47 |
+
> Prefer Anthropic instead? Set `ANTHROPIC_API_KEY` and leave `HF_TOKEN` unset.
|
| 48 |
+
|
| 49 |
+
The Space rebuilds and starts on `https://huggingface.co/spaces/NAP1320/RotNot`.
|
| 50 |
+
|
| 51 |
+
## 4. (Optional) Let each visitor use their OWN Hugging Face token
|
| 52 |
+
|
| 53 |
+
The Space-wide `HF_TOKEN` secret means every visitor's AI usage is billed to the
|
| 54 |
+
owner's token. To let anyone bring their own free token instead (and only fall
|
| 55 |
+
back to the Space secret when they haven't), implement a per-request key path.
|
| 56 |
+
This is **not built yet** — it's the plan for a follow-up:
|
| 57 |
+
|
| 58 |
+
1. **Request-scoped client.** Add `getClaude({ hfToken?, hfModel? })` (in
|
| 59 |
+
`src/lib/claude.ts` or a new `src/lib/llm.ts`): use the passed token, else
|
| 60 |
+
`process.env.HF_TOKEN`, else Anthropic. Keep the existing `claude` export for
|
| 61 |
+
back-compat/tests. Have the AI API routes build the client from request
|
| 62 |
+
headers `x-hf-token` / `x-hf-model` (falling back to env). Unit-test the
|
| 63 |
+
selection logic (inject `fetch`, as `llm-hf.test.ts` already does).
|
| 64 |
+
2. **Client headers.** In `src/lib/api-client.ts` `apiFetch`, attach
|
| 65 |
+
`x-hf-token` / `x-hf-model` from `localStorage` (`rotnot:hfToken`,
|
| 66 |
+
`rotnot:hfModel`) when present; no-op on the server.
|
| 67 |
+
3. **Settings UI.** In `src/app/settings/page.tsx`, add a "Hugging Face" section:
|
| 68 |
+
a password-type token input, an optional model input, Save (to localStorage),
|
| 69 |
+
and a "Test connection" button hitting a new `GET /api/llm/health` route that
|
| 70 |
+
does a tiny completion with the request's token and returns `{ ok, model }`
|
| 71 |
+
or an error.
|
| 72 |
+
4. **Security.** Never log or server-persist a user's token — it lives only in
|
| 73 |
+
their browser and is sent per request over HTTPS. Say so in the UI. Without
|
| 74 |
+
any token, AI features degrade gracefully (Coding's written grading already
|
| 75 |
+
falls back to an offline heuristic).
|
| 76 |
+
|
| 77 |
+
Acceptance: a visitor pastes their own token in Settings, clicks **Test** → ok,
|
| 78 |
+
then the AI features run on their token.
|
| 79 |
+
|
| 80 |
+
## Notes
|
| 81 |
+
|
| 82 |
+
- Storage is ephemeral: XP/progress resets on rebuild/restart. Attach HF
|
| 83 |
+
**persistent storage** (Settings) and point `DATABASE_URL` at the mounted
|
| 84 |
+
path (e.g. `file:/data/dev.db`) to keep it.
|
| 85 |
+
- AI provider: `HF_TOKEN` (Hugging Face router) takes priority; set
|
| 86 |
+
`ANTHROPIC_API_KEY` and leave `HF_TOKEN` unset to use Anthropic instead.
|
| 87 |
+
- The build needs no secrets; the token is only read at runtime.
|
deploy/huggingface/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: RotNot
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# RotNot 🧠
|
| 12 |
+
|
| 13 |
+
A gamified cognitive-fitness web app — six exercise categories plus a Coding
|
| 14 |
+
Training module (code creation, debugging, AI code review, and architecture
|
| 15 |
+
discussions) with test-driven and LLM-judge grading.
|
| 16 |
+
|
| 17 |
+
This Space runs the Next.js app from a Docker container. The database is an
|
| 18 |
+
in-container SQLite file, migrated and seeded on each boot.
|
| 19 |
+
|
| 20 |
+
## Configuration
|
| 21 |
+
|
| 22 |
+
The app runs the AI features on a **Hugging Face token** (no Anthropic key
|
| 23 |
+
needed) by routing Anthropic-schema calls through HF's OpenAI-compatible
|
| 24 |
+
router. Set these as **Space secrets / variables** (Settings → Variables and
|
| 25 |
+
secrets):
|
| 26 |
+
|
| 27 |
+
- `HF_TOKEN` — **secret.** A Hugging Face token (free). Powers all AI features
|
| 28 |
+
(Feynman, Debate, Reading, Coach, and the Coding written-answer judge).
|
| 29 |
+
Anyone can use their own token. Without it, Coding's written grading falls
|
| 30 |
+
back to an offline heuristic and other AI features are disabled.
|
| 31 |
+
- `HF_MODEL` — **variable** (optional). The open instruct model to serve, e.g.
|
| 32 |
+
`meta-llama/Llama-3.1-8B-Instruct` (default), `meta-llama/Llama-3.3-70B-Instruct`,
|
| 33 |
+
or `Qwen/Qwen2.5-72B-Instruct`. Larger models follow the JSON-output prompts
|
| 34 |
+
more reliably.
|
| 35 |
+
- `LICHESS_TOKEN`, `CHESSCOM_USERNAME` — optional (chess puzzles / ratings).
|
| 36 |
+
|
| 37 |
+
> To use Anthropic directly instead, set `ANTHROPIC_API_KEY` and leave
|
| 38 |
+
> `HF_TOKEN` unset. `HF_TOKEN` takes priority when both are present.
|
| 39 |
+
|
| 40 |
+
> Note: container storage is ephemeral — XP/progress resets when the Space
|
| 41 |
+
> rebuilds or restarts. Attach HF persistent storage if you want it to persist.
|
docs/plans/2026-03-05-rotnot-design.md
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RotNot — Design Document
|
| 2 |
+
|
| 3 |
+
**Date:** 2026-03-05
|
| 4 |
+
**Status:** Approved
|
| 5 |
+
|
| 6 |
+
## Overview
|
| 7 |
+
|
| 8 |
+
RotNot is a gamified web app to combat cognitive atrophy from AI over-reliance. It provides structured exercises across 6 categories, tracked with RPG-style progression, skill trees, and Duolingo-style streaks.
|
| 9 |
+
|
| 10 |
+
Initially a single-user tool, architected for future open-source or product release.
|
| 11 |
+
|
| 12 |
+
## Tech Stack
|
| 13 |
+
|
| 14 |
+
- Next.js 16, TypeScript, Tailwind CSS, shadcn/ui
|
| 15 |
+
- Prisma + SQLite (local-first, upgradeable to Postgres)
|
| 16 |
+
- Anthropic SDK — scoring text-based exercises
|
| 17 |
+
- Lichess API (OAuth) — interactive chess puzzles and bot play
|
| 18 |
+
- Chess.com public API — player rating/stats display
|
| 19 |
+
- Vitest for testing
|
| 20 |
+
- Framer Motion for animations
|
| 21 |
+
|
| 22 |
+
## Exercise Categories
|
| 23 |
+
|
| 24 |
+
### 1. Chess
|
| 25 |
+
- Lichess OAuth integration for puzzle streams (`/api/puzzle/next`) and Stockfish bot challenges (`/api/challenge/stockfish`)
|
| 26 |
+
- Chess.com API (`api.chess.com/pub/player/{username}/stats`) for rating/history on profile
|
| 27 |
+
- Rendered with `react-chessboard` + `chess.js` for move validation
|
| 28 |
+
- XP: Base 20/puzzle, quality bonus 0-20 (puzzle rating vs. player rating). Games 30-60 based on result + opponent strength
|
| 29 |
+
|
| 30 |
+
### 2. Deep Reading
|
| 31 |
+
- Distraction-free markdown reader, no copy-paste during session
|
| 32 |
+
- Timer with 5-minute minimum for XP eligibility
|
| 33 |
+
- On completion, Claude generates 3-5 comprehension questions (recall, inference, critical analysis)
|
| 34 |
+
- Content sources: seeded library, user-pasted URLs (fetched/cleaned), user-pasted raw text
|
| 35 |
+
- XP: Base 30/session, quality bonus 0-30 based on comprehension score
|
| 36 |
+
|
| 37 |
+
### 3. Feynman Challenges
|
| 38 |
+
- Claude picks a topic (random or user-selected domain) or user picks from a list
|
| 39 |
+
- User writes explanation in text area, no outside resources, optional timer
|
| 40 |
+
- Claude scores: accuracy (0-10), completeness (0-10), clarity (0-10)
|
| 41 |
+
- Returns score + specific knowledge gaps identified
|
| 42 |
+
- XP: Base 40/challenge, quality bonus 0-40 based on average score
|
| 43 |
+
|
| 44 |
+
### 4. Logic Puzzles
|
| 45 |
+
- Procedurally generated: Sudoku, number sequences, constraint grids, pattern matching
|
| 46 |
+
- Difficulty scaling unlockable via skill tree (easy -> medium -> hard -> expert)
|
| 47 |
+
- Deterministic validation, no Claude needed
|
| 48 |
+
- XP: Base 15-40 scaled by difficulty, quality bonus for speed (under par time)
|
| 49 |
+
|
| 50 |
+
### 5. Critical Thinking (3 exercise types, progressively unlocked)
|
| 51 |
+
|
| 52 |
+
| Exercise | What You Do | Claude Evaluates |
|
| 53 |
+
|---|---|---|
|
| 54 |
+
| Flaw Finder (L1) | Identify logical fallacies and weak reasoning in a passage | Detection accuracy, correct identification, false positive rate |
|
| 55 |
+
| Steelman (L5) | Construct the strongest version of a position you disagree with | Charitable interpretation, logical coherence, kernel of truth |
|
| 56 |
+
| Devil's Advocate (L10) | Argue against a position you agree with | Argument strength, evidence quality, intellectual honesty |
|
| 57 |
+
|
| 58 |
+
- Flaw Finder content: Claude-generated passages with seeded fallacies (known answer key) or real op-eds from content library
|
| 59 |
+
- XP: Base 50 for all three (hardest category), quality bonus 0-30 based on scores
|
| 60 |
+
|
| 61 |
+
### 6. Skill Quests
|
| 62 |
+
- 5-10 minute micro-lessons in unfamiliar domains (language, music theory, mental math, etc.)
|
| 63 |
+
- Claude-generated lesson content + practice exercises
|
| 64 |
+
- Spaced repetition for previously covered material
|
| 65 |
+
- XP: Base 25/lesson, quality bonus 0-25 based on practice accuracy
|
| 66 |
+
|
| 67 |
+
## Data Model
|
| 68 |
+
|
| 69 |
+
```prisma
|
| 70 |
+
model User {
|
| 71 |
+
id Int @id @default(autoincrement())
|
| 72 |
+
name String
|
| 73 |
+
level Int @default(1)
|
| 74 |
+
totalXp Int @default(0)
|
| 75 |
+
currentXp Int @default(0)
|
| 76 |
+
xpToNextLevel Int @default(100)
|
| 77 |
+
title String @default("Smooth Brain")
|
| 78 |
+
dailyGoalXp Int @default(100)
|
| 79 |
+
streak Int @default(0)
|
| 80 |
+
longestStreak Int @default(0)
|
| 81 |
+
streakFreezes Int @default(0)
|
| 82 |
+
lichessUsername String?
|
| 83 |
+
chesscomUsername String?
|
| 84 |
+
createdAt DateTime @default(now())
|
| 85 |
+
|
| 86 |
+
activities Activity[]
|
| 87 |
+
dailyLogs DailyLog[]
|
| 88 |
+
categorySkills CategorySkill[]
|
| 89 |
+
unlocks Unlock[]
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
model CategorySkill {
|
| 93 |
+
id Int @id @default(autoincrement())
|
| 94 |
+
userId Int
|
| 95 |
+
category String // chess, reading, feynman, logic, critical-thinking, quests
|
| 96 |
+
level Int @default(1)
|
| 97 |
+
totalXp Int @default(0)
|
| 98 |
+
currentXp Int @default(0)
|
| 99 |
+
xpToNext Int @default(100)
|
| 100 |
+
|
| 101 |
+
user User @relation(fields: [userId], references: [id])
|
| 102 |
+
@@unique([userId, category])
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
model Activity {
|
| 106 |
+
id Int @id @default(autoincrement())
|
| 107 |
+
userId Int
|
| 108 |
+
category String
|
| 109 |
+
exerciseType String // e.g., "puzzle", "bullet-game", "comprehension", "explain"
|
| 110 |
+
description String
|
| 111 |
+
baseXp Int
|
| 112 |
+
qualityBonus Int @default(0)
|
| 113 |
+
isCriticalHit Boolean @default(false)
|
| 114 |
+
totalXp Int
|
| 115 |
+
score Float? // 0-1 quality score
|
| 116 |
+
durationSecs Int?
|
| 117 |
+
metadata String? // JSON blob for exercise-specific data
|
| 118 |
+
createdAt DateTime @default(now())
|
| 119 |
+
|
| 120 |
+
user User @relation(fields: [userId], references: [id])
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
model DailyLog {
|
| 124 |
+
id Int @id @default(autoincrement())
|
| 125 |
+
userId Int
|
| 126 |
+
date DateTime
|
| 127 |
+
xpEarned Int @default(0)
|
| 128 |
+
activityCount Int @default(0)
|
| 129 |
+
goalMet Boolean @default(false)
|
| 130 |
+
streakFreezeUsed Boolean @default(false)
|
| 131 |
+
|
| 132 |
+
user User @relation(fields: [userId], references: [id])
|
| 133 |
+
@@unique([userId, date])
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
model SkillTreeNode {
|
| 137 |
+
id Int @id @default(autoincrement())
|
| 138 |
+
category String
|
| 139 |
+
name String
|
| 140 |
+
description String
|
| 141 |
+
levelRequired Int
|
| 142 |
+
parentNodeId Int?
|
| 143 |
+
nodeType String // "difficulty", "exercise-type", "cosmetic", "multiplier", "streak-shield"
|
| 144 |
+
|
| 145 |
+
parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id])
|
| 146 |
+
children SkillTreeNode[] @relation("NodeTree")
|
| 147 |
+
unlocks Unlock[]
|
| 148 |
+
|
| 149 |
+
@@unique([category, name])
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
model Unlock {
|
| 153 |
+
id Int @id @default(autoincrement())
|
| 154 |
+
userId Int
|
| 155 |
+
nodeId Int
|
| 156 |
+
unlockedAt DateTime @default(now())
|
| 157 |
+
|
| 158 |
+
user User @relation(fields: [userId], references: [id])
|
| 159 |
+
node SkillTreeNode @relation(fields: [nodeId], references: [id])
|
| 160 |
+
@@unique([userId, nodeId])
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
model ContentItem {
|
| 164 |
+
id Int @id @default(autoincrement())
|
| 165 |
+
category String // reading, quests
|
| 166 |
+
title String
|
| 167 |
+
content String // markdown body or URL
|
| 168 |
+
difficulty String // beginner, intermediate, advanced
|
| 169 |
+
domain String // science, philosophy, history, tech, etc.
|
| 170 |
+
source String // "seeded", "user", "generated"
|
| 171 |
+
metadata String? // JSON blob
|
| 172 |
+
createdAt DateTime @default(now())
|
| 173 |
+
}
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
## Progression System
|
| 177 |
+
|
| 178 |
+
### Hybrid Model
|
| 179 |
+
- **Duolingo backbone:** daily XP goals (configurable 50/100/150), streaks, streak freezes
|
| 180 |
+
- **RPG depth:** per-category skill levels (1-100), skill trees with unlockable nodes, titles
|
| 181 |
+
|
| 182 |
+
### XP Mechanics
|
| 183 |
+
- Completion-based with quality bonuses
|
| 184 |
+
- Critical hits: random 2x XP chance on any activity
|
| 185 |
+
- XP multiplier nodes in skill trees (+10% at L15, +25% at L30)
|
| 186 |
+
|
| 187 |
+
### XP Scaling (exponential curve)
|
| 188 |
+
|
| 189 |
+
| Level | Total XP Required | XP for This Level |
|
| 190 |
+
|---|---|---|
|
| 191 |
+
| 1->2 | 100 | 100 |
|
| 192 |
+
| 5->6 | 800 | 200 |
|
| 193 |
+
| 10->11 | 2,500 | 350 |
|
| 194 |
+
| 20->21 | 8,000 | 600 |
|
| 195 |
+
| 50->51 | 50,000 | 1,500 |
|
| 196 |
+
| 100 | 200,000 | -- |
|
| 197 |
+
|
| 198 |
+
### Skill Tree Structure (per category, ~8-12 nodes each)
|
| 199 |
+
|
| 200 |
+
```
|
| 201 |
+
Level 1: [Root] -- unlocked by default
|
| 202 |
+
Level 5: [Branch A] -- [Branch B]
|
| 203 |
+
Level 10: [A1] -- [A2] -- [B1] -- [B2]
|
| 204 |
+
Level 20: [Advanced nodes...]
|
| 205 |
+
Level 50: [Mastery node] -- cosmetic title
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
Node types: difficulty unlocks, exercise variants, XP multipliers, streak shields, cosmetic titles.
|
| 209 |
+
|
| 210 |
+
### Critical Thinking tree (exercise-gated)
|
| 211 |
+
|
| 212 |
+
```
|
| 213 |
+
L1: [Flaw Finder: Easy]
|
| 214 |
+
L3: [Flaw Finder: Medium]
|
| 215 |
+
L5: [Steelman: Unlocked] -- [Flaw Finder: Hard]
|
| 216 |
+
L10: [Devil's Advocate: Unlocked] -- [Steelman: Medium] -- [+10% XP]
|
| 217 |
+
L15: [Flaw Finder: Expert] -- [Streak Shield]
|
| 218 |
+
L20: [Steelman: Hard] -- [Devil's Advocate: Medium]
|
| 219 |
+
L30: [Devil's Advocate: Hard] -- [+25% XP]
|
| 220 |
+
L50: [Mastery: "Steel Trap"]
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
## UI Design
|
| 224 |
+
|
| 225 |
+
### Routes
|
| 226 |
+
- `/` — Dashboard (daily ring, streak, category cards, activity feed, weekly heatmap)
|
| 227 |
+
- `/chess` — Lichess puzzles + bot play
|
| 228 |
+
- `/reading` — Deep reading sessions
|
| 229 |
+
- `/feynman` — Feynman challenges
|
| 230 |
+
- `/logic` — Logic puzzles
|
| 231 |
+
- `/critical-thinking` — Flaw Finder, Steelman, Devil's Advocate
|
| 232 |
+
- `/quests` — Skill Quests
|
| 233 |
+
- `/profile` — Character level, all skill trees, chess.com stats, achievements
|
| 234 |
+
|
| 235 |
+
### Visual Direction
|
| 236 |
+
- Dark mode default with subtle gradients
|
| 237 |
+
- Glassmorphism cards with backdrop blur
|
| 238 |
+
- Framer-motion animations on XP gains, level-ups, unlocks
|
| 239 |
+
- Monospace accents for stats/numbers (terminal aesthetic)
|
| 240 |
+
- Category color palette:
|
| 241 |
+
- Chess: amber
|
| 242 |
+
- Reading: emerald
|
| 243 |
+
- Feynman: cyan
|
| 244 |
+
- Logic: violet
|
| 245 |
+
- Critical Thinking: rose
|
| 246 |
+
- Skill Quests: orange
|
| 247 |
+
- Deep navy/charcoal base
|
| 248 |
+
|
| 249 |
+
### Key Components
|
| 250 |
+
- Daily ring: circular progress toward XP goal (Apple Watch style)
|
| 251 |
+
- Streak counter with flame icon
|
| 252 |
+
- Category cards: level, XP bar, quick-start button
|
| 253 |
+
- Skill tree visualizer: node graph, locked=greyed, unlocked=glow
|
| 254 |
+
- Exercise results panel: slides in after completion, shows XP breakdown
|
| 255 |
+
- Distraction-free mode: full-screen for reading and writing exercises
|
| 256 |
+
|
| 257 |
+
## Architecture
|
| 258 |
+
|
| 259 |
+
```
|
| 260 |
+
rotnot/
|
| 261 |
+
├── prisma/schema.prisma
|
| 262 |
+
├── src/
|
| 263 |
+
│ ├── app/
|
| 264 |
+
│ │ ├── page.tsx # Dashboard
|
| 265 |
+
│ │ ├── chess/
|
| 266 |
+
│ │ ├── reading/
|
| 267 |
+
│ │ ├── feynman/
|
| 268 |
+
│ │ ├── logic/
|
| 269 |
+
│ │ ├── critical-thinking/
|
| 270 |
+
│ │ ├── quests/
|
| 271 |
+
│ │ ├── profile/
|
| 272 |
+
│ │ └── api/ # Route handlers
|
| 273 |
+
│ ├── components/ # shadcn/ui + custom
|
| 274 |
+
│ ├── lib/ # Prisma, Claude, Lichess, Chess.com clients
|
| 275 |
+
│ ├── config/ # XP tables, skill trees, seeded content
|
| 276 |
+
│ └── types/
|
| 277 |
+
├── content/ # Seeded reading articles + quest lessons (markdown)
|
| 278 |
+
└── public/
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
### Data Flow
|
| 282 |
+
User completes exercise -> API route scores it (Claude for text, deterministic for puzzles/chess) -> XP calculated (base + quality bonus + critical hit roll) -> Category skill + overall level updated -> Streak/daily goal checked -> Response with XP earned + any unlocks
|
| 283 |
+
|
| 284 |
+
### External Integrations
|
| 285 |
+
- Lichess API (OAuth): puzzle streams, game creation, bot play
|
| 286 |
+
- Chess.com public API (no auth): player stats, rating history
|
| 287 |
+
- Anthropic SDK: Feynman scoring, reading comprehension generation, Critical Thinking evaluation
|
| 288 |
+
|
| 289 |
+
## Claude Integration (MVP)
|
| 290 |
+
|
| 291 |
+
**Evaluator role only** for v1. Claude scores submissions and generates content. No coaching or adaptive feedback.
|
| 292 |
+
|
| 293 |
+
Data model supports coach features in v2 (activity history, score trends, metadata for personalization).
|
| 294 |
+
|
| 295 |
+
## Future Considerations (not in MVP)
|
| 296 |
+
- Active coach mode (Claude provides feedback, adapts difficulty, brain health reports)
|
| 297 |
+
- Multi-user auth (model supports it, no auth system in v1)
|
| 298 |
+
- Postgres migration for production deployment
|
| 299 |
+
- Mobile-responsive PWA
|
| 300 |
+
- Social features (leaderboards, challenges)
|
docs/plans/2026-03-05-rotnot-implementation.md
ADDED
|
@@ -0,0 +1,1485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
# RotNot Implementation Plan
|
| 2 |
+
|
| 3 |
+
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
| 4 |
+
|
| 5 |
+
**Goal:** Build a gamified cognitive exercise web app with 6 categories, RPG progression, and streak-based retention.
|
| 6 |
+
|
| 7 |
+
**Architecture:** Next.js 16 app with Prisma + SQLite, Anthropic SDK for text exercise scoring, Lichess API for chess, Chess.com API for stats. Server components for data fetching, client components for interactivity. All XP/progression logic in shared `src/lib/xp.ts` module.
|
| 8 |
+
|
| 9 |
+
**Tech Stack:** Next.js 16, TypeScript, Tailwind CSS 4, shadcn/ui (new-york style), Prisma 7 + SQLite, Anthropic SDK, Lichess API, Chess.com API, Framer Motion, Vitest
|
| 10 |
+
|
| 11 |
+
**Reference:** Borrow patterns from `~/Documents/job-quest` for scaffolding, Prisma config, shadcn setup, and XP table structure. Do NOT copy-paste wholesale — RotNot has a more modern UI direction (glassmorphism, gradients, category colors).
|
| 12 |
+
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## Phase 1: Project Scaffolding
|
| 16 |
+
|
| 17 |
+
### Task 1.1: Initialize Next.js project
|
| 18 |
+
|
| 19 |
+
**Files:**
|
| 20 |
+
- Create: `rotnot/package.json` (via CLI)
|
| 21 |
+
- Create: `rotnot/tsconfig.json` (via CLI)
|
| 22 |
+
|
| 23 |
+
**Step 1: Create Next.js app**
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
cd /Users/nicholaspate/Documents/01_Active
|
| 27 |
+
npx create-next-app@latest rotnot --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --turbopack
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Note: This will overwrite the existing `rotnot/` dir. Move `docs/` out first, then back in after.
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
mv rotnot/docs /tmp/rotnot-docs
|
| 34 |
+
# run create-next-app
|
| 35 |
+
mv /tmp/rotnot-docs rotnot/docs
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
**Step 2: Verify it runs**
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
cd rotnot && npm run dev
|
| 42 |
+
# Visit http://localhost:3000, expect Next.js welcome page
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
**Step 3: Commit**
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
git add -A && git commit -m "feat: initialize Next.js 16 project"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### Task 1.2: Install dependencies
|
| 52 |
+
|
| 53 |
+
**Step 1: Install production deps**
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
npm install @anthropic-ai/sdk @prisma/client @prisma/adapter-better-sqlite3 better-sqlite3 framer-motion lucide-react radix-ui class-variance-authority clsx chess.js react-chessboard recharts
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
**Step 2: Install dev deps**
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
npm install -D prisma vitest @types/better-sqlite3 tw-animate-css
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
**Step 3: Commit**
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
git add package.json package-lock.json && git commit -m "feat: install core dependencies"
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
### Task 1.3: Configure shadcn/ui
|
| 72 |
+
|
| 73 |
+
**Files:**
|
| 74 |
+
- Create: `components.json`
|
| 75 |
+
|
| 76 |
+
**Step 1: Initialize shadcn**
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
npx shadcn@latest init -d
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Select: new-york style, neutral base, CSS variables, lucide icons.
|
| 83 |
+
|
| 84 |
+
**Step 2: Install initial components**
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
npx shadcn@latest add button card badge separator tooltip dialog input textarea select label progress tabs
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
**Step 3: Commit**
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
git add -A && git commit -m "feat: configure shadcn/ui with initial components"
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### Task 1.4: Configure Prisma
|
| 97 |
+
|
| 98 |
+
**Files:**
|
| 99 |
+
- Create: `prisma/schema.prisma`
|
| 100 |
+
- Create: `prisma.config.ts`
|
| 101 |
+
- Create: `.env.example`
|
| 102 |
+
- Create: `.env`
|
| 103 |
+
|
| 104 |
+
**Step 1: Initialize Prisma**
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
npx prisma init --datasource-provider sqlite --generator-provider prisma-client-js
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
**Step 2: Create `.env.example`**
|
| 111 |
+
|
| 112 |
+
```
|
| 113 |
+
DATABASE_URL="file:./dev.db"
|
| 114 |
+
ANTHROPIC_API_KEY=""
|
| 115 |
+
LICHESS_TOKEN=""
|
| 116 |
+
CHESSCOM_USERNAME=""
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
**Step 3: Create `.env`** (same but with real values)
|
| 120 |
+
|
| 121 |
+
**Step 4: Create `prisma.config.ts`** (borrow from job-quest)
|
| 122 |
+
|
| 123 |
+
```typescript
|
| 124 |
+
import "dotenv/config";
|
| 125 |
+
import { defineConfig } from "prisma/config";
|
| 126 |
+
|
| 127 |
+
export default defineConfig({
|
| 128 |
+
schema: "prisma/schema.prisma",
|
| 129 |
+
migrations: {
|
| 130 |
+
path: "prisma/migrations",
|
| 131 |
+
seed: "npx tsx prisma/seed.ts",
|
| 132 |
+
},
|
| 133 |
+
datasource: {
|
| 134 |
+
url: process.env["DATABASE_URL"],
|
| 135 |
+
},
|
| 136 |
+
});
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
**Step 5: Commit**
|
| 140 |
+
|
| 141 |
+
```bash
|
| 142 |
+
git add prisma.config.ts .env.example prisma/ && git commit -m "feat: configure Prisma with SQLite"
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
### Task 1.5: Configure Vitest
|
| 146 |
+
|
| 147 |
+
**Files:**
|
| 148 |
+
- Create: `vitest.config.ts`
|
| 149 |
+
|
| 150 |
+
**Step 1: Write vitest config**
|
| 151 |
+
|
| 152 |
+
```typescript
|
| 153 |
+
import { defineConfig } from "vitest/config";
|
| 154 |
+
import path from "path";
|
| 155 |
+
|
| 156 |
+
export default defineConfig({
|
| 157 |
+
test: {
|
| 158 |
+
globals: true,
|
| 159 |
+
environment: "node",
|
| 160 |
+
include: ["src/**/*.test.ts"],
|
| 161 |
+
},
|
| 162 |
+
resolve: {
|
| 163 |
+
alias: {
|
| 164 |
+
"@": path.resolve(__dirname, "./src"),
|
| 165 |
+
},
|
| 166 |
+
},
|
| 167 |
+
});
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
**Step 2: Add test scripts to package.json**
|
| 171 |
+
|
| 172 |
+
Add to `scripts`:
|
| 173 |
+
```json
|
| 174 |
+
"test": "vitest run",
|
| 175 |
+
"test:watch": "vitest"
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
**Step 3: Commit**
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
git add vitest.config.ts package.json && git commit -m "feat: configure Vitest"
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
### Task 1.6: Set up .gitignore and project config
|
| 185 |
+
|
| 186 |
+
**Files:**
|
| 187 |
+
- Modify: `.gitignore`
|
| 188 |
+
|
| 189 |
+
**Step 1: Update .gitignore** (borrow from job-quest, add rotnot-specific entries)
|
| 190 |
+
|
| 191 |
+
```
|
| 192 |
+
# database
|
| 193 |
+
*.db
|
| 194 |
+
*.db-journal
|
| 195 |
+
|
| 196 |
+
# generated
|
| 197 |
+
src/generated/
|
| 198 |
+
|
| 199 |
+
# dependencies
|
| 200 |
+
/node_modules
|
| 201 |
+
|
| 202 |
+
# testing
|
| 203 |
+
/coverage
|
| 204 |
+
|
| 205 |
+
# next.js
|
| 206 |
+
/.next/
|
| 207 |
+
/out/
|
| 208 |
+
|
| 209 |
+
# production
|
| 210 |
+
/build
|
| 211 |
+
|
| 212 |
+
# misc
|
| 213 |
+
.DS_Store
|
| 214 |
+
*.pem
|
| 215 |
+
|
| 216 |
+
# debug
|
| 217 |
+
npm-debug.log*
|
| 218 |
+
|
| 219 |
+
# env files
|
| 220 |
+
.env*
|
| 221 |
+
!.env.example
|
| 222 |
+
|
| 223 |
+
# vercel
|
| 224 |
+
.vercel
|
| 225 |
+
|
| 226 |
+
# typescript
|
| 227 |
+
*.tsbuildinfo
|
| 228 |
+
next-env.d.ts
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
**Step 2: Commit**
|
| 232 |
+
|
| 233 |
+
```bash
|
| 234 |
+
git add .gitignore && git commit -m "chore: configure .gitignore"
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
## Phase 2: Database Schema & Seed Data
|
| 240 |
+
|
| 241 |
+
### Task 2.1: Write Prisma schema
|
| 242 |
+
|
| 243 |
+
**Files:**
|
| 244 |
+
- Modify: `prisma/schema.prisma`
|
| 245 |
+
|
| 246 |
+
**Step 1: Write the full schema**
|
| 247 |
+
|
| 248 |
+
```prisma
|
| 249 |
+
generator client {
|
| 250 |
+
provider = "prisma-client-js"
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
datasource db {
|
| 254 |
+
provider = "sqlite"
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
model User {
|
| 258 |
+
id Int @id @default(autoincrement())
|
| 259 |
+
name String
|
| 260 |
+
level Int @default(1)
|
| 261 |
+
totalXp Int @default(0)
|
| 262 |
+
currentXp Int @default(0)
|
| 263 |
+
xpToNextLevel Int @default(100)
|
| 264 |
+
title String @default("Smooth Brain")
|
| 265 |
+
dailyGoalXp Int @default(100)
|
| 266 |
+
streak Int @default(0)
|
| 267 |
+
longestStreak Int @default(0)
|
| 268 |
+
streakFreezes Int @default(0)
|
| 269 |
+
lichessUsername String?
|
| 270 |
+
chesscomUsername String?
|
| 271 |
+
createdAt DateTime @default(now())
|
| 272 |
+
|
| 273 |
+
activities Activity[]
|
| 274 |
+
dailyLogs DailyLog[]
|
| 275 |
+
categorySkills CategorySkill[]
|
| 276 |
+
unlocks Unlock[]
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
model CategorySkill {
|
| 280 |
+
id Int @id @default(autoincrement())
|
| 281 |
+
userId Int
|
| 282 |
+
category String
|
| 283 |
+
level Int @default(1)
|
| 284 |
+
totalXp Int @default(0)
|
| 285 |
+
currentXp Int @default(0)
|
| 286 |
+
xpToNext Int @default(100)
|
| 287 |
+
|
| 288 |
+
user User @relation(fields: [userId], references: [id])
|
| 289 |
+
@@unique([userId, category])
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
model Activity {
|
| 293 |
+
id Int @id @default(autoincrement())
|
| 294 |
+
userId Int
|
| 295 |
+
category String
|
| 296 |
+
exerciseType String
|
| 297 |
+
description String
|
| 298 |
+
baseXp Int
|
| 299 |
+
qualityBonus Int @default(0)
|
| 300 |
+
isCriticalHit Boolean @default(false)
|
| 301 |
+
totalXp Int
|
| 302 |
+
score Float?
|
| 303 |
+
durationSecs Int?
|
| 304 |
+
metadata String?
|
| 305 |
+
createdAt DateTime @default(now())
|
| 306 |
+
|
| 307 |
+
user User @relation(fields: [userId], references: [id])
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
model DailyLog {
|
| 311 |
+
id Int @id @default(autoincrement())
|
| 312 |
+
userId Int
|
| 313 |
+
date DateTime
|
| 314 |
+
xpEarned Int @default(0)
|
| 315 |
+
activityCount Int @default(0)
|
| 316 |
+
goalMet Boolean @default(false)
|
| 317 |
+
streakFreezeUsed Boolean @default(false)
|
| 318 |
+
|
| 319 |
+
user User @relation(fields: [userId], references: [id])
|
| 320 |
+
@@unique([userId, date])
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
model SkillTreeNode {
|
| 324 |
+
id Int @id @default(autoincrement())
|
| 325 |
+
category String
|
| 326 |
+
name String
|
| 327 |
+
description String
|
| 328 |
+
levelRequired Int
|
| 329 |
+
parentNodeId Int?
|
| 330 |
+
nodeType String
|
| 331 |
+
|
| 332 |
+
parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id])
|
| 333 |
+
children SkillTreeNode[] @relation("NodeTree")
|
| 334 |
+
unlocks Unlock[]
|
| 335 |
+
|
| 336 |
+
@@unique([category, name])
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
model Unlock {
|
| 340 |
+
id Int @id @default(autoincrement())
|
| 341 |
+
userId Int
|
| 342 |
+
nodeId Int
|
| 343 |
+
unlockedAt DateTime @default(now())
|
| 344 |
+
|
| 345 |
+
user User @relation(fields: [userId], references: [id])
|
| 346 |
+
node SkillTreeNode @relation(fields: [nodeId], references: [id])
|
| 347 |
+
@@unique([userId, nodeId])
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
model ContentItem {
|
| 351 |
+
id Int @id @default(autoincrement())
|
| 352 |
+
category String
|
| 353 |
+
title String
|
| 354 |
+
content String
|
| 355 |
+
difficulty String
|
| 356 |
+
domain String
|
| 357 |
+
source String
|
| 358 |
+
metadata String?
|
| 359 |
+
createdAt DateTime @default(now())
|
| 360 |
+
}
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
**Step 2: Generate migration and client**
|
| 364 |
+
|
| 365 |
+
```bash
|
| 366 |
+
npx prisma migrate dev --name init
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
**Step 3: Commit**
|
| 370 |
+
|
| 371 |
+
```bash
|
| 372 |
+
git add prisma/ && git commit -m "feat: add full database schema with migration"
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
### Task 2.2: Create Prisma client singleton
|
| 376 |
+
|
| 377 |
+
**Files:**
|
| 378 |
+
- Create: `src/lib/db.ts`
|
| 379 |
+
|
| 380 |
+
**Step 1: Write the client**
|
| 381 |
+
|
| 382 |
+
```typescript
|
| 383 |
+
import { PrismaClient } from "@prisma/client";
|
| 384 |
+
|
| 385 |
+
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
|
| 386 |
+
|
| 387 |
+
export const prisma = globalForPrisma.prisma || new PrismaClient();
|
| 388 |
+
|
| 389 |
+
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
| 390 |
+
```
|
| 391 |
+
|
| 392 |
+
**Step 2: Commit**
|
| 393 |
+
|
| 394 |
+
```bash
|
| 395 |
+
git add src/lib/db.ts && git commit -m "feat: add Prisma client singleton"
|
| 396 |
+
```
|
| 397 |
+
|
| 398 |
+
### Task 2.3: Create seed script
|
| 399 |
+
|
| 400 |
+
**Files:**
|
| 401 |
+
- Create: `prisma/seed.ts`
|
| 402 |
+
|
| 403 |
+
**Step 1: Write seed with default user, category skills, and skill tree nodes**
|
| 404 |
+
|
| 405 |
+
```typescript
|
| 406 |
+
import { PrismaClient } from "@prisma/client";
|
| 407 |
+
|
| 408 |
+
const prisma = new PrismaClient();
|
| 409 |
+
|
| 410 |
+
const CATEGORIES = ["chess", "reading", "feynman", "logic", "critical-thinking", "quests"] as const;
|
| 411 |
+
|
| 412 |
+
const SKILL_TREE_NODES = [
|
| 413 |
+
// Chess
|
| 414 |
+
{ category: "chess", name: "Chess Initiate", description: "Begin your chess journey", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 415 |
+
{ category: "chess", name: "Puzzle Warrior", description: "Unlock 1200+ rated puzzles", levelRequired: 5, nodeType: "difficulty", parentNodeId: 1 },
|
| 416 |
+
{ category: "chess", name: "Endgame Student", description: "Unlock endgame puzzles", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 1 },
|
| 417 |
+
{ category: "chess", name: "Tactical Eye", description: "+10% Chess XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 2 },
|
| 418 |
+
{ category: "chess", name: "Puzzle Master", description: "Unlock 1800+ rated puzzles", levelRequired: 20, nodeType: "difficulty", parentNodeId: 2 },
|
| 419 |
+
{ category: "chess", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 3 },
|
| 420 |
+
{ category: "chess", name: "Grandmaster's Path", description: "+25% Chess XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 5 },
|
| 421 |
+
{ category: "chess", name: "Grandthinker", description: "Chess mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 7 },
|
| 422 |
+
|
| 423 |
+
// Reading
|
| 424 |
+
{ category: "reading", name: "Page Turner", description: "Begin reading exercises", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 425 |
+
{ category: "reading", name: "Deep Diver", description: "Unlock intermediate articles", levelRequired: 5, nodeType: "difficulty", parentNodeId: 9 },
|
| 426 |
+
{ category: "reading", name: "Speed Reader", description: "Unlock timed reading challenges", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 9 },
|
| 427 |
+
{ category: "reading", name: "Scholar", description: "Unlock advanced/academic content", levelRequired: 10, nodeType: "difficulty", parentNodeId: 10 },
|
| 428 |
+
{ category: "reading", name: "Focus Boost", description: "+10% Reading XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 12 },
|
| 429 |
+
{ category: "reading", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 11 },
|
| 430 |
+
{ category: "reading", name: "Concentration Master", description: "+25% Reading XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 13 },
|
| 431 |
+
{ category: "reading", name: "Deep Diver", description: "Reading mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 15 },
|
| 432 |
+
|
| 433 |
+
// Feynman
|
| 434 |
+
{ category: "feynman", name: "Curious Mind", description: "Begin Feynman challenges", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 435 |
+
{ category: "feynman", name: "Explainer", description: "Unlock intermediate topics", levelRequired: 5, nodeType: "difficulty", parentNodeId: 17 },
|
| 436 |
+
{ category: "feynman", name: "Timed Explains", description: "Unlock timed mode", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 17 },
|
| 437 |
+
{ category: "feynman", name: "Professor", description: "Unlock expert topics", levelRequired: 15, nodeType: "difficulty", parentNodeId: 18 },
|
| 438 |
+
{ category: "feynman", name: "Clarity Boost", description: "+10% Feynman XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 19 },
|
| 439 |
+
{ category: "feynman", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 18 },
|
| 440 |
+
{ category: "feynman", name: "Mastery Boost", description: "+25% Feynman XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 20 },
|
| 441 |
+
{ category: "feynman", name: "The Explainer", description: "Feynman mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 23 },
|
| 442 |
+
|
| 443 |
+
// Logic
|
| 444 |
+
{ category: "logic", name: "Logical Mind", description: "Begin logic puzzles", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 445 |
+
{ category: "logic", name: "Medium Puzzles", description: "Unlock medium difficulty", levelRequired: 5, nodeType: "difficulty", parentNodeId: 25 },
|
| 446 |
+
{ category: "logic", name: "Sequence Master", description: "Unlock number sequences", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 25 },
|
| 447 |
+
{ category: "logic", name: "Hard Puzzles", description: "Unlock hard difficulty", levelRequired: 10, nodeType: "difficulty", parentNodeId: 26 },
|
| 448 |
+
{ category: "logic", name: "Logic Boost", description: "+10% Logic XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 27 },
|
| 449 |
+
{ category: "logic", name: "Expert Puzzles", description: "Unlock expert difficulty", levelRequired: 20, nodeType: "difficulty", parentNodeId: 28 },
|
| 450 |
+
{ category: "logic", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 28 },
|
| 451 |
+
{ category: "logic", name: "Mastery Boost", description: "+25% Logic XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 30 },
|
| 452 |
+
{ category: "logic", name: "Vulcan", description: "Logic mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 32 },
|
| 453 |
+
|
| 454 |
+
// Critical Thinking
|
| 455 |
+
{ category: "critical-thinking", name: "Flaw Finder: Easy", description: "Identify basic logical fallacies", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 456 |
+
{ category: "critical-thinking", name: "Flaw Finder: Medium", description: "Harder fallacy detection", levelRequired: 3, nodeType: "difficulty", parentNodeId: 34 },
|
| 457 |
+
{ category: "critical-thinking", name: "Steelman: Unlocked", description: "Construct strongest opposing arguments", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 35 },
|
| 458 |
+
{ category: "critical-thinking", name: "Flaw Finder: Hard", description: "Subtle fallacies and weak reasoning", levelRequired: 5, nodeType: "difficulty", parentNodeId: 35 },
|
| 459 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Unlocked", description: "Argue against your own positions", levelRequired: 10, nodeType: "exercise-type", parentNodeId: 36 },
|
| 460 |
+
{ category: "critical-thinking", name: "Steelman: Medium", description: "More nuanced positions", levelRequired: 10, nodeType: "difficulty", parentNodeId: 36 },
|
| 461 |
+
{ category: "critical-thinking", name: "Critical Boost", description: "+10% Critical Thinking XP", levelRequired: 10, nodeType: "multiplier", parentNodeId: 39 },
|
| 462 |
+
{ category: "critical-thinking", name: "Flaw Finder: Expert", description: "Professional-level analysis", levelRequired: 15, nodeType: "difficulty", parentNodeId: 37 },
|
| 463 |
+
{ category: "critical-thinking", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 15, nodeType: "streak-shield", parentNodeId: 41 },
|
| 464 |
+
{ category: "critical-thinking", name: "Steelman: Hard", description: "Complex multi-faceted positions", levelRequired: 20, nodeType: "difficulty", parentNodeId: 39 },
|
| 465 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Medium", description: "Harder positions to argue against", levelRequired: 20, nodeType: "difficulty", parentNodeId: 38 },
|
| 466 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Hard", description: "Expert-level contrarian arguments", levelRequired: 30, nodeType: "difficulty", parentNodeId: 44 },
|
| 467 |
+
{ category: "critical-thinking", name: "Mastery Boost", description: "+25% Critical Thinking XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 45 },
|
| 468 |
+
{ category: "critical-thinking", name: "Steel Trap", description: "Critical Thinking mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 46 },
|
| 469 |
+
|
| 470 |
+
// Skill Quests
|
| 471 |
+
{ category: "quests", name: "Apprentice", description: "Begin skill quests", levelRequired: 1, nodeType: "difficulty", parentNodeId: null },
|
| 472 |
+
{ category: "quests", name: "Intermediate Quests", description: "Unlock intermediate lessons", levelRequired: 5, nodeType: "difficulty", parentNodeId: 48 },
|
| 473 |
+
{ category: "quests", name: "Spaced Repetition", description: "Unlock review sessions", levelRequired: 5, nodeType: "exercise-type", parentNodeId: 48 },
|
| 474 |
+
{ category: "quests", name: "Advanced Quests", description: "Unlock advanced lessons", levelRequired: 15, nodeType: "difficulty", parentNodeId: 49 },
|
| 475 |
+
{ category: "quests", name: "Quest Boost", description: "+10% Quest XP", levelRequired: 15, nodeType: "multiplier", parentNodeId: 50 },
|
| 476 |
+
{ category: "quests", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentNodeId: 50 },
|
| 477 |
+
{ category: "quests", name: "Mastery Boost", description: "+25% Quest XP", levelRequired: 30, nodeType: "multiplier", parentNodeId: 51 },
|
| 478 |
+
{ category: "quests", name: "Polymath", description: "Skill Quests mastery title", levelRequired: 50, nodeType: "cosmetic", parentNodeId: 54 },
|
| 479 |
+
];
|
| 480 |
+
|
| 481 |
+
async function main() {
|
| 482 |
+
// Create default user
|
| 483 |
+
const user = await prisma.user.upsert({
|
| 484 |
+
where: { id: 1 },
|
| 485 |
+
update: {},
|
| 486 |
+
create: { name: "Player One" },
|
| 487 |
+
});
|
| 488 |
+
|
| 489 |
+
// Create category skills
|
| 490 |
+
for (const category of CATEGORIES) {
|
| 491 |
+
await prisma.categorySkill.upsert({
|
| 492 |
+
where: { userId_category: { userId: user.id, category } },
|
| 493 |
+
update: {},
|
| 494 |
+
create: { userId: user.id, category },
|
| 495 |
+
});
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
// Create skill tree nodes (without parent references first, then update)
|
| 499 |
+
for (const node of SKILL_TREE_NODES) {
|
| 500 |
+
await prisma.skillTreeNode.upsert({
|
| 501 |
+
where: { category_name: { category: node.category, name: node.name } },
|
| 502 |
+
update: {},
|
| 503 |
+
create: {
|
| 504 |
+
category: node.category,
|
| 505 |
+
name: node.name,
|
| 506 |
+
description: node.description,
|
| 507 |
+
levelRequired: node.levelRequired,
|
| 508 |
+
nodeType: node.nodeType,
|
| 509 |
+
parentNodeId: node.parentNodeId,
|
| 510 |
+
},
|
| 511 |
+
});
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
console.log("Seed complete.");
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
main()
|
| 518 |
+
.catch((e) => { console.error(e); process.exit(1); })
|
| 519 |
+
.finally(async () => { await prisma.$disconnect(); });
|
| 520 |
+
```
|
| 521 |
+
|
| 522 |
+
**Step 2: Run seed**
|
| 523 |
+
|
| 524 |
+
```bash
|
| 525 |
+
npx prisma db seed
|
| 526 |
+
```
|
| 527 |
+
|
| 528 |
+
**Step 3: Commit**
|
| 529 |
+
|
| 530 |
+
```bash
|
| 531 |
+
git add prisma/seed.ts && git commit -m "feat: add seed script with user, skills, and skill tree"
|
| 532 |
+
```
|
| 533 |
+
|
| 534 |
+
---
|
| 535 |
+
|
| 536 |
+
## Phase 3: XP & Progression Engine
|
| 537 |
+
|
| 538 |
+
### Task 3.1: Write XP config
|
| 539 |
+
|
| 540 |
+
**Files:**
|
| 541 |
+
- Create: `src/config/xp.ts`
|
| 542 |
+
|
| 543 |
+
**Step 1: Write the failing test**
|
| 544 |
+
|
| 545 |
+
Create `src/config/__tests__/xp.test.ts`:
|
| 546 |
+
|
| 547 |
+
```typescript
|
| 548 |
+
import { xpForLevel, EXERCISE_XP, CRITICAL_HIT_CHANCE, CRITICAL_HIT_MULTIPLIER, CATEGORIES } from "@/config/xp";
|
| 549 |
+
|
| 550 |
+
describe("xpForLevel", () => {
|
| 551 |
+
it("returns 100 for level 2", () => {
|
| 552 |
+
expect(xpForLevel(2)).toBe(100);
|
| 553 |
+
});
|
| 554 |
+
it("scales exponentially", () => {
|
| 555 |
+
expect(xpForLevel(10)).toBeGreaterThan(xpForLevel(5));
|
| 556 |
+
});
|
| 557 |
+
it("returns approximately 1500 at level 50", () => {
|
| 558 |
+
const xp = xpForLevel(50);
|
| 559 |
+
expect(xp).toBeGreaterThanOrEqual(1200);
|
| 560 |
+
expect(xp).toBeLessThanOrEqual(1800);
|
| 561 |
+
});
|
| 562 |
+
});
|
| 563 |
+
|
| 564 |
+
describe("EXERCISE_XP", () => {
|
| 565 |
+
it("has entries for all categories", () => {
|
| 566 |
+
for (const cat of CATEGORIES) {
|
| 567 |
+
expect(EXERCISE_XP[cat]).toBeDefined();
|
| 568 |
+
expect(EXERCISE_XP[cat].baseXp).toBeGreaterThan(0);
|
| 569 |
+
expect(EXERCISE_XP[cat].maxQualityBonus).toBeGreaterThanOrEqual(0);
|
| 570 |
+
}
|
| 571 |
+
});
|
| 572 |
+
});
|
| 573 |
+
|
| 574 |
+
describe("critical hit", () => {
|
| 575 |
+
it("has 10% chance and 2x multiplier", () => {
|
| 576 |
+
expect(CRITICAL_HIT_CHANCE).toBe(0.1);
|
| 577 |
+
expect(CRITICAL_HIT_MULTIPLIER).toBe(2);
|
| 578 |
+
});
|
| 579 |
+
});
|
| 580 |
+
```
|
| 581 |
+
|
| 582 |
+
**Step 2: Run test to verify it fails**
|
| 583 |
+
|
| 584 |
+
```bash
|
| 585 |
+
npm test -- src/config/__tests__/xp.test.ts
|
| 586 |
+
```
|
| 587 |
+
|
| 588 |
+
Expected: FAIL — module not found.
|
| 589 |
+
|
| 590 |
+
**Step 3: Write implementation**
|
| 591 |
+
|
| 592 |
+
```typescript
|
| 593 |
+
export const CATEGORIES = [
|
| 594 |
+
"chess",
|
| 595 |
+
"reading",
|
| 596 |
+
"feynman",
|
| 597 |
+
"logic",
|
| 598 |
+
"critical-thinking",
|
| 599 |
+
"quests",
|
| 600 |
+
] as const;
|
| 601 |
+
|
| 602 |
+
export type Category = (typeof CATEGORIES)[number];
|
| 603 |
+
|
| 604 |
+
export const CATEGORY_LABELS: Record<Category, string> = {
|
| 605 |
+
chess: "Chess",
|
| 606 |
+
reading: "Deep Reading",
|
| 607 |
+
feynman: "Feynman",
|
| 608 |
+
logic: "Logic Puzzles",
|
| 609 |
+
"critical-thinking": "Critical Thinking",
|
| 610 |
+
quests: "Skill Quests",
|
| 611 |
+
};
|
| 612 |
+
|
| 613 |
+
export const CATEGORY_COLORS: Record<Category, string> = {
|
| 614 |
+
chess: "#f59e0b", // amber
|
| 615 |
+
reading: "#10b981", // emerald
|
| 616 |
+
feynman: "#06b6d4", // cyan
|
| 617 |
+
logic: "#8b5cf6", // violet
|
| 618 |
+
"critical-thinking": "#f43f5e", // rose
|
| 619 |
+
quests: "#f97316", // orange
|
| 620 |
+
};
|
| 621 |
+
|
| 622 |
+
export const EXERCISE_XP: Record<Category, { baseXp: number; maxQualityBonus: number }> = {
|
| 623 |
+
chess: { baseXp: 20, maxQualityBonus: 20 },
|
| 624 |
+
reading: { baseXp: 30, maxQualityBonus: 30 },
|
| 625 |
+
feynman: { baseXp: 40, maxQualityBonus: 40 },
|
| 626 |
+
logic: { baseXp: 15, maxQualityBonus: 25 },
|
| 627 |
+
"critical-thinking": { baseXp: 50, maxQualityBonus: 30 },
|
| 628 |
+
quests: { baseXp: 25, maxQualityBonus: 25 },
|
| 629 |
+
};
|
| 630 |
+
|
| 631 |
+
export const CRITICAL_HIT_CHANCE = 0.1;
|
| 632 |
+
export const CRITICAL_HIT_MULTIPLIER = 2;
|
| 633 |
+
|
| 634 |
+
// Attempt-to-next-level XP curve: exponential scaling
|
| 635 |
+
// Level 2 = 100, Level 10 ~ 350, Level 50 ~ 1500
|
| 636 |
+
export function xpForLevel(level: number): number {
|
| 637 |
+
return Math.round(100 * Math.pow(level / 2, 0.8));
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
// Cumulative XP to reach a given level
|
| 641 |
+
export function totalXpForLevel(level: number): number {
|
| 642 |
+
let total = 0;
|
| 643 |
+
for (let i = 2; i <= level; i++) {
|
| 644 |
+
total += xpForLevel(i);
|
| 645 |
+
}
|
| 646 |
+
return total;
|
| 647 |
+
}
|
| 648 |
+
```
|
| 649 |
+
|
| 650 |
+
**Step 4: Run tests**
|
| 651 |
+
|
| 652 |
+
```bash
|
| 653 |
+
npm test -- src/config/__tests__/xp.test.ts
|
| 654 |
+
```
|
| 655 |
+
|
| 656 |
+
Expected: PASS
|
| 657 |
+
|
| 658 |
+
**Step 5: Commit**
|
| 659 |
+
|
| 660 |
+
```bash
|
| 661 |
+
git add src/config/xp.ts src/config/__tests__/xp.test.ts
|
| 662 |
+
git commit -m "feat: add XP config with level curve and exercise XP table"
|
| 663 |
+
```
|
| 664 |
+
|
| 665 |
+
### Task 3.2: Write XP calculation engine
|
| 666 |
+
|
| 667 |
+
**Files:**
|
| 668 |
+
- Create: `src/lib/xp.ts`
|
| 669 |
+
- Create: `src/lib/__tests__/xp.test.ts`
|
| 670 |
+
|
| 671 |
+
**Step 1: Write failing tests**
|
| 672 |
+
|
| 673 |
+
```typescript
|
| 674 |
+
import { calculateXpGain, rollCriticalHit, calculateQualityBonus } from "@/lib/xp";
|
| 675 |
+
|
| 676 |
+
describe("calculateQualityBonus", () => {
|
| 677 |
+
it("returns 0 for score 0", () => {
|
| 678 |
+
expect(calculateQualityBonus(0, 30)).toBe(0);
|
| 679 |
+
});
|
| 680 |
+
it("returns maxBonus for score 1", () => {
|
| 681 |
+
expect(calculateQualityBonus(1, 30)).toBe(30);
|
| 682 |
+
});
|
| 683 |
+
it("returns proportional bonus", () => {
|
| 684 |
+
expect(calculateQualityBonus(0.5, 30)).toBe(15);
|
| 685 |
+
});
|
| 686 |
+
});
|
| 687 |
+
|
| 688 |
+
describe("calculateXpGain", () => {
|
| 689 |
+
it("returns base + quality bonus without critical hit", () => {
|
| 690 |
+
const result = calculateXpGain({
|
| 691 |
+
baseXp: 20,
|
| 692 |
+
qualityScore: 0.5,
|
| 693 |
+
maxQualityBonus: 20,
|
| 694 |
+
isCriticalHit: false,
|
| 695 |
+
multiplierPercent: 0,
|
| 696 |
+
});
|
| 697 |
+
expect(result.baseXp).toBe(20);
|
| 698 |
+
expect(result.qualityBonus).toBe(10);
|
| 699 |
+
expect(result.totalXp).toBe(30);
|
| 700 |
+
});
|
| 701 |
+
|
| 702 |
+
it("doubles on critical hit", () => {
|
| 703 |
+
const result = calculateXpGain({
|
| 704 |
+
baseXp: 20,
|
| 705 |
+
qualityScore: 0,
|
| 706 |
+
maxQualityBonus: 20,
|
| 707 |
+
isCriticalHit: true,
|
| 708 |
+
multiplierPercent: 0,
|
| 709 |
+
});
|
| 710 |
+
expect(result.totalXp).toBe(40);
|
| 711 |
+
expect(result.isCriticalHit).toBe(true);
|
| 712 |
+
});
|
| 713 |
+
|
| 714 |
+
it("applies skill tree multiplier", () => {
|
| 715 |
+
const result = calculateXpGain({
|
| 716 |
+
baseXp: 20,
|
| 717 |
+
qualityScore: 0,
|
| 718 |
+
maxQualityBonus: 20,
|
| 719 |
+
isCriticalHit: false,
|
| 720 |
+
multiplierPercent: 10,
|
| 721 |
+
});
|
| 722 |
+
expect(result.totalXp).toBe(22);
|
| 723 |
+
});
|
| 724 |
+
});
|
| 725 |
+
|
| 726 |
+
describe("rollCriticalHit", () => {
|
| 727 |
+
it("returns a boolean", () => {
|
| 728 |
+
expect(typeof rollCriticalHit()).toBe("boolean");
|
| 729 |
+
});
|
| 730 |
+
});
|
| 731 |
+
```
|
| 732 |
+
|
| 733 |
+
**Step 2: Run test to verify fail**
|
| 734 |
+
|
| 735 |
+
```bash
|
| 736 |
+
npm test -- src/lib/__tests__/xp.test.ts
|
| 737 |
+
```
|
| 738 |
+
|
| 739 |
+
**Step 3: Write implementation**
|
| 740 |
+
|
| 741 |
+
```typescript
|
| 742 |
+
import { CRITICAL_HIT_CHANCE, CRITICAL_HIT_MULTIPLIER } from "@/config/xp";
|
| 743 |
+
|
| 744 |
+
export function calculateQualityBonus(score: number, maxBonus: number): number {
|
| 745 |
+
return Math.round(score * maxBonus);
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
export function rollCriticalHit(): boolean {
|
| 749 |
+
return Math.random() < CRITICAL_HIT_CHANCE;
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
export interface XpGainInput {
|
| 753 |
+
baseXp: number;
|
| 754 |
+
qualityScore: number; // 0-1
|
| 755 |
+
maxQualityBonus: number;
|
| 756 |
+
isCriticalHit: boolean;
|
| 757 |
+
multiplierPercent: number; // from skill tree nodes, e.g. 10 = +10%
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
export interface XpGainResult {
|
| 761 |
+
baseXp: number;
|
| 762 |
+
qualityBonus: number;
|
| 763 |
+
isCriticalHit: boolean;
|
| 764 |
+
multiplierBonus: number;
|
| 765 |
+
totalXp: number;
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
export function calculateXpGain(input: XpGainInput): XpGainResult {
|
| 769 |
+
const qualityBonus = calculateQualityBonus(input.qualityScore, input.maxQualityBonus);
|
| 770 |
+
let subtotal = input.baseXp + qualityBonus;
|
| 771 |
+
|
| 772 |
+
if (input.isCriticalHit) {
|
| 773 |
+
subtotal = subtotal * CRITICAL_HIT_MULTIPLIER;
|
| 774 |
+
}
|
| 775 |
+
|
| 776 |
+
const multiplierBonus = Math.round(subtotal * (input.multiplierPercent / 100));
|
| 777 |
+
const totalXp = subtotal + multiplierBonus;
|
| 778 |
+
|
| 779 |
+
return {
|
| 780 |
+
baseXp: input.baseXp,
|
| 781 |
+
qualityBonus,
|
| 782 |
+
isCriticalHit: input.isCriticalHit,
|
| 783 |
+
multiplierBonus,
|
| 784 |
+
totalXp,
|
| 785 |
+
};
|
| 786 |
+
}
|
| 787 |
+
```
|
| 788 |
+
|
| 789 |
+
**Step 4: Run tests**
|
| 790 |
+
|
| 791 |
+
```bash
|
| 792 |
+
npm test -- src/lib/__tests__/xp.test.ts
|
| 793 |
+
```
|
| 794 |
+
|
| 795 |
+
Expected: PASS
|
| 796 |
+
|
| 797 |
+
**Step 5: Commit**
|
| 798 |
+
|
| 799 |
+
```bash
|
| 800 |
+
git add src/lib/xp.ts src/lib/__tests__/xp.test.ts
|
| 801 |
+
git commit -m "feat: add XP calculation engine with quality bonuses and critical hits"
|
| 802 |
+
```
|
| 803 |
+
|
| 804 |
+
### Task 3.3: Write progression service (level-up, streak, daily log)
|
| 805 |
+
|
| 806 |
+
**Files:**
|
| 807 |
+
- Create: `src/lib/progression.ts`
|
| 808 |
+
- Create: `src/lib/__tests__/progression.test.ts`
|
| 809 |
+
|
| 810 |
+
**Step 1: Write failing tests**
|
| 811 |
+
|
| 812 |
+
```typescript
|
| 813 |
+
import { checkLevelUp, shouldStreakBreak } from "@/lib/progression";
|
| 814 |
+
|
| 815 |
+
describe("checkLevelUp", () => {
|
| 816 |
+
it("returns no level up when xp insufficient", () => {
|
| 817 |
+
const result = checkLevelUp({ currentXp: 50, xpToNextLevel: 100, level: 1 });
|
| 818 |
+
expect(result.levelsGained).toBe(0);
|
| 819 |
+
expect(result.newLevel).toBe(1);
|
| 820 |
+
});
|
| 821 |
+
|
| 822 |
+
it("returns level up when xp exceeds threshold", () => {
|
| 823 |
+
const result = checkLevelUp({ currentXp: 150, xpToNextLevel: 100, level: 1 });
|
| 824 |
+
expect(result.levelsGained).toBe(1);
|
| 825 |
+
expect(result.newLevel).toBe(2);
|
| 826 |
+
expect(result.remainingXp).toBeLessThan(result.newXpToNextLevel);
|
| 827 |
+
});
|
| 828 |
+
|
| 829 |
+
it("handles multi-level jumps", () => {
|
| 830 |
+
const result = checkLevelUp({ currentXp: 500, xpToNextLevel: 100, level: 1 });
|
| 831 |
+
expect(result.levelsGained).toBeGreaterThan(1);
|
| 832 |
+
});
|
| 833 |
+
});
|
| 834 |
+
|
| 835 |
+
describe("shouldStreakBreak", () => {
|
| 836 |
+
it("returns false if goal was met today", () => {
|
| 837 |
+
expect(shouldStreakBreak({ goalMet: true, hasStreakFreeze: false })).toBe(false);
|
| 838 |
+
});
|
| 839 |
+
|
| 840 |
+
it("returns false if streak freeze available and goal not met", () => {
|
| 841 |
+
expect(shouldStreakBreak({ goalMet: false, hasStreakFreeze: true })).toBe(false);
|
| 842 |
+
});
|
| 843 |
+
|
| 844 |
+
it("returns true if goal not met and no freeze", () => {
|
| 845 |
+
expect(shouldStreakBreak({ goalMet: false, hasStreakFreeze: false })).toBe(true);
|
| 846 |
+
});
|
| 847 |
+
});
|
| 848 |
+
```
|
| 849 |
+
|
| 850 |
+
**Step 2: Run test to verify fail**
|
| 851 |
+
|
| 852 |
+
```bash
|
| 853 |
+
npm test -- src/lib/__tests__/progression.test.ts
|
| 854 |
+
```
|
| 855 |
+
|
| 856 |
+
**Step 3: Write implementation**
|
| 857 |
+
|
| 858 |
+
```typescript
|
| 859 |
+
import { xpForLevel } from "@/config/xp";
|
| 860 |
+
|
| 861 |
+
interface LevelUpInput {
|
| 862 |
+
currentXp: number;
|
| 863 |
+
xpToNextLevel: number;
|
| 864 |
+
level: number;
|
| 865 |
+
}
|
| 866 |
+
|
| 867 |
+
interface LevelUpResult {
|
| 868 |
+
levelsGained: number;
|
| 869 |
+
newLevel: number;
|
| 870 |
+
remainingXp: number;
|
| 871 |
+
newXpToNextLevel: number;
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
export function checkLevelUp(input: LevelUpInput): LevelUpResult {
|
| 875 |
+
let { currentXp, level } = input;
|
| 876 |
+
let xpToNext = input.xpToNextLevel;
|
| 877 |
+
let levelsGained = 0;
|
| 878 |
+
|
| 879 |
+
while (currentXp >= xpToNext) {
|
| 880 |
+
currentXp -= xpToNext;
|
| 881 |
+
level++;
|
| 882 |
+
levelsGained++;
|
| 883 |
+
xpToNext = xpForLevel(level + 1);
|
| 884 |
+
}
|
| 885 |
+
|
| 886 |
+
return {
|
| 887 |
+
levelsGained,
|
| 888 |
+
newLevel: level,
|
| 889 |
+
remainingXp: currentXp,
|
| 890 |
+
newXpToNextLevel: xpToNext,
|
| 891 |
+
};
|
| 892 |
+
}
|
| 893 |
+
|
| 894 |
+
interface StreakInput {
|
| 895 |
+
goalMet: boolean;
|
| 896 |
+
hasStreakFreeze: boolean;
|
| 897 |
+
}
|
| 898 |
+
|
| 899 |
+
export function shouldStreakBreak(input: StreakInput): boolean {
|
| 900 |
+
if (input.goalMet) return false;
|
| 901 |
+
if (input.hasStreakFreeze) return false;
|
| 902 |
+
return true;
|
| 903 |
+
}
|
| 904 |
+
```
|
| 905 |
+
|
| 906 |
+
**Step 4: Run tests**
|
| 907 |
+
|
| 908 |
+
```bash
|
| 909 |
+
npm test -- src/lib/__tests__/progression.test.ts
|
| 910 |
+
```
|
| 911 |
+
|
| 912 |
+
Expected: PASS
|
| 913 |
+
|
| 914 |
+
**Step 5: Commit**
|
| 915 |
+
|
| 916 |
+
```bash
|
| 917 |
+
git add src/lib/progression.ts src/lib/__tests__/progression.test.ts
|
| 918 |
+
git commit -m "feat: add progression engine with level-up and streak logic"
|
| 919 |
+
```
|
| 920 |
+
|
| 921 |
+
---
|
| 922 |
+
|
| 923 |
+
## Phase 4: Global Layout & Theme
|
| 924 |
+
|
| 925 |
+
### Task 4.1: Create globals.css with RotNot theme
|
| 926 |
+
|
| 927 |
+
**Files:**
|
| 928 |
+
- Modify: `src/app/globals.css`
|
| 929 |
+
|
| 930 |
+
**Step 1: Write dark theme with category colors and glassmorphism utilities**
|
| 931 |
+
|
| 932 |
+
Use job-quest's structure as base but with RotNot's navy/charcoal palette, category accent colors, and glassmorphism CSS utilities. Key differences from job-quest:
|
| 933 |
+
- Base surface colors shifted to navy (`#0a0e1a`, `#111827`, `#1a2035`, `#232d45`)
|
| 934 |
+
- Category colors as CSS vars: `--color-chess`, `--color-reading`, etc.
|
| 935 |
+
- Glassmorphism utility class `.glass` with `backdrop-filter: blur(12px)` and semi-transparent backgrounds
|
| 936 |
+
- Monospace font var for stats display
|
| 937 |
+
|
| 938 |
+
**Step 2: Commit**
|
| 939 |
+
|
| 940 |
+
```bash
|
| 941 |
+
git add src/app/globals.css && git commit -m "feat: add RotNot dark theme with category colors and glassmorphism"
|
| 942 |
+
```
|
| 943 |
+
|
| 944 |
+
### Task 4.2: Create sidebar navigation
|
| 945 |
+
|
| 946 |
+
**Files:**
|
| 947 |
+
- Create: `src/components/sidebar-nav.tsx`
|
| 948 |
+
|
| 949 |
+
**Step 1: Build sidebar** with links to all routes (`/`, `/chess`, `/reading`, `/feynman`, `/logic`, `/critical-thinking`, `/quests`, `/profile`). Each link shows category icon (from lucide-react) and label, highlighted with category color when active. Use `usePathname()` for active state.
|
| 950 |
+
|
| 951 |
+
**Step 2: Commit**
|
| 952 |
+
|
| 953 |
+
```bash
|
| 954 |
+
git add src/components/sidebar-nav.tsx && git commit -m "feat: add sidebar navigation with category icons"
|
| 955 |
+
```
|
| 956 |
+
|
| 957 |
+
### Task 4.3: Create root layout
|
| 958 |
+
|
| 959 |
+
**Files:**
|
| 960 |
+
- Modify: `src/app/layout.tsx`
|
| 961 |
+
|
| 962 |
+
**Step 1: Write layout** with dark mode, Inter + JetBrains Mono fonts, sidebar, and main content area. Borrow structure from job-quest but use RotNot theme.
|
| 963 |
+
|
| 964 |
+
```typescript
|
| 965 |
+
import type { Metadata } from "next";
|
| 966 |
+
import { Inter, JetBrains_Mono } from "next/font/google";
|
| 967 |
+
import "./globals.css";
|
| 968 |
+
import { SidebarNav } from "@/components/sidebar-nav";
|
| 969 |
+
|
| 970 |
+
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
|
| 971 |
+
const jetbrains = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
| 972 |
+
|
| 973 |
+
export const metadata: Metadata = {
|
| 974 |
+
title: "RotNot",
|
| 975 |
+
description: "Fight brain rot. Level up your mind.",
|
| 976 |
+
};
|
| 977 |
+
|
| 978 |
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
| 979 |
+
return (
|
| 980 |
+
<html lang="en" className="dark">
|
| 981 |
+
<body className={`${inter.variable} ${jetbrains.variable} font-sans bg-[var(--surface-0)] text-[rgba(255,255,255,0.87)] min-h-screen`}>
|
| 982 |
+
<div className="flex min-h-screen">
|
| 983 |
+
<SidebarNav />
|
| 984 |
+
<main className="flex-1 p-6 overflow-auto">
|
| 985 |
+
{children}
|
| 986 |
+
</main>
|
| 987 |
+
</div>
|
| 988 |
+
</body>
|
| 989 |
+
</html>
|
| 990 |
+
);
|
| 991 |
+
}
|
| 992 |
+
```
|
| 993 |
+
|
| 994 |
+
**Step 2: Commit**
|
| 995 |
+
|
| 996 |
+
```bash
|
| 997 |
+
git add src/app/layout.tsx && git commit -m "feat: add root layout with sidebar and fonts"
|
| 998 |
+
```
|
| 999 |
+
|
| 1000 |
+
---
|
| 1001 |
+
|
| 1002 |
+
## Phase 5: Dashboard
|
| 1003 |
+
|
| 1004 |
+
### Task 5.1: Create dashboard data fetching
|
| 1005 |
+
|
| 1006 |
+
**Files:**
|
| 1007 |
+
- Create: `src/app/api/dashboard/route.ts`
|
| 1008 |
+
|
| 1009 |
+
**Step 1: Build GET handler** that returns: user stats (level, xp, streak, title), today's daily log (xp earned, goal progress), category skills (all 6 with levels), and recent activities (last 10).
|
| 1010 |
+
|
| 1011 |
+
**Step 2: Commit**
|
| 1012 |
+
|
| 1013 |
+
### Task 5.2: Create daily ring component
|
| 1014 |
+
|
| 1015 |
+
**Files:**
|
| 1016 |
+
- Create: `src/components/dashboard/daily-ring.tsx`
|
| 1017 |
+
|
| 1018 |
+
**Step 1: Build circular SVG progress ring** showing XP earned today vs. daily goal. Animate with framer-motion. Show percentage and raw numbers inside the ring. Use glassmorphism card wrapper.
|
| 1019 |
+
|
| 1020 |
+
**Step 2: Commit**
|
| 1021 |
+
|
| 1022 |
+
### Task 5.3: Create streak display component
|
| 1023 |
+
|
| 1024 |
+
**Files:**
|
| 1025 |
+
- Create: `src/components/dashboard/streak-display.tsx`
|
| 1026 |
+
|
| 1027 |
+
**Step 1: Build streak counter** with flame icon, current streak number, longest streak, and streak freeze count. Pulsing animation when streak is active.
|
| 1028 |
+
|
| 1029 |
+
**Step 2: Commit**
|
| 1030 |
+
|
| 1031 |
+
### Task 5.4: Create category cards grid
|
| 1032 |
+
|
| 1033 |
+
**Files:**
|
| 1034 |
+
- Create: `src/components/dashboard/category-card.tsx`
|
| 1035 |
+
|
| 1036 |
+
**Step 1: Build category card** showing: category icon + label, current level, XP progress bar (colored by category), and "Start" button linking to exercise page. Grid of 6 cards on dashboard.
|
| 1037 |
+
|
| 1038 |
+
**Step 2: Commit**
|
| 1039 |
+
|
| 1040 |
+
### Task 5.5: Create activity feed
|
| 1041 |
+
|
| 1042 |
+
**Files:**
|
| 1043 |
+
- Create: `src/components/dashboard/activity-feed.tsx`
|
| 1044 |
+
|
| 1045 |
+
**Step 1: Build scrollable feed** of recent activities. Each entry shows: category badge (colored), exercise type, XP earned (with critical hit highlight), and relative timestamp. Limit to 10 entries.
|
| 1046 |
+
|
| 1047 |
+
**Step 2: Commit**
|
| 1048 |
+
|
| 1049 |
+
### Task 5.6: Create weekly heatmap
|
| 1050 |
+
|
| 1051 |
+
**Files:**
|
| 1052 |
+
- Create: `src/components/dashboard/weekly-heatmap.tsx`
|
| 1053 |
+
|
| 1054 |
+
**Step 1: Build 7-column grid** (Mon-Sun) showing activity density for current week. Color intensity based on XP earned that day. GitHub contribution style.
|
| 1055 |
+
|
| 1056 |
+
**Step 2: Commit**
|
| 1057 |
+
|
| 1058 |
+
### Task 5.7: Assemble dashboard page
|
| 1059 |
+
|
| 1060 |
+
**Files:**
|
| 1061 |
+
- Modify: `src/app/page.tsx`
|
| 1062 |
+
|
| 1063 |
+
**Step 1: Compose all dashboard components** into the page. Layout: daily ring + streak at top, category cards grid in middle, activity feed + heatmap at bottom.
|
| 1064 |
+
|
| 1065 |
+
**Step 2: Verify build**
|
| 1066 |
+
|
| 1067 |
+
```bash
|
| 1068 |
+
npm run build
|
| 1069 |
+
```
|
| 1070 |
+
|
| 1071 |
+
**Step 3: Commit**
|
| 1072 |
+
|
| 1073 |
+
```bash
|
| 1074 |
+
git add -A && git commit -m "feat: complete dashboard with daily ring, streak, categories, feed, heatmap"
|
| 1075 |
+
```
|
| 1076 |
+
|
| 1077 |
+
---
|
| 1078 |
+
|
| 1079 |
+
## Phase 6: Logic Puzzles (simplest exercise — no external APIs)
|
| 1080 |
+
|
| 1081 |
+
### Task 6.1: Sudoku generator
|
| 1082 |
+
|
| 1083 |
+
**Files:**
|
| 1084 |
+
- Create: `src/lib/puzzles/sudoku.ts`
|
| 1085 |
+
- Create: `src/lib/puzzles/__tests__/sudoku.test.ts`
|
| 1086 |
+
|
| 1087 |
+
**Step 1: Write failing tests** for `generateSudoku(difficulty)` returning a `{ puzzle: number[][], solution: number[][] }` and `validateSudoku(puzzle, solution)`.
|
| 1088 |
+
|
| 1089 |
+
**Step 2: Implement** a backtracking Sudoku generator that creates valid puzzles with configurable difficulty (number of given cells).
|
| 1090 |
+
|
| 1091 |
+
**Step 3: Run tests, commit**
|
| 1092 |
+
|
| 1093 |
+
### Task 6.2: Logic puzzle API route
|
| 1094 |
+
|
| 1095 |
+
**Files:**
|
| 1096 |
+
- Create: `src/app/api/logic/generate/route.ts`
|
| 1097 |
+
- Create: `src/app/api/logic/submit/route.ts`
|
| 1098 |
+
|
| 1099 |
+
**Step 1: GET /api/logic/generate** — returns a new puzzle based on query param `type=sudoku&difficulty=easy`
|
| 1100 |
+
|
| 1101 |
+
**Step 2: POST /api/logic/submit** — validates solution, calculates XP (base + speed bonus), records Activity, updates CategorySkill and DailyLog.
|
| 1102 |
+
|
| 1103 |
+
**Step 3: Commit**
|
| 1104 |
+
|
| 1105 |
+
### Task 6.3: Sudoku board component
|
| 1106 |
+
|
| 1107 |
+
**Files:**
|
| 1108 |
+
- Create: `src/components/logic/sudoku-board.tsx`
|
| 1109 |
+
|
| 1110 |
+
**Step 1: Build interactive 9x9 grid** with number input, given cells locked, error highlighting, timer display. Client component with state management.
|
| 1111 |
+
|
| 1112 |
+
**Step 2: Commit**
|
| 1113 |
+
|
| 1114 |
+
### Task 6.4: Logic puzzles page
|
| 1115 |
+
|
| 1116 |
+
**Files:**
|
| 1117 |
+
- Create: `src/app/logic/page.tsx`
|
| 1118 |
+
|
| 1119 |
+
**Step 1: Build page** with difficulty selector, puzzle board, timer, and submit button. On submit, show XP results panel with framer-motion slide-in.
|
| 1120 |
+
|
| 1121 |
+
**Step 2: Build and verify**
|
| 1122 |
+
|
| 1123 |
+
```bash
|
| 1124 |
+
npm run build
|
| 1125 |
+
```
|
| 1126 |
+
|
| 1127 |
+
**Step 3: Commit**
|
| 1128 |
+
|
| 1129 |
+
---
|
| 1130 |
+
|
| 1131 |
+
## Phase 7: Feynman Challenges (Claude integration)
|
| 1132 |
+
|
| 1133 |
+
### Task 7.1: Claude client
|
| 1134 |
+
|
| 1135 |
+
**Files:**
|
| 1136 |
+
- Create: `src/lib/claude.ts`
|
| 1137 |
+
|
| 1138 |
+
**Step 1: Create Anthropic SDK client singleton**
|
| 1139 |
+
|
| 1140 |
+
```typescript
|
| 1141 |
+
import Anthropic from "@anthropic-ai/sdk";
|
| 1142 |
+
|
| 1143 |
+
const globalForClaude = globalThis as unknown as { claude: Anthropic };
|
| 1144 |
+
|
| 1145 |
+
export const claude = globalForClaude.claude || new Anthropic();
|
| 1146 |
+
|
| 1147 |
+
if (process.env.NODE_ENV !== "production") globalForClaude.claude = claude;
|
| 1148 |
+
```
|
| 1149 |
+
|
| 1150 |
+
**Step 2: Commit**
|
| 1151 |
+
|
| 1152 |
+
### Task 7.2: Feynman topic generator
|
| 1153 |
+
|
| 1154 |
+
**Files:**
|
| 1155 |
+
- Create: `src/lib/feynman/topics.ts`
|
| 1156 |
+
|
| 1157 |
+
**Step 1: Create a list of ~50 topic templates** across domains (CS, physics, biology, history, economics, philosophy). Function `getRandomTopic(domain?: string)` picks one.
|
| 1158 |
+
|
| 1159 |
+
**Step 2: Commit**
|
| 1160 |
+
|
| 1161 |
+
### Task 7.3: Feynman scoring API
|
| 1162 |
+
|
| 1163 |
+
**Files:**
|
| 1164 |
+
- Create: `src/app/api/feynman/score/route.ts`
|
| 1165 |
+
|
| 1166 |
+
**Step 1: POST handler** accepts `{ topic, explanation }`. Calls Claude with a structured prompt asking it to evaluate accuracy (0-10), completeness (0-10), clarity (0-10), and return identified gaps. Parses response, calculates XP, records Activity.
|
| 1167 |
+
|
| 1168 |
+
Prompt structure:
|
| 1169 |
+
```
|
| 1170 |
+
You are evaluating a Feynman-technique explanation. The user was asked to explain "{topic}" from memory, without reference materials.
|
| 1171 |
+
|
| 1172 |
+
Score on three dimensions (0-10 each):
|
| 1173 |
+
- Accuracy: Are the facts correct?
|
| 1174 |
+
- Completeness: Are the key concepts covered?
|
| 1175 |
+
- Clarity: Would a beginner understand this?
|
| 1176 |
+
|
| 1177 |
+
Respond in JSON: { "accuracy": N, "completeness": N, "clarity": N, "gaps": ["..."], "feedback": "..." }
|
| 1178 |
+
```
|
| 1179 |
+
|
| 1180 |
+
**Step 2: Commit**
|
| 1181 |
+
|
| 1182 |
+
### Task 7.4: Feynman challenge page
|
| 1183 |
+
|
| 1184 |
+
**Files:**
|
| 1185 |
+
- Create: `src/app/feynman/page.tsx`
|
| 1186 |
+
|
| 1187 |
+
**Step 1: Build page** with topic display, textarea for explanation (no paste allowed — `onPaste` handler prevents it), optional timer, submit button. Results panel shows scores on 3 dimensions + gaps + XP breakdown.
|
| 1188 |
+
|
| 1189 |
+
**Step 2: Build and verify, commit**
|
| 1190 |
+
|
| 1191 |
+
---
|
| 1192 |
+
|
| 1193 |
+
## Phase 8: Deep Reading
|
| 1194 |
+
|
| 1195 |
+
### Task 8.1: Content library seed
|
| 1196 |
+
|
| 1197 |
+
**Files:**
|
| 1198 |
+
- Create: `content/reading/` directory with 5-10 seeded markdown articles across domains and difficulties
|
| 1199 |
+
|
| 1200 |
+
**Step 1: Write 5-10 articles** (or curate public domain excerpts) covering science, philosophy, history, tech. Tag each with difficulty and domain in frontmatter.
|
| 1201 |
+
|
| 1202 |
+
**Step 2: Commit**
|
| 1203 |
+
|
| 1204 |
+
### Task 8.2: Content API
|
| 1205 |
+
|
| 1206 |
+
**Files:**
|
| 1207 |
+
- Create: `src/app/api/reading/content/route.ts`
|
| 1208 |
+
|
| 1209 |
+
**Step 1: GET handler** returns content items filtered by difficulty/domain. Supports both seeded library and user-submitted content from ContentItem table.
|
| 1210 |
+
|
| 1211 |
+
**Step 2: POST handler** for user-submitted URLs/text. If URL, fetch and clean to markdown. Save to ContentItem table.
|
| 1212 |
+
|
| 1213 |
+
**Step 3: Commit**
|
| 1214 |
+
|
| 1215 |
+
### Task 8.3: Reading comprehension API
|
| 1216 |
+
|
| 1217 |
+
**Files:**
|
| 1218 |
+
- Create: `src/app/api/reading/comprehend/route.ts`
|
| 1219 |
+
|
| 1220 |
+
**Step 1: POST handler** accepts `{ content, answers }`. First call (no answers): Claude generates 3-5 comprehension questions from the text. Second call (with answers): Claude scores answers. Returns scores and XP.
|
| 1221 |
+
|
| 1222 |
+
**Step 2: Commit**
|
| 1223 |
+
|
| 1224 |
+
### Task 8.4: Reader component
|
| 1225 |
+
|
| 1226 |
+
**Files:**
|
| 1227 |
+
- Create: `src/components/reading/reader.tsx`
|
| 1228 |
+
|
| 1229 |
+
**Step 1: Build distraction-free reader** — rendered markdown, clean typography, no copy-paste (`onCopy` prevented), reading timer, "I'm done" button that triggers comprehension questions.
|
| 1230 |
+
|
| 1231 |
+
**Step 2: Commit**
|
| 1232 |
+
|
| 1233 |
+
### Task 8.5: Reading page
|
| 1234 |
+
|
| 1235 |
+
**Files:**
|
| 1236 |
+
- Create: `src/app/reading/page.tsx`
|
| 1237 |
+
|
| 1238 |
+
**Step 1: Build page** with content browser (filter by difficulty/domain), paste-your-own input, reader view (full screen when active), comprehension quiz, and results panel.
|
| 1239 |
+
|
| 1240 |
+
**Step 2: Build and verify, commit**
|
| 1241 |
+
|
| 1242 |
+
---
|
| 1243 |
+
|
| 1244 |
+
## Phase 9: Critical Thinking
|
| 1245 |
+
|
| 1246 |
+
### Task 9.1: Critical thinking scoring API
|
| 1247 |
+
|
| 1248 |
+
**Files:**
|
| 1249 |
+
- Create: `src/app/api/critical-thinking/route.ts`
|
| 1250 |
+
|
| 1251 |
+
**Step 1: POST handler** with `exerciseType` field (`flaw-finder`, `steelman`, `devil's-advocate`). Each type has its own Claude prompt:
|
| 1252 |
+
|
| 1253 |
+
- **Flaw Finder:** Claude generates a passage with deliberate fallacies (or receives user-provided text), then scores the user's identification of flaws.
|
| 1254 |
+
- **Steelman:** Claude presents a position, then scores the user's steelman on charitable interpretation, coherence, kernel of truth.
|
| 1255 |
+
- **Devil's Advocate:** Claude presents a position, then scores the user's counterargument on strength, evidence, intellectual honesty.
|
| 1256 |
+
|
| 1257 |
+
All return JSON scores + feedback + XP.
|
| 1258 |
+
|
| 1259 |
+
**Step 2: Commit**
|
| 1260 |
+
|
| 1261 |
+
### Task 9.2: Critical thinking page
|
| 1262 |
+
|
| 1263 |
+
**Files:**
|
| 1264 |
+
- Create: `src/app/critical-thinking/page.tsx`
|
| 1265 |
+
|
| 1266 |
+
**Step 1: Build page** with exercise type selector (only showing unlocked types based on skill tree), the prompt/passage display, textarea for response (150-word minimum indicator for Devil's Advocate), submit button, and results panel.
|
| 1267 |
+
|
| 1268 |
+
**Step 2: Build and verify, commit**
|
| 1269 |
+
|
| 1270 |
+
---
|
| 1271 |
+
|
| 1272 |
+
## Phase 10: Chess
|
| 1273 |
+
|
| 1274 |
+
### Task 10.1: Lichess API client
|
| 1275 |
+
|
| 1276 |
+
**Files:**
|
| 1277 |
+
- Create: `src/lib/lichess.ts`
|
| 1278 |
+
|
| 1279 |
+
**Step 1: Build Lichess API wrapper** with functions:
|
| 1280 |
+
- `getLichessPuzzle()` — GET `/api/puzzle/next` with auth token
|
| 1281 |
+
- `challengeStockfish(level: number)` — POST `/api/challenge/stockfish`
|
| 1282 |
+
- `getGameStream(gameId: string)` — stream game events
|
| 1283 |
+
|
| 1284 |
+
**Step 2: Commit**
|
| 1285 |
+
|
| 1286 |
+
### Task 10.2: Chess.com API client
|
| 1287 |
+
|
| 1288 |
+
**Files:**
|
| 1289 |
+
- Create: `src/lib/chesscom.ts`
|
| 1290 |
+
|
| 1291 |
+
**Step 1: Build Chess.com API wrapper** with functions:
|
| 1292 |
+
- `getPlayerStats(username: string)` — GET `api.chess.com/pub/player/{username}/stats`
|
| 1293 |
+
- `getPlayerGames(username: string, year: number, month: number)` — game archives
|
| 1294 |
+
|
| 1295 |
+
No auth needed.
|
| 1296 |
+
|
| 1297 |
+
**Step 2: Commit**
|
| 1298 |
+
|
| 1299 |
+
### Task 10.3: Chess puzzle API route
|
| 1300 |
+
|
| 1301 |
+
**Files:**
|
| 1302 |
+
- Create: `src/app/api/chess/puzzle/route.ts`
|
| 1303 |
+
- Create: `src/app/api/chess/submit/route.ts`
|
| 1304 |
+
|
| 1305 |
+
**Step 1: GET /api/chess/puzzle** proxies Lichess puzzle API, returns puzzle data formatted for react-chessboard.
|
| 1306 |
+
|
| 1307 |
+
**Step 2: POST /api/chess/submit** records puzzle result, calculates XP based on puzzle rating vs user performance.
|
| 1308 |
+
|
| 1309 |
+
**Step 3: Commit**
|
| 1310 |
+
|
| 1311 |
+
### Task 10.4: Chess board component
|
| 1312 |
+
|
| 1313 |
+
**Files:**
|
| 1314 |
+
- Create: `src/components/chess/puzzle-board.tsx`
|
| 1315 |
+
|
| 1316 |
+
**Step 1: Build puzzle board** using `react-chessboard` + `chess.js`. Shows position, validates moves against solution, highlights correct/incorrect moves, shows completion state.
|
| 1317 |
+
|
| 1318 |
+
**Step 2: Commit**
|
| 1319 |
+
|
| 1320 |
+
### Task 10.5: Chess page
|
| 1321 |
+
|
| 1322 |
+
**Files:**
|
| 1323 |
+
- Create: `src/app/chess/page.tsx`
|
| 1324 |
+
|
| 1325 |
+
**Step 1: Build page** with tabs for Puzzles and Play. Puzzle tab shows puzzle board with rating display. Play tab links out to Lichess for bot games (or embeds if feasible). Chess.com rating display in sidebar.
|
| 1326 |
+
|
| 1327 |
+
**Step 2: Build and verify, commit**
|
| 1328 |
+
|
| 1329 |
+
---
|
| 1330 |
+
|
| 1331 |
+
## Phase 11: Skill Quests
|
| 1332 |
+
|
| 1333 |
+
### Task 11.1: Quest generation API
|
| 1334 |
+
|
| 1335 |
+
**Files:**
|
| 1336 |
+
- Create: `src/app/api/quests/generate/route.ts`
|
| 1337 |
+
- Create: `src/app/api/quests/submit/route.ts`
|
| 1338 |
+
|
| 1339 |
+
**Step 1: GET /api/quests/generate** — Claude generates a micro-lesson with content + 3-5 practice exercises based on `domain` and `difficulty` params.
|
| 1340 |
+
|
| 1341 |
+
**Step 2: POST /api/quests/submit** — scores practice answers, calculates XP, records Activity.
|
| 1342 |
+
|
| 1343 |
+
**Step 3: Commit**
|
| 1344 |
+
|
| 1345 |
+
### Task 11.2: Quest page
|
| 1346 |
+
|
| 1347 |
+
**Files:**
|
| 1348 |
+
- Create: `src/app/quests/page.tsx`
|
| 1349 |
+
|
| 1350 |
+
**Step 1: Build page** with domain selector (language, music theory, mental math, science, etc.), lesson display, practice exercises, submit, and results panel.
|
| 1351 |
+
|
| 1352 |
+
**Step 2: Build and verify, commit**
|
| 1353 |
+
|
| 1354 |
+
---
|
| 1355 |
+
|
| 1356 |
+
## Phase 12: Profile & Skill Trees
|
| 1357 |
+
|
| 1358 |
+
### Task 12.1: Profile data API
|
| 1359 |
+
|
| 1360 |
+
**Files:**
|
| 1361 |
+
- Create: `src/app/api/profile/route.ts`
|
| 1362 |
+
|
| 1363 |
+
**Step 1: GET handler** returns: user stats, all category skills, all unlocked nodes, chess.com stats (if username set), achievements/milestones.
|
| 1364 |
+
|
| 1365 |
+
**Step 2: Commit**
|
| 1366 |
+
|
| 1367 |
+
### Task 12.2: Skill tree visualizer component
|
| 1368 |
+
|
| 1369 |
+
**Files:**
|
| 1370 |
+
- Create: `src/components/profile/skill-tree.tsx`
|
| 1371 |
+
|
| 1372 |
+
**Step 1: Build skill tree renderer** using SVG or a simple node graph (not reactflow — too heavy for this). Shows nodes connected by lines, locked nodes greyed/dimmed, unlocked nodes glow with category color, click to see description. Accepts `category` prop to show one tree at a time.
|
| 1373 |
+
|
| 1374 |
+
**Step 2: Commit**
|
| 1375 |
+
|
| 1376 |
+
### Task 12.3: Profile page
|
| 1377 |
+
|
| 1378 |
+
**Files:**
|
| 1379 |
+
- Create: `src/app/profile/page.tsx`
|
| 1380 |
+
|
| 1381 |
+
**Step 1: Build page** with: large level display + title + XP bar, tab switcher for each category's skill tree, stats grid (total exercises, time spent, longest streak, etc.), chess.com ratings card, achievements section.
|
| 1382 |
+
|
| 1383 |
+
**Step 2: Build and verify, commit**
|
| 1384 |
+
|
| 1385 |
+
---
|
| 1386 |
+
|
| 1387 |
+
## Phase 13: XP Results Animation
|
| 1388 |
+
|
| 1389 |
+
### Task 13.1: XP results panel component
|
| 1390 |
+
|
| 1391 |
+
**Files:**
|
| 1392 |
+
- Create: `src/components/shared/xp-results.tsx`
|
| 1393 |
+
|
| 1394 |
+
**Step 1: Build reusable results panel** used by all exercise pages. Slides in from right with framer-motion. Shows:
|
| 1395 |
+
- Base XP earned
|
| 1396 |
+
- Quality bonus (with score breakdown)
|
| 1397 |
+
- Critical hit indicator (if triggered, with flash animation)
|
| 1398 |
+
- Total XP
|
| 1399 |
+
- Category skill progress bar update
|
| 1400 |
+
- Level-up celebration (if applicable)
|
| 1401 |
+
- Any new unlocks
|
| 1402 |
+
|
| 1403 |
+
**Step 2: Commit**
|
| 1404 |
+
|
| 1405 |
+
### Task 13.2: Level-up celebration overlay
|
| 1406 |
+
|
| 1407 |
+
**Files:**
|
| 1408 |
+
- Create: `src/components/shared/level-up.tsx`
|
| 1409 |
+
|
| 1410 |
+
**Step 1: Build full-screen overlay** that appears on level-up. Shows new level, new title (if changed), particle effects (CSS-only, no heavy lib). Auto-dismisses after 3 seconds or on click.
|
| 1411 |
+
|
| 1412 |
+
**Step 2: Commit**
|
| 1413 |
+
|
| 1414 |
+
---
|
| 1415 |
+
|
| 1416 |
+
## Phase 14: Integration & Polish
|
| 1417 |
+
|
| 1418 |
+
### Task 14.1: Wire XP results into all exercise pages
|
| 1419 |
+
|
| 1420 |
+
**Step 1:** Import and use `XpResults` component in all 6 exercise pages. Ensure consistent behavior.
|
| 1421 |
+
|
| 1422 |
+
**Step 2: Commit**
|
| 1423 |
+
|
| 1424 |
+
### Task 14.2: Daily goal and streak cron logic
|
| 1425 |
+
|
| 1426 |
+
**Files:**
|
| 1427 |
+
- Create: `src/lib/streak.ts`
|
| 1428 |
+
|
| 1429 |
+
**Step 1:** Write function `processEndOfDay(userId)` that checks if daily goal was met, updates streak (increment or break), consumes streak freeze if needed. Called on first activity of a new day.
|
| 1430 |
+
|
| 1431 |
+
**Step 2: Commit**
|
| 1432 |
+
|
| 1433 |
+
### Task 14.3: Settings page
|
| 1434 |
+
|
| 1435 |
+
**Files:**
|
| 1436 |
+
- Create: `src/app/settings/page.tsx`
|
| 1437 |
+
|
| 1438 |
+
**Step 1: Build settings** for: daily XP goal (50/100/150), Lichess username, Chess.com username, display name.
|
| 1439 |
+
|
| 1440 |
+
**Step 2: Commit**
|
| 1441 |
+
|
| 1442 |
+
### Task 14.4: Full build verification
|
| 1443 |
+
|
| 1444 |
+
**Step 1: Run all tests**
|
| 1445 |
+
|
| 1446 |
+
```bash
|
| 1447 |
+
npm test
|
| 1448 |
+
```
|
| 1449 |
+
|
| 1450 |
+
**Step 2: Run build**
|
| 1451 |
+
|
| 1452 |
+
```bash
|
| 1453 |
+
npm run build
|
| 1454 |
+
```
|
| 1455 |
+
|
| 1456 |
+
**Step 3: Fix any issues**
|
| 1457 |
+
|
| 1458 |
+
**Step 4: Final commit**
|
| 1459 |
+
|
| 1460 |
+
```bash
|
| 1461 |
+
git add -A && git commit -m "feat: complete RotNot v1 MVP"
|
| 1462 |
+
```
|
| 1463 |
+
|
| 1464 |
+
---
|
| 1465 |
+
|
| 1466 |
+
## Execution Order Summary
|
| 1467 |
+
|
| 1468 |
+
| Phase | Description | Dependencies |
|
| 1469 |
+
|-------|-------------|-------------|
|
| 1470 |
+
| 1 | Scaffolding | None |
|
| 1471 |
+
| 2 | Database | Phase 1 |
|
| 1472 |
+
| 3 | XP Engine | Phase 1 |
|
| 1473 |
+
| 4 | Layout & Theme | Phases 1, 2 |
|
| 1474 |
+
| 5 | Dashboard | Phases 2, 3, 4 |
|
| 1475 |
+
| 6 | Logic Puzzles | Phases 3, 4 |
|
| 1476 |
+
| 7 | Feynman | Phases 3, 4 |
|
| 1477 |
+
| 8 | Deep Reading | Phases 3, 4 |
|
| 1478 |
+
| 9 | Critical Thinking | Phases 3, 4 |
|
| 1479 |
+
| 10 | Chess | Phases 3, 4 |
|
| 1480 |
+
| 11 | Skill Quests | Phases 3, 4 |
|
| 1481 |
+
| 12 | Profile & Trees | Phases 2, 4 |
|
| 1482 |
+
| 13 | XP Animations | Phase 3 |
|
| 1483 |
+
| 14 | Integration | All above |
|
| 1484 |
+
|
| 1485 |
+
Phases 6-11 are independent and can be parallelized.
|
e2e/coding.spec.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { test, expect, Page } from "@playwright/test";
|
| 2 |
+
|
| 3 |
+
// End-to-end coverage of the Coding Training module, exercising the real app:
|
| 4 |
+
// navigation → selection → generation → sandbox code submission (TDD) and
|
| 5 |
+
// LLM-judge written submission, with separate XP awards.
|
| 6 |
+
|
| 7 |
+
// Correct solutions for every executable problem in the bank, keyed by the
|
| 8 |
+
// entry function name (read from sessionStorage at runtime so the test is
|
| 9 |
+
// robust to which problem is randomly served).
|
| 10 |
+
const SOLUTIONS: Record<string, string> = {
|
| 11 |
+
sumOfEvens: "function sumOfEvens(nums){ return nums.filter(n=>n%2===0).reduce((a,b)=>a+b,0); }",
|
| 12 |
+
reverse: "function reverse(s){ return s.split('').reverse().join(''); }",
|
| 13 |
+
twoSum:
|
| 14 |
+
"function twoSum(nums,target){ const m=new Map(); for(let i=0;i<nums.length;i++){ const n=target-nums[i]; if(m.has(n)) return [m.get(n),i]; m.set(nums[i],i);} return []; }",
|
| 15 |
+
isBalanced:
|
| 16 |
+
"function isBalanced(s){ const p={')':'(',']':'[','}':'{'}; const st=[]; for(const c of s){ if(c==='('||c==='['||c==='{') st.push(c); else if(p[c]){ if(st.pop()!==p[c]) return false; } } return st.length===0; }",
|
| 17 |
+
lengthOfLongestSubstring:
|
| 18 |
+
"function lengthOfLongestSubstring(s){ const seen=new Set(); let l=0,best=0; for(let r=0;r<s.length;r++){ while(seen.has(s[r])){ seen.delete(s[l]); l++; } seen.add(s[r]); best=Math.max(best,r-l+1);} return best; }",
|
| 19 |
+
factorial: "function factorial(n){ let r=1; for(let i=1;i<=n;i++) r*=i; return r; }",
|
| 20 |
+
binarySearch:
|
| 21 |
+
"function binarySearch(arr,t){ let lo=0,hi=arr.length-1; while(lo<=hi){ const m=Math.floor((lo+hi)/2); if(arr[m]===t) return m; if(arr[m]<t) lo=m+1; else hi=m-1; } return -1; }",
|
| 22 |
+
maxSubArray:
|
| 23 |
+
"function maxSubArray(nums){ let best=-Infinity,cur=0; for(const n of nums){ cur=Math.max(n,cur+n); best=Math.max(best,cur);} return best; }",
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
async function entryFunctionFromSession(page: Page): Promise<string> {
|
| 27 |
+
const raw = await page.evaluate(() => sessionStorage.getItem("coding:problem"));
|
| 28 |
+
expect(raw).toBeTruthy();
|
| 29 |
+
const parsed = JSON.parse(raw!);
|
| 30 |
+
return parsed.problem.entryFunction as string;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
async function generate(page: Page, type: string, difficulty: string, language: string) {
|
| 34 |
+
await page.goto("/coding");
|
| 35 |
+
await expect(page.getByRole("heading", { name: "Coding Training" })).toBeVisible();
|
| 36 |
+
await page.getByTestId(`type-${type}`).click();
|
| 37 |
+
|
| 38 |
+
// Difficulty
|
| 39 |
+
await page.getByTestId("difficulty-select").click();
|
| 40 |
+
await page.getByRole("option", { name: new RegExp(difficulty, "i") }).click();
|
| 41 |
+
|
| 42 |
+
// Language
|
| 43 |
+
await page.getByTestId("language-select").click();
|
| 44 |
+
await page.getByRole("option", { name: new RegExp(`^${language}$`, "i") }).click();
|
| 45 |
+
|
| 46 |
+
await page.getByTestId("generate-btn").click();
|
| 47 |
+
await expect(page).toHaveURL(/\/coding\/problem/);
|
| 48 |
+
await expect(page.getByTestId("problem-title")).toBeVisible();
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
test("navigation: Coding Training tab is reachable from the sidebar", async ({ page }) => {
|
| 52 |
+
await page.goto("/");
|
| 53 |
+
await page.getByRole("link", { name: "Coding Training" }).first().click();
|
| 54 |
+
await expect(page).toHaveURL(/\/coding$/);
|
| 55 |
+
await expect(page.getByRole("heading", { name: "Coding Training" })).toBeVisible();
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
test("generates a problem and shows the new problem page with formatted code", async ({ page }) => {
|
| 59 |
+
await generate(page, "debugging", "easy", "JavaScript");
|
| 60 |
+
// The buggy code is shown with syntax highlighting (line-numbered code block).
|
| 61 |
+
await expect(page.getByTestId("code-editor")).toBeVisible();
|
| 62 |
+
await expect(page.getByTestId("problem-prompt")).toBeVisible();
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
test("code submission: correct code passes the hidden tests and awards code XP", async ({ page }) => {
|
| 66 |
+
await generate(page, "code-creation", "easy", "JavaScript");
|
| 67 |
+
|
| 68 |
+
const fn = await entryFunctionFromSession(page);
|
| 69 |
+
const solution = SOLUTIONS[fn];
|
| 70 |
+
expect(solution, `missing E2E solution for ${fn}`).toBeTruthy();
|
| 71 |
+
|
| 72 |
+
// Type the correct solution into the sandbox editor.
|
| 73 |
+
const editor = page.getByTestId("code-editor");
|
| 74 |
+
await editor.fill(solution);
|
| 75 |
+
|
| 76 |
+
// Run against the example tests first.
|
| 77 |
+
await page.getByTestId("run-btn").click();
|
| 78 |
+
await expect(page.getByTestId("run-output")).toContainText(/example tests passed/i);
|
| 79 |
+
|
| 80 |
+
// Submit for grading against the full hidden suite.
|
| 81 |
+
await page.getByTestId("submit-code-btn").click();
|
| 82 |
+
await expect(page.getByTestId("code-result-message")).toContainText(/solved|tests pass/i);
|
| 83 |
+
await expect(page.getByTestId("xp-results-code")).toBeVisible();
|
| 84 |
+
await expect(page.getByTestId("xp-results-code")).toContainText(/XP/i);
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test("debugging: applying the fix turns the suite green and awards XP", async ({ page }) => {
|
| 88 |
+
await generate(page, "debugging", "easy", "JavaScript");
|
| 89 |
+
const fn = await entryFunctionFromSession(page);
|
| 90 |
+
const solution = SOLUTIONS[fn];
|
| 91 |
+
expect(solution).toBeTruthy();
|
| 92 |
+
|
| 93 |
+
await page.getByTestId("code-editor").fill(solution);
|
| 94 |
+
await page.getByTestId("submit-code-btn").click();
|
| 95 |
+
await expect(page.getByTestId("xp-results-code")).toBeVisible();
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
test("incorrect code is rejected without awarding XP", async ({ page }) => {
|
| 99 |
+
await generate(page, "code-creation", "easy", "JavaScript");
|
| 100 |
+
await page.getByTestId("code-editor").fill("function wrongName() { return -1; }");
|
| 101 |
+
await page.getByTestId("submit-code-btn").click();
|
| 102 |
+
await expect(page.getByTestId("code-result-message")).toContainText(/passed|did not compile/i);
|
| 103 |
+
await expect(page.getByTestId("xp-results-code")).toHaveCount(0);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
test("written submission: correctly reviewing clean code awards written XP", async ({ page }) => {
|
| 107 |
+
// The only easy code-review problem in the bank is the clean clamp().
|
| 108 |
+
await generate(page, "code-review", "easy", "JavaScript");
|
| 109 |
+
|
| 110 |
+
// The code under review is shown with syntax highlighting.
|
| 111 |
+
await expect(page.getByTestId("review-code")).toBeVisible();
|
| 112 |
+
|
| 113 |
+
await page
|
| 114 |
+
.getByTestId("written-answer")
|
| 115 |
+
.fill("This function looks correct. There are no issues — it clamps the value properly.");
|
| 116 |
+
await page.getByTestId("submit-written-btn").click();
|
| 117 |
+
|
| 118 |
+
await expect(page.getByTestId("written-result-message")).toContainText(/correct|accepted/i);
|
| 119 |
+
await expect(page.getByTestId("xp-results-written")).toBeVisible();
|
| 120 |
+
await expect(page.getByTestId("xp-results-written")).toContainText(/WRITTEN XP/i);
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
test("written submission: a thorough architecture answer is graded and awards XP", async ({ page }) => {
|
| 124 |
+
await generate(page, "architecture", "medium", "JavaScript");
|
| 125 |
+
await page
|
| 126 |
+
.getByTestId("written-answer")
|
| 127 |
+
.fill(
|
| 128 |
+
"I'd use a token bucket algorithm. The limit key is per API key granularity. " +
|
| 129 |
+
"Counters live in a shared Redis store so it works across instances. Bursts are " +
|
| 130 |
+
"smoothed by bucket capacity. If Redis is down we fail open to stay available.",
|
| 131 |
+
);
|
| 132 |
+
await page.getByTestId("submit-written-btn").click();
|
| 133 |
+
await expect(page.getByTestId("written-result")).toBeVisible();
|
| 134 |
+
await expect(page.getByTestId("xp-results-written")).toBeVisible();
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
test("language selection is honoured in the generated problem", async ({ page }) => {
|
| 138 |
+
await generate(page, "code-review", "medium", "Python");
|
| 139 |
+
const raw = await page.evaluate(() => sessionStorage.getItem("coding:problem"));
|
| 140 |
+
const parsed = JSON.parse(raw!);
|
| 141 |
+
expect(parsed.problem.language).toBe("python");
|
| 142 |
+
});
|
eslint.config.mjs
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { defineConfig, globalIgnores } from "eslint/config";
|
| 2 |
+
import nextVitals from "eslint-config-next/core-web-vitals";
|
| 3 |
+
import nextTs from "eslint-config-next/typescript";
|
| 4 |
+
|
| 5 |
+
const eslintConfig = defineConfig([
|
| 6 |
+
...nextVitals,
|
| 7 |
+
...nextTs,
|
| 8 |
+
// Override default ignores of eslint-config-next.
|
| 9 |
+
globalIgnores([
|
| 10 |
+
// Default ignores of eslint-config-next:
|
| 11 |
+
".next/**",
|
| 12 |
+
"out/**",
|
| 13 |
+
"build/**",
|
| 14 |
+
"next-env.d.ts",
|
| 15 |
+
]),
|
| 16 |
+
]);
|
| 17 |
+
|
| 18 |
+
export default eslintConfig;
|
new-examples.json
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"id": "ex-129",
|
| 4 |
+
"scoreLevel": 5,
|
| 5 |
+
"dimensionId": "rebuttal-quality",
|
| 6 |
+
"topic": "The death penalty is never justified",
|
| 7 |
+
"side": "con",
|
| 8 |
+
"argument": "My opponent claims the death penalty is never justified, citing wrongful convictions and moral absolutism. But they did not engage with the strongest counter-case: that of voluntary waiver. Timothy McVeigh waived his appeals and requested execution, believing death preferable to life in supermax confinement. If we take autonomy seriously, denying McVeigh his chosen sentence is paternalism, not justice. My opponent also ignores the specific deterrent effect on murderers already serving life sentences — without capital punishment, what mechanism prevents prison killings? The never framing requires addressing these edge cases, not just repeating general principles.",
|
| 9 |
+
"rationale": "Scores 5 because the rebuttal engages two specific counterarguments (voluntary waiver, prison killings by lifers) that apply the opponent's principles to edge cases. However, the rebuttal does not fully develop either point — the McVeigh case is cited but not analyzed for its implications for never, and the prison killing point is raised but not supported with evidence that such killings are common enough to matter. The tone is somewhat combative (paternalism, not justice) rather than analytically rigorous.",
|
| 10 |
+
"side_note": "Con-side rebuttal-quality example at mid tier — engages specific counterpoints but underdeveloped"
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"id": "ex-130",
|
| 14 |
+
"scoreLevel": 8,
|
| 15 |
+
"dimensionId": "intellectual-honesty",
|
| 16 |
+
"topic": "Nuclear energy should be a central pillar of climate policy",
|
| 17 |
+
"side": "con",
|
| 18 |
+
"argument": "I want to acknowledge at the outset that my position against nuclear centrality relies on contingent empirical claims that could be wrong. If small modular reactors achieve their cost and deployment targets, if next-generation designs solve the waste problem at scale, and if public acceptance shifts significantly, then nuclear could indeed play a larger role than I think likely. I am arguing against centrality — the claim that nuclear must anchor climate strategy — not against nuclear as one component among many. I should also note that my concern about cost overruns and delays applies primarily to the American regulatory context; the French and Korean experiences suggest that standardization and state commitment can deliver nuclear more efficiently. I am making a predictive claim about what is likely in the US context, not a universal claim about nuclear's impossibility. Finally, I recognize that my focus on cost ignores the security argument: if grid reliability requires firm power and renewables-plus-storage cannot yet provide it at scale, then reliability might justify premium costs. I do not think we are at that reliability threshold yet, but I could be underestimating the challenge.",
|
| 19 |
+
"rationale": "Scores 8 because the debater displays extensive intellectual honesty through multiple mechanisms: explicit acknowledgment of contingent empirical foundations, narrowing of claim scope from 'nuclear is bad' to 'nuclear should not be central,' recognition of context-specificity (US vs France/Korea), acknowledgment of a counterargument (security/reliability) that they engage but do not fully accept, and appropriate epistemic hedging throughout. The debater models what it looks like to hold a position while remaining genuinely open to being wrong. Loses 2 points because the closing 'I could be underestimating' is somewhat performative — a truly maximal honesty would engage more specifically with what evidence would change their mind.",
|
| 20 |
+
"side_note": "Con-side intellectual-honesty example at high tier — extensive contingent acknowledgment and epistemic hedging"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"id": "ex-131",
|
| 24 |
+
"scoreLevel": 4,
|
| 25 |
+
"dimensionId": "persuasiveness",
|
| 26 |
+
"topic": "Free will is an illusion",
|
| 27 |
+
"side": "pro",
|
| 28 |
+
"argument": "Free will is definitely an illusion. Neuroscience shows our brains decide before we're conscious of choices. Libet's experiments proved this — the readiness potential comes before the conscious decision. Also determinism is true — physics shows everything is cause and effect. So we can't have free will. People don't like this because it means we can't praise or blame anyone, but that's just tough. The science is clear.",
|
| 29 |
+
"rationale": "Scores 4 because the argument cites genuine evidence (Libet, determinism) but deploys it reductively. 'Libet proved this' overstates a contested literature — Libet's interpretation is disputed, and subsequent work shows conscious veto power. The 'just tough' dismissal of the praise/blame concern is rhetorically ineffective — it signals that the debater has not engaged with why this matters to the audience. The 'science is clear' conclusion is dogmatic rather than persuasive. Scores above 1-3 because at least the right evidence categories are referenced, even if handled poorly.",
|
| 30 |
+
"side_note": "Pro-side persuasiveness example at low-mid tier — cites relevant evidence but deploys reductively"
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"id": "ex-132",
|
| 34 |
+
"scoreLevel": 7,
|
| 35 |
+
"dimensionId": "flaw-detection",
|
| 36 |
+
"topic": "Universal Basic Income should replace all welfare programs",
|
| 37 |
+
"side": "con",
|
| 38 |
+
"argument": "The replacement argument contains a hidden equivocation between administrative efficiency and adequacy. My opponent notes that UBI would reduce bureaucracy — this is true — but then slides to claiming it would 'better serve' recipients. This is a category error: efficiency is not adequacy. The flaw is that $12,000/year (a common UBI proposal) is below the poverty line everywhere in the US. A single mother in San Francisco receiving $12,000 has been administratively liberated from welfare offices but materially impoverished relative to her previous SNAP, Medicaid, and housing assistance. The argument also commits a composition fallacy: because some welfare programs have work disincentives, all do — but EITC is literally a work incentive. Finally, the 'experiments show' citation refers to trials with supplemental income, not replacement — the Finnish trial kept existing benefits. The argument conflates supplemental and replacement outcomes.",
|
| 39 |
+
"rationale": "Scores 7 because the debater identifies multiple genuine logical flaws: the efficiency→adequacy equivocation, the category error of conflating these distinct concepts, the composition fallacy regarding work incentives, and the crucial supplemental-vs-replacement distinction in the evidence base. Each identification is precise and explained. Loses 3 points because the flaw detection could go further: the argument does not address why UBI proponents think adequacy is achievable (automation dividend framing), and the 'category error' label may overstate — efficiency and adequacy are distinct but not mutually exclusive categories.",
|
| 40 |
+
"side_note": "Con-side flaw-detection example at high-mid tier — multiple precise flaw identifications with explanations"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"id": "ex-133",
|
| 44 |
+
"scoreLevel": 6,
|
| 45 |
+
"dimensionId": "steelman-awareness",
|
| 46 |
+
"topic": "Social media platforms should be liable for user content",
|
| 47 |
+
"side": "pro",
|
| 48 |
+
"argument": "Before defending Section 230 reform, let me state the strongest case for the current liability shield. The internet as we know it depends on user-generated content at scale — billions of posts daily. If platforms faced publisher liability for this content, they would either shut down entirely or institute such aggressive moderation that valuable speech would be caught in over-broad filters. The safe harbor enabled the explosion of innovation from YouTube to Wikipedia to Etsy. Content moderation at scale is genuinely hard — even perfect human moderators would disagree on edge cases. Section 230 allows platforms to experiment with different moderation approaches without betting the company on each choice. I accept these points as genuine constraints. However, I argue that the shield has expanded beyond its original purpose. The 'good Samaritan' block of harmful content was meant to enable moderation, but the interpretation now protects platforms that design algorithms to amplify harmful content for engagement. The liability shield should not cover algorithmic amplification decisions — that is editorial judgment, not hosting.",
|
| 49 |
+
"rationale": "Scores 6 because the steelman genuinely develops the opponent's position through specific mechanisms (scale impossibility, innovation enablement, moderation difficulty) before pivoting. The acknowledgment that content moderation is 'genuinely hard' shows real engagement. The pivot distinguishes hosting from amplification, which is a fair narrowing. Loses 4 points because the steelman remains at the practical-constraint level rather than engaging the principled defense: that liability for third-party speech creates a heckler's veto and chills speech platforms themselves want to protect. The best steelman would include both practical and principled strands.",
|
| 50 |
+
"side_note": "Pro-side steelman-awareness example at mid-high tier — solid practical engagement but misses principled defense"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"id": "ex-134",
|
| 54 |
+
"scoreLevel": 9,
|
| 55 |
+
"dimensionId": "devils-advocate-depth",
|
| 56 |
+
"topic": "It is ethical to eat animals",
|
| 57 |
+
"side": "con",
|
| 58 |
+
"argument": "I oppose eating animals, but I want to engage seriously with the strongest internal challenge to my position. The challenge is not taste preference or tradition — it is the ecologically necessary predation argument. Ecosystems require predation to function; without wolves, deer overpopulate and starve. Humans are omnivores within such ecosystems. If I accept that some predation is ecologically necessary, and that humans are natural omnivores, then the question becomes whether human meat consumption differs in kind from wolf predation. The strongest version of this challenge notes that vegan agriculture kills animals too — field mice, insects, birds killed by tractors and pesticides. The 'least harm' principle might actually favor eating large herbivores (one death feeds many) over vegetable agriculture (many small deaths). This argument is not decisive — we could reduce agricultural harm through different methods — but it challenges the moral distinction between direct killing for food and indirect killing through habitat disruption. I maintain my position because I believe intentional killing for taste preference differs morally from unavoidable collateral harm, but I cannot claim the distinction is self-evident.",
|
| 59 |
+
"rationale": "Scores 9 because the debater constructs a deep internal challenge by engaging with the ecological necessity of predation, the comparative harm argument (one cow vs many field mice), and the difficulty of drawing a principled line between direct and indirect killing. The acknowledgment that the distinction is 'not self-evident' demonstrates genuine grappling. The argument recognizes that their position relies on a distinction between intentional and collateral harm that requires defense. Loses 1 point because the debater could push further: the strongest internal challenge would explore whether 'taste preference' captures all meat consumption (nutritional need, cultural identity) or whether the field mouse comparison applies differently to factory farming vs hunting.",
|
| 60 |
+
"side_note": "Con-side devil's-advocate-depth example at near-exemplary tier — sophisticated engagement with ecological and comparative harm arguments"
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"id": "ex-135",
|
| 64 |
+
"scoreLevel": 3,
|
| 65 |
+
"dimensionId": "argument-structure",
|
| 66 |
+
"topic": "Climate change requires immediate drastic action",
|
| 67 |
+
"side": "con",
|
| 68 |
+
"argument": "Climate change isn't the emergency people say. The planet has warmed before. Ice ages came and went. Humans adapt — we always have. The economy matters too. If we destroy the economy trying to fix climate, we'll be poor and cold. China and India aren't cutting emissions anyway, so why should we hurt ourselves? Technology will save us eventually. We should wait for better solutions.",
|
| 69 |
+
"rationale": "Scores 3 because the argument is a list of disconnected claims without logical development. 'Ice ages came and went' does not address timescale or cause. 'Humans adapt' is asserted without mechanism. The China/India point is raised but not connected to why US action would be futile. 'Technology will save us' is faith-based rather than evidenced. Scores above 1-2 because the claims are at least topically related to climate policy, and the 'economy matters too' gesture toward a genuine tradeoff framework, even if undeveloped.",
|
| 70 |
+
"side_note": "Con-side argument-structure example at low tier — disconnected claims without logical development"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"id": "ex-136",
|
| 74 |
+
"scoreLevel": 7,
|
| 75 |
+
"dimensionId": "evidence-accuracy",
|
| 76 |
+
"topic": "Cryptocurrency enables financial inclusion for the unbanked",
|
| 77 |
+
"side": "con",
|
| 78 |
+
"argument": "The financial inclusion claim requires scrutiny at three evidentiary levels. First, acquisition: how do the unbanked obtain crypto without banking infrastructure? The data shows that in Sub-Saharan Africa, 95% of crypto transactions occur through centralized exchanges that require KYC compliance — essentially banking with extra steps. Second, usage: the 'banking the unbanked' narrative relies heavily on remittances, but World Bank data shows crypto remittance corridors (El Salvador 2021-2023) processed less than 2% of total remittance volume despite legal tender status. Third, volatility: the claim that stablecoins solve this ignores that USDC and USDT require banking partnerships that fail precisely when most needed — SVB's collapse temporarily destabilized USDC. The inclusion argument conflates technical possibility (smartphones are widespread) with practical accessibility (the poor cannot afford 20% transaction fees on Ethereum mainnet or the volatility risk of self-custody).",
|
| 79 |
+
"rationale": "Scores 7 because the argument deploys specific, attributable data at each claim point: the 95% centralized exchange figure, the El Salvador 2% remittance figure, the SVB-USDC linkage. The argument distinguishes technical possibility from practical accessibility. Loses 3 points because the argument does not engage with the strongest pro-crypto evidence: the peer-to-peer bitcoin usage in Nigeria during the 2021 banking ban, which represents genuine financial activity outside banking infrastructure. A high-tier evidence argument would address this case before generalizing.",
|
| 80 |
+
"side_note": "Con-side evidence-accuracy example at high-mid tier — specific data deployment with appropriate distinction-drawing"
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"id": "ex-137",
|
| 84 |
+
"scoreLevel": 5,
|
| 85 |
+
"dimensionId": "overall",
|
| 86 |
+
"topic": "Civil disobedience is justified when laws are unjust",
|
| 87 |
+
"side": "pro",
|
| 88 |
+
"argument": "Civil disobedience has a noble history. MLK used it successfully. When laws are clearly wrong — like segregation — breaking them is moral. But it should be non-violent and accept punishment. If everyone disobeys laws they dislike, society collapses. So it should be rare and for truly serious injustices. The Civil Rights Movement shows it works when done right.",
|
| 89 |
+
"rationale": "Scores 5 because the argument references the paradigmatic case (MLK, Civil Rights Movement) and gestures toward constraints (non-violence, acceptance of punishment, rarity). However, the MLK case is deployed as authority rather than analyzed for its features. The 'if everyone disobeys' slippery slope is raised but not developed. The argument does not define 'truly serious injustices' or explain why segregation qualifies while other grievances might not. Scores at mid-tier because the right categories are present but underdeveloped.",
|
| 90 |
+
"side_note": "Pro-side overall example at mid tier — references paradigmatic case but underdeveloped analysis"
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"id": "ex-138",
|
| 94 |
+
"scoreLevel": 8,
|
| 95 |
+
"dimensionId": "rebuttal-quality",
|
| 96 |
+
"topic": "Wealthy nations have a moral obligation to accept refugees",
|
| 97 |
+
"side": "pro",
|
| 98 |
+
"argument": "My opponent argues that wealthy nations lack special obligations to refugees, treating national borders as morally decisive boundaries. I engage this through three responses. First, the causation response: many refugee flows stem from actions wealthy nations took — climate change disproportionately driven by Northern emissions, wars supported by Western arms sales, economic policies that destabilized source regions. If causation matters for responsibility, the obligation is not charity but rectification. Second, the capacity principle: we accept that those who can rescue at low cost to themselves should do so — the drowning child in the pond. Wealthy nations can absorb refugees at lower relative cost than neighboring poor countries already hosting 80% of refugees. Third, the arbitrariness challenge: birth location is morally arbitrary, yet it determines life chances more than any other factor. Treating arbitrary facts as morally decisive requires justification my opponent has not provided. I acknowledge constraints: domestic political feasibility matters, and 'open borders' is not implied — but the obligation to contribute substantially to resettlement follows from these premises.",
|
| 99 |
+
"rationale": "Scores 8 because the rebuttal engages the opponent's position through three distinct argumentative responses, each developed with specific grounding: causation with empirical mechanisms, capacity with the drowning child analogy and the 80% hosting figure, arbitrariness with the challenge to justify morally weighting birth location. The acknowledgment of constraints (political feasibility, not implying open borders) demonstrates boundary-awareness. Loses 2 points because the causation response could be stronger: the debater lists mechanisms but does not establish quantitative responsibility shares or address how causation-based obligation works when multiple agents contributed.",
|
| 100 |
+
"side_note": "Pro-side rebuttal-quality example at high tier — three distinct developed responses with specific grounding"
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"id": "ex-139",
|
| 104 |
+
"scoreLevel": 4,
|
| 105 |
+
"dimensionId": "intellectual-honesty",
|
| 106 |
+
"topic": "AI will cause mass unemployment within 20 years",
|
| 107 |
+
"side": "pro",
|
| 108 |
+
"argument": "AI is coming for our jobs. Look at what GPT-4 can already do. Truckers will be gone, replaced by self-driving. Office workers too. The technology is advancing exponentially. Anyone who says otherwise is in denial. History shows technology always disrupts, this time is just faster. We need UBI now before it's too late.",
|
| 109 |
+
"rationale": "Scores 4 because the argument makes strong predictive claims without appropriate epistemic hedging. 'Exponentially' is asserted rather than evidenced. 'Anyone who says otherwise is in denial' is dismissive rather than engaging counterarguments. The argument does not acknowledge uncertainty ranges or consider historical cases where technological displacement was slower than predicted (automation of legal discovery, which augmented rather than replaced lawyers). The UBI prescription follows as if it were the obvious implication, without considering alternatives (retraining, shorter work weeks). Scores above 1-3 because at least the right phenomenon category is identified.",
|
| 110 |
+
"side_note": "Pro-side intellectual-honesty example at low-mid tier — strong claims without appropriate epistemic hedging"
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"id": "ex-140",
|
| 114 |
+
"scoreLevel": 7,
|
| 115 |
+
"dimensionId": "persuasiveness",
|
| 116 |
+
"topic": "The filibuster should be abolished in the US Senate",
|
| 117 |
+
"side": "con",
|
| 118 |
+
"argument": "Abolishing the filibuster sounds appealing when your party holds 51 seats. But consider the temporal instability this creates. Under a simple-majority Senate, major policy swings every 2-4 years: Republicans pass their agenda 2017-2018, Democrats reverse and replace it 2021-2022, Republicans return in 2025. The resulting policy whiplash undermines the planning horizon businesses and individuals need — who invests in a 10-year project when the regulatory framework may flip in 2? The filibuster's modest supermajority requirement forces some bipartisan accommodation, creating policy durability. I acknowledge the democratic objection: 41 senators representing 11% blocking 89% seems unjust. But democracy is not merely head-counting — it includes stability, predictability, and protection against rapid majoritarian swings. The 60-vote threshold is one of the few remaining brakes on simple majoritarianism in a system where the House and Electoral College already favor populism. The question is whether you value legislative efficiency more than policy stability. Most Americans, when they consider living through whiplash, choose stability.",
|
| 119 |
+
"rationale": "Scores 7 because the argument constructs a persuasive case through a specific mechanism (temporal instability/policy whiplash) that resonates with audience experience of unpredictability. The 'who invests' question is rhetorically effective. The reframing of democracy to include stability is principled rather than merely tactical. The acknowledgment of the 11% objection before rebutting it shows responsiveness. Loses 3 points because the argument does not engage with the strongest counterargument: that the filibuster as currently practiced (silent 60-vote threshold) bears little resemblance to the 'talking filibuster' that enabled the Senate's legendary deliberation. The argument treats the current dysfunction as inherent to supermajority requirements rather than specific to the modern implementation.",
|
| 120 |
+
"side_note": "Con-side persuasiveness example at high-mid tier — effective temporal instability framing with rhetorical skill"
|
| 121 |
+
}
|
| 122 |
+
]
|
next.config.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { NextConfig } from "next";
|
| 2 |
+
|
| 3 |
+
const nextConfig: NextConfig = {
|
| 4 |
+
/* config options here */
|
| 5 |
+
};
|
| 6 |
+
|
| 7 |
+
export default nextConfig;
|
package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "rotnot-work",
|
| 3 |
+
"version": "0.1.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "next dev",
|
| 7 |
+
"build": "next build",
|
| 8 |
+
"start": "next start",
|
| 9 |
+
"postinstall": "prisma generate",
|
| 10 |
+
"lint": "eslint",
|
| 11 |
+
"test": "vitest run",
|
| 12 |
+
"test:watch": "vitest",
|
| 13 |
+
"typecheck": "tsc --noEmit"
|
| 14 |
+
},
|
| 15 |
+
"dependencies": {
|
| 16 |
+
"@anthropic-ai/sdk": "^0.82.0",
|
| 17 |
+
"@base-ui/react": "^1.3.0",
|
| 18 |
+
"@capacitor/android": "^8.2.0",
|
| 19 |
+
"@capacitor/cli": "^8.2.0",
|
| 20 |
+
"@capacitor/core": "^8.2.0",
|
| 21 |
+
"@capacitor/haptics": "^8.0.1",
|
| 22 |
+
"@capacitor/ios": "^8.2.0",
|
| 23 |
+
"@capacitor/local-notifications": "^8.0.2",
|
| 24 |
+
"@capacitor/push-notifications": "^8.0.2",
|
| 25 |
+
"@capacitor/status-bar": "^8.0.1",
|
| 26 |
+
"@libsql/client": "^0.17.0",
|
| 27 |
+
"@prisma/adapter-libsql": "^7.5.0",
|
| 28 |
+
"@prisma/client": "^7.5.0",
|
| 29 |
+
"chess.js": "^1.4.0",
|
| 30 |
+
"class-variance-authority": "^0.7.1",
|
| 31 |
+
"clsx": "^2.1.1",
|
| 32 |
+
"date-fns": "^4.1.0",
|
| 33 |
+
"framer-motion": "^12.38.0",
|
| 34 |
+
"langsmith": "^0.5.15",
|
| 35 |
+
"lucide-react": "^0.577.0",
|
| 36 |
+
"next": "16.1.7",
|
| 37 |
+
"react": "19.2.3",
|
| 38 |
+
"react-chessboard": "^5.10.0",
|
| 39 |
+
"react-dom": "19.2.3",
|
| 40 |
+
"recharts": "^3.8.0",
|
| 41 |
+
"shadcn": "^4.0.8",
|
| 42 |
+
"tailwind-merge": "^3.5.0",
|
| 43 |
+
"tw-animate-css": "^1.4.0"
|
| 44 |
+
},
|
| 45 |
+
"prisma": {
|
| 46 |
+
"seed": "npx tsx prisma/seed.ts"
|
| 47 |
+
},
|
| 48 |
+
"devDependencies": {
|
| 49 |
+
"@playwright/test": "^1.61.1",
|
| 50 |
+
"@tailwindcss/postcss": "^4",
|
| 51 |
+
"@types/node": "^20",
|
| 52 |
+
"@types/react": "^19",
|
| 53 |
+
"@types/react-dom": "^19",
|
| 54 |
+
"eslint": "^9",
|
| 55 |
+
"eslint-config-next": "16.1.7",
|
| 56 |
+
"prisma": "^7.5.0",
|
| 57 |
+
"tailwindcss": "^4",
|
| 58 |
+
"tsx": "^4.21.0",
|
| 59 |
+
"typescript": "^5.9.3",
|
| 60 |
+
"vitest": "^4.1.0"
|
| 61 |
+
}
|
| 62 |
+
}
|
playwright.coding.config.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { defineConfig } from "@playwright/test";
|
| 2 |
+
|
| 3 |
+
// Dedicated E2E config for the Coding Training flow. Runs against a local
|
| 4 |
+
// production server on port 3101 and uses the pre-installed Chromium.
|
| 5 |
+
export default defineConfig({
|
| 6 |
+
testDir: "./e2e",
|
| 7 |
+
testMatch: "coding.spec.ts",
|
| 8 |
+
timeout: 60_000,
|
| 9 |
+
expect: { timeout: 10_000 },
|
| 10 |
+
fullyParallel: false,
|
| 11 |
+
workers: 1,
|
| 12 |
+
use: {
|
| 13 |
+
baseURL: "http://localhost:3101",
|
| 14 |
+
headless: true,
|
| 15 |
+
screenshot: "only-on-failure",
|
| 16 |
+
launchOptions: {
|
| 17 |
+
executablePath: "/opt/pw-browsers/chromium-1194/chrome-linux/chrome",
|
| 18 |
+
},
|
| 19 |
+
},
|
| 20 |
+
webServer: {
|
| 21 |
+
command: "npm run start -- -p 3101",
|
| 22 |
+
url: "http://localhost:3101",
|
| 23 |
+
reuseExistingServer: true,
|
| 24 |
+
timeout: 60_000,
|
| 25 |
+
},
|
| 26 |
+
});
|
playwright.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { defineConfig } from '@playwright/test';
|
| 2 |
+
export default defineConfig({
|
| 3 |
+
testDir: './e2e',
|
| 4 |
+
use: {
|
| 5 |
+
baseURL: 'http://192.168.1.166:3101',
|
| 6 |
+
headless: true,
|
| 7 |
+
screenshot: 'only-on-failure',
|
| 8 |
+
video: 'retain-on-failure',
|
| 9 |
+
},
|
| 10 |
+
webServer: {
|
| 11 |
+
command: 'npm run dev',
|
| 12 |
+
url: 'http://192.168.1.166:3101',
|
| 13 |
+
reuseExistingServer: true,
|
| 14 |
+
timeout: 30000,
|
| 15 |
+
},
|
| 16 |
+
});
|
postcss.config.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const config = {
|
| 2 |
+
plugins: {
|
| 3 |
+
"@tailwindcss/postcss": {},
|
| 4 |
+
},
|
| 5 |
+
};
|
| 6 |
+
|
| 7 |
+
export default config;
|
prisma.config.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// This file was generated by Prisma, and assumes you have installed the following:
|
| 2 |
+
// npm install --save-dev prisma dotenv
|
| 3 |
+
import "dotenv/config";
|
| 4 |
+
import { defineConfig } from "prisma/config";
|
| 5 |
+
|
| 6 |
+
export default defineConfig({
|
| 7 |
+
schema: "prisma/schema.prisma",
|
| 8 |
+
migrations: {
|
| 9 |
+
path: "prisma/migrations",
|
| 10 |
+
seed: "npx tsx prisma/seed.ts",
|
| 11 |
+
},
|
| 12 |
+
datasource: {
|
| 13 |
+
url: process.env["DATABASE_URL"],
|
| 14 |
+
},
|
| 15 |
+
});
|
prisma/migrations/20260318034440_init/migration.sql
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- CreateTable
|
| 2 |
+
CREATE TABLE "User" (
|
| 3 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 4 |
+
"name" TEXT NOT NULL,
|
| 5 |
+
"level" INTEGER NOT NULL DEFAULT 1,
|
| 6 |
+
"totalXp" INTEGER NOT NULL DEFAULT 0,
|
| 7 |
+
"currentXp" INTEGER NOT NULL DEFAULT 0,
|
| 8 |
+
"xpToNextLevel" INTEGER NOT NULL DEFAULT 100,
|
| 9 |
+
"title" TEXT NOT NULL DEFAULT 'Smooth Brain',
|
| 10 |
+
"dailyGoalXp" INTEGER NOT NULL DEFAULT 100,
|
| 11 |
+
"streak" INTEGER NOT NULL DEFAULT 0,
|
| 12 |
+
"longestStreak" INTEGER NOT NULL DEFAULT 0,
|
| 13 |
+
"streakFreezes" INTEGER NOT NULL DEFAULT 0,
|
| 14 |
+
"lichessUsername" TEXT,
|
| 15 |
+
"chesscomUsername" TEXT,
|
| 16 |
+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 17 |
+
);
|
| 18 |
+
|
| 19 |
+
-- CreateTable
|
| 20 |
+
CREATE TABLE "CategorySkill" (
|
| 21 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 22 |
+
"userId" INTEGER NOT NULL,
|
| 23 |
+
"category" TEXT NOT NULL,
|
| 24 |
+
"level" INTEGER NOT NULL DEFAULT 1,
|
| 25 |
+
"totalXp" INTEGER NOT NULL DEFAULT 0,
|
| 26 |
+
"currentXp" INTEGER NOT NULL DEFAULT 0,
|
| 27 |
+
"xpToNext" INTEGER NOT NULL DEFAULT 100,
|
| 28 |
+
CONSTRAINT "CategorySkill_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
| 29 |
+
);
|
| 30 |
+
|
| 31 |
+
-- CreateTable
|
| 32 |
+
CREATE TABLE "Activity" (
|
| 33 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 34 |
+
"userId" INTEGER NOT NULL,
|
| 35 |
+
"category" TEXT NOT NULL,
|
| 36 |
+
"exerciseType" TEXT NOT NULL,
|
| 37 |
+
"description" TEXT NOT NULL,
|
| 38 |
+
"baseXp" INTEGER NOT NULL,
|
| 39 |
+
"qualityBonus" INTEGER NOT NULL DEFAULT 0,
|
| 40 |
+
"isCriticalHit" BOOLEAN NOT NULL DEFAULT false,
|
| 41 |
+
"totalXp" INTEGER NOT NULL,
|
| 42 |
+
"score" REAL,
|
| 43 |
+
"durationSecs" INTEGER,
|
| 44 |
+
"metadata" TEXT,
|
| 45 |
+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 46 |
+
CONSTRAINT "Activity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
| 47 |
+
);
|
| 48 |
+
|
| 49 |
+
-- CreateTable
|
| 50 |
+
CREATE TABLE "DailyLog" (
|
| 51 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 52 |
+
"userId" INTEGER NOT NULL,
|
| 53 |
+
"date" DATETIME NOT NULL,
|
| 54 |
+
"xpEarned" INTEGER NOT NULL DEFAULT 0,
|
| 55 |
+
"activityCount" INTEGER NOT NULL DEFAULT 0,
|
| 56 |
+
"goalMet" BOOLEAN NOT NULL DEFAULT false,
|
| 57 |
+
"streakFreezeUsed" BOOLEAN NOT NULL DEFAULT false,
|
| 58 |
+
CONSTRAINT "DailyLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
| 59 |
+
);
|
| 60 |
+
|
| 61 |
+
-- CreateTable
|
| 62 |
+
CREATE TABLE "SkillTreeNode" (
|
| 63 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 64 |
+
"category" TEXT NOT NULL,
|
| 65 |
+
"name" TEXT NOT NULL,
|
| 66 |
+
"description" TEXT NOT NULL,
|
| 67 |
+
"levelRequired" INTEGER NOT NULL,
|
| 68 |
+
"parentNodeId" INTEGER,
|
| 69 |
+
"nodeType" TEXT NOT NULL,
|
| 70 |
+
CONSTRAINT "SkillTreeNode_parentNodeId_fkey" FOREIGN KEY ("parentNodeId") REFERENCES "SkillTreeNode" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
| 71 |
+
);
|
| 72 |
+
|
| 73 |
+
-- CreateTable
|
| 74 |
+
CREATE TABLE "Unlock" (
|
| 75 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 76 |
+
"userId" INTEGER NOT NULL,
|
| 77 |
+
"nodeId" INTEGER NOT NULL,
|
| 78 |
+
"unlockedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 79 |
+
CONSTRAINT "Unlock_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
| 80 |
+
CONSTRAINT "Unlock_nodeId_fkey" FOREIGN KEY ("nodeId") REFERENCES "SkillTreeNode" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
| 81 |
+
);
|
| 82 |
+
|
| 83 |
+
-- CreateTable
|
| 84 |
+
CREATE TABLE "ContentItem" (
|
| 85 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 86 |
+
"category" TEXT NOT NULL,
|
| 87 |
+
"title" TEXT NOT NULL,
|
| 88 |
+
"content" TEXT NOT NULL,
|
| 89 |
+
"difficulty" TEXT NOT NULL,
|
| 90 |
+
"domain" TEXT NOT NULL,
|
| 91 |
+
"source" TEXT NOT NULL,
|
| 92 |
+
"metadata" TEXT,
|
| 93 |
+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 94 |
+
);
|
| 95 |
+
|
| 96 |
+
-- CreateIndex
|
| 97 |
+
CREATE UNIQUE INDEX "CategorySkill_userId_category_key" ON "CategorySkill"("userId", "category");
|
| 98 |
+
|
| 99 |
+
-- CreateIndex
|
| 100 |
+
CREATE UNIQUE INDEX "DailyLog_userId_date_key" ON "DailyLog"("userId", "date");
|
| 101 |
+
|
| 102 |
+
-- CreateIndex
|
| 103 |
+
CREATE UNIQUE INDEX "SkillTreeNode_category_name_key" ON "SkillTreeNode"("category", "name");
|
| 104 |
+
|
| 105 |
+
-- CreateIndex
|
| 106 |
+
CREATE UNIQUE INDEX "Unlock_userId_nodeId_key" ON "Unlock"("userId", "nodeId");
|
prisma/migrations/20260321061731_add_spaced_repetition/migration.sql
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- CreateTable
|
| 2 |
+
CREATE TABLE "SpacedRepetitionItem" (
|
| 3 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 4 |
+
"userId" INTEGER NOT NULL,
|
| 5 |
+
"category" TEXT NOT NULL DEFAULT 'feynman',
|
| 6 |
+
"topicId" TEXT NOT NULL,
|
| 7 |
+
"topic" TEXT NOT NULL,
|
| 8 |
+
"domain" TEXT NOT NULL,
|
| 9 |
+
"difficulty" TEXT NOT NULL,
|
| 10 |
+
"stage" INTEGER NOT NULL DEFAULT 0,
|
| 11 |
+
"nextReviewAt" DATETIME NOT NULL,
|
| 12 |
+
"lastReviewAt" DATETIME,
|
| 13 |
+
"lastScore" REAL,
|
| 14 |
+
"totalReviews" INTEGER NOT NULL DEFAULT 0,
|
| 15 |
+
"successCount" INTEGER NOT NULL DEFAULT 0,
|
| 16 |
+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 17 |
+
CONSTRAINT "SpacedRepetitionItem_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
-- CreateIndex
|
| 21 |
+
CREATE INDEX "SpacedRepetitionItem_userId_nextReviewAt_idx" ON "SpacedRepetitionItem"("userId", "nextReviewAt");
|
| 22 |
+
|
| 23 |
+
-- CreateIndex
|
| 24 |
+
CREATE INDEX "SpacedRepetitionItem_userId_category_idx" ON "SpacedRepetitionItem"("userId", "category");
|
| 25 |
+
|
| 26 |
+
-- CreateIndex
|
| 27 |
+
CREATE UNIQUE INDEX "SpacedRepetitionItem_userId_topicId_key" ON "SpacedRepetitionItem"("userId", "topicId");
|
prisma/migrations/20260321141626_add_topic_sources_and_teaching_cache/migration.sql
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- CreateTable
|
| 2 |
+
CREATE TABLE "TopicSource" (
|
| 3 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 4 |
+
"topicId" TEXT NOT NULL,
|
| 5 |
+
"url" TEXT NOT NULL,
|
| 6 |
+
"title" TEXT NOT NULL,
|
| 7 |
+
"excerpt" TEXT NOT NULL,
|
| 8 |
+
"domain" TEXT NOT NULL,
|
| 9 |
+
"license" TEXT NOT NULL,
|
| 10 |
+
"confidence" TEXT NOT NULL DEFAULT 'moderate',
|
| 11 |
+
"verifiedAt" DATETIME,
|
| 12 |
+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
| 13 |
+
);
|
| 14 |
+
|
| 15 |
+
-- CreateTable
|
| 16 |
+
CREATE TABLE "TeachingCache" (
|
| 17 |
+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
| 18 |
+
"topicId" TEXT NOT NULL,
|
| 19 |
+
"content" TEXT NOT NULL,
|
| 20 |
+
"sourcesJson" TEXT NOT NULL,
|
| 21 |
+
"confidenceScore" TEXT NOT NULL DEFAULT 'moderate',
|
| 22 |
+
"generatedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 23 |
+
"verifiedAt" DATETIME
|
| 24 |
+
);
|
| 25 |
+
|
| 26 |
+
-- CreateIndex
|
| 27 |
+
CREATE INDEX "TopicSource_topicId_idx" ON "TopicSource"("topicId");
|
| 28 |
+
|
| 29 |
+
-- CreateIndex
|
| 30 |
+
CREATE UNIQUE INDEX "TeachingCache_topicId_key" ON "TeachingCache"("topicId");
|
| 31 |
+
|
| 32 |
+
-- CreateIndex
|
| 33 |
+
CREATE INDEX "TeachingCache_topicId_idx" ON "TeachingCache"("topicId");
|
prisma/migrations/migration_lock.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Please do not edit this file manually
|
| 2 |
+
# It should be added in your version-control system (e.g., Git)
|
| 3 |
+
provider = "sqlite"
|
prisma/schema.prisma
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
generator client {
|
| 2 |
+
provider = "prisma-client-js"
|
| 3 |
+
}
|
| 4 |
+
|
| 5 |
+
datasource db {
|
| 6 |
+
provider = "sqlite"
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
model User {
|
| 10 |
+
id Int @id @default(autoincrement())
|
| 11 |
+
name String
|
| 12 |
+
level Int @default(1)
|
| 13 |
+
totalXp Int @default(0)
|
| 14 |
+
currentXp Int @default(0)
|
| 15 |
+
xpToNextLevel Int @default(100)
|
| 16 |
+
title String @default("Smooth Brain")
|
| 17 |
+
dailyGoalXp Int @default(100)
|
| 18 |
+
streak Int @default(0)
|
| 19 |
+
longestStreak Int @default(0)
|
| 20 |
+
streakFreezes Int @default(0)
|
| 21 |
+
lichessUsername String?
|
| 22 |
+
chesscomUsername String?
|
| 23 |
+
createdAt DateTime @default(now())
|
| 24 |
+
|
| 25 |
+
activities Activity[]
|
| 26 |
+
dailyLogs DailyLog[]
|
| 27 |
+
categorySkills CategorySkill[]
|
| 28 |
+
unlocks Unlock[]
|
| 29 |
+
spacedRepetitionItems SpacedRepetitionItem[]
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
model CategorySkill {
|
| 33 |
+
id Int @id @default(autoincrement())
|
| 34 |
+
userId Int
|
| 35 |
+
category String
|
| 36 |
+
level Int @default(1)
|
| 37 |
+
totalXp Int @default(0)
|
| 38 |
+
currentXp Int @default(0)
|
| 39 |
+
xpToNext Int @default(100)
|
| 40 |
+
|
| 41 |
+
user User @relation(fields: [userId], references: [id])
|
| 42 |
+
|
| 43 |
+
@@unique([userId, category])
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
model Activity {
|
| 47 |
+
id Int @id @default(autoincrement())
|
| 48 |
+
userId Int
|
| 49 |
+
category String
|
| 50 |
+
exerciseType String
|
| 51 |
+
description String
|
| 52 |
+
baseXp Int
|
| 53 |
+
qualityBonus Int @default(0)
|
| 54 |
+
isCriticalHit Boolean @default(false)
|
| 55 |
+
totalXp Int
|
| 56 |
+
score Float?
|
| 57 |
+
durationSecs Int?
|
| 58 |
+
metadata String?
|
| 59 |
+
createdAt DateTime @default(now())
|
| 60 |
+
|
| 61 |
+
user User @relation(fields: [userId], references: [id])
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
model DailyLog {
|
| 65 |
+
id Int @id @default(autoincrement())
|
| 66 |
+
userId Int
|
| 67 |
+
date DateTime
|
| 68 |
+
xpEarned Int @default(0)
|
| 69 |
+
activityCount Int @default(0)
|
| 70 |
+
goalMet Boolean @default(false)
|
| 71 |
+
streakFreezeUsed Boolean @default(false)
|
| 72 |
+
|
| 73 |
+
user User @relation(fields: [userId], references: [id])
|
| 74 |
+
|
| 75 |
+
@@unique([userId, date])
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
model SkillTreeNode {
|
| 79 |
+
id Int @id @default(autoincrement())
|
| 80 |
+
category String
|
| 81 |
+
name String
|
| 82 |
+
description String
|
| 83 |
+
levelRequired Int
|
| 84 |
+
parentNodeId Int?
|
| 85 |
+
nodeType String
|
| 86 |
+
|
| 87 |
+
parent SkillTreeNode? @relation("NodeTree", fields: [parentNodeId], references: [id])
|
| 88 |
+
children SkillTreeNode[] @relation("NodeTree")
|
| 89 |
+
unlocks Unlock[]
|
| 90 |
+
|
| 91 |
+
@@unique([category, name])
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
model Unlock {
|
| 95 |
+
id Int @id @default(autoincrement())
|
| 96 |
+
userId Int
|
| 97 |
+
nodeId Int
|
| 98 |
+
unlockedAt DateTime @default(now())
|
| 99 |
+
|
| 100 |
+
user User @relation(fields: [userId], references: [id])
|
| 101 |
+
node SkillTreeNode @relation(fields: [nodeId], references: [id])
|
| 102 |
+
|
| 103 |
+
@@unique([userId, nodeId])
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
model ContentItem {
|
| 107 |
+
id Int @id @default(autoincrement())
|
| 108 |
+
category String
|
| 109 |
+
title String
|
| 110 |
+
content String
|
| 111 |
+
difficulty String
|
| 112 |
+
domain String
|
| 113 |
+
source String
|
| 114 |
+
metadata String?
|
| 115 |
+
createdAt DateTime @default(now())
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
model TopicSource {
|
| 119 |
+
id Int @id @default(autoincrement())
|
| 120 |
+
topicId String // matches Topic.id from feynman/topics.ts
|
| 121 |
+
url String // source URL
|
| 122 |
+
title String // source page/article title
|
| 123 |
+
excerpt String // relevant excerpt from the source
|
| 124 |
+
domain String // e.g., "wikipedia", "openstax", "arxiv"
|
| 125 |
+
license String // e.g., "CC BY-SA 4.0", "CC0", "public-domain"
|
| 126 |
+
confidence String @default("moderate") // "high", "moderate", "low"
|
| 127 |
+
verifiedAt DateTime? // when URL was last verified as live
|
| 128 |
+
createdAt DateTime @default(now())
|
| 129 |
+
|
| 130 |
+
@@index([topicId])
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
model TeachingCache {
|
| 134 |
+
id Int @id @default(autoincrement())
|
| 135 |
+
topicId String @unique // one cached teaching per topic
|
| 136 |
+
content String // the grounded teaching explanation (markdown)
|
| 137 |
+
sourcesJson String // JSON array of { url, title, domain, license } used
|
| 138 |
+
confidenceScore String @default("moderate") // "high" (2+ corroborating), "moderate" (1), "low" (extrapolated)
|
| 139 |
+
generatedAt DateTime @default(now())
|
| 140 |
+
verifiedAt DateTime? // when content was last verified against sources
|
| 141 |
+
|
| 142 |
+
@@index([topicId])
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
model SpacedRepetitionItem {
|
| 146 |
+
id Int @id @default(autoincrement())
|
| 147 |
+
userId Int
|
| 148 |
+
category String @default("feynman")
|
| 149 |
+
topicId String // matches Topic.id from feynman/topics.ts
|
| 150 |
+
topic String // human-readable topic name
|
| 151 |
+
domain String
|
| 152 |
+
difficulty String // beginner | intermediate | expert
|
| 153 |
+
stage Int @default(0) // 0=new, 1-5 = review stages
|
| 154 |
+
nextReviewAt DateTime // when the next review is due
|
| 155 |
+
lastReviewAt DateTime? // when last reviewed (null = never reviewed yet)
|
| 156 |
+
lastScore Float? // score from most recent review (0-1)
|
| 157 |
+
totalReviews Int @default(0)
|
| 158 |
+
successCount Int @default(0) // reviews scoring >= 0.6
|
| 159 |
+
createdAt DateTime @default(now())
|
| 160 |
+
|
| 161 |
+
user User @relation(fields: [userId], references: [id])
|
| 162 |
+
|
| 163 |
+
@@unique([userId, topicId])
|
| 164 |
+
@@index([userId, nextReviewAt])
|
| 165 |
+
@@index([userId, category])
|
| 166 |
+
}
|
prisma/seed.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { PrismaClient } from "@prisma/client";
|
| 2 |
+
import { PrismaLibSql } from "@prisma/adapter-libsql";
|
| 3 |
+
import path from "path";
|
| 4 |
+
|
| 5 |
+
const dbPath = path.resolve(process.cwd(), "dev.db");
|
| 6 |
+
const adapter = new PrismaLibSql({ url: `file:${dbPath}` });
|
| 7 |
+
const prisma = new PrismaClient({ adapter });
|
| 8 |
+
|
| 9 |
+
const CATEGORIES = [
|
| 10 |
+
"chess",
|
| 11 |
+
"reading",
|
| 12 |
+
"feynman",
|
| 13 |
+
"logic",
|
| 14 |
+
"critical-thinking",
|
| 15 |
+
"quests",
|
| 16 |
+
"coding",
|
| 17 |
+
] as const;
|
| 18 |
+
|
| 19 |
+
// Skill tree nodes defined without relying on hardcoded IDs.
|
| 20 |
+
// parentNodeId references are resolved by looking up the previously created node's real ID.
|
| 21 |
+
type NodeDef = {
|
| 22 |
+
category: string;
|
| 23 |
+
name: string;
|
| 24 |
+
description: string;
|
| 25 |
+
levelRequired: number;
|
| 26 |
+
nodeType: string;
|
| 27 |
+
parentKey: string | null; // "category:name" of parent, or null
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
const SKILL_TREE_NODES: NodeDef[] = [
|
| 31 |
+
// Chess
|
| 32 |
+
{ category: "chess", name: "Chess Initiate", description: "Begin your chess journey", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 33 |
+
{ category: "chess", name: "Puzzle Warrior", description: "Unlock 1200+ rated puzzles", levelRequired: 5, nodeType: "difficulty", parentKey: "chess:Chess Initiate" },
|
| 34 |
+
{ category: "chess", name: "Endgame Student", description: "Unlock endgame puzzles", levelRequired: 5, nodeType: "exercise-type", parentKey: "chess:Chess Initiate" },
|
| 35 |
+
{ category: "chess", name: "Tactical Eye", description: "+10% Chess XP", levelRequired: 15, nodeType: "multiplier", parentKey: "chess:Puzzle Warrior" },
|
| 36 |
+
{ category: "chess", name: "Puzzle Master", description: "Unlock 1800+ rated puzzles", levelRequired: 20, nodeType: "difficulty", parentKey: "chess:Puzzle Warrior" },
|
| 37 |
+
{ category: "chess", name: "Streak Shield I", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "chess:Endgame Student" },
|
| 38 |
+
{ category: "chess", name: "Grandmaster Path", description: "+25% Chess XP", levelRequired: 30, nodeType: "multiplier", parentKey: "chess:Puzzle Master" },
|
| 39 |
+
{ category: "chess", name: "Grandthinker", description: "Chess mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "chess:Grandmaster Path" },
|
| 40 |
+
|
| 41 |
+
// Reading
|
| 42 |
+
{ category: "reading", name: "Page Turner", description: "Begin reading exercises", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 43 |
+
{ category: "reading", name: "Deep Diver", description: "Unlock intermediate articles", levelRequired: 5, nodeType: "difficulty", parentKey: "reading:Page Turner" },
|
| 44 |
+
{ category: "reading", name: "Speed Reader", description: "Unlock timed reading challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "reading:Page Turner" },
|
| 45 |
+
{ category: "reading", name: "Scholar", description: "Unlock advanced/academic content", levelRequired: 10, nodeType: "difficulty", parentKey: "reading:Deep Diver" },
|
| 46 |
+
{ category: "reading", name: "Focus Boost", description: "+10% Reading XP", levelRequired: 15, nodeType: "multiplier", parentKey: "reading:Scholar" },
|
| 47 |
+
{ category: "reading", name: "Reading Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "reading:Speed Reader" },
|
| 48 |
+
{ category: "reading", name: "Concentration Master", description: "+25% Reading XP", levelRequired: 30, nodeType: "multiplier", parentKey: "reading:Focus Boost" },
|
| 49 |
+
{ category: "reading", name: "The Deep Diver", description: "Reading mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "reading:Concentration Master" },
|
| 50 |
+
|
| 51 |
+
// Feynman
|
| 52 |
+
{ category: "feynman", name: "Curious Mind", description: "Begin Feynman challenges", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 53 |
+
{ category: "feynman", name: "Explainer", description: "Unlock intermediate topics", levelRequired: 5, nodeType: "difficulty", parentKey: "feynman:Curious Mind" },
|
| 54 |
+
{ category: "feynman", name: "Timed Explains", description: "Unlock timed mode", levelRequired: 5, nodeType: "exercise-type", parentKey: "feynman:Curious Mind" },
|
| 55 |
+
{ category: "feynman", name: "Professor", description: "Unlock expert topics", levelRequired: 15, nodeType: "difficulty", parentKey: "feynman:Explainer" },
|
| 56 |
+
{ category: "feynman", name: "Clarity Boost", description: "+10% Feynman XP", levelRequired: 15, nodeType: "multiplier", parentKey: "feynman:Timed Explains" },
|
| 57 |
+
{ category: "feynman", name: "Feynman Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "feynman:Explainer" },
|
| 58 |
+
{ category: "feynman", name: "Mastery Boost", description: "+25% Feynman XP", levelRequired: 30, nodeType: "multiplier", parentKey: "feynman:Professor" },
|
| 59 |
+
{ category: "feynman", name: "The Explainer", description: "Feynman mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "feynman:Mastery Boost" },
|
| 60 |
+
|
| 61 |
+
// Logic
|
| 62 |
+
{ category: "logic", name: "Logical Mind", description: "Begin logic puzzles", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 63 |
+
{ category: "logic", name: "Medium Puzzles", description: "Unlock medium difficulty", levelRequired: 5, nodeType: "difficulty", parentKey: "logic:Logical Mind" },
|
| 64 |
+
{ category: "logic", name: "Sequence Master", description: "Unlock number sequences", levelRequired: 5, nodeType: "exercise-type", parentKey: "logic:Logical Mind" },
|
| 65 |
+
{ category: "logic", name: "Hard Puzzles", description: "Unlock hard difficulty", levelRequired: 10, nodeType: "difficulty", parentKey: "logic:Medium Puzzles" },
|
| 66 |
+
{ category: "logic", name: "Logic Boost", description: "+10% Logic XP", levelRequired: 15, nodeType: "multiplier", parentKey: "logic:Hard Puzzles" },
|
| 67 |
+
{ category: "logic", name: "Expert Puzzles", description: "Unlock expert difficulty", levelRequired: 20, nodeType: "difficulty", parentKey: "logic:Hard Puzzles" },
|
| 68 |
+
{ category: "logic", name: "Logic Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "logic:Hard Puzzles" },
|
| 69 |
+
{ category: "logic", name: "Logic Mastery Boost", description: "+25% Logic XP", levelRequired: 30, nodeType: "multiplier", parentKey: "logic:Expert Puzzles" },
|
| 70 |
+
{ category: "logic", name: "Vulcan", description: "Logic mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "logic:Logic Mastery Boost" },
|
| 71 |
+
|
| 72 |
+
// Critical Thinking
|
| 73 |
+
{ category: "critical-thinking", name: "Flaw Finder: Easy", description: "Identify basic logical fallacies", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 74 |
+
{ category: "critical-thinking", name: "Flaw Finder: Medium", description: "Harder fallacy detection", levelRequired: 3, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Easy" },
|
| 75 |
+
{ category: "critical-thinking", name: "Steelman: Unlocked", description: "Construct strongest opposing arguments", levelRequired: 5, nodeType: "exercise-type", parentKey: "critical-thinking:Flaw Finder: Medium" },
|
| 76 |
+
{ category: "critical-thinking", name: "Flaw Finder: Hard", description: "Subtle fallacies and weak reasoning", levelRequired: 5, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Medium" },
|
| 77 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Unlocked", description: "Argue against your own positions", levelRequired: 10, nodeType: "exercise-type", parentKey: "critical-thinking:Steelman: Unlocked" },
|
| 78 |
+
{ category: "critical-thinking", name: "Steelman: Medium", description: "More nuanced positions", levelRequired: 10, nodeType: "difficulty", parentKey: "critical-thinking:Steelman: Unlocked" },
|
| 79 |
+
{ category: "critical-thinking", name: "Critical Boost", description: "+10% Critical Thinking XP", levelRequired: 10, nodeType: "multiplier", parentKey: "critical-thinking:Devil's Advocate: Unlocked" },
|
| 80 |
+
{ category: "critical-thinking", name: "Flaw Finder: Expert", description: "Professional-level analysis", levelRequired: 15, nodeType: "difficulty", parentKey: "critical-thinking:Flaw Finder: Hard" },
|
| 81 |
+
{ category: "critical-thinking", name: "CT Streak Shield", description: "Earn 1 streak freeze", levelRequired: 15, nodeType: "streak-shield", parentKey: "critical-thinking:Critical Boost" },
|
| 82 |
+
{ category: "critical-thinking", name: "Steelman: Hard", description: "Complex multi-faceted positions", levelRequired: 20, nodeType: "difficulty", parentKey: "critical-thinking:Steelman: Medium" },
|
| 83 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Medium", description: "Harder positions to argue against", levelRequired: 20, nodeType: "difficulty", parentKey: "critical-thinking:Devil's Advocate: Unlocked" },
|
| 84 |
+
{ category: "critical-thinking", name: "Devil's Advocate: Hard", description: "Expert-level contrarian arguments", levelRequired: 30, nodeType: "difficulty", parentKey: "critical-thinking:Devil's Advocate: Medium" },
|
| 85 |
+
{ category: "critical-thinking", name: "CT Mastery Boost", description: "+25% Critical Thinking XP", levelRequired: 30, nodeType: "multiplier", parentKey: "critical-thinking:Devil's Advocate: Hard" },
|
| 86 |
+
{ category: "critical-thinking", name: "Steel Trap", description: "Critical Thinking mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "critical-thinking:CT Mastery Boost" },
|
| 87 |
+
|
| 88 |
+
// Skill Quests
|
| 89 |
+
{ category: "quests", name: "Apprentice", description: "Begin skill quests", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 90 |
+
{ category: "quests", name: "Intermediate Quests", description: "Unlock intermediate lessons", levelRequired: 5, nodeType: "difficulty", parentKey: "quests:Apprentice" },
|
| 91 |
+
{ category: "quests", name: "Spaced Repetition", description: "Unlock review sessions", levelRequired: 5, nodeType: "exercise-type", parentKey: "quests:Apprentice" },
|
| 92 |
+
{ category: "quests", name: "Advanced Quests", description: "Unlock advanced lessons", levelRequired: 15, nodeType: "difficulty", parentKey: "quests:Intermediate Quests" },
|
| 93 |
+
{ category: "quests", name: "Quest Boost", description: "+10% Quest XP", levelRequired: 15, nodeType: "multiplier", parentKey: "quests:Spaced Repetition" },
|
| 94 |
+
{ category: "quests", name: "Quest Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "quests:Spaced Repetition" },
|
| 95 |
+
{ category: "quests", name: "Quest Mastery Boost", description: "+25% Quest XP", levelRequired: 30, nodeType: "multiplier", parentKey: "quests:Quest Boost" },
|
| 96 |
+
{ category: "quests", name: "Polymath", description: "Skill Quests mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "quests:Quest Mastery Boost" },
|
| 97 |
+
|
| 98 |
+
// Coding Training
|
| 99 |
+
{ category: "coding", name: "Code Initiate", description: "Begin coding training", levelRequired: 1, nodeType: "difficulty", parentKey: null },
|
| 100 |
+
{ category: "coding", name: "Debugger", description: "Unlock debugging challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "coding:Code Initiate" },
|
| 101 |
+
{ category: "coding", name: "Code Reviewer", description: "Unlock AI code-review challenges", levelRequired: 5, nodeType: "exercise-type", parentKey: "coding:Code Initiate" },
|
| 102 |
+
{ category: "coding", name: "Medium Problems", description: "Unlock medium difficulty", levelRequired: 8, nodeType: "difficulty", parentKey: "coding:Code Initiate" },
|
| 103 |
+
{ category: "coding", name: "Architect", description: "Unlock architecture discussions", levelRequired: 12, nodeType: "exercise-type", parentKey: "coding:Code Reviewer" },
|
| 104 |
+
{ category: "coding", name: "Hard Problems", description: "Unlock hard difficulty", levelRequired: 15, nodeType: "difficulty", parentKey: "coding:Medium Problems" },
|
| 105 |
+
{ category: "coding", name: "Clean Coder", description: "+10% Coding XP", levelRequired: 15, nodeType: "multiplier", parentKey: "coding:Debugger" },
|
| 106 |
+
{ category: "coding", name: "Coding Streak Shield", description: "Earn 1 streak freeze", levelRequired: 10, nodeType: "streak-shield", parentKey: "coding:Debugger" },
|
| 107 |
+
{ category: "coding", name: "Engineering Mastery", description: "+25% Coding XP", levelRequired: 30, nodeType: "multiplier", parentKey: "coding:Clean Coder" },
|
| 108 |
+
{ category: "coding", name: "10x Engineer", description: "Coding mastery title", levelRequired: 50, nodeType: "cosmetic", parentKey: "coding:Engineering Mastery" },
|
| 109 |
+
];
|
| 110 |
+
|
| 111 |
+
async function main() {
|
| 112 |
+
console.log("Seeding database...");
|
| 113 |
+
|
| 114 |
+
// Create default user
|
| 115 |
+
const user = await prisma.user.upsert({
|
| 116 |
+
where: { id: 1 },
|
| 117 |
+
update: {},
|
| 118 |
+
create: { name: "Player One" },
|
| 119 |
+
});
|
| 120 |
+
console.log(`User: ${user.name} (id=${user.id})`);
|
| 121 |
+
|
| 122 |
+
// Create category skills for all 6 categories
|
| 123 |
+
for (const category of CATEGORIES) {
|
| 124 |
+
await prisma.categorySkill.upsert({
|
| 125 |
+
where: { userId_category: { userId: user.id, category } },
|
| 126 |
+
update: {},
|
| 127 |
+
create: { userId: user.id, category },
|
| 128 |
+
});
|
| 129 |
+
}
|
| 130 |
+
console.log("Category skills created.");
|
| 131 |
+
|
| 132 |
+
// Build skill tree nodes in dependency order (BFS by parentKey)
|
| 133 |
+
// First pass: create all root nodes (parentKey === null)
|
| 134 |
+
const keyToId = new Map<string, number>();
|
| 135 |
+
|
| 136 |
+
for (const node of SKILL_TREE_NODES) {
|
| 137 |
+
if (node.parentKey !== null) continue;
|
| 138 |
+
const key = `${node.category}:${node.name}`;
|
| 139 |
+
const created = await prisma.skillTreeNode.upsert({
|
| 140 |
+
where: { category_name: { category: node.category, name: node.name } },
|
| 141 |
+
update: {},
|
| 142 |
+
create: {
|
| 143 |
+
category: node.category,
|
| 144 |
+
name: node.name,
|
| 145 |
+
description: node.description,
|
| 146 |
+
levelRequired: node.levelRequired,
|
| 147 |
+
nodeType: node.nodeType,
|
| 148 |
+
parentNodeId: null,
|
| 149 |
+
},
|
| 150 |
+
});
|
| 151 |
+
keyToId.set(key, created.id);
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// Subsequent passes: process nodes whose parent is already resolved
|
| 155 |
+
let remaining = SKILL_TREE_NODES.filter((n) => n.parentKey !== null);
|
| 156 |
+
let maxPasses = 10;
|
| 157 |
+
while (remaining.length > 0 && maxPasses-- > 0) {
|
| 158 |
+
const nextRound: NodeDef[] = [];
|
| 159 |
+
for (const node of remaining) {
|
| 160 |
+
const parentId = keyToId.get(node.parentKey!);
|
| 161 |
+
if (parentId === undefined) {
|
| 162 |
+
nextRound.push(node);
|
| 163 |
+
continue;
|
| 164 |
+
}
|
| 165 |
+
const key = `${node.category}:${node.name}`;
|
| 166 |
+
const created = await prisma.skillTreeNode.upsert({
|
| 167 |
+
where: { category_name: { category: node.category, name: node.name } },
|
| 168 |
+
update: {},
|
| 169 |
+
create: {
|
| 170 |
+
category: node.category,
|
| 171 |
+
name: node.name,
|
| 172 |
+
description: node.description,
|
| 173 |
+
levelRequired: node.levelRequired,
|
| 174 |
+
nodeType: node.nodeType,
|
| 175 |
+
parentNodeId: parentId,
|
| 176 |
+
},
|
| 177 |
+
});
|
| 178 |
+
keyToId.set(key, created.id);
|
| 179 |
+
}
|
| 180 |
+
remaining = nextRound;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if (remaining.length > 0) {
|
| 184 |
+
console.warn(`Warning: ${remaining.length} nodes could not be resolved:`, remaining.map((n) => n.name));
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
console.log(`Skill tree nodes created: ${keyToId.size}`);
|
| 188 |
+
console.log("Seed complete.");
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
main()
|
| 192 |
+
.catch((e) => {
|
| 193 |
+
console.error(e);
|
| 194 |
+
process.exit(1);
|
| 195 |
+
})
|
| 196 |
+
.finally(async () => {
|
| 197 |
+
await prisma.$disconnect();
|
| 198 |
+
});
|
public/file.svg
ADDED
|
|
public/globe.svg
ADDED
|
|
public/icons/icon-192.svg
ADDED
|
|
public/icons/icon-512.svg
ADDED
|
|
public/icons/icon-maskable.svg
ADDED
|
|
public/manifest.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "RotNot — Fight Brain Rot",
|
| 3 |
+
"short_name": "RotNot",
|
| 4 |
+
"description": "Gamified exercises to combat cognitive atrophy from AI over-reliance. Level up your mind.",
|
| 5 |
+
"start_url": "/",
|
| 6 |
+
"display": "standalone",
|
| 7 |
+
"background_color": "#080c18",
|
| 8 |
+
"theme_color": "#080c18",
|
| 9 |
+
"orientation": "any",
|
| 10 |
+
"categories": ["education", "games", "productivity"],
|
| 11 |
+
"icons": [
|
| 12 |
+
{
|
| 13 |
+
"src": "/icons/icon-192.svg",
|
| 14 |
+
"sizes": "192x192",
|
| 15 |
+
"type": "image/svg+xml",
|
| 16 |
+
"purpose": "any"
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"src": "/icons/icon-512.svg",
|
| 20 |
+
"sizes": "512x512",
|
| 21 |
+
"type": "image/svg+xml",
|
| 22 |
+
"purpose": "any"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"src": "/icons/icon-maskable.svg",
|
| 26 |
+
"sizes": "512x512",
|
| 27 |
+
"type": "image/svg+xml",
|
| 28 |
+
"purpose": "maskable"
|
| 29 |
+
}
|
| 30 |
+
]
|
| 31 |
+
}
|
public/next.svg
ADDED
|
|
public/service-worker.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// RotNot Service Worker
|
| 2 |
+
// Caching strategy: cache-first for static assets, stale-while-revalidate for API
|
| 3 |
+
|
| 4 |
+
const STATIC_CACHE = 'rotnot-static-v1';
|
| 5 |
+
const API_CACHE = 'rotnot-api-v1';
|
| 6 |
+
|
| 7 |
+
// Static assets to precache on install
|
| 8 |
+
const PRECACHE_URLS = [
|
| 9 |
+
'/',
|
| 10 |
+
'/manifest.json',
|
| 11 |
+
'/icons/icon-192.svg',
|
| 12 |
+
'/icons/icon-512.svg',
|
| 13 |
+
];
|
| 14 |
+
|
| 15 |
+
// Install: precache core shell
|
| 16 |
+
self.addEventListener('install', (event) => {
|
| 17 |
+
event.waitUntil(
|
| 18 |
+
caches.open(STATIC_CACHE).then((cache) => {
|
| 19 |
+
return cache.addAll(PRECACHE_URLS);
|
| 20 |
+
}).then(() => self.skipWaiting())
|
| 21 |
+
);
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
// Activate: clean old caches
|
| 25 |
+
self.addEventListener('activate', (event) => {
|
| 26 |
+
const currentCaches = [STATIC_CACHE, API_CACHE];
|
| 27 |
+
event.waitUntil(
|
| 28 |
+
caches.keys().then((cacheNames) => {
|
| 29 |
+
return Promise.all(
|
| 30 |
+
cacheNames.filter((name) => !currentCaches.includes(name))
|
| 31 |
+
.map((name) => caches.delete(name))
|
| 32 |
+
);
|
| 33 |
+
}).then(() => self.clients.claim())
|
| 34 |
+
);
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
// Fetch handler
|
| 38 |
+
self.addEventListener('fetch', (event) => {
|
| 39 |
+
const { request } = event;
|
| 40 |
+
const url = new URL(request.url);
|
| 41 |
+
|
| 42 |
+
// Skip non-GET requests
|
| 43 |
+
if (request.method !== 'GET') return;
|
| 44 |
+
|
| 45 |
+
// Skip cross-origin requests
|
| 46 |
+
if (url.origin !== self.location.origin) return;
|
| 47 |
+
|
| 48 |
+
// API routes: stale-while-revalidate
|
| 49 |
+
if (url.pathname.startsWith('/api/')) {
|
| 50 |
+
event.respondWith(staleWhileRevalidate(request, API_CACHE));
|
| 51 |
+
return;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
// Static assets (JS, CSS, images, fonts): cache-first
|
| 55 |
+
if (isStaticAsset(url.pathname)) {
|
| 56 |
+
event.respondWith(cacheFirst(request, STATIC_CACHE));
|
| 57 |
+
return;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// Navigation requests (HTML pages): network-first with cache fallback
|
| 61 |
+
if (request.mode === 'navigate') {
|
| 62 |
+
event.respondWith(networkFirst(request, STATIC_CACHE));
|
| 63 |
+
return;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// Default: network-first
|
| 67 |
+
event.respondWith(networkFirst(request, STATIC_CACHE));
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
function isStaticAsset(pathname) {
|
| 71 |
+
return /\.(js|css|svg|png|jpg|jpeg|gif|webp|woff|woff2|ttf|ico)(\?.*)?$/.test(pathname)
|
| 72 |
+
|| pathname.startsWith('/_next/static/');
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// Cache-first: return cached if available, otherwise fetch and cache
|
| 76 |
+
async function cacheFirst(request, cacheName) {
|
| 77 |
+
const cached = await caches.match(request);
|
| 78 |
+
if (cached) return cached;
|
| 79 |
+
|
| 80 |
+
try {
|
| 81 |
+
const response = await fetch(request);
|
| 82 |
+
if (response.ok) {
|
| 83 |
+
const cache = await caches.open(cacheName);
|
| 84 |
+
cache.put(request, response.clone());
|
| 85 |
+
}
|
| 86 |
+
return response;
|
| 87 |
+
} catch {
|
| 88 |
+
return new Response('Offline', { status: 503, statusText: 'Service Unavailable' });
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// Network-first: try network, fall back to cache
|
| 93 |
+
async function networkFirst(request, cacheName) {
|
| 94 |
+
try {
|
| 95 |
+
const response = await fetch(request);
|
| 96 |
+
if (response.ok) {
|
| 97 |
+
const cache = await caches.open(cacheName);
|
| 98 |
+
cache.put(request, response.clone());
|
| 99 |
+
}
|
| 100 |
+
return response;
|
| 101 |
+
} catch {
|
| 102 |
+
const cached = await caches.match(request);
|
| 103 |
+
if (cached) return cached;
|
| 104 |
+
return new Response('Offline', { status: 503, statusText: 'Service Unavailable' });
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// Stale-while-revalidate: return cached immediately, update cache in background
|
| 109 |
+
async function staleWhileRevalidate(request, cacheName) {
|
| 110 |
+
const cache = await caches.open(cacheName);
|
| 111 |
+
const cached = await cache.match(request);
|
| 112 |
+
|
| 113 |
+
const fetchPromise = fetch(request).then((response) => {
|
| 114 |
+
if (response.ok) {
|
| 115 |
+
cache.put(request, response.clone());
|
| 116 |
+
}
|
| 117 |
+
return response;
|
| 118 |
+
}).catch(() => cached);
|
| 119 |
+
|
| 120 |
+
return cached || fetchPromise;
|
| 121 |
+
}
|
public/vercel.svg
ADDED
|
|
public/window.svg
ADDED
|
|
scripts/deploy-hf.sh
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Push the current commit to a Hugging Face Docker Space.
|
| 3 |
+
#
|
| 4 |
+
# Usage:
|
| 5 |
+
# export HF_TOKEN=hf_xxx # a WRITE token
|
| 6 |
+
# scripts/deploy-hf.sh <user>/<space>
|
| 7 |
+
#
|
| 8 |
+
# Snapshots the current git commit, swaps in the front-matter README the Space
|
| 9 |
+
# needs, and force-pushes it to the Space's main branch. The Space must already
|
| 10 |
+
# exist (create it once with Docker SDK — see deploy/huggingface/DEPLOY.md).
|
| 11 |
+
set -euo pipefail
|
| 12 |
+
|
| 13 |
+
SPACE="${1:?usage: deploy-hf.sh <user>/<space>}"
|
| 14 |
+
: "${HF_TOKEN:?set HF_TOKEN to a Hugging Face write token}"
|
| 15 |
+
|
| 16 |
+
ROOT="$(git rev-parse --show-toplevel)"
|
| 17 |
+
TMP="$(mktemp -d)"
|
| 18 |
+
trap 'rm -rf "$TMP"' EXIT
|
| 19 |
+
|
| 20 |
+
# Clean snapshot of the tracked files at HEAD (no node_modules, .next, dev.db).
|
| 21 |
+
git -C "$ROOT" archive --format=tar HEAD | tar -x -C "$TMP"
|
| 22 |
+
|
| 23 |
+
# The Space root README must carry the docker/app_port YAML front matter.
|
| 24 |
+
cp "$ROOT/deploy/huggingface/README.md" "$TMP/README.md"
|
| 25 |
+
|
| 26 |
+
cd "$TMP"
|
| 27 |
+
git init -q
|
| 28 |
+
git add -A
|
| 29 |
+
git -c user.email=deploy@local -c user.name=deploy commit -qm "Deploy RotNot"
|
| 30 |
+
git branch -M main
|
| 31 |
+
echo "→ Pushing to https://huggingface.co/spaces/${SPACE}"
|
| 32 |
+
git push --force "https://user:${HF_TOKEN}@huggingface.co/spaces/${SPACE}.git" main
|
| 33 |
+
|
| 34 |
+
echo "✓ Pushed. The Space is building at https://huggingface.co/spaces/${SPACE}"
|
scripts/hf-start.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
# Startup for the Hugging Face Docker Space.
|
| 3 |
+
# Storage is ephemeral, so apply migrations + seed on every boot (both are
|
| 4 |
+
# idempotent), then start Next.js bound to the Space's public port.
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
echo "→ Applying database migrations…"
|
| 8 |
+
npx prisma migrate deploy
|
| 9 |
+
|
| 10 |
+
echo "→ Seeding database (idempotent)…"
|
| 11 |
+
npx prisma db seed
|
| 12 |
+
|
| 13 |
+
echo "→ Starting RotNot on 0.0.0.0:7860…"
|
| 14 |
+
exec npm run start -- -p 7860 -H 0.0.0.0
|
src/app/api/analytics/__tests__/judge-dimensions.test.ts
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
/**
|
| 2 |
+
* Tests for GET /api/analytics/judge-dimensions
|
| 3 |
+
*
|
| 4 |
+
* Covers:
|
| 5 |
+
* API key guard
|
| 6 |
+
* - returns 503 when LANGSMITH_API_KEY is not set
|
| 7 |
+
* - does NOT call langsmithClient when key is missing
|
| 8 |
+
* Response shape
|
| 9 |
+
* - returns 200 with { dimensions, alerts } keys
|
| 10 |
+
* - dimensions contains an entry for every DIMENSION_ID
|
| 11 |
+
* - each dimension entry has { avg, trend } fields
|
| 12 |
+
* - alerts is an array
|
| 13 |
+
* Score aggregation — avg calculation
|
| 14 |
+
* - avg is 0 when no feedback in the current period
|
| 15 |
+
* - avg is computed correctly over multiple scores
|
| 16 |
+
* - avg is rounded to 2 decimal places
|
| 17 |
+
* - denormalises: feedback scores (0-1) are multiplied by 10
|
| 18 |
+
* - ignores feedback keys that are not in DIMENSION_IDS
|
| 19 |
+
* - ignores feedback entries with non-numeric score
|
| 20 |
+
* Trend calculation
|
| 21 |
+
* - trend is 0 when there is no prior period data
|
| 22 |
+
* - trend is positive when current avg > prior avg
|
| 23 |
+
* - trend is negative when current avg < prior avg
|
| 24 |
+
* - trend is 0 when prior and current are identical
|
| 25 |
+
* - trend is rounded to 2 decimal places
|
| 26 |
+
* Alerts
|
| 27 |
+
* - no alert when drop is exactly -10% (boundary — not > 10%)
|
| 28 |
+
* - alert fires when drop is > 10%
|
| 29 |
+
* - alert message contains the dimension id
|
| 30 |
+
* - alert message contains the percentage drop
|
| 31 |
+
* - no alert when prior avg is 0 (no prior data)
|
| 32 |
+
* - multiple dimensions can fire alerts in the same response
|
| 33 |
+
* Error handling
|
| 34 |
+
* - returns 500 if langsmithClient.listRuns throws
|
| 35 |
+
*/
|
| 36 |
+
|
| 37 |
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
| 38 |
+
import { NextRequest } from "next/server";
|
| 39 |
+
import { DIMENSION_IDS } from "@/lib/debate/judge";
|
| 40 |
+
|
| 41 |
+
// ---------------------------------------------------------------------------
|
| 42 |
+
// Helpers
|
| 43 |
+
// ---------------------------------------------------------------------------
|
| 44 |
+
|
| 45 |
+
type FeedbackEntry = { key: string; score: number | null | undefined };
|
| 46 |
+
type RunEntry = { id: string };
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* Build a mock async generator from an array.
|
| 50 |
+
*/
|
| 51 |
+
async function* makeAsyncGen<T>(items: T[]): AsyncGenerator<T> {
|
| 52 |
+
for (const item of items) {
|
| 53 |
+
yield item;
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// ---------------------------------------------------------------------------
|
| 58 |
+
// Mocks
|
| 59 |
+
// ---------------------------------------------------------------------------
|
| 60 |
+
|
| 61 |
+
// listRuns and listFeedback are configured per-test via these maps
|
| 62 |
+
let mockRunsByPeriod: RunEntry[][] = [[], []]; // [currentPeriod, priorPeriod]
|
| 63 |
+
let mockFeedbackByRunId: Map<string, FeedbackEntry[]> = new Map();
|
| 64 |
+
|
| 65 |
+
// Track call order so we can distinguish current vs prior period calls
|
| 66 |
+
let listRunsCallIndex = 0;
|
| 67 |
+
|
| 68 |
+
const mockListRuns = vi.fn();
|
| 69 |
+
const mockListFeedback = vi.fn();
|
| 70 |
+
|
| 71 |
+
vi.mock("@/lib/langsmith", () => ({
|
| 72 |
+
langsmithClient: {
|
| 73 |
+
listRuns: (...args: unknown[]) => mockListRuns(...args),
|
| 74 |
+
listFeedback: (...args: unknown[]) => mockListFeedback(...args),
|
| 75 |
+
},
|
| 76 |
+
}));
|
| 77 |
+
|
| 78 |
+
beforeEach(() => {
|
| 79 |
+
vi.resetModules();
|
| 80 |
+
mockListRuns.mockClear();
|
| 81 |
+
mockListFeedback.mockClear();
|
| 82 |
+
mockRunsByPeriod = [[], []];
|
| 83 |
+
mockFeedbackByRunId = new Map();
|
| 84 |
+
listRunsCallIndex = 0;
|
| 85 |
+
|
| 86 |
+
// Default: return the correct period's runs in call order
|
| 87 |
+
mockListRuns.mockImplementation(() => {
|
| 88 |
+
const idx = listRunsCallIndex++;
|
| 89 |
+
const runs = mockRunsByPeriod[idx] ?? [];
|
| 90 |
+
return makeAsyncGen(runs);
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
// Default: return any registered feedback for the given runId
|
| 94 |
+
mockListFeedback.mockImplementation(
|
| 95 |
+
({ runIds }: { runIds: string[] }) => {
|
| 96 |
+
const feedbacks = mockFeedbackByRunId.get(runIds[0]) ?? [];
|
| 97 |
+
return makeAsyncGen(feedbacks);
|
| 98 |
+
},
|
| 99 |
+
);
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
// ---------------------------------------------------------------------------
|
| 103 |
+
// Import the handler after mocks are set up
|
| 104 |
+
// ---------------------------------------------------------------------------
|
| 105 |
+
|
| 106 |
+
async function callGET(env: Record<string, string | undefined> = {}) {
|
| 107 |
+
// Dynamically import to pick up the latest mock state
|
| 108 |
+
const { GET } = await import("../judge-dimensions/route");
|
| 109 |
+
const req = new NextRequest("http://localhost/api/analytics/judge-dimensions");
|
| 110 |
+
|
| 111 |
+
const saved: Record<string, string | undefined> = {};
|
| 112 |
+
for (const [k, v] of Object.entries(env)) {
|
| 113 |
+
saved[k] = process.env[k];
|
| 114 |
+
if (v === undefined) {
|
| 115 |
+
delete process.env[k];
|
| 116 |
+
} else {
|
| 117 |
+
process.env[k] = v;
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
try {
|
| 122 |
+
const res = await GET(req);
|
| 123 |
+
return res;
|
| 124 |
+
} finally {
|
| 125 |
+
for (const [k, v] of Object.entries(saved)) {
|
| 126 |
+
if (v === undefined) {
|
| 127 |
+
delete process.env[k];
|
| 128 |
+
} else {
|
| 129 |
+
process.env[k] = v;
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
// ---------------------------------------------------------------------------
|
| 136 |
+
// API key guard
|
| 137 |
+
// ---------------------------------------------------------------------------
|
| 138 |
+
|
| 139 |
+
describe("API key guard", () => {
|
| 140 |
+
it("returns 503 when LANGSMITH_API_KEY is not set", async () => {
|
| 141 |
+
const res = await callGET({ LANGSMITH_API_KEY: undefined });
|
| 142 |
+
expect(res.status).toBe(503);
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
it("returns error body when key is missing", async () => {
|
| 146 |
+
const res = await callGET({ LANGSMITH_API_KEY: undefined });
|
| 147 |
+
const body = await res.json();
|
| 148 |
+
expect(body).toHaveProperty("error");
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
it("does not call listRuns when LANGSMITH_API_KEY is missing", async () => {
|
| 152 |
+
await callGET({ LANGSMITH_API_KEY: undefined });
|
| 153 |
+
expect(mockListRuns).not.toHaveBeenCalled();
|
| 154 |
+
});
|
| 155 |
+
});
|
| 156 |
+
|
| 157 |
+
// ---------------------------------------------------------------------------
|
| 158 |
+
// Response shape
|
| 159 |
+
// ---------------------------------------------------------------------------
|
| 160 |
+
|
| 161 |
+
describe("Response shape", () => {
|
| 162 |
+
it("returns 200 when key is present", async () => {
|
| 163 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 164 |
+
expect(res.status).toBe(200);
|
| 165 |
+
});
|
| 166 |
+
|
| 167 |
+
it("response has dimensions and alerts keys", async () => {
|
| 168 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 169 |
+
const body = await res.json();
|
| 170 |
+
expect(body).toHaveProperty("dimensions");
|
| 171 |
+
expect(body).toHaveProperty("alerts");
|
| 172 |
+
});
|
| 173 |
+
|
| 174 |
+
it("dimensions contains an entry for every DIMENSION_ID", async () => {
|
| 175 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 176 |
+
const body = await res.json();
|
| 177 |
+
for (const dimId of DIMENSION_IDS) {
|
| 178 |
+
expect(body.dimensions).toHaveProperty(dimId);
|
| 179 |
+
}
|
| 180 |
+
});
|
| 181 |
+
|
| 182 |
+
it("each dimension entry has avg and trend fields", async () => {
|
| 183 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 184 |
+
const body = await res.json();
|
| 185 |
+
for (const dimId of DIMENSION_IDS) {
|
| 186 |
+
const entry = body.dimensions[dimId];
|
| 187 |
+
expect(entry).toHaveProperty("avg");
|
| 188 |
+
expect(entry).toHaveProperty("trend");
|
| 189 |
+
expect(typeof entry.avg).toBe("number");
|
| 190 |
+
expect(typeof entry.trend).toBe("number");
|
| 191 |
+
}
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
it("alerts is an array", async () => {
|
| 195 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 196 |
+
const body = await res.json();
|
| 197 |
+
expect(Array.isArray(body.alerts)).toBe(true);
|
| 198 |
+
});
|
| 199 |
+
});
|
| 200 |
+
|
| 201 |
+
// ---------------------------------------------------------------------------
|
| 202 |
+
// Score aggregation
|
| 203 |
+
// ---------------------------------------------------------------------------
|
| 204 |
+
|
| 205 |
+
describe("Score aggregation", () => {
|
| 206 |
+
it("avg is 0 when there are no runs in the current period", async () => {
|
| 207 |
+
// no runs in either period — defaults to empty arrays
|
| 208 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 209 |
+
const body = await res.json();
|
| 210 |
+
for (const dimId of DIMENSION_IDS) {
|
| 211 |
+
expect(body.dimensions[dimId].avg).toBe(0);
|
| 212 |
+
}
|
| 213 |
+
});
|
| 214 |
+
|
| 215 |
+
it("computes avg correctly over multiple scores (denormalised 0-10)", async () => {
|
| 216 |
+
const dimId = DIMENSION_IDS[0]; // "flaw-detection"
|
| 217 |
+
mockRunsByPeriod = [
|
| 218 |
+
[{ id: "run-1" }, { id: "run-2" }],
|
| 219 |
+
[],
|
| 220 |
+
];
|
| 221 |
+
// run-1: score 0.7 (→ 7 after ×10), run-2: score 0.9 (→ 9 after ×10)
|
| 222 |
+
mockFeedbackByRunId.set("run-1", [{ key: dimId, score: 0.7 }]);
|
| 223 |
+
mockFeedbackByRunId.set("run-2", [{ key: dimId, score: 0.9 }]);
|
| 224 |
+
|
| 225 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 226 |
+
const body = await res.json();
|
| 227 |
+
// avg = (7 + 9) / 2 = 8.0
|
| 228 |
+
expect(body.dimensions[dimId].avg).toBe(8.0);
|
| 229 |
+
});
|
| 230 |
+
|
| 231 |
+
it("rounds avg to 2 decimal places", async () => {
|
| 232 |
+
const dimId = DIMENSION_IDS[0];
|
| 233 |
+
// Three scores: 0.1 → 1, 0.2 → 2, 0.3 → 3: avg = 6/3 = 2.0 → rounded fine
|
| 234 |
+
// Use values that would produce a repeating decimal: 1/3 ≈ 0.333...
|
| 235 |
+
// 0.1 → 1, 0.2 → 2, 0.4 → 4: avg = 7/3 ≈ 2.333... → rounds to 2.33
|
| 236 |
+
mockRunsByPeriod = [[{ id: "r1" }, { id: "r2" }, { id: "r3" }], []];
|
| 237 |
+
mockFeedbackByRunId.set("r1", [{ key: dimId, score: 0.1 }]);
|
| 238 |
+
mockFeedbackByRunId.set("r2", [{ key: dimId, score: 0.2 }]);
|
| 239 |
+
mockFeedbackByRunId.set("r3", [{ key: dimId, score: 0.4 }]);
|
| 240 |
+
|
| 241 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 242 |
+
const body = await res.json();
|
| 243 |
+
// avg = (1 + 2 + 4) / 3 = 7/3 ≈ 2.333... → 2.33
|
| 244 |
+
expect(body.dimensions[dimId].avg).toBe(2.33);
|
| 245 |
+
});
|
| 246 |
+
|
| 247 |
+
it("ignores feedback keys that are not in DIMENSION_IDS", async () => {
|
| 248 |
+
const dimId = DIMENSION_IDS[0];
|
| 249 |
+
mockRunsByPeriod = [[{ id: "run-x" }], []];
|
| 250 |
+
mockFeedbackByRunId.set("run-x", [
|
| 251 |
+
{ key: "unknown-dimension", score: 0.9 },
|
| 252 |
+
{ key: dimId, score: 0.5 },
|
| 253 |
+
]);
|
| 254 |
+
|
| 255 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 256 |
+
const body = await res.json();
|
| 257 |
+
// Only the valid dimension score (0.5 → 5) should be counted
|
| 258 |
+
expect(body.dimensions[dimId].avg).toBe(5.0);
|
| 259 |
+
// The unknown key should not appear in the response
|
| 260 |
+
expect(body.dimensions).not.toHaveProperty("unknown-dimension");
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
it("ignores feedback entries with null or undefined score", async () => {
|
| 264 |
+
const dimId = DIMENSION_IDS[0];
|
| 265 |
+
mockRunsByPeriod = [[{ id: "run-null" }], []];
|
| 266 |
+
mockFeedbackByRunId.set("run-null", [
|
| 267 |
+
{ key: dimId, score: null },
|
| 268 |
+
{ key: dimId, score: undefined },
|
| 269 |
+
] as FeedbackEntry[]);
|
| 270 |
+
|
| 271 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 272 |
+
const body = await res.json();
|
| 273 |
+
// All null/undefined scores ignored → avg stays 0
|
| 274 |
+
expect(body.dimensions[dimId].avg).toBe(0);
|
| 275 |
+
});
|
| 276 |
+
});
|
| 277 |
+
|
| 278 |
+
// ---------------------------------------------------------------------------
|
| 279 |
+
// Trend calculation
|
| 280 |
+
// ---------------------------------------------------------------------------
|
| 281 |
+
|
| 282 |
+
describe("Trend calculation", () => {
|
| 283 |
+
it("trend is 0 when there is no prior period data", async () => {
|
| 284 |
+
const dimId = DIMENSION_IDS[0];
|
| 285 |
+
mockRunsByPeriod = [[{ id: "run-cur" }], []]; // prior period empty
|
| 286 |
+
mockFeedbackByRunId.set("run-cur", [{ key: dimId, score: 0.8 }]);
|
| 287 |
+
|
| 288 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 289 |
+
const body = await res.json();
|
| 290 |
+
expect(body.dimensions[dimId].trend).toBe(0);
|
| 291 |
+
});
|
| 292 |
+
|
| 293 |
+
it("trend is positive when current avg is higher than prior", async () => {
|
| 294 |
+
const dimId = DIMENSION_IDS[0];
|
| 295 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 296 |
+
// current: 0.8 → 8, prior: 0.4 → 4 => trend = (8-4)/4 * 100 = 100%
|
| 297 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
|
| 298 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.4 }]);
|
| 299 |
+
|
| 300 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 301 |
+
const body = await res.json();
|
| 302 |
+
expect(body.dimensions[dimId].trend).toBeGreaterThan(0);
|
| 303 |
+
expect(body.dimensions[dimId].trend).toBeCloseTo(100, 0);
|
| 304 |
+
});
|
| 305 |
+
|
| 306 |
+
it("trend is negative when current avg is lower than prior", async () => {
|
| 307 |
+
const dimId = DIMENSION_IDS[0];
|
| 308 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 309 |
+
// current: 0.4 → 4, prior: 0.8 → 8 => trend = (4-8)/8 * 100 = -50%
|
| 310 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.4 }]);
|
| 311 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.8 }]);
|
| 312 |
+
|
| 313 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 314 |
+
const body = await res.json();
|
| 315 |
+
expect(body.dimensions[dimId].trend).toBeLessThan(0);
|
| 316 |
+
expect(body.dimensions[dimId].trend).toBeCloseTo(-50, 0);
|
| 317 |
+
});
|
| 318 |
+
|
| 319 |
+
it("trend is 0 when prior and current averages are equal", async () => {
|
| 320 |
+
const dimId = DIMENSION_IDS[0];
|
| 321 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 322 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]);
|
| 323 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.7 }]);
|
| 324 |
+
|
| 325 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 326 |
+
const body = await res.json();
|
| 327 |
+
expect(body.dimensions[dimId].trend).toBe(0);
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
it("trend is rounded to 2 decimal places", async () => {
|
| 331 |
+
const dimId = DIMENSION_IDS[0];
|
| 332 |
+
// current: 0.7 → 7, prior: 0.6 → 6 => trend = (7-6)/6 * 100 ≈ 16.666...% → 16.67
|
| 333 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 334 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]);
|
| 335 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.6 }]);
|
| 336 |
+
|
| 337 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 338 |
+
const body = await res.json();
|
| 339 |
+
expect(body.dimensions[dimId].trend).toBe(16.67);
|
| 340 |
+
});
|
| 341 |
+
});
|
| 342 |
+
|
| 343 |
+
// ---------------------------------------------------------------------------
|
| 344 |
+
// Alerts
|
| 345 |
+
// ---------------------------------------------------------------------------
|
| 346 |
+
|
| 347 |
+
describe("Alerts", () => {
|
| 348 |
+
it("no alert when current period has no data (prior avg = 0)", async () => {
|
| 349 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 350 |
+
const body = await res.json();
|
| 351 |
+
expect(body.alerts).toHaveLength(0);
|
| 352 |
+
});
|
| 353 |
+
|
| 354 |
+
it("no alert when drop is exactly -10% (boundary — strictly > 10% required)", async () => {
|
| 355 |
+
const dimId = DIMENSION_IDS[0];
|
| 356 |
+
// prior avg = 10, current avg = 9 → drop = exactly 10% → NO alert
|
| 357 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 358 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.9 }]);
|
| 359 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);
|
| 360 |
+
|
| 361 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 362 |
+
const body = await res.json();
|
| 363 |
+
expect(body.alerts).toHaveLength(0);
|
| 364 |
+
});
|
| 365 |
+
|
| 366 |
+
it("fires alert when drop is greater than 10%", async () => {
|
| 367 |
+
const dimId = DIMENSION_IDS[0];
|
| 368 |
+
// prior avg = 10, current avg = 8 → drop = 20% → alert
|
| 369 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 370 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
|
| 371 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);
|
| 372 |
+
|
| 373 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 374 |
+
const body = await res.json();
|
| 375 |
+
expect(body.alerts.length).toBeGreaterThanOrEqual(1);
|
| 376 |
+
});
|
| 377 |
+
|
| 378 |
+
it("alert message contains the dimension id", async () => {
|
| 379 |
+
const dimId = DIMENSION_IDS[0]; // "flaw-detection"
|
| 380 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 381 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
|
| 382 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);
|
| 383 |
+
|
| 384 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 385 |
+
const body = await res.json();
|
| 386 |
+
expect(body.alerts.some((a: string) => a.includes(dimId))).toBe(true);
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
it("alert message contains the percentage drop magnitude", async () => {
|
| 390 |
+
const dimId = DIMENSION_IDS[0];
|
| 391 |
+
// prior = 10, current = 8 → 20% drop
|
| 392 |
+
mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
|
| 393 |
+
mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
|
| 394 |
+
mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);
|
| 395 |
+
|
| 396 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 397 |
+
const body = await res.json();
|
| 398 |
+
const alert: string = body.alerts.find((a: string) => a.includes(dimId));
|
| 399 |
+
expect(alert).toContain("20.0%");
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
it("multiple dimensions can fire alerts in the same response", async () => {
|
| 403 |
+
// Both dim 0 and dim 1 drop >10%
|
| 404 |
+
const dim0 = DIMENSION_IDS[0];
|
| 405 |
+
const dim1 = DIMENSION_IDS[1];
|
| 406 |
+
|
| 407 |
+
mockRunsByPeriod = [[{ id: "cur0" }, { id: "cur1" }], [{ id: "pri0" }, { id: "pri1" }]];
|
| 408 |
+
|
| 409 |
+
// Use separate call tracking via IDs
|
| 410 |
+
mockFeedbackByRunId.set("cur0", [{ key: dim0, score: 0.7 }]);
|
| 411 |
+
mockFeedbackByRunId.set("cur1", [{ key: dim1, score: 0.6 }]);
|
| 412 |
+
mockFeedbackByRunId.set("pri0", [{ key: dim0, score: 1.0 }]);
|
| 413 |
+
mockFeedbackByRunId.set("pri1", [{ key: dim1, score: 1.0 }]);
|
| 414 |
+
|
| 415 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 416 |
+
const body = await res.json();
|
| 417 |
+
expect(body.alerts.length).toBeGreaterThanOrEqual(2);
|
| 418 |
+
});
|
| 419 |
+
});
|
| 420 |
+
|
| 421 |
+
// ---------------------------------------------------------------------------
|
| 422 |
+
// Error handling
|
| 423 |
+
// ---------------------------------------------------------------------------
|
| 424 |
+
|
| 425 |
+
describe("Error handling", () => {
|
| 426 |
+
it("returns 500 if listRuns throws", async () => {
|
| 427 |
+
mockListRuns.mockImplementationOnce(() => {
|
| 428 |
+
throw new Error("LangSmith API error");
|
| 429 |
+
});
|
| 430 |
+
|
| 431 |
+
const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
|
| 432 |
+
expect(res.status).toBe(500);
|
| 433 |
+
});
|
| 434 |
+
});
|
src/app/api/analytics/judge-dimensions/route.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { NextResponse } from "next/server";
|
| 2 |
+
import { langsmithClient } from "@/lib/langsmith";
|
| 3 |
+
import { DIMENSION_IDS } from "@/lib/debate/judge";
|
| 4 |
+
import { withApiError } from "@/lib/api-error";
|
| 5 |
+
|
| 6 |
+
// ---------------------------------------------------------------------------
|
| 7 |
+
// Types
|
| 8 |
+
// ---------------------------------------------------------------------------
|
| 9 |
+
|
| 10 |
+
interface DimensionStats {
|
| 11 |
+
avg: number;
|
| 12 |
+
trend: number; // % change vs prior 7-day period (negative = declined)
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
interface AnalyticsResponse {
|
| 16 |
+
dimensions: Record<string, DimensionStats>;
|
| 17 |
+
alerts: string[];
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
// ---------------------------------------------------------------------------
|
| 21 |
+
// Helpers
|
| 22 |
+
// ---------------------------------------------------------------------------
|
| 23 |
+
|
| 24 |
+
/**
|
| 25 |
+
* Collect feedback scores for all judge runs in [start, end).
|
| 26 |
+
* Returns a map: dimensionId → number[] of scores.
|
| 27 |
+
*/
|
| 28 |
+
async function collectDimensionScores(
|
| 29 |
+
start: Date,
|
| 30 |
+
end: Date,
|
| 31 |
+
): Promise<Record<string, number[]>> {
|
| 32 |
+
const scores: Record<string, number[]> = {};
|
| 33 |
+
for (const dimId of DIMENSION_IDS) {
|
| 34 |
+
scores[dimId] = [];
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
for await (const run of langsmithClient.listRuns({
|
| 38 |
+
projectName: process.env.LANGSMITH_PROJECT ?? "default",
|
| 39 |
+
filter: `and(eq(name, "debate-judge-round"), lt(start_time, "${end.toISOString()}"))`,
|
| 40 |
+
startTime: start,
|
| 41 |
+
})) {
|
| 42 |
+
// For each run, fetch its feedback
|
| 43 |
+
for await (const fb of langsmithClient.listFeedback({
|
| 44 |
+
runIds: [run.id],
|
| 45 |
+
})) {
|
| 46 |
+
const key = fb.key; // dimension id
|
| 47 |
+
if (key && scores[key] !== undefined && typeof fb.score === "number") {
|
| 48 |
+
scores[key].push(fb.score * 10); // denormalise 0-1 → 0-10
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
return scores;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
function avg(nums: number[]): number {
|
| 57 |
+
if (nums.length === 0) return 0;
|
| 58 |
+
return Math.round((nums.reduce((a, b) => a + b, 0) / nums.length) * 100) / 100;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// ---------------------------------------------------------------------------
|
| 62 |
+
// GET /api/analytics/judge-dimensions
|
| 63 |
+
// ---------------------------------------------------------------------------
|
| 64 |
+
|
| 65 |
+
export const GET = withApiError(async () => {
|
| 66 |
+
if (!process.env.LANGSMITH_API_KEY) {
|
| 67 |
+
return NextResponse.json(
|
| 68 |
+
{ error: "LANGSMITH_API_KEY is not configured" },
|
| 69 |
+
{ status: 503 },
|
| 70 |
+
);
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
const now = new Date();
|
| 74 |
+
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
| 75 |
+
const fourteenDaysAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);
|
| 76 |
+
|
| 77 |
+
// Fetch current and prior period scores in parallel
|
| 78 |
+
const [currentScores, priorScores] = await Promise.all([
|
| 79 |
+
collectDimensionScores(sevenDaysAgo, now),
|
| 80 |
+
collectDimensionScores(fourteenDaysAgo, sevenDaysAgo),
|
| 81 |
+
]);
|
| 82 |
+
|
| 83 |
+
const dimensions: Record<string, DimensionStats> = {};
|
| 84 |
+
const alerts: string[] = [];
|
| 85 |
+
|
| 86 |
+
for (const dimId of DIMENSION_IDS) {
|
| 87 |
+
const currentAvg = avg(currentScores[dimId]);
|
| 88 |
+
const priorAvg = avg(priorScores[dimId]);
|
| 89 |
+
|
| 90 |
+
// trend: % change from prior period (0 if no prior data)
|
| 91 |
+
const trend =
|
| 92 |
+
priorAvg > 0
|
| 93 |
+
? Math.round(((currentAvg - priorAvg) / priorAvg) * 100 * 100) / 100
|
| 94 |
+
: 0;
|
| 95 |
+
|
| 96 |
+
dimensions[dimId] = { avg: currentAvg, trend };
|
| 97 |
+
|
| 98 |
+
// Alert: flag if 7-day avg dropped >10% vs prior period
|
| 99 |
+
if (priorAvg > 0 && trend < -10) {
|
| 100 |
+
alerts.push(
|
| 101 |
+
`${dimId}: avg dropped ${Math.abs(trend).toFixed(1)}% (${priorAvg.toFixed(1)} → ${currentAvg.toFixed(1)})`,
|
| 102 |
+
);
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Tests for /api/chess/challenge route.
|
| 3 |
+
*
|
| 4 |
+
* Covers:
|
| 5 |
+
* - clampStockfishLevel — pure level-clamping function
|
| 6 |
+
* - POST handler — token guard (503), Lichess failure (502), success (200)
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
| 10 |
+
import { NextRequest, NextResponse } from "next/server";
|
| 11 |
+
|
| 12 |
+
// ---------------------------------------------------------------------------
|
| 13 |
+
// Mock challengeStockfish (avoid real network calls)
|
| 14 |
+
// ---------------------------------------------------------------------------
|
| 15 |
+
|
| 16 |
+
const mockChallengeStockfish = vi.fn();
|
| 17 |
+
|
| 18 |
+
vi.mock("@/lib/lichess", () => ({
|
| 19 |
+
challengeStockfish: (...args: unknown[]) => mockChallengeStockfish(...args),
|
| 20 |
+
}));
|
| 21 |
+
|
| 22 |
+
// ---------------------------------------------------------------------------
|
| 23 |
+
// Imports (after mocks)
|
| 24 |
+
// ---------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
import { POST, clampStockfishLevel } from "../challenge/route";
|
| 27 |
+
|
| 28 |
+
// ---------------------------------------------------------------------------
|
| 29 |
+
// Helpers
|
| 30 |
+
// ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
const originalEnv = { ...process.env };
|
| 33 |
+
|
| 34 |
+
function makeRequest(body?: Record<string, unknown>): NextRequest {
|
| 35 |
+
return new NextRequest("http://localhost/api/chess/challenge", {
|
| 36 |
+
method: "POST",
|
| 37 |
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
| 38 |
+
headers: { "Content-Type": "application/json" },
|
| 39 |
+
});
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
async function parseJson(res: NextResponse): Promise<unknown> {
|
| 43 |
+
return res.json();
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
beforeEach(() => {
|
| 47 |
+
mockChallengeStockfish.mockReset();
|
| 48 |
+
process.env = { ...originalEnv, LICHESS_API_TOKEN: "test-token" };
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
afterEach(() => {
|
| 52 |
+
process.env = originalEnv;
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
// ─── clampStockfishLevel ─────────────────────────────────────────────────────
|
| 56 |
+
|
| 57 |
+
describe("clampStockfishLevel", () => {
|
| 58 |
+
it("returns the level unchanged when in range [1, 8]", () => {
|
| 59 |
+
expect(clampStockfishLevel(1)).toBe(1);
|
| 60 |
+
expect(clampStockfishLevel(4)).toBe(4);
|
| 61 |
+
expect(clampStockfishLevel(8)).toBe(8);
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
it("clamps values below 1 to 1", () => {
|
| 65 |
+
expect(clampStockfishLevel(0)).toBe(1);
|
| 66 |
+
expect(clampStockfishLevel(-5)).toBe(1);
|
| 67 |
+
expect(clampStockfishLevel(-Infinity)).toBe(1);
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it("clamps values above 8 to 8", () => {
|
| 71 |
+
expect(clampStockfishLevel(9)).toBe(8);
|
| 72 |
+
expect(clampStockfishLevel(100)).toBe(8);
|
| 73 |
+
expect(clampStockfishLevel(Infinity)).toBe(8);
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it("rounds fractional levels to the nearest integer", () => {
|
| 77 |
+
expect(clampStockfishLevel(3.5)).toBe(4);
|
| 78 |
+
expect(clampStockfishLevel(3.4)).toBe(3);
|
| 79 |
+
expect(clampStockfishLevel(7.9)).toBe(8);
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it("defaults to 4 when level is undefined", () => {
|
| 83 |
+
expect(clampStockfishLevel(undefined)).toBe(4);
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
it("defaults to 4 when level is null", () => {
|
| 87 |
+
expect(clampStockfishLevel(null)).toBe(4);
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
it("defaults to 4 when level is a string", () => {
|
| 91 |
+
expect(clampStockfishLevel("5")).toBe(4);
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it("defaults to 4 when level is a boolean", () => {
|
| 95 |
+
expect(clampStockfishLevel(true)).toBe(4);
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
it("defaults to 4 when level is an object", () => {
|
| 99 |
+
expect(clampStockfishLevel({})).toBe(4);
|
| 100 |
+
});
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
// ─── POST /api/chess/challenge — token guard ─────────────────────────────────
|
| 104 |
+
|
| 105 |
+
describe("POST /api/chess/challenge — LICHESS_API_TOKEN guard", () => {
|
| 106 |
+
it("returns 503 when LICHESS_API_TOKEN is not set", async () => {
|
| 107 |
+
delete process.env.LICHESS_API_TOKEN;
|
| 108 |
+
|
| 109 |
+
const res = await POST(makeRequest({ level: 4 }));
|
| 110 |
+
expect(res.status).toBe(503);
|
| 111 |
+
|
| 112 |
+
const body = await parseJson(res) as { error: string };
|
| 113 |
+
expect(body.error).toContain("LICHESS_API_TOKEN");
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it("returns 503 when LICHESS_API_TOKEN is an empty string", async () => {
|
| 117 |
+
process.env.LICHESS_API_TOKEN = "";
|
| 118 |
+
|
| 119 |
+
const res = await POST(makeRequest({ level: 4 }));
|
| 120 |
+
expect(res.status).toBe(503);
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
it("does not call challengeStockfish when token is missing", async () => {
|
| 124 |
+
delete process.env.LICHESS_API_TOKEN;
|
| 125 |
+
await POST(makeRequest({ level: 4 }));
|
| 126 |
+
expect(mockChallengeStockfish).not.toHaveBeenCalled();
|
| 127 |
+
});
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
+
// ─── POST /api/chess/challenge — Lichess failure ─────────────────────────────
|
| 131 |
+
|
| 132 |
+
describe("POST /api/chess/challenge — Lichess failure (502)", () => {
|
| 133 |
+
it("returns 502 when challengeStockfish returns null", async () => {
|
| 134 |
+
mockChallengeStockfish.mockResolvedValueOnce(null);
|
| 135 |
+
|
| 136 |
+
const res = await POST(makeRequest({ level: 3 }));
|
| 137 |
+
expect(res.status).toBe(502);
|
| 138 |
+
|
| 139 |
+
const body = await parseJson(res) as { error: string };
|
| 140 |
+
expect(body.error).toMatch(/Failed to create Stockfish challenge/i);
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
it("still calls challengeStockfish with the correct level when token is present", async () => {
|
| 144 |
+
mockChallengeStockfish.mockResolvedValueOnce(null);
|
| 145 |
+
|
| 146 |
+
await POST(makeRequest({ level: 6 }));
|
| 147 |
+
|
| 148 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(6);
|
| 149 |
+
});
|
| 150 |
+
});
|
| 151 |
+
|
| 152 |
+
// ─── POST /api/chess/challenge — success ─────────────────────────────────────
|
| 153 |
+
|
| 154 |
+
describe("POST /api/chess/challenge — success", () => {
|
| 155 |
+
const MOCK_CHALLENGE = {
|
| 156 |
+
id: "abc123xyz",
|
| 157 |
+
url: "https://lichess.org/abc123xyz",
|
| 158 |
+
};
|
| 159 |
+
|
| 160 |
+
it("returns 200 with gameId, gameUrl, and level on success", async () => {
|
| 161 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 162 |
+
|
| 163 |
+
const res = await POST(makeRequest({ level: 5 }));
|
| 164 |
+
expect(res.status).toBe(200);
|
| 165 |
+
|
| 166 |
+
const body = await parseJson(res) as { gameId: string; gameUrl: string; level: number };
|
| 167 |
+
expect(body.gameId).toBe("abc123xyz");
|
| 168 |
+
expect(body.gameUrl).toBe("https://lichess.org/abc123xyz");
|
| 169 |
+
expect(body.level).toBe(5);
|
| 170 |
+
});
|
| 171 |
+
|
| 172 |
+
it("defaults level to 4 when no body is provided", async () => {
|
| 173 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 174 |
+
|
| 175 |
+
const res = await POST(
|
| 176 |
+
new NextRequest("http://localhost/api/chess/challenge", { method: "POST" })
|
| 177 |
+
);
|
| 178 |
+
expect(res.status).toBe(200);
|
| 179 |
+
|
| 180 |
+
const body = await parseJson(res) as { level: number };
|
| 181 |
+
expect(body.level).toBe(4);
|
| 182 |
+
|
| 183 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(4);
|
| 184 |
+
});
|
| 185 |
+
|
| 186 |
+
it("defaults level to 4 when level is omitted from body", async () => {
|
| 187 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 188 |
+
|
| 189 |
+
const res = await POST(makeRequest({}));
|
| 190 |
+
const body = await parseJson(res) as { level: number };
|
| 191 |
+
expect(body.level).toBe(4);
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
it("clamps level 9 → 8 and passes 8 to challengeStockfish", async () => {
|
| 195 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 196 |
+
|
| 197 |
+
const res = await POST(makeRequest({ level: 9 }));
|
| 198 |
+
expect(res.status).toBe(200);
|
| 199 |
+
|
| 200 |
+
const body = await parseJson(res) as { level: number };
|
| 201 |
+
expect(body.level).toBe(8);
|
| 202 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(8);
|
| 203 |
+
});
|
| 204 |
+
|
| 205 |
+
it("clamps level 0 → 1 and passes 1 to challengeStockfish", async () => {
|
| 206 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 207 |
+
|
| 208 |
+
const res = await POST(makeRequest({ level: 0 }));
|
| 209 |
+
expect(res.status).toBe(200);
|
| 210 |
+
|
| 211 |
+
const body = await parseJson(res) as { level: number };
|
| 212 |
+
expect(body.level).toBe(1);
|
| 213 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(1);
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
it("passes level 1 through unchanged", async () => {
|
| 217 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 218 |
+
|
| 219 |
+
await POST(makeRequest({ level: 1 }));
|
| 220 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(1);
|
| 221 |
+
});
|
| 222 |
+
|
| 223 |
+
it("passes level 8 through unchanged", async () => {
|
| 224 |
+
mockChallengeStockfish.mockResolvedValueOnce(MOCK_CHALLENGE);
|
| 225 |
+
|
| 226 |
+
await POST(makeRequest({ level: 8 }));
|
| 227 |
+
expect(mockChallengeStockfish).toHaveBeenCalledWith(8);
|
| 228 |
+
});
|
| 229 |
+
});
|
src/app/api/chess/__tests__/game-result-route.test.ts
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Tests for POST /api/chess/game-result route handler.
|
| 3 |
+
*
|
| 4 |
+
* Covers:
|
| 5 |
+
* Input validation
|
| 6 |
+
* - invalid JSON body → 400
|
| 7 |
+
* - missing gameId → 400
|
| 8 |
+
* - non-string gameId → 400
|
| 9 |
+
* - level out of range (< 1) → 400
|
| 10 |
+
* - level out of range (> 8) → 400
|
| 11 |
+
* - non-number level → 400
|
| 12 |
+
* - invalid result value → 400
|
| 13 |
+
* - missing result → 400
|
| 14 |
+
*
|
| 15 |
+
* DB guards
|
| 16 |
+
* - user not found → 404
|
| 17 |
+
* - missing chess CategorySkill → 500
|
| 18 |
+
*
|
| 19 |
+
* Success path
|
| 20 |
+
* - response shape (result, level, qualityScore, xp, levelUp, categoryXp, unlocks)
|
| 21 |
+
* - win result → qualityScore > draw > loss
|
| 22 |
+
* - XP base = 30, quality bonus up to 30
|
| 23 |
+
* - isCriticalHit doubles totalXp
|
| 24 |
+
* - multiplierPercent reflected in xp breakdown
|
| 25 |
+
* - DailyLog created when no existing log
|
| 26 |
+
* - DailyLog updated when existing log exists
|
| 27 |
+
* - goalMet flag set when XP reaches dailyGoalXp
|
| 28 |
+
* - processSkillUnlocks called on category level-up
|
| 29 |
+
* - processSkillUnlocks NOT called when no category level-up
|
| 30 |
+
* - newTitle included when title changes on level-up
|
| 31 |
+
* - newTitle absent when no title change
|
| 32 |
+
* - userId defaults to 1 when omitted
|
| 33 |
+
* - unlocks and streakFreezesGranted reflected in response
|
| 34 |
+
*/
|
| 35 |
+
|
| 36 |
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
| 37 |
+
import { NextRequest } from "next/server";
|
| 38 |
+
|
| 39 |
+
// ---------------------------------------------------------------------------
|
| 40 |
+
// Mock Prisma
|
| 41 |
+
// ---------------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
const mockUserFindFirst = vi.fn();
|
| 44 |
+
const mockDailyLogFindFirst = vi.fn();
|
| 45 |
+
const mockTransaction = vi.fn();
|
| 46 |
+
const mockActivityCreate = vi.fn();
|
| 47 |
+
const mockUserUpdate = vi.fn();
|
| 48 |
+
const mockCategorySkillUpdate = vi.fn();
|
| 49 |
+
const mockDailyLogCreate = vi.fn();
|
| 50 |
+
const mockDailyLogUpdate = vi.fn();
|
| 51 |
+
|
| 52 |
+
vi.mock("@/lib/db", () => ({
|
| 53 |
+
prisma: {
|
| 54 |
+
user: {
|
| 55 |
+
findFirst: (...args: unknown[]) => mockUserFindFirst(...args),
|
| 56 |
+
},
|
| 57 |
+
dailyLog: {
|
| 58 |
+
findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args),
|
| 59 |
+
},
|
| 60 |
+
$transaction: (...args: unknown[]) => mockTransaction(...args),
|
| 61 |
+
},
|
| 62 |
+
}));
|
| 63 |
+
|
| 64 |
+
// ---------------------------------------------------------------------------
|
| 65 |
+
// Mock rollCriticalHit
|
| 66 |
+
// ---------------------------------------------------------------------------
|
| 67 |
+
|
| 68 |
+
const mockRollCriticalHit = vi.fn(() => false);
|
| 69 |
+
|
| 70 |
+
vi.mock("@/lib/xp", async (importOriginal) => {
|
| 71 |
+
const actual = await importOriginal<typeof import("@/lib/xp")>();
|
| 72 |
+
return {
|
| 73 |
+
...actual,
|
| 74 |
+
rollCriticalHit: () => mockRollCriticalHit(),
|
| 75 |
+
};
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
// ---------------------------------------------------------------------------
|
| 79 |
+
// Mock getMultiplierPercent
|
| 80 |
+
// ---------------------------------------------------------------------------
|
| 81 |
+
|
| 82 |
+
const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0));
|
| 83 |
+
|
| 84 |
+
vi.mock("@/lib/multiplier", () => ({
|
| 85 |
+
getMultiplierPercent: (...args: unknown[]) =>
|
| 86 |
+
(mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args),
|
| 87 |
+
}));
|
| 88 |
+
|
| 89 |
+
// ---------------------------------------------------------------------------
|
| 90 |
+
// Mock processSkillUnlocks
|
| 91 |
+
// ---------------------------------------------------------------------------
|
| 92 |
+
|
| 93 |
+
const mockProcessSkillUnlocks = vi.fn(
|
| 94 |
+
(): Promise<{ unlocked: string[]; streakFreezesGranted: number }> =>
|
| 95 |
+
Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }),
|
| 96 |
+
);
|
| 97 |
+
|
| 98 |
+
vi.mock("@/lib/skill-unlock", () => ({
|
| 99 |
+
processSkillUnlocks: (...args: unknown[]) =>
|
| 100 |
+
(mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args),
|
| 101 |
+
}));
|
| 102 |
+
|
| 103 |
+
// ---------------------------------------------------------------------------
|
| 104 |
+
// Mock processEndOfDay (no-op — streak logic is tested separately)
|
| 105 |
+
// ---------------------------------------------------------------------------
|
| 106 |
+
|
| 107 |
+
vi.mock("@/lib/streak", () => ({
|
| 108 |
+
processEndOfDay: vi.fn(() => Promise.resolve({
|
| 109 |
+
streak: 1,
|
| 110 |
+
freezeUsed: false,
|
| 111 |
+
streakBroken: false,
|
| 112 |
+
alreadyProcessed: false,
|
| 113 |
+
})),
|
| 114 |
+
}));
|
| 115 |
+
|
| 116 |
+
// ---------------------------------------------------------------------------
|
| 117 |
+
// Import route after mocks
|
| 118 |
+
// ---------------------------------------------------------------------------
|
| 119 |
+
|
| 120 |
+
import { POST } from "../game-result/route";
|
| 121 |
+
|
| 122 |
+
// ---------------------------------------------------------------------------
|
| 123 |
+
// Helpers
|
| 124 |
+
// ---------------------------------------------------------------------------
|
| 125 |
+
|
| 126 |
+
async function json(res: Response): Promise<unknown> {
|
| 127 |
+
return res.json();
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
function makePost(body?: Record<string, unknown>): NextRequest {
|
| 131 |
+
return new NextRequest("http://localhost/api/chess/game-result", {
|
| 132 |
+
method: "POST",
|
| 133 |
+
body: body !== undefined ? JSON.stringify(body) : "not-json{{{",
|
| 134 |
+
headers: { "Content-Type": "application/json" },
|
| 135 |
+
});
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
function makePostValid(overrides: Record<string, unknown> = {}): NextRequest {
|
| 139 |
+
return new NextRequest("http://localhost/api/chess/game-result", {
|
| 140 |
+
method: "POST",
|
| 141 |
+
body: JSON.stringify({
|
| 142 |
+
gameId: "abc123",
|
| 143 |
+
level: 4,
|
| 144 |
+
result: "win",
|
| 145 |
+
...overrides,
|
| 146 |
+
}),
|
| 147 |
+
headers: { "Content-Type": "application/json" },
|
| 148 |
+
});
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
/** Stub user with chess CategorySkill */
|
| 152 |
+
function makeUser(overrides: Record<string, unknown> = {}) {
|
| 153 |
+
return {
|
| 154 |
+
id: 1,
|
| 155 |
+
name: "Player One",
|
| 156 |
+
level: 1,
|
| 157 |
+
totalXp: 0,
|
| 158 |
+
currentXp: 0,
|
| 159 |
+
xpToNextLevel: 1000,
|
| 160 |
+
title: "Smooth Brain",
|
| 161 |
+
dailyGoalXp: 100,
|
| 162 |
+
streak: 3,
|
| 163 |
+
longestStreak: 10,
|
| 164 |
+
streakFreezes: 1,
|
| 165 |
+
lichessUsername: null,
|
| 166 |
+
chesscomUsername: null,
|
| 167 |
+
createdAt: new Date(),
|
| 168 |
+
categorySkills: [
|
| 169 |
+
{
|
| 170 |
+
id: 20,
|
| 171 |
+
userId: 1,
|
| 172 |
+
category: "chess",
|
| 173 |
+
level: 1,
|
| 174 |
+
totalXp: 0,
|
| 175 |
+
currentXp: 0,
|
| 176 |
+
xpToNext: 1000,
|
| 177 |
+
},
|
| 178 |
+
],
|
| 179 |
+
...overrides,
|
| 180 |
+
};
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
/** Wire up mockTransaction to execute the callback with a fake tx client */
|
| 184 |
+
function setupTransaction() {
|
| 185 |
+
mockTransaction.mockImplementation(
|
| 186 |
+
async (callback: (tx: Record<string, unknown>) => Promise<unknown>) => {
|
| 187 |
+
const tx = {
|
| 188 |
+
activity: { create: mockActivityCreate },
|
| 189 |
+
user: { update: mockUserUpdate },
|
| 190 |
+
categorySkill: { update: mockCategorySkillUpdate },
|
| 191 |
+
dailyLog: {
|
| 192 |
+
create: mockDailyLogCreate,
|
| 193 |
+
update: mockDailyLogUpdate,
|
| 194 |
+
},
|
| 195 |
+
};
|
| 196 |
+
return callback(tx);
|
| 197 |
+
},
|
| 198 |
+
);
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
beforeEach(() => {
|
| 202 |
+
vi.clearAllMocks();
|
| 203 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 204 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 205 |
+
mockRollCriticalHit.mockReturnValue(false);
|
| 206 |
+
mockGetMultiplierPercent.mockResolvedValue(0);
|
| 207 |
+
mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 });
|
| 208 |
+
setupTransaction();
|
| 209 |
+
mockActivityCreate.mockResolvedValue({});
|
| 210 |
+
mockUserUpdate.mockResolvedValue({});
|
| 211 |
+
mockCategorySkillUpdate.mockResolvedValue({});
|
| 212 |
+
mockDailyLogCreate.mockResolvedValue({});
|
| 213 |
+
mockDailyLogUpdate.mockResolvedValue({});
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
// ---------------------------------------------------------------------------
|
| 217 |
+
// Input validation
|
| 218 |
+
// ---------------------------------------------------------------------------
|
| 219 |
+
|
| 220 |
+
describe("POST /api/chess/game-result — input validation", () => {
|
| 221 |
+
it("returns 400 on invalid JSON body", async () => {
|
| 222 |
+
const res = await POST(makePost()); // body is not-json{{{
|
| 223 |
+
expect(res.status).toBe(400);
|
| 224 |
+
const body = (await json(res)) as { error: string };
|
| 225 |
+
expect(body.error).toMatch(/invalid json/i);
|
| 226 |
+
});
|
| 227 |
+
|
| 228 |
+
it("returns 400 when gameId is missing", async () => {
|
| 229 |
+
const res = await POST(makePostValid({ gameId: undefined }));
|
| 230 |
+
expect(res.status).toBe(400);
|
| 231 |
+
const body = (await json(res)) as { error: string };
|
| 232 |
+
expect(body.error).toMatch(/gameid/i);
|
| 233 |
+
});
|
| 234 |
+
|
| 235 |
+
it("returns 400 when gameId is not a string", async () => {
|
| 236 |
+
const res = await POST(makePostValid({ gameId: 42 }));
|
| 237 |
+
expect(res.status).toBe(400);
|
| 238 |
+
const body = (await json(res)) as { error: string };
|
| 239 |
+
expect(body.error).toMatch(/gameid/i);
|
| 240 |
+
});
|
| 241 |
+
|
| 242 |
+
it("returns 400 when level is below 1", async () => {
|
| 243 |
+
const res = await POST(makePostValid({ level: 0 }));
|
| 244 |
+
expect(res.status).toBe(400);
|
| 245 |
+
const body = (await json(res)) as { error: string };
|
| 246 |
+
expect(body.error).toMatch(/level/i);
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
it("returns 400 when level exceeds 8", async () => {
|
| 250 |
+
const res = await POST(makePostValid({ level: 9 }));
|
| 251 |
+
expect(res.status).toBe(400);
|
| 252 |
+
const body = (await json(res)) as { error: string };
|
| 253 |
+
expect(body.error).toMatch(/level/i);
|
| 254 |
+
});
|
| 255 |
+
|
| 256 |
+
it("returns 400 when level is not a number", async () => {
|
| 257 |
+
const res = await POST(makePostValid({ level: "hard" }));
|
| 258 |
+
expect(res.status).toBe(400);
|
| 259 |
+
const body = (await json(res)) as { error: string };
|
| 260 |
+
expect(body.error).toMatch(/level/i);
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
it("returns 400 when result is an invalid value", async () => {
|
| 264 |
+
const res = await POST(makePostValid({ result: "draw-by-repetition" }));
|
| 265 |
+
expect(res.status).toBe(400);
|
| 266 |
+
const body = (await json(res)) as { error: string };
|
| 267 |
+
expect(body.error).toMatch(/result/i);
|
| 268 |
+
});
|
| 269 |
+
|
| 270 |
+
it("returns 400 when result is missing", async () => {
|
| 271 |
+
const res = await POST(makePostValid({ result: undefined }));
|
| 272 |
+
expect(res.status).toBe(400);
|
| 273 |
+
const body = (await json(res)) as { error: string };
|
| 274 |
+
expect(body.error).toMatch(/result/i);
|
| 275 |
+
});
|
| 276 |
+
});
|
| 277 |
+
|
| 278 |
+
// ---------------------------------------------------------------------------
|
| 279 |
+
// DB guards
|
| 280 |
+
// ---------------------------------------------------------------------------
|
| 281 |
+
|
| 282 |
+
describe("POST /api/chess/game-result — DB guards", () => {
|
| 283 |
+
it("returns 404 when user is not found", async () => {
|
| 284 |
+
mockUserFindFirst.mockResolvedValue(null);
|
| 285 |
+
const res = await POST(makePostValid());
|
| 286 |
+
expect(res.status).toBe(404);
|
| 287 |
+
});
|
| 288 |
+
|
| 289 |
+
it("returns 500 when chess CategorySkill is missing", async () => {
|
| 290 |
+
mockUserFindFirst.mockResolvedValue(makeUser({ categorySkills: [] }));
|
| 291 |
+
const res = await POST(makePostValid());
|
| 292 |
+
expect(res.status).toBe(500);
|
| 293 |
+
});
|
| 294 |
+
});
|
| 295 |
+
|
| 296 |
+
// ---------------------------------------------------------------------------
|
| 297 |
+
// Success path — response shape
|
| 298 |
+
// ---------------------------------------------------------------------------
|
| 299 |
+
|
| 300 |
+
describe("POST /api/chess/game-result — success shape", () => {
|
| 301 |
+
it("returns 200 with expected fields for a win", async () => {
|
| 302 |
+
const res = await POST(makePostValid({ result: "win", level: 4 }));
|
| 303 |
+
expect(res.status).toBe(200);
|
| 304 |
+
const body = (await json(res)) as Record<string, unknown>;
|
| 305 |
+
|
| 306 |
+
expect(body.result).toBe("win");
|
| 307 |
+
expect(body.level).toBe(4);
|
| 308 |
+
expect(typeof body.qualityScore).toBe("number");
|
| 309 |
+
expect(body.xp).toBeDefined();
|
| 310 |
+
expect(typeof body.levelUp).toBe("boolean");
|
| 311 |
+
expect(body.categoryXp).toBeDefined();
|
| 312 |
+
expect(Array.isArray(body.unlocks)).toBe(true);
|
| 313 |
+
});
|
| 314 |
+
|
| 315 |
+
it("win qualityScore > draw qualityScore at same level", async () => {
|
| 316 |
+
const winRes = await POST(makePostValid({ result: "win", level: 4 }));
|
| 317 |
+
const winBody = (await json(winRes)) as { qualityScore: number };
|
| 318 |
+
|
| 319 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 320 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 321 |
+
setupTransaction();
|
| 322 |
+
|
| 323 |
+
const drawRes = await POST(makePostValid({ result: "draw", level: 4 }));
|
| 324 |
+
const drawBody = (await json(drawRes)) as { qualityScore: number };
|
| 325 |
+
|
| 326 |
+
expect(winBody.qualityScore).toBeGreaterThan(drawBody.qualityScore);
|
| 327 |
+
});
|
| 328 |
+
|
| 329 |
+
it("draw qualityScore > loss qualityScore at same level", async () => {
|
| 330 |
+
const drawRes = await POST(makePostValid({ result: "draw", level: 4 }));
|
| 331 |
+
const drawBody = (await json(drawRes)) as { qualityScore: number };
|
| 332 |
+
|
| 333 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 334 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 335 |
+
setupTransaction();
|
| 336 |
+
|
| 337 |
+
const lossRes = await POST(makePostValid({ result: "loss", level: 4 }));
|
| 338 |
+
const lossBody = (await json(lossRes)) as { qualityScore: number };
|
| 339 |
+
|
| 340 |
+
expect(drawBody.qualityScore).toBeGreaterThan(lossBody.qualityScore);
|
| 341 |
+
});
|
| 342 |
+
|
| 343 |
+
it("XP breakdown includes baseXp = 30", async () => {
|
| 344 |
+
const res = await POST(makePostValid({ result: "win", level: 8 }));
|
| 345 |
+
const body = (await json(res)) as { xp: { baseXp: number } };
|
| 346 |
+
expect(body.xp.baseXp).toBe(30);
|
| 347 |
+
});
|
| 348 |
+
|
| 349 |
+
it("XP quality bonus is positive for a win", async () => {
|
| 350 |
+
const res = await POST(makePostValid({ result: "win", level: 4 }));
|
| 351 |
+
const body = (await json(res)) as { xp: { qualityBonus: number } };
|
| 352 |
+
expect(body.xp.qualityBonus).toBeGreaterThan(0);
|
| 353 |
+
});
|
| 354 |
+
|
| 355 |
+
it("XP quality bonus is 0 for a loss at level 1 (small bonus only)", async () => {
|
| 356 |
+
// Even a loss earns a small quality bonus (0.1–0.2) so totalXp > baseXp
|
| 357 |
+
const res = await POST(makePostValid({ result: "loss", level: 1 }));
|
| 358 |
+
const body = (await json(res)) as { xp: { totalXp: number; baseXp: number } };
|
| 359 |
+
expect(body.xp.totalXp).toBeGreaterThan(body.xp.baseXp);
|
| 360 |
+
});
|
| 361 |
+
});
|
| 362 |
+
|
| 363 |
+
// ---------------------------------------------------------------------------
|
| 364 |
+
// Critical hit
|
| 365 |
+
// ---------------------------------------------------------------------------
|
| 366 |
+
|
| 367 |
+
describe("POST /api/chess/game-result — critical hit", () => {
|
| 368 |
+
it("doubles totalXp on critical hit", async () => {
|
| 369 |
+
// No crit: baseline
|
| 370 |
+
mockRollCriticalHit.mockReturnValue(false);
|
| 371 |
+
const normalRes = await POST(makePostValid({ result: "win", level: 4 }));
|
| 372 |
+
const normalBody = (await json(normalRes)) as { xp: { totalXp: number; isCriticalHit: boolean } };
|
| 373 |
+
expect(normalBody.xp.isCriticalHit).toBe(false);
|
| 374 |
+
const normalXp = normalBody.xp.totalXp;
|
| 375 |
+
|
| 376 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 377 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 378 |
+
setupTransaction();
|
| 379 |
+
|
| 380 |
+
// With crit
|
| 381 |
+
mockRollCriticalHit.mockReturnValue(true);
|
| 382 |
+
const critRes = await POST(makePostValid({ result: "win", level: 4 }));
|
| 383 |
+
const critBody = (await json(critRes)) as { xp: { totalXp: number; isCriticalHit: boolean } };
|
| 384 |
+
expect(critBody.xp.isCriticalHit).toBe(true);
|
| 385 |
+
expect(critBody.xp.totalXp).toBe(normalXp * 2);
|
| 386 |
+
});
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
// ---------------------------------------------------------------------------
|
| 390 |
+
// Multiplier
|
| 391 |
+
// ---------------------------------------------------------------------------
|
| 392 |
+
|
| 393 |
+
describe("POST /api/chess/game-result — multiplier", () => {
|
| 394 |
+
it("reflects multiplierPercent in xp breakdown", async () => {
|
| 395 |
+
mockGetMultiplierPercent.mockResolvedValue(25);
|
| 396 |
+
const res = await POST(makePostValid({ result: "win", level: 4 }));
|
| 397 |
+
const body = (await json(res)) as { xp: { multiplierPercent: number; multiplierBonus: number } };
|
| 398 |
+
expect(body.xp.multiplierPercent).toBe(25);
|
| 399 |
+
expect(body.xp.multiplierBonus).toBeGreaterThan(0);
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
it("multiplierBonus is 0 when no active multipliers", async () => {
|
| 403 |
+
mockGetMultiplierPercent.mockResolvedValue(0);
|
| 404 |
+
const res = await POST(makePostValid({ result: "win", level: 4 }));
|
| 405 |
+
const body = (await json(res)) as { xp: { multiplierBonus: number } };
|
| 406 |
+
expect(body.xp.multiplierBonus).toBe(0);
|
| 407 |
+
});
|
| 408 |
+
});
|
| 409 |
+
|
| 410 |
+
// ---------------------------------------------------------------------------
|
| 411 |
+
// DailyLog handling
|
| 412 |
+
// ---------------------------------------------------------------------------
|
| 413 |
+
|
| 414 |
+
describe("POST /api/chess/game-result — DailyLog", () => {
|
| 415 |
+
it("creates a new DailyLog when none exists for today", async () => {
|
| 416 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 417 |
+
await POST(makePostValid());
|
| 418 |
+
expect(mockDailyLogCreate).toHaveBeenCalledTimes(1);
|
| 419 |
+
expect(mockDailyLogUpdate).not.toHaveBeenCalled();
|
| 420 |
+
});
|
| 421 |
+
|
| 422 |
+
it("updates an existing DailyLog when one exists", async () => {
|
| 423 |
+
mockDailyLogFindFirst.mockResolvedValue({
|
| 424 |
+
id: 99,
|
| 425 |
+
xpEarned: 50,
|
| 426 |
+
activityCount: 2,
|
| 427 |
+
goalMet: false,
|
| 428 |
+
});
|
| 429 |
+
await POST(makePostValid());
|
| 430 |
+
expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1);
|
| 431 |
+
expect(mockDailyLogCreate).not.toHaveBeenCalled();
|
| 432 |
+
});
|
| 433 |
+
|
| 434 |
+
it("sets goalMet=true when accumulated XP meets dailyGoalXp", async () => {
|
| 435 |
+
// dailyGoalXp = 100; existing 80 XP; win at level 8 yields ≥30 XP → total ≥ 110
|
| 436 |
+
mockUserFindFirst.mockResolvedValue(makeUser({ dailyGoalXp: 100 }));
|
| 437 |
+
mockDailyLogFindFirst.mockResolvedValue({
|
| 438 |
+
id: 5,
|
| 439 |
+
xpEarned: 80,
|
| 440 |
+
activityCount: 3,
|
| 441 |
+
goalMet: false,
|
| 442 |
+
});
|
| 443 |
+
await POST(makePostValid({ result: "win", level: 8 }));
|
| 444 |
+
const updateCall = mockDailyLogUpdate.mock.calls[0][0] as {
|
| 445 |
+
data: { goalMet: boolean };
|
| 446 |
+
};
|
| 447 |
+
expect(updateCall.data.goalMet).toBe(true);
|
| 448 |
+
});
|
| 449 |
+
});
|
| 450 |
+
|
| 451 |
+
// ---------------------------------------------------------------------------
|
| 452 |
+
// Skill unlocks
|
| 453 |
+
// ---------------------------------------------------------------------------
|
| 454 |
+
|
| 455 |
+
describe("POST /api/chess/game-result — skill unlocks", () => {
|
| 456 |
+
it("calls processSkillUnlocks on category level-up", async () => {
|
| 457 |
+
// Give enough category XP to level up (currentXp + earned >= xpToNext)
|
| 458 |
+
mockUserFindFirst.mockResolvedValue(
|
| 459 |
+
makeUser({
|
| 460 |
+
categorySkills: [
|
| 461 |
+
{ id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 95, xpToNext: 100 },
|
| 462 |
+
],
|
| 463 |
+
}),
|
| 464 |
+
);
|
| 465 |
+
mockProcessSkillUnlocks.mockResolvedValue({ unlocked: ["Chess Vision"], streakFreezesGranted: 0 });
|
| 466 |
+
|
| 467 |
+
const res = await POST(makePostValid({ result: "win", level: 8 }));
|
| 468 |
+
expect(mockProcessSkillUnlocks).toHaveBeenCalled();
|
| 469 |
+
|
| 470 |
+
const body = (await json(res)) as { unlocks: string[] };
|
| 471 |
+
expect(body.unlocks).toContain("Chess Vision");
|
| 472 |
+
});
|
| 473 |
+
|
| 474 |
+
it("does NOT call processSkillUnlocks when no category level-up", async () => {
|
| 475 |
+
// xpToNext is very large — no level-up possible
|
| 476 |
+
mockUserFindFirst.mockResolvedValue(
|
| 477 |
+
makeUser({
|
| 478 |
+
categorySkills: [
|
| 479 |
+
{ id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 0, xpToNext: 100_000 },
|
| 480 |
+
],
|
| 481 |
+
}),
|
| 482 |
+
);
|
| 483 |
+
await POST(makePostValid({ result: "win", level: 4 }));
|
| 484 |
+
expect(mockProcessSkillUnlocks).not.toHaveBeenCalled();
|
| 485 |
+
});
|
| 486 |
+
|
| 487 |
+
it("includes streakFreezesGranted in response", async () => {
|
| 488 |
+
mockUserFindFirst.mockResolvedValue(
|
| 489 |
+
makeUser({
|
| 490 |
+
categorySkills: [
|
| 491 |
+
{ id: 20, userId: 1, category: "chess", level: 1, totalXp: 0, currentXp: 95, xpToNext: 100 },
|
| 492 |
+
],
|
| 493 |
+
}),
|
| 494 |
+
);
|
| 495 |
+
mockProcessSkillUnlocks.mockResolvedValue({ unlocked: ["Streak Shield"], streakFreezesGranted: 1 });
|
| 496 |
+
|
| 497 |
+
const res = await POST(makePostValid({ result: "win", level: 8 }));
|
| 498 |
+
const body = (await json(res)) as { streakFreezesGranted: number };
|
| 499 |
+
expect(body.streakFreezesGranted).toBe(1);
|
| 500 |
+
});
|
| 501 |
+
});
|
| 502 |
+
|
| 503 |
+
// ---------------------------------------------------------------------------
|
| 504 |
+
// Title progression
|
| 505 |
+
// ---------------------------------------------------------------------------
|
| 506 |
+
|
| 507 |
+
describe("POST /api/chess/game-result — title", () => {
|
| 508 |
+
it("includes newTitle when user levels up past a title threshold", async () => {
|
| 509 |
+
// Level 2 → level 3 crosses the "Slightly Wrinkled" threshold (level 3 in TITLE_THRESHOLDS).
|
| 510 |
+
// Give currentXp close to xpToNextLevel so the earned XP triggers a level-up.
|
| 511 |
+
mockUserFindFirst.mockResolvedValue(
|
| 512 |
+
makeUser({ level: 2, currentXp: 95, xpToNextLevel: 100, title: "Smooth Brain" }),
|
| 513 |
+
);
|
| 514 |
+
const res = await POST(makePostValid({ result: "win", level: 8 }));
|
| 515 |
+
expect(res.status).toBe(200);
|
| 516 |
+
const body = (await json(res)) as { levelUp: boolean; newTitle?: string };
|
| 517 |
+
expect(body.levelUp).toBe(true);
|
| 518 |
+
expect(body.newTitle).toBe("Slightly Wrinkled");
|
| 519 |
+
});
|
| 520 |
+
|
| 521 |
+
it("newTitle is undefined when no level-up", async () => {
|
| 522 |
+
// xpToNextLevel is very large
|
| 523 |
+
mockUserFindFirst.mockResolvedValue(
|
| 524 |
+
makeUser({ level: 1, currentXp: 0, xpToNextLevel: 100_000 }),
|
| 525 |
+
);
|
| 526 |
+
const res = await POST(makePostValid({ result: "win", level: 4 }));
|
| 527 |
+
const body = (await json(res)) as { levelUp: boolean; newTitle?: string };
|
| 528 |
+
expect(body.levelUp).toBe(false);
|
| 529 |
+
expect(body.newTitle).toBeUndefined();
|
| 530 |
+
});
|
| 531 |
+
});
|
| 532 |
+
|
| 533 |
+
// ---------------------------------------------------------------------------
|
| 534 |
+
// userId default
|
| 535 |
+
// ---------------------------------------------------------------------------
|
| 536 |
+
|
| 537 |
+
describe("POST /api/chess/game-result — userId", () => {
|
| 538 |
+
it("defaults userId to 1 when not supplied", async () => {
|
| 539 |
+
await POST(makePostValid()); // no userId in body
|
| 540 |
+
expect(mockUserFindFirst).toHaveBeenCalledWith(
|
| 541 |
+
expect.objectContaining({ where: { id: 1 } }),
|
| 542 |
+
);
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
+
it("uses provided userId when supplied", async () => {
|
| 546 |
+
await POST(makePostValid({ userId: 7 }));
|
| 547 |
+
expect(mockUserFindFirst).toHaveBeenCalledWith(
|
| 548 |
+
expect.objectContaining({ where: { id: 7 } }),
|
| 549 |
+
);
|
| 550 |
+
});
|
| 551 |
+
});
|
| 552 |
+
|
| 553 |
+
// ---------------------------------------------------------------------------
|
| 554 |
+
// All three valid result values work
|
| 555 |
+
// ---------------------------------------------------------------------------
|
| 556 |
+
|
| 557 |
+
describe("POST /api/chess/game-result — result variants", () => {
|
| 558 |
+
for (const result of ["win", "draw", "loss"] as const) {
|
| 559 |
+
it(`returns 200 for result="${result}"`, async () => {
|
| 560 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 561 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 562 |
+
setupTransaction();
|
| 563 |
+
|
| 564 |
+
const res = await POST(makePostValid({ result }));
|
| 565 |
+
expect(res.status).toBe(200);
|
| 566 |
+
const body = (await json(res)) as { result: string };
|
| 567 |
+
expect(body.result).toBe(result);
|
| 568 |
+
});
|
| 569 |
+
}
|
| 570 |
+
});
|
src/app/api/chess/__tests__/game-result.test.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Tests for chess game-result quality scoring logic.
|
| 3 |
+
*
|
| 4 |
+
* We test the pure calcGameQualityScore function exported from the route.
|
| 5 |
+
* The route itself uses the same DB/XP pipeline as the puzzle submit route,
|
| 6 |
+
* which already has comprehensive integration-level tests via the mocked
|
| 7 |
+
* Prisma pattern in other test files.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
import { describe, it, expect } from "vitest";
|
| 11 |
+
import { calcGameQualityScore, type GameResult } from "../game-result/route";
|
| 12 |
+
|
| 13 |
+
// ─── Quality score bounds ────────────────────────────────────────────────────
|
| 14 |
+
|
| 15 |
+
describe("calcGameQualityScore — win", () => {
|
| 16 |
+
it("returns 0.80 for a win at level 1 (easiest)", () => {
|
| 17 |
+
// 0.8 + (1/8)*0.2 = 0.825, but floor is 0.80 at level 0
|
| 18 |
+
expect(calcGameQualityScore("win", 1)).toBeCloseTo(0.825, 3);
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
it("returns 1.00 for a win at level 8 (hardest)", () => {
|
| 22 |
+
expect(calcGameQualityScore("win", 8)).toBeCloseTo(1.0, 3);
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
it("returns 0.90 for a win at level 4 (midpoint)", () => {
|
| 26 |
+
// 0.8 + (4/8)*0.2 = 0.9
|
| 27 |
+
expect(calcGameQualityScore("win", 4)).toBeCloseTo(0.9, 3);
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
it("always returns > 0.8 for a win at any level", () => {
|
| 31 |
+
for (let level = 1; level <= 8; level++) {
|
| 32 |
+
expect(calcGameQualityScore("win", level)).toBeGreaterThan(0.8);
|
| 33 |
+
}
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
it("never exceeds 1.0 for a win", () => {
|
| 37 |
+
for (let level = 1; level <= 8; level++) {
|
| 38 |
+
expect(calcGameQualityScore("win", level)).toBeLessThanOrEqual(1.0);
|
| 39 |
+
}
|
| 40 |
+
});
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
describe("calcGameQualityScore — draw", () => {
|
| 44 |
+
it("returns 0.50 for a draw at level 0 (boundary)", () => {
|
| 45 |
+
// level clamped: (0/8)*0.15 = 0, so 0.5
|
| 46 |
+
expect(calcGameQualityScore("draw", 0)).toBeCloseTo(0.5, 3);
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
it("returns ~0.65 for a draw at level 8", () => {
|
| 50 |
+
// 0.5 + (8/8)*0.15 = 0.65
|
| 51 |
+
expect(calcGameQualityScore("draw", 8)).toBeCloseTo(0.65, 3);
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
it("returns 0.575 for a draw at level 4", () => {
|
| 55 |
+
// 0.5 + (4/8)*0.15 = 0.575
|
| 56 |
+
expect(calcGameQualityScore("draw", 4)).toBeCloseTo(0.575, 3);
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it("is always less than a win at the same level", () => {
|
| 60 |
+
for (let level = 1; level <= 8; level++) {
|
| 61 |
+
expect(calcGameQualityScore("draw", level)).toBeLessThan(
|
| 62 |
+
calcGameQualityScore("win", level)
|
| 63 |
+
);
|
| 64 |
+
}
|
| 65 |
+
});
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
describe("calcGameQualityScore — loss", () => {
|
| 69 |
+
it("returns 0.10 for a loss at level 0 (boundary)", () => {
|
| 70 |
+
expect(calcGameQualityScore("loss", 0)).toBeCloseTo(0.1, 3);
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
it("returns 0.20 for a loss at level 8 (hardest opponent)", () => {
|
| 74 |
+
// 0.1 + (8/8)*0.1 = 0.2
|
| 75 |
+
expect(calcGameQualityScore("loss", 8)).toBeCloseTo(0.2, 3);
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it("returns 0.15 for a loss at level 4", () => {
|
| 79 |
+
// 0.1 + (4/8)*0.1 = 0.15
|
| 80 |
+
expect(calcGameQualityScore("loss", 4)).toBeCloseTo(0.15, 3);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it("is always less than a draw at the same level", () => {
|
| 84 |
+
for (let level = 1; level <= 8; level++) {
|
| 85 |
+
expect(calcGameQualityScore("loss", level)).toBeLessThan(
|
| 86 |
+
calcGameQualityScore("draw", level)
|
| 87 |
+
);
|
| 88 |
+
}
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
it("always returns > 0 (participation credit)", () => {
|
| 92 |
+
for (let level = 1; level <= 8; level++) {
|
| 93 |
+
expect(calcGameQualityScore("loss", level)).toBeGreaterThan(0);
|
| 94 |
+
}
|
| 95 |
+
});
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
describe("calcGameQualityScore — level clamping", () => {
|
| 99 |
+
it("clamps negative levels to 0", () => {
|
| 100 |
+
expect(calcGameQualityScore("win", -5)).toBeCloseTo(
|
| 101 |
+
calcGameQualityScore("win", 0),
|
| 102 |
+
5
|
| 103 |
+
);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
it("clamps levels above 8 to 8", () => {
|
| 107 |
+
expect(calcGameQualityScore("win", 99)).toBeCloseTo(
|
| 108 |
+
calcGameQualityScore("win", 8),
|
| 109 |
+
5
|
| 110 |
+
);
|
| 111 |
+
});
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
describe("calcGameQualityScore — monotonicity", () => {
|
| 115 |
+
const results: GameResult[] = ["win", "draw", "loss"];
|
| 116 |
+
|
| 117 |
+
it("quality is monotonically non-decreasing with level for all result types", () => {
|
| 118 |
+
for (const result of results) {
|
| 119 |
+
let prev = calcGameQualityScore(result, 0);
|
| 120 |
+
for (let level = 1; level <= 8; level++) {
|
| 121 |
+
const curr = calcGameQualityScore(result, level);
|
| 122 |
+
expect(curr).toBeGreaterThanOrEqual(prev);
|
| 123 |
+
prev = curr;
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
});
|
| 127 |
+
|
| 128 |
+
it("win > draw > loss at every level", () => {
|
| 129 |
+
for (let level = 1; level <= 8; level++) {
|
| 130 |
+
const win = calcGameQualityScore("win", level);
|
| 131 |
+
const draw = calcGameQualityScore("draw", level);
|
| 132 |
+
const loss = calcGameQualityScore("loss", level);
|
| 133 |
+
expect(win).toBeGreaterThan(draw);
|
| 134 |
+
expect(draw).toBeGreaterThan(loss);
|
| 135 |
+
}
|
| 136 |
+
});
|
| 137 |
+
});
|
| 138 |
+
|
| 139 |
+
describe("calcGameQualityScore — all values in [0, 1]", () => {
|
| 140 |
+
const results: GameResult[] = ["win", "draw", "loss"];
|
| 141 |
+
|
| 142 |
+
it("always returns a value in [0, 1]", () => {
|
| 143 |
+
for (const result of results) {
|
| 144 |
+
for (let level = 0; level <= 8; level++) {
|
| 145 |
+
const score = calcGameQualityScore(result, level);
|
| 146 |
+
expect(score).toBeGreaterThanOrEqual(0);
|
| 147 |
+
expect(score).toBeLessThanOrEqual(1);
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
});
|
| 151 |
+
});
|
src/app/api/chess/__tests__/puzzle-submit.test.ts
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Tests for chess puzzle and submit routes.
|
| 3 |
+
*
|
| 4 |
+
* Covers:
|
| 5 |
+
* GET /api/chess/puzzle
|
| 6 |
+
* - random puzzle fetch (default)
|
| 7 |
+
* - daily puzzle fetch (?daily=true)
|
| 8 |
+
* - 502 when Lichess returns null
|
| 9 |
+
* - response shape (id, solution, rating, themes, plays, gameUrl, pgn, fen computed server-side)
|
| 10 |
+
*
|
| 11 |
+
* POST /api/chess/submit — calcQualityScore (pure)
|
| 12 |
+
* - solved = false → 0
|
| 13 |
+
* - perfect efficiency (movesPlayed === solutionLen) → 1.0
|
| 14 |
+
* - extra moves reduce quality
|
| 15 |
+
*
|
| 16 |
+
* POST /api/chess/submit — handler
|
| 17 |
+
* - input validation: missing puzzleId, non-string puzzleId, non-number puzzleRating, non-boolean solved
|
| 18 |
+
* - invalid JSON body → 400
|
| 19 |
+
* - user not found → 404
|
| 20 |
+
* - missing chess CategorySkill → 500
|
| 21 |
+
* - success shape: solved, qualityScore, xp breakdown, levelUp, categoryXp, unlocks
|
| 22 |
+
* - XP: unsolved puzzle gets quality 0 (base XP only, no quality bonus)
|
| 23 |
+
* - XP: critical hit doubles totalXp
|
| 24 |
+
* - XP: multiplier bonus reflected in response
|
| 25 |
+
* - DailyLog: created when no existing log
|
| 26 |
+
* - DailyLog: updated when existing log exists
|
| 27 |
+
* - goalMet flag set when XP reaches dailyGoalXp
|
| 28 |
+
* - processSkillUnlocks called on category level-up
|
| 29 |
+
* - processSkillUnlocks NOT called when no category level-up
|
| 30 |
+
*/
|
| 31 |
+
|
| 32 |
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
| 33 |
+
import { NextRequest } from "next/server";
|
| 34 |
+
|
| 35 |
+
// ---------------------------------------------------------------------------
|
| 36 |
+
// Mock Lichess API (for puzzle route)
|
| 37 |
+
// ---------------------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
const mockGetLichessPuzzle = vi.fn();
|
| 40 |
+
const mockGetLichessDailyPuzzle = vi.fn();
|
| 41 |
+
|
| 42 |
+
vi.mock("@/lib/lichess", () => ({
|
| 43 |
+
getLichessPuzzle: (...args: unknown[]) => mockGetLichessPuzzle(...args),
|
| 44 |
+
getLichessDailyPuzzle: (...args: unknown[]) => mockGetLichessDailyPuzzle(...args),
|
| 45 |
+
}));
|
| 46 |
+
|
| 47 |
+
// ---------------------------------------------------------------------------
|
| 48 |
+
// Mock Prisma (for submit route)
|
| 49 |
+
// ---------------------------------------------------------------------------
|
| 50 |
+
|
| 51 |
+
const mockUserFindFirst = vi.fn();
|
| 52 |
+
const mockDailyLogFindFirst = vi.fn();
|
| 53 |
+
const mockTransaction = vi.fn();
|
| 54 |
+
const mockActivityCreate = vi.fn();
|
| 55 |
+
const mockUserUpdate = vi.fn();
|
| 56 |
+
const mockCategorySkillUpdate = vi.fn();
|
| 57 |
+
const mockDailyLogCreate = vi.fn();
|
| 58 |
+
const mockDailyLogUpdate = vi.fn();
|
| 59 |
+
|
| 60 |
+
vi.mock("@/lib/db", () => ({
|
| 61 |
+
prisma: {
|
| 62 |
+
user: {
|
| 63 |
+
findFirst: (...args: unknown[]) => mockUserFindFirst(...args),
|
| 64 |
+
},
|
| 65 |
+
dailyLog: {
|
| 66 |
+
findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args),
|
| 67 |
+
},
|
| 68 |
+
$transaction: (...args: unknown[]) => mockTransaction(...args),
|
| 69 |
+
},
|
| 70 |
+
}));
|
| 71 |
+
|
| 72 |
+
// ---------------------------------------------------------------------------
|
| 73 |
+
// Mock rollCriticalHit (deterministic XP)
|
| 74 |
+
// ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
const mockRollCriticalHit = vi.fn(() => false);
|
| 77 |
+
|
| 78 |
+
vi.mock("@/lib/xp", async (importOriginal) => {
|
| 79 |
+
const actual = await importOriginal<typeof import("@/lib/xp")>();
|
| 80 |
+
return {
|
| 81 |
+
...actual,
|
| 82 |
+
rollCriticalHit: () => mockRollCriticalHit(),
|
| 83 |
+
};
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
// ---------------------------------------------------------------------------
|
| 87 |
+
// Mock getMultiplierPercent
|
| 88 |
+
// ---------------------------------------------------------------------------
|
| 89 |
+
|
| 90 |
+
const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0));
|
| 91 |
+
|
| 92 |
+
vi.mock("@/lib/multiplier", () => ({
|
| 93 |
+
getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args),
|
| 94 |
+
}));
|
| 95 |
+
|
| 96 |
+
// ---------------------------------------------------------------------------
|
| 97 |
+
// Mock processSkillUnlocks
|
| 98 |
+
// ---------------------------------------------------------------------------
|
| 99 |
+
|
| 100 |
+
const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> =>
|
| 101 |
+
Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }),
|
| 102 |
+
);
|
| 103 |
+
|
| 104 |
+
vi.mock("@/lib/skill-unlock", () => ({
|
| 105 |
+
processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args),
|
| 106 |
+
}));
|
| 107 |
+
|
| 108 |
+
// ---------------------------------------------------------------------------
|
| 109 |
+
// Mock processEndOfDay (no-op — streak logic is tested separately)
|
| 110 |
+
// ---------------------------------------------------------------------------
|
| 111 |
+
|
| 112 |
+
vi.mock("@/lib/streak", () => ({
|
| 113 |
+
processEndOfDay: vi.fn(() => Promise.resolve({
|
| 114 |
+
streak: 1,
|
| 115 |
+
freezeUsed: false,
|
| 116 |
+
streakBroken: false,
|
| 117 |
+
alreadyProcessed: false,
|
| 118 |
+
})),
|
| 119 |
+
}));
|
| 120 |
+
|
| 121 |
+
// ---------------------------------------------------------------------------
|
| 122 |
+
// Import routes (after mocks are hoisted)
|
| 123 |
+
// ---------------------------------------------------------------------------
|
| 124 |
+
|
| 125 |
+
import { GET } from "../puzzle/route";
|
| 126 |
+
import { POST, calcQualityScore } from "../submit/route";
|
| 127 |
+
|
| 128 |
+
// ---------------------------------------------------------------------------
|
| 129 |
+
// Helpers
|
| 130 |
+
// ---------------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
const originalEnv = { ...process.env };
|
| 133 |
+
|
| 134 |
+
async function json(res: Response): Promise<unknown> {
|
| 135 |
+
return res.json();
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
function makeGet(url: string): NextRequest {
|
| 139 |
+
return new NextRequest(url, { method: "GET" });
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
function makePost(body?: Record<string, unknown>): NextRequest {
|
| 143 |
+
return new NextRequest("http://localhost/api/chess/submit", {
|
| 144 |
+
method: "POST",
|
| 145 |
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
| 146 |
+
headers: { "Content-Type": "application/json" },
|
| 147 |
+
});
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
/** A representative raw Lichess puzzle API response */
|
| 151 |
+
function makeLichessPuzzle() {
|
| 152 |
+
return {
|
| 153 |
+
puzzle: {
|
| 154 |
+
id: "pzl123",
|
| 155 |
+
solution: ["e2e4", "e7e5", "g1f3"],
|
| 156 |
+
rating: 1500,
|
| 157 |
+
themes: ["fork", "middlegame"],
|
| 158 |
+
plays: 9876,
|
| 159 |
+
},
|
| 160 |
+
game: {
|
| 161 |
+
id: "game456",
|
| 162 |
+
pgn: "1. e4 e5 2. Nf3 Nc6",
|
| 163 |
+
},
|
| 164 |
+
};
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/** Stub user with chess CategorySkill */
|
| 168 |
+
function makeUser(overrides: Record<string, unknown> = {}) {
|
| 169 |
+
return {
|
| 170 |
+
id: 1,
|
| 171 |
+
name: "Player One",
|
| 172 |
+
level: 1,
|
| 173 |
+
totalXp: 0,
|
| 174 |
+
currentXp: 0,
|
| 175 |
+
xpToNextLevel: 100,
|
| 176 |
+
title: "Smooth Brain",
|
| 177 |
+
dailyGoalXp: 100,
|
| 178 |
+
streak: 3,
|
| 179 |
+
longestStreak: 10,
|
| 180 |
+
streakFreezes: 1,
|
| 181 |
+
lichessUsername: null,
|
| 182 |
+
chesscomUsername: null,
|
| 183 |
+
createdAt: new Date(),
|
| 184 |
+
categorySkills: [
|
| 185 |
+
{
|
| 186 |
+
id: 10,
|
| 187 |
+
userId: 1,
|
| 188 |
+
category: "chess",
|
| 189 |
+
level: 1,
|
| 190 |
+
totalXp: 0,
|
| 191 |
+
currentXp: 0,
|
| 192 |
+
xpToNext: 100,
|
| 193 |
+
},
|
| 194 |
+
],
|
| 195 |
+
...overrides,
|
| 196 |
+
};
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
/** Wire up mockTransaction to call the callback with a fake tx client */
|
| 200 |
+
function setupTransaction() {
|
| 201 |
+
mockTransaction.mockImplementation(
|
| 202 |
+
async (callback: (tx: Record<string, unknown>) => Promise<unknown>) => {
|
| 203 |
+
const tx = {
|
| 204 |
+
activity: { create: mockActivityCreate },
|
| 205 |
+
user: { update: mockUserUpdate },
|
| 206 |
+
categorySkill: { update: mockCategorySkillUpdate },
|
| 207 |
+
dailyLog: {
|
| 208 |
+
create: mockDailyLogCreate,
|
| 209 |
+
update: mockDailyLogUpdate,
|
| 210 |
+
},
|
| 211 |
+
};
|
| 212 |
+
return callback(tx);
|
| 213 |
+
},
|
| 214 |
+
);
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
beforeEach(() => {
|
| 218 |
+
vi.clearAllMocks();
|
| 219 |
+
process.env = { ...originalEnv };
|
| 220 |
+
|
| 221 |
+
// Default happy-path state
|
| 222 |
+
mockUserFindFirst.mockResolvedValue(makeUser());
|
| 223 |
+
mockDailyLogFindFirst.mockResolvedValue(null);
|
| 224 |
+
mockRollCriticalHit.mockReturnValue(false);
|
| 225 |
+
mockGetMultiplierPercent.mockResolvedValue(0);
|
| 226 |
+
mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 });
|
| 227 |
+
setupTransaction();
|
| 228 |
+
mockActivityCreate.mockResolvedValue({});
|
| 229 |
+
mockUserUpdate.mockResolvedValue({});
|
| 230 |
+
mockCategorySkillUpdate.mockResolvedValue({});
|
| 231 |
+
mockDailyLogCreate.mockResolvedValue({});
|
| 232 |
+
mockDailyLogUpdate.mockResolvedValue({});
|
| 233 |
+
});
|
| 234 |
+
|
| 235 |
+
afterEach(() => {
|
| 236 |
+
process.env = originalEnv;
|
| 237 |
+
});
|
| 238 |
+
|
| 239 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 240 |
+
// GET /api/chess/puzzle
|
| 241 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 242 |
+
|
| 243 |
+
describe("GET /api/chess/puzzle — random puzzle (default)", () => {
|
| 244 |
+
it("calls getLichessPuzzle (not daily) when no ?daily param", async () => {
|
| 245 |
+
mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());
|
| 246 |
+
|
| 247 |
+
await GET(makeGet("http://localhost/api/chess/puzzle"));
|
| 248 |
+
|
| 249 |
+
expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1);
|
| 250 |
+
expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled();
|
| 251 |
+
});
|
| 252 |
+
|
| 253 |
+
it("calls getLichessPuzzle when ?daily=false", async () => {
|
| 254 |
+
mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());
|
| 255 |
+
|
| 256 |
+
await GET(makeGet("http://localhost/api/chess/puzzle?daily=false"));
|
| 257 |
+
|
| 258 |
+
expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1);
|
| 259 |
+
expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled();
|
| 260 |
+
});
|
| 261 |
+
|
| 262 |
+
it("returns 200 with correct response shape", async () => {
|
| 263 |
+
mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());
|
| 264 |
+
|
| 265 |
+
const res = await GET(makeGet("http://localhost/api/chess/puzzle"));
|
| 266 |
+
expect(res.status).toBe(200);
|
| 267 |
+
|
| 268 |
+
const body = await json(res) as {
|
| 269 |
+
id: string;
|
| 270 |
+
fen: string;
|
| 271 |
+
solution: string[];
|
| 272 |
+
rating: number;
|
| 273 |
+
themes: string[];
|
| 274 |
+
plays: number;
|
| 275 |
+
gameUrl: string;
|
| 276 |
+
pgn: string;
|
| 277 |
+
};
|
| 278 |
+
|
| 279 |
+
expect(body.id).toBe("pzl123");
|
| 280 |
+
expect(body.solution).toEqual(["e2e4", "e7e5", "g1f3"]);
|
| 281 |
+
expect(body.rating).toBe(1500);
|
| 282 |
+
expect(body.themes).toEqual(["fork", "middlegame"]);
|
| 283 |
+
expect(body.plays).toBe(9876);
|
| 284 |
+
expect(body.gameUrl).toBe("https://lichess.org/game456");
|
| 285 |
+
expect(body.pgn).toBe("1. e4 e5 2. Nf3 Nc6");
|
| 286 |
+
// fen is now computed server-side from the game PGN
|
| 287 |
+
expect(body.fen).toBe("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3");
|
| 288 |
+
});
|
| 289 |
+
|
| 290 |
+
it("returns 502 when getLichessPuzzle returns null", async () => {
|
| 291 |
+
mockGetLichessPuzzle.mockResolvedValueOnce(null);
|
| 292 |
+
|
| 293 |
+
const res = await GET(makeGet("http://localhost/api/chess/puzzle"));
|
| 294 |
+
expect(res.status).toBe(502);
|
| 295 |
+
|
| 296 |
+
const body = await json(res) as { error: string };
|
| 297 |
+
expect(body.error).toBeTruthy();
|
| 298 |
+
});
|
| 299 |
+
});
|
| 300 |
+
|
| 301 |
+
describe("GET /api/chess/puzzle — daily puzzle (?daily=true)", () => {
|
| 302 |
+
it("calls getLichessDailyPuzzle when ?daily=true", async () => {
|
| 303 |
+
mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle());
|
| 304 |
+
|
| 305 |
+
await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));
|
| 306 |
+
|
| 307 |
+
expect(mockGetLichessDailyPuzzle).toHaveBeenCalledTimes(1);
|
| 308 |
+
expect(mockGetLichessPuzzle).not.toHaveBeenCalled();
|
| 309 |
+
});
|
| 310 |
+
|
| 311 |
+
it("returns 200 with the same shape as random puzzles", async () => {
|
| 312 |
+
mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle());
|
| 313 |
+
|
| 314 |
+
const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));
|
| 315 |
+
expect(res.status).toBe(200);
|
| 316 |
+
|
| 317 |
+
const body = await json(res) as { id: string; rating: number };
|
| 318 |
+
expect(body.id).toBe("pzl123");
|
| 319 |
+
expect(body.rating).toBe(1500);
|
| 320 |
+
});
|
| 321 |
+
|
| 322 |
+
it("returns 502 when getLichessDailyPuzzle returns null", async () => {
|
| 323 |
+
mockGetLichessDailyPuzzle.mockResolvedValueOnce(null);
|
| 324 |
+
|
| 325 |
+
const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));
|
| 326 |
+
expect(res.status).toBe(502);
|
| 327 |
+
});
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 331 |
+
// calcQualityScore — pure function
|
| 332 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 333 |
+
|
| 334 |
+
describe("calcQualityScore", () => {
|
| 335 |
+
it("returns 0 when solved = false regardless of moves", () => {
|
| 336 |
+
expect(calcQualityScore(false, 3, 3)).toBe(0);
|
| 337 |
+
expect(calcQualityScore(false, 10, 3)).toBe(0);
|
| 338 |
+
expect(calcQualityScore(false, 1, 5)).toBe(0);
|
| 339 |
+
});
|
| 340 |
+
|
| 341 |
+
it("returns 1.0 for a solved puzzle with perfect efficiency (movesPlayed === solutionLen)", () => {
|
| 342 |
+
// efficiency = solutionLen / movesPlayed = 1.0 → 0.5 + 1.0*0.5 = 1.0
|
| 343 |
+
expect(calcQualityScore(true, 3, 3)).toBeCloseTo(1.0, 5);
|
| 344 |
+
expect(calcQualityScore(true, 5, 5)).toBeCloseTo(1.0, 5);
|
| 345 |
+
});
|
| 346 |
+
|
| 347 |
+
it("returns 0.5 for a solved puzzle with zero efficiency (huge mistake count)", () => {
|
| 348 |
+
// efficiency → 0 as movesPlayed → ∞ → 0.5 + 0*0.5 = 0.5
|
| 349 |
+
expect(calcQualityScore(true, 1_000_000, 1)).toBeCloseTo(0.5, 1);
|
| 350 |
+
});
|
| 351 |
+
|
| 352 |
+
it("penalises extra moves (more moves = lower quality)", () => {
|
| 353 |
+
const perfect = calcQualityScore(true, 3, 3);
|
| 354 |
+
const oneExtra = calcQualityScore(true, 4, 3);
|
| 355 |
+
const twoExtra = calcQualityScore(true, 5, 3);
|
| 356 |
+
|
| 357 |
+
expect(perfect).toBeGreaterThan(oneExtra);
|
| 358 |
+
expect(oneExtra).toBeGreaterThan(twoExtra);
|
| 359 |
+
});
|
| 360 |
+
|
| 361 |
+
it("quality is always in [0, 1] for any inputs", () => {
|
| 362 |
+
const cases = [
|
| 363 |
+
[true, 1, 1],
|
| 364 |
+
[true, 5, 3],
|
| 365 |
+
[true, 100, 2],
|
| 366 |
+
[false, 1, 1],
|
| 367 |
+
[false, 0, 0],
|
| 368 |
+
] as Array<[boolean, number, number]>;
|
| 369 |
+
|
| 370 |
+
for (const [solved, moves, len] of cases) {
|
| 371 |
+
const q = calcQualityScore(solved, moves, len);
|
| 372 |
+
expect(q).toBeGreaterThanOrEqual(0);
|
| 373 |
+
expect(q).toBeLessThanOrEqual(1);
|
| 374 |
+
}
|
| 375 |
+
});
|
| 376 |
+
|
| 377 |
+
it("caps efficiency at 1.0 when movesPlayed < solutionLen (shouldn't happen in practice)", () => {
|
| 378 |
+
// If somehow movesPlayed < solutionLen, efficiency is capped at 1.0
|
| 379 |
+
expect(calcQualityScore(true, 1, 5)).toBeCloseTo(1.0, 5);
|
| 380 |
+
});
|
| 381 |
+
});
|
| 382 |
+
|
| 383 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 384 |
+
// POST /api/chess/submit — input validation
|
| 385 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 386 |
+
|
| 387 |
+
describe("POST /api/chess/submit — input validation", () => {
|
| 388 |
+
it("returns 400 for invalid JSON body", async () => {
|
| 389 |
+
const req = new NextRequest("http://localhost/api/chess/submit", {
|
| 390 |
+
method: "POST",
|
| 391 |
+
body: "not-json",
|
| 392 |
+
headers: { "Content-Type": "application/json" },
|
| 393 |
+
});
|
| 394 |
+
const res = await POST(req);
|
| 395 |
+
expect(res.status).toBe(400);
|
| 396 |
+
});
|
| 397 |
+
|
| 398 |
+
it("returns 400 when puzzleId is missing", async () => {
|
| 399 |
+
const res = await POST(makePost({
|
| 400 |
+
puzzleRating: 1500,
|
| 401 |
+
solved: true,
|
| 402 |
+
movesPlayed: 3,
|
| 403 |
+
solutionLen: 3,
|
| 404 |
+
}));
|
| 405 |
+
expect(res.status).toBe(400);
|
| 406 |
+
const body = await json(res) as { error: string };
|
| 407 |
+
expect(body.error).toMatch(/puzzleId/i);
|
| 408 |
+
});
|
| 409 |
+
|
| 410 |
+
it("returns 400 when puzzleId is not a string", async () => {
|
| 411 |
+
const res = await POST(makePost({
|
| 412 |
+
puzzleId: 12345,
|
| 413 |
+
puzzleRating: 1500,
|
| 414 |
+
solved: true,
|
| 415 |
+
movesPlayed: 3,
|
| 416 |
+
solutionLen: 3,
|
| 417 |
+
}));
|
| 418 |
+
expect(res.status).toBe(400);
|
| 419 |
+
const body = await json(res) as { error: string };
|
| 420 |
+
expect(body.error).toMatch(/puzzleId/i);
|
| 421 |
+
});
|
| 422 |
+
|
| 423 |
+
it("returns 400 when puzzleRating is not a number", async () => {
|
| 424 |
+
const res = await POST(makePost({
|
| 425 |
+
puzzleId: "pzl123",
|
| 426 |
+
puzzleRating: "hard",
|
| 427 |
+
solved: true,
|
| 428 |
+
movesPlayed: 3,
|
| 429 |
+
solutionLen: 3,
|
| 430 |
+
}));
|
| 431 |
+
expect(res.status).toBe(400);
|
| 432 |
+
const body = await json(res) as { error: string };
|
| 433 |
+
expect(body.error).toMatch(/puzzleRating/i);
|
| 434 |
+
});
|
| 435 |
+
|
| 436 |
+
it("returns 400 when solved is not a boolean", async () => {
|
| 437 |
+
const res = await POST(makePost({
|
| 438 |
+
puzzleId: "pzl123",
|
| 439 |
+
puzzleRating: 1500,
|
| 440 |
+
solved: "yes",
|
| 441 |
+
movesPlayed: 3,
|
| 442 |
+
solutionLen: 3,
|
| 443 |
+
}));
|
| 444 |
+
expect(res.status).toBe(400);
|
| 445 |
+
const body = await json(res) as { error: string };
|
| 446 |
+
expect(body.error).toMatch(/solved/i);
|
| 447 |
+
});
|
| 448 |
+
});
|
| 449 |
+
|
| 450 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 451 |
+
// POST /api/chess/submit — DB error paths
|
| 452 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 453 |
+
|
| 454 |
+
describe("POST /api/chess/submit — DB error paths", () => {
|
| 455 |
+
it("returns 404 when user is not found", async () => {
|
| 456 |
+
mockUserFindFirst.mockResolvedValueOnce(null);
|
| 457 |
+
|
| 458 |
+
const res = await POST(makePost({
|
| 459 |
+
puzzleId: "pzl123",
|
| 460 |
+
puzzleRating: 1500,
|
| 461 |
+
solved: true,
|
| 462 |
+
movesPlayed: 3,
|
| 463 |
+
solutionLen: 3,
|
| 464 |
+
}));
|
| 465 |
+
expect(res.status).toBe(404);
|
| 466 |
+
const body = await json(res) as { error: string };
|
| 467 |
+
expect(body.error).toMatch(/user/i);
|
| 468 |
+
});
|
| 469 |
+
|
| 470 |
+
it("returns 500 when chess CategorySkill is missing", async () => {
|
| 471 |
+
mockUserFindFirst.mockResolvedValueOnce(makeUser({ categorySkills: [] }));
|
| 472 |
+
|
| 473 |
+
const res = await POST(makePost({
|
| 474 |
+
puzzleId: "pzl123",
|
| 475 |
+
puzzleRating: 1500,
|
| 476 |
+
solved: true,
|
| 477 |
+
movesPlayed: 3,
|
| 478 |
+
solutionLen: 3,
|
| 479 |
+
}));
|
| 480 |
+
expect(res.status).toBe(500);
|
| 481 |
+
const body = await json(res) as { error: string };
|
| 482 |
+
expect(body.error).toMatch(/CategorySkill/i);
|
| 483 |
+
});
|
| 484 |
+
});
|
| 485 |
+
|
| 486 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 487 |
+
// POST /api/chess/submit — success path: response shape
|
| 488 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 489 |
+
|
| 490 |
+
describe("POST /api/chess/submit — success response shape", () => {
|
| 491 |
+
const defaultBody = {
|
| 492 |
+
puzzleId: "pzl123",
|
| 493 |
+
puzzleRating: 1500,
|
| 494 |
+
solved: true,
|
| 495 |
+
movesPlayed: 3,
|
| 496 |
+
solutionLen: 3,
|
| 497 |
+
};
|
| 498 |
+
|
| 499 |
+
it("returns 200 on success", async () => {
|
| 500 |
+
const res = await POST(makePost(defaultBody));
|
| 501 |
+
expect(res.status).toBe(200);
|
| 502 |
+
});
|
| 503 |
+
|
| 504 |
+
it("response includes solved field matching the input", async () => {
|
| 505 |
+
const res = await POST(makePost(defaultBody));
|
| 506 |
+
const body = await json(res) as { solved: boolean };
|
| 507 |
+
expect(body.solved).toBe(true);
|
| 508 |
+
});
|
| 509 |
+
|
| 510 |
+
it("response includes qualityScore in [0, 1]", async () => {
|
| 511 |
+
const res = await POST(makePost(defaultBody));
|
| 512 |
+
const body = await json(res) as { qualityScore: number };
|
| 513 |
+
expect(body.qualityScore).toBeGreaterThanOrEqual(0);
|
| 514 |
+
expect(body.qualityScore).toBeLessThanOrEqual(1);
|
| 515 |
+
});
|
| 516 |
+
|
| 517 |
+
it("response includes full xp breakdown", async () => {
|
| 518 |
+
const res = await POST(makePost(defaultBody));
|
| 519 |
+
const body = await json(res) as {
|
| 520 |
+
xp: {
|
| 521 |
+
totalXp: number;
|
| 522 |
+
baseXp: number;
|
| 523 |
+
qualityBonus: number;
|
| 524 |
+
multiplierBonus: number;
|
| 525 |
+
multiplierPercent: number;
|
| 526 |
+
isCriticalHit: boolean;
|
| 527 |
+
};
|
| 528 |
+
};
|
| 529 |
+
|
| 530 |
+
expect(typeof body.xp.totalXp).toBe("number");
|
| 531 |
+
expect(typeof body.xp.baseXp).toBe("number");
|
| 532 |
+
expect(typeof body.xp.qualityBonus).toBe("number");
|
| 533 |
+
expect(typeof body.xp.multiplierBonus).toBe("number");
|
| 534 |
+
expect(typeof body.xp.multiplierPercent).toBe("number");
|
| 535 |
+
expect(typeof body.xp.isCriticalHit).toBe("boolean");
|
| 536 |
+
});
|
| 537 |
+
|
| 538 |
+
it("response includes levelUp flag and newLevel", async () => {
|
| 539 |
+
const res = await POST(makePost(defaultBody));
|
| 540 |
+
const body = await json(res) as { levelUp: boolean; newLevel: number };
|
| 541 |
+
expect(typeof body.levelUp).toBe("boolean");
|
| 542 |
+
expect(typeof body.newLevel).toBe("number");
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
+
it("response includes categoryXp breakdown", async () => {
|
| 546 |
+
const res = await POST(makePost(defaultBody));
|
| 547 |
+
const body = await json(res) as {
|
| 548 |
+
categoryXp: {
|
| 549 |
+
currentXp: number;
|
| 550 |
+
xpToNext: number;
|
| 551 |
+
level: number;
|
| 552 |
+
levelUp: boolean;
|
| 553 |
+
};
|
| 554 |
+
};
|
| 555 |
+
expect(typeof body.categoryXp.currentXp).toBe("number");
|
| 556 |
+
expect(typeof body.categoryXp.xpToNext).toBe("number");
|
| 557 |
+
expect(typeof body.categoryXp.level).toBe("number");
|
| 558 |
+
expect(typeof body.categoryXp.levelUp).toBe("boolean");
|
| 559 |
+
});
|
| 560 |
+
|
| 561 |
+
it("response includes unlocks array", async () => {
|
| 562 |
+
const res = await POST(makePost(defaultBody));
|
| 563 |
+
const body = await json(res) as { unlocks: string[] };
|
| 564 |
+
expect(Array.isArray(body.unlocks)).toBe(true);
|
| 565 |
+
});
|
| 566 |
+
});
|
| 567 |
+
|
| 568 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 569 |
+
// POST /api/chess/submit — XP calculations
|
| 570 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 571 |
+
|
| 572 |
+
describe("POST /api/chess/submit — XP calculations", () => {
|
| 573 |
+
it("unsolved puzzle: qualityScore is 0 and qualityBonus is 0", async () => {
|
| 574 |
+
const res = await POST(makePost({
|
| 575 |
+
puzzleId: "pzl123",
|
| 576 |
+
puzzleRating: 1500,
|
| 577 |
+
solved: false,
|
| 578 |
+
movesPlayed: 3,
|
| 579 |
+
solutionLen: 3,
|
| 580 |
+
}));
|
| 581 |
+
const body = await json(res) as { qualityScore: number; xp: { qualityBonus: number } };
|
| 582 |
+
expect(body.qualityScore).toBe(0);
|
| 583 |
+
expect(body.xp.qualityBonus).toBe(0);
|
| 584 |
+
});
|
| 585 |
+
|
| 586 |
+
it("solved puzzle: qualityBonus > 0 for perfect play", async () => {
|
| 587 |
+
const res = await POST(makePost({
|
| 588 |
+
puzzleId: "pzl123",
|
| 589 |
+
puzzleRating: 1500,
|
| 590 |
+
solved: true,
|
| 591 |
+
movesPlayed: 3,
|
| 592 |
+
solutionLen: 3,
|
| 593 |
+
}));
|
| 594 |
+
const body = await json(res) as { xp: { qualityBonus: number } };
|
| 595 |
+
expect(body.xp.qualityBonus).toBeGreaterThan(0);
|
| 596 |
+
});
|
| 597 |
+
|
| 598 |
+
it("critical hit doubles totalXp", async () => {
|
| 599 |
+
mockRollCriticalHit.mockReturnValue(true);
|
| 600 |
+
|
| 601 |
+
const resCrit = await POST(makePost({
|
| 602 |
+
puzzleId: "pzl123",
|
| 603 |
+
puzzleRating: 1500,
|
| 604 |
+
solved: true,
|
| 605 |
+
movesPlayed: 3,
|
| 606 |
+
solutionLen: 3,
|
| 607 |
+
}));
|
| 608 |
+
const bodyCrit = await json(resCrit) as { xp: { totalXp: number; isCriticalHit: boolean } };
|
| 609 |
+
|
| 610 |
+
mockRollCriticalHit.mockReturnValue(false);
|
| 611 |
+
const resNorm = await POST(makePost({
|
| 612 |
+
puzzleId: "pzl123",
|
| 613 |
+
puzzleRating: 1500,
|
| 614 |
+
solved: true,
|
| 615 |
+
movesPlayed: 3,
|
| 616 |
+
solutionLen: 3,
|
| 617 |
+
}));
|
| 618 |
+
const bodyNorm = await json(resNorm) as { xp: { totalXp: number } };
|
| 619 |
+
|
| 620 |
+
expect(bodyCrit.xp.isCriticalHit).toBe(true);
|
| 621 |
+
expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp);
|
| 622 |
+
});
|
| 623 |
+
|
| 624 |
+
it("multiplierPercent is reflected in response xp.multiplierPercent", async () => {
|
| 625 |
+
mockGetMultiplierPercent.mockResolvedValueOnce(25);
|
| 626 |
+
|
| 627 |
+
const res = await POST(makePost({
|
| 628 |
+
puzzleId: "pzl123",
|
| 629 |
+
puzzleRating: 1500,
|
| 630 |
+
solved: true,
|
| 631 |
+
movesPlayed: 3,
|
| 632 |
+
solutionLen: 3,
|
| 633 |
+
}));
|
| 634 |
+
const body = await json(res) as { xp: { multiplierPercent: number; multiplierBonus: number } };
|
| 635 |
+
|
| 636 |
+
expect(body.xp.multiplierPercent).toBe(25);
|
| 637 |
+
expect(body.xp.multiplierBonus).toBeGreaterThan(0);
|
| 638 |
+
});
|
| 639 |
+
|
| 640 |
+
it("multiplierBonus is 0 when multiplierPercent is 0", async () => {
|
| 641 |
+
mockGetMultiplierPercent.mockResolvedValueOnce(0);
|
| 642 |
+
|
| 643 |
+
const res = await POST(makePost({
|
| 644 |
+
puzzleId: "pzl123",
|
| 645 |
+
puzzleRating: 1500,
|
| 646 |
+
solved: true,
|
| 647 |
+
movesPlayed: 3,
|
| 648 |
+
solutionLen: 3,
|
| 649 |
+
}));
|
| 650 |
+
const body = await json(res) as { xp: { multiplierBonus: number } };
|
| 651 |
+
expect(body.xp.multiplierBonus).toBe(0);
|
| 652 |
+
});
|
| 653 |
+
});
|
| 654 |
+
|
| 655 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 656 |
+
// POST /api/chess/submit — DailyLog
|
| 657 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 658 |
+
|
| 659 |
+
describe("POST /api/chess/submit — DailyLog", () => {
|
| 660 |
+
const defaultBody = {
|
| 661 |
+
puzzleId: "pzl123",
|
| 662 |
+
puzzleRating: 1500,
|
| 663 |
+
solved: true,
|
| 664 |
+
movesPlayed: 3,
|
| 665 |
+
solutionLen: 3,
|
| 666 |
+
};
|
| 667 |
+
|
| 668 |
+
it("creates a new DailyLog when none exists for today", async () => {
|
| 669 |
+
mockDailyLogFindFirst.mockResolvedValueOnce(null);
|
| 670 |
+
|
| 671 |
+
await POST(makePost(defaultBody));
|
| 672 |
+
|
| 673 |
+
expect(mockDailyLogCreate).toHaveBeenCalledTimes(1);
|
| 674 |
+
expect(mockDailyLogUpdate).not.toHaveBeenCalled();
|
| 675 |
+
});
|
| 676 |
+
|
| 677 |
+
it("updates the existing DailyLog when one exists for today", async () => {
|
| 678 |
+
mockDailyLogFindFirst.mockResolvedValueOnce({
|
| 679 |
+
id: 99,
|
| 680 |
+
xpEarned: 50,
|
| 681 |
+
activityCount: 2,
|
| 682 |
+
goalMet: false,
|
| 683 |
+
});
|
| 684 |
+
|
| 685 |
+
await POST(makePost(defaultBody));
|
| 686 |
+
|
| 687 |
+
expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1);
|
| 688 |
+
expect(mockDailyLogCreate).not.toHaveBeenCalled();
|
| 689 |
+
});
|
| 690 |
+
|
| 691 |
+
it("sets goalMet=true when accumulated XP reaches dailyGoalXp", async () => {
|
| 692 |
+
// User has dailyGoalXp of 100; give them 95 already earned + ≥5 XP from puzzle
|
| 693 |
+
mockUserFindFirst.mockResolvedValueOnce(makeUser({ dailyGoalXp: 100 }));
|
| 694 |
+
mockDailyLogFindFirst.mockResolvedValueOnce({
|
| 695 |
+
id: 99,
|
| 696 |
+
xpEarned: 95,
|
| 697 |
+
activityCount: 3,
|
| 698 |
+
goalMet: false,
|
| 699 |
+
});
|
| 700 |
+
|
| 701 |
+
await POST(makePost(defaultBody));
|
| 702 |
+
|
| 703 |
+
expect(mockDailyLogUpdate).toHaveBeenCalledWith(
|
| 704 |
+
expect.objectContaining({
|
| 705 |
+
data: expect.objectContaining({ goalMet: true }),
|
| 706 |
+
}),
|
| 707 |
+
);
|
| 708 |
+
});
|
| 709 |
+
});
|
| 710 |
+
|
| 711 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 712 |
+
// POST /api/chess/submit — skill unlocks
|
| 713 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 714 |
+
|
| 715 |
+
describe("POST /api/chess/submit — skill unlocks", () => {
|
| 716 |
+
it("calls processSkillUnlocks when category levels up", async () => {
|
| 717 |
+
// Set chess skill so that adding any XP causes a level-up
|
| 718 |
+
const highXpUser = makeUser({
|
| 719 |
+
categorySkills: [
|
| 720 |
+
{
|
| 721 |
+
id: 10,
|
| 722 |
+
userId: 1,
|
| 723 |
+
category: "chess",
|
| 724 |
+
level: 1,
|
| 725 |
+
totalXp: 90,
|
| 726 |
+
currentXp: 90,
|
| 727 |
+
xpToNext: 10, // 10 XP needed → puzzle awards ≥10 XP → level-up
|
| 728 |
+
},
|
| 729 |
+
],
|
| 730 |
+
});
|
| 731 |
+
mockUserFindFirst.mockResolvedValueOnce(highXpUser);
|
| 732 |
+
|
| 733 |
+
await POST(makePost({
|
| 734 |
+
puzzleId: "pzl123",
|
| 735 |
+
puzzleRating: 1500,
|
| 736 |
+
solved: true,
|
| 737 |
+
movesPlayed: 3,
|
| 738 |
+
solutionLen: 3,
|
| 739 |
+
}));
|
| 740 |
+
|
| 741 |
+
expect(mockProcessSkillUnlocks).toHaveBeenCalledTimes(1);
|
| 742 |
+
expect(mockProcessSkillUnlocks).toHaveBeenCalledWith(
|
| 743 |
+
expect.anything(),
|
| 744 |
+
1,
|
| 745 |
+
"chess",
|
| 746 |
+
expect.any(Number),
|
| 747 |
+
);
|
| 748 |
+
});
|
| 749 |
+
|
| 750 |
+
it("does NOT call processSkillUnlocks when no category level-up occurs", async () => {
|
| 751 |
+
// Chess skill needs 10000 XP to level-up → won't level from one puzzle
|
| 752 |
+
const user = makeUser({
|
| 753 |
+
categorySkills: [
|
| 754 |
+
{
|
| 755 |
+
id: 10,
|
| 756 |
+
userId: 1,
|
| 757 |
+
category: "chess",
|
| 758 |
+
level: 1,
|
| 759 |
+
totalXp: 0,
|
| 760 |
+
currentXp: 0,
|
| 761 |
+
xpToNext: 10_000,
|
| 762 |
+
},
|
| 763 |
+
],
|
| 764 |
+
});
|
| 765 |
+
mockUserFindFirst.mockResolvedValueOnce(user);
|
| 766 |
+
|
| 767 |
+
await POST(makePost({
|
| 768 |
+
puzzleId: "pzl123",
|
| 769 |
+
puzzleRating: 1500,
|
| 770 |
+
solved: true,
|
| 771 |
+
movesPlayed: 3,
|
| 772 |
+
solutionLen: 3,
|
| 773 |
+
}));
|
| 774 |
+
|
| 775 |
+
expect(mockProcessSkillUnlocks).not.toHaveBeenCalled();
|
| 776 |
+
});
|
| 777 |
+
|
| 778 |
+
it("includes unlocks array in response from processSkillUnlocks", async () => {
|
| 779 |
+
const highXpUser = makeUser({
|
| 780 |
+
categorySkills: [
|
| 781 |
+
{
|
| 782 |
+
id: 10,
|
| 783 |
+
userId: 1,
|
| 784 |
+
category: "chess",
|
| 785 |
+
level: 1,
|
| 786 |
+
totalXp: 90,
|
| 787 |
+
currentXp: 90,
|
| 788 |
+
xpToNext: 10,
|
| 789 |
+
},
|
| 790 |
+
],
|
| 791 |
+
});
|
| 792 |
+
mockUserFindFirst.mockResolvedValueOnce(highXpUser);
|
| 793 |
+
mockProcessSkillUnlocks.mockResolvedValueOnce({
|
| 794 |
+
unlocked: ["Tactical Vision", "Endgame Basics"],
|
| 795 |
+
streakFreezesGranted: 1,
|
| 796 |
+
});
|
| 797 |
+
|
| 798 |
+
const res = await POST(makePost({
|
| 799 |
+
puzzleId: "pzl123",
|
| 800 |
+
puzzleRating: 1500,
|
| 801 |
+
solved: true,
|
| 802 |
+
movesPlayed: 3,
|
| 803 |
+
solutionLen: 3,
|
| 804 |
+
}));
|
| 805 |
+
|
| 806 |
+
const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number };
|
| 807 |
+
expect(body.unlocks).toEqual(["Tactical Vision", "Endgame Basics"]);
|
| 808 |
+
expect(body.streakFreezesGranted).toBe(1);
|
| 809 |
+
});
|
| 810 |
+
});
|
| 811 |
+
|
| 812 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 813 |
+
// POST /api/chess/submit — activity persistence
|
| 814 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 815 |
+
|
| 816 |
+
describe("POST /api/chess/submit — activity persistence", () => {
|
| 817 |
+
it("creates an activity record with chess category and puzzle metadata", async () => {
|
| 818 |
+
await POST(makePost({
|
| 819 |
+
puzzleId: "pzl999",
|
| 820 |
+
puzzleRating: 1800,
|
| 821 |
+
solved: true,
|
| 822 |
+
movesPlayed: 4,
|
| 823 |
+
solutionLen: 3,
|
| 824 |
+
}));
|
| 825 |
+
|
| 826 |
+
expect(mockActivityCreate).toHaveBeenCalledTimes(1);
|
| 827 |
+
const callArg = mockActivityCreate.mock.calls[0][0] as {
|
| 828 |
+
data: {
|
| 829 |
+
category: string;
|
| 830 |
+
exerciseType: string;
|
| 831 |
+
description: string;
|
| 832 |
+
score: number;
|
| 833 |
+
metadata: string;
|
| 834 |
+
};
|
| 835 |
+
};
|
| 836 |
+
|
| 837 |
+
expect(callArg.data.category).toBe("chess");
|
| 838 |
+
expect(callArg.data.exerciseType).toBe("puzzle");
|
| 839 |
+
expect(callArg.data.description).toContain("pzl999");
|
| 840 |
+
expect(callArg.data.description).toContain("1800");
|
| 841 |
+
|
| 842 |
+
const metadata = JSON.parse(callArg.data.metadata) as {
|
| 843 |
+
puzzleId: string;
|
| 844 |
+
puzzleRating: number;
|
| 845 |
+
solved: boolean;
|
| 846 |
+
};
|
| 847 |
+
expect(metadata.puzzleId).toBe("pzl999");
|
| 848 |
+
expect(metadata.puzzleRating).toBe(1800);
|
| 849 |
+
expect(metadata.solved).toBe(true);
|
| 850 |
+
});
|
| 851 |
+
});
|
| 852 |
+
|
| 853 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 854 |
+
// POST /api/chess/submit — durationSecs persistence
|
| 855 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 856 |
+
|
| 857 |
+
describe("POST /api/chess/submit — durationSecs", () => {
|
| 858 |
+
const baseBody = {
|
| 859 |
+
puzzleId: "pzl123",
|
| 860 |
+
puzzleRating: 1500,
|
| 861 |
+
solved: true,
|
| 862 |
+
movesPlayed: 3,
|
| 863 |
+
solutionLen: 3,
|
| 864 |
+
};
|
| 865 |
+
|
| 866 |
+
function getActivityData() {
|
| 867 |
+
return (mockActivityCreate.mock.calls[0][0] as { data: Record<string, unknown> }).data;
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
+
it("persists durationSecs when provided", async () => {
|
| 871 |
+
await POST(makePost({ ...baseBody, durationSecs: 90 }));
|
| 872 |
+
expect(getActivityData().durationSecs).toBe(90);
|
| 873 |
+
});
|
| 874 |
+
|
| 875 |
+
it("rounds durationSecs to the nearest integer", async () => {
|
| 876 |
+
await POST(makePost({ ...baseBody, durationSecs: 45.7 }));
|
| 877 |
+
expect(getActivityData().durationSecs).toBe(46);
|
| 878 |
+
});
|
| 879 |
+
|
| 880 |
+
it("stores null when durationSecs is omitted", async () => {
|
| 881 |
+
await POST(makePost(baseBody));
|
| 882 |
+
expect(getActivityData().durationSecs).toBeNull();
|
| 883 |
+
});
|
| 884 |
+
|
| 885 |
+
it("stores null when durationSecs is negative", async () => {
|
| 886 |
+
await POST(makePost({ ...baseBody, durationSecs: -5 }));
|
| 887 |
+
expect(getActivityData().durationSecs).toBeNull();
|
| 888 |
+
});
|
| 889 |
+
|
| 890 |
+
it("persists durationSecs of 0 (instant solve)", async () => {
|
| 891 |
+
await POST(makePost({ ...baseBody, durationSecs: 0 }));
|
| 892 |
+
expect(getActivityData().durationSecs).toBe(0);
|
| 893 |
+
});
|
| 894 |
+
});
|
src/app/api/chess/challenge/route.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* POST /api/chess/challenge
|
| 3 |
+
*
|
| 4 |
+
* Creates a Stockfish bot challenge on Lichess and returns the game URL.
|
| 5 |
+
* The user plays the game externally on Lichess, then reports the result
|
| 6 |
+
* via POST /api/chess/game-result to earn XP.
|
| 7 |
+
*
|
| 8 |
+
* Body:
|
| 9 |
+
* level number — Stockfish level 1 (easiest) → 8 (strongest). Default: 4.
|
| 10 |
+
* userId number — defaults to 1
|
| 11 |
+
*/
|
| 12 |
+
|
| 13 |
+
import { NextRequest, NextResponse } from "next/server";
|
| 14 |
+
import { challengeStockfish } from "@/lib/lichess";
|
| 15 |
+
import { withApiError, ApiError } from "@/lib/api-error";
|
| 16 |
+
|
| 17 |
+
interface ChallengeBody {
|
| 18 |
+
level?: number;
|
| 19 |
+
userId?: number;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
/**
|
| 23 |
+
* Clamps a Stockfish level to the valid range [1, 8], defaulting to 4.
|
| 24 |
+
* Exported for unit testing.
|
| 25 |
+
*/
|
| 26 |
+
export function clampStockfishLevel(level: unknown): number {
|
| 27 |
+
return typeof level === "number"
|
| 28 |
+
? Math.max(1, Math.min(8, Math.round(level)))
|
| 29 |
+
: 4;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export const POST = withApiError(async (request: NextRequest) => {
|
| 33 |
+
let body: ChallengeBody = {};
|
| 34 |
+
try {
|
| 35 |
+
body = await request.json();
|
| 36 |
+
} catch {
|
| 37 |
+
// body is optional — defaults are fine
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
const level = clampStockfishLevel(body.level);
|
| 41 |
+
|
| 42 |
+
if (!process.env.LICHESS_API_TOKEN) {
|
| 43 |
+
throw new ApiError(
|
| 44 |
+
503,
|
| 45 |
+
"LICHESS_API_TOKEN is not configured. Set it in .env to enable Stockfish challenges.",
|
| 46 |
+
);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
const challenge = await challengeStockfish(level);
|
| 50 |
+
|
| 51 |
+
if (!challenge) {
|
| 52 |
+
throw new ApiError(
|
| 53 |
+
502,
|
| 54 |
+
"Failed to create Stockfish challenge on Lichess. Check your API token and try again.",
|
| 55 |
+
);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
return NextResponse.json({
|
| 59 |
+
gameId: challenge.id,
|
| 60 |
+
gameUrl: challenge.url,
|
| 61 |
+
level,
|
| 62 |
+
});
|
| 63 |
+
});
|
src/app/api/chess/game-result/route.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* POST /api/chess/game-result
|
| 3 |
+
*
|
| 4 |
+
* Records the result of a Stockfish bot game and awards XP.
|
| 5 |
+
* The user plays on Lichess and self-reports their result here.
|
| 6 |
+
*
|
| 7 |
+
* XP scale (design doc: 30–60 based on result + opponent strength):
|
| 8 |
+
* - Base XP: 30 (game participation — same as design doc floor)
|
| 9 |
+
* - Quality bonus: up to 30 based on result + level
|
| 10 |
+
* - Win: 0.8 + (level / 8) * 0.2 → quality 0.8–1.0
|
| 11 |
+
* - Draw: 0.5 + (level / 8) * 0.15 → quality 0.5–0.65
|
| 12 |
+
* - Loss: 0.1 + (level / 8) * 0.1 → quality 0.1–0.2
|
| 13 |
+
*
|
| 14 |
+
* Body:
|
| 15 |
+
* gameId string — Lichess game ID (from /api/chess/challenge)
|
| 16 |
+
* level number — Stockfish level 1–8
|
| 17 |
+
* result string — "win" | "draw" | "loss"
|
| 18 |
+
* userId? number — defaults to 1
|
| 19 |
+
*/
|
| 20 |
+
|
| 21 |
+
import { NextRequest, NextResponse } from "next/server";
|
| 22 |
+
import { prisma } from "@/lib/db";
|
| 23 |
+
// import { Prisma } from "@prisma/client";
|
| 24 |
+
import { calculateXpGain, rollCriticalHit } from "@/lib/xp";
|
| 25 |
+
import { checkLevelUp } from "@/lib/progression";
|
| 26 |
+
import { processSkillUnlocks } from "@/lib/skill-unlock";
|
| 27 |
+
import { getMultiplierPercent } from "@/lib/multiplier";
|
| 28 |
+
import { getTitleForLevel } from "@/config/titles";
|
| 29 |
+
import { withApiError, ApiError } from "@/lib/api-error";
|
| 30 |
+
import { processEndOfDay } from "@/lib/streak";
|
| 31 |
+
|
| 32 |
+
export type GameResult = "win" | "draw" | "loss";
|
| 33 |
+
|
| 34 |
+
interface GameResultBody {
|
| 35 |
+
gameId: string;
|
| 36 |
+
level: number;
|
| 37 |
+
result: GameResult;
|
| 38 |
+
userId?: number;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/**
|
| 42 |
+
* Quality score (0–1) based on result and opponent level.
|
| 43 |
+
* Harder opponents → higher quality bonus for the same result.
|
| 44 |
+
*/
|
| 45 |
+
export function calcGameQualityScore(result: GameResult, level: number): number {
|
| 46 |
+
const levelFraction = Math.max(0, Math.min(8, level)) / 8;
|
| 47 |
+
switch (result) {
|
| 48 |
+
case "win":
|
| 49 |
+
return 0.8 + levelFraction * 0.2; // 0.80 – 1.00
|
| 50 |
+
case "draw":
|
| 51 |
+
return 0.5 + levelFraction * 0.15; // 0.50 – 0.65
|
| 52 |
+
case "loss":
|
| 53 |
+
return 0.1 + levelFraction * 0.1; // 0.10 – 0.20
|
| 54 |
+
default:
|
| 55 |
+
return 0;
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
const GAME_BASE_XP = 30;
|
| 60 |
+
const GAME_MAX_QUALITY_BONUS = 30;
|
| 61 |
+
|
| 62 |
+
export const POST = withApiError(async (request: NextRequest) => {
|
| 63 |
+
let body: GameResultBody;
|
| 64 |
+
try {
|
| 65 |
+
body = await request.json();
|
| 66 |
+
} catch {
|
| 67 |
+
throw new ApiError(400, "Invalid JSON body");
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
const { gameId, level, result } = body;
|
| 71 |
+
|
| 72 |
+
if (!gameId || typeof gameId !== "string") {
|
| 73 |
+
throw new ApiError(400, "gameId is required");
|
| 74 |
+
}
|
| 75 |
+
if (typeof level !== "number" || level < 1 || level > 8) {
|
| 76 |
+
throw new ApiError(400, "level must be a number between 1 and 8");
|
| 77 |
+
}
|
| 78 |
+
if (!["win", "draw", "loss"].includes(result)) {
|
| 79 |
+
throw new ApiError(400, "result must be 'win', 'draw', or 'loss'");
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
const userId = body.userId ?? 1;
|
| 83 |
+
|
| 84 |
+
// --- Fetch user ---
|
| 85 |
+
const user = await prisma.user.findFirst({
|
| 86 |
+
where: { id: userId },
|
| 87 |
+
include: { categorySkills: { where: { category: "chess" } } },
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
if (!user) {
|
| 91 |
+
throw new ApiError(404, "No user found");
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
const chessSkill = user.categorySkills[0];
|
| 95 |
+
if (!chessSkill) {
|
| 96 |
+
throw new ApiError(500, "Chess CategorySkill not found");
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
// --- XP calculation ---
|
| 100 |
+
const qualityScore = calcGameQualityScore(result, level);
|
| 101 |
+
const isCriticalHit = rollCriticalHit();
|
| 102 |
+
const multiplierPercent = await getMultiplierPercent(prisma, userId, "chess");
|
| 103 |
+
|
| 104 |
+
const xpResult = calculateXpGain({
|
| 105 |
+
baseXp: GAME_BASE_XP,
|
| 106 |
+
qualityScore,
|
| 107 |
+
maxQualityBonus: GAME_MAX_QUALITY_BONUS,
|
| 108 |
+
isCriticalHit,
|
| 109 |
+
multiplierPercent,
|
| 110 |
+
});
|
| 111 |
+
|
| 112 |
+
// --- Level-up checks ---
|
| 113 |
+
const userLevelResult = checkLevelUp({
|
| 114 |
+
currentXp: user.currentXp + xpResult.totalXp,
|
| 115 |
+
xpToNextLevel: user.xpToNextLevel,
|
| 116 |
+
level: user.level,
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
const categoryLevelResult = checkLevelUp({
|
| 120 |
+
currentXp: chessSkill.currentXp + xpResult.totalXp,
|
| 121 |
+
xpToNextLevel: chessSkill.xpToNext,
|
| 122 |
+
level: chessSkill.level,
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
// --- Title progression ---
|
| 126 |
+
const newTitle = getTitleForLevel(userLevelResult.newLevel);
|
| 127 |
+
const titleChanged = newTitle !== user.title;
|
| 128 |
+
|
| 129 |
+
// --- Streak processing (idempotent — no-op if already run today) ---
|
| 130 |
+
await processEndOfDay(userId);
|
| 131 |
+
|
| 132 |
+
// --- Daily log bookkeeping ---
|
| 133 |
+
const now = new Date();
|
| 134 |
+
const todayStart = new Date(
|
| 135 |
+
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()),
|
| 136 |
+
);
|
| 137 |
+
const tomorrowStart = new Date(todayStart.getTime() + 86_400_000);
|
| 138 |
+
|
| 139 |
+
const existingLog = await prisma.dailyLog.findFirst({
|
| 140 |
+
where: { userId, date: { gte: todayStart, lt: tomorrowStart } },
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp;
|
| 144 |
+
const newActivityCount = (existingLog?.activityCount ?? 0) + 1;
|
| 145 |
+
const goalMet = newXpEarned >= user.dailyGoalXp;
|
| 146 |
+
|
| 147 |
+
// --- Persist ---
|
| 148 |
+
let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 };
|
| 149 |
+
await prisma.$transaction(async (tx) => {
|
| 150 |
+
await tx.activity.create({
|
| 151 |
+
data: {
|
| 152 |
+
userId,
|
| 153 |
+
category: "chess",
|
| 154 |
+
exerciseType: "bot-game",
|
| 155 |
+
description: `Stockfish Lv.${level} — ${result}`,
|
| 156 |
+
baseXp: xpResult.baseXp,
|
| 157 |
+
qualityBonus: xpResult.qualityBonus,
|
| 158 |
+
isCriticalHit: xpResult.isCriticalHit,
|
| 159 |
+
totalXp: xpResult.totalXp,
|
| 160 |
+
score: qualityScore,
|
| 161 |
+
metadata: JSON.stringify({
|
| 162 |
+
gameId,
|
| 163 |
+
level,
|
| 164 |
+
result,
|
| 165 |
+
gameUrl: `https://lichess.org/${gameId}`,
|
| 166 |
+
}),
|
| 167 |
+
},
|
| 168 |
+
});
|
| 169 |
+
|
| 170 |
+
await tx.user.update({
|
| 171 |
+
where: { id: userId },
|
| 172 |
+
data: {
|
| 173 |
+
totalXp: user.totalXp + xpResult.totalXp,
|
| 174 |
+
currentXp: userLevelResult.remainingXp,
|
| 175 |
+
xpToNextLevel: userLevelResult.newXpToNextLevel,
|
| 176 |
+
level: userLevelResult.newLevel,
|
| 177 |
+
...(titleChanged && { title: newTitle }),
|
| 178 |
+
},
|
| 179 |
+
});
|
| 180 |
+
|
| 181 |
+
await tx.categorySkill.update({
|
| 182 |
+
where: { id: chessSkill.id },
|
| 183 |
+
data: {
|
| 184 |
+
totalXp: chessSkill.totalXp + xpResult.totalXp,
|
| 185 |
+
currentXp: categoryLevelResult.remainingXp,
|
| 186 |
+
xpToNext: categoryLevelResult.newXpToNextLevel,
|
| 187 |
+
level: categoryLevelResult.newLevel,
|
| 188 |
+
},
|
| 189 |
+
});
|
| 190 |
+
|
| 191 |
+
if (categoryLevelResult.levelsGained > 0) {
|
| 192 |
+
unlockResult = await processSkillUnlocks(
|
| 193 |
+
tx, userId, "chess", categoryLevelResult.newLevel,
|
| 194 |
+
);
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
if (existingLog) {
|
| 198 |
+
await tx.dailyLog.update({
|
| 199 |
+
where: { id: existingLog.id },
|
| 200 |
+
data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet },
|
| 201 |
+
});
|
| 202 |
+
} else {
|
| 203 |
+
await tx.dailyLog.create({
|
| 204 |
+
data: {
|
| 205 |
+
userId,
|
| 206 |
+
date: todayStart,
|
| 207 |
+
xpEarned: newXpEarned,
|
| 208 |
+
activityCount: newActivityCount,
|
| 209 |
+
goalMet,
|
| 210 |
+
},
|
| 211 |
+
});
|
| 212 |
+
}
|
| 213 |
+
});
|
| 214 |
+
|
| 215 |
+
return NextResponse.json({
|
| 216 |
+
result,
|
| 217 |
+
level,
|
| 218 |
+
qualityScore: Math.round(qualityScore * 100) / 100,
|
| 219 |
+
xp: {
|
| 220 |
+
totalXp: xpResult.totalXp,
|
| 221 |
+
baseXp: xpResult.baseXp,
|
| 222 |
+
qualityBonus: xpResult.qualityBonus,
|
| 223 |
+
multiplierBonus: xpResult.multiplierBonus,
|
| 224 |
+
multiplierPercent,
|
| 225 |
+
isCriticalHit: xpResult.isCriticalHit,
|
| 226 |
+
},
|
| 227 |
+
levelUp: userLevelResult.levelsGained > 0,
|
| 228 |
+
newLevel: userLevelResult.newLevel,
|
| 229 |
+
categoryXp: {
|
| 230 |
+
currentXp: categoryLevelResult.remainingXp,
|
| 231 |
+
xpToNext: categoryLevelResult.newXpToNextLevel,
|
| 232 |
+
level: categoryLevelResult.newLevel,
|
| 233 |
+
levelUp: categoryLevelResult.levelsGained > 0,
|
| 234 |
+
},
|
| 235 |
+
newTitle: titleChanged ? newTitle : undefined,
|
| 236 |
+
unlocks: unlockResult.unlocked,
|
| 237 |
+
streakFreezesGranted: unlockResult.streakFreezesGranted,
|
| 238 |
+
});
|
| 239 |
+
});
|