src/cards.js
// Flashcard extraction, SM-2 scheduling and seeded quiz generation for study-assistant. Pure functions.
// Study material is untrusted data: it is pattern-matched into cards, never executed or followed.
import { createHash } from "node:crypto";
const DAY = 86400000;
export function stripInline(s) {
return s
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/`([^`]*)`/g, "$1")
.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "$2")
.replace(/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\w)/g, "$1$2")
.replace(/<\/?[A-Za-z][^>]*>/g, "")
.replace(/\s+/g, " ")
.trim();
}
function slug(s) {
return s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
}
export function cardId(front, back) {
return `c-${createHash("sha1").update(`${front}\u0000${back}`).digest("hex").slice(0, 12)}`;
}
function firstSentence(text) {
const m = /^(.+?[.!?])(?=\s+["'(\[]?[A-Z0-9]|\s*$)/s.exec(text);
return (m ? m[1] : text).trim();
}
const Q_RE = /^\s*(?:[-*+]\s+)?(?:\*\*|__)?(?:Q|Question)(?:\*\*|__)?\s*:(?:\*\*|__)?\s*(.*)$/i;
const A_RE = /^\s*(?:[-*+]\s+)?(?:\*\*|__)?(?:A|Answer)(?:\*\*|__)?\s*:(?:\*\*|__)?\s*(.*)$/i;
const HEADING_RE = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
const LIST_RE = /^\s*(?:[-*+]|\d+[.)])\s+/;
// Words that commonly start a "Label: text" list item without being a term to learn.
const LABEL_WORDS = new Set(["note", "notes", "nb", "example", "examples", "e.g", "eg", "tip", "tips", "hint", "see", "source", "sources", "todo", "to do", "warning", "important", "remember", "reminder", "date", "time", "due", "page", "pages", "chapter", "homework", "reading", "update", "edit", "summary"]);
// "term — definition", "term – definition", "term -- definition", "term :: definition",
// "**term**: definition" / "**term:** definition" (any line), and "- term: definition" (list items only,
// short terms, common labels such as "Note:" excluded).
function termLine(line) {
const isItem = LIST_RE.test(line);
const body = line.replace(LIST_RE, "");
let m = /^(.+?)\s*(?:—|–)\s*(.+)$/.exec(body);
if (m && (body.match(/[—–]/g) ?? []).length !== 1) m = null;
if (!m) m = /^(.+?)\s+--\s+(.+)$/.exec(body) ?? /^(.+?)\s*::\s*(.+)$/.exec(body);
if (!m) {
const b = /^(\*\*|__)([^*_:]+?)(:?)\1(:?)\s*(.+)$/.exec(body);
if (b && (b[3] || b[4]) && !(b[3] && b[4])) m = [b[0], b[2], b[5]];
}
if (!m && isItem) {
const p = /^([^:]{1,60}?):\s+(\S.*)$/.exec(body);
if (p && !/\d$/.test(p[1]) && !LABEL_WORDS.has(stripInline(p[1]).toLowerCase()) && stripInline(p[1]).split(/\s+/).length <= 5) m = p;
}
if (!m) return null;
const term = stripInline(m[1]).replace(/[:]$/, "").trim();
const def = stripInline(m[2]);
if (!term || !def || term.length > 80 || term.split(/\s+/).length > 8 || /[.!?;]$/.test(term)) return null;
return { term, def };
}
export function extractCards(text, { tags = [], deck, includeHeadings = true, nowIso }) {
const lines = String(text ?? "").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n");
const cards = [];
const skipped = [];
const seen = new Map();
const counts = { qa: 0, term: 0, heading: 0 };
let fence = null;
let heading = null; // {text, line, used}
let q = null; // {text, line}
let a = null; // {q, text, line}
let para = null; // {text, line} first prose paragraph after a heading
const sectionTags = () => {
const t = [...tags];
if (heading) { const s = slug(heading.text); if (s && !t.includes(s)) t.push(s); }
return t;
};
const add = (kind, front, back, line) => {
const f = front.trim();
const b = back.trim();
if (!f || !b) return;
const key = `${f.toLowerCase()}\u0000${b.toLowerCase().replace(/\s+/g, " ")}`;
if (seen.has(key)) { skipped.push({ line, reason: `Duplicate of card ${seen.get(key)}` }); return; }
const id = cardId(f, b);
seen.set(key, id);
counts[kind]++;
cards.push({ id, front: f, back: b, tags: sectionTags(), ...(deck ? { deck } : {}), kind, source_line: line, due: nowIso, interval_days: 0, ease: 2.5, repetitions: 0, lapses: 0 });
};
const closeAnswer = () => {
if (a) { add("qa", a.q.text, a.text, a.q.line); a = null; }
};
const closeQuestion = () => {
if (q) { skipped.push({ line: q.line, reason: "Question without an answer (expected an 'A:' line)" }); q = null; }
};
const closePara = () => {
if (para && heading && !heading.used && includeHeadings) {
add("heading", heading.text, firstSentence(para.text), heading.line);
heading.used = true;
}
para = null;
};
// A heading card pairs a heading with the first sentence of the prose paragraph directly under it.
// Any other first block (list, table, term line, Q/A, code) ends that chance, so a later unrelated
// paragraph is never paired with the heading.
const endIntro = () => {
closePara();
if (heading) heading.used = true;
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const n = i + 1;
const f = /^ {0,3}(`{3,}|~{3,})/.exec(line);
if (fence) { if (f && f[1][0] === fence[0] && /^ {0,3}(`{3,}|~{3,})\s*$/.test(line)) fence = null; continue; }
if (f) { closeAnswer(); closeQuestion(); endIntro(); fence = f[1]; continue; }
const h = HEADING_RE.exec(line);
if (h) {
closeAnswer(); closeQuestion(); closePara();
heading = { text: stripInline(h[2]), line: n, used: false };
continue;
}
if (!line.trim()) {
closeAnswer();
closePara();
if (q) q.afterBlank = true; // one blank line between Q: and A: is allowed
continue;
}
const qm = Q_RE.exec(line);
if (qm) {
closeAnswer(); closeQuestion(); endIntro();
q = { text: stripInline(qm[1]), line: n };
continue;
}
const am = A_RE.exec(line);
if (am) {
endIntro();
if (!q) { skipped.push({ line: n, reason: "Answer without a preceding 'Q:' line" }); continue; }
if (!q.text) { skipped.push({ line: q.line, reason: "Empty question" }); q = null; continue; }
a = { q, text: stripInline(am[1]), line: n };
q = null;
continue;
}
if (q?.afterBlank) closeQuestion(); // a paragraph after the blank line means the answer never came
if (a) { a.text = a.text ? `${a.text}\n${stripInline(line)}` : stripInline(line); continue; }
if (q) { q.text = `${q.text} ${stripInline(line)}`.trim(); continue; }
const t = termLine(line);
if (t) { endIntro(); add("term", t.term, t.def, n); continue; }
// Prose paragraph (not list, table, quote marker-only) right after a heading feeds a heading card.
if (LIST_RE.test(line) || /^\s*\|/.test(line)) endIntro();
else if (heading && !heading.used) {
const content = stripInline(line.replace(/^\s*>\s?/, ""));
if (content) para = para ? { ...para, text: `${para.text} ${content}` } : { text: content, line: n };
}
}
closeAnswer();
closeQuestion();
closePara();
return { cards, skipped, counts: { ...counts, total: cards.length } };
}
// ---------------------------------------------------------------------------------------------
// SM-2 (Wozniak, 1987/1990). EF' = EF + (0.1 - (5-q)(0.08 + (5-q)·0.02)), floor 1.3.
// q >= 3: I(1)=1, I(2)=6, I(n)=ceil(I(n-1)·EF) using the EF before this review.
// q < 3: repetitions restart (next interval 1 day); EF is still updated, as in common implementations.
// ---------------------------------------------------------------------------------------------
export function sm2(card, quality, nowMs) {
const prevEase = card.ease ?? 2.5;
const prevInterval = card.interval_days ?? 0;
const prevReps = card.repetitions ?? 0;
let repetitions;
let interval;
const lapse = quality < 3;
if (!lapse) {
if (prevReps === 0) interval = 1;
else if (prevReps === 1) interval = 6;
else interval = Math.max(1, Math.ceil(Number((Math.max(1, prevInterval) * prevEase).toFixed(6))));
repetitions = prevReps + 1;
} else {
repetitions = 0;
interval = 1;
}
const d = 5 - quality;
const ease = Math.max(1.3, Math.round((prevEase + (0.1 - d * (0.08 + d * 0.02))) * 100) / 100);
return {
repetitions,
interval_days: interval,
ease,
lapses: (card.lapses ?? 0) + (lapse ? 1 : 0),
due: new Date(nowMs + interval * DAY).toISOString(),
last_reviewed: new Date(nowMs).toISOString(),
lapse,
previous: { interval_days: prevInterval, ease: prevEase, repetitions: prevReps },
};
}
// ---------------------------------------------------------------------------------------------
// Seeded RNG (FNV-1a seed hash + mulberry32) and quiz generation
// ---------------------------------------------------------------------------------------------
function seedHash(seed) {
let h = 0x811c9dc5;
for (const ch of String(seed)) { h ^= ch.codePointAt(0); h = Math.imul(h, 0x01000193) >>> 0; }
return h >>> 0;
}
export function mulberry32(seed) {
let a = seedHash(seed);
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffle(arr, rnd) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rnd() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const norm = (s) => String(s).trim().toLowerCase().replace(/\s+/g, " ");
export function makeQuiz(cards, { count, choices, seed, dueOnly, nowMs }) {
const rnd = mulberry32(seed);
const notes = [];
const pool = dueOnly ? cards.filter((c) => !c.due || Date.parse(c.due) <= nowMs) : cards;
if (dueOnly) notes.push(`${pool.length} of ${cards.length} card(s) are due`);
const questions = [];
// Tags carried by every card (a deck or course tag) say nothing about which cards are related.
const tagCount = new Map();
for (const c of cards) for (const t of new Set(c.tags ?? [])) tagCount.set(t, (tagCount.get(t) ?? 0) + 1);
const specific = (c) => (c.tags ?? []).filter((t) => tagCount.get(t) < cards.length);
for (const card of shuffle(pool, rnd)) {
if (questions.length >= count) break;
const correct = norm(card.back);
const tagSet = new Set(specific(card));
const seenAns = new Set([correct]);
// Distractors come from other cards' answers (all cards, not just due ones), never invented.
// Preference: same kind of card (definition vs Q/A answer) and same section, then same kind, then
// same section, then anything, so wrong choices look like plausible answers to the prompt.
const tiers = [[], [], [], []];
for (const c of cards) {
if (c === card) continue;
const k = norm(c.back);
if (!k || seenAns.has(k)) continue;
seenAns.add(k);
const sameKind = Boolean(card.kind) && c.kind === card.kind;
const sameTag = specific(c).some((t) => tagSet.has(t));
tiers[sameKind && sameTag ? 0 : sameKind ? 1 : sameTag ? 2 : 3].push(c.back.trim());
}
const distractors = tiers.flatMap((t) => shuffle(t, rnd)).slice(0, choices - 1);
if (!distractors.length) { notes.push(`Card ${card.id} skipped: no other card has a different answer to use as a distractor`); continue; }
if (distractors.length < choices - 1) notes.push(`Card ${card.id} has only ${distractors.length + 1} choices (not enough distinct answers)`);
const opts = shuffle([card.back.trim(), ...distractors], rnd);
const answerIndex = opts.indexOf(card.back.trim());
questions.push({ n: questions.length + 1, card_id: card.id, prompt: card.front, choices: opts, answer_index: answerIndex, answer: card.back.trim() });
}
if (questions.length < count && pool.length) notes.push(`Requested ${count} question(s); generated ${questions.length}`);
return { questions, notes, available_cards: pool.length };
}