# Mnemosyne — Architecture

> The humanistic learning and cultural intelligence platform

Mnemosyne is the Oshun domain responsible for every facet of lifelong humanistic
study: spaced repetition, language acquisition, classical pedagogy, art history,
mythology, cultural heritage preservation, history, and archaeology. The name
comes from the Greek Titaness of memory — mother of the nine Muses — which
captures the domain's mission: making the memory-intensive work of humanities
study tractable and rewarding over years.

The domain lives entirely in `libs/mnemosyne/` within the Oshun Nx monorepo. It
ships as **19 independent TypeScript libraries** under the `@mnemosyne/<name>`
naming convention, each declared `private: true` so they are consumed only
through an orchestrating application layer. There is no database, no HTTP
server, and no network client inside the domain — every package is a pure,
in-memory computation library whose only runtime dependency is `zod`.

This architecture document describes how those 19 packages are organized, how
they relate to one another, and what the most important packages contain.

---

## Library Organization

The 19 packages span three broad concerns: a **core learning science
foundation** (`core`, `knowledge-graph`, `experience`, `gamification-plus`), a
**language and linguistics cluster** (`polyglot`, `phonetics`, `pronunciation`,
`writing`, `linguistics`, `classical-tools`, `philology`, `immersion`,
`community`), and a **humanities knowledge cluster** (`aesthetics`, `mythology`,
`heritage`, `temporal`, `rhetoric`, `platform`).

```
libs/mnemosyne/
├── core/              # @mnemosyne/core           — Foundation: memory science, SRS, assessment, knowledge graph, AI
├── platform/          # @mnemosyne/platform       — Data I/O, external integration, multi-platform, content management
├── polyglot/          # @mnemosyne/polyglot       — Multi-language engine: vocabulary, grammar, CEFR, reading
├── linguistics/       # @mnemosyne/linguistics    — Linguistic analysis tools
├── phonetics/         # @mnemosyne/phonetics      — IPA, phoneme inventory, minimal pairs, tone systems, prosody
├── pronunciation/     # @mnemosyne/pronunciation  — Pronunciation training and assessment
├── writing/           # @mnemosyne/writing        — Writing systems and script pedagogy
├── classical-tools/   # @mnemosyne/classical-tools — Alpheios-style reader and DCC-style annotated texts
├── philology/         # @mnemosyne/philology      — Etymology, semantics, stylometrics, corpus analysis
├── rhetoric/          # @mnemosyne/rhetoric       — The Trivium: grammar, logic, rhetoric; disputation, oratory
├── aesthetics/        # @mnemosyne/aesthetics     — Art history and visual analysis
├── mythology/         # @mnemosyne/mythology      — Comparative religion, folklore, sacred text studies
├── heritage/          # @mnemosyne/heritage       — Cultural heritage preservation and digital archives
├── knowledge-graph/   # @mnemosyne/knowledge-graph — Domain knowledge graph operations
├── temporal/          # @mnemosyne/temporal       — History, archaeology, anthropology
├── immersion/         # @mnemosyne/immersion      — Comprehensible input and immersion infrastructure
├── experience/        # @mnemosyne/experience     — Adaptive learning, gamification, social, analytics
├── gamification-plus/ # @mnemosyne/gamification-plus — Advanced league/competition/streak/seasonal systems
└── community/         # @mnemosyne/community      — User-generated content, peer learning, forums
```

---

## Dependency Layering

Understanding how these packages relate to each other is important for knowing
where to add new code and where to look for shared types. In practice, the
packages are almost entirely independent: each package's `package.json` declares
exactly one runtime dependency — `zod` — and `vitest` as a dev dependency. The
only cross-package dependency that exists in code is `@mnemosyne/polyglot`
importing shared types (`CEFRLevel`, `LearnerId`) from `@mnemosyne/core`.

