Domain · Specifications

Mnemosyne — Technical Specifications

shared domain model; src/memory-science.ts, src/assessment.ts,

18sections24 minread

On this page

The humanistic learning and cultural intelligence platform

This document specifies the data models, algorithms, public APIs, and configuration of the Mnemosyne domain as actually implemented in libs/mnemosyne/*. Mnemosyne ships as 19 TypeScript libraries under the @mnemosyne/<name> namespace.

Every library is a pure, in-memory TypeScript package — there is no server, no Prisma/Drizzle schema, no HTTP route layer, and no message bus inside the domain. "Persistence", "events", and "APIs" below therefore describe library-level data shapes and function signatures, not a running service. This means the specifications here are authoritative descriptions of what functions exist and what TypeScript types they accept — a consuming application is responsible for wiring them to a database, network, or UI.

Each package declares only zod (validation) as a runtime dependency and vitest as a dev dependency. @mnemosyne/polyglot additionally imports @mnemosyne/core for shared types; all other packages are standalone. Source layout per package is src/<name>.ts plus src/<name>.test.ts and a barrel src/index.ts. A few packages — core, polyglot, phonetics — split into multiple source files.


1. Core Domain Model (@mnemosyne/core)#

@mnemosyne/core is the foundation package. Its src/types.ts defines the shared domain model; src/memory-science.ts, src/assessment.ts, src/knowledge-graph.ts, and src/ai-infrastructure.ts add algorithms and their associated types.

1.1 Branded ID Types#

All entity IDs use TypeScript nominal branding so the type system prevents accidentally passing a SRSCardId where a LearnerId is expected. The Brand<T, B> helper achieves this via intersection types:

typescript
type Brand<T, B> = T & { readonly __brand: B };

The twelve branded ID types defined in @mnemosyne/core are:

Type Underlying Brand
LearnerId string 'LearnerId'
KnowledgeItemId string 'KnowledgeItemId'
SRSCardId string 'SRSCardId'
KGNodeId string 'KGNodeId'
KGEdgeId string 'KGEdgeId'
LearningPathId string 'LearningPathId'
CurriculumId string 'CurriculumId'
ExerciseId string 'ExerciseId'
AssessmentId string 'AssessmentId'
AchievementBadgeId string 'AchievementBadgeId'
TestItemId string 'TestItemId'
DeckId string 'DeckId'

1.2 Learner Types#

The LearnerProfile is the central entity in the learning model. It carries the learner's language history, study preferences, cognitive style, and cumulative statistics. Several supporting types compose into it:

CognitiveStyle models learner preferences using the VARK model — four 0–1 preference scores rather than a single categorical label, reflecting that most learners blend modalities:

typescript
interface CognitiveStyle {
  visual: number; // 0-1 preference strength
  auditory: number; // 0-1
  kinesthetic: number; // 0-1
  readingWriting: number; // 0-1
}

Other learner-related types:

typescript
type StudyTimePreference = 'morning' | 'afternoon' | 'evening' | 'night';

interface LanguageProficiency {
  languageCode: string; // ISO 639-1
  level: CEFRLevel;
  isNative: boolean;
  subScores?: {
    reading: number; // 0-100
    listening: number;
    speaking: number;
    writing: number;
  };
}

interface LearnerStats {
  totalReviews: number;
  totalStudyTimeMinutes: number;
  cardsLearned: number;
  cardsMastered: number;
  averageRetention: number; // 0-1
  averageResponseTimeMs: number;
}

interface LearnerProfile {
  id: LearnerId;
  displayName: string;
  cognitiveStyle: CognitiveStyle;
  languages: LanguageProficiency[]; // ordered strongest → weakest
  dailyStudyMinutes: number;
  preferredStudyTime: StudyTimePreference;
  activeDomains: string[];
  createdAt: number; // epoch ms
  updatedAt: number; // epoch ms
  stats: LearnerStats;
  streakDays: number;
  longestStreakDays: number;
}

Session and progress types capture what happens during a single study period:

typescript
interface LearningSession {
  id: string;
  learnerId: LearnerId;
  startTime: number; // epoch ms
  endTime: number | null; // null = ongoing
  itemsStudied: SRSCardId[];
  correctCount: number;
  incorrectCount: number;
  focusScore: number; // 0-1, derived from response-time variance
  averageDifficulty: number;
  domains: string[];
}

interface ProgressMeasurement {
  recall: number; // 0-1
  speed: number; // 0-1, 1 = fastest
  accuracy: number; // 0-1
  fluency: number; // 0-1, productive fluency
  measuredAt: number; // epoch ms
  sampleSize: number;
}

1.3 Knowledge Item#

KnowledgeItem is the atomic unit of learning content — a fact, concept, skill, or procedure in any humanities domain. It carries prerequisite links directly so the knowledge graph can traverse them:

typescript
type KnowledgeItemType = 'fact' | 'concept' | 'skill' | 'procedure';

interface KnowledgeItem {
  id: KnowledgeItemId;
  type: KnowledgeItemType;
  title: string;
  description: string;
  domain: string; // e.g. "japanese", "calculus"
  difficulty: number; // 0-1
  prerequisites: KnowledgeItemId[];
  tags: string[];
  content?: string;
  createdAt: number;
  updatedAt: number;
}

KnowledgeItemType has exactly four values. There is no vocabulary or grammar item type; language-specific items live in @mnemosyne/polyglot's own VocabularyItem / GrammarRule types (§4).

1.4 Mastery Levels#

Six proficiency levels following the Dreyfus model of skill acquisition. The MASTERY_LEVELS constant provides the canonical ascending order used for all comparisons:

typescript
type MasteryLevel =
  | 'novice'
  | 'beginner'
  | 'intermediate'
  | 'advanced'
  | 'expert'
  | 'master';

const MASTERY_LEVELS: readonly MasteryLevel[]; // ordered, index = ordinal

1.5 Competency Frameworks#

Three international language proficiency frameworks are supported. Each has its own level enumeration and a corresponding descriptor type:

CEFR (Common European Framework of Reference) — the most widely used international standard:

typescript
type CEFRLevel = 'A1' | 'A2' | 'B1' | 'B2' | 'C1' | 'C2';

interface CEFRDescriptor {
  level: CEFRLevel;
  label: string; // 'Breakthrough', 'Waystage', 'Threshold', …
  description: string;
  canDo: string[]; // "can-do" statements
}

CEFR_LEVELS (ordered) and CEFR_DESCRIPTORS (6 entries, Council of Europe definitions) are exported constants.

ILR (Interagency Language Roundtable) — the US government scale used for military and intelligence language assessment, with 11 discrete levels:

typescript
type ILRLevel =
  | '0'
  | '0+'
  | '1'
  | '1+'
  | '2'
  | '2+'
  | '3'
  | '3+'
  | '4'
  | '4+'
  | '5';

interface ILRDescriptor {
  level: ILRLevel;
  label: string; // 'No Proficiency', 'Elementary Proficiency', …
  description: string;
}

ILR_LEVELS (11 entries) and ILR_DESCRIPTORS (11 entries) are exported.

ACTFL (American Council on the Teaching of Foreign Languages) — the standard used in US academic language programs:

typescript
type ACTFLLevel =
  | 'Novice Low'
  | 'Novice Mid'
  | 'Novice High'
  | 'Intermediate Low'
  | 'Intermediate Mid'
  | 'Intermediate High'
  | 'Advanced Low'
  | 'Advanced Mid'
  | 'Advanced High'
  | 'Superior'
  | 'Distinguished';

ACTFL_LEVELS is an ordered 11-entry constant. The ACTFL labels use spaces, not hyphens ('Novice Low', not 'Novice-Low').

A CompetencyFramework type provides a normalized interface over all three:

typescript
interface CompetencyFramework {
  name: 'CEFR' | 'ILR' | 'ACTFL';
  levels: readonly string[];
  normalise(level: string): number; // → 0-1 normalised score
}

1.6 SRS Card and Review Types#

The spaced repetition card design is central to the system. A single SRSCard carries state for both SM-2 and FSRS simultaneously so either algorithm can be used without card duplication. The review types track a learner's grading response and how the card schedule should be updated.

typescript
type ReviewGrade = 'again' | 'hard' | 'good' | 'easy';

const REVIEW_GRADE_MAP: Record<ReviewGrade, number>;
// { again: 1, hard: 2, good: 3, easy: 4 }

type SM2Grade = 0 | 1 | 2 | 3 | 4 | 5; // 0 = blackout, 5 = perfect

type FSRSState = 'New' | 'Learning' | 'Review' | 'Relearning';

The SRSCard interface showing both SM-2 and FSRS fields:

typescript
interface SRSCard {
  id: SRSCardId;
  front: string;
  back: string;
  deckId: DeckId;
  tags: string[];

  // SM-2 fields
  easeFactor: number; // initialised at 2.5
  interval: number; // days
  repetitions: number; // consecutive correct (SM-2 n)

  // FSRS fields
  difficulty: number; // 1-10 scale
  stability: number; // days
  state: FSRSState;
  lapses: number;
  reps: number;

  // Scheduling
  lastReviewAt: number | null; // epoch ms
  nextReviewAt: number; // epoch ms
  createdAt: number; // epoch ms
}

interface ReviewSchedule {
  cardId: SRSCardId;
  nextReviewAt: number; // epoch ms
  intervalDays: number;
  easeFactor: number;
}

interface ReviewResult {
  cardId: SRSCardId;
  grade: ReviewGrade;
  responseTimeMs: number;
  wasCorrect: boolean;
  reviewedAt: number; // epoch ms
}

1.7 FSRS Parameters#

FSRS v4 uses a 17-element weight vector that was calibrated on large review datasets. The default weights come from open-spaced-repetition/fsrs4anki:

typescript
interface FSRSParameters {
  w: readonly [number × 17];   // 17-element weight vector w[0]..w[16]
  requestRetention: number;    // 0-1, target retention
  maximumInterval: number;     // days
}

const FSRS_DEFAULT_PARAMETERS: FSRSParameters = {
  w: [
    0.4072, 1.1829, 3.1262, 15.4722, 7.2102, 0.5316, 1.0651, 0.0589,
    1.5747, 0.0838, 0.9816, 2.0379, 0.11, 0.2553, 2.218, 0.2267, 2.867,
  ],
  requestRetention: 0.9,
  maximumInterval: 36500,   // ~100 years
};

1.8 Assessment Types (IRT / CAT)#

IRT parameters describe each item's measurement properties. The three parameters correspond to the 3PL model: discrimination (how sharply the item distinguishes ability levels), difficulty (where on the ability scale the item is located), and guessing (the baseline probability of a correct answer by chance).

typescript
interface IRTParameters {
  a: number; // discrimination (slope), typically 0.5-2.5
  b: number; // difficulty (location on theta scale), typically -3..+3
  c: number; // pseudo-guessing (lower asymptote), typically 0-0.35
}

interface IRTAbilityEstimate {
  theta: number; // point estimate of ability
  standardError: number;
  itemCount: number;
  logLikelihood: number; // log-likelihood at the MLE
}

interface TestItem {
  id: TestItemId;
  question: string;
  options: string[];
  correctOptionIndex: number;
  irtParameters: IRTParameters;
  domain: string;
  administered?: boolean;
}

interface ItemResponse {
  itemId: TestItemId;
  selectedOptionIndex: number;
  correct: boolean;
  responseTimeMs: number;
}

interface AssessmentResult {
  id: AssessmentId;
  learnerId: LearnerId;
  items: ItemResponse[];
  abilityEstimate: IRTAbilityEstimate;
  score: number; // fraction correct
  totalTimeMs: number;
  averageDifficulty: number;
  completedAt: number; // epoch ms
}

The CAT configuration determines when the adaptive test starts, what selection strategy it uses, and when it stops:

typescript
interface CATConfig {
  minItems: number;
  maxItems: number;
  seThreshold: number; // stop when SE < this value
  initialTheta: number;
  selectionStrategy: 'max_info' | 'random' | 'stratified';
}

const DEFAULT_CAT_CONFIG: CATConfig = {
  minItems: 5,
  maxItems: 50,
  seThreshold: 0.3,
  initialTheta: 0.0,
  selectionStrategy: 'max_info',
};

1.9 Rubric Types#

Rubric assessment scores open-response submissions against multi-criterion definitions. Each criterion has an explicit weight and a set of ordered levels with descriptors so raters apply it consistently:

typescript
interface RubricCriterion {
  name: string;
  description: string;
  weight: number; // normalised internally
  levels: RubricLevel[]; // ordered lowest → highest
}

interface RubricLevel {
  score: number; // 0-based
  label: string;
  description: string;
}

interface Rubric {
  id: string;
  title: string;
  criteria: RubricCriterion[];
}

interface RubricEvaluation {
  rubricId: string;
  criterionScores: Array<{
    criterionName: string;
    score: number;
    maxScore: number;
    feedback: string;
  }>;
  totalScore: number; // weighted, 0-1
  overallFeedback: string;
}

1.10 Knowledge Graph Types#

The knowledge graph models relationships between concepts. The six relationship types cover both pedagogical dependencies and semantic associations:

typescript
type KGRelationType =
  | 'prerequisite'
  | 'part_of'
  | 'related_to'
  | 'causes'
  | 'temporal'
  | 'semantic_similar';

interface KGNode {
  id: KGNodeId;
  label: string;
  type: string; // domain-specific node type
  domain: string;
  properties: Record<string, string | number | boolean>;
  mastery?: MasteryLevel;
}

interface KGEdge {
  id: KGEdgeId;
  sourceId: KGNodeId;
  targetId: KGNodeId;
  type: KGRelationType;
  weight: number; // 0-1
  provenance: string; // e.g. 'expert', 'mined', 'inferred'
}

interface KGPath {
  nodes: KGNodeId[];
  edges: KGEdgeId[];
  totalWeight: number;
}

1.11 Learning Path Types#

Learning paths connect a curriculum (a structured sequence of modules and lessons) to a specific learner's progress through it. Branching rules allow the path to adapt based on what the learner has demonstrated:

typescript
type ExerciseType =
  | 'multiple_choice'
  | 'fill_in'
  | 'production'
  | 'matching'
  | 'ordering'
  | 'cloze';

interface Exercise {
  id: ExerciseId;
  type: ExerciseType;
  prompt: string;
  correctAnswers: string[];
  distractors?: string[];
  hint?: string;
  difficulty: number; // 0-1
  knowledgeItemId?: KnowledgeItemId;
  domain: string;
}

interface Lesson {
  id: string;
  title: string;
  description: string;
  knowledgeItems: KnowledgeItemId[];
  exercises: ExerciseId[];
  estimatedMinutes: number;
  order: number;
}

interface CurriculumModule {
  id: string;
  title: string;
  description: string;
  lessons: Lesson[];
  prerequisites: string[]; // module IDs
  order: number;
}

interface Curriculum {
  id: CurriculumId;
  title: string;
  description: string;
  domain: string;
  modules: CurriculumModule[];
  targetLevel: MasteryLevel;
  estimatedHours: number;
  createdAt: number;
  updatedAt: number;
}

interface LearningPath {
  id: LearningPathId;
  learnerId: LearnerId;
  curriculumId: CurriculumId;
  moduleOrder: string[];
  unlockedModules: string[];
  completedModules: string[];
  currentModuleId: string | null;
  branchingRules: BranchingRule[];
  createdAt: number;
  updatedAt: number;
}

interface BranchingRule {
  condition: BranchCondition;
  targetModuleId: string;
  action: 'skip' | 'unlock';
}

type BranchCondition =
  | { type: 'score_above'; moduleId: string; threshold: number }
  | {
      type: 'mastery_at_least';
      knowledgeItemId: KnowledgeItemId;
      level: MasteryLevel;
    }
  | { type: 'time_spent_below'; moduleId: string; minutes: number };

1.12 Gamification Types#

Badge tiers are distinct from competitive league tiers — badges are awarded for individual accomplishments and use five tiers; leagues (in @mnemosyne/gamification-plus) are competitive divisions and use six tiers including Obsidian.

typescript
type BadgeTier = 'bronze' | 'silver' | 'gold' | 'platinum' | 'diamond';

const BADGE_TIERS: readonly BadgeTier[];

interface AchievementBadge {
  id: AchievementBadgeId;
  name: string;
  description: string;
  iconUrl: string;
  tier: BadgeTier;
  domain: string; // or 'global'
  criteria: BadgeCriteria;
  xpReward: number;
}

type BadgeCriteria =
  | { type: 'streak'; days: number }
  | { type: 'cards_reviewed'; count: number }
  | { type: 'mastery_reached'; level: MasteryLevel; domain: string }
  | { type: 'accuracy_above'; threshold: number; windowDays: number }
  | { type: 'sessions_completed'; count: number }
  | { type: 'perfect_session'; count: number };

interface EarnedBadge {
  badgeId: AchievementBadgeId;
  learnerId: LearnerId;
  earnedAt: number;
}

The BadgeTier set is bronze/silver/gold/platinum/diamond (five tiers). The Duolingo-style competitive league tiers (Bronze … Obsidian) are a separate type defined in @mnemosyne/gamification-plus (§10).

1.13 Cognitive Load Types#

Based on Sweller's Cognitive Load Theory, the load estimate separates three types of mental effort. When total load exceeds 0.85 the system recommends reducing difficulty or ending the session:

typescript
interface CognitiveLoadEstimate {
  intrinsicLoad: number; // 0-1, from the material itself
  extraneousLoad: number; // 0-1, from presentation / interface
  germaneLoad: number; // 0-1, productive learning effort
  totalLoad: number; // 0-1; > 0.85 → overload risk
  recommendation: CognitiveLoadRecommendation;
}

type CognitiveLoadRecommendation =
  | 'continue'
  | 'reduce_difficulty'
  | 'take_break'
  | 'end_session';

1.14 Review Forecast and Interleaving Types#

Forecast types model the future review queue so a learner (or application) can anticipate load and plan study time:

typescript
interface ReviewForecast {
  startDate: number; // epoch ms
  dailyCounts: DailyReviewCount[];
  averageDailyReviews: number;
  peakDailyReviews: number;
}

interface DailyReviewCount {
  dayOffset: number; // 0 = today
  dueCount: number;
  estimatedMinutes: number;
}

interface InterleavingPlan {
  sequence: SRSCardId[];
  domains: string[];
  strategy: InterleavingStrategy;
}

type InterleavingStrategy =
  | 'round_robin'
  | 'weighted_random'
  | 'difficulty_interleaved';

1.15 Half-Life Regression Types#

HLR fits a personalized forgetting curve per learner per item. The weight vector encodes how each feature (number of repetitions, time since last review, prior half-life) contributes to the predicted half-life:

typescript
interface HLRFeatures {
  repetitionCount: number;
  lagTimeDays: number;
  previousHalfLife: number; // days
  extras?: Record<string, number>;
}

interface HLRWeights {
  intercept: number;
  repetitionWeight: number;
  lagTimeWeight: number;
  previousHalfLifeWeight: number;
  extraWeights?: Record<string, number>;
}

const DEFAULT_HLR_WEIGHTS: HLRWeights = {
  intercept: 2.0,
  repetitionWeight: 0.9,
  lagTimeWeight: -0.2,
  previousHalfLifeWeight: 0.5,
};

1.16 Feedback Types#

Feedback is richly typed to support different delivery contexts. FeedbackTiming distinguishes immediate (shown right after a response) from delayed (shown in a later review). FeedbackGranularity ranges from simple verification ("correct!") through elaboration to metacognitive reflection:

typescript
type FeedbackTiming = 'immediate' | 'delayed';
type FeedbackPurpose = 'formative' | 'summative' | 'diagnostic';
type FeedbackGranularity =
  | 'verification'
  | 'correct_response'
  | 'elaboration'
  | 'strategic'
  | 'metacognitive';
type FeedbackModality = 'text' | 'audio' | 'visual' | 'interactive';

interface Feedback {
  id: string;
  timing: FeedbackTiming;
  purpose: FeedbackPurpose;
  granularity: FeedbackGranularity;
  modality: FeedbackModality;
  content: string;
  explanation?: FeedbackExplanation;
  targetItemId?: ExerciseId | KnowledgeItemId | TestItemId;
  learnerResponse?: string;
  wasCorrect?: boolean;
  confidence?: number; // 0-1
  tags: string[];
  createdAt: number;
}

Supporting interfaces include FeedbackExplanation (summary, steps, misconceptions, references, alternativeApproaches), FeedbackReference (title, type ∈ textbook/video/article/exercise/external, url, anchor), ImmediateFeedbackConfig, DelayedFeedbackConfig, FormativeFeedback (strengths, areasForImprovement, nextSteps, progressTowardObjective, identifiedGaps, suggestedRemediation), and SummativeFeedback (overallScore, gradeLabel, masteryLevel, domainScores, optional certification, percentileRank, narrative).


2. Core Algorithms (@mnemosyne/core)#

2.1 Memory Science (src/memory-science.ts)#

The memory science module implements all scheduling algorithms as pure functions. Each function's signature, formula, and error-handling behavior is documented below. Input invariants that are violated throw RangeError rather than returning silently incorrect results.

Function Signature summary Behaviour
calculateRetention(stability, elapsed) → number Ebbinghaus R = e^(-t/S); throws RangeError on stability ≤ 0 or elapsed < 0
estimateHalfLife(reviews) → number | null Half-life from {elapsedDays, recalled}[]; S = -avgElapsed/ln(retention), h = S·ln2, floored at 0.01
sm2Review(card, grade, now?) SM2ReviewResult SM-2: EF' = EF + (0.1 − (5−q)·(0.08 + (5−q)·0.02)), clamped ≥ 1.3; fail (q<3) resets; pass intervals 1, 6, then interval·EF
fsrsRetrievability(elapsedDays, stability) → number FSRS power-law R = (1 + t/(9S))^(-1)
fsrsReview(card, grade, params?, now?) FSRSReviewResult Full FSRS v4 state machine + stability/difficulty update
hlrPredict(features, weights?) → number Half-Life Regression h = 2^(θ·x), clamped 0.01–3650 days
hlrRetention(elapsedDays, features, weights?) → number p = 2^(-t/h)
calculateOptimalReviewTime(stability, targetRetention) → number t = 9·S·(1/R − 1) days
prioritizeReviews(cards, availableTimeMinutes, avgReviewSeconds?, now?) SRSCardId[] Greedy urgency ranking within a time budget
calculateReviewLoad(cards, days, avgMinutesPerReview?, now?) ReviewForecast Per-day due-count projection
estimateCognitiveLoad(itemCount, avgDifficulty, sessionMinutes, maxMinutes?) CognitiveLoadEstimate Sweller CLT: intrinsic / extraneous / germane / total + recommendation
recommendSessionLength(learner) → number Minutes (clamped 10–60) from profile, retention, streak, chronotype
suggestInterleaving(cards, strategy?) InterleavingPlan Round-robin / weighted-random / difficulty-interleaved ordering
lectorSchedule(cards, similarities, recentlyReviewed?, transferCoeff?, now?) SRSCardId[] Semantic-aware scheduling: P = urgency·(1 − α·maxSim)·diversityBonus
createAdaptiveDifficultyState(initialDifficulty?) AdaptiveDifficultyState Initialise adaptive-difficulty tracker
adjustDifficulty(state, wasCorrect, config?, now?) AdaptiveDifficultyState PID-style ZPD controller targeting an accuracy rate
selectByDifficulty(items, targetDifficulty, count, bandwidth?) T[] Gaussian-kernel selection around a target difficulty
getCircadianPhase(hour) CircadianPhase Time-of-day bin
getCircadianProfile(hour) CircadianPerformanceProfile Performance profile for an hour
hoursUntilSleep(currentHour, schedule) → number Hours to next sleep onset
sleepAwareSchedule(rawIntervalDays, difficulty, schedule, currentHour?) { adjustedIntervalDays, recommendedHour, phase } Circadian + pre-sleep consolidation interval adjustment
circadianEfficiency(currentHour, schedule) → number 0-1 efficiency multiplier (0.1 during sleep hours)

Memory-science return types: SM2ReviewResult (easeFactor, interval, repetitions, nextReviewAt), FSRSReviewResult (difficulty, stability, state, interval, reps, lapses, nextReviewAt), AdaptiveDifficultyConfig, AdaptiveDifficultyState, CircadianPhase, CircadianPerformanceProfile, SleepSchedule.

The seven circadian phases and the adaptive difficulty defaults are:

typescript
type CircadianPhase =
  | 'early_morning'
  | 'morning'
  | 'early_afternoon'
  | 'afternoon'
  | 'evening'
  | 'night'
  | 'late_night';

const DEFAULT_ADAPTIVE_DIFFICULTY_CONFIG: AdaptiveDifficultyConfig = {
  targetAccuracy: 0.85,
  smoothingFactor: 0.3,
  minDifficulty: 0.05,
  maxDifficulty: 0.95,
  adjustmentRate: 0.1,
  minResponsesBeforeAdjust: 3,
};

DEFAULT_CIRCADIAN_PROFILES is a 7-entry constant array (one CircadianPerformanceProfile per CircadianPhase) with empirically motivated learningEfficiency and consolidationBonus values.

FSRS v4 State Machine#

fsrsReview implements the full FSRS v4 transition graph on the card's state field. The transitions work as follows:

  • New → first review initialises D0 = w[4] − (g−3)·w[5] and S0 = w[g−1]; grade again/hardLearning, good/easyReview.
  • Learning / Relearningagain stays in the current learning state; hard/good/easy graduate to Review. A lapse counter increments only in Relearning.
  • Reviewagain applies the lapse-stability formula and transitions to Relearning (increments lapses); hard/good/easy apply the success-stability formula and stay in Review.

Interval is 9·S·(1/requestRetention − 1) for Review cards (rounded, clamped to [1, maximumInterval]); learning/relearning cards use short 0–1 day intervals.

2.2 Assessment (src/assessment.ts)#

All IRT functions take ability (theta) and item parameters; they return probabilities or information values. The classes provide stateful workflows built on top of these pure functions.

Function Behaviour
irt1PL(theta, b) Rasch: P = 1/(1 + e^(-(θ-b)))
irt2PL(theta, a, b) P = 1/(1 + e^(-a(θ-b))); throws if a ≤ 0
irt3PL(theta, a, b, c) P = c + (1-c)/(1 + e^(-a(θ-b))); throws if a ≤ 0 or c ∉ [0,1)
irtProbability(theta, params) 3PL convenience wrapper over IRTParameters
itemInformation(theta, a, b, c) Fisher information I = a²(P-c)²(1-P) / ((1-c)²P)
itemInformationFromParams(theta, params) Convenience wrapper
testInformation(theta, items) Σ Iᵢ(θ) over items
standardErrorFromInformation(information) SE = 1/√I (Infinity if I ≤ 0)
estimateAbility(responses, items, initialTheta?, maxIter?, tolerance?) MLE via Newton-Raphson with step-halving; handles all-correct / all-incorrect with a Bayesian warm estimate
selectNextItem(theta, itemBank, administered) Max-Fisher-information item not yet administered
shouldTerminate(theta, se, administered, config?) CAT stopping rule (min items, SE threshold, max items)
simulateResponse(trueTheta, item, rng?) IRT-probabilistic simulated answer
runAdaptiveTest(itemBank, trueTheta, config?, rngSeed?) Full simulated CAT loop → { estimate, responses }
evaluateWithRubric(scores, rubric) Weighted rubric scoring → RubricEvaluation
generateFeedback(evaluation) Strengths / developing / improvement narrative string
computeIntegrityScore(flags) Proctoring integrity 0-1 from flags with per-type diminishing returns

The stateful assessment classes are:

  • ItemBank — in-memory item bank: addItem / addItems / removeItem / getItem / getAllItems, size; filters getByDomain, getByDifficultyRange, getByDiscriminationRange; exposure tracking recordAdministration / getExposureCount / getUnderexposedItems; getStatistics()ItemBankStatistics; clear().
  • PortfolioTrackerPortfolioEntry collection with addEntry, getEntries, getByType, getByTimeRange, size, computeGrowthTrajectory(domain?), analyzeStrengthsWeaknesses(), clear().
  • PeerAssessmentManager — peer-review workflow: createAssignments, submitReview, getAssignmentsForReviewer, getReviewsForSubmission, computeAgreement (variance-based inter-rater agreement), aggregateReviews (reliability-weighted consensus), setReviewerReliability / getReviewerReliability.
  • SelfAssessmentCalibratoraddPrediction, recordActualScore, computeCalibration()CalibrationMetrics (bias, absoluteError, calibrationSlope, resolution, sampleSize, over/underconfidence rates), generateFeedback(), clear().
  • CertificationManagerregisterCertification, getCertification, getAllCertifications, checkRequirements, issueCredential (issues only when all requirements are met), getCredentialsForLearner, refreshValidity.

Assessment data types include ItemBankStatistics, PortfolioEntry, PeerReviewStatus (pending/in_progress/completed/disputed), PeerReviewAssignment, PeerReview, SelfAssessmentPrediction, CalibrationMetrics, Certification, CertificationRequirement (a tagged union: min_score / min_mastery / portfolio_entries / study_hours), Credential, CredentialEvidence, ProctoringMode (unproctored / ai_proctored / live_proctored / record_and_review), ProctoringFlag, ProctoringFlagType (10 values: tab_switch, face_not_detected, multiple_faces, audio_anomaly, copy_paste, screen_share, unusual_typing, time_anomaly, browser_resize, external_device), ProctoringSession.

2.3 Knowledge Graph (src/knowledge-graph.ts)#

The KnowledgeGraph class is an in-memory directed weighted graph. Node similarity is computed as Jaccard similarity over the two nodes' properties maps (each key-value pair is treated as a set element).

Node operations: addNode, removeNode (cascades incident edges), getNode, getAllNodes, nodeCount, getNodesByType, getNodesByDomain.

Edge operations: addEdge (validates endpoints exist), removeEdge, getEdge, getEdgesFrom, getEdgesTo, getAllEdges, edgeCount, getEdgesByType, getNeighbours, getInDegree, getOutDegree.

Traversal and pathfinding:

  • findPath — BFS shortest path between two nodes.
  • findAllPaths — DFS all paths, bounded by maxDepth.
  • getPrerequisites — transitive backward traversal over prerequisite edges.
  • getDependents — transitive forward traversal.
  • topologicalSort() — Kahn's algorithm over prerequisite edges; throws on a cycle.

Learning-specific operations:

  • identifyKnowledgeGaps(learnerMastery, targetNodeId, minLevel?) — missing or under-mastered prerequisites given the learner's current state.
  • recommendNextItems(learnerMastery, count, targetLevel?) — items whose prerequisites are met, ranked by dependent count and mastery gap.
  • findSimilarNodes(nodeId, threshold?) — Jaccard similarity search.
  • query(query: GraphQuery) — SPARQL-style Basic Graph Pattern matching over TriplePattern[] (conjunctive); supports node-property and edge patterns, ?-prefixed variables.
  • discoverCrossDomainLinks(similarityThreshold?, maxLinksPerNode?) — creates semantic_similar edges between similar nodes in different domains.
  • getTimeline(startNodeId, direction?, maxDepth?) — temporal traversal.
  • getNodesInTimeRange(startYear, endYear) — year-filtered node set.
  • buildTemporalChain(domain) — orders nodes in a domain chronologically.
  • clear().

Query types: TriplePattern (subject, predicate, object), GraphQuery (where: TriplePattern[]).

2.4 AI / ML Infrastructure (src/ai-infrastructure.ts)#

The AI infrastructure layer is designed to run with or without a live LLM. With an injected LLMProvider it can use generative power; without one it falls back to algorithmic and template implementations. The layer covers 15 subsystems:

LLM integration. LLMProvider interface (complete, embed, name, isAvailable); LLMMessage, MessageRole (system/user/assistant), CompletionConfig, LLMCompletionResult. Default parameters: DEFAULT_COMPLETION_CONFIG = { maxTokens: 1024, temperature: 0.7, topP: 0.9, frequencyPenalty: 0.1, presencePenalty: 0.1 }.

Bloom's taxonomy and scaffolding. BloomLevel (remember, understand, apply, analyze, evaluate, create), BLOOM_LEVELS, BLOOM_ACTION_VERBS (verb lists per level), ScaffoldingLevel (full/partial/minimal/none), SCAFFOLDING_LEVELS. EducationalContext carries mastery, domain, cognitive style, bloom level, and scaffolding level.

Prompt framework. PromptTemplate ({{placeholder}} syntax), renderPromptTemplate, buildEducationalSystemPrompt, EDUCATIONAL_PROMPT_TEMPLATES (5 built-in templates: explain_concept, socratic_question, generate_hint, detect_misconception, generate_analogy), selectPromptTemplate.

RAG pipeline. DocumentChunk, ChunkingConfig (fixed_size/sentence/paragraph/semantic strategy), DEFAULT_CHUNKING_CONFIG (512 max tokens, 64 overlap, sentence strategy), chunkDocument, cosineSimilarity, bm25Score (Okapi BM25), retrieveChunks (BM25 / cosine / hybrid), assembleRAGContext, RetrievalResult.

Knowledge-grounded responses. generateGroundedResponseGroundedResponse with Citation[] and a groundingScore.

Socratic dialogue. SocraticMethod (elenchus, maieutic, reductio, hypothesis_testing, dialectic), SocraticQuestion, SocraticDialogueTurn, SocraticDialogueState; generateSocraticQuestion, createSocraticDialogue, advanceSocraticDialogue.

Adaptive hints. HintLevel (nudge, clue, explanation, solution), HINT_LEVELS, Hint, HintSequenceState; generateHint, createHintSequence, getNextHint, selectInitialHintLevel.

Multi-perspective explanations. ExplanationPerspective (analogy, formal, visual, historical, practical, first_principles, comparative — seven perspectives), PerspectiveExplanation, MultiPerspectiveExplanation; generateMultiPerspectiveExplanation, selectBestPerspective.

Misconception detection. MisconceptionPattern, MisconceptionDetectionResult, COMMON_MISCONCEPTIONS (curated, research-based pattern library), detectMisconceptions, createMisconceptionPattern.

Question generation. QuestionType, GeneratedQuestion, AQGConfig, DEFAULT_AQG_CONFIG, generateQuestionsFromText.

Distractor generation. Distractor, DistractorErrorType, generateDistractors.

Cloze deletion. ClozeDeletion, ClozeScoreFactors, generateClozeDeletions, estimateClozeDifficulty (→ MasteryLevel).

Semantic cards. SemanticCard, SemanticCardType, generateSemanticCards, generateCardsFromText.

Multimodal content. ContentModality, MultimodalContent, AccessibilityMetadata, ContentGenerationRequest, generateMultimodalContentPlan.

Personalized examples. LearnerInterestProfile, PersonalizedExample, generatePersonalizedExamples.

Learning analytics. LearningDataPoint, DropoutPrediction, MasteryTimeline, OptimalReviewPrediction, EngagementTrend; predictDropoutRisk, predictMasteryTimeline, predictOptimalReviewCount, analyzeEngagementTrend.


3. Memory Science Algorithm Reference#

The formulas below are the exact computations implemented in src/memory-science.ts. They are repeated here for quick reference without needing to read source code.

SM-2#

text
EF' = EF + (0.1 − (5 − q) × (0.08 + (5 − q) × 0.02))   (clamped ≥ 1.3)
q < 3 → repetitions = 0, interval = 1
q ≥ 3 → repetitions++, interval = 1 (n=1), 6 (n=2), round(interval × EF') (n≥3)

FSRS v4 Retrievability#

text
R(t, S) = (1 + t / (9 · S))^(−1)

IRT Probability Models#

text
1PL  P(θ, b)        = 1 / (1 + e^(−(θ − b)))
2PL  P(θ, a, b)     = 1 / (1 + e^(−a(θ − b)))
3PL  P(θ, a, b, c)  = c + (1 − c) / (1 + e^(−a(θ − b)))

Fisher Information (3PL)#

text
I(θ) = a² · (P − c)² · (1 − P) / ((1 − c)² · P)

Half-Life Regression#

text
h = 2^(θ · x)        retention p = 2^(−t / h)

The full Bayesian Knowledge Tracing implementation lives in @mnemosyne/experience (§9), not in @mnemosyne/core.


4. Polyglot — Language Engine (@mnemosyne/polyglot)#

@mnemosyne/polyglot splits across nine source files: language-database.ts, vocabulary.ts, grammar.ts, reading.ts, skills-extended.ts, vocab-grammar-extended.ts, cefr.ts, phonetic.ts, frequency-bands.ts, plus types.ts.

4.1 Language Metadata Types#

Language codes are branded strings so a raw string cannot be passed where a LanguageCode is expected:

typescript
type LanguageCode = string & { __brand: 'LanguageCode' }; // ISO 639-3

The full set of language classification types:

typescript
type LanguageFamily =
  | 'Indo-European'
  | 'Sino-Tibetan'
  | 'Afro-Asiatic'
  | 'Niger-Congo'
  | 'Austronesian'
  | 'Dravidian'
  | 'Turkic'
  | 'Japonic'
  | 'Koreanic'
  | 'Uralic'
  | 'Tai-Kadai'
  | 'Austroasiatic'
  | 'Language Isolate'
  | 'Kartvelian'
  | 'Mongolic'
  | 'Tungusic'
  | 'Quechuan'
  | 'Arawakan'
  | 'Tupian'
  | 'Nilo-Saharan'
  | 'Hmong-Mien'
  | 'Trans-New Guinea'
  | 'Creole'
  | 'Sign Language';

type WritingSystemType =
  | 'alphabet'
  | 'abjad'
  | 'abugida'
  | 'syllabary'
  | 'logographic'
  | 'featural'
  | 'alphasyllabary';

type ScriptDirectionality = 'LTR' | 'RTL' | 'TTB';
type WordOrder = 'SOV' | 'SVO' | 'VSO' | 'VOS' | 'OVS' | 'OSV' | 'Free';
type MorphologicalType =
  | 'analytic'
  | 'synthetic'
  | 'agglutinative'
  | 'fusional'
  | 'polysynthetic';

type PartOfSpeech =
  | 'noun'
  | 'verb'
  | 'adjective'
  | 'adverb'
  | 'pronoun'
  | 'preposition'
  | 'conjunction'
  | 'determiner'
  | 'interjection'
  | 'numeral'
  | 'particle'
  | 'auxiliary';

WritingSystem, UnicodeRange, TypologicalFeatures, and LanguageMetadata record full script and typological metadata. The exported registries and accessors are: LANGUAGE_DATABASE, WRITING_SYSTEMS, getLanguage, getAllLanguages, getLanguageFamily, getLanguageSubfamily, getRelatedLanguages, getLanguagesInFamily, getTypologicalFeatures, getLanguageDistance, getWritingSystem, getAllWritingSystems, getUnicodeRanges. The langCode helper brands a raw string as a LanguageCode.

Cross-language vocabulary relationships: COGNATE_DATABASE / getCognates and FALSE_FRIENDS_DATABASE / getFalseFriends / findFalseFriend cover cross-language cognates and false friends (CognateEntry, FalseFriendEntry).

4.2 Vocabulary Types#

Each VocabularyItem carries the word's cross-language translations, example sentences, typical collocations, and CEFR level so exercises can be tailored to the learner's current proficiency:

typescript
type Register =
  | 'informal'
  | 'neutral'
  | 'formal'
  | 'literary'
  | 'slang'
  | 'technical';

interface VocabularyItem {
  word: string;
  language: LanguageCode;
  translations: Record<string, string>; // keyed by language code
  exampleSentences: ExampleSentence[];
  collocations: string[];
  register: Register;
  cefrLevel: CEFRLevel;
  partOfSpeech: PartOfSpeech;
  ipa?: string;
  audioUrl?: string;
  notes?: string;
}

Supporting vocabulary types: ExampleSentence, ThematicModule, ThemeCategory (20 categories: travel, food_dining, shopping, health_medical, business, technology, education, family, housing, transportation, weather, sports, entertainment, law_government, environment, arts_culture, science, emotions, work_career, daily_routines), ThematicActivity, VocabularyCoverage, WordFamily, WordFamilyMember, DerivationType, MnemonicKeyword, CoverageOptions.

Vocabulary functions and constants include CEFR_VOCABULARY_SIZE, COVERAGE_THRESHOLDS, estimateCEFRFromVocabSize, estimateVocabSizeFromCEFR, getVocabSizeRange, estimateCoverageFromVocabSize, getFrequencyList, generateFrequencyList, calculateCoverage, getThematicModules, getThematicModule, getModulesForLevel, expandWordFamily, getDerivationPatterns, generateMnemonic, SAMPLE_MNEMONICS. DEFAULT_COVERAGE_OPTIONS uses 0.95 (extensive) / 0.90 (assisted) reading thresholds, word families on, proper nouns counted as known.

4.3 Grammar Types#

Grammar types cover both reference data (rules, paradigms, patterns) and exercise generation:

GrammarRule, GrammarExample, MorphologicalParadigm, ParadigmForm, SyntacticPattern, PatternSlot, GrammarExerciseType (fill_in, transform, error_correct, judgment, multiple_choice, sentence_build, conjugate), GrammarExercise, ContrastiveAnalysis, TransferError.

Grammar functions: getGrammarRules, getGrammarRulesForLevel, getGrammarRule, getGrammarRulesByTopic, getParadigms, getParadigm, getForm, getSyntacticPatterns, getSyntacticPattern, generateFillInBlank, generateTransformation, generateErrorCorrection, generateGrammaticalityJudgment, generateMultipleChoice, getContrastiveAnalysis, getContrastiveAnalyses, getTransferErrors, getPredictedDifficulty.

4.4 Reading and Frequency Analysis#

Reading analysis types model both text properties and learner comprehension skills:

TextDifficulty, VocabularyProfile (K1/K2/K3/offList bands), ComprehensionSkill (literal, inferential, evaluative, main_idea, vocabulary_in_context, author_purpose, text_structure), ComprehensionQuestion, ReadingMetrics, TextAnalysisResult.

Reading functions: countSyllables, splitSentences, tokenizeWords, fleschReadingEase, fleschKincaidGradeLevel, fleschToCEFR, analyzeVocabularyProfile, analyzeTextDifficulty, analyzeVocabularyCoverage, analyzeText, generateLiteralQuestion, generateInferentialQuestion, generateMainIdeaQuestion, generateVocabularyQuestion, calculateReadingMetrics, recommendReadingApproach.

Corpus frequency bands (frequency-bands.ts): BandLabel, FrequencyBands, SUPPORTED_BAND_LANGUAGES, getDefaultBands, getWordBand, profileFromCorpus. The package ships real corpus data under libs/mnemosyne/polyglot/data/: en-frequency-bands.json (New General Service List v1.2, 2,801 headwords) and es-frequency-bands.json (top-3000 Spanish lemmas), each grouped into K1/K2/K3 bands per Laufer & Nation's Lexical Frequency Profile.

4.5 Phonetic Transcription#

phonetic.ts exports: wordToIPA, phoneticSimilarity, tokenizeIPA, detectLanguage, and the DetectedLanguage type.

4.6 CEFR Mapping#

All three international proficiency scales are supported with bidirectional mapping between them:

LanguageSkill (reading, writing, listening, speaking, interaction), CEFRSkillDescriptor, CEFRProgressReport, SkillEstimate, ProficiencyEstimate, StandardizedTestType (IELTS, TOEFL_iBT, TOEFL_PBT, Cambridge, DELF_DALF, Goethe, DELE, JLPT, HSK, TOPIK, TestDaF), TestScoreMapping, CEFREvidence.

CEFR functions: CEFR_SKILL_DESCRIPTORS, getCEFRDescriptors, getCEFRDescriptorsForSkill, getCEFRDescriptor, mapToILR, mapToACTFL, mapILRToCEFR, mapACTFLToCEFR, cefrToNumericScore, numericScoreToCEFR, mapToCEFR, estimateCEFRLevel, createProficiencyEstimate, compareCEFRLevels, nextCEFRLevel, previousCEFRLevel, cefrRange.

@mnemosyne/polyglot also implements extended skill descriptors (skills-extended.ts) and extended vocabulary/grammar modules (vocab-grammar-extended.ts).


5. Classical Tools (@mnemosyne/classical-tools)#

The classical tools package supports assisted reading of ancient texts in seven languages. The ClassicalLanguage union names those languages; the types below describe the morphological, syntactic, and annotation structures needed for an Alpheios-style reading environment.

typescript
type ClassicalLanguage = …;   // Latin, Ancient Greek, Sanskrit, Classical
                              // Arabic, Biblical Hebrew, Old Church Slavonic,
                              // Classical Syriac
type GrammaticalCase = …;
type VerbTense = …;  type VerbMood = …;  type VerbVoice = …;

Domain types: MorphologicalForm, MorphologicalAnalysis, DictionaryEntry, DictionaryExample, DictionarySource, ParadigmCell, ParadigmTable, GrammarReference, TreebankToken, TreebankAnnotation, SyntacticRelation, AlignmentPair, TranslationAlignment, ClassicalReadingProgress, VocabularyListEntry, PassageDifficultyAssessment, ReadingCheckpoint, CheckpointQuestion, AnnotationLayer, TextAnnotation, AnnotationMedia, CrossReference, MapReference, StudyGuide, StudyGuideSection, AnnotationQuizQuestion, CollaborativeAnnotationEdit, AnnotationExport, CoreVocabularyList, CoreVocabularyEntry, CEFREquivalent.

Functions include describeMorphForm, createMorphologicalAnalysis, buildDictionaryLookupUrl, buildLatinFirstDeclensionParadigm, buildGreekThematicVerbParadigm, GRAMMAR_REFERENCES / findGrammarReferences, getTokenDependents, getTokenPath, createTranslationAlignment, createReadingProgress, recordWordLookup, createVocabularyListEntry, assessPassageDifficulty, createReadingCheckpoint, createTextAnnotation, generateStudyGuide, generateQuizFromAnnotations, proposeAnnotationEdit, applyAnnotationEdit, exportAnnotations.


6. Phonetics (@mnemosyne/phonetics)#

The phonetics package is organized across six source modules covering the full IPA system and language-specific phonological features:

  • IPA databasePULMONIC_CONSONANTS, IPA_VOWELS, IPA_DIACRITICS, IPA_SUPRASEGMENTALS, ALL_IPA_ENTRIES constant arrays. Accessors: getIPAEntry, getIPAEntryByName, getConsonantsByFeatures, getVowelsByFeatures, describeSymbol, getDiacritic, getDiacriticsByCategory. Feature types: PlaceOfArticulation, MannerOfArticulation, VowelHeight, VowelBackness, Voicing, VowelRounding, with PLACES_OF_ARTICULATION / MANNERS_OF_ARTICULATION / VOWEL_HEIGHTS / VOWEL_BACKNESSES ordered constants.
  • Phoneme inventorygetPhonemeInventory, getAvailableLanguages, compareInventories, identifyDifficultPhonemes, getPhonemeDistribution; types Phoneme, PhonemeInventory, InventoryDiphthong.
  • Minimal pairsgenerateMinimalPairs, getAvailableContrasts, rankMinimalPairDifficulty, generateDiscriminationExercise.
  • Tone systemsgetToneSystem, getTonalLanguages, applyMandarinSandhi, getMandarinToneValue, getCantoneseToneValue, getToneSandhiRules, isTonalLanguage, compareToneSystems.
  • ProsodypredictStressedSyllableIndex, analyzeStressPattern, analyzeSentenceStress, analyzeRhythm, identifyConnectedSpeechRules, getConnectedSpeechRulesByType, getSyllableStructure, getAllRhythmProfiles, compareRhythm.

7. Heritage (@mnemosyne/heritage)#

The heritage package models the full pipeline from physical digitization through digital archiving to legal provenance documentation. Key enum types establish the vocabulary of methods and classification systems used in conservation science:

typescript
type DigitizationMethod = …;        // photogrammetry, structured light, …
type FileFormat3D = …;              // OBJ, STL, PLY, glTF, …
type ReconstructionUncertainty = …;
type ConditionGrade =
  | 'excellent' | 'good' | 'fair' | 'poor' | 'critical';
type ICHDomain = …;                 // UNESCO intangible-heritage domains

Selected interfaces and constants organized by area:

Digitization: PhotogrammetryPipeline / PHOTOGRAMMETRY_PIPELINE, StructuredLightScanner / STRUCTURED_LIGHT_SCANNING, LiDARProcessingConfig / LIDAR_PROCESSING, CTScanVisualization / CT_SCAN_VISUALIZATION, RTIConfiguration / RTI_CONFIGURATION, MultiSpectralImaging / MULTISPECTRAL_IMAGING, MeshOptimizationConfig, AnnotationModel, MeasurementResult, ChangeDetectionResult, PointCloud.

Virtual reconstruction: ArchitecturalReconstruction, LONDON_CHARTER_PRINCIPLES, SEVILLE_PRINCIPLES, VirtualAnastylosis, PolychromyReconstruction / CLASSICAL_POLYCHROMY_PIGMENTS, UncertaintyVisualization, PhaseTimeline.

Digital archiving: OAISModel / OAIS_MODEL, PREMISMetadata, DublinCoreRecord, METSDocument, EADFindingAid, FormatMigrationPlan / FORMAT_RISK_REGISTRY, DOIAssignment, OAIPMHRecord, FAIR_PRINCIPLES_CHECKLIST.

Virtual museums: VirtualGallery, VirtualMuseumObject, GuidedTour, ExhibitionSchedule, VisitorAnalytics.

Conservation: ConditionAssessment / CONDITION_ASSESSMENT_TEMPLATES, TreatmentRecord, CONSERVATION_MATERIALS_DATABASE, EnvironmentalMonitoring / ICCROM_ENVIRONMENTAL_STANDARDS, RiskAssessment.

Provenance and repatriation: ProvenanceChain, ArtLossRecord, NAZI_ERA_PROVENANCE_GUIDELINES, ColonialAcquisitionAnalysis, RepatriationClaim / REPATRIATION_LEGAL_FRAMEWORKS, BlockchainProvenanceRecord.

Intangible heritage: UNESCOICHElement / INTANGIBLE_HERITAGE_EXAMPLES, OralHistoryInterview, TraditionalKnowledgeRecord / LOCAL_CONTEXTS_TK_LABELS, PerformanceCaptureSession / LABANOTATION_SYMBOLS, FoodwaysDocumentation, UNESCOICHSafeguardingPlan.

Functions: create3DAnnotation, measureDistance, compareScans, calculateReconstructionCompleteness, buildPhaseTimeline, createPREMISObject, verifyChecksum, assignDOI, createVirtualGallery, addObjectToGallery, calculateRiskScore, generateProvenanceReport, createICHSafeguardingPlan. The package exports a HERITAGE_CAPABILITIES summary constant.


8. Temporal — History / Archaeology / Anthropology (@mnemosyne/temporal)#

The temporal package models historical knowledge structurally: events have typed dates, people exist in prosopographical networks, sites have stratigraphic sequences, and artifacts have classification schemas.

HistoricalDate uses a CalendarSystem tag to indicate which calendar a date is expressed in. Note that the package does not currently implement cross-calendar numeric conversion functions; CalendarSystem is a classification tag, not a conversion engine.

typescript
type CalendarSystem =
  | 'gregorian'
  | 'julian'
  | 'coptic'
  | 'islamic'
  | 'hebrew'
  | 'chinese'
  | 'mayan'
  | 'roman'
  | 'egyptian';

type DateCertainty =
  | 'exact'
  | 'approximate'
  | 'circa'
  | 'terminus_post_quem'
  | 'terminus_ante_quem'
  | 'floruit';

interface HistoricalDate {
  year: number; // negative = BCE
  month?: number;
  day?: number;
  calendar: CalendarSystem;
  certainty: DateCertainty;
  label?: string; // e.g. "ca. 480 BCE", "fl. 5th c. BCE"
}

The HistoricalEvent type connects events causally and geographically:

typescript
type EventType =
  | 'battle'
  | 'treaty'
  | 'coronation'
  | 'death'
  | 'birth'
  | 'migration'
  | 'founding'
  | 'disaster'
  | 'invention'
  | 'trade_contact'
  | 'religious'
  | 'political'
  | 'cultural';

interface HistoricalEvent {
  id: string;
  name: string;
  date: HistoricalDate;
  dateEnd?: HistoricalDate;
  type: EventType;
  location?: GeographicPoint;
  participants: string[]; // person / polity ids
  description: string;
  sources: HistoricalSource[];
  causes?: string[]; // event ids
  consequences?: string[]; // event ids
  significance: 'local' | 'regional' | 'civilizational' | 'global';
  tags: string[];
}

Further types, organized by sub-domain:

Historiography: HistoricalPeriod, HistoricalSource (with a 1-5 reliability score), HistoriographyEntry, HistoriographicalSchool (12 schools), CausationChain, CausationFactor, CausationConsequence.

Prosopography: HistoricalPerson, PersonName, PersonRelationship, RelationshipType, GenealogicalTree, GenealogicalNode, ProsopographicalNetwork, NetworkNode, NetworkEdge, SocialStatus.

Geography: GeographicPoint, GeographicRegion, PopulationEstimate, BorderChange, TradeRoute, TradedCommodity, MigrationEvent.

Archaeology: ArchaeologicalSite, SiteType, StratigraphicLayer, DatingMethod, DateEstimate, ArtifactRecord, ArtifactCategory.

AI discovery: SatelliteImageryFeature, PredictiveModel, PredictiveVariable, SitePrediction, PatternRecognitionResult.

Anthropology: KinshipSystem, KinshipTerminologySystem, RitualSystem, CulturalMaterialSystem, EthnographicRecord.

Bioarchaeology: SkeletalAnalysisResult, AgeAtDeath, SkeletalPathology, ActivityMarker, DentitionAnalysis, AncientDNAResult, AdmixtureComponent, IsotopeAnalysis, Taxon.

Economic history: HistoricalCurrency, PriceSeriesEntry, EconomicSystem, EconomicRegime, TradeNetworkNode.

Data constants include HISTORICAL_PERIODS, HISTORICAL_TRADE_ROUTES, ARCHAEOLOGICAL_SITES, KINSHIP_SYSTEMS, and HOMO_LINEAGE. Functions include getPeriodByYear, formatHistoricalDate, yearSpan, buildCausationChain, rankCausationFactors, buildGenealogicalTree, computeNetworkCentrality, findShortestRelationshipPath, calculateRouteLength, haversineDistance, routeSpanYears, computeStratigraphicSequence, findArtifactsByCategory, getBestDateEstimate, scoreFeatureSignificance, clusterFeaturesProximity, runPredictiveModel, detectRitualLandscape, classifyKinshipSystem, analyzeRitualStructure, computeCulturalDiffusion, estimateDietFromIsotopes, isMigrant, estimateLifeExpectancy, assessNutritionalStatus.


9. Experience — Adaptive Learning Engine (@mnemosyne/experience)#

@mnemosyne/experience is the adaptive learning, gamification, and analytics engine. It is where dynamic skill modelling (BKT, DKT), Zone of Proximal Development management, and the core gamification loop all live.

9.1 Knowledge Tracing#

BKT models the latent probability that a learner has truly mastered a skill. The four parameters capture the probabilistic nature of learning and performance:

typescript
interface BKTParams {
  p_init;
  p_learn;
  p_slip;
  p_guess;
} // four params
interface BKTState {
  skillId;
  p_known;
  observationCount;
}

const DEFAULT_BKT_PARAMS: BKTParams;

updateBKT(state, params, correct) applies the Bayesian Knowledge Tracing update rule; initBKTState initialises state for a new skill.

Deep Knowledge Tracing uses an LSTM-style decay model: DKTFeatureVector, DKTState, initDKTState, updateDKTState.

9.2 Trajectory and ZPD#

These types and functions keep the learner working at appropriate difficulty by reasoning about Zone of Proximal Development:

LearningItem, TrajectoryConfig, optimiseLearningTrajectory, sequenceByPrerequisites (topological ordering, returns null on cycle). ZPDZone (too_easy / zpd / too_hard), classifyZPD. CognitiveLoadEstimate + estimateCognitiveLoad (this package's own variant, distinct from @mnemosyne/core's version). Multi-armed bandit: BanditArm, ucb1SelectArm, updateBanditArm. Reinforcement-learning policy: RLState, RLAction, selectRLAction.

9.3 Learner Modelling#

Learner modelling types track cognitive style, daily performance patterns, fatigue, and session calibration:

ContentModality (visual / auditory / reading / kinesthetic), LearningStyleProfile, createLearningStyleProfile, updateLearningStylePreference; TimeOfDayProfile, buildTimeOfDayProfile; FatigueModel, estimateFatigue; SessionLengthRecommendation, recommendSessionLength; ReviewNewBalance, balanceReviewNew; DifficultyRamp, calibrateDifficultyRamp. A/B testing: ABTestVariant, ABTest, createABTest, assignABTestVariant, concludeABTest.

9.4 Gamification#

The gamification system provides XP economy, achievements, social structures, and accessibility tooling. Key types and constants:

LevelDefinition + LEVEL_DEFINITIONS constant; UserXPState, calculateLevel, awardXP, XP_REWARDS constant. Achievements: AchievementCategory, Achievement, ACHIEVEMENT_CATALOG, checkAchievements. Streaks: StreakState, updateStreak. Challenges: Challenge, generateDailyChallenges. Leaderboards: LeaderboardEntry, LeaderboardType (global / friends / league / weekly), buildLeaderboard. Leagues: League (BronzeObsidian), LeagueDefinition, LEAGUE_DEFINITIONS, determineLeaguePromotion. Economy: VirtualCurrency, ShopItem, SHOP_CATALOG, purchaseShopItem. Avatars: AvatarConfig, AVATAR_BASE_STYLES, AVATAR_ACCESSORIES, BACKGROUND_SCENES, createDefaultAvatar. Social: UserProfile, ShareableCard, createShareableCard, TeamChallenge, updateTeamChallengeProgress, StudyGroup, createStudyGroup, joinStudyGroup, TutorProfile, TuteeRequest, matchTutorTutee. Skill trees: SkillNode, SkillTree, HUMANITIES_SKILL_TREE. Certificates and quests: Certificate, issueCertificate, Quest, SAMPLE_QUESTS.


10. Gamification-Plus (@mnemosyne/gamification-plus)#

@mnemosyne/gamification-plus adds advanced, Duolingo-style competitive gamification. It is a self-contained library with no code dependency on @mnemosyne/experience. The six-tier league system is the primary new concept it introduces:

typescript
type LeagueTier =
  | 'Bronze'
  | 'Silver'
  | 'Gold'
  | 'Platinum'
  | 'Diamond'
  | 'Obsidian';
type LeagueStatus = 'active' | 'promotion_zone' | 'demotion_zone';

LEAGUE_DEFINITIONS is a Record<LeagueTier, LeagueDefinition>. League functions: createLeague, addParticipantToLeague, rankLeague, resolveLeagueWeek (computes promotions / demotions), getNextTier, getPreviousTier, matchLeaguesByActivity. Types: LeagueDefinition, LeagueParticipant, League.

XP multiplier events: XPMultiplierEvent, createXPMultiplierEvent, getActiveXPMultiplier. Friend challenges: ChallengeStatus, FriendChallenge, createFriendChallenge, acceptChallenge, updateChallengeProgress. Team leagues: TeamLeague, Team, createTeam, updateTeamXP. League achievements: LeagueAchievementId, LeagueAchievement, LEAGUE_ACHIEVEMENTS, checkLeagueAchievements. Anti-gaming: AntiGamingAnalysis, analyseAntiGaming.

Streak milestones are defined at specific day counts, and the system awards multiplied XP for reaching them:

text
STREAK_MILESTONES: [3, 7, 14, 21, 30, 60, 100, 150, 200, 365, 500, 1000]

Streak functions: StreakState, STREAK_MILESTONES, STREAK_XP_MULTIPLIERS, computeStreakMultiplier, createStreakState, updateStreak, streakRepairCost, repairStreak, checkMilestone, celebrateMilestone, purchaseStreakFreeze, purchaseStreakInsurance, activateGracePeriod.

Habits and scheduling: HabitTracker, createHabitTracker, updateHabitTracker, StudySchedule, StudyReminder, CalendarEvent, createStudySchedule, generateCalendarEvents, buildStreakSocialShareText.

Seasonal events: EventType, LearningEvent, EventReward, EventBadge, CommunityGoal, ContentPack, PartnerInfo, EventLeaderboardEntry, createLearningEvent, updateCommunityGoal, getCountdownSeconds, addEventLeaderboardEntry, SAMPLE_SEASONAL_EVENTS, UserEventProposal, createEventProposal, getActiveEvents, getUpcomingEvents.


11. Immersion (@mnemosyne/immersion)#

The immersion package implements comprehensible-input and immersion methodology across four sub-domains: general difficulty scoring, sentence mining, video immersion, reading immersion, and listening immersion.

  • Morpheme analysisMorphemeFrequency, MorphemeAnalysis, FREQUENCY_SAMPLES, analyseMorphemes.
  • Difficulty / comprehensionSentenceDifficultyScore, scoreSentenceDifficulty, estimateComprehension, ImmersionContent, buildDifficultyLadder, recommendIPlus1Content (i+1 content selection).
  • Refold stagingRefoldStage (1-4), RefoldStageDefinition, REFOLD_STAGES, determineRefoldStage.
  • Immersion sessionsImmersionMode (active / passive / intensive), ImmersionSessionRecord, createImmersionSession, ImmersionStats, computeStreaks, computeImmersionStats, WordDensityMap, buildWordDensityMap.
  • Acquisition vs learningAcquisitionMode, AcquisitionProfile, analyseAcquisitionBalance.
  • Sentence miningMinedSentence, SubtitleEntry, parseSRT (SRT subtitle parser), extractMiningSentences, filterOneTargetSentences (1T sentences), SentenceQualityFactors, scoreSentenceQuality, computeJaccardSentenceSimilarity, detectNearDuplicates, BilingualSubtitle, alignBilingualSubtitles, CardTemplate, CardTemplateDefinition, CARD_TEMPLATES.
  • Video immersionVideoDifficultyTier, VideoDifficultyDefinition, VIDEO_DIFFICULTY_TIERS, VideoContent, CreatorProfile, classifyVideoDifficulty, SubtitleWord, InteractiveSubtitle, buildInteractiveSubtitle, VideoWatchHistoryRecord.
  • Reading immersionWordStatus (1|2|3|4|5|'known'|'ignored'), TrackedWord, createTrackedWord, advanceWordStatus, WORD_FAMILIARITY_LEVELS, ReadingSessionRecord, createReadingSession, computeReadingStats, GradedReader, GRADED_READER_CATALOG, ParallelTextSegment, buildParallelText, PopupDictionaryEntry, buildPopupEntry.
  • Listening immersionPodcastFeed, PodcastEpisode, SAMPLE_COMPREHENSIBLE_PODCASTS, AudioCondensationConfig, DEFAULT_CONDENSATION_CONFIG, AudioTimestamp, ListeningJournalEntry, createListeningJournalEntry, ListeningLevelAssessment, assessListeningLevel, recommendPodcasts, ListeningExerciseType, ListeningExercise, generateGapFillExercise, ListeningQuizQuestion, generateComprehensionQuiz, RadioStation, SAMPLE_RADIO_STATIONS.

The package exports an IMMERSION_CAPABILITIES summary constant.


12. Community (@mnemosyne/community)#

The community package provides language-exchange and peer-learning infrastructure. It is the only package in the domain that models real-time social interactions (voice rooms, whiteboard).

  • Partner matchingLanguageProfile, ExchangeProfile, MatchScore, computeMatchScore, findLanguagePartners; PartnerRating, createPartnerRating, computeAverageRating; ReportReason, UserReport, createUserReport.
  • Exchange sessionsExchangeSessionStatus, ExchangeSession, scheduleExchangeSession, checkTimeSplitBalance; PartnerRelationship, createPartnerRelationship, updatePartnerRelationship.
  • Chat with inline correctionMessageType, CorrectionType, InlineCorrection, ChatMessage, createTextMessage, applyInlineCorrection, renderCorrectionMarkup, saveVocabularyFromCorrection; ConversationTopicSuggestion, TOPIC_SUGGESTIONS, suggestConversationTopics.
  • Transliteration (transliteration.ts) — TransliterationRequest, TransliterationResult, buildTransliterationRequest, and a transliterate dispatcher backed by per-script implementations: transliterateKanaSequence, transliterateKanji, transliterateHangul, transliterateCyrillic, transliterateArabic, transliterateDevanagari, transliterateThai, transliterateGeorgian.
  • WhiteboardWhiteboardElement, Whiteboard, createWhiteboard, addWhiteboardElement.
  • Social momentsMomentType, MomentVisibility, Moment, MomentCorrection, createMoment, addMomentCorrection, filterMomentsForLearner, MomentAnalytics, computeMomentAnalytics; WritingPrompt, WRITING_PROMPTS, detectSpam.
  • Voice roomsRoomStatus, ParticipantRole, VoiceRoomParticipant, VoiceRoom, LiveTranscriptSegment, RoomParticipationStats, createVoiceRoom, joinVoiceRoom, toggleHandRaise.

13. Platform — Integration Library (@mnemosyne/platform)#

@mnemosyne/platform provides data interchange and external-service integration descriptors. Like the rest of the domain, it is a pure library: it builds request URLs and parses payloads, but does not itself perform network I/O.

  • Anki interchangeAnkiField, AnkiNote, AnkiDeck, AnkiNoteModel; parseAnkiDeck (parses a simplified Anki deck JSON export — an .apkg deconstruction, not the binary archive) and exportAnkiDeck.
  • CSV vocabularyVocabularyEntry, CSVImportResult, parseCSVVocabulary.
  • LMS / e-learning standardsSCORMManifest + parseSCORMManifest; XAPIStatement, XAPI_VERBS, createXAPIStatement; LTIConfig, LTILaunchParams, validateLTILaunch.
  • Reference managersZoteroItem, parseZoteroExport.
  • Portable data / privacyPortableProgressData, buildPortableProgressData; GDPRDataPackage, buildGDPRPackage.
  • Public API descriptorsAPIEndpointDefinition and the PUBLIC_API_ENDPOINTS constant describe a REST surface a hosting application could expose; they are declarative metadata, not a server.
  • External content connectors (URL builders + payload parsers) — Wikipedia / Wikidata (buildWikipediaSearchUrl, buildWikidataSparqlUrl, extractLearningContentFromWikipedia), Europeana (buildEuropeanaSearchQuery), Internet Archive (buildArchiveSearchUrl), dictionaries (DICTIONARY_PROVIDERS), translation (TRANSLATION_PROVIDER_CONFIGS), museum APIs (MUSEUM_API_CONFIGS, buildMetObjectSearchUrl), and library catalogs (buildSRUQueryUrl).
  • LLM configurationLLMProvider, LLMConfig (configuration shapes for consuming applications).

14. Other Domain Libraries#

The table below covers the five remaining packages, listing their most significant exported symbols. Each is fully implemented with domain-specific algorithms and real data constants.

Library Coverage (selected)
@mnemosyne/linguistics Morphology (segmentMorphemes, parseMorphology, buildInflectionalParadigm, analyzeCompound, buildMorphologicalFamilyTree, classifyMorphologicalTypology), syntax (parseDependency, buildXBarStructure, parseConstituency, analyzeArgumentStructure, analyzeBinding, analyzeControlRaising, analyzeSyntacticMovement), and semantics (LogicalForm, LambdaTerm, TruthCondition, QuantifierScope, SemanticFrame, thematic roles)
@mnemosyne/philology Classical curricula (ANCIENT_GREEK_CURRICULUM, LATIN_CURRICULUM, SANSKRIT_CURRICULUM, CLASSICAL_CURRICULA_DATABASE), script modules (Greek, Cuneiform, Hieroglyphic, Devanagari, Chinese radicals), and textual criticism (Leiden conventions, TEI: tokenizeLeiden, renderLeidenText, leidenToTEI, buildStemma, collateTexts, detectVariants, generateTEIXML, generateApparatusCriticusLine)
@mnemosyne/mythology Pantheon databases (DEITY_DATABASE, HERO_DATABASE, CREATURE_DATABASE, SACRED_PLACES, SACRED_OBJECTS, cosmogony / flood / underworld myths), comparative analysis (HERO_JOURNEY_STAGES, JUNGIAN_ARCHETYPES, MYTHEMES, ATU_TALE_INDEX, THOMPSON_MOTIFS_SAMPLE, classifyTaleType, extractMotifs), sacred-text and world-religion data
@mnemosyne/aesthetics Artwork schema and search (ArtworkSchema, searchArtworkDatabase, IIIF manifests, CIDOC-CRM mapping, Getty AAT), visual analysis (classifyArtworkStyle, analyzeAttribution, analyzeColorPalette, detectForgeryIndicators), iconography (ICONOGRAPHIC_SYMBOLS, SAINT_ATTRIBUTES, HERALDRY_DATABASE, identifySaint), period modules, global traditions, architecture (CLASSICAL_ORDERS, ARCHITECTURAL_GLOSSARY)
@mnemosyne/rhetoric Grammar (analyzeSentenceStructure, identifyPartOfSpeech, diagramSentence), logic (LOGIC_SYMBOLS, evaluateTruthTable, generateTruthTable, SYLLOGISM_FORMS, LOGICAL_FALLACIES, detectFallacy, COGNITIVE_BIASES), rhetoric (CLASSICAL_RHETORICIANS, TOPOI, STASIS_THEORY, CANONS_OF_RHETORIC, analyzeRhetoricalSituation), disputation (SOCRATIC_MOVES, DISPUTATIO_EXAMPLES), speech (SPEECH_DELIVERY_RUBRIC), citation (generateCitation, CRAAP source evaluation)
@mnemosyne/pronunciation Pronunciation scoring (computeOverallPronunciationScore, identifyWeakPoints), L1 error patterns (L1_ERROR_DATABASE, getL1Errors), pronunciation dictionary with crowd-sourced recordings (createDictionaryEntry, createRecording, moderateRecording, voteRecording), offline packs, AI voice coach (VoiceCoachSession, addTurn, adaptDifficulty, generateUtteranceFeedback, detectFillerWords), speaking certificates
@mnemosyne/writing Grammar checking (GRAMMAR_RULES, buildGrammarCheckResult), readability (computeReadability, per-language syllable counters), formality and repetition analysis, writing prompts (WRITING_PROMPTS, generateDailyPrompt), rubric scoring (IELTS_TASK2_RUBRIC, computeRubricScore), genre templates, peer review, portfolios, writing streaks
@mnemosyne/knowledge-graph Standalone knowledge-graph operations package (separate from @mnemosyne/core's KnowledgeGraph class)

15. Validation, Invariants, and Acceptance Criteria#

Input Validation#

Each package declares zod as a runtime dependency for schema validation. Algorithmic functions enforce input invariants directly with RangeError rather than silently producing incorrect results:

  • calculateRetention rejects non-positive stability.
  • irt2PL / irt3PL reject non-positive discrimination.
  • irt3PL rejects a guessing parameter outside [0, 1).
  • fsrsInterval requires requestRetention ∈ (0, 1).

Invariants Enforced in Code#

These invariants are maintained by the implementation and cannot be violated through normal function calls:

  • SM-2 ease factor is clamped to a minimum of 1.3.
  • FSRS difficulty is clamped to [1, 10]; stability has a floor of 0.1; a lapse never increases stability.
  • FSRS intervals are clamped to [1, maximumInterval].
  • KnowledgeGraph.addEdge rejects edges whose source or target node is absent.
  • KnowledgeGraph.topologicalSort throws when a cycle exists in the prerequisite sub-graph.
  • CertificationManager.issueCredential returns null unless every requirement is satisfied.
  • PeerAssessmentManager.createAssignments skips a reviewer who is the author.
  • Adaptive difficulty does not adjust until minResponsesBeforeAdjust responses have been observed.

Acceptance Criteria#

Every package ships a co-located Vitest suite (src/<name>.test.ts, plus *-extended.test.ts where the package is split). The tests assert domain correctness against known values — they would fail on random or hardcoded returns. Representative concrete assertions from the test suite:

  • MASTERY_LEVELS.length === 6
  • ILR_LEVELS.length === 11
  • FSRS_DEFAULT_PARAMETERS.w.length === 17
  • FSRS_DEFAULT_PARAMETERS.requestRetention === 0.9
  • DEFAULT_CAT_CONFIG.maxItems === 50
  • REVIEW_GRADE_MAP mapping again/hard/good/easy → 1/2/3/4

A package is considered complete when its tsc build and vitest run pass and it provides genuine domain algorithms rather than only CRUD operations.


16. Configuration#

Mnemosyne libraries are pure, dependency-injected TypeScript. They do not read environment variables, connect to PostgreSQL/Redis, or call LLM/TTS services on their own. All configuration is supplied through typed function parameters and exported default constants that a consuming application can override.

Constant Package Purpose
FSRS_DEFAULT_PARAMETERS core FSRS v4 weight vector + retention
DEFAULT_CAT_CONFIG core CAT min/max items, SE threshold, strategy
DEFAULT_HLR_WEIGHTS core Half-Life Regression weights
DEFAULT_ADAPTIVE_DIFFICULTY_CONFIG core ZPD adaptive-difficulty controller
DEFAULT_CIRCADIAN_PROFILES core Per-phase circadian performance
DEFAULT_COMPLETION_CONFIG core LLM completion defaults
DEFAULT_CHUNKING_CONFIG core RAG document-chunking defaults
DEFAULT_AQG_CONFIG core Automatic-question-generation defaults
DEFAULT_COVERAGE_OPTIONS polyglot Vocabulary-coverage thresholds
DEFAULT_CONDENSATION_CONFIG immersion Audio-condensation defaults
DEFAULT_NORMALIZATION_SPEC pronunciation Audio-normalisation defaults

LLM-backed features accept an injected LLMProvider; with no provider they fall back to the deterministic template/algorithmic implementations described in §2.4. Any database, cache, embedding service, or HTTP layer is the responsibility of a consuming application. @mnemosyne/platform (§13) parses and emits Anki deck JSON and builds external-service request URLs, but binary .apkg archive handling, cross-calendar numeric conversion, webhook delivery, and a running HTTP server do not exist inside libs/mnemosyne/* today.


17. Integration Points#

Inbound Dependencies#

@mnemosyne/* packages import only zod and (for non-core packages) @mnemosyne/core. The AI infrastructure accepts an injected LLMProvider implementation from the caller. No package opens a network connection or reads a process environment variable.

Cross-Domain Boundary#

The Mnemosyne packages declare no @oshun/*, @sophia/*, or @metis/* dependency. This boundary is intentional: Mnemosyne is a library of pure learning-science and humanities-knowledge functions, not a service.

The data that would flow across this boundary if a consuming application chose to integrate Mnemosyne with other Oshun domains:

  • Outbound from Mnemosyne: LearnerProfile, AssessmentResult, KnowledgeItem, LearningPath, ReviewResult — structured learning records that other domains might use for enrichment or analytics.
  • Inbound to Mnemosyne: An LLMProvider implementation for AI-backed features; content payloads for the knowledge graph or vocabulary database.

Any cross-domain orchestration (Sophia knowledge enrichment, Metis assessment sharing) is assembled in a consuming application, not inside this domain.


18. Phase Reference#

Mnemosyne is implemented as Phase 39 of the Oshun migration plan (TODOS/phase-39.md), "Mnemosyne Domain — Humanistic Learning & Cultural Intelligence Platform". The table below maps sub-sections to the 19 libraries they cover.

Phase Library
39.1 @mnemosyne/core
39.2 @mnemosyne/polyglot
39.5 @mnemosyne/temporal
39.6 @mnemosyne/polyglot extensions
39.7 @mnemosyne/aesthetics
39.8 @mnemosyne/rhetoric
39.9 @mnemosyne/mythology
39.10 @mnemosyne/heritage
39.11 @mnemosyne/phonetics
39.11.5 @mnemosyne/linguistics
39.12 @mnemosyne/experience
39.13 @mnemosyne/platform
39.14 @mnemosyne/immersion
39.15 @mnemosyne/classical-tools
39.16 @mnemosyne/philology
39.17 @mnemosyne/pronunciation
39.18 @mnemosyne/writing
39.19 @mnemosyne/gamification-plus
39.20 @mnemosyne/community