Skip to content

Language module Phase 2 — module foundation — implementation plan

Companion to ADR-0058 (event lane + projector charter), ADR-0059 (lexeme catalog + dictionary/delivery), ADR-0060 (pursuits), and Language Module Migration V1 (Phase plan → Phase 2). Decisions ratified in the 2026-08-01 design session; this plan is the executable slicing. Phase 2 is the module foundation: nothing here is learner-visible UI (Phase 3 starts that); it is the data model, the event lane, the projector, and the dictionary machinery that Phases 3–5 render.

  • Phase 1 complete (A1–A3, B1–B4, C1) plus the two review campaigns; prerequisites per the migration plan’s dependency line all present.
  • Both Phase-2 entry gates are discharged by ADRs: forwarder/projector ordering by ADR-0058 (archive-on-arrival; forwarder dormant), lexicon-projection language scoping by ADR-0060 (pursuits + module mapping + projection migration).
  • The pgxsinkit event-queue ingestion feature is specced and delivered to the pgxsinkit repo (2026-08-01). Nothing in Phase 2 blocks on it: ADR-0058 decision 7 mandates replay-path-first construction; the queue-consumer callback is a thin adapter added on arrival.
  • Module conventions (settled by recommendation, objection window closed): module tables live in public with the lang_ prefix (the lrs/archive pg schemas are non-synced server lanes; synced module tables ride the standard conventions — registry, RLS twins, erasure, migrations runbook). The extension-architecture doc’s namespace/ownership declaration is satisfied by the prefix + the module manifest. cmi5/xAPI→archive mapping is deferred to Phase 3+ (recorded in ADR-0058 decision 9). Learner/org-admin import UI is Phase 3; Phase 2 ships operator-grade tooling only.

Every slice: implementer → coordinator diff review → adversarial reviewer on destructive/privacy surfaces → full gates (scoped suites + coverage lane + validate at commit) → commit. Schema work follows the migrations runbook; every person-linked table registers erasure + row filters + RLS twins; every sync entry declares its tier and read-contract assertion.

2a-1 — pursuits + module mapping + projection migration (ADR-0060). Core person_subject_pursuit (subject FK, source, effective window; owner-managed; erasure delete-by-person). Module lang_subject_language mapping (subject → language tag; seeded for the launch languages). The B3 lexicon_node_inventory projection moves from competency-framework.ts into the module’s registry contribution with per-language public shape predicates and pursuit-driven activation (ADR-0060 decision 4’s activation model), revision-bumped; core keeps competency_node DENY_ALL; the P11 activation warning is retired by the scoping’s arrival. Scope consequence (accepted in review): the shared per-language shape carries the curated inventory only — B3’s evidenced-by-me disjunct is per-person by construction and incompatible with a shared shape log, so a learner’s own machine-segmented/learner-coined items are per-person data delivered by the module’s owner-read operational tables (2a-3/2a-4), not by this shape. The module manifest lands here as the module’s first artifact — the extension-architecture contract: namespace (lang.v1), owner, entity targets, schema version, compatibility policy, validation contracts, migration policy.

2a-2 — the lexeme layer (ADR-0059 decisions 1–2). lang_lexeme (L2-only identity, legacy_id, nullable competency_node_id bridge — added to the merge procedure’s HANDLED_REFERRERS with a repoint classification), lang_surface_form (form → lexeme, unique per (L2, form, lexeme)), and the slim column-projected resolution read projections (language-scoped lazy shapes; identical-predicate-per-language — the shared-shape-log case). Server mint path for never-seen forms (the ADR-0059 decision-3 lookup contract’s write half), alias-aware via resolveNodeKey conventions where it touches nodes (it does not — minting a lexeme is not minting a node; the bridge stays null until the projector evidences it).

2a-3 — module operational tables (ADR-0058 decision 5’s targets). The policy half is superseded by the offline plan R6 (2026-09-12): the verdict is computed from lang_word_state where it is read, and lang_node_policy_output is gone. lang_node_fact and lang_node_policy_output (the Q2 facts/policy split; both keyed (person, node), projector-only writers, owner-read sync entries at background-eager tier), learner source-preference rows (ADR-0059 decision 7). RLS: owner-read, no client writes (projector-only) except preferences (owner readwrite). Erasure: cascade-by-person. Carry-forward from 2a-1’s scope consequence: the client must be able to resolve identity (surface form) for its own non-curated nodes — the shared lexicon shape no longer carries them, so either the 2a-2 resolution index’s lexeme rows expose the competency_node_id bridge for a local join, or this slice adds an owner-scoped identity shape; decide here, when the fact tables land.