```
@mnemosyne/core              Foundation: memory science, SRS, IRT/CAT,
                             knowledge graph, AI infrastructure.
                             Runtime dependency: zod only.

@mnemosyne/polyglot          Imports type-only symbols from @mnemosyne/core.

all other packages           No @mnemosyne/* dependency. Each is a
(17 packages)                self-contained library depending only on zod —
                             including phonetics, linguistics,
                             classical-tools, philology, rhetoric,
                             aesthetics, mythology, heritage, temporal,
                             knowledge-graph, pronunciation, writing,
                             immersion, experience, gamification-plus,
                             community, and platform.
```

`@mnemosyne/core` is the conceptual foundation — it defines the shared learner /
SRS / assessment model — but only `@mnemosyne/polyglot` currently imports from
it. The remaining packages each define their own local types where needed (for
example `@mnemosyne/phonetics` and `@mnemosyne/classical-tools` each declare
their own `LanguageCode` / `PartOfSpeech` types rather than importing core's).
This means there is no import cycle risk, but also no enforced layering today. A
future refactor that wires all domain packages onto `@mnemosyne/core` would
introduce the strict layer hierarchy this document otherwise implies.

---

## Core Package Architecture (`@mnemosyne/core`)

`@mnemosyne/core` is the foundation package and contains the most critical
algorithms. It is organized into five source files, each covering a distinct
sub-domain of learning science:

```
core/src/
├── types.ts             — All shared type definitions, enums, constants
│                           (LearnerProfile, SRSCard, CEFRLevel, IRTParameters,
│                            KnowledgeItem, LearningPath, Curriculum, Feedback, etc.)
├── memory-science.ts    — SRS algorithms: Ebbinghaus, SM-2, FSRS, HLR, LECTOR
│                           Cognitive load, interleaving, circadian, sleep-aware scheduling
├── knowledge-graph.ts   — KnowledgeGraph class, graph queries, similarity calculation
├── assessment.ts        — IRT (1PL/2PL/3PL), CAT, rubric evaluation, portfolio,
│                           peer assessment, self-assessment, certification, proctoring
├── ai-infrastructure.ts — LLM client types, prompt templates, RAG pipeline,
│                           Socratic dialogue, hint sequences, misconception detection,
│                           AQG, cloze generation, semantic cards, learning analytics
└── index.ts             — Public API barrel export (all types, values, and classes)
```

### Memory Science Module — Key Exports

The memory science module implements several distinct algorithms for scheduling
reviews, each making different assumptions about how memory works. The table
below lists each public function, its type, and what it computes.

| Export                       | Type     | Description                                             |
| ---------------------------- | -------- | ------------------------------------------------------- |
| `calculateRetention`         | function | Ebbinghaus retention at time t given half-life          |
| `estimateHalfLife`           | function | Half-life from review history                           |
| `sm2Review`                  | function | SM-2 algorithm: new interval and ease factor            |
| `fsrsReview`                 | function | FSRS: stability, difficulty, and due date update        |
| `fsrsRetrievability`         | function | Current retrievability given stability and elapsed time |
| `hlrPredict`                 | function | Half-Life Regression prediction                         |
| `calculateOptimalReviewTime` | function | Optimal next review balancing retention and load        |
| `prioritizeReviews`          | function | Ranked review queue by forgetting probability           |
| `estimateCognitiveLoad`      | function | Session cognitive load estimate (0–1)                   |
| `recommendSessionLength`     | function | Minutes recommendation to prevent overload              |
| `lectorSchedule`             | function | LECTOR algorithm scheduling                             |
| `adjustDifficulty`           | function | Adaptive difficulty state update                        |
| `sleepAwareSchedule`         | function | Circadian and sleep-optimized scheduling                |

### Assessment Module — Key Exports

The assessment module covers both psychometric measurement (IRT and CAT) and
richer qualitative approaches (rubrics, portfolios, peer review). The classes
represent stateful workflows; the functions are pure computations.

| Export                       | Type      | Description                                     |
| ---------------------------- | --------- | ----------------------------------------------- |
| `irt1PL`, `irt2PL`, `irt3PL` | functions | IRT probability models                          |
| `itemInformation`            | function  | Fisher information for an item at ability theta |
| `testInformation`            | function  | Summed test information                         |
| `estimateAbility`            | function  | MLE/EAP ability estimation from response vector |
| `selectNextItem`             | function  | CAT maximum-information item selection          |
| `shouldTerminate`            | function  | Stopping criterion evaluation                   |
| `runAdaptiveTest`            | function  | Full CAT simulation loop                        |
| `evaluateWithRubric`         | function  | Open-response scoring against rubric            |
| `generateFeedback`           | function  | Criterion-level feedback generation             |
| `ItemBank`                   | class     | Item bank CRUD and psychometric statistics      |
| `PortfolioTracker`           | class     | Portfolio evidence management                   |
| `PeerAssessmentManager`      | class     | Peer review assignment and calibration          |
| `SelfAssessmentCalibrator`   | class     | Self-assessment accuracy tracking               |
| `CertificationManager`       | class     | Certification lifecycle management              |
| `computeIntegrityScore`      | function  | Proctoring session integrity scoring            |

---

## Polyglot Package Architecture (`@mnemosyne/polyglot`)

`@mnemosyne/polyglot` is the multi-language mastery engine. Unlike the single
`classical-tools.ts` monolith, it splits its surface area across ten source
files so each language-learning concern can be read and modified independently.

```
polyglot/src/
├── language-database.ts      — Language metadata registry (ISO 639 codes, families, typology)
├── vocabulary.ts             — VocabularyItem, word families, frequency lists, cognates
├── grammar.ts                — GrammarRule, paradigms, syntactic patterns, exercises, contrastive analysis
├── reading.ts                — Text difficulty analysis, comprehension skills and questions, reading metrics
├── skills-extended.ts        — Extended CEFR skill descriptors and proficiency assessment
├── vocab-grammar-extended.ts — Thematic modules, mnemonic keywords, vocabulary coverage analysis
├── cefr.ts                   — CEFR/ILR/ACTFL descriptors and cross-framework mapping
├── phonetic.ts               — Word→IPA transcription, phonetic similarity, language detection
├── frequency-bands.ts        — Corpus frequency-band profiling (data/ JSON for en, es)
├── language-resources.ts     — Capitalization, punctuation, and other per-language orthographic resource features
├── types.ts                  — Shared type definitions
└── index.ts                  — Public API barrel export
```

---

## Classical Tools Package Architecture (`@mnemosyne/classical-tools`)

`@mnemosyne/classical-tools` supports assisted reading and annotation of ancient
texts in seven languages. The `ClassicalLanguage` union names those languages,
and the package provides the parsing, display, and progress-tracking primitives
a reading environment needs.

Classical languages are represented by the `ClassicalLanguage` union (Latin,
Ancient Greek, Sanskrit, Classical Arabic, Biblical Hebrew, Old Church Slavonic,
Classical Syriac). The core abstractions implemented in `classical-tools.ts`
include:

- `MorphologicalForm` / `MorphologicalAnalysis` plus `describeMorphForm` and
  `createMorphologicalAnalysis` — Alpheios-style morphological parsing that
  identifies every grammatical attribute of a clicked word in context.
- Paradigm builders: `buildLatinFirstDeclensionParadigm`,
  `buildGreekThematicVerbParadigm` (`ParadigmTable` / `ParadigmCell`) — for
  generating the full conjugation or declension table of any word form.
- Dictionary lookups: `DictionaryEntry`, `DictionarySource`,
  `buildDictionaryLookupUrl` — constructing URLs to external lexicons (Lewis and
  Short, LSJ, Monier-Williams).
- Treebank syntax: `TreebankToken`, `TreebankAnnotation`, `SyntacticRelation`,
  `getTokenDependents`, `getTokenPath` — dependency-tree navigation following
  the AGDT/PROIEL treebank format.
- DCC-style annotated reading: `TextAnnotation`, `AnnotationLayer`,
  `createTextAnnotation`, `generateStudyGuide`, `generateQuizFromAnnotations`,
  collaborative annotation editing, and `ClassicalReadingProgress` /
  `recordWordLookup` progress tracking.
- Passage difficulty: `assessPassageDifficulty`, `PassageDifficultyAssessment`.

---

## Platform Package Architecture (`@mnemosyne/platform`)

`@mnemosyne/platform` is a pure interchange-and-integration library. Its role is
to let a consuming application move data in and out of external tools (Anki, LMS
systems, library catalogs, museum APIs) and to declare the REST surface that a
hosting application could expose. It builds request URLs and parses payloads,
but performs no network I/O itself.

| Area                    | Contents                                                                                                                                         |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Data interchange        | Anki deck JSON import/export (`parseAnkiDeck` / `exportAnkiDeck`), CSV vocabulary import                                                         |
| LMS / e-learning        | SCORM manifest parsing, xAPI statement creation (`XAPI_VERBS`), LTI launch validation                                                            |
| Reference / portability | Zotero export parsing, portable progress data, GDPR data-package assembly                                                                        |
| External connectors     | URL builders + payload parsers for Wikipedia/Wikidata, Europeana, Internet Archive, dictionaries, translation, museum APIs, library SRU catalogs |
| API descriptors         | `APIEndpointDefinition` / `PUBLIC_API_ENDPOINTS` — declarative REST-surface metadata                                                             |

`parseAnkiDeck` operates on a simplified Anki deck JSON export (an `.apkg`
deconstruction), not on the binary `.apkg` archive. The package does not
implement a running server, EPUB/PDF parsing, or TTS/STT.

---

## Key Design Patterns

### Algorithm-First Implementation

The Mnemosyne domain is built around domain-correct algorithms rather than
generic CRUD operations. `@mnemosyne/core` contains genuine implementations of
Ebbinghaus forgetting curves, SM-2 intervals, FSRS v4 stability/difficulty
updates, Half-Life Regression, LECTOR semantic scheduling, IRT 1PL/2PL/3PL
probability models, full CAT loops, and circadian-phase scheduling. All core
functions are pure and deterministic wherever possible, which makes them
straightforward to unit-test against known correct outputs. Bayesian Knowledge
Tracing (BKT) and Deep Knowledge Tracing (DKT) are the exception — they live in
`@mnemosyne/experience`, not in `@mnemosyne/core`, because they require stateful
learner modelling rather than per-card computations.

### Branded ID Types

All entity IDs use branded types (TypeScript nominal typing) to prevent
accidental assignment between different entity types. For example, a `LearnerId`
and a `SRSCardId` are both strings at runtime, but the TypeScript type system
treats them as incompatible. `@mnemosyne/core` defines a `Brand<T, B>` helper
and applies it to twelve ID types:

```typescript
type Brand<T, B extends string> = T & { readonly __brand: B };
type LearnerId = Brand<string, 'LearnerId'>;
type KnowledgeItemId = Brand<string, 'KnowledgeItemId'>;
type SRSCardId = Brand<string, 'SRSCardId'>;
// … KGNodeId, KGEdgeId, LearningPathId, CurriculumId, ExerciseId,
//    AssessmentId, AchievementBadgeId, TestItemId, DeckId
```

### Bloom's Taxonomy Integration

The AI infrastructure module integrates Bloom's six-level taxonomy
(`BLOOM_LEVELS`, `BLOOM_ACTION_VERBS`) for question generation and scaffolding.
Bloom's taxonomy orders cognitive tasks from recall at the bottom through
creation at the top. Scaffolding levels (`SCAFFOLDING_LEVELS`) separately
control how much AI assistance is provided for a given interaction, ranging from
`full` scaffolding for beginners down to `none` for independent learners.

### Circadian and Sleep-Aware Scheduling

Scheduling algorithms in `@mnemosyne/core/memory-science.ts` account for the
fact that memory consolidation is not uniform across the day.
`sleepAwareSchedule` adjusts review intervals to avoid scheduling difficult
items immediately before sleep (where consolidation occurs) or during predicted
low-performance circadian phases. `circadianEfficiency` provides a 0–1
multiplier that drops to 0.1 during sleep hours.

### Modular Gamification

Gamification is deliberately split across two packages to keep core motivational
mechanics separate from the more advanced competitive layer:

- `@mnemosyne/experience` owns foundational gamification: XP, levels, badges,
  leaderboards, a virtual-currency shop, and avatars — plus adaptive-learning
  models including Bayesian Knowledge Tracing (BKT) and Deep Knowledge Tracing
  (DKT).
- `@mnemosyne/gamification-plus` adds the Duolingo-style competitive layer:
  six-tier leagues with weekly promotion/demotion, streak freezes and insurance,
  seasonal events, community goals, and team leagues. It is a self-contained
  library with no code dependency on `@mnemosyne/experience`.

---

## Technology Stack

Mnemosyne is implemented entirely as pure TypeScript libraries. No package
contains a database schema, cache client, or LLM provider binding — each
package's only runtime dependency is `zod`. This design means any consuming
application can inject whatever infrastructure it needs without the domain
libraries prescribing a particular stack.

| Layer      | Technology                                                                                                                                         |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Language   | TypeScript                                                                                                                                         |
| Runtime    | Node.js                                                                                                                                            |
| Testing    | Vitest (co-located `*.test.ts` per package)                                                                                                        |
| Build      | Nx (`@nx/js:tsc` build target per `project.json`)                                                                                                  |
| Validation | Zod                                                                                                                                                |
| LLM        | Provider-agnostic: `LLMProvider` is an injected interface; the AI infrastructure has deterministic template fallbacks when no provider is supplied |

Persistence (PostgreSQL, Redis), embedding services, and LLM provider wiring are
the responsibility of a consuming application and are not part of this domain.

---

## Cross-Domain Boundaries

Mnemosyne's packages declare no `@oshun/*`, `@sophia/*`, or `@metis/*`
dependency. This boundary is intentional: the domain is a library of pure
learning-science and humanities-knowledge functions, not a service that calls
out to other Oshun domains.

If a consuming application wants to combine Mnemosyne's learning infrastructure
with, say, Sophia's knowledge enrichment or Metis's subject-matter content, it
assembles those dependencies itself. The data that would cross the boundary is
typically a `LearnerProfile` or a `KnowledgeItem` carrying a domain identifier —
the consumer maps those into whatever Sophia or Metis expects. Nothing inside
`libs/mnemosyne/*` makes that call.

---

## Phase Reference

Mnemosyne libraries are implemented across phase 39 of the Oshun TODOS.md
migration plan. The table below maps phase sub-sections to the libraries they
cover.

| Phase Range | Domain                                                                                  |
| ----------- | --------------------------------------------------------------------------------------- |
| 39.1–39.4   | Core learning infrastructure (SRS, IRT, knowledge graph, AI)                            |
| 39.5        | History, archaeology, anthropology (`@mnemosyne/temporal`)                              |
| 39.6        | Polyglot language engine (`@mnemosyne/polyglot`)                                        |
| 39.7        | Art history (`@mnemosyne/aesthetics`)                                                   |
| 39.8        | Classical education / Trivium (`@mnemosyne/rhetoric`)                                   |
| 39.9        | Mythology and comparative religion (`@mnemosyne/mythology`)                             |
| 39.10       | Cultural heritage (`@mnemosyne/heritage`)                                               |
| 39.11       | Phonetics (`@mnemosyne/phonetics`)                                                      |
| 39.11.5     | Linguistic analysis tools (`@mnemosyne/linguistics`)                                    |
| 39.12       | Learning experience and gamification (`@mnemosyne/experience`)                          |
| 39.13       | Platform integration (`@mnemosyne/platform`)                                            |
| 39.14       | Immersion infrastructure (`@mnemosyne/immersion`)                                       |
| 39.15–39.18 | Classical tools, philology, pronunciation, writing (`@mnemosyne/classical-tools`, etc.) |
| 39.19       | Advanced gamification (`@mnemosyne/gamification-plus`)                                  |
| 39.20       | Community features (`@mnemosyne/community`)                                             |
