Files
CatoandClaude 083dd52f0d feat(engine): courses in data, pack-declared forms, level sources, and meanings in the learner's language (#355)
* feat(course): every stored record names its course, and today's progress is the Zurich course's

A course registry (lib/course/registry.ts) lists the one course there is;
lib/variety/active.ts resolves its pack. Browser stores that hold course
progress move to an envelope keyed by course under .v2 keys, and a value
under the old .v1 key is read as the default course without being rewritten.
progress_devices, certificates and entitlements gain a course column that
defaults to the Zurich course. Item ids are unique across courses, and the
default course's ids are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* refactor(variety): the pack declares its articles, persons, respellings, voices and prompt lines

Article, FormLabel and VocabularyGroup were closed unions of the Zurich
values, the answer comparison folded Zurich respellings for every language,
word distance lower-cased as German, the voice ranking named two German tags
and the prompt builder carried Swiss spelling advice. Each is now a field of
the pack, read by the engine; a contract test over every pack refuses a value
the pack did not declare, and the leak test also looks for the taught
language's own words in engine code. The Ukrainian pack gains one verb with
its own pronouns and no articles. The 2,956 published items and the system
prompt are byte-identical.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* refactor(practice): an item's level comes from a source the course chooses

A course entered from a sibling language measures each item's distance from
that language, exactly as before; a course entered from zero reads a declared
CEFR band on the word, the line or the topic. levels.ts exposes both as
LevelSource and picks by Course.entry. Every published item keeps its level.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* feat(meaning): a meaning can be shown in the learner's language

A meaning is the bridge form plus an optional gloss in the interface
language. One pure rule (lib/domain/meaning/meaning.ts) decides what is
printed from the learner's answer to «Wie gut ist dein Deutsch?»: good shows
German only, as before and by default; some shows German and the gloss; none
shows the gloss; without a gloss German is always shown. Every exercise, the
word list and the scene pages print meanings through one component. The
answer is a course store, set in the settings and asked once after the start
card, only in an interface language that has glosses. Gloss sets are one
file per course and language, loaded on demand.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* content(glosses): English and Russian meanings for every word and scene line; French and Italian for every word

Machine drafts from the Zurich form and its German meaning together, marked
unreviewed in the data. One file per language beside the pack, keyed by the
German the course gives. Tests refuse a key no entry carries, an empty gloss
and two glosses for one German form; pnpm run glosses:coverage prints what
is covered.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* content(glosses): French and Italian meanings for every scene line

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* docs: courses, pack-declared forms, level sources and glosses, as they now are

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* refactor(variety): the pack says which grammatical person each of its labels is

The gloss check and the prompt's auxiliary table, both new on main, matched
the Zurich labels «ich» and «er» by name. The forms pass of the leak test
caught it on rebase. The pack now declares personOf, and both read it; the
system prompt and the published items are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-25 14:17:35 +01:00

220 lines
7.8 KiB
TypeScript

