From 4875723f009a105fd9864b14537191764ec147e9 Mon Sep 17 00:00:00 2001 From: prathamkashyap Date: Sun, 4 Oct 2026 18:44:20 +0530 Subject: [PATCH] Align documentation with current implementation --- README.md | 376 +++++++++++++++++++++++--------------- docs/KNOWN_LIMITATIONS.md | 161 +++++++++++----- 2 files changed, 347 insertions(+), 190 deletions(-) diff --git a/README.md b/README.md index 09a44a8..bf3c52c 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,27 @@
-

πŸ›οΈ AthenaeumAI

-

AI-powered adaptive learning platform

-

Generates quizzes, flashcards, analytics, and tutoring experiences from uploaded study material.

+

AthenaeumAI

+

Adaptive learning platform built on your own study material

+

Ingest material, generate grounded assessments, record attempts, track mastery and forgetting, and schedule revision from what you actually got wrong.


[![Node.js](https://img.shields.io/badge/Node.js-20+-339933?logo=nodedotjs&logoColor=white)](https://nodejs.org/) [![React](https://img.shields.io/badge/React-18-61DAFB?logo=react&logoColor=black)](https://react.dev/) - [![MongoDB](https://img.shields.io/badge/MongoDB-Replica_Set-47A248?logo=mongodb&logoColor=white)](https://www.mongodb.com/) + [![MongoDB](https://img.shields.io/badge/MongoDB-Atlas-47A248?logo=mongodb&logoColor=white)](https://www.mongodb.com/atlas/) [![Redis](https://img.shields.io/badge/Redis-BullMQ-DC382D?logo=redis&logoColor=white)](https://redis.io/) - [![Docker](https://img.shields.io/badge/Docker-Compose-2496ED?logo=docker&logoColor=white)](https://docs.docker.com/compose/) - [![GitHub Release](https://img.shields.io/github/v/release/prathamkashyap/AthenaeumAI?color=blue&logo=github)](https://github.com/prathamkashyap/AthenaeumAI/releases) + [![Docker](https://img.shields.io/badge/Docker-Compose-2496ED?logo=docker&logoColor=white)](https://docs.docker.com/compose/) [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
--- -## Why AthenaeumAI? +## What AthenaeumAI does Most quiz generators are stateless β€” they produce questions and forget. -AthenaeumAI is different. It **remembers what you got wrong**, calculates how your knowledge is decaying over time, and surfaces the exact topics you need to review before they fade. It uses spaced repetition algorithms, an AI tutor grounded strictly in your uploaded material, and an asynchronous processing pipeline that handles everything from PDF parsing to mistake analysis in the background. +AthenaeumAI records what you answered, derives a per-topic mastery and confidence state from those records, decays that state as time passes, and schedules revision from the topics you have not yet proved you know. The LLM writes questions and explanations. It does **not** compute mastery, confidence, decay or the review schedule β€” those are deterministic calculations over stored attempts, and the distinction is maintained deliberately. -The result is a platform that adapts to how you actually learn, not just what you study. +The retrieval that grounds the tutor is a **lexical baseline, not semantic search**. See [Retrieval](#retrieval-what-the-tutor-actually-searches) for exactly what it does and does not do. --- @@ -34,45 +33,115 @@ graph TB UI[React + Vite + TailwindCSS] end - subgraph API["Express API Server"] - Auth[JWT Authentication] - QE[Quiz Engine] - Tutor[AI Tutor] - FC[Flashcard Service] - Analytics[Analytics Engine] - Rec[Recommendation Engine] + subgraph API["Express API (one process in production)"] + Auth[JWT auth + refresh rotation] + QE[Quiz generation] + Tutor[Grounded tutor] + FC[SM-2 flashcards] + Analytics[Analytics] + Rec[Recommendations] end - subgraph Background["BullMQ Worker"] - IDX[Material Indexing] - SYNC[Attempt Sync] - RBQ[Review Queue Rebuild] - MA[Mistake Analysis] + subgraph Worker["BullMQ consumer (same process in production)"] + IDX[INDEX_MATERIAL] + SYNC[SYNC_ATTEMPT] + RBQ[REBUILD_REVIEW_QUEUE] end subgraph Storage - Mongo[(MongoDB Replica Set)] + Mongo[(MongoDB)] Redis[(Redis)] end subgraph External - Groq[Groq API β€” Llama 3.3 70B] + Groq[Groq API] end UI -->|REST| Auth Auth --> QE & Tutor & FC & Analytics & Rec QE & Tutor -->|LLM| Groq - QE & Analytics -->|enqueue| Redis - Redis -->|dequeue| IDX & SYNC & RBQ & MA - IDX & SYNC & RBQ & MA -->|read/write| Mongo + QE -->|enqueue INDEX_MATERIAL| Redis + Analytics -->|enqueue SYNC_ATTEMPT| Redis + Redis --> IDX & SYNC & RBQ + IDX & SYNC & RBQ -->|read/write| Mongo QE & Tutor & FC & Analytics & Rec -->|read/write| Mongo ``` +Mistake analysis, spaced-repetition scheduling and every mastery calculation run **inline in the request**, not in the queue. Only two jobs are enqueued by the API today: `INDEX_MATERIAL` after a quiz is generated, and `SYNC_ATTEMPT` after an attempt is recorded. `REBUILD_REVIEW_QUEUE` is handled by the worker but is not currently triggered by any route. + +--- + +## Synchronous vs background + +This is the distinction most worth stating precisely, because "asynchronous pipeline" is easy to overclaim. + +**Synchronous, inside the HTTP request:** + +| Operation | Where | +| :--- | :--- | +| Quiz generation β€” the provider calls | `quizController.js` β†’ `aiQuizService.generateQuiz` | +| Mistake analysis for incorrect answers | `quizController.js` β†’ `mistakeAnalysisService` | +| SM-2 scheduling, analytics, recommendations, review-queue reads | services, on-request | +| Tutor answer (non-streaming and SSE) | `tutorController.js` | + +**Background, via BullMQ:** + +| Job | Enqueued by | Does | +| :--- | :--- | :--- | +| `INDEX_MATERIAL` | `POST /quiz/generate`, after commit | chunk and index material for retrieval | +| `SYNC_ATTEMPT` | `POST /quiz/:id/attempt`, after commit | apply learner effects: mastery, confidence, events, mistake analysis records | +| `REBUILD_REVIEW_QUEUE` | worker-supported, no current route trigger | recompute the review queue | + +Two consequences worth knowing: + +- **Quiz generation is a synchronous request that can take minutes.** It is not queued. See [Known production limitation](#known-production-limitation-reasoning-model-latency). +- **Durable work is committed before its job is scheduled.** If Redis is unavailable at that point the business write has already succeeded. The response is still truthful β€” it carries `backgroundProcessing: { "status": "not_scheduled", ... }` β€” but the background work genuinely has not run, and nothing re-enqueues it automatically. `INDEX_MATERIAL` self-heals on read; `SYNC_ATTEMPT` is retryable by the client via `POST /api/v1/jobs/:id/retry`. Details in [`docs/KNOWN_LIMITATIONS.md`](docs/KNOWN_LIMITATIONS.md). + --- -## Screenshots +## The learning loop -> Screenshots will be added after deployment. To preview, run `docker compose up --build` and visit `http://localhost:8080`. +The adaptive behaviour is **deterministic and rule-based**, not a trained personalisation model. Given the same attempts it produces the same state. + +1. **Attempt recorded** β€” the attempt is persisted first, with a durable per-attempt claim so a redelivered `SYNC_ATTEMPT` applies its effects exactly once. +2. **Learner effects applied** β€” `SYNC_ATTEMPT` updates `UserProgress` per topic: mastery from accuracy, confidence from a weighted blend of accuracy, recency and existing confidence (`progressService.js`: `0.5Β·accuracy + 0.3Β·recency + 0.2Β·confidence`). +3. **Decay applied** β€” per-topic retention decays exponentially with time since last practice: `100 Β· e^(βˆ’elapsedDays / 21)` (`progressService.js`). The dashboard's aggregate `retentionScore` uses a separate linear penalty; these are two different figures and are not the same number. +4. **Weakness ranked** β€” a topic's weakness score is `0.55Β·mastery + 0.3Β·confidence + 0.15Β·(100 βˆ’ weaknessDrag)`, which re-ranks the review queue (`recommendationService.js`). +5. **Review scheduled** β€” flashcards follow SM-2 with ease-factor clamping and a 6-day second interval (`flashcardService.js`); failed questions become review items scoped to the attempt. + +Achievements are rule-based too. Nothing on the dashboard or profile is inferred or predicted. + +--- + +## Retrieval: what the tutor actually searches + +Stated plainly, because "RAG" would overstate it. + +The shipped retriever is `local-hash-v1` (`backend/services/embeddingService.js`): + +- Tokenise, drop stop words, hash each token with **FNV-1a** into one of 384 dimensions with a sign bit, and L2-normalise. +- Score by **cosine similarity** between the query vector and each chunk vector. +- Blend with a lexical keyword-overlap score: `0.78 Β· vector + 0.22 Β· lexical`. + +Every component is lexical. There is no learned embedding model, no sentence transformer and no vector database β€” two texts using different wording for the same concept can score near zero. That is a deliberate baseline that is measured and documented, not an oversight. + +A full **BM25** implementation exists in `backend/services/bm25Retriever.js`, but it is imported only by its own tests. It is an evaluation candidate, not the active retriever. + +The tutor additionally gates on evidence **before** calling the model: if retrieval returns nothing, or every score is exactly zero, it refuses rather than answering ungrounded. That gate detects *absent* evidence only β€” it cannot detect a confidently-retrieved wrong chunk, and the measured score ranges show why no numeric threshold could. See [`docs/KNOWN_LIMITATIONS.md`](docs/KNOWN_LIMITATIONS.md). + +The tutor has **no conversational memory**. Each query retrieves fresh and answers from retrieved context alone. `GET /api/v1/tutor/history` returns an audit log of past interactions (topic, question, result, timestamp) reconstructed from `LearningEvent` records β€” it is a history of what was asked, not a transcript the model can recall. + +--- + +## Where the LLM is actually used + +| Used for | Not used for | +| :--- | :--- | +| Writing questions, options, explanations and difficulty | Scoring answers β€” the stored selection is the record | +| Tutor answers, constrained to retrieved context | Deciding whether retrieval was good enough | +| Mistake diagnosis text | Any mastery, confidence, decay or scheduling number | + +The provider is resolved per call. The model is `process.env.GROQ_MODEL || "openai/gpt-oss-120b"` (`groqProvider.js`) β€” configurable by environment variable precisely so a provider-side model retirement is a config change rather than a code change. The previous hard-coded default was retired by Groq and returned 404 `model_not_found` on every AI feature; it is named only in the source comment recording that incident. --- @@ -80,136 +149,95 @@ graph TB | Category | Feature | Description | | :--- | :--- | :--- | -| **PDF Processing** | Knowledge Extraction | Parses uploaded PDFs, chunks text, and indexes material for retrieval | -| **Quiz Generation** | Adaptive Difficulty | Generates quizzes using Llama 3.3 70B with configurable difficulty levels | -| **Spaced Repetition** | SM-2 Flashcards | Implements the SM-2 algorithm with ease factor clamping and interval scheduling | -| **Analytics** | Decay-Aware Tracking | Calculates per-topic retention scores using exponential decay over time | -| **AI Tutor** | RAG-Grounded Chat | Conversational tutor that answers strictly from uploaded study material | -| **Recommendations** | Weak Topic Surfacing | Automatically re-ranks the review queue based on weakness and confidence | -| **Background Jobs** | BullMQ Pipeline | Material indexing, attempt sync, and mistake analysis run asynchronously | -| **Authentication** | JWT + HttpOnly | Secure token-based auth with refresh token rotation | +| **PDF processing** | Material ingest | Extracts text, chunks at 1800 chars with 260 overlap, indexes for lexical retrieval | +| **Quiz generation** | Grounded generation | Questions written from uploaded text, with explanations and per-question topics | +| **Attempts** | Durable recording | Attempts persisted before effects are applied, with an idempotent claim | +| **Mastery** | Per-topic state | Mastery, confidence and exponentially decayed retention computed from real attempts | +| **Spaced repetition** | SM-2 flashcards | Ease-factor scheduling with interval progression | +| **Review queue** | Failure-driven | Overdue flashcards, failed questions and weak topics, ranked by weakness | +| **Analytics** | Attempt-derived | Accuracy trends, weak topics, mastery and readiness | +| **AI tutor** | Grounded answers | Lexical retrieval plus a pre-model evidence gate; SSE streaming available | +| **Achievements** | Rule-based | Unlocked from recorded events, never inferred | +| **Auth** | JWT + httpOnly rotation | Access token plus rotated refresh token in an httpOnly cookie | +| **Public site** | Marketing page | `/` is public; the workspace is `/dashboard` | --- -## Tech Stack +## Tech stack -**Frontend** β€” React 18, TypeScript, Vite, TailwindCSS, shadcn/ui, TanStack Query, React Router +**Frontend** β€” React 18, TypeScript 5.8, Vite 5, TailwindCSS 3, shadcn/ui, TanStack Query 5, React Router 6, Lucide -**Backend** β€” Node.js 20+, Express 5, MongoDB (Mongoose 9 with transactions), Redis, BullMQ, Zod validation +**Backend** β€” Node.js 20+, Express 5, Mongoose 9 (transactions), MongoDB, Redis via ioredis, BullMQ 5, Zod 4, Winston -**AI** β€” Groq API (Llama 3.3 70B), RAG retrieval, streaming tutor responses +**AI** β€” Groq (`openai/gpt-oss-120b` by default, `GROQ_MODEL`-overridable), lexical retrieval, optional SSE streaming -**Infrastructure** β€” Docker Compose, Winston logging, OpenAPI/Swagger, GitHub Actions CI +**Infrastructure** β€” Docker Compose, GitHub Actions CI, Vitest, Jest, Playwright, OpenAPI/Swagger --- -## Folder Structure +## Folder structure ```text . β”œβ”€β”€ backend/ -β”‚ β”œβ”€β”€ config/ # Database, environment validation (Zod) -β”‚ β”œβ”€β”€ controllers/ # Route handlers -β”‚ β”œβ”€β”€ middleware/ # Auth, error handling, rate limiting, validation +β”‚ β”œβ”€β”€ config/ # database, Zod environment validation +β”‚ β”œβ”€β”€ controllers/ # route handlers +β”‚ β”œβ”€β”€ middleware/ # auth, error handling, rate limiting, validation β”‚ β”œβ”€β”€ models/ # Mongoose schemas (12 models) β”‚ β”œβ”€β”€ routes/ # Express route definitions -β”‚ β”œβ”€β”€ services/ # Business logic, AI, analytics, recommendations -β”‚ β”œβ”€β”€ utils/ # BullMQ queue, logger, transactions, errors -β”‚ β”œβ”€β”€ tests/ # Jest unit + integration tests -β”‚ β”œβ”€β”€ worker.js # Dedicated BullMQ consumer process -β”‚ └── server.js # HTTP entry point +β”‚ β”œβ”€β”€ services/ # business logic, AI, retrieval, analytics, recommendations +β”‚ β”œβ”€β”€ utils/ # BullMQ queue, logger, transactions, PDF parsing, chunking +β”‚ β”œβ”€β”€ tests/ # Jest unit + integration +β”‚ β”œβ”€β”€ worker.js # BullMQ consumer +β”‚ β”œβ”€β”€ main.js # combined server + worker entry (production) +β”‚ └── server.js # HTTP-only entry β”œβ”€β”€ src/ -β”‚ β”œβ”€β”€ components/ # shadcn/ui + custom components -β”‚ β”œβ”€β”€ context/ # Auth + Quiz context providers -β”‚ β”œβ”€β”€ lib/ # API client utilities -β”‚ └── pages/ # Lazy-loaded route views -β”œβ”€β”€ docs/ # Architecture, ADRs, API reference -β”œβ”€β”€ tests/ # Playwright E2E tests -β”œβ”€β”€ docker-compose.yml # Full-stack orchestration -└── .github/workflows/ # CI pipeline -``` - ---- - -## System Design - -### Quiz Generation Pipeline - -```mermaid -sequenceDiagram - participant U as User - participant API as Express API - participant LLM as Groq Llama 3.3 - participant DB as MongoDB - participant Q as BullMQ - participant W as Worker - - U->>API: Upload PDF - API->>DB: Save StudyMaterial - API->>Q: Enqueue INDEX_MATERIAL - API-->>U: 202 Accepted - W->>Q: Dequeue job - W->>DB: Create MaterialChunks - - U->>API: Generate Quiz - API->>DB: Load material text - API->>LLM: Generate questions - LLM-->>API: Structured JSON - API->>DB: Save Quiz (transaction) - API-->>U: Quiz payload +β”‚ β”œβ”€β”€ components/ # app shell, landing page, shadcn/ui +β”‚ β”œβ”€β”€ context/ # auth + quiz providers +β”‚ β”œβ”€β”€ lib/ # API client, theme, topic identity, public copy +β”‚ └── pages/ # route views +β”œβ”€β”€ docs/ # architecture, ADRs, API reference, evaluations +β”œβ”€β”€ tests/e2e/ # Playwright +β”œβ”€β”€ render.yaml # Blueprint for the deployed topology +β”œβ”€β”€ docker-compose.yml # full local stack +└── .github/workflows/ # CI ``` -### Adaptive Learning Pipeline - -1. **Attempt Submission** β€” User answers are validated and the attempt is persisted first; the learner effects it implies are then applied by a background job inside a Mongoose transaction, guarded by a durable per-attempt claim so a redelivery applies them once. -2. **Background Sync** β€” A BullMQ job updates `UserProgress` per-topic mastery, records `LearningEvents`, and triggers mistake analysis for incorrect answers. -3. **Decay Calculation** β€” The analytics engine applies exponential decay to per-topic confidence based on time since last practice. -4. **Review Queue** β€” The recommendation service re-ranks topics by weakness score and populates the review queue with overdue flashcards and low-confidence topics. - -### AI Tutor Pipeline - -The tutor is strictly RAG-grounded to prevent hallucination: -1. The user's query is combined with their session history. -2. The embedding service retrieves relevant chunks from the uploaded material. -3. A constrained system prompt instructs the LLM to answer **only** from the provided context. - --- ## Installation ### Prerequisites + - Node.js v20+ - Docker & Docker Compose -- [Groq API Key](https://console.groq.com/) +- [Groq API key](https://console.groq.com/) -### Docker (Recommended) +### Docker (recommended) ```bash git clone https://github.com/prathamkashyap/AthenaeumAI.git cd AthenaeumAI -# Configure environment cp backend/.env.example backend/.env -# Edit backend/.env with your GROQ_API_KEY and JWT_SECRET +# Edit backend/.env with GROQ_API_KEY and JWT_SECRET -# Start all services docker compose up --build -d ``` -Frontend: `http://localhost:8080` Β· API: `http://localhost:5000` Β· Swagger: `http://localhost:5000/api-docs` +Frontend `http://localhost:8080` Β· API `http://localhost:5000` Β· Swagger `http://localhost:5000/api-docs` -### Local Development +Compose runs MongoDB as a single-node replica set, which is required β€” see [transaction support](#transactions-require-a-replica-set). + +### Local development ```bash -# Install dependencies npm install && cd backend && npm install && cd .. -# Start MongoDB replica set and Redis locally, then: - # Terminal 1 β€” API server cd backend && npm run dev -# Terminal 2 β€” Background worker +# Terminal 2 β€” background worker cd backend && node worker.js # Terminal 3 β€” Frontend @@ -218,73 +246,125 @@ npm run dev --- -## Environment Variables +## Environment variables + +Validated by Zod at startup in [`backend/config/env.js`](backend/config/env.js). | Variable | Required | Description | | :--- | :---: | :--- | -| `NODE_ENV` | βœ“ | `development` or `production` | -| `PORT` | | API port (default `5000`) | -| `MONGODB_URI` | βœ“ | Replica set connection string | -| `REDIS_HOST` | | Redis hostname (default `localhost`) | -| `REDIS_PORT` | | Redis port (default `6379`) | -| `JWT_SECRET` | βœ“ | 256-bit secret for token signing | | `GROQ_API_KEY` | βœ“ | Groq API access token | -| `FRONTEND_URL` | βœ“ | Allowed CORS origin | +| `MONGODB_URI` | βœ“ | MongoDB connection string; must reach a replica set or sharded cluster | +| `JWT_SECRET` | βœ“ | Secret for token signing | +| `NODE_ENV` | | `development` \| `production` \| `test` (default `development`) | +| `PORT` | | API port (default `5000`) | +| `GROQ_MODEL` | | Override the generation model (default `openai/gpt-oss-120b`) | +| `REDIS_URL` | | Managed Redis connection string; takes precedence over host/port | +| `ALLOWED_ORIGINS` | production | Comma-separated CORS allowlist; **required** in production | -See [`backend/config/env.js`](backend/config/env.js) for Zod validation schema. +In production an empty `ALLOWED_ORIGINS` allows no browser origin at all. --- ## Testing +Measured on `main` (`9bc6029`). Every figure below is from an actual run. + ```bash -# Frontend unit tests (Vitest) +# Frontend unit tests (Vitest) β€” 374 tests across 29 files npm test -# Backend unit tests (Jest) β€” 118 tests across 6 suites +# Backend unit tests (Jest) β€” 942 tests across 36 suites cd backend && npm run test:unit -# Backend integration tests (requires MongoDB + Redis) +# Backend integration tests β€” 101 passed, 13 skipped +# requires MongoDB + Redis; runs serially cd backend && npm run test:integration -# E2E tests (Playwright) +# E2E tests (Playwright) β€” 26 passed, 2 skipped npm run test:e2e -# Backend syntax check -cd backend && npm run build +# Typecheck, lint, build +npm run typecheck +npm run lint +npm run build ``` +| Suite | Result | +| :--- | :--- | +| Frontend (Vitest) | 374 passed / 29 files | +| Backend unit (Jest) | 942 passed / 36 suites | +| Backend integration (Jest) | 101 passed, 13 skipped / 114 total | +| Browser E2E (Playwright) | 26 passed, 2 skipped | +| `typecheck` Β· `lint` Β· `build` | pass | + +The 13 skipped integration tests and 2 skipped E2E tests are gated behind opt-in flags (`E2E_REAL_QUEUE` and similar) that require live infrastructure; they skip loudly rather than passing without having proved anything. + --- ## Deployment -The repository ships with production-ready Dockerfiles: +### Production topology + +Deployed on **Render free tiers only** β€” no paid plan, no card. Defined in [`render.yaml`](render.yaml): + +| Component | Plan | Detail | +| :--- | :--- | :--- | +| `athenaeum-frontend` | free static site | `npm run build`, serves `./dist`, `VITE_API_ROOT` set at build time | +| `athenaeum-api` | free web service | `npm run start:combined` β†’ `node main.js` | +| `athenaeum-redis` | free Key Value | BullMQ backing store | +| MongoDB | Atlas **M0** | free shared cluster | + +`main.js` starts the HTTP server **and** the BullMQ consumer in one process, so the queue is drained without a second service. `autoDeployTrigger` is `off` on both services: **a merge does not deploy.** Redeploy deliberately. + +### Docker images + +- **Frontend** β€” Vite build served by Nginx +- **Backend** β€” Node Alpine image; `server.js` for HTTP-only, `main.js` for combined, `worker.js` for worker-only -- **Frontend** β€” Vite build served via Nginx (`Dockerfile`) -- **Backend** β€” Node Alpine image for the API server (`backend/Dockerfile`) -- **Worker** β€” Same backend image running `worker.js` as an independent container +### Transactions require a replica set -Recommended production stack: -- **MongoDB** β†’ Atlas (M10+ with replica set) -- **Redis** β†’ Upstash or ElastiCache -- **Backend + Worker** β†’ Railway, Render, or AWS ECS -- **Frontend** β†’ Vercel or AWS Amplify +`POST /quiz/generate` writes material and quiz in one transaction, and `SYNC_ATTEMPT` claims the attempt and applies learner effects in one transaction. A standalone `mongod` cannot do this. The deployment is probed at connect time via `hello` and reports `transactions: supported | unsupported | unknown` on `GET /api/v1/health`; transaction-backed paths refuse with `503` rather than silently degrading. Atlas M0 and the Compose replica set both satisfy this. + +### Known production limitation: reasoning-model latency + +Every model currently reachable on the configured Groq key is a **reasoning** model, so it spends part of its token budget reasoning before answering. Measured end to end, a five-question quiz takes **117–244s**. The tutor is unaffected in practice (~7s). + +Generation is synchronous and makes up to three sequential provider calls (first, middle and last chunk of the extracted text). Each individual call is bounded by a 30s completion timeout (`AI_COMPLETION_TIMEOUT_MS`), so no single call trips it β€” the wall-clock is the sum. This is a real user-visible wait on the primary action. It is recorded in [`docs/DEPLOYMENT.md`](docs/DEPLOYMENT.md) and is the first roadmap item. --- ## Roadmap -- [x] PDF upload and parsing -- [x] AI quiz generation with quality filtering -- [x] Adaptive difficulty and per-topic mastery -- [x] SM-2 spaced repetition flashcards -- [x] Analytics dashboard with decay-aware retention -- [x] AI tutor with RAG grounding -- [x] BullMQ background processing with reliability hardening -- [x] Docker Compose orchestration -- [x] CI pipeline (GitHub Actions) -- [ ] **Phase 6:** Sentence Transformer embeddings + Qdrant vector search -- [ ] **Phase 7:** Hybrid retrieval with cross-encoder reranking +### Shipped + +- [x] PDF upload, parsing and lexical indexing +- [x] Grounded quiz generation with quality filtering +- [x] Per-topic mastery, confidence and exponential decay from real attempts +- [x] SM-2 spaced-repetition flashcards +- [x] Review queue ranked by weakness, with attempt-scoped snooze +- [x] Analytics dashboard and recommendations +- [x] Grounded tutor with a pre-model evidence gate and optional SSE streaming +- [x] BullMQ background processing with tracked job status, durable claims and client retry +- [x] Rule-based achievements, truthful empty states +- [x] Public landing page, consolidated brand identity, SEO metadata +- [x] Docker Compose orchestration and free-tier Render deployment +- [x] CI pipeline (GitHub Actions) gating typecheck, lint, build, unit, integration and E2E + +### Deferred β€” not implemented + +- [ ] **Generation latency.** Streaming or partially-generated quizzes, so the first questions are usable before the last is written. +- [ ] **Semantic retrieval.** Sentence-transformer embeddings plus a vector store, replacing `local-hash-v1`. Deferred deliberately: the lexical baseline is measured first (see [`docs/RETRIEVAL_EVALUATION.md`](docs/RETRIEVAL_EVALUATION.md)) so any change is justified by evidence of a plateau rather than by assumption. BM25 is implemented and available for that comparison. +- [ ] **Hybrid retrieval with cross-encoder reranking.** Depends on the above. +- [ ] **Transactional outbox and HTTP idempotency keys** for background-work scheduling. +- [ ] **Automatic terminal-job recovery** β€” reconciliation instead of user-triggered retry. +- [ ] **Security, observability and performance hardening** as a documented contract: rate-limit and payload budgets per route, structured audit logging, latency and error instrumentation, and load testing. None of this is in place today. +- [ ] **Tutor conversational memory**, if product value justifies the persistence cost. + +--- + +## Known limitations + +[`docs/KNOWN_LIMITATIONS.md`](docs/KNOWN_LIMITATIONS.md) is the authoritative list. In brief: lexical retrieval with no semantic matching, reasoning-model generation latency, a grounding gate that detects absent rather than wrong evidence, background work committed before it is scheduled, no HTTP idempotency on attempt submission, topic-item snoozes that a rebuild resets, and the flashcard `due_flashcard` ↔ `overdue_review` identity boundary. --- diff --git a/docs/KNOWN_LIMITATIONS.md b/docs/KNOWN_LIMITATIONS.md index e6f48ff..53e5db3 100644 --- a/docs/KNOWN_LIMITATIONS.md +++ b/docs/KNOWN_LIMITATIONS.md @@ -1,79 +1,156 @@ # Known Limitations -This document lists the architectural limitations of the current AthenaeumAI platform. These items serve as key triggers for downstream sprints. +This document records the boundaries of the current AthenaeumAI platform: what it does not do yet, and where a deliberate design decision is carrying a known cost. ---- +These are **limitations and deferred work, not defects in the shipped system**. Where something is deferred on purpose, the reasoning is given rather than implied. Where a claim was measured rather than assumed, the measurement is stated so it can be re-checked. -## πŸ” Local Hash Vector Representation -- **Limitation**: The current embedding pipeline (`local-hash-v1`) relies on deterministic lexical hashes. -- **Impact**: It lacks semantic understanding (e.g., matching "process states" to "PCB layout" if wording is dissimilar). RAG results may exclude relevant chunks if there is zero keyword overlap. +Everything below was verified against the code on `main` (`9bc6029`) during the documentation truth pass. --- -## ⚑ Synchronous Document Indexing -- **Limitation**: PDF text parsing, chunking, hashing, and database writes execute synchronously within the Express route lifecycle. -- **Impact**: Heavy PDF uploads can cause HTTP request timeouts (e.g. if the PDF is 50+ pages) and degrade performance for concurrent users. +## Summary + +| Area | Status | +| :--- | :--- | +| Retrieval semantics | Lexical baseline by design; semantic retrieval deferred pending evidence | +| Generation latency | Real user-visible wait; first roadmap item | +| Grounding gate | Detects absent evidence, not wrong evidence; measured, no viable threshold | +| Background scheduling | Committed before enqueued; truthful response, no automatic recovery | +| Attempt idempotency | No HTTP-level key; duplicate submission possible | +| Snooze durability | Preserved for failed questions, deliberately not for topic items | +| Review queue identity | `due_flashcard` ↔ `overdue_review` crossing can duplicate a card | +| Tutor memory | Interaction audit log only; no conversational context | +| Transactions | Require a replica set; probed and refused explicitly otherwise | +| Theme control | Public routes honour the stored theme but expose no toggle | +| Security / observability / performance | Post-launch contract work, not yet started | --- -## βš™οΈ Lack of Background Task Runners -- **Limitation**: Tasks like rebuilding the review queue, updating streaks, and calculating recommendation snapshots run in-process on Express routes. -- **Impact**: Server execution paths are blocked, leading to performance variance. There is no job retry or crash-handling queue. +## Retrieval is a lexical baseline + +- **What ships**: `local-hash-v1`. Text is tokenised, stop words removed, each token hashed with FNV-1a into one of 384 dimensions with a sign bit, L2-normalised, and compared by cosine similarity. The result is blended with a lexical keyword-overlap score at `0.78 Β· vector + 0.22 Β· lexical`. +- **Limitation**: every component is lexical. There is no learned embedding model and no vector database, so semantically equivalent phrasings with low keyword overlap score near zero. A question about "process states" will not reliably retrieve a chunk that only says "PCB layout". +- **Why it is still here**: the baseline is measured before it is replaced. `docs/RETRIEVAL_EVALUATION.md` records the evaluation that justifies the current retriever, and `bm25Retriever.js` exists as a comparison arm β€” it is imported only by tests and is **not** the active retriever. +- **What would change it**: sentence-transformer embeddings plus a vector store, adopted on evidence that the lexical baseline has plateaued, not on the assumption that embeddings are better in general. --- -## 🧠 Limited Tutor Context Memory -- **Limitation**: The RAG tutoring pipeline only injects prior misconceptions and immediate material chunks. -- **Impact**: There is no long-term chat session window memory. Subsequent user queries do not inherit conversational history. +## Generation latency on the current reasoning model + +- **What ships**: `POST /quiz/generate` is **synchronous**. It calls the provider inline and returns the finished quiz. It is not queued. +- **Limitation**: every model currently reachable on the configured Groq key is a reasoning model, so it spends part of its token budget reasoning before answering. Measured end to end, a five-question quiz takes **117–244s**. This is a real wait on the primary user action. +- **Scope of the timeout**: `AI_COMPLETION_TIMEOUT_MS` is `30_000` and is applied **per provider call**. Generation issues up to three sequential calls (first, middle and last chunk of the extracted text), so no single call trips the timeout while the total is minutes. The tutor is unaffected in practice (~7s). +- **What would change it**: streaming or partially-generated quizzes, so earlier questions are usable while later ones are still being written. --- -## πŸ›‘οΈ The Tutor Grounding Gate Detects Absent Evidence, Not Wrong Evidence -- **Limitation**: `tutorGrounding.js` makes an explicit grounding decision before the model is called, and refuses when retrieval produced **no evidence at all** β€” an empty result set, or a set in which every score is exactly zero. It cannot detect a *confidently retrieved wrong chunk*. -- **Why there is no numeric confidence threshold**: this was measured rather than assumed. Across three independent query sets over the frozen evaluation corpus, the production retriever's top-1 score for a query whose answer was **not** retrieved falls **entirely inside** the range of the top-1 score for a query whose answer **was** retrieved: +## The grounding gate detects absent evidence, not wrong evidence + +- **What ships**: `tutorGrounding.js` makes an explicit grounding decision **before** the model is called, and refuses when retrieval produced no evidence at all β€” an empty result set, or one in which every score is exactly zero. +- **Limitation**: it cannot detect a *confidently retrieved wrong chunk*. A question about the wrong topic can still be answered, still cited, and still be wrong, and it passes this gate. +- **Why there is no numeric confidence threshold**: this was measured, not assumed. Across three independent query sets over the frozen evaluation corpus, the production retriever's top-1 score for a query whose answer was **not** retrieved falls entirely inside the range for a query whose answer **was** retrieved: | Top-1 combined score | Range | | --- | --- | | Correct answer retrieved | 0.168 – 0.611 | | Wrong answer retrieved | 0.136 – 0.507 | - Sweeping every threshold from 0.00 to 0.65 in steps of 0.01, **no value both rejects every wrong case and keeps every correct one**. The highest threshold that rejects all wrong cases discards 20 of 37 correct ones. Lexical coverage and the top-1-minus-top-2 margin overlap the same way. A constant such as `0.35` would not be a calibration: it would reject most correctly-answered questions *and* still admit confidently-ranked wrong chunks, converting a visible failure into a silent one. -- **Impact**: the gate prevents the tutor from claiming to be grounded when it retrieved nothing, and it does so in code rather than by asking the model to use judgement. It does **not** raise answer quality on questions where retrieval returns a plausible-looking but wrong chunk. A question about the wrong topic can still be answered, still cited, and still be wrong β€” and it will pass this gate. -- **What would actually close it**: a retriever whose scores separate correct from incorrect retrieval, which the current one demonstrably does not; or a verification step after generation. The retrieval evaluation is the evidence for both claims. + Sweeping every threshold from 0.00 to 0.65 in steps of 0.01, **no value both rejects every wrong case and keeps every correct one**. The highest threshold rejecting all wrong cases discards 20 of 37 correct ones. Lexical coverage and the top-1-minus-top-2 margin overlap the same way. A constant such as `0.35` would not be a calibration: it would reject most correctly-answered questions *and* still admit confidently-ranked wrong chunks, converting a visible failure into a silent one. +- **What the gate is worth**: it prevents the tutor claiming to be grounded when it retrieved nothing, in code rather than by asking the model to use judgement. It does not raise answer quality where retrieval returns a plausible-but-wrong chunk. +- **What would actually close it**: a retriever whose scores separate correct from incorrect retrieval, which this one demonstrably does not; or a verification step after generation. --- -## πŸ“¬ Background Work Can Be Committed To But Unscheduled -- **Limitation**: Durable application state is written and committed *before* its background job is scheduled. `POST /quiz/generate` commits the material and quiz, then enqueues `INDEX_MATERIAL`; `POST /quiz/:id/attempt` writes the attempt, then enqueues `SYNC_ATTEMPT`. If Redis is unavailable at that point, the commit has already succeeded and cannot be undone. -- **Current behaviour**: Since `829a226`/`Make queue failures truthful after commit`, a scheduling failure is no longer reported as a failure of the business operation. The endpoint returns **200** with its normal success payload plus an additive field: +## Background work can be committed to but unscheduled + +- **What ships**: durable state is written and committed **before** its background job is scheduled. `POST /quiz/generate` commits material and quiz, then enqueues `INDEX_MATERIAL`; `POST /quiz/:id/attempt` writes the attempt, then enqueues `SYNC_ATTEMPT`. +- **Current behaviour**: a scheduling failure is no longer reported as a failure of the business operation. The endpoint returns **200** with its normal payload plus an additive field: + ```json "backgroundProcessing": { "status": "not_scheduled", "task": "INDEX_MATERIAL" } ``` - The success path is unchanged and carries no such field. Genuine failures before the commit β€” a database write, a missing quiz, an unavailable database, or any non-queue fault while scheduling β€” are still reported as failures. -- **Impact**: The response is truthful, but the background work genuinely has not run. Material indexing for an unscheduled job still recovers on read, and an unscheduled `SYNC_ATTEMPT` can now be re-run on demand by its owner (see the next section), but **neither happens automatically**: there is no transactional outbox, no automatic rescheduling, no reconciliation pass, and no HTTP idempotency key. -- **Known residual risk**: because there is no request-level idempotency, a client that retries after a scheduling failure will create a *second* quiz or a *second* attempt. `SYNC_ATTEMPT` remains safe against duplicate *processing* (`829a226` durable claim on `QuizAttempt._id`), but it cannot prevent duplicate *submission*. Closing this needs the explicit job-status/idempotency contract, not a change to the queue. + + The success path carries no such field. Genuine failures before the commit β€” a database write, a missing quiz, an unavailable database, or any non-queue fault while scheduling β€” are still reported as failures. +- **Limitation**: the response is truthful, but the background work genuinely has not run. `INDEX_MATERIAL` self-heals on read through `ensureChunksForUser`, and an unscheduled `SYNC_ATTEMPT` can be re-run on demand, but **neither happens automatically**: there is no transactional outbox, no automatic rescheduling, and no reconciliation pass. +- **Job status is tracked, terminal recovery is manual**: background work already asynchronous is recorded in a `BackgroundJob` document, readable at `GET /api/v1/jobs/:id` scoped to the authenticated learner, with states `pending β†’ queued β†’ running β†’ completed | failed` plus `not_scheduled`. `POST /api/v1/jobs/:id/retry` re-runs a terminal `SYNC_ATTEMPT` for its owner, rebuilding the payload from the stored job and reusing the same durable claim, so a still-pending attempt applies exactly once and an already-applied attempt applies nothing further. The record is deliberately **not** created inside the business transaction and is not an outbox β€” a row written after the business row has committed cannot be rolled back with it. Retention is a 30-day TTL on `completedAt`, so an unresolved job is retained indefinitely rather than silently dropped, and a job that has aged out can no longer be retried by id. +- **A `BackgroundJob` describes background processing only.** It is never evidence that a `StudyMaterial`, `Quiz` or `QuizAttempt` exists, and it is not the correctness boundary for `SYNC_ATTEMPT` β€” the durable claim on `QuizAttempt.sync` inside the business transaction is. + +--- + +## No HTTP-level idempotency on attempt submission + +- **Limitation**: there is no idempotency key on `POST /quiz/:id/attempt`. A client that retries after a scheduling failure, a timeout or a double tap will create a **second** attempt. +- **What does protect against this**: `SYNC_ATTEMPT` is safe against duplicate *processing*. A durable claim on `QuizAttempt._id`, taken inside the business transaction, means a redelivered job applies learner effects exactly once. +- **Consequence**: duplicate *submission* is still possible. The guarantee is on processing, not on submission. +- **What would close it**: an explicit idempotency-key contract on the write endpoints, paired with the transactional outbox above. Not a change to the queue. + +--- + +## Topic-item snoozes are reset by a review-queue rebuild + +- **What ships**: `POST /api/v1/review-queue/:id/snooze` is a single atomic `findOneAndUpdate` β€” there is no read-then-write window. +- **Limitation**: durability differs by item type, deliberately. A `failed_question` item's `dueAt` is protected during a rebuild by `$max`/`$min` inside the same write, so the later date wins and a snooze survives a replay. A **topic** item's `dueAt` (`weak_topic`, `low_confidence_topic`) is recomputed from learner progress on every rebuild and **is overwritten**, so a topic snooze does not survive one. +- **Why**: a topic's due date is derived from current progress, so letting a stale snooze pin it would freeze a schedule that should track the learner. Only a failed question is snoozed by the learner and has no scheduler behind it. +- **What would change it**: a per-item snooze that survives recomputation β€” for example storing the snooze separately from the derived `dueAt` β€” if product behaviour ever requires topic snoozes to be durable. + +--- + +## `due_flashcard` ↔ `overdue_review` can duplicate a flashcard + +- **What ships**: on rebuild, a flashcard's `itemType` is computed from how overdue it is β€” `overdue_review` at one day or more, otherwise `due_flashcard`. `itemType` is part of both the upsert filter and the unique index. +- **Limitation**: when a card crosses the one-day boundary its computed `itemType` changes, so the rebuild's identifying lookup no longer matches the existing row and **inserts a second one**. The service contains no delete or cleanup of superseded rows, so the previously-inserted `due_flashcard` row remains. A single card can therefore appear twice in the review queue β€” once stale under the old type, once current under the new. +- **Scope**: affects the queue only. The card's own SM-2 schedule in `FlashcardSet` is unaffected, and the two rows refer to the same `source.flashcardId`. +- **What would close it**: derive the item type from something stable rather than from a moving threshold β€” for example keying the row on the card and storing "overdue" as a computed property β€” or reconciling superseded rows on rebuild. --- -## πŸ”Ž Background Job Status Is Tracked; Terminal Recovery Is Manual -- **What now exists**: background work that was already asynchronous (`INDEX_MATERIAL`, `SYNC_ATTEMPT`) is recorded in a `BackgroundJob` document and readable at `GET /api/v1/jobs/:id`, scoped to the authenticated learner. States are `pending β†’ queued β†’ running β†’ completed | failed`, plus `not_scheduled` when the queue refused the work. A client can therefore tell the difference between work that is genuinely running and work that never started. -- **Ordering**: the job record is created *after* the business record is committed and *before* the enqueue is attempted, so a job is never reported as `queued` when Redis refused it. The record is deliberately **not** created inside the business transaction and **is not** a transactional outbox. The reason is this ordering, not a deployment limitation: both provisioned topologies are transaction-capable (`docker-compose.yml` runs `mongod --replSet rs0`, and CI initializes a single-node `rs0`), but a record written after the business row has committed cannot be rolled back with it. -- **Separation of state**: a `BackgroundJob` describes background processing only. It is never evidence that a `StudyMaterial`, `Quiz` or `QuizAttempt` exists, and it is not the correctness boundary for `SYNC_ATTEMPT` β€” the durable claim on `QuizAttempt.sync` inside the business transaction remains that boundary. -- **Retry added**: the record is no longer only visible. `POST /api/v1/jobs/:id/retry` re-runs a terminal `SYNC_ATTEMPT` for its owner. It is scoped by user, accepts no resource identifiers from the caller (the payload is rebuilt from the stored job), and retries the *existing* `BackgroundJob` record rather than creating a second tracking row. The retry reuses the same durable claim, so re-running a still-pending attempt applies it exactly once and re-running an already-applied attempt applies nothing further. The result page offers this as a primary action for `failed` and `not_scheduled`. -- **Still missing**: recovery is **user-triggered, not automatic**. Nothing re-enqueues a terminal job on its own, there is no reconciliation pass, and no outbox would recover a job whose process died between the commit and the enqueue. `INDEX_MATERIAL` is deliberately not retryable here β€” it self-heals on read through `ensureChunksForUser` β€” and `REBUILD_REVIEW_QUEUE` is recomputable and carries no `BackgroundJob` record at all. Retention is a 30-day TTL on `completedAt`, so a job that never resolves is retained indefinitely rather than silently dropped, and a job that has already aged out can no longer be retried by id. -- **Residual risk unchanged**: client-driven duplicate submission is still possible, because there is no HTTP idempotency key. +## Tutor has no conversational memory + +- **What ships**: each tutor query retrieves fresh and answers from retrieved context alone. `tutorService.js` holds no message history and no turn window. +- **`GET /api/v1/tutor/history` is not session memory.** It reconstructs an audit log from `LearningEvent` records with `eventType: "ai_tutoring_interaction"`, returning topic, question, result and timestamp. It records what was asked; the model cannot recall it. Follow-up questions do not inherit earlier turns. +- **Limitation**: a learner must restate context that a conversational product would carry forward. +- **What would change it**: persisting turns and injecting a bounded window, if the product value justifies the storage and the grounding cost of a longer prompt. --- -## 🧱 Transaction-Capable MongoDB Is Required -- **Limitation**: multi-document transactions need a replica set or a sharded cluster. A plain standalone `mongod` cannot run them, whatever the connection string says. -- **Why it is mandatory**: `POST /api/v1/quiz/generate` writes the `StudyMaterial` and its `Quiz` inside one transaction, and `SYNC_ATTEMPT` claims the attempt and applies the learner effects in one transaction so the durable claim and its effects commit together or not at all. Those guarantees do not survive being written without the transaction, so there is deliberately no fallback path. -- **Detection**: the connected deployment is asked what it is, at `connectDB` time, by running `hello` and reading `setName` (replica set) or `msg: "isdbgrid"` (sharded cluster). The answer is never inferred from the URI, because a URI can carry `?replicaSet=rs0` while the server behind it is a standalone. It is reported as `supported`, `unsupported` or `unknown`; `unknown` means unprobed, not incapable, so an inconclusive probe never disables transaction paths. -- **Behaviour on a standalone deployment**: the transaction-backed operations are refused with a `503` `DatabaseError` before a session is opened, and `GET /api/v1/health` reports `degraded` with `database.transactions: "unsupported"`. `GET /api/v1/health/ready` still returns `200 ready`, because every path that does not need a transaction remains usable and the worker depends on that endpoint; the capability is disclosed alongside `ready` so the two are not confused. Before this was explicit, the caller instead saw HTTP 500 with *"This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string"* β€” advice that does not work, since `retryWrites=false` does not make a standalone server able to transact. -- **Supported deployment**: the `docker-compose.yml` stack runs MongoDB as a single-node replica set (`rs0`, initialised by the `mongo-init` service), so the intended deployment satisfies this. A developer running a bare `mongod` on `27017` cannot generate a quiz or sync attempts. +## Transactions require a replica set or sharded cluster + +- **Limitation**: multi-document transactions need a replica set or a sharded cluster. A standalone `mongod` cannot run them whatever the connection string says. +- **Why it is mandatory**: `POST /quiz/generate` writes `StudyMaterial` and its `Quiz` in one transaction, and `SYNC_ATTEMPT` claims the attempt and applies learner effects in one transaction so the durable claim and its effects commit together or not at all. Those guarantees do not survive being written without the transaction, so there is deliberately no fallback path. +- **Detection**: the connected deployment is asked what it is, at `connectDB` time, by running `hello` and reading `setName` or `msg: "isdbgrid"`. The answer is never inferred from the URI, because a URI can carry `?replicaSet=rs0` while the server behind it is standalone. It is reported as `supported`, `unsupported` or `unknown`; `unknown` means unprobed, not incapable, so an inconclusive probe never disables transaction paths. +- **Behaviour on a standalone deployment**: transaction-backed operations refuse with a `503` `DatabaseError` before a session is opened, and `GET /api/v1/health` reports `degraded` with `database.transactions: "unsupported"`. `GET /api/v1/health/ready` still returns `200 ready`, because every path that does not need a transaction stays usable and the worker depends on that endpoint; the capability is disclosed alongside `ready` so the two are not confused. +- **Satisfied by**: the Compose stack runs MongoDB as a single-node replica set (`rs0`), and production uses Atlas M0, which supports transactions. --- -## πŸ’Ύ Single Instance MongoDB Dependency -- **Limitation**: System operations assume a single-instance MongoDB connection. -- **Impact**: If MongoDB fails, crucial parts of the application (e.g. signup, login, dashboard retrieval, attempts saving) degrade. +## Theme control is not exposed on public routes + +- **What ships**: the persisted theme preference is applied at application boot, before the first render, on **every** route β€” the landing page, `/auth` and `/dashboard` all honour `athenaeum-theme`. The value, storage key, cycle order and normalisation of a stale stored value are unchanged, and this is centralised in one module rather than duplicated. +- **Limitation**: the landing page and auth screen expose **no theme toggle**. Switching remains available in the authenticated shell. A visitor who arrives on a public route with no prior preference stays on the default until they sign in. +- **This is not an initialisation defect.** Theme initialisation on public routes was fixed; the remaining gap is only the absence of a control on those two surfaces. +- **Why it is minor**: the public routes are a marketing and entry surface, the preference is honoured wherever the user has expressed one, and adding a second toggle control is a design decision rather than a correctness fix. + +--- + +## Single-instance MongoDB dependency + +- **Limitation**: system operations assume a single-instance MongoDB connection. +- **Impact**: if MongoDB is unavailable, signup, login, dashboard retrieval and attempt saving degrade together. There is no partial-availability design, because the transaction-dependent paths have no non-transactional fallback by intent. + +--- + +## Security, observability and performance are not yet a contract + +- **Status**: post-launch roadmap work, **not implemented**. Stated here so it is not mistaken for a completed capability. +- **Not yet in place**: per-route rate-limit and payload budgets as a documented contract; structured audit logging beyond Winston request logs; latency and error instrumentation with dashboards; load testing and capacity limits; alerting. +- **What does exist today**: rate limiting on auth and AI routes, Zod validation on request bodies and params, Helmet-style security headers, a CORS allowlist that is required in production, hashed refresh tokens with rotation and reuse detection, and job status scoped to the authenticated owner. +- **What would change it**: agreeing and writing down the contract first, then implementing against it. + +--- + +## Not limitations β€” deliberate decisions, recorded so they are not mistaken for gaps + +- **`REBUILD_REVIEW_QUEUE` has no route trigger.** The worker handles it and it is exercised in tests, but no controller currently enqueues it. The review queue is otherwise built and read synchronously on demand. +- **Mistake analysis runs inline.** It is part of the attempt request, not a background job, and is not slow enough to need queueing. +- **Achievements are rule-based.** They unlock from recorded events rather than being inferred, so the profile can show a truthful empty state instead of a flattering score. +- **`BM25` is implemented but inactive.** It exists as an evaluation arm for a future retrieval decision and is imported only by tests.