Entry point to agent-oriented documentation for the Sefaria codebase. External API docs (for end users): https://developers.sefaria.org/docs/welcome
Sefaria is a Django + MongoDB + React web application serving a digital library of Jewish texts with translations, commentary, source sheets, topics, and cross-references. The core abstraction is the Ref — a canonical citation (e.g. "Genesis 1:1", "Rashi on Genesis 1:1:1") — and nearly every feature is either producing, resolving, or rendering refs.
- Backend: Django (Python 3), MongoDB (primary store — texts, sheets, topics, links, history, etc.), Postgres (all Django-native ORM: auth, sessions, admin-managed content for Chatbot, Guides, Remote Config, Sites, Topic Pool Management, Reader experiments), Redis (pub/sub + cache), Elasticsearch (search), Varnish (HTTP cache), Celery (async tasks)
- Frontend: React (no Redux — component state + Context +
SefariaJS singleton), server-side rendered via Django templates, hydrated on the client - Infra: Multiple app servers coordinated via Redis pub/sub; Varnish in front for HTTP caching; Cloudflare for static assets
agent_docs/
├── model/ # MongoDB ORM + domain models (29 docs)
├── sefaria/ # Backend package: views, business logic, helpers, infra
│ ├── helper/ # Business logic layer
│ └── system/ # DB, cache (incl. GenCache), middleware, Varnish
├── reader/ # Reader Django app (main web views)
├── frontend/ # React components + Sefaria JS singleton
├── apps/ # Smaller Django apps (api, sourcesheets, chatbot, etc.)
└── scripts.md # Top-level scripts/
| Working on... | Start here |
|---|---|
| Any data model, Ref, Index, Version, schema | agent_docs/model/README.md |
| Django views, URL routing, subdomains | agent_docs/sefaria/views_and_routing.md |
| Source sheets | agent_docs/sefaria/sheets.md |
| Search / Elasticsearch | agent_docs/sefaria/search.md |
| Text mutations, history, diffs | agent_docs/sefaria/tracker_and_history.md |
| Helper layer (text edits, topics, linker, LLM, CRM) | agent_docs/sefaria/helper/README.md |
| DB, caching, middleware, multi-server, Varnish | agent_docs/sefaria/system/README.md |
| Linker / find-refs / citation resolution | agent_docs/model/linker/README.md |
| React components | agent_docs/frontend/README.md |
The Sefaria JS singleton |
agent_docs/frontend/sefaria_js.md |
| Reader views (the main reading app) | agent_docs/reader/README.md |
| API, sourcesheets, chatbot, guides, etc. | agent_docs/apps/README.md |
| Scripts / one-off jobs | agent_docs/scripts.md |
| Production slowness / performance incidents | docs/runbooks/performance-triage.md |
| Config, exports, stats, sitemap, image gen | agent_docs/sefaria/config_and_utilities.md |
AbstractMongoRecord.save() runs: _normalize → _validate → _sanitize → _pre_save → (write) → notify. The notify() step fires pub/sub callbacks registered in sefaria/model/dependencies.py. A single Index title change triggers 14 cascading callbacks across collections — never bypass this by writing directly to Mongo.
Never call Version.save() directly to change text. Use sefaria.tracker.modify_text(...) so that:
- History is logged
- Varnish is invalidated
- Search indices are queued for update
- Multi-server caches sync
from sefaria.model import library — the TOC tree, title maps, autocompleters. Call sites often import it inside functions to avoid circular imports, but the singleton itself eagerly builds index maps during its second init stage at module import (not on first access). See agent_docs/model/text.md for the three-stage init.
Model.save() → notify() → in-process cache update + gen_cache.publish()/mark_fresh()/invalidate() (new Redis/Sentinel generation token)
→ other servers' next gen_cache.get() notices the counter changed and refreshes
→ Varnish purge/ban (called directly, no confirmation wait)
→ (optional) Cloudflare purge
Details in agent_docs/sefaria/system/gencache_and_varnish.md. A peer can lag by up to GENCACHE_CHECK_INTERVAL_SECONDS (2s by default) before noticing a change -- by design.
The RefCacheType metaclass intercepts Ref(...) construction and returns a cached instance when the input string or its normal form matches a previous call. The cache is an OrderedDict with LRU-style eviction; the limit defaults to 60,000 and is tunable at runtime via remoteConfigCache (REF_CACHE_LIMIT_KEY). Constructing the same ref string returns the same object. Don't mutate a Ref; derive a new one.
catch_error_as_json converts InputError subclasses (BookNameError, PartialRefInputError, etc.) into structured JSON responses. Other exceptions bubble up as 500s. Raise InputError for anything the caller did wrong.
No Redux. State lives in React component state, a few Contexts, and the global Sefaria JS singleton (caches + API wrapper). Django SSR renders initial props into the page; React hydrates from them. See agent_docs/frontend/sefaria_js.md.
Linker disambiguation, LLM calls, search indexing, CRM syncs, and email are all Celery tasks. Never block an HTTP request on an LLM call.
Markers (pytest.ini): needs_mongo runs on mongomock seeded from a recorded fixture; needs_corpus runs the full library on a real Mongo restored from the public dump (corpus CI job); needs_linker runs in the linker job. Unmarked tests run on mongomock seeded with _base.json only. Fixtures live in sefaria/tests/fixtures/mongo/ (_base.json, one overlay per needs_mongo test, _manifest.json, _shapes.json); never hand-edit them, and keep the total under 20 MiB. If you change a Mongo query, filter or projection, a model's required_attrs/optional_attrs/attr_schemas, or add, rename, re-parametrize or delete a needs_mongo test, run python scripts/pytest_minimal_dataset/rerecord_fixtures.py [--only <nodeid>] (needs docker) and commit the diff under sefaria/tests/fixtures/mongo/. CI (check_fixtures.py, sefaria/tests/fixture_schema_test.py, the shape guard in every needs_mongo test) fails with this exact command otherwise. Never set SEFARIA_MOCK_MONGO_INCOMPLETE_OK or SEFARIA_FIXTURE_SHAPES=off in CI. Runbook: Sefaria wiki runbooks/pytest-fixture-maintenance.md.
Python is linted/formatted with Ruff (pyproject.toml), JS/JSX with ESLint + Prettier, SCSS with Stylelint + Prettier.
A husky pre-commit hook and the Linting GitHub workflow enforce it. Run npm run lint / npm run lint:py to check and
npm run lint:fix to auto-fix. Don't reformat unrelated code in feature PRs. Deferred rules live in the ignore lists
with explanatory comments. See docs/linting.md; the one-time bulk cleanup procedure is in
docs/runbooks/linting-rollout.md.
- Public API docs: https://developers.sefaria.org/docs/welcome
- Codebase: this repo. Source lives alongside the
agent_docs/mirror — every doc cites its source file path.
Code wins. These docs are a map, not the territory. If you find a discrepancy, read the source and update the doc. Flag surprising findings at the top of your response so they aren't lost.
The docs in AGENTS.md and agent_docs/ are stamped to a specific commit in agent_docs/.stamp. Everything between that commit and HEAD is unaudited — trust the docs less in areas where source has changed.
STAMP=$(grep '^commit=' agent_docs/.stamp | cut -d= -f2)
# What source has changed since the stamp?
git diff --name-only "$STAMP"..HEAD -- sefaria/ reader/ static/js/ api/ \
sourcesheets/ chatbot/ guides/ remote_config/ django_topics/ \
emailusernames/ promotions/ scripts/Each changed path maps to a doc via the navigation table above. If a changed file's behavior, signature, or relationships shifted in ways the doc claims otherwise, update the doc.
Expect most diffs to produce no doc updates. These docs live at a summary level — internal refinements, small bug fixes, new helper methods, and UI tweaks usually don't invalidate anything. Focus on: pipeline shape changes, disabled/removed features, new public entry points, changed collection/field names, shifted module boundaries. If you review a changed file and conclude no update is needed, that's the common case — not a sign you missed something.
When a doc claim rests on a specific commit (e.g. a feature that was disabled, a workaround added for a known bug), cite the short SHA inline: "Currently commented out (commit 8f079ea)." This gives the next agent a direct pointer to the reasoning without forcing them to git blame the source.
Bump commit= and date= in agent_docs/.stamp (and update note= with a one-line summary) after:
- A full re-audit of the tree, or
- A targeted update that refreshes every doc touched by the diff since the last stamp.
Don't bump the stamp for partial updates — the stamp's value is that everything up to that commit has been audited. A partial bump silently certifies docs that weren't actually reviewed.
If you're making a code change that invalidates a doc:
- Update the doc in the same PR as the code change.
- Do not bump
.stamp— your change is one file; the stamp covers the whole tree. - The next full-tree audit bumps the stamp.