/**
* What this browser is actually holding for Heidi, and how to be rid of it.
*
* DERIVED FROM THE PRIVACY PAGE, not listed again.
*
* `lib/config/privacy.ts` already enumerates every flow with the storage key
* beside it, precisely so a reader can open their own dev tools and check. A
* second list here would be the same claim written twice, and the copy that
* drifts is always the one nobody is reading — a settings page that forgot a
* key would quietly leave data behind while promising it was gone. So the keys
* come from `FLOWS`, and the privacy page's own test already asserts that each
* one still appears somewhere in the code.
*
* WHY SIZE AND NOT CONTENTS. Reporting "4 conversations, 11 saved words" would
* need this module to know the shape of every store, which is four decoders
* that go stale one at a time. Bytes need no shape, cannot go stale, and
* answer the question somebody actually has when they open this: is there
* anything of mine in here, and how much.
*
* Pure apart from the storage calls, which are guarded: `localStorage` throws
* rather than returning null in a private window and in a browser set to block
* site data, and a settings page that crashes on open is worse than one that
* says it cannot read.
*/
import { FLOWS } from "../config/privacy.ts";
import { legacyKeyOf } from "../course/stored.ts";
export type DeviceStore = {
/** The flow id, so the page can reuse the privacy page's own translated label. */
id: string;
/** The `localStorage` key. */
key: string;
/** Bytes it occupies, or 0 when nothing is stored under it. */
bytes: number;
};
/**
* Every `heidi.*` key the privacy page declares as living on the device.
*
* `place === "device"` rather than `leavesDevice === false`: the learner's own
* model key is stored here AND forwarded on the request it is for, so it is a
* device store that leaves — and it is certainly something somebody opening
* this page wants to be able to delete.
*/
/**
* How a storage key is recognised inside a `where` string.
*
* EXPORTED, because `privacy.test.ts` needs the same pattern to check that a
* declared key still exists in the code — and had its own copy, which is the
* duplication this whole module is about. Two regexes for one convention drift
* silently: adding `heidi.dictation.recogniser-dead.v1` matched one and not
* the other, because only one of them allowed a hyphen.
*
* Hyphens are allowed. `v1` suffixes are allowed. Colons are NOT — a key that
* uses them is invisible here, which is exactly how the dictation verdict
* escaped both the privacy page and the delete-everything button.
*/
export const STORAGE_KEY_PATTERN = /heidi\.[a-z0-9.-]+/;
export function declaredKeys(): Array<{ id: string; key: string }> {
const out: Array<{ id: string; key: string }> = [];
for (const flow of FLOWS) {
if (flow.place !== "device") continue;
const key = flow.where.match(STORAGE_KEY_PATTERN)?.[0];
if (key) out.push({ id: flow.id, key });
}
return out;
}
/**
* A declared key and everything stored under it.
*
* Most flows are one key. chatkit's conversation store is a family — the list
* at `<key>:v1` and each conversation at `<key>:v1:<id>` — and a delete that
* removed only the list would leave every conversation behind while the page
* said they were gone. So a key owns itself and every key beginning `<key>:`.
*/
export function familyOf(key: string, stored: readonly string[]): string[] {
return stored.filter((k) => k === key || k.startsWith(`${key}:`));
}
/**
* The declared key itself, whatever this browser holds under it, and the key
* the same store had before courses existed (`lib/course/stored.ts`): a value
* still sitting there is the learner's, so it is counted, exported and
* deleted with the rest.
*/
function keysOf(key: string): string[] {
const legacy = legacyKeyOf(key);
const stored = storedKeys();
return [...new Set([key, ...familyOf(key, stored), ...(legacy ? familyOf(legacy, stored) : [])])];
}
function storedKeys(): string[] {
try {
const out: string[] = [];
for (let i = 0; i < window.localStorage.length; i++) {
const k = window.localStorage.key(i);
if (k) out.push(k);
}
return out;
} catch {
return [];
}
}
function sizeOf(key: string): number {
try {
let bytes = 0;
for (const k of keysOf(key)) {
const raw = window.localStorage.getItem(k);
if (raw) bytes += new Blob([raw]).size;
}
return bytes;
} catch {
return 0;
}
}
/** What is on this device right now. Empty on the server, where there is none. */
export function readStores(): DeviceStore[] {
if (typeof window === "undefined") return [];
return declaredKeys().map(({ id, key }) => ({ id, key, bytes: sizeOf(key) }));
}
/**
* Storage as an external store, which is what it is.
*
* `store.ts` next door already treats a single key this way, and for the same
* reason: a React state mirror of something the browser owns has to be pushed
* back into sync by hand after every write, and the sync that gets forgotten is
* the one in another tab. Subscribing instead means a delete here and a delete
* in a second tab both reach this list, and the component needs no effect.
*
* The snapshot is cached because `useSyncExternalStore` compares by identity —
* a fresh array every call is an infinite render loop. It is dropped on any change
* rather than diffed: four `getItem` calls are cheaper than being clever.
*/
const listeners = new Set<() => void>();
let snapshot: DeviceStore[] | null = null;
const announce = () => {
snapshot = null;
for (const l of listeners) l();
};
export function subscribeStores(onChange: () => void): () => void {
listeners.add(onChange);
// `storage` fires only for OTHER tabs, which is exactly the case a manual
// refresh after our own write would miss.
window.addEventListener("storage", announce);
return () => {
listeners.delete(onChange);
window.removeEventListener("storage", announce);
};
}
export function storesSnapshot(): DeviceStore[] {
if (snapshot === null) snapshot = readStores();
return snapshot;
}
/**
* The server's answer, as one frozen value.
*
* Module-level so its identity is stable across renders: returning a new `[]`
* from `getServerSnapshot` is the same infinite loop as returning a new array
* from the client one.
*/
export const NO_STORES: DeviceStore[] = [];
export function forget(key: string): void {
try {
for (const k of keysOf(key)) window.localStorage.removeItem(k);
} catch {
// Nothing to do and nothing worth saying: a browser that refuses to delete
// also refused to store, so the list is already right.
}
announce();
}
/**
* Everything, as one object, for a person who wants to keep it.
*
* The counterpart to deletion and the half most products skip. Somebody who is
* told their data is theirs should be able to walk out with it — and here that
* is four keys and no server round trip, which is the one part of this
* architecture that makes export trivial rather than a project.
*
* Values are parsed where they parse so the file is readable rather than a
* wall of escaped JSON inside JSON.
*/
export function exportAll(): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const { key: declared } of declaredKeys()) {
for (const key of keysOf(declared)) {
try {
const raw = window.localStorage.getItem(key);
if (raw === null) continue;
try {
out[key] = JSON.parse(raw);
} catch {
out[key] = raw;
}
} catch {
// Unreadable storage: the export simply does not contain that key.
}
}
}
return out;
}
/** Bytes as a person reads them. */
export function humanSize(bytes: number): string {
if (bytes <= 0) return "0";
if (bytes < 1024) return `${bytes} B`;
return `${Math.round((bytes / 1024) * 10) / 10} kB`;
}