Language module Phase 4 — Language Reader — implementation plan
Companion to ADR-0026 (epub/pdf reading, reading state), ADR-0061 (import and content), ADR-0056 (personal offerings), ADR-0058/0059 (event lane, lexeme catalog), Language Module Migration V1 (decision 8, the Phase list) and the Phase 3 plan (its recorded deferrals). Phase 3 is complete. Phase 4 delivers the reader: the content pipeline for the personal and the Offering channels, the token-grained Language Reader, and the locator scheme.
Status: closed 2026-09-09 — every slice landed on develop (4a-1, 4b-1, 4a-2, 4c-2, 4a-3,
4b-2, 4b-3, 4c-1, 4d-1, 4d-2; git log is the record). Ratified 2026-09-08 (R1–R10 as written;
the ADR-0061 rule restated in Grounding — no re-import or replacement of a Content ever, retries
only before processed — was applied to the draft before ratification). R1 amended
2026-09-08: TokenDetails and Mouseover render in the parent page, not in the section document
(see R1). Decisions taken while landing, recorded in the commits: a processed enriched Content is
delivered as its package in both reader modes (one locator space per Content); sidecars are served
per part behind the entitlement gate; an undeclared epub/pdf is processed on arrival with its
pass-through bundle (the defect that had left the generic reader nothing to open); a text
Content always carries a declaration; “words met” on a Content counts encounter_count > 0
(narrower than the home’s “met”). Named follow-ups: personal-door refusal copy is English-only;
the document cap is not reachable from a client package; the Playwright learner lane has no
enriched-package fixture.
Grounding (verified 2026-09-08)
Section titled “Grounding (verified 2026-09-08)”- The generic reader exists and is the frame.
apps/learner-web/src/features/document-reader/renders epub and pdf with vendored foliate-js 1.0.1 (pdfjs-dist for pdf): foliate creates one iframe per section, the app injects a strict CSP into each section document (lib/sandbox.ts,script-src 'none'), positions are EPUB CFI (lib/locator.ts,lib/reading-position.tsover foliate’srelocate), progress is captured todocument_progress_event(no locator column; nothing persists the CFI). Delivery is a signed URL to the opaque object (document-delivery-service.ts). ADR-0026 chose this library and rejected Readium; its demarcation stands: the generic reader defends against hostile books, the Language Reader assumes reprocessed, trusted input, and the two never share a delivery path or a state model. - The predecessor’s reader is not what the migration plan describes. Boocrobes is a
hand-rolled host over a persistent same-origin iframe with
sandbox="allow-same-origin allow-scripts …"(no isolation), a synchronouswindow.__TC_READER_FRAMEAPI andwindow.parent.*property sharing — not a postMessage bridge. It never used CFI: positions are theenriched-text-fragmentid nearest the viewport centre, and those ids arecrypto.randomUUID()per processing run, so nothing outside one run can name a place in a book. Progress rides last-write-wins on the wholecontent.configblob. Its chapter-enrichment runtime (lazy render at 0.9 visibility above 50 000 tokens, the 15 s read rule, the per-token observer) andreadingSpans.tsare sound and already partly ported (Phase 3’smount.ts,encounter.ts). - The enrichment stage runs, but only over plain text.
runLangEnrichmentiterates parts fromDocumentTextSource.loadTextParts; epub and pdf answerno-text-extractor(a decline, not an attempt). The stage is awaited on the request path behind a dated gate that names Phase 4 as its expiry. The DOM walk that turns a chapter into fragment-tagged XHTML withfformatting (reformatElement/prepareFormattedElement,enrichHtmlToHtml) has no emergent counterpart; the characterization corpus carries the captured inputs and outputs of exactly that stage and marks it “⛔ NOT PORTED”. The enriched model has nof, andcontent_kindhas notext. - What a learner can import today: epub and pdf through
/workflow/personal-imports(homed in the sentinel org, bound to the personal offering) and media; no UI exists for it, and nothing setsdeclaration_payload, so no personal import is ever enriched. Teachers have no epub upload UI; org admins have/workflow/document-packages. - Events and locators:
contentRefis the<namespace>:<type>:<id>form andpositionan opaque locator; the renderer setspositionto the fragment id; no surface emitslang_reading_spanyet (the paste page has no artefact);lang_day_factalready folds spans. - Renderer seams already in place:
mountEnrichedTextMarkup(container, { document, contentRef, onEncounter, onAidShown, readDelayMs }),applyReaderConfig(config, doc?),ensureEnrichedTextBaseStyles(doc?), the store’sview(drivesinFramecoordinate handling), TokenDetails/Mouseover positioning in their own document. Two defects to fix on the way:finishMountre-applies config to the ambient document, and the host hook passes noview. - Reader config: 13 fields in localStorage per language (Phase 3 v1, versioned key, migration intended); the synced table was deferred here. Predecessor precedence: defaults → per-reader-type → per-content → runtime.
- Video is Phase 6 by ADR-0061 and the migration plan; the platform holds no cues and the player has no track callbacks. Nothing here touches it.
- Import and Content are terminal (ADR-0061). Neither is updated after its final state;
“multiplicity replaces mutation everywhere”: a new version of a file is a new Import, a better
processing of the same file is a new Content, and there is no re-enrichment. Every artefact,
locator and event in this plan is therefore scoped to ONE Content identity for its whole life;
the only repeated run the pipeline knows is the retry of a FAILED attempt before the Content
reaches
processed, which is not a re-processing of anything a learner has seen.
Rulings requested (ratify before slicing starts)
Section titled “Rulings requested (ratify before slicing starts)”R1 — The Language Reader is the enriched-text renderer inside the foliate-js frame, not a port
of the predecessor’s host. The reader shell (foliate-js: package parsing, section iframes, CSP,
pagination, TOC, CFI) is the generic reader’s; the Language Reader adds a per-section mount of the
Phase 3 renderer over the section’s own Document and window (the document/view seams),
with TokenDetails and Mouseover rendered in the PARENT page, positioned over the section’s
iframe by translating the section’s client coordinates through the iframe’s bounding rectangle
(amended at 4b-2 grounding: rendering them inside the section would mean injecting Mantine’s
stylesheet into every sandboxed section, which nothing does today and the section CSP only just
permits; the predecessor kept its popups in the parent and offset them). The migration plan’s “port the
iframe-sandboxed frame + postMessage bridge” is superseded: the predecessor has neither a sandbox
nor a bridge worth porting, and foliate-js already owns anchoring and rendering. ADR-0026’s
demarcation holds by construction — the Language Reader opens only the enriched package (R4),
never the raw upload, and writes token-grained events, never Reading State. “Two readers coexist”
becomes “one shell, two modes”: a Content with an enriched package opens in Language mode, any
other document in generic mode. Host chrome is Mantine, in features/language-reader.
R2 — Locators are EPUB CFI; fragment ids are deterministic. The migration plan’s planning
task is answered: the Language Reader adopts CFI for every position it records — the encounter
and aid events’ position, the reading span’s position/endPosition, and the resume position —
computed with foliate’s own CFI.fromRange/element anchoring. Fragment ids in the enriched
package are content-derived (<part ordinal>-<fragment ordinal> within the part), never random,
so a retried failed attempt and a test fixture reproduce the same package, and a fragment can be
named without a lookup; a locator’s validity never rests on them — a CFI addresses the package’s
structure, and under ADR-0061 that structure is fixed for the Content’s whole life. PDF positions stay the generic
reader’s page+region; the Language Reader has no PDF mode in this phase (R9).
R3 — The DOM walk is ported as a characterized stage, and the fence is amended for it. The
enrichment engine gains the predecessor’s chapter path: enrichHtmlToHtml = reformatElement
(reduce inline formatting into f fragments over the chapter’s own tag sets, the zh whitespace
rule included) + prepareFormattedElement (fragment-tag every enrichable text run) + per-fragment
enrichText, in a NEW module beside the existing engine, characterized byte-for-byte against the
corpus’s epub-cleaned → webpub-parsed capture (which exists for both languages), with the
existing pinned outputs untouched. This requires amending the Phase 2/3 fence
(packages/db/src/lang-enrichment/**, tests/characterization/** — not one character): the
amendment is additive files only, plus the §4 assertion that f is unrepresentable flipping to a
positive pin, and every existing byte-for-byte pin stays a pin. The enriched model gains an
optional f (formatting fragments) — additive on the strict schema; the renderer already consumes
it. The three silent {} bail-outs and the “replace the parent, not the text node” quirk are
ported as-is and pinned (they are the captured behaviour), with a named follow-up.
R4 — The artefact is an enriched package: the EPUB rewritten in place, plus a models sidecar
per part. Server-side, an epub Content is unzipped (the cartridge importer already handles OCF),
each spine XHTML is cleaned and DOM-walked (R3), enriched per fragment, and written back into a
copy of the package; per part a <href>.lang.v1.json sidecar carries that part’s models; a
manifest (langEnrichedPackageManifestSchema: parts, fragment counts, lexeme id count, engine
version, provenance) rides content_artifact.manifest_payload under role enriched-package. The
package is a valid EPUB, so foliate opens it unchanged; the reader fetches the sidecar for a
section when the section loads. Delivery mirrors documents: a signed URL per artefact, keyed by the
binding, entitlement-checked, plus a sidecar URL per part. Plain-text Content (R7) takes the same
path with one synthetic part. The enriched-document artefact of Phase 2/3 is retired: nothing
consumed it, and the package subsumes it.
R5 — Enrichment leaves the request path: a worker claims and processes. A new host
apps/api/src/lang-enrichment-worker.ts on the archive/telemetry worker pattern (chart worker
mirroring lang-event-consumer, health from its own claim loop) claims Content rows in
processing_requested, runs the stage (declines and the attempt cap unchanged), and publishes.
Imports return immediately with the Content in processing_requested; the request-path stage is
deleted, and the operator re-run enqueues rather than runs. The learner-facing state is the
Content’s own processing columns, already synced.
R6 — Reader config is a synced module table; reading position is ADR-0026’s Reading State,
built now for position only. lang_reader_config (person, language_tag, nullable
content_ref, the thirteen presentation fields as typed columns; owner-readwrite, LWW,
background-eager, delete door; precedence (content) > (∅) per language, resolved client-side;
the Phase 3 localStorage record migrates on first read and is then ignored). reading_position
(person, content_id, locator kind + value, updated_at; owner-readwrite, LWW, sever on
erasure like document_progress_event) is the first Reading State row (ADR-0026 §4, Tier 2
narrowed to position) and is written by BOTH readers — the generic reader today persists no CFI —
so resume works for any document. Bookmarks and annotations stay deferred.
R7 — Personal channel: import UI, the library, and pasted text saved as text Content.
content_kind gains text; saving a paste creates an import + a plain-text Content in the
personal space (declaration = pursued language + the pair complement, which is what turns
enrichment on) and the reader opens it once processed. The personal document import UI (epub;
pdf stays generic) lands on /lang/library: upload, the person’s Content with processing state,
open in the reader, remove (archive lifecycle). The 5 MiB/30 000-char paste cap stays for the
stateless endpoint; a saved text takes the document import’s cap.
R8 — Offering channel: the declaration is set at upload, by the teacher. The teacher portal
gains an epub/text upload with the lang.v1 declaration (language, gloss language, glosses on)
through the existing org document upload, bound to the offering or learning unit as today;
learners reach it through the viewport host, which dispatches a document carrying an
enriched-package artefact to the Language Reader host and everything else to the generic one.
No new entitlement: the binding’s read gate is the gate.
R9 — PDF enrichment is not Phase 4. No extractor exists, pdfjs text extraction loses reading
order on real books, and a wrong order corrupts every span. PDFs open in the generic reader with
resume through reading_position; the extractor is a named deferral.
R10 — Capture semantics ported, with the predecessor’s known defects not ported. Encounters:
per fragment, the 15 s on-screen rule, aidShown from the verdict at that moment (never from
“has a gloss mode” — the predecessor’s lookedUp conflation is the defect the corpus notes as
TODO: WARNING). Reading spans: one open span per reader, opened at the first read fragment,
extended per fragment, closed when the end fragment leaves or the section changes, flushed on
unmount; tokenCount from the models; positions are CFIs (R2). Lazy render above 50 000 tokens
per section at 0.9 visibility, eager below. The de flag stays runtime-only. Offline: the
package and sidecars ride the generic reader’s Cache API store, and prefetch policy 3
(offline-content) backfills the package’s lexeme ids when a Content is pinned.
Slices
Section titled “Slices”Workstream 4a — pipeline
Section titled “Workstream 4a — pipeline”4a-1 — the enrichment worker (R5). Host, chart values, runbook row; the request-path stage
removed; rerunLangEnrichment enqueues; integration: an import lands processing_requested, the
worker’s drainOnce publishes it.
4a-2 — the DOM walk stage (R3). Fence amendment recorded in this plan and in the
characterization README; reformatElement/prepareFormattedElement/enrichHtmlToHtml ported;
f on the enriched model; characterization extended over epub-cleaned → webpub-parsed for both
corpora; test:lang-enrichment byte-identical on every existing pin.
4a-3 — the enriched package (R4). EPUB text source (unzip, spine walk, XHTML clean), the
package writer, the manifest schema, the artefact role, delivery endpoints (package + sidecar),
retirement of enriched-document; the plain-text path through the same writer. Integration: an
epub fixture (the corpus’s) → package + sidecars; a second Content processed from the same bytes
is a new identity with its own package, and a retried failed attempt reproduces the first’s ids.
Workstream 4b — the reader
Section titled “Workstream 4b — the reader”4b-1 — reader config and reading position (R6). Both tables, applier, erasure, registry,
posture tests, migration regen; the localStorage migration; the generic reader writes
reading_position and resumes from it.
4b-2 — the Language mode (R1, R2, R10). features/language-reader: the section hook that
fetches the sidecar and mounts the renderer over the section document with the section’s view;
CFI positions on every event; span capture; lazy/eager strategy; TokenDetails/Mouseover in the
parent page over the section iframe (R1 as amended); the two Phase 3 defects fixed. Component
tests over the corpus package.
4b-3 — chrome and routes. Mantine chrome (TOC, settings drawer over lang_reader_config,
progress footer, keyboard paging), /lang/read/$contentId, the viewport host dispatch.
Workstream 4c — channels
Section titled “Workstream 4c — channels”4c-1 — personal channel (R7). text kind, save-a-paste, /lang/library, upload, processing
state, open, archive.
4c-2 — offering channel (R8). Teacher upload with the declaration; the learner viewport path; the offering-contents lane extended.
Workstream 4d — offline and stats
Section titled “Workstream 4d — offline and stats”4d-1 — offline (R10). Package pinning through the reader’s cache; policy 3 prefetch; the library shows pinned state.
4d-2 — per-Content stats. Words met / known share per Content from the sidecars ⨝ verdicts, on the library card and the reader footer.
Order and dependencies
Section titled “Order and dependencies”4a-1 → 4a-2 → 4a-3 → 4b-2. 4b-1 any time; 4b-3 after 4b-2; 4c-1 after 4a-3 + 4b-3; 4c-2 after 4b-3; 4d-1/4d-2 after 4c-1. Suggested lane: 4a-1, 4b-1, 4a-2, 4a-3, 4b-2, 4b-3, 4c-1, 4c-2, 4d-1, 4d-2.
Verification baseline (every slice)
Section titled “Verification baseline (every slice)”The Phase 3 baseline, plus: the characterization gate byte-identical on every existing pin and green on the new DOM-walk pins; the reader’s component tests over the corpus package; the lang integration lanes plus the new worker, package and reading-position cycles.
Recorded deferrals
Section titled “Recorded deferrals”- PDF text extraction and PDF Language mode (R9).
- Bookmarks and annotations (ADR-0026 Tier 2 beyond position).
- Video and subtitles: Phase 6.
- The DOM walk’s inherited quirks (silent bail-outs, parent replacement): pinned now, revisited with a corpus regeneration decision.
- Read-aloud / sentence TTS (the predecessor has only click-to-speak).