Skip to content

Language module Phase 5 — spaced repetition, goals, stats — implementation plan

Scope: the fifth phase of the language-module migration (docs/architecture/language-module-migration-v1.md, decision 7 and the Phase 5 line), plus what Phase 3 parked here (list-level aggregation 3c-4, the level construct and level-badge, the goals UI, the review grade source and card retirement). Phase 4 is closed. Phases 4 and 5 touch disjoint surfaces; nothing here reopens the reader.

Status: closed 2026-09-09. Every slice is on develop (5a-1 be5a5a69, 5b-1 362f5fb6, 5a-2 63ff07c8 + 77347546, 5c-1 ca47e527, 5c-2 4676a6de; the goal create contract fix e9b9ed73); the pgxsinkit build carrying 24956c7 (json columns decoded once on the client apply path, the read model’s overlay test hashed, opt-in localIndexes) closed the last two items: the list-state lane’s shape test is green and lang_card declares its due_at and lexeme_id local indexes. Measured on 100k cards after the bump (bun run --cwd packages/offline-data test:perf): due scan 16 ms, new candidates 49 ms per type, whole selection 205 ms at session start; within a session the next card is instant from memory. Ratified 2026-09-09 (R1–R8 as amended in review: card state is client-owned, phrase cards and recent-sentence collection are v1-plus, dashboards leave the phase; today’s review counts come from the local card rows). Decisions taken while landing, in the commits: list state creates a row at in-progress (unlike a node); “met” for a Content counts encounter_count > 0; the projector’s achievement write stamps the LWW clock; a finished goal keeps its status and loses its frozen figure on full re-derivation; the applier’s terminal-field refusal sentence has no domain home yet.

  • Grades already flow. lang_review_grade (lang-event-streams.ts:241-288) carries {lexemeId, grade ∈ unknown|hard|good|known, source ∈ content|dictionary|list|list-import, contentRef?, position?}; langGradeIsSuccess = grade !== "unknown". The fold accumulates grade_count, success_count, first/last_graded_at, first_success_at on lang_node_fact; policy v2 derives aids_off, counts_as_known, srs_eligible = !excluded. Scheduling scalars are explicitly absent (lang-node-operational.ts:236-239). /lang/grade (3c-2) and TokenDetails’ 1–4 keys are the two grade producers; recordGrade is the one writer.
  • The predecessor’s SRS (transcrobes/packages/lib/src/review.ts): SM-2 with grades mapped 2/3/4/5 (unknown/hard/good/known), pass = grade ≥ 3, gap 1 → 6 → round(gap × efactor), efactor += 0.1 − (5−g)(0.08 + (5−g)0.02) clamped at 1.3, failure resets gap and repetition; due = last success + gap days, or a 600 s wait after a failure; known retires the card. Card types graph | sound | meaning | phrase; a card is (word, card_type), minted lazily. Due selection mixes new and revision cards against maxNew 20 / maxRevisions 100 with a learner-set day start; one card per word per day; nb_seen-then-frequency ordering for new cards. “Retention” is not a predecessor concept; it is ADR-0005’s objective name.
  • Red lines (ruled 2026-09-09). This is an education tool: the SRS must be extremely fast and fully offline; new-card ordering must be rich (fixed and dynamic criteria); next-review accuracy is not a product requirement (review history may later inform teachers’ effort assessments); a last-writer-wins overwrite is acceptable wherever it keeps the design simple, fast and offline. Design choices that do not touch those lines stand.
  • Card state is therefore the client’s. ADR-0058 makes the projector the writer of derived state (decisions 2, 6) and backlogs offline model advance (decision 12); the predecessor kept card rows client-side and synced them, and an SRS whose grades only take effect after a server round trip is not offline. R2 records the ruled exception: lang_card is client-written and LWW-synced; the grade event still lands in the archive, so a rebuild of card state from events remains possible as a maintenance act. Aids and known-ness keep flowing through the projector as in Phase 3 (a grade’s effect on aids_off arrives with sync; Phase 3 R2 accepted that). Superseded by the offline plan R1/R2 (2026-09-12): a grade also writes lang_word_state, and aids and known-ness are computed on the device from that row.
  • Goals exist as a core table (goal, owner-readwrite, LWW; referent_kind ∈ competency_framework_version | assessment_definition | extension; success_criterion v1 = {kind: "state-threshold", targetState, thresholdPct}; criterion_policy_version; status active → achieved | archived). No UI, no evaluation; ADR-0058 decision 5 names goal-progress evaluation as the Phase 5 seam keyed by criterion_policy_version. The lang.v1:word-list:<id> referent resolves to a curated list node or a personal list row (3c-3).
  • Lists are container nodes (tier list, node_key = "list:<slug>", members by is-child-of with sequence_number = rank). HSK 1–6 are six such nodes; nothing orders them except the key string. The client folds per-list coverage (foldListCoverage, use-lang-stats.ts:67-98); the server-side aggregation is the parked 3c-4, whose target is person_competency_state for the list node (no lang_list_fact exists and the module refuses a second home for mastery).
  • level-badge is dark: LearnerFacet.levelLabel is never set (use-learner-facet.ts).
  • Native Extensions (CONTEXT.md:421-425; migration decision 7): the QTI Native Extension is the interaction contract only — one templated namespaced item per card type, Mantine-skin rendered, payload resolved from the node at delivery; the review record is a lean module event on the rail, never item_session; drill telemetry never lands in core assessment tables. flashcard/word-card/dictation are already in the ADR-0050 widget/activity vocabulary.
  • Surfaces: /lang home with useLangStats and @mantine/charts; the lang-progress widget over LearnerFacet.langProgress; lang_day_fact (encounters, lookups, grades, successes, reading ms); streak from lang-day-facts.ts. No teacher-side view of a learner’s language progress exists and the module tables are owner-only by posture.
  • Sentences: the predecessor’s phrase cards drew on userrecentsentence; emergent stores no sentences. The enriched sidecars of a person’s Content carry sentences per model, cached offline for pinned Content (4d-1).
  • Import and Content are terminal (ADR-0061); nothing here touches Content.

