
Private learning notebook that fact-checks your notes and flags what you missed.
Overview
Scholar is a private learning notebook. You write notes in your own words; Scholar tells you when something you wrote is factually wrong and what important concepts are missing, and then stops. It never rewrites your note or produces paste-ready prose, because the point of a learning note is that you did the thinking.
Live at scholar.aayushmaharjan.com.
What it does
- Unlimited nested directories and notes, one-second autosave, Draft and Published states
- Rich editor (TipTap) with Markdown shortcuts, highlighted code blocks, tables, and image uploads
- Fact-check: claim-by-claim, streamed live, with red inline flags, a short reason, and sources. Claims are extracted and judged with OpenAI models, scored by the OpenAI Decisions API, and verified with the Responses API
web_searchtool - What's missing: a persistent checklist of specific concepts you skipped, generated on demand by an OpenAI model with schema-validated structured output
- Inline chat: select any passage and ask an OpenAI-powered tutor question about it
- Visualize: turn a note into a small explained diagram (nodes, edges, sample input/output), streamed from the OpenAI Responses API
- Note-to-note links and a d3 knowledge graph
- Weighted Postgres full-text search with
Cmd/Ctrl + K - A
Cmd/Ctrl + Jterminal for managing directories and notes with shell-style commands - Soft-delete batches with recursive Trash restore
- Bring your own OpenAI key: add your key and pick a model (default
gpt-5-nano) in Settings; it is encrypted at rest and there is no shared key - Per-user AI usage and estimated spend, broken down by task and model
The fact-check pipeline
The product rule is that fact-check must be sparse and consequential. A learner asserting something false about the world (for example, "semantic chunking means chunking by character length") should get a red underline, a one-line reason, and a source. Ordinary true tutorial statements, pipeline steps, opinions, and walkthrough narration should not, and should never cost a web search.
TipTap JSON
→ documentToText (code blocks dropped)
→ chunk (≤ 2,800 chars, paragraph-packed)
→ extractClaims cheap model, structured output, ≤ 8 claims
→ decideClaims Decisions API, P(likely wrong) per claim
→ keep score > 0.7, top 5 by score
→ judgeClaim Responses API + web_search, claim ± 2 paragraphs
→ claims table correct | incorrect | unsure + sources
Results stream to the editor as NDJSON events (extracting, extracted, scoring, scored, checking, claim), so the UI shows each stage as it happens instead of a long spinner.
Chunking decisions
Chunking shows up at every stage, and each stage chunks differently because each one has a different job.
Extract: paragraph packing at 2,800 characters. The note is converted from TipTap JSON to plain text (code fences are skipped, because code is not a prose claim). Paragraphs are split on blank lines and packed greedily into chunks of at most 2,800 characters. A paragraph that is itself longer than the limit is hard-cut in 2,800-character slices. Chunks are extracted with a concurrency of 2, each chunk is told to return only suspicious or high-risk claims (a soft cap of about five per passage), and results are de-duplicated case-insensitively with a hard cap of 8 claims per run.
Why paragraphs and not a fixed sliding window: a claim usually lives inside one paragraph, and cutting mid-paragraph is how you split a definition from the sentence that qualifies it. Packing whole paragraphs keeps each claim next to its own qualifiers while still bounding tokens per call.
Gate: batches of 40 with ±1 paragraph of context. Claims are sent to the Decisions API in batches of 40. Each claim carries a small context (the paragraph it came from plus one neighbor on each side, capped at 900 characters) so the model can tell a false definition from a sentence that only sounds wrong out of context.
Judge: claim plus ±2 paragraphs. The expensive step gets the widest window: the claim and two paragraphs on either side (capped at about 2,200 characters), labelled for interpretation only. This is what stops the judge from "correcting" an illustrative example. If a note says similarity between neighboring sentence embeddings drops when the sample text shifts from FastAPI to PostgreSQL, the judge evaluates that observation, not a made-up claim that PostgreSQL computes vector similarity.
Gaps: one head-only window. The "What's missing" analysis does not chunk. It reads the first 8,000 characters of the note in a single call.
What I would change next, and why it is not shipped yet:
- Structure-aware chunks. Split on TipTap headings and list blocks first, then pack, so chunk boundaries follow how the note is actually organized.
- Offsets and content hashes per chunk. Today every run wipes and rebuilds claims. Hashing chunks would let unchanged text keep its verdicts and re-extract only dirty chunks, the single biggest cost lever for small edits and re-publishes.
- Small overlap (100–200 characters) if character packing stays.
- Gaps by section. Map/reduce per section, or head plus tail, so a long note's ending is not silently dropped.
Cost controls and API decisions
Scholar's AI features are a funnel where each stage is cheaper and broader than the next, and the web search (the priciest call) runs last on the fewest items.
| Stage | API | Model (default) | Budget |
|---|---|---|---|
| Extract | OpenAI Responses, structured JSON | gpt-5-nano (user-configurable) | one call per chunk |
| Gate | OpenAI Decisions API, predicate questions | gpt-6-luna | one call per 40 claims |
| Judge | Responses + web_search tool | the user's model | ≤ 5 per run |
| Gaps | Responses, structured JSON | the user's model | one per analysis |
| Inline chat | Responses, structured JSON | the user's model | per question, last 6 turns kept |
| Visualize | Responses, streamed turns | the user's model | ≤ 16 nodes, ≤ 24 edges per diagram |
- The gate asks the right question. The first version asked "is this checkable?" and almost every tutorial sentence passed, so a single note triggered 40+ web searches. The gate now asks "is this claim likely factually wrong?" with surrounding context, and defaults to skip when unsure. Only claims scoring above 0.7 continue, sorted by score, capped at the top 5.
- No source, no verdict. If the judge returns
incorrectwith zero sources, the server coerces it tounsure. Underlines appear only forincorrectverdicts with at least one source URL. - Hard caps beat hope. 8 extracted claims and 5 web judges per run bound the worst case regardless of how the model behaves.
- Structured output everywhere. Every call returns schema-validated JSON (Zod on the server), so a malformed response fails one claim, not the run. A failed judge marks the note's fact-check as incomplete instead of silently dropping the claim.
- Safer claim swaps. New verdicts are inserted first and old rows are deleted only after, so a failed run does not leave a note with no claims.
- Usage is measured. Every call writes an
ai_usagerow (task, model, tokens in/out, tool calls, latency, web searches, success) and the Usage page turns that into estimated spend by day, task, and model.
Bring your own key (BYOK)
Scholar has no shared OpenAI key and no env-based fallback. Each user supplies their own key in Settings → Providers, so nobody's usage is subsidized and the operator never holds a key that can run up someone else's bill.
- Encrypted at rest. The key is encrypted with AES-256-GCM using a 32-byte master key from
CREDENTIALS_ENCRYPTION_KEY. Each encryption uses a fresh random 12-byte IV, and the stored value isiv ‖ ciphertext ‖ auth tag, base64-encoded. GCM's tag means a tampered or wrong-key ciphertext fails to decrypt rather than returning garbage. - Never sent back to the browser. The settings API returns only
apiKeyConfigured: true/false. Editing a provider without typing a new key keeps the existing ciphertext. - Decrypted only per request. A route resolves the user's credentials, decrypts the key in memory, builds an OpenAI client, and records usage. If the master key has changed, the error tells the user to re-enter their key rather than leaking internals.
- SSRF-safe base URL. The base URL is not free text. It is canonicalized to the provider's known endpoint, and validation rejects non-HTTPS, embedded credentials, non-443 ports, localhost /
.internal/.localhosts, private and link-local IPv4 and IPv6 ranges, and any host outside the provider allowlist. - Connection status. A probe against the provider's
/modelsendpoint (15s timeout) shows whether the saved key is accepted, rejected, or just unreachable, without making a paid call. - Provider model. The schema supports multiple providers per user with one active. OpenRouter is wired in but disabled for now: the Decisions gate is OpenAI-specific, and I did not want a provider that silently skips the cost gate.
API surface
Scholar is a single Next.js App Router app: the UI and the API live together. Every route sits behind a session check.
| Area | Routes |
|---|---|
| Auth | POST /api/auth/signup, login, logout, forgot-password, reset-password |
| Content | /api/notes, /api/notes/[id], /api/directories, /api/tree, /api/trash, /api/search, /api/checklist/[id], /api/graph, /api/graph/links |
| AI per note | POST /api/notes/[id]/fact-check (NDJSON stream), gaps, visualize (streamed turns), inline-chat, publish |
| Media | POST /api/uploads, GET /api/media/[...key] |
| Settings | /api/settings/providers, providers/status, usage |
| Health | GET /api/health/db |
Auth without a library. Sessions are a custom HMAC-SHA256 cookie of the form userId.expiry.signature, valid for 30 days and compared in constant time. A proxy.ts layer verifies it on every request: pages redirect to /login, API calls get a 401. Passwords are hashed, and password reset uses a hashed one-time code with an attempt counter, delivered over SMTP (Nodemailer).
Scoped by user. Every query filters on the session's userId, and notes and directories are soft-deleted in batches so Trash can restore a whole subtree at once.
Image uploads and Cloudflare R2
Images uploaded into a note are stored in Cloudflare R2, Cloudflare's S3-compatible object storage, through the AWS SDK S3 client pointed at an R2 endpoint.
Upload path (POST /api/uploads)
- The route requires a session, then reads the multipart form.
- It allows only
image/jpeg,image/png,image/gif, andimage/webp, and rejects anything empty or larger than 8 MB. SVG is deliberately not accepted on upload. - The file is buffered and written with
PutObjectCommandundernotes/<userId>/<uuid>-<sanitized-name>. The filename is stripped to[a-zA-Z0-9._-]and truncated to 80 characters, and the UUID prefix means two uploads can never collide or overwrite each other. - The route returns an app URL,
/api/media/notes/<userId>/…, not a bucket URL. That URL is what the editor stores in the TipTap document.
Read path (GET /api/media/[...key])
- The bucket stays private. Images are served through an authenticated route that streams the object from R2.
- The key must start with
notes/<the session's userId>/and may not contain.., so one user can never read another user's objects and path traversal is rejected with a404. - Responses use
Cache-Control: private, max-age=31536000, immutable. Keys contain a random UUID and never change, so the browser can cache them indefinitely without a CDN ever seeing private images. - If an object does turn out to be SVG, it is forced to download with
Content-Disposition: attachmentand adefault-src 'none'; sandboxCSP, so a hostile file can't run script in the app's origin.
Why R2: it speaks the S3 API, so the same client code works against any S3-compatible store, and R2 has no egress fees, which matters when every image view streams through the app. Configuration is four environment variables (R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET) plus an optional R2_ENDPOINT override.
Data model
Neon Postgres through Drizzle ORM:
users,password_resetsdirectories(self-referencing tree) andnotes(TipTap JSON injsonb, a plain-text copy for search, avisualizeblob)note_links(source → target) powering the graphclaims(text, verdict, reason, sources) andchecklist_itemsprovider_credentials(provider, model, base URL, encrypted key, active flag)ai_usage(task, model, tokens, latency, tool calls, ok)
Search is weighted Postgres full-text over note titles and plain text, using the built-in tsvector support rather than an extension that Neon has since retired.
Tech stack
App and UI
- Next.js 16 (App Router) and React 19, one codebase for pages and API route handlers
- TypeScript throughout
- Tailwind CSS 4, shadcn/ui, Radix UI,
class-variance-authority, andtailwind-merge - Lucide icons and Sonner toasts
- Bun for installs and scripts
Editor and visualization
- TipTap 3 (ProseMirror) with StarterKit, tables, images, and code blocks highlighted by lowlight
- d3 for the knowledge graph and the note visualizer
Data
- Neon serverless Postgres over its HTTP driver
- Drizzle ORM and drizzle-kit migrations
- Zod 4 for request and model-output validation
AI
- OpenAI SDK: Responses API with the
web_searchtool, structured outputs, and the Decisions API for the cheap gate - Bring-your-own-key, encrypted with Node's built-in
crypto(AES-256-GCM)
Storage, auth, and mail
- Cloudflare R2 through
@aws-sdk/client-s3 - Custom HMAC-signed session cookies via the Web Crypto API
- Nodemailer over SMTP for welcome and password-reset email
What I learned
The expensive part of an AI feature is not the model, it is the number of calls. Reframing the gate from "is this checkable?" to "is this likely wrong?" cut web searches by an order of magnitude and improved precision at the same time, because a model that is allowed to say "skip" produces far fewer false flags.
Context matters more than model size for fact-checking. A sentence judged alone is routinely mislabeled; the same sentence judged with two paragraphs of its own note almost never is.
Security for BYOK is mostly about boring constraints: encrypt the key, never return it, pin the base URL, and scope every object path to the session.
What's next
Structure-aware chunking with content hashes so re-publishing an unchanged note costs nothing, a golden evaluation set of must-flag and must-not-flag fixtures, dismissable flags that stay dismissed, run locking, and a verdict cache keyed on claim and context.