2a-4 — archive streams + projector core (ADR-0058). The C1 partitioning revisit trigger is resolved by declination (ruled 2026-08-01; rationale + the new trigger recorded in the Phase-1 plan’s C1 amendment) — the streams register unpartitioned. First, split the archive contract per ADR-0058 decision 3: the durable half of defineArchiveStream (name, versioned payload schema, retention, mandatory anonymize, archive-table mint) becomes the base native-stream definition with a client-event-id dedupe key; the rail bindings (source table/columns, client retention, forwarder projection) become an optional adapter over it — no dummy rail tables. Then register lang_token_encounter, lang_aid_interaction, lang_reading_span (strict-zod versioned payloads; indefinite retention; per-stream anonymize projections; the ADR-0058 decision-11 erasure consumer gate). The projector: pure fold functions (lexeme→node resolution + lazy minting, fact accumulation, policy-output recomputation stamped with the module policy version, B4 evidence emission, state derivation honoring + clearing merge-touched stamps), driven replay-path-first by an archive cursor scan; per-stream cursor table; two-class replay implemented (policy-only recompute; full truncate-and-rebuild scoped to projector-written tables, quiesced per ADR-0058 decision 6; policy-only recompute also re-derives touched state). The merge-touched sweep registers as the runner’s second work source (ADR-0058 decision 5e). Four obligations were pinned by the 2a-3 review; this slice discharges all of them. (i) The sweep’s discharge is not state-only — it recomputes lang_node_policy_output for stamped (person, node) rows as well, through the same recomputeDerivedForKeys the fold uses, so stale post-merge verdicts have a recomputation trigger that does not depend on event arrival (superseded by the offline plan R6: there is no verdict table left, so the state row the sweep re-derives is the whole of the obligation); a stamped row with no module facts still has its stamp cleared, or the sweep would return it forever. (ii) State-derivation totality is RESOLVED: transitions and state rows stay THRESHOLD-GATED, and totality is not required. A learner meets ~10⁵ items a year, so deriving a person_competency_state row for every touched (person, node) would put the module’s exposure volume into a core table built for human-meaningful assertions (ADR-0052 decision 3). The staleness worry that motivated the question is answered elsewhere: a merge now DELETES the affected policy rows (2a-3), so a post-merge verdict is absent rather than wrong and self-heals on the next fold or sweep, and a below-threshold person has no state row that could go stale. No separate staleness channel is needed. (iii) The fold’s fact accumulation is key-ordered on the same (person, node) axis the merge locks — the deltas are resolved to nodes and re-sorted before the upsert loop, because (person, lexeme) order is not (person, node) order — so a fold and a merge queue rather than cross; the merge takes FOR UPDATE on those rows before its own fold; where the projector mints it takes the framework advisory lock first, matching the merge’s advisory-before-row-locks ordering (ADR-0058 decision 10). (iv) The bridge-setter pins lexeme↔node language consistency (a lexeme may only bridge to a node of its language’s machine-lexicon framework — a convention the database cannot check across tables, so the projector’s own tests own it) and marks the minting lexeme canonical (ADR-0059 decision 1’s amendment); a lexeme that lands on a pre-existing node, or follows an alias redirect, is a resolution alias and is not marked. The learnerPolicies.ts port lands here as the judgment layer; v1 computes the predecessor’s two verdicts from the Phase-2 fact set (the review stream that carries first_success_date is Phase 5), so they coincide until declarations land — recorded at the port rather than silently collapsed. The queue-consumer adapter is a follow-up slice item gated on the pgxsinkit release (archive-insert + fold in one transaction, dedupe on event id). HARD OBLIGATION on that item: the projector’s quiesce lock is pg_advisory_xact_lock, which releases at each COMMIT — so a full re-derivation (a clear transaction followed by N scan transactions) is NOT held behind one lock today. That is sufficient while replay is the only driver, because two replays serialize per transaction and the fold converges either way. Before any LIVE consumer exists the rebuild must hold a session-scoped lock, or run as a single transaction: otherwise a live consumer can acquire the lock between the clear transaction and the first scan batch, fold a fresh batch, and advance the cursor past the archive prefix the rebuild was about to re-read — which is then skipped silently, its facts simply absent from the rebuilt model.

Workstream 2b — dictionaries and delivery

Section titled “Workstream 2b — dictionaries and delivery”

2b-1 — dictionary model + server delivery (ADR-0059 decisions 3–5). lang_dictionary (the ADR-0059 decision-5 checked scope discriminator: per-scope column sets under database checks, membership/enrollment access predicates, per-scope creation authority; content hash + atomic replace protocol for personal), lang_dictionary_entry (dictionary, lexeme, content — system/org content), the ingest-parser framework (bespoke parser per system dictionary; machine-translation as a provider with per-(lexeme, L1) content + the enrichment-service seam calling the external API), the entitlement-gated batch definitions endpoint (“entries for ids [X…] across accessible dictionaries”), personal blobs on the A3 prefix with hash-gated fetch. Erasure: personal rows + prefix (inherited); nothing else person-linked.

2b-2 — client data layer + operator tooling (ADR-0059 decision 6). The definition-cache manager (local store keyed (dictionary, lexeme); the five population policies: base list, SRS/goal lists, offline-content diff, live-parse backfill, lookup fallback chain), resolution index consumption, personal-blob explode into a local indexed table, entitlement-lapse eviction. Operator-grade system-dictionary import tooling (parser runner + report). No UI.