Rulings requested (ratify before slicing starts)

Section titled “Rulings requested (ratify before slicing starts)”

R1 — A card is (person, node, card type), never a row until it is scheduled. Card types are a domain enum graph | sound | meaning | phrase. Cards are not minted: a node with srs_eligible and an enabled card type IS a new card until the scheduler has a state row for it. lang_review_grade gains cardType? and the review source; a grade with a card type is a card-level grade (that card only); a grade without one (content, dictionary, list, list-import) is word-level and applies to every enabled card type of the node. known retires: a card-level known retires that card, a word-level known retires all of the node’s cards (Phase 3’s “know completely → never schedule”). Retirement is a scheduling output, not a declaration: lang_word_state.excluded is untouched and srs_eligible keeps meaning “may be scheduled at all”.

R2 — Card state is the client’s, written at grade time, synced last-writer-wins. A new owner-readwrite module table lang_card (person, lexeme, card type; the predecessor’s fields as they are: gap, repetition, efactor, due_at, known, first_revision_at, last_revision_at, first_success_at), LWW on the lang_reader_config pattern, minted lazily at first practice. The client applies the predecessor’s SM-2 exactly (supermemo and practice ported verbatim into packages/domain, grades mapped 2/3/4/5, pass = grade ≥ 3, 600 s failure wait) and writes the row locally in the same act as the grade, so the card is rescheduled before the finger lifts and for as long as the device is offline. A word-level grade (content, list, dictionary, list-import) upserts every enabled card type of the lexeme; known retires. Two devices grading the same card while both offline: the later row wins, by ruling. The projector computes no scheduling. Recorded as an amendment to ADR-0058 (decision 12’s scope; a ruled client-owned exception to projector-written derived state).

