mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-05 01:29:15 +01:00
* Practice: choose or type, one switch above every question A remembered habit (heidi.practice.habit.v2) decides, for each word that has both, whether its meaning is chosen or its sentence typed. A flip swaps the questions still ahead one for one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Practice: a word typed right comes back later than one chosen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Practice: one hardness number for every question Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Plans: your own AI key is offered, and the pass card says what a pass is Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Knowledge map: a deterministic layout, and every node's state from the ledger lib/visual/knowledge-map is the first knowledge-map layout in the fleet, written to be extracted: plain data in, coordinates out, no app imports. Clusters packed into columns, nodes in rows under each cluster's name, labels wrapped with the real font's widths; no two cells meet, so no two labels can, at 320px as at 1280px. Same input, same picture. lib/domain/progress reads where a learner stands on every situation, grammar topic and word group (not started / started / shaky / solid / mastered) from the learner model, the review memory and the situation readings the situation pages already use, and orders the few lines worth acting on: the learner's own situations first, then new ones in their areas, then what wobbles, then the words that keep slipping. Nothing is counted in advance. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * «Was du kannst»: the map page, the weak-spots card, and the ways to it /[locale]/progress draws the whole course as a map coloured by the learner's own answers, with a legend and one motion (what is known fills in, off under reduced motion). Tapping a node opens a sheet with what it is, the numbers (asked, right, last seen, due) and «Üben», «Bis es sitzt» (goal=nail), and for a situation «Situation starten»; an area's name opens its situations and practises the whole area (module=…). Works signed out from this device and signed in with the synced views; with no data it is the course, not started, and where to begin. The card «Was sitzt, was fehlt» is on the personal page and above the map; /practice links to the map; the avatar menu lists it. Personal and noindex like settings, so not in the sitemap. Strings in all seven dictionaries; the responsive audit measures /progress. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Practice: an area scope, «Nail it», hardest first, and nothing right today asked again - module=<area>: every scene of one situation area (care, hospitals, ...) and the words said in them; subjects=<list>: named words and lines, for the weak spots. - goal=nail (nail.ts): a drill over a scope until each question is right twice in a row, the second at least three questions later and in the typed form where a word has one; a miss comes back after two to four others; at most 30 subjects, hardest not-known first. - order=hard: hardest first by hardness(); «Harder» prefers the harder question inside its band. - A sitting's order is shuffled (order.ts), never the same subject back to back and the same kind only where unavoidable; cards keep their most-heard-first order. - Answered right today and not wrong today, on any screen (stats now date every wrong answer): not new again today in a sitting; read instead of asked in a situation run (withKnownRead), unless its review is due. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Play together: a challenge link and a live round A challenge is ten fixed questions behind a link (/play/c/<id>): the same questions in the same order with the same option order for everyone, a nickname and no account, marked on the server, and a board of names, right answers and times. It is kept 30 days, and expired ones are removed when somebody next touches the table. A live round is a host screen (/play/host) with a six-digit code and a QR code, players on their phones (/play?code=), 20 seconds a question, points for right plus speed, counts per option on the host's screen, a short board on the phones and a podium. Realtime is short polling against Postgres: one primary-key read with a version, 204 when nothing moved. At most 50 players per room; a room is gone two hours after its last move, checked on access. Host actions need the host secret kept on the host's device; creating rooms and joining are limited with limitkit; nicknames are cleaned, capped at 24 and only ever rendered as text. Five new tables (migration 0033), two privacy flows, the strings in all seven languages, one section on /practice and one button at the end of a sitting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Practice: wrong answers a German reader cannot see through, and «Find the German word» A harness (scripts/audit/options.ts, not shipped) measures how often a reader who knows no Zurich German answers each chosen-answer question by looks alone: most like the prompt, least like it, odd shape, longest. options.test.ts holds the rates near chance. - «Say it in Zurich German» (run): the wrong lines are the right line with one word changed: a Standard German word from the pack's leaks or the course's own cognate pairs, a form the pack places elsewhere, or an article the noun never takes. By looks: 99% -> 32%. Other lines only where a line has fewer than two such changes. - Look-alikes skip Zurich words that stand for two standard words (bi: bin/bei, wänn: wann/wenn) and course pairs that are not cognates, so a planted word is certainly not Zurich German. - «Stimmt das?»: a false claim is a near miss of the line's meaning (near-miss.ts), never another line; no near miss, no false claim. By resemblance: 96% -> 64%. - «What is meant?»: more near-miss meanings (modals, Herr/Frau, times, places, colours...), the closest first. Lines with one: 21% -> 42%. - Cognates («gah», gehen) are asked from German with real course words as the other options; the rest by meaning, with distractors as alike as the answer (resembles: letters and consonant skeleton). - Options, banks and columns are laid out from a seed per sitting and the question id (present.ts), one helper for practice and the runs. - hardness.ts counts giveaways, confusable options and odds; a cognate asked from Zurich rates easier than the same word asked from German. - New kind «Find the German word» (spot): a course line with one word in Standard German, tap the word; the answer shows the Zurich word and the line. Strings in all seven languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Questions: «Tschüss» is never offered as the certainly-wrong German word Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Exercises: read before moving on, and tap the words instead of typing The moment after an answer (exercises/chrome.tsx, useMoveOn): - a right answer shows the whole line where the question showed part of it, its meaning and the reason, then moves on after a beat as long as that text: 1.3 s + 45 ms a character, at most 6 s (move-on.ts); - a touch, wheel or focus on the session screen, or «Anhalten» beside «Weiter», holds it: the bar fades and the control reads «Angehalten» in the same box, so nothing moves; Enter or Space continues; - a wrong answer or a skip never moves on; - «Von selbst weiter: An | Aus» in the sitting's sheet, remembered on the device (heidi.practice.move-on.v1, person-level, on the privacy page); - reduced motion: no draining bar, the seconds are counted on «Weiter». The situation run's follow steps use the same hook and controls, and the run now has the same sheet behind the sliders. Tap instead of type (tiles.ts, exercises/tiles.tsx, answer-how.tsx): - every translate question can be built from tiles: its own words plus two or three real course words from the same scene, topic or word group, look-alikes first; marked against the course line (case and punctuation ignored), typed answers stay self-marked; - the build kind's tile UI is now TileAnswer, shared by both; - the habit is «Wählen | Antippen | Tippen»; old stored values stay valid; on a typed question it is that question's switch, and «Wählen» is not offered where there is no meaning question; - the run's «Lieber schreiben» link is the same «Wörter antippen | Tippen» switch, above the question; - tiles are recorded as mode "tap": not typed, not scheduled as recalled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Heidi Plus: a subscription that renews, monthly or yearly, with an intro price The one-time pass becomes «Heidi Plus»: a monthly plan that renews until cancelled, a yearly one at a saving, and an optional lower price for the first months, through Stripe (paykit 0.6 `stripeBilling`). The pass stays, offered below as «Lieber einmal zahlen?». - /plans is paykit's PlanPicker: Free | Heidi Plus (recommended) | Eigener KI-Schlüssel | Organisationen. The own-key tier is CHF 0 to Heidi, names the providers from ai-kit's BYOK_VENDORS and leads to /settings#model; the old own-key section is gone. Without prices, Plus is «Bald verfügbar» with the notify form. - A review step before Stripe (paykit's PlanReview): summary, notes, the account, the renewal box that must be ticked (Heidi has no terms page, so no terms box), the practice reminders as an optional box, and an active pass or subscription shown with «Abo verwalten» instead of a second one. - Prices only from HEIDI_PLUS_MONTH_CHF, HEIDI_PLUS_YEAR_CHF, HEIDI_PLUS_INTRO_CHF, HEIDI_PLUS_INTRO_MONTHS; the proposal is on /owner/payments and in .env.example, marked as one. - Stripe webhook: subscription events verified, handled once by event id (pay_events), the record in pay_subscriptions (migration 0034). A paid period moves the same entitlements row a pass uses, never back. - Settings: «Abo verwalten» opens Stripe's portal, with the status line (renews / ends / payment failed / ended). - Deleting the account cancels the subscription at Stripe first. - Privacy: the passPayments flow names the subscription, its tables and the email Stripe receives; the flows have anchors. - Strings in all seven languages. package.json asks for @bitbaum/paykit ^0.6.0; the lockfile follows once it is published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Play together: «Find the German word» can be played; the said-too list lives in the packs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Practice: «Was willst du üben?» on /practice and the personal page; «Bis es sitzt» drills - The builder: what (everything, words, forms and grammar, a situation, an area, my weak spots), which (a searchable list, each row with the learner's state: not started, in progress, strong), how (quick round, Nail it, test; hardest first). It opens a URL of the sitting contract. - A «Nail it» sitting shows «12 of 20 nailed», says when the drill took only the hardest 30, and ends with a short summary; it resumes where it was left. - A situation run shows a line answered right today as a line to read. - «Bis es sitzt üben» on every situation page and grammar topic page with questions. - Strings in all seven dictionaries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * «Which one is Zurich German?»: a wrong article names its noun; a form Zurich speakers use is never planted as wrong (tested) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Session bar: progress keeps its room, repeats shorten below 380px; audit measures the new answer moment The top bar's progress bar keeps a minimum width, and the «+1 repeat» note collapses to «+1 ↻» on the narrowest phones so 2/8 never pushes it off. The responsive audit gains ONLY= to narrow to changed pages, measures a held run step, measures a typed question as tiles before switching to typing, and answers the meaning gate (after hydration) where a language shows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Situation run: the reason for each wrong line is shown once, with the article's noun Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Situation run: what a step asks is the sitting's own small line above the question (one shape with practice) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Changelog 2026-12-03: the exercise revamp Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Plan test: new questions per sitting checked over 40 learners, not one lucky seed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * /practice: one picker — the quick round's mix sits under «Was willst du üben?» without a second «what / test» row Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Changelog 2026-12-03: plans (Free, Heidi Plus, own AI key, Organisations) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Lockfile: @bitbaum/paykit 0.6.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Heidi: «Was du kannst» answers next step, standing per area, what to do inside The knowledge map (unlabelled dots in rows, lines that meant nothing) is replaced by a page that answers, in order: one next step with its reason and one black button; per area a segmented bar of lines that sit, wobble and were never asked, with untouched areas collapsed to one line; inside an area every situation, topic or word group with its bar, status word and the action that fits it, sorted by what to do next. The step comes from a pure planOf (lib/domain/progress/plan.ts) that the personal page's card uses too, so the two never disagree. The map layout module, its tests and the weak-spots card are removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Questions: one standard for practice, runs and play Every question now passes the same five rules, written down in code in lib/domain/questions/standard.ts and checked by tests: 1. Ask only what a German reader doesn't get for free. A line that can be read straight off its German is read, not asked. «Chasch mer schnäll hälfe?» is now a line to read. 2. Wrong options are the same kind of thing as the answer. «mir» is offered with «wir», «uns» and «euch», never with «nirgends» or «übermorgen». The reading shelf no longer fills a short list with words of another kind. 3. A question must not be solvable without knowing Zurich German. Seven solvers that don't know the language (look-alike, longest, odd one out and others) may beat chance by at most 15 points per kind; balance() drops the questions that let them do better. 4. Feedback gives the rule, other lines with the same word, and a line where the word means something else. A later line of the run asks the word again (transfer). 5. Hardness is real: it is measured from the options. Homographs: a word whose meaning depends on the line is asked only when the line's German proves the taught meaning (provesMeaning). The «wo» cue ", wo" matched «Ah, wo denn?», where «wo» is the question word. That cue is gone, and comma cues now end at a word boundary. This removes 5 false proofs, including «wohin». The sourced Einsiedeln text now asks «cho». Close is not wrong: choosing a look-alike that differs only by a form said in another Swiss region («geit», Bern) gets «Fast», with where that form is said. It is scheduled as FSRS «hard», not as a lapse. One rule, lookalikeVerdict, decides this. A Standard German word stays wrong. Questions are now chosen from ASKED_ITEMS, the items that meet the standard. PACK_ITEMS still holds everything, so stored progress, glosses and reminders keep working. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Questions: rules that are rules, fair German-first words, spot, transfer - A rule line appears only where there is a rule. The line «Merk es dir im Satz…» shown under every plain word is gone (ruleOf in questions/standard.ts). «mir» and «si» now carry how their line tells the two meanings apart (homograph-role, homograph-modal), with examples taken from course lines, in all seven languages. The pack names which rule applies to which homograph. - Asked from German: wrong options come from the word's own group, are never rude, and look as much like the German word as the answer does. If the answer is the only word that looks like the German one, the word is not asked. Balance no longer keeps a kind's last question when a solver wins it. - Spot never plants a mere spelling of the Zurich word («bestelle» for «bstelle», «gehört» for «ghört»). It never plants a lone word ending in «-en» either, since that can be found by its ending alone. The word is quoted without its punctuation. - Transfer: a run asks a word at most twice. A homograph's second question goes to a later line that uses the other meaning, when the part has one («bi mir» after «Mir händ…»). A contrast question is never the first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r --------- Co-authored-by: Claude <noreply@anthropic.com>
353 lines
14 KiB
TypeScript
353 lines
14 KiB
TypeScript
import { REVIEW_STEPS } from "../saved/review.ts";
|
|
import type { PracticeItem } from "./types.ts";
|
|
|
|
/**
|
|
* When each question comes back — so what was learned is asked again just
|
|
* before it would be forgotten, instead of never or at random.
|
|
*
|
|
* THE GAP IT CLOSES. The learner model (`model.ts`) knows which AREAS are weak,
|
|
* and `history.ts` knows what was asked lately; neither knows TIME. This is
|
|
* where each question's next day is kept.
|
|
*
|
|
* BY MEMORY, NOT BY CALENDAR (practice plan step 4, 2026-12-01). Until then
|
|
* every question walked the same ladder as kept words — 1, 3, 7, 16, 35 days
|
|
* (`REVIEW_STEPS`), back to day 1 on a miss — whatever the question. Measured
|
|
* with a simulated learner (80% right, up to three sittings a day, the whole
|
|
* course; `schedule.test.ts`): the due pile grew by about 80 questions a week
|
|
* and stood at 917 after twelve weeks.
|
|
*
|
|
* Now each question carries a memory state — STABILITY (days until the chance
|
|
* of recalling it falls to 90%) and DIFFICULTY (1 to 10) — and its next day
|
|
* follows from them: FSRS, the open Free Spaced Repetition Scheduler (Ye, Su
|
|
* and Cao 2022, https://doi.org/10.1145/3534678.3539081), version 5, with its
|
|
* published default weights. The formulas and the weights are those of
|
|
* ts-fsrs 6.0.1 (MIT), `src/models/fsrs-5/algorithm.ts` and `constants.ts`,
|
|
* read from the npm package; written out here rather than installed because
|
|
* that package needs Node 24. Same-day learning steps (FSRS's "short term")
|
|
* are left out: a sitting counts only the first answer to a question, so
|
|
* there are none to schedule.
|
|
*
|
|
* A QUESTION HAS THREE STATES, and the order a sitting takes them in is the
|
|
* point of the module (`urgency`):
|
|
*
|
|
* due its day has come — asked first, most overdue first;
|
|
* new never answered — fills what is left;
|
|
* resting answered, and not due yet — asked only when nothing else is
|
|
* left, soonest first. Asking it early spends the spacing that
|
|
* makes the next answer worth more.
|
|
*
|
|
* A DAY HAS A CAP (`REVIEWS_PER_DAY`): what a learner is told today asks is
|
|
* at most that many, less the reviews already answered today (`todayCount`);
|
|
* and a sitting takes fewer new questions while the pile is large
|
|
* (`newShareFor`), because every new question is a future review.
|
|
*
|
|
* ONLY THE FIRST ANSWER IN A SITTING COUNTS, as for the model and for kept
|
|
* words: a question requeued after a miss is answered a minute after seeing
|
|
* the answer, which is not the retrieval the schedule is built on. The caller
|
|
* enforces that; this module records what it is handed.
|
|
*
|
|
* Kept words (`recall:` items) are not recorded here: they carry their own
|
|
* schedule on the word, and two schedules for one word would disagree.
|
|
*
|
|
* WHERE IT LIVES: the browser, like the model, and synced to the account only
|
|
* when the learner turns sync on. Pure: every function returns a new value.
|
|
*/
|
|
|
|
/** One question's place in the schedule. Times are epoch milliseconds. */
|
|
export type Card = {
|
|
/**
|
|
* Right answers in a row, at most `REVIEW_STEPS.length - 1`. Kept from the
|
|
* old ladder so a card written by either version reads in both; nothing
|
|
* schedules by it any more.
|
|
*/
|
|
step: number;
|
|
/** When it is due again. */
|
|
due: number;
|
|
/** When it was last answered — the newer answer wins across devices. */
|
|
seen: number;
|
|
/** How often it was answered wrong after having been answered at all. */
|
|
lapses: number;
|
|
/**
|
|
* FSRS stability in days. Absent on a card written before 2026-12-01: it
|
|
* is then read from the interval that card was given (`stateOf`).
|
|
*/
|
|
s?: number;
|
|
/** FSRS difficulty, 1 to 10. Absent on an older card, like `s`. */
|
|
d?: number;
|
|
/** How many answers have been scheduled on it. Absent on an older card. */
|
|
n?: number;
|
|
};
|
|
|
|
/** Cards by item id. */
|
|
export type Memory = Readonly<Record<string, Card>>;
|
|
|
|
export const NO_MEMORY: Memory = {};
|
|
|
|
const DAY_MS = 86_400_000;
|
|
|
|
/**
|
|
* The most cards a stored memory may hold. Every question in the packs is
|
|
* about 1,800; this leaves room to grow and bounds what a hostile or broken
|
|
* record can make a page parse.
|
|
*/
|
|
export const MEMORY_LIMIT = 10_000;
|
|
|
|
/** Whether an item is scheduled here at all. */
|
|
export function schedules(item: Pick<PracticeItem, "kind">): boolean {
|
|
return item.kind !== "recall";
|
|
}
|
|
|
|
/** FSRS-5 default weights (ts-fsrs 6.0.1, `FSRS5_DEFAULT_WEIGHTS`). */
|
|
export const FSRS_WEIGHTS = [
|
|
0.40255, 1.18385, 3.173, 15.69105, 7.1949, 0.5345, 1.4604, 0.0046, 1.54575, 0.1192, 1.01925, 1.9395, 0.11, 0.29605, 2.2698,
|
|
0.2315, 2.9898, 0.51655, 0.6621,
|
|
] as const;
|
|
const DECAY = 0.5;
|
|
const FACTOR = 19 / 81;
|
|
const S_MIN = 0.01;
|
|
const S_MAX = 36_500;
|
|
|
|
/**
|
|
* The chance of recall the schedule aims at when a question comes back: 90%,
|
|
* FSRS's own default. With FSRS-5's curve this makes the interval equal to
|
|
* the stability, in days.
|
|
*/
|
|
export const DESIRED_RETENTION = 0.9;
|
|
|
|
/**
|
|
* The longest a question waits: half a year. OURS, not a finding — a course
|
|
* is not a lifetime deck, and a question that never comes back has quietly
|
|
* left the course. FSRS itself allows a century.
|
|
*/
|
|
export const MAX_INTERVAL_DAYS = 180;
|
|
|
|
/**
|
|
* How many reviews a day is told it has, at most: three sittings of eight.
|
|
* OURS, not a finding: a ceiling, and most days are under it.
|
|
*/
|
|
export const REVIEWS_PER_DAY = 24;
|
|
|
|
/** FSRS ratings used here: a miss (Again), a close one (Hard), a right answer chosen (Good), typed (Easy). */
|
|
export type Rating = 1 | 2 | 3 | 4;
|
|
|
|
const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
|
|
const w = FSRS_WEIGHTS;
|
|
|
|
/** The chance of recalling a question `days` after it was last answered. */
|
|
export function retrievability(days: number, stability: number): number {
|
|
return Math.pow(1 + (FACTOR * Math.max(0, days)) / stability, -DECAY);
|
|
}
|
|
|
|
const initialDifficulty = (g: Rating) => clamp(w[4] - Math.exp((g - 1) * w[5]) + 1, 1, 10);
|
|
|
|
function nextDifficulty(d: number, g: Rating): number {
|
|
const delta = -w[6] * (g - 3);
|
|
const damped = d + (delta * (10 - d)) / 9;
|
|
return clamp(w[7] * initialDifficulty(4) + (1 - w[7]) * damped, 1, 10);
|
|
}
|
|
|
|
function nextStability(d: number, s: number, r: number, g: Rating): number {
|
|
if (g === 1) {
|
|
const afterFail = w[11] * Math.pow(d, -w[12]) * (Math.pow(s + 1, w[13]) - 1) * Math.exp((1 - r) * w[14]);
|
|
return clamp(Math.min(s, afterFail), S_MIN, S_MAX);
|
|
}
|
|
const easy = g === 4 ? w[16] : 1;
|
|
const hard = g === 2 ? w[15] : 1;
|
|
const grown = s * (1 + Math.exp(w[8]) * (11 - d) * Math.pow(s, -w[9]) * (Math.exp((1 - r) * w[10]) - 1) * hard * easy);
|
|
return clamp(grown, S_MIN, S_MAX);
|
|
}
|
|
|
|
/** Whole days until the next review, from a stability. */
|
|
export function intervalDays(stability: number): number {
|
|
const modifier = (Math.pow(DESIRED_RETENTION, 1 / -DECAY) - 1) / FACTOR;
|
|
return clamp(Math.round(stability * modifier), 1, MAX_INTERVAL_DAYS);
|
|
}
|
|
|
|
/**
|
|
* A card's memory state. A card from before FSRS has none: its stability is
|
|
* read as the interval the old ladder gave it (at 90% retention FSRS sets the
|
|
* interval to the stability, so the old schedule is kept exactly), and its
|
|
* difficulty as a first right answer's, one point harder per miss — ours, the
|
|
* old card recorded nothing finer.
|
|
*/
|
|
export function stateOf(card: Card): { s: number; d: number } {
|
|
if (card.s !== undefined && card.d !== undefined) return { s: card.s, d: card.d };
|
|
return { s: clamp((card.due - card.seen) / DAY_MS, 1, S_MAX), d: clamp(initialDifficulty(3) + card.lapses, 1, 10) };
|
|
}
|
|
|
|
/**
|
|
* Record one answer.
|
|
*
|
|
* A skip is not an answer about knowledge (the same rule as `observe`), and
|
|
* leaves the card as it was. A right answer TYPED counts as FSRS's «easy»
|
|
* when the caller says so: producing a word is the harder retrieval than
|
|
* choosing it (Laufer and Goldstein 2004), so it stretches the next interval
|
|
* further. A miss is «again», a right answer chosen «good», a close one
|
|
* (Swiss German of another region for the Zurich form) «hard».
|
|
*/
|
|
export function scheduleAnswer(
|
|
memory: Memory,
|
|
item: Pick<PracticeItem, "id" | "kind">,
|
|
outcome: "right" | "wrong" | "skipped",
|
|
now: Date,
|
|
{ typed = false, close = false }: { typed?: boolean; close?: boolean } = {},
|
|
): Memory {
|
|
if (outcome === "skipped" || !schedules(item)) return memory;
|
|
const before = memory[item.id];
|
|
const right = outcome === "right";
|
|
// CLOSE (`lookalikeVerdict`): a form of another region chosen for the
|
|
// Zurich one is FSRS's «hard» — known, not yet told apart. Not a miss.
|
|
const g: Rating = !right ? 1 : close ? 2 : typed ? 4 : 3;
|
|
const at = now.getTime();
|
|
let s: number;
|
|
let d: number;
|
|
if (!before) {
|
|
s = clamp(w[g - 1]!, S_MIN, S_MAX);
|
|
d = initialDifficulty(g);
|
|
} else {
|
|
const state = stateOf(before);
|
|
const r = retrievability((at - before.seen) / DAY_MS, state.s);
|
|
s = nextStability(state.d, state.s, r, g);
|
|
d = nextDifficulty(state.d, g);
|
|
}
|
|
const card: Card = {
|
|
step: right ? (before ? Math.min(before.step + 1, REVIEW_STEPS.length - 1) : 0) : 0,
|
|
due: at + intervalDays(s) * DAY_MS,
|
|
seen: at,
|
|
lapses: (before?.lapses ?? 0) + (!right && before ? 1 : 0),
|
|
s: Math.round(s * 1000) / 1000,
|
|
d: Math.round(d * 1000) / 1000,
|
|
n: (before ? (before.n ?? 1) : 0) + 1,
|
|
};
|
|
return { ...memory, [item.id]: card };
|
|
}
|
|
|
|
/** 0 due, 1 new, 2 resting — lower is asked sooner. */
|
|
export type Urgency = 0 | 1 | 2;
|
|
|
|
export function urgency(memory: Memory, id: string, now: Date): Urgency {
|
|
const card = memory[id];
|
|
if (!card) return 1;
|
|
return card.due <= now.getTime() ? 0 : 2;
|
|
}
|
|
|
|
/**
|
|
* The order two items of the SAME urgency take: due and resting by due time
|
|
* (most overdue, or soonest, first); new ones tie and fall through to the
|
|
* caller's own order.
|
|
*/
|
|
export function dueOrder(memory: Memory, a: string, b: string): number {
|
|
return (memory[a]?.due ?? 0) - (memory[b]?.due ?? 0);
|
|
}
|
|
|
|
/** How many of these items are due now — the whole pile. Without `ids`, every card. */
|
|
export function dueCount(memory: Memory, now: Date, ids?: Iterable<string>): number {
|
|
const at = now.getTime();
|
|
if (!ids) return Object.values(memory).filter((card) => card.due <= at).length;
|
|
let n = 0;
|
|
for (const id of ids) if ((memory[id]?.due ?? Infinity) <= at) n++;
|
|
return n;
|
|
}
|
|
|
|
/** The start of the local day `now` is in, as the device running this sees it. */
|
|
function startOfDay(now: Date): number {
|
|
const day = new Date(now.getTime());
|
|
day.setHours(0, 0, 0, 0);
|
|
return day.getTime();
|
|
}
|
|
|
|
/**
|
|
* How many reviews were answered today: cards answered today that had been
|
|
* answered before. A card from before FSRS (no `n`) counts as a review — the
|
|
* first answer under FSRS would have written an `n`.
|
|
*/
|
|
export function reviewedToday(memory: Memory, now: Date): number {
|
|
const from = startOfDay(now);
|
|
const at = now.getTime();
|
|
return Object.values(memory).filter((card) => card.seen >= from && card.seen <= at && (card.n ?? 2) >= 2).length;
|
|
}
|
|
|
|
/**
|
|
* What TODAY asks: the questions due, at most `REVIEWS_PER_DAY` less the
|
|
* reviews already answered today. This is the number a learner is shown;
|
|
* `dueCount` is the whole pile, and showing the pile made a debt that only
|
|
* grew. What is over the cap waits for tomorrow, most overdue first
|
|
* (`dueOrder`), and a sitting still offers it to whoever wants more.
|
|
*/
|
|
export function todayCount(memory: Memory, now: Date, ids?: Iterable<string>): number {
|
|
return Math.min(dueCount(memory, now, ids), Math.max(0, REVIEWS_PER_DAY - reviewedToday(memory, now)));
|
|
}
|
|
|
|
/**
|
|
* The share of a sitting that may go to NEW questions, given how many are
|
|
* due: `full` while the pile fits in a day's cap, then less, and none once it
|
|
* is twice the cap. Every new question is a future review; pausing them while
|
|
* the reviews catch up is what keeps the pile bounded (`schedule.test.ts`).
|
|
*/
|
|
export function newShareFor(pile: number, full: number): number {
|
|
return full * clamp((2 * REVIEWS_PER_DAY - pile) / REVIEWS_PER_DAY, 0, 1);
|
|
}
|
|
|
|
/** How many come back within `days` from now, not counting those due already. */
|
|
export function comingBack(memory: Memory, now: Date, days = 1): number {
|
|
const at = now.getTime();
|
|
const horizon = at + days * DAY_MS;
|
|
return Object.values(memory).filter((card) => card.due > at && card.due <= horizon).length;
|
|
}
|
|
|
|
/**
|
|
* Several devices' memories as one: per question, the card answered most
|
|
* recently. Each device only records what it observed, so the newest answer
|
|
* is the truth about where that question stands.
|
|
*/
|
|
export function combineMemories(memories: readonly Memory[]): Memory {
|
|
if (memories.length === 1) return memories[0]!;
|
|
const out: Record<string, Card> = {};
|
|
for (const memory of memories) {
|
|
for (const [id, card] of Object.entries(memory)) {
|
|
const current = out[id];
|
|
if (!current || card.seen > current.seen) out[id] = card;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
const within = (x: unknown, lo: number, hi: number): x is number =>
|
|
typeof x === "number" && Number.isFinite(x) && x >= lo && x <= hi;
|
|
|
|
/**
|
|
* Read a stored memory back, keeping only well-formed cards.
|
|
*
|
|
* Null for something that is not a memory at all, so the sync endpoint can
|
|
* refuse it; a record with some bad cards keeps the good ones. A card written
|
|
* before FSRS has no `s`, `d` or `n` and is read as it was (`stateOf`).
|
|
*/
|
|
export function decodeMemory(raw: string): Memory | null {
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
const out: Record<string, Card> = {};
|
|
let kept = 0;
|
|
for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
if (kept >= MEMORY_LIMIT) break;
|
|
if (!id.trim() || id.length > 200 || !value || typeof value !== "object") continue;
|
|
const { step, due, seen, lapses, s, d, n } = value as Record<string, unknown>;
|
|
if (![step, due, seen, lapses].every((x) => typeof x === "number" && Number.isFinite(x) && x >= 0)) continue;
|
|
out[id] = {
|
|
step: Math.min(Math.trunc(step as number), REVIEW_STEPS.length - 1),
|
|
due: Math.trunc(due as number),
|
|
seen: Math.trunc(seen as number),
|
|
lapses: Math.trunc(lapses as number),
|
|
// The memory state travels whole: a stability without its difficulty is read like an old card.
|
|
...(within(s, S_MIN, S_MAX) && within(d, 1, 10) ? { s, d } : {}),
|
|
...(within(n, 1, 1_000_000) ? { n: Math.trunc(n) } : {}),
|
|
};
|
|
kept++;
|
|
}
|
|
return out;
|
|
}
|