mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-04 11:37:39 +01:00
* feat(profile): a learner profile, and a personal page that answers three questions One profile model as a view over the stores that already hold each answer; the setup «Dein Profil einrichten», one question per screen; the profile card on the personal page; «Wo stehe ich?» and «Nutze ich Heidi gut?»; progress kept with the account by default; reminders only when behind the learner's own weekly goal. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * docs(profile): record the new sync default and the profile; audit the setup screen Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(profile): interests lead the listening One more profile question, «Was interessiert dich?»: nine choices that name the topics every row of the listening register already carries. The listening page opens with the rows that fit, each saying which choice it is there for and how much can be asked about it; «Nutze ich Heidi gut?» names one of them when the thing to do is listen. Chosen in the browser, so the page stays cached; stored as a field of the profile record. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix: an eight-character password floor, a localised investors door, page titles and four layout leftovers - A new password needs eight characters (sign-up, change, reset), through a plugin the account package accepts; signing in with an older, shorter password still works. The message is in all seven languages. - The investors door says «Passwort / Öffnen» in the reader's language. - A failed sign-in, the unsubscribe page and the signed-in personal page have their own titles; a test holds every page to one. - The kept sentence under a saved word is no longer hyphenated («Schlüs- / sel» at 320px). - «Warum die Übungen so gebaut sind» is a closed row with a chevron. - The account forms' primary button is black, like every other. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(sync): the merge policy is a tested function; the profile says when sync failed What one pull changes in this browser moved out of a useEffect into lib/domain/progress/merge.ts (planMerge, decodeDevices, statusAfter), with tests for every rule. The runner only fetches and writes. A failed request and a 401 used to be swallowed; the personal page went on saying progress was stored with the account. They are now reported through an in-memory status, and the sync line shows when it last got through, that it did not (with a retry), or that this browser is signed out (with the way in). One deliberate difference: a device that holds no bridge/difficulty choice no longer hides an older device's choice from a third one. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(practice): one recordAnswer, a tested and resumable test run, exercise words by context Items 2, 3, 7, 13, 16 and the practice and test screens of 12, which share files. recordAnswer (lib/domain/practice/record.ts) is the one place an answer is written into history, model, memory and the day. The sitting and the warm-up wrote it out twice with different rules and the test a third time. Decided: the first answer teaches (the sitting's rule); the day counts from the first answer, so a warm-up left half way now counts (the sitting's rule won); a test answer counts for the day only, kept on purpose and said why. The test's draw and its stored shape are lib/domain/practice/test-run.ts, tested. A run survives a reload (heidi.practice.test.v2, per course, on the privacy page), keyed by sitting, with the clock held as a deadline. practice-session.tsx 620 -> 217 and test-session.tsx 427 -> 146: state and rules to use-sitting.ts, use-test-run.ts and lib/domain/practice/sitting-run.ts (tested); LevelRow, UsedUp, the test's start and result screens, and the warm-up's result are their own files. The six dictionary slices every exercise read as props come from one provider (exercises/words.tsx); the pages build them with exerciseWords(). heidi.voice.v1 is on the privacy page, so 'delete everything on this device' removes it; privacy.test.ts now checks both directions. The warm-up and the home page's speech bubble take the variety from the pack instead of writing 'gsw', and the leak ratchet covers app/. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * revert(auth): accounts stay the package's; no password rule of Heidi's own Sign-up and sign-in behave exactly as @bitbaum/accountkit defines them. The eight-character floor added here as a local plugin is removed, with its message and note; a rule about passwords belongs in the package, for every app at once, or nowhere. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(model): one chain, a tested judgeTake, and the speaking check says why it has nothing Items 4 and 8. lib/domain/model/chain.ts: modelChain() and ownChain() replace four copies of usableChain(freeChain("HEIDI")), and hold the health tracker three routes imported from the chat's route file. A test fails on a fifth copy. lib/domain/speaking/judge.ts: the take's judgement (request reading, the bridge/target gate, the model call, the gate on the suggestion) with tests and an injectable model. api/speaking/take/route.ts 222 -> 45 lines. The route's answer now says which kind of nothing it is (opinion), and the screen reads the status too: a rate limit, a model that could not be reached and a model with nothing to add each have their own sentence, in seven languages. Before, all three printed 'Heidi has nothing to add right now'. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(shell): an error screen inside the site, and loading states where they cannot change a status code Item 5. app/[locale]/error.tsx: a page that throws keeps the header, footer and chat, says so in the reader's language, and offers retry and the way home. Its five words come from the layout through a small context, so the dictionaries are not shipped to the browser. loading.tsx is NOT at app/[locale]/, on purpose. It was added and measured: a loading file starts the response before the page runs, so 9 of 22 probed addresses changed status (every unknown page 404 -> 200, /account and /portal 307 -> 200). The same screen is instead the loading state of the six routes that can only answer 200 (vocabulary, speaking, listen, profile, settings, warmup), and a test fails if a loading file is put above a page that calls notFound() or redirect(). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(a11y): the two modal sheets are real modals, and an accessibility pass over existing screens Item 6. The sitting's settings and the model connection claimed aria-modal on a plain div with no focus trap. Both are now chatkit's Sheet (a native dialog opened with showModal): focus stays inside, the page behind is inert, Escape closes, and the opener gets focus back. A test fails on aria-modal anywhere else. The pass, in code: - the model sheet's close button was labelled with a multiplication sign; it is the package's labelled 44px button now (model.close, 7 languages) - tap targets under 44px raised: the settings chip, saved words' export and clear, a take's delete, a failed chat bubble's retry, the word popover's button, the invite link's rotate - a listening question marked the right option by outline colour alone; it carries the drill's tick and cross - seven error lines appeared without role=alert (topics, rounds, recorder) Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(chat): one way to follow a conversation, and the dock in three files Items 10 and 12 (dock). chat.tsx, the dock and the group chat each scrolled a marker into view on every change of the messages. That is now chatkit's useStickToBottom behind one small hook (chat/use-follow.ts): the thread is followed until the reader scrolls up, so a token or a message from someone else no longer pulls them away from an older answer. chat/dock.tsx 577 -> 235: the panel is chat/dock-panel.tsx (242), and the two facts only a browser knows about the launcher (is it lying on a control, how tall is it) are chat/use-dock-launcher.ts. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor: answer view, round list and chat workspace under 300 lines, with their logic in lib Item 12, the remaining three. chat/answer-view.tsx 421 -> 185: the glosses, the suggestions and the row of buttons are their own files; what the row holds (ownRowItems) moved to lib/domain/chat/row.ts with tests. round-list.tsx 415 -> 216: the form to open a round is round-open.tsx; what a viewer may do with a round (roundChoices) and the request a host's form becomes (newRoundBody) are lib/domain/speaking/round-view.ts with tests. chat/workspace.tsx 415 -> 263: the transport is a hook, the words handed to chatkit's ChatApp are workspace-words.ts (tested in all seven languages), and the offer to keep a browser conversation is adopt-prompt.tsx. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(http): one id pattern, one organiser check, one audio-upload guard Item 11. The UUID pattern was defined in eleven files; it is lib/http/ids.ts. organiserGroup was written out in the invite and the team route; it is in lib/domain/groups/store.ts beside groupById. The bounded read of an uploaded recording, copied between the two transcription routes, is lib/http/audio-upload.ts with tests. A test fails on a second definition of any of the three. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * chore: remove dead code and dictionary keys nothing reads Item 15. scripts/responsive-audit.mjs is superseded by scripts/audit/responsive.mjs, which package.json's audit:responsive runs; nothing referenced the old one. Exports with no reader anywhere (code, tests or scripts), found with knip and confirmed by search: draftTransport, CowLockup, useHistoryView, recordFor, Prose, countNewSince, isChannelId, isVideoId, lastChanged, moveId, forgetInterest (account deletion removes those rows in erase.ts), isObjective, stretchOf, essaysAbout. useTheme is used only in its own file and is no longer exported. 36 dictionary keys whose name appears nowhere outside the dictionaries, in all seven languages: home.{trustTitle,trustBody,trustLink,pillarsTitle, methodLink,researchLink,contributeTitle,contributeCta}, pillars, check.{failShort,noteTitle}, technology.directionLabel, privacy.updatedLabel, contribute.{needTitle,needList}, auth.{portalLead,notSignedIn}, streak.goalLabel, practice.{correctIs,buildPrompt,verifyPrompt,typeLabel, testAnswer,testDone}, essays.notTranslated, review.noneHint, organisations.momentLabel, shell.{wordsTitle,wordsDue,wordsNone,wordsOpen, courseSteady,resumeTitle,resumeProgress,resumeNone,resumeStart}. Keys read by id (privacy.flows.*, chat.learn.*Label, feedback reasons) were checked and kept. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(a11y): the modal sheet gives focus back to what opened it Found in the browser: closing the model sheet with its close button left focus on <body>. The opener was read in an effect, which runs after the sheet's own effect has already moved focus into the dialog. It is read while rendering now. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(shell): no focus ring round the error screen's heading It is focused by the page so a screen reader starts there; the ring drawn round it read as a text field. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * refactor(components): one folder per feature under _components The flat folder of 131 files is sorted the way chat/, exercises/, profile/, session/ and speaking/ already were: shell, shared, home, languages, dialect, dashboard, vocabulary, listening, channels, groups, rounds, sync, practice, situations, warmup, voice, byok, auth, essays. Files moved with git mv; no barrel files, as before. The stores that are storage and nothing else (practice, focus, streak, warm-up, video), the one write path for an answer and the API error wording moved to lib/browser and lib/http. Tests that scanned or named the old paths follow, and the two that read 'this folder' still read every component. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(listen): «Für dich» is the first thing under the title The rows that fit a learner's interests, or the one card that asks for them, sat below the diglossia warning. They now come straight after the title and its lead; the warning, the day's picks and the whole register stay below. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * chore(i18n): drop footer.varietyName, which nothing reads Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * chore: remove four exports and three types nothing references Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(listen, profile): the interest tiles stay under the finger; the sync choice is one column on a phone Found walking the release at 390px. /listen: the first tile tapped in the invite card already makes a pick, and the card turned into the list at that moment, with the tiles pushed below three rows. The card now stays a card until «Fertig», and then the list is brought to the top of the screen. Mein Bereich, signed in: the two answers to the sync notice sat side by side inside the profile card, some 130px each, and «Nur auf diesem Gerät behalten» stood four lines tall. One column below sm. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(situations): the logic of a guided run through one situation A situation was a reference list, and practising it was a random draw of eight questions. This adds what a guided five-minute run needs, as pure functions with typed results and no screens. lib/domain/situations: - planRun: every heard line in pack order with one question about its meaning, then up to two lines built from their words and said aloud, then the whole exchange again. Deterministic for a seed; a stored run is rebuilt from its step ids (heidi.situation.run.v2, per course, declared on the privacy page). - situationProgress: followed x of y and new / started / followed / due, read from the learner model's line traces and the memory's due dates. A run's answers are recorded by recordAnswer; nothing else is stored. - nextSituation, orderSituations: one recommendation with its reason, and the list with the learner's own situations first. lib/situations: optional speaker, addressee, register, answers, reviewed on a line and beats on a scene, with a validator test. Read from what the packs and the reply questions already state (lines.ts); beats are written for the fourteen scenes that were deepened by ten appended lines. Fixes at the cause: - a sitting on a scene no longer takes a quarter of its questions from the neighbouring scenes, and no longer asks a word inside a line of another scene; - a wrong meaning in «Stimmt das?» is the same sentence type as the right one wherever the scene has such a line; - the speaking task list can be held to one scene. Strings for the future screens are under situationRun in all seven dictionaries. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(design): every main page opens with a place, lists are rows, and a sitting ends as a moment Shared primitives in _components/shared: Scene (a full-height photograph with the page's one headline, one line and one action on it, white on a shade in both themes), RowList/RowLink (lists as rows with hairlines, no cards), SectionHeading, and Ending (one full-screen ending for practice, the warm-up, the test and a used-up scope). The type scale is three roles in globals.css: headline, subhead, kicker. Home, practice, listening, speaking, the situations list, languages, about and Mein Bereich each open with their own Swiss place, by day and by night: 16 photographs from Wikimedia Commons, author and licence read on each file's page and listed in lib/config/photos.ts (credits on the Impressum). During an exercise the question stands alone, without a box. Motion is CSS only and off under prefers-reduced-motion. Removes hero-photo.tsx and the card boxes around lists on these pages. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(situations): a situation is a guided run, and every ending hands on to one A situation page was a reference list with «Üben» at the bottom. It is now the opener of a five-minute run, one thing per screen: - /situations/<id>: a photograph of the place, one sentence, lines and minutes, one button (start, or pick up at the step it was left on); the review state said once; the old list one quiet link away (./lines). - /situations/<id>/run: each heard line alone with its one question, then the German; two lines to build and to say aloud with the speaking recorder held to this scene (played back, never marked); the whole exchange again without German, by speaker and paced; the shared ending with ONE next situation and its reason. Every answer goes through the one ledger; the place is kept. - /situations: a run left half way pinned on top, the learner's own situations, then each domain, as rows with their state. The twenty-chip picker on /practice and the board of figures are this list now. - The endings of practice, the test and the warm-up offer a situation when one is the learner's next step; the home page leads a new visitor to the warm-up; «Weiter: <situation>» on the home card and the personal page. - The warm-up's pointer now holds: its own answers made the scene it points at read "started", so it was never recommended. Design: during an exercise only close, progress and the question remain (the sitting's name and choices are behind one button in the bar); kickers and actions on one line at 390px; rows instead of boxes on listening, speaking, grammar and vocabulary; on a wide screen the shade is only where the words are. Openers with a crane, a scaffold or a flat sky are replaced, and the situations open with their own places (Wikimedia Commons, credited in lib/config/photos.ts). The responsive audit walks a run through every kind of step to its ending. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(photos): the care briefs open on the lake, and the night opener has no cranes The two pictures of the hospital were a dark office front behind a parked car, and they opened every care situation. No better licensed picture of the place was found, so the care scenes open on the lake by day and at dawn, both already in the register. The blue-hour picture on the home page, the practice page and the tram brief is replaced by one without building cranes (Dark Blue Zurich, kuhnmi, CC BY 2.0, read on the file's page at Wikimedia Commons). The tram brief keeps the tram's front on a phone and leaves the car beside it out. The three unused files and their entries are removed. The alt texts of the removed pictures go with the next commit, which touches the same dictionaries. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * feat(situations): a run is one part of a situation, about five minutes A run through a whole situation was twenty-two steps, seventeen of them the same «Stimmt das?». A run now takes one part: a beat where the scene has one, about eight heard lines otherwise, with up to two lines to build, one to say aloud and the replay of that part. The next run goes on with the next part, read from the ledger (no second record); once every part has been gone through, a run revisits the part with the most lines missed or due. The brief says what the next run is (heard lines, minutes, part n of m), the ending counts the part and, while a part is ahead, its one next step is that part. Progress on the list still reads across the whole situation. Questions vary: a «Stimmt das?» can be asked the other way round as three meanings of the same scene, recorded against the same item, so one shape does not come three times running where the line can be asked another way, and the claims put to the learner are wrong about as often as right. The claim is drawn as a claim, in its own labelled frame, not as the line's translation. Stored runs keep their shape; the replay's step id now names its part, so a run stored before this is planned afresh. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * fix(model): the free chain is built in one place, pass model included Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T --------- Co-authored-by: Claude <noreply@anthropic.com>
331 lines
15 KiB
TypeScript
331 lines
15 KiB
TypeScript
import type { PracticeItem } from "./types.ts";
|
||
import { KIND_META } from "./kinds/meta.ts";
|
||
|
||
/**
|
||
* What this learner keeps getting wrong — the part that makes practice smart
|
||
* instead of merely random.
|
||
*
|
||
* THE PROBLEM. A session drew eight questions from a pool by recency alone, so
|
||
* a topic somebody has missed four times out of four is exactly as likely to
|
||
* come up as one they have never got wrong. That is not a scheduling detail;
|
||
* it is the difference between a drill and teaching. `isch gsi` becomes a
|
||
* reflex by being asked more often than the things that are already reflexes,
|
||
* and nothing in the product knew which those were.
|
||
*
|
||
* WHAT IT IS NOT, and the distinction is the whole of §8. This is a record of
|
||
* WHAT NEEDS WORK, not a score. It is never rendered as a number out of ten, a
|
||
* percentage, a level or a streak — the surfaces that read it show which
|
||
* topics to look at again and offer a session on them. A measure that points
|
||
* at the material is diagnostic; the same measure pointed at the person is the
|
||
* thing this product refuses to build.
|
||
*
|
||
* WHERE IT LIVES: the learner's browser, with their kept words and for the
|
||
* same reason. HEIDI.md is explicit that saved vocabulary is device-local
|
||
* because it keeps Heidi from holding a record of what a particular person
|
||
* cannot understand. This IS that record, in its purest form, so it gets the
|
||
* same treatment — and unlike the kept words it is also declared on the
|
||
* privacy page and deletable from settings, because a thing this personal must
|
||
* be visible to the person it is about.
|
||
*
|
||
* Pure: every function here takes a model and returns a new one.
|
||
*/
|
||
|
||
/** How often an area was asked, and how often it was missed. */
|
||
export type Trace = { asked: number; missed: number };
|
||
|
||
/**
|
||
* Traces by area, where an "area" is whatever an item can be attributed to.
|
||
*
|
||
* FOUR AXES BECAUSE ITEMS CARRY FOUR KINDS OF PROVENANCE, not because four
|
||
* felt thorough. `ItemSource` already says where every question came from —
|
||
* that field was built so a wrong answer could be traced back — and this reads
|
||
* exactly the same field. A fifth axis would need a fifth kind of source.
|
||
*/
|
||
export type LearnerModel = {
|
||
topics: Record<string, Trace>;
|
||
scenes: Record<string, Trace>;
|
||
groups: Record<string, Trace>;
|
||
words: Record<string, Trace>;
|
||
/**
|
||
* ONE LINE OF ONE SCENE, keyed `sceneId:index` — the axis that lets a
|
||
* situation be something a learner can finish.
|
||
*
|
||
* `scenes` above answers "how have you done in the handover", which is a
|
||
* real question and the wrong one for "can you follow a handover". Twelve
|
||
* right answers about one sentence and one right answer about each of
|
||
* twelve sentences are the same number on that axis and are not the same
|
||
* learner. Only the second has met the situation.
|
||
*
|
||
* So coverage is counted here, one line at a time, and `situation-strength.ts`
|
||
* turns it into the claim. It is the fifth axis and the first that is not
|
||
* about a NAMED thing in the packs — `areasOf`'s comment says a fifth axis
|
||
* would need a fifth kind of provenance, and this one has it: `ItemSource`
|
||
* now carries the line.
|
||
*/
|
||
lines: Record<string, Trace>;
|
||
/**
|
||
* By what the question tests (`kinds/meta.ts`): verb forms, articles,
|
||
* words, understanding, saying it, the sound rules. "You keep missing
|
||
* articles" is a fact about this axis.
|
||
*/
|
||
skills: Record<string, Trace>;
|
||
/** By how far the Zurich German is from German: "1", "2", "3" (`distance.ts`). */
|
||
levels: Record<string, Trace>;
|
||
};
|
||
|
||
/** The key a line's evidence is stored under. One spelling, used everywhere. */
|
||
export function lineKey(scene: string, line: number): string {
|
||
return `${scene}:${line}`;
|
||
}
|
||
|
||
/** Every axis of the model, once: observing, decoding and summing devices all read this. */
|
||
export const MODEL_AXES = ["topics", "scenes", "groups", "words", "lines", "skills", "levels"] as const satisfies readonly (keyof LearnerModel)[];
|
||
|
||
/** A model built axis by axis from `MODEL_AXES`, so no copy of the list can drop one. */
|
||
export function modelFrom(axis: (name: keyof LearnerModel) => Record<string, Trace>): LearnerModel {
|
||
return Object.fromEntries(MODEL_AXES.map((name) => [name, axis(name)])) as LearnerModel;
|
||
}
|
||
|
||
export const EMPTY_MODEL: LearnerModel = modelFrom(() => ({}));
|
||
|
||
/** Which areas an item belongs to. One item can touch two — a scene and a topic. */
|
||
export function areasOf(item: PracticeItem): { axis: keyof LearnerModel; id: string }[] {
|
||
const own = originsOf(item);
|
||
// A kept word is scheduled by `review.ts` alone, so it is not tracked at all.
|
||
if (item.source.kind === "saved") return own;
|
||
const level = item.source.level;
|
||
return [
|
||
...own,
|
||
{ axis: "skills", id: KIND_META[item.kind].skill },
|
||
...(level ? [{ axis: "levels" as const, id: String(level) }] : []),
|
||
];
|
||
}
|
||
|
||
function originsOf(item: PracticeItem): { axis: keyof LearnerModel; id: string }[] {
|
||
const source = item.source;
|
||
switch (source.kind) {
|
||
case "grammar":
|
||
return [{ axis: "topics", id: source.topic }];
|
||
case "situation": {
|
||
const areas: { axis: keyof LearnerModel; id: string }[] = [{ axis: "scenes", id: source.scene }];
|
||
// A `gaptext` passage spans several lines and carries no single one; it
|
||
// still counts toward the scene. See `ItemSource`.
|
||
if (source.line !== undefined) areas.push({ axis: "lines", id: lineKey(source.scene, source.line) });
|
||
if (source.topic) areas.push({ axis: "topics", id: source.topic });
|
||
return areas;
|
||
}
|
||
case "word":
|
||
return [
|
||
{ axis: "words", id: source.word },
|
||
{ axis: "groups", id: source.group },
|
||
];
|
||
case "rule":
|
||
return [{ axis: "words", id: source.rule }];
|
||
case "saved":
|
||
// A kept word already has a schedule of its own in `review.ts`, and two
|
||
// mechanisms moving the same word would fight. Deliberately untracked.
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Record one answer.
|
||
*
|
||
* A SKIP IS NOT A MISS and is not recorded at all. The learner said "not now",
|
||
* which is an answer about their attention rather than about their knowledge,
|
||
* and counting it as a failure would make the model recommend whatever
|
||
* somebody happened to skip on a tram.
|
||
*/
|
||
export function observe(model: LearnerModel, item: PracticeItem, outcome: "right" | "wrong" | "skipped"): LearnerModel {
|
||
if (outcome === "skipped") return model;
|
||
|
||
const next: LearnerModel = modelFrom((name) => ({ ...model[name] }));
|
||
|
||
for (const { axis, id } of areasOf(item)) {
|
||
const before = next[axis][id] ?? { asked: 0, missed: 0 };
|
||
next[axis][id] = { asked: before.asked + 1, missed: before.missed + (outcome === "wrong" ? 1 : 0) };
|
||
}
|
||
|
||
return next;
|
||
}
|
||
|
||
/**
|
||
* How much confidence a rate needs before it is allowed to shout.
|
||
*
|
||
* OURS, not a finding — three answers is the point where a miss rate starts
|
||
* being about the material rather than about the afternoon. Stated as a
|
||
* constant so it is one decision rather than a number buried in an expression.
|
||
*/
|
||
export const CONFIDENCE = 3;
|
||
|
||
/**
|
||
* How badly an area needs work, as a number a sort can use.
|
||
*
|
||
* SHRUNK TOWARD ZERO BY SAMPLE SIZE, and getting this right took a failing
|
||
* test. The obvious smoothing — a notional extra right answer, `missed /
|
||
* (asked + 1)` — does not work: one miss out of one is still 0.5 and nine out
|
||
* of twenty is 0.43, so the first question somebody ever got wrong would
|
||
* outrank a topic they have been failing for a fortnight and would own their
|
||
* next four sessions.
|
||
*
|
||
* What is wanted is not a corrected rate but a rate we are entitled to act on.
|
||
* So the observed rate is multiplied by `asked / (asked + CONFIDENCE)`, which
|
||
* is near zero for one answer and approaches the true rate as evidence
|
||
* accumulates:
|
||
*
|
||
* 1 of 1 missed 1.00 × 1/4 = 0.25
|
||
* 2 of 2 missed 1.00 × 2/5 = 0.40
|
||
* 9 of 20 missed 0.45 × 20/23 = 0.39
|
||
*
|
||
* Two misses out of two still edges ahead of a chronic 45%, which is right:
|
||
* missing both attempts is real signal, just not as much as it looks.
|
||
*
|
||
* An area never asked returns 0 rather than 1. Unknown is not the same as
|
||
* weak, and treating it as weak would make the model chase novelty — which the
|
||
* recency ordering already handles, and handles better.
|
||
*/
|
||
export function pressure(trace: Trace | undefined): number {
|
||
if (!trace || trace.asked === 0) return 0;
|
||
return (trace.missed / trace.asked) * (trace.asked / (trace.asked + CONFIDENCE));
|
||
}
|
||
|
||
/** The most pressing area an item belongs to. Items touch at most two. */
|
||
export function pressureOf(model: LearnerModel, item: PracticeItem): number {
|
||
let worst = 0;
|
||
for (const { axis, id } of areasOf(item)) {
|
||
// Skills and levels are for REPORTING (and the level frontier), not for
|
||
// pressure: missing one grammar topic five times must not push every verb
|
||
// question forward, and struggling with hard words is no reason to be
|
||
// shown more of them. Pressure stays on the specific thing that is missed.
|
||
if (axis === "skills" || axis === "levels") continue;
|
||
worst = Math.max(worst, pressure(model[axis][id]));
|
||
}
|
||
return worst;
|
||
}
|
||
|
||
/**
|
||
* The areas worth going back to, worst first.
|
||
*
|
||
* `minimum` exists so a surface can refuse to name anything on one wrong
|
||
* answer. Telling somebody after a single miss that `wo-relative` is their
|
||
* weakness is a claim the evidence does not support, and it is the kind of
|
||
* false precision §8 forbids everywhere else.
|
||
*/
|
||
export function weakest(
|
||
model: LearnerModel,
|
||
axis: keyof LearnerModel,
|
||
{ limit = 3, minimum = 2 }: { limit?: number; minimum?: number } = {},
|
||
): { id: string; trace: Trace }[] {
|
||
return Object.entries(model[axis])
|
||
.filter(([, trace]) => trace.missed > 0 && trace.asked >= minimum)
|
||
.sort((a, b) => pressure(b[1]) - pressure(a[1]) || a[0].localeCompare(b[0]))
|
||
.slice(0, limit)
|
||
.map(([id, trace]) => ({ id, trace }));
|
||
}
|
||
|
||
/**
|
||
* Parse whatever is in storage, tolerating anything.
|
||
*
|
||
* IT TOOK `unknown` AND WAS HANDED A STRING, so it returned `EMPTY_MODEL`
|
||
* EVERY TIME and the learner model never once survived a reload.
|
||
*
|
||
* `Decode<T>` is `(raw: string) => T | null` — `createBrowserStore` passes
|
||
* `localStorage.getItem(key)` straight in, unparsed, which is what
|
||
* `decodeHistory` next door has always done correctly. This function declared
|
||
* `unknown`, and a function accepting `unknown` structurally satisfies one
|
||
* accepting `string`, so the mismatch type-checked perfectly. Then
|
||
* `typeof "{...}" !== "object"` was true of every value ever stored.
|
||
*
|
||
* WHAT IT COST, which is the reason this comment is long. Everything built on
|
||
* the model read an empty one on every page load: the focus panel, whose whole
|
||
* job is "what you keep getting wrong", had nothing to be wrong about; the
|
||
* mastered panel, which exists to say what you can do now that you could not
|
||
* before, could never say anything. The dashboard was reported as useless —
|
||
* "Heute nichts fällig. Kommen Sie morgen wieder" — and it was, structurally,
|
||
* because the record it reads from was thrown away between every render.
|
||
*
|
||
* NOTHING FAILED. History used a different decoder and persisted correctly, so
|
||
* sessions genuinely varied day to day and the one observable symptom of a
|
||
* dead model looked like the feature working. The parameter type is now
|
||
* `string`, which is what makes this un-writable a second time.
|
||
*/
|
||
export function decodeModel(raw: string): LearnerModel {
|
||
let parsed: unknown;
|
||
try {
|
||
parsed = JSON.parse(raw);
|
||
} catch {
|
||
return EMPTY_MODEL;
|
||
}
|
||
if (!parsed || typeof parsed !== "object") return EMPTY_MODEL;
|
||
const source = parsed as Partial<Record<keyof LearnerModel, unknown>>;
|
||
const axis = (value: unknown): Record<string, Trace> => {
|
||
if (!value || typeof value !== "object") return {};
|
||
const out: Record<string, Trace> = {};
|
||
for (const [id, trace] of Object.entries(value as Record<string, unknown>)) {
|
||
if (!trace || typeof trace !== "object") continue;
|
||
const { asked, missed } = trace as { asked?: unknown; missed?: unknown };
|
||
if (typeof asked !== "number" || typeof missed !== "number") continue;
|
||
if (!Number.isFinite(asked) || !Number.isFinite(missed) || asked < 0 || missed < 0) continue;
|
||
out[id] = { asked: Math.trunc(asked), missed: Math.trunc(missed) };
|
||
}
|
||
return out;
|
||
};
|
||
|
||
return modelFrom((name) => axis(source[name]));
|
||
}
|
||
|
||
/**
|
||
* THE LADDER: recognise a line before producing it.
|
||
*
|
||
* A line the learner has not yet recognised reliably is asked in a form that
|
||
* shows it — "Stimmt das?", the gist, the meaning of a word in it. Once it is
|
||
* recognised (asked twice or more, missed at most a quarter of the time), the
|
||
* same line comes back to be PRODUCED — built from its words, translated,
|
||
* transformed. Retrieval in a harder form is what makes a thing stick; asking
|
||
* the easy form forever is what makes practice feel like a loop.
|
||
*
|
||
* 0 means "this form suits this line now", 1 means "not yet / not any more",
|
||
* and kinds on neither rung are 0 always. Used as a tie-break after the
|
||
* schedule and after what the learner is struggling with, never before.
|
||
*/
|
||
export function recognised(model: LearnerModel, scene: string, line: number): boolean {
|
||
const trace = model.lines[lineKey(scene, line)];
|
||
return Boolean(trace && trace.asked >= 2 && trace.missed / trace.asked <= 0.25);
|
||
}
|
||
|
||
export function ladderOf(model: LearnerModel, item: PracticeItem): 0 | 1 {
|
||
const source = item.source;
|
||
// A card has the same two rungs, per WORD. Meaning → dialect asks for a
|
||
// word to be produced; for a word never met, that is a question with no
|
||
// way to answer it. So the dialect → meaning card of a new word goes first,
|
||
// and the other direction waits until the word has been asked once.
|
||
if (item.kind === "card") {
|
||
if (item.direction !== "produce" || source.kind !== "word") return 0;
|
||
return (model.words[source.word]?.asked ?? 0) > 0 ? 0 : 1;
|
||
}
|
||
if (source.kind !== "situation" || source.line === undefined) return 0;
|
||
const known = recognised(model, source.scene, source.line);
|
||
const rung = KIND_META[item.kind].rung;
|
||
if (rung === "recognise") return known ? 1 : 0;
|
||
if (rung === "produce") return known ? 0 : 1;
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* THE LEVEL A LEARNER IS WORKING AT, from their own answers: level 1 (like
|
||
* German) until it holds, then 2 (by a sound rule), then 3 (different, and
|
||
* the false friends). "Holds": at least twelve answers there, at most one in
|
||
* five missed. Twelve because fewer cannot tell a level from a lucky sitting.
|
||
*/
|
||
export const LEVEL_HOLDS = { asked: 12, missRate: 0.2 } as const;
|
||
|
||
export function frontierOf(model: LearnerModel): 1 | 2 | 3 {
|
||
for (const level of [1, 2] as const) {
|
||
const trace = model.levels[String(level)];
|
||
const holds = trace && trace.asked >= LEVEL_HOLDS.asked && trace.missed / trace.asked <= LEVEL_HOLDS.missRate;
|
||
if (!holds) return level;
|
||
}
|
||
return 3;
|
||
}
|
||
|