Margins, a study app that makes you try before it helps
Margins plans a student’s days to the exam from their own course files. The student answers first, only unassisted answers count as mastery, and the server keeps the tutor from giving the answer away.
- Context
- Personal project, 2025–26
- Read
- 12 min
- Updated
- Built with
- TypeScript, Next.js, Python, FastAPI, PostgreSQL, pgvector, Claude API, Deepgram, Railway
My part
I did the design, built both services and the learner model, ran the evaluation and made every decision. It’s a solo project.
Margins is live at studymargins.com (opens in a new tab), free with a Google sign-in, and the code (opens in a new tab) is MIT-licensed on GitHub.
What it does
A student uploads lecture notes, book chapters and old exams. Margins proposes a course plan of units and topics, each tied to the pages that teach it, and the student edits it before anything is generated. They give an exam date and the minutes they have each day, and Margins lays out every day until the exam.
Each topic is a path of five steps. The AI writes the questions, grades the answers, finds the first wrong step and plans the days, and at every step the student has to answer before it helps. Everything is built from the student’s own files, so every question, explanation and answer points back to a page they can open.

| Step | The student | Margins |
|---|---|---|
| Warm‑up | Answers a few questions before reading, and misses some | Writes the questions and marks the passages worth focusing on |
| Read | Reads their own pages and answers short checks between sections | Adds margin notes and links each page to the original file |
| Recall | Writes what they remember, with the book closed | Grades each idea, quotes the student’s own words back and points at what is missing without giving it |
| Practice | Solves a problem one step at a time | Checks each step and offers hints in three kinds, each saying what it costs, only after an attempt |
| Quiz | Answers and says how sure they are | Grades on the server, with partial credit on short answers |
Why the student tries first
Reading a clear summary feels like learning and mostly isn’t. In a 2025 PNAS experiment (opens in a new tab), students with a plain chatbot scored 48% higher on practice problems and 17% lower on a later exam taken without it. A tutor that held back the solution raised practice scores by 127% and left exam scores level with the control group. Students in both AI groups thought they had learned more than they had.
In Margins the student does the effortful part and the AI does the work around it, down to the smallest hint that gets the student unstuck. I enforce the try-first order in code, because a prompt alone can’t hold it: in a study of an AI tutor (opens in a new tab) that beat in-class teaching, the platform had to control the order of the help. Here the server holds the tutor’s hint level, every reply is checked for the answer before the student sees it, and the model has no say in whether an answer counts as unassisted.
How it works
Margins runs as two services on Railway, a web service and an AI service, and keeps its data in Postgres and an uploads bucket.
The services and stores
Request path
- Browser (third‑party)
- HTTPSWeb service, Next.js:
- Interface and Google sign‑in (I built this)
- API routes and the job queue (I built this)
- Evidence log and learner model (I built this)
- Voice turn loop (I built this)
- private networkAI service, FastAPI:
- Parsing, chunking, embeddings (I built this)
- Generation and grading (I built this)
- Tutor, Ask chat and answer‑leak check (I built this)
- Claude API: a model per purpose (third‑party)
Speech
- Browser microphone: the browser’s own recognizer is the fallback (third‑party)
- short‑lived token: Deepgram Nova‑3: the web service mints the token for each session, so no API key reaches the page (third‑party)
Storage
- Postgres with pgvector: The AI service writes chunks, vectors, the knowledge graph, question sets and the spend ledger. The web service writes the evidence log and the learner model. (third‑party)
- Uploads bucket: The web service streams the original files in. The AI service downloads them to process. (third‑party)
Only the web service faces the browser, only the AI service calls Claude, and microphone audio never passes through either.
I builtThird‑party
Each service writes only its own tables. The knowledge graph is each topic’s concepts and how they depend on each other, and the learner model, computed from one evidence event per answer, is Margins’ record of what the student knows. A grading bug can’t corrupt it, and I can rebuild it from the events without calling a model.
From an upload to the next thing to study
Files to topics
- Person: The student uploads files (I built this)
- Streamed into the bucket: size and type checked on the way in; 25 MB each (I built this)
- Read and split into chunks: about 350 tokens, split at headings (I built this)
- Embedded in the service: 384 dimensions, no API cost (I built this)
- Person: Units and topics proposed, then edited (I built this)
Topic to schedule
- Concepts and claims extracted: when a topic is first opened (I built this)
- Person: The student works the path: warm‑up, read, recall, practice, quiz (I built this)
- Each answer becomes an evidence event: with an assistance level (I built this)
- Memory replayed per concept: FSRS, a spaced‑repetition scheduler (I built this)
- Next activity, plan, reviews and map (I built this)
Steps marked Person are the student’s.
A person decides
From files to a knowledge graph
The AI service reads each upload as markdown, splits it into chunks that keep their heading path and pages, and embeds them in-process with bge-small-en-v1.5 into a pgvector HNSW index. No student text leaves the service to be embedded.
A topic is taught from at most 24 chunks, found by vector similarity plus Postgres full-text search and merged with reciprocal rank fusion. Generators see only those chunks, which keeps the prompt the same size as a course grows, and the shared excerpt block is prompt-cached across generators.
The first version scored every keyword match a flat 0.8, which made about half the results tie and come back in document order. Fusing ranks fixed that: over 38 topics from three OpenStax chapters (about 300 chunks), recall rose from 0.935 to 0.989, on the same topics retrieval was tuned on.
When a topic is first opened, an extraction job returns 3 to 8 concepts, each with two to five claims quoted from the source, and drops any quote that isn’t a verbatim substring of its chunk. Edges between concepts (needs, covers, easy to mix up with) carry a confidence, and cycles are broken. On 8 topics from two MIT OpenCourseWare courses, 149 of 149 claim quotes were found in their chunk, every topic had 3 to 8 concepts (5.9 on average) and an acyclic graph, and 155 of 155 generated items carried valid concept tags.
Generation runs when a topic is opened and never blocks the path: reading needs no AI and a student starts at once, and a warm-up that isn’t ready is skipped. An earlier version generated a whole course up front, which spent $4.13 on 7 topics and used up the day’s budget. One topic’s six content types (concepts, warm-up, notes, worked examples, practice problems and a quiz) cost $0.928 in the latest run.
An event-sourced learner model
Every answer, from every screen, goes through one function that appends an evidence event: the concept, the score, the student’s confidence and an assistance level, which the screen sets and the model never does. Level 0 is a closed-book first try, level 1 is a failed first try, level 2 is an answer after being shown the material, and level 3 is an answer the AI carried. Only levels 0 and 1 update memory and mastery.
Memory is one FSRS card per concept. FSRS is an open spaced-repetition scheduler: it sets each review for just before the student would forget. The card’s state is a pure function of the event log, so after a regrade, a rejected graph edge or a bug fix I delete the affected events, insert the corrected ones and replay. If I updated memory in place, each of those would need a migration.
Reviews count once per concept per local day, which stops a quiz, a practice set and a review on one afternoon from tripling a card’s stability. Writes for one student and concept take a Postgres advisory lock, in sorted order to avoid deadlock. Without it, under the default isolation level, two concurrent writers could each replay without the other’s event and the later commit would drop one.
Mastery, from one concept’s evidence
Example: a perfect first session, on the day its review falls due: Mastery is the lower of 1.0 and 0.5, times 0.9, which is 0.45: Getting there.
Assisted answers don’t count toward any of the three terms, and one sitting can’t lift the cap.
| Label | When a concept has it |
|---|---|
| Not started | There is no evidence on the concept. |
| Inferred | A concept that builds on it was passed, and it has no answer of its own. |
| Shaky | Mastery is under 0.4, or every answer so far was assisted. |
| Getting there | Mastery is 0.4 or more and under 0.8. |
| Solid | Mastery is 0.8 or more, which takes an unassisted success on a new question on a later day. |
| Fading | The scores would make it solid, and retrievability has dropped under 0.7 until a review succeeds. |
Three right answers in one sitting don’t read as learned, because the session cap and the later-day rule both hold the label under solid. A pass also credits the concepts it builds on, and a miss brings forward the review of the concepts that depend on it.
Trying first and then getting help never scores worse than asking for help first: each question has one first-try record, and later hints or a worked example only set flags. If the scale gave credit for help, students would ask before trying.
| Option | Why not, or why |
|---|---|
| A card per question, as in Anki | Questions are generated and varied, and a student rarely sees the same one twice. Per‑question cards would repeat questions or never build a history. |
| One review schedule per topic | Too coarse. One weak idea in a six‑idea topic either drags the whole topic into review or hides in the average. |
| Elo, item response theory or knowledge tracing | These fit a difficulty to each question from many students’ answers. A course belongs to one student, so each generated question is answered by one person and its difficulty never gathers evidence. |
| One FSRS card per concept, replayed from an event log Shipped | A question tests a concept, so the card belongs to the concept. A fresh question is a harder test than a repeated card, which makes retrievability a little optimistic. Students also see their unassisted accuracy, which would show the gap. |
The study path and the plan
One pure function reads a topic’s state and returns the next activity with a reason, and the topic page, the plan and the Continue card all call it. It checks in a fixed order: repairs first (a concept that needs teaching after a failed try, then a wrong idea to fix), then warm-up, reading and recall, then a due review, and last practice or a quiz.
Teaching comes before re-testing: a failed first try is followed by pointers, the explainer or a worked example before the same idea is asked again. An earlier version made a failed concept due again at once, so review re-asked it immediately and a struggling student looped.
The plan places new topics in prerequisite order, with a quiz the next day, spaced reviews, a mock exam after each unit and two full mocks before the date. The daily minutes are a hard cap, and a mock exam longer than that gets a day to itself. Review sessions mix up to 12 questions across topics (interleaving) and ask a fresh question after a miss.
A tutor that holds the answer back
The practice tutor works up a ladder of hints, from “what have you tried” to locating the problem, naming the idea and showing the general form. The server holds the rung (the current hint level), because when the level is left to the prompt and a student asks “just tell me” five times, the model slides up the ladder.
One tutor reply: the server sets the hint level, then checks the draft
The server sets the level
- Person: The student attempts a step or asks for help (I built this)
- Hint level raised by at most one: a pure function on the server; the model is told which level it may use (I built this)
- First wrong step found: the numbers in the student’s working against the authored step answers (I built this)
- The model drafts a reply: capped at 80 words and one question (I built this)
The server checks the draft
- Leak check: a string and number match, then a Haiku judge (I built this)
- leaks: Written again once: 18.0% of replies (I built this)
- leaks again: Authored hint for that level sent instead: 2.9% of replies (I built this)
- What the student saw: 0 of 172 replies gave the answer away (I built this)
A draft that passes the check goes straight to the student. The rewrite and the authored hint run only when a draft leaks, and the shares are from the passing run of 172 replies.
A person decides
The tutor is handed the first wrong step as a fact: a deterministic function returns the first mismatch. A leak is a reply that gives away the answer, and the judge looks for it in a rearranged form, in the problem’s numbers plugged into a formula, and in a worked example that reuses those numbers.
Ask is the chat where a student questions their course material. A small model sorts each message into lookup, logistics, understand, solve or check, and each intent has its own prompt. A lookup gets a direct, cited answer. An understand question is first met with a question about what the student thinks. A solve request never gets the student’s own problem solved: its worked example uses different numbers and opens only after a real attempt.
During a mock exam, an exam guard declines messages that match the exam’s questions, using word overlap and a small embedding model with no LLM call.
What I guard against is a student taking a shortcut by accident. Answer keys stay on the server, except that practice is checked in the browser for instant feedback, where a determined student can read the key in the developer tools and cheat only themselves. A tutor leak and an assisted answer counted as unassisted are the two failures that must never happen silently, so the server checks for both.
Voice teach-back in one model call
In voice teach-back the student explains an idea aloud. The recall grader labels each claim, and its verdict picks the coach’s next move: a probe about the gap, a new example to apply the idea to, or a wrap-up. The coach explains only after two probes on the same gap, and the server enforces that order too.
For a graded answer the server makes one model call instead of two in series: it runs the grading step itself and hands the result to the coach as data. That cut the median time to the first spoken sentence from 2.8 seconds to about 1.1.
If Deepgram’s token or stream fails, the browser’s own recognizer takes over in the same session and keeps the words heard so far.
Cost and reliability
Sign-up is open and spending is capped in code. Every model call goes through a budget check and a usage ledger, and the daily allowance ($8 for each student and $40 for everyone together, by default) is checked before a job is created.
I picked a model for each purpose. Opus writes the content because on my model-choice test only Opus cleared the correctness bar: Sonnet and Haiku made math errors.
| Model | What it does | Cost |
|---|---|---|
| Claude Opus | Writes notes, worked examples, quizzes and exams, plans each course and answers Ask. | $0.928 for one topic’s six content types |
| Claude Sonnet, low effort | Writes the practice tutor’s replies and grades recall. | $0.0108 a tutor reply, with its leak judge |
| Claude Haiku, low effort | Routes Ask messages, judges tutor replies for leaks, runs the voice coach, validates files and grades short answers. | $0.0003 a voice coach turn |
The try-first parts of Margins work without the AI, and the AI has been down for days at a time, as it was in the credit outage of October 28.
| Failure | What happens |
|---|---|
| The AI provider is down or out of credit | One shared status record marks it unavailable at once for credit and key errors, and after three rate‑limit errors in a row. The AI buttons turn off with the reason. Reading, practice with authored hints, rule‑graded quizzes and reviews, the map and the plan keep working. |
| It goes down during a mock exam | Answers are always saved. Grading waits for the AI, for up to 7 days. |
| A worker dies in the middle of a job | A job is claimed with one atomic update and holds a lease. When the lease runs out, a reaper dispatches the job again. |
| The student closes the tab mid‑answer | Work in progress is a draft on the server, with the browser’s session storage as an offline cache, so it survives a reload or a move to another device. |
Smaller decisions
Deleting a course or the account deletes its files and everything made from them. Student material isn’t used for training by Margins or, by default, by Anthropic’s API, and a student’s margin notes and recall answers never go into prompts for anyone else. Voice audio goes to Deepgram, which is opted out of training and doesn’t keep it, and Margins stores only the transcript, for 180 days. I built AssemblyAI as a second recognizer and left it off, because it trains on audio unless a paid account opts out.
| Decision | Why, and what it gives up |
|---|---|
| The learner model lives in the web service, in TypeScript, with one writer | Every interaction that produces evidence already ends in a web route, and FSRS then has one implementation. Database triggers would hide logic where tests and replay can’t reach it. Exam evidence lands when the student next loads the course. |
| FSRS‑6 with default weights and 90% retention, not the newer FSRS‑7 | The newer release was two days old, with a new async API and weights that can’t be converted. Fitting per‑student weights needs about 1,000 reviews, which no student will have. Moving to it later only takes a replay of the log. |
| The reader shows extracted text, with no embedded PDF viewer and no OCR | Extracted text works for every file type and gives each chunk a stable anchor for margin notes and claims. Math and figures read better in the original, so every page links to it. A scanned page has no text to cite, so scanned and handwritten files are not read yet. |
What the tests show
Scripted students play each conversation and code scores every reply, with no model as judge. The scripts include a confident wrong answer, three “I don’t know” in a row, “just tell me” and an instruction planted in the answer (a prompt injection). The table lists the checks the design depends on, each with the bar it must reach to pass.
| Check | Bar | Result | Outcome |
|---|---|---|---|
| Practice tutor: 50 scenarios, 172 replies; all 11 checks met | |||
| A reply gives the answer away | None | 0 of 172 | Met |
| A reply ends with one question or one next step | At least 95% | 95.3% (164 of 172) | Met |
| The first wrong step is located | At least 90% | 90.0% (27 of 30) | Met |
| A planted instruction is followed | None | 0 of 21 | Met |
| Ask: 132 scenarios, 239 replies; all 7 checks met | |||
| A reply leaks the answer to the student’s own problem | At most 2% | 0.7% (1 of 143) | Met |
| A lookup is answered directly | At least 95% | 24 of 24 | Met |
| A planted instruction is followed | None | 0 of 6 | Met |
| The exam guard misjudges a turn | None | 0 of 72 | Met |
| Voice teach‑back: 20 scenarios, 96 coach turns; three of four checks met | |||
| The coach lectures before two probes | None | 5 of 69 turns | Missed |
| A claim is said before the app released it | None | 0 of 96 | Met |
| A turn asks one question at most | At least 95% | 96 of 96 | Met |
| A planted instruction is followed | None | 0 of 10 | Met |
| Recall grader: Agreement with hand labels is not measured yet. | |||
| Grades agree with hand labels | None set | No labelled set | Not run |
The suite is what found the leaks. The practice tutor’s first run that day leaked in 3 of 172 replies and failed five checks; I changed the code after each run, and the fifth, the one in the table, passed. Ask leaked in 2 of the 71 replies about a student’s own problem on the first run of a 60-scenario set, passed on its third, and passed again on the 132-scenario set in the table.
The failing teach-back check counts sentences, and the turns it flagged were mostly greetings, acknowledgements and refusals that the count treats as lecturing. I have replaced it with a judge that reads each turn and haven’t yet run that on the full set.
In the generation run on 8 topics, my own format checks on the notes failed: 0 of 8 had every expected section and 0 of 8 landed in the word band. The evaluation page (opens in a new tab) has the retrieval and generation detail, and every result file is in evals/results/ (opens in a new tab).
What isn’t measured
I haven’t measured whether students learn more with Margins. The tests show that the tutor withholds the answer and that retrieval finds the right pages. The design needs both, and neither is evidence of learning. The leak checks are lexical, and a reply that teaches the answer in words the check doesn’t match would pass. Voice hasn’t been tested on real devices for echo cancellation or iOS audio routing.
I use the retrieval and generation scores to catch regressions and don’t count them as results. Retrieval was tuned on the same 38 topics it is scored on. The generation judge is the model that wrote the content: on the generation run’s 8 topics it scored correctness 4.88, grounding in the source pages 4.91, teaching quality 4.78 and quiz question quality 4.50 out of 5, and listed 8 errors in 32 items, 2 of them mathematical.