R3 — Selection is local and the learner’s next card appears in under 250–300 ms; new-card ordering is a scored policy over local columns. The practice session selects from the local store: repeats (failed this session, past the failure wait), due revisions (due_at ≤ now, not known), and new cards (srs_eligible nodes with no lang_card row of that type), mixed by maxNew/maxRevisions and progress as the predecessor does, one card per lexeme per day, a learner-set day start. New-card ordering is a versioned scoring policy in packages/domain over columns the client already holds: fixed criteria (source-list rank, frequency, level ordinal) and dynamic ones (encounter_count, last_encountered_at, aid_interaction_count, failures on sibling card types), with the predecessor’s presets (Personal, frequency, natural order) as named weightings and a learner-chosen preset in lang_practice_config. The budget is the learner’s: next-card appearance, from grade to the next prompt painted, under 250–300 ms on the practice surface; the selection query takes whatever share of that the rendering leaves it. The predecessor found overlay views collapsing plans by 70× and fell back to a per-day staging table; 5b-1 measures first and reaches for the same device only if the measurement demands it. Today’s counts are the learner’s too: a card whose first_revision_at falls after the learner’s day start is a new card done today and one whose last_revision_at does is a revision done today, counted from the local lang_card rows (instant, offline, consistent across devices through the synced rows); maxNew/maxRevisions are enforced against them and the surface shows done-today against the limits. Session configuration is a new owner-readwrite module table lang_practice_config (person, language_tag; max_new, max_revisions, failure_wait_s, day_starts_hour, card_types enabled, new_card_ordering preset, source_list_refs) with the predecessor’s defaults.

R4 — The retention seam is a named module function behind a domain constant, not a framework. ADR-0005 reserves the objective; no Selection Policy interface exists. Phase 5 defines RETENTION_OBJECTIVE = "retention" in domain and one module entry point, selectPracticeCards(input), that the practice surface and any future selection policy call; the scheduler stays module code. Nothing else is built for the seam.

R5 — Card rendering is the module’s; the Native-Extension templates are contracts in domain; phrase cards are a type, not a feature, this phase. Card types are the domain enum graph | sound | meaning | phrase and the matching database enum, so nothing migrates later; phrase cannot be enabled in lang_practice_config and has no renderer, no sentence lookup and no sentence store in Phase 5 (recent sentences as a whole are deferred). Three namespaced item templates are live (lang.v1:card:graph|sound|meaning; the fourth is declared and inert) as the interaction contract in packages/domain (prompt slot, answer slot, the node payload each resolves at delivery), and the ADR-0050 activity kind flashcard resolves to the practice surface. No QTI item is authored or stored in assessment_definition, no item_session is written: drill acts are events (migration decision 7). The Mantine renderers reuse TokenDetails’ pieces: graph shows the graph, sound the phones, meaning the definitions from the definition cache.

R6 — List-level state lands (3c-4), and it is what “level” reads. The projector writes person_competency_state for list nodes: in-progress when any member is demonstrated, demonstrated when the share of members counts_as_known reaches the list policy threshold (LANG_LIST_STATE_POLICY_VERSION = 1, 80 %), re-derived for the lists containing any node the batch touched. Curated list import gains an optional --level <ordinal> so a list can be a level in its language (HSK 1–6 → 1–6; the frequency list has none), stored on the list node’s revision metadata and projected into lang_list_<lang>. Level = the highest ordinal whose list and every lower ordinal’s list are demonstrated; LearnerFacet.levelLabel is the list title, level-badge lights, the home shows it with the next level’s coverage.

R7 — Goal progress is projector-derived; achievement is written by the projector. A new projector-owned goal_progress (goal, person; progress_pct, evaluated_at, criterion_policy_version) is re-evaluated for a person’s active goals in the same fold turn that touches any node under a goal’s referent: for a lang.v1:word-list referent the members’ person_competency_state against targetState; for a competency_framework_version referent the framework’s nodes likewise. When progress_pct ≥ thresholdPct the projector sets goal.status = achieved through the server write path; a later client edit (archive) wins by LWW as any later write does. The evaluation seam is goal.criterion_policy_version: a criterion policy bump re-evaluates every active goal in the policy-only replay class. Alternative named and rejected: the client observing coverage and flipping status itself (no server truth, diverges per device, and ADR-0052 decision 9 puts progress derivation in the evidence → state machinery).