Workstream 2c — enrichment pipeline and import stage

Section titled “Workstream 2c — enrichment pipeline and import stage”

(Restored 2026-08-01 by ratification-review ruling: the governing migration plan places the enrichment port in Phase 2; the initial slicing had left it unscheduled.)

2c-1 — enrichment pipeline port (migration plan item 11). The portable enrichment TS moves into the monorepo behind the EnrichmentManager provider seam (enricher / parser / lemmatizer / translators / transliterator per language pair); CoreNLP + Bing ship unchanged as provider v1 (engine modernisation stays a post-migration project behind the stable interface). Tokenisation output carries lexeme ids (ADR-0058 decision 4’s enriched-content shape), minting never-seen forms through the 2a-2 server mint path.

2c-2 — import-workflow enrichment stage. Upload → document-package decompose → language enrichment stage (tokenise, per-token lexeme refs, gloss provisioning) → enriched webpub/VTT artefacts + catalog registration, integrated into the existing import workflow (the A3 import-service seams). The stage is POST-COMMIT, not a withinTransaction consumer: the degraded-not-failed posture requires the import to commit regardless of the enrichment outcome, and provider HTTP plus thousands of mints must not extend the import transaction. It is gated on an explicit language-content declaration, so undeclared content costs one primary-key SELECT and nothing else. Phase-4 entry gate, recorded here and at the seam — DISCHARGED by Phase-4 slice 4a-1: the stage was AWAITED on the request path in v1, which was sound only while the surfaces that reach real text were operator-grade (the org-admin generic import and the operator re-run). Before Phase 4’s content pipeline made text reachable from a learner upload, the stage had to move to background execution — otherwise a book-sized import is a gateway timeout while the server keeps working, and the learner is told an import failed that did not. It did: the stage now ENQUEUES (processing_requested, one transaction) and apps/api/src/lang-enrichment-worker.ts runs the engine. Media/VTT stays a typed seam until Phase 6 (verified: media_resource carries only an external captions_url; the platform holds no cues).

2a-1 independent. 2a-2 → 2a-3 → 2a-4. 2b-1 needs 2a-2 (lexeme ids); 2b-2 needs 2b-1. 2c-1 needs 2a-2 (lexeme minting); 2c-2 needs 2c-1. The 2a-4 queue adapter waits on the pgxsinkit event-queue release; everything else in 2a-4 does not. Phase 3 (first learner-visible slice) needs 2a-4 + 2b-2 + 2c-2.

Migrations runbook for schema work; row-filter/RLS tests in the schema test convention (executed against PGlite, not string-pinned only — the B3 precedent); erasure-registry test green; read-contract assertions for every new/changed sync entry; bun run validate + affected suites + the db coverage lane at commit; no new read helper wraps the upstream hooks.

Upstream gate (2026-08-01 — closed 2026-08-02)

Section titled “Upstream gate (2026-08-01 — closed 2026-08-02)”

Two pgxsinkit defects found by the 2a-3 reviews were handed to the pgxsinkit session (pgxsinkit/tmp/agents/defect-handover-apply-function-grants-and-arrays-2026-08-01.md): the P0 apply-function grant hardening (forged-claims impersonation via exposed RPC) and the P1 array-column cast support (uuid[]). Until the fix released, lang_source_preference client writes were gated off at the applier with a named refusal; nothing in emergent worked around either defect.

Closed by pgxsinkit 0.2.6 (deny-by-default ACL with role-existence-guarded revokes and an ACL converger, per its ADR-0054; array-aware payload casts): deps bumped, the pgxsinkit_utilities and sync_artifact migrations regenerated, the applier gate deleted, and the integration lane proves both fixes end-to-end (tests/integration/lang-source-preference-sync-cycle.integration.test.ts — multi-element and empty uuid[] round trips with claims-stamped ownership, and the 42501 refusal of a direct client-role call with forged claims, with the legitimate owner path proven unharmed in the same test). The remaining release item — the queue-consumer adapter, now on pgxsinkit’s first-class event lane (its ADR-0053) — is slice 2a-5: registry stream registration, the pgmq --events migration, the /api/events ingest route, a dedicated consumer worker host on the archive-worker.ts host shape (maintainer-ruled: separate Bun process; server adapter only, client outbox wiring stays Phase 3), archive-insert + fold in one transaction with the decision-11 erasure gate, and the session-scoped replay lock the 2a-4 hard obligation requires before any live consumer exists.

  • Offline model advance: backlog, with the aggregates+outbox view sketch (ADR-0058 decision 12).
  • Upward aggregation (list/level mastery): Phase 3, with list import.
  • Goal-progress evaluation: Phase 5.
  • cmi5/xAPI → archive mapping: Phase 3+ open question.
  • Learner/org-admin dictionary import UI: Phase 3.