R8 — Goals surface for learners only; teachers see nothing new this phase. Every goal write is a client write on the synced goal row over pgxsinkit (no endpoint); /lang/goals: create a goal over a curated list, a personal list (lang.v1:word-list:<id>) or a level (the list node with that ordinal), with targetState and thresholdPct (defaults demonstrated, 100 %), an optional due date; progress from goal_progress with the client’s own coverage fold as the display while the row is hydrating; achieved and archived states; a goals tile on the home. The goal table stays out of the teacher and admin registries (existing posture); a teacher view of learner language progress is recorded as a deferral, not built.

Dashboards are not Phase 5. The home keeps only the practice entry point (due and new counts, part of 5b-1); a dashboards phase (review split, day-level review facts, teacher views) is recorded as a later phase.

5a-1 — the card table and SM-2 (R1, R2). cardType/review on the stream; lang_card and lang_practice_config (schema, RLS twins, erasure registry, owner-readwrite sync entries, migration set regenerated; the card-type database enum with phrase); supermemo/practice ported verbatim into domain with the predecessor’s tests beside them; the ADR-0058 amendment note; lane lang-card-cycle (a grade writes the card locally, the row and the event both reach the server, a second device receives the row, LWW on a concurrent overwrite, known retires, a word-level grade upserts every enabled type).

5a-2 — list-level state and the level (R6). List state derivation in the fold; --level on lists:import and the projection column; level policy; levelLabel on the facet; lane lang-list-state-cycle (grades over a list’s members flip the list node’s state and the level).

5b-1 — the practice surface (R3, R4, R5). selectPracticeCards and the ordering policy; the session state machine (prompt → reveal → grade, repeats, day boundary); graph/sound/meaning renderers; /lang/practice; flashcard activity kind → surface; the home entry point with due/new counts; component tests over real offline-data views; the next-card budget measured on the surface and recorded in the slice’s commit.

5c-1 — goal progress and achievement (R7). goal_progress (schema, RLS, erasure, sync owner-read); evaluation in the fold; achieved write; criterion-policy replay; lane lang-goal-progress-cycle (a goal over an HSK list reaches achieved through grades; a policy bump re-evaluates; archive after achieved wins).

5c-2 — goals UI (R8). /lang/goals, the create form with the three referent kinds, progress and states, the home tile.

5a-1 → 5b-1; 5a-2 after 5a-1; 5c-1 after 5a-2; 5c-2 after 5c-1. Suggested lane: 5a-1, 5b-1, 5a-2, 5c-1, 5c-2.

The Phase 4 baseline, plus: lang_card and lang_practice_config carry the full learner-writable table discipline (row filters, RLS twins, erasure, optimistic-attribution and writable-column guards); the ported SM-2 is pinned against the predecessor’s formula; the practice session’s component tests run over real offline-data views; next-card appearance is measured on the surface; the lang integration lanes plus the three new cycles.

  • Teacher view of a learner’s language progress and goals (owner-only posture stands).
  • Local rescheduling during an offline session (ADR-0058 decision 12 stands).
  • Authored/stored QTI items for the card templates; the contract only (R5).
  • Recent sentences as a whole, v1-plus: no collection during reading (the predecessor’s collection path is not ported), no sentence store, no phrase renderer, phrase stays disabled (R5).
  • Dashboards: review split, day-level review facts, teacher views of progress and goals (a later phase).
  • Rebuilding lang_card from the archived grade events: possible by construction, built only when a need appears (R2).
  • Automatic goal creation (e.g. “next level”); goals are learner-created (R8).
  • Phase 7 seeding of lang_card_fact/lang_card_schedule from predecessor card state: Phase 7 decides whether it lands as synthetic lang_review_grade events (source: "import") or as a one-time fact write; R2’s facts-first shape admits either.