German B1+ Exam-Prep PWA — Plan
Context
Build a mobile-first PWA (UI in English or Arabic, learning material in German) for learners preparing German B1/B2 exams (Goethe, telc, ÖSD, DTZ). Three bottom tabs: Cards (flashcards, spaced repetition), Quiz (fill-the-gap + mixed per topic, "All topics", and a randomized 60–80-question Quick test), Rules (rules + common mistakes). Nine content topics are given as headlines by the owner and 13 more are added for full exam coverage (22 total); all content is generated originally by omp into seed files and curated by the owner in an admin dashboard. End goal is revenue → freemium with a paid Pro pass, payments via a Merchant-of-Record, server-side content gating. Working name: B1+ Deutsch, repo deutsch-b1.
Scope set by the owner during planning: (1) the interface is either English or Arabic (switchable; Arabic is RTL) — German appears only as the learning material itself, never as UI text; (2) every card and rule carries 2–3 original usage examples (German + English + Arabic translations); (3) every quiz question has exactly one correct answer, no multi-select anywhere; (4) the code lives in a private GitHub repo created from the Pi; (5) an advertising/growth plan with in-app attribution, referral and SEO is part of the deliverable; (6) extra agent skills are vetted and installed before coding; (7) grammar content must be correct, including disputed cases such as Dativ vs Akkusativ government: a source-backed verification pipeline (see "Content correctness policy") gates what users can see. No process can certify 100 % by itself, so the plan makes a human-approved state the only "certified" state and treats user error reports as the residual control.
Decisions (defaults — only the items under "Assumptions" are user-overridable)
| Area | Decision |
|---|---|
| Framework | Next.js 15 App Router, TypeScript, Tailwind v4, shadcn/ui, lucide-react icons |
| PWA | @serwist/next service worker (precache app shell, NetworkFirst for /api/content/*), manifest.webmanifest, custom install banner |
| Local state / offline | Dexie (IndexedDB) tables bundles, reviews, attempts, outbox; Zustand for UI state |
| DB / ORM | Postgres 16 + Prisma |
| Auth | Auth.js v5: Email magic link (Resend) + Google; guest mode with anonymous id, merged on login |
| Payments | Lemon Squeezy (MoR, handles VAT/global tax): products pass-90 €9.99 (90 days) and lifetime €19.99; webhook order_created |
| UI language | Two UI locales: English (en, default) and Arabic (ar, RTL) via next-intl without URL prefix for app routes (messages/en.json, messages/ar.json, identical key sets, enforced by a vitest). No German UI exists; German is only learning content. Locale in cookie locale (1 year) and User.locale; first visit: browser language starting with ar → ar, otherwise en; switch lives in the header avatar sheet. <html lang dir> follow the locale (ar → dir="rtl"). Translated content fields exist in both languages (meaningEn/meaningAr, examples[].en/.ar, explanationEn/explanationAr, bodyMdEn/bodyMdAr, noteEn/noteAr, titleEn/titleAr) and the app shows only the active locale's one; German learning text is always lang="de" dir="ltr". Admin dashboard is English only. |
| Analytics | Own Event table (no third party); admin dashboard aggregates |
| Staging | On the Pi: next dev on 127.0.0.1:3850 (user unit deutsch-b1-dev.service), Postgres in Docker, Caddy site https://<pi-host>:3850 (same pattern as omp-stats :3847) |
| Production | Hetzner CX22 VPS, Docker Compose (app + postgres + caddy), GitHub Actions builds the image to GHCR and deploys on main via SSH, domain bought by owner |
| Repo | Private GitHub repo deutsch-b1 under the account authenticated in gh on the Pi (gh auth status currently reports NOT logged in and no GH_TOKEN is set; fixed in Phase 1 step 0a) |
| Workflow | Initial commit on main, then feature branches + pull requests; owner merges; never push to main after the initial commit; commit identity omp-pi <omp-pi@albishara.net> (already set in global git config) |
Business model
Exam prep is time-boxed (6–12 weeks), so a one-time pass converts better than monthly subscriptions and avoids churn ops.
| Tier | Gets | Price |
|---|---|---|
| Free | Topics konnektoren + satzbau + pruefung (exam guide) fully; first 15 cards + 10 questions of every other topic; rules of free topics + top 10 mistakes; 1 Quick test/day capped at 20 questions; study plan + countdown; local progress |
€0 |
| Pro Pass 90 | All topics, unlimited 60–80 Quick test, Sprachbausteine mock tests, mistake notebook, weak-topic trainer, writing/speaking trainer, cloud sync, offline packs | €9.99 one-time, 90 days |
| Pro Lifetime | Same, forever | €19.99 one-time |
Gating values live in Setting rows so the owner tunes them in admin without deploys: freeTopicSlugs=["konnektoren","satzbau","pruefung"], freeCardsPerTopic=15, freeQuestionsPerTopic=10, freeQuickQuizPerDay=1, freeQuickQuizSize=20, freeMistakesCount=10, freeCardsOverride={"wortschatz-b1":30} (per-topic override of freeCardsPerTopic; the "partial" entries in the Topics table are exactly haeufige-fehler → freeMistakesCount and wortschatz-b1 → this override).
Growth loops (no extra scope now; content supports them): public SEO rule pages for free topics (/rules/<slug> server-rendered, indexable), share-image of Quick test result, Telegram channel "Wort des Tages" deep-linking to a card (owner already runs a Telegram bot).
Product spec
Topics (22: 9 from the owner's headline list + 13 added for exam coverage) — content/seed/<slug>.json
| order | slug | titleEn | titleAr | free | cards / questions / rules |
|---|---|---|---|---|---|
| 1 | konnektoren |
Connectors & linking words (incl. two-part connectors, fixed phrases) | أدوات الربط | yes | 90 / 45 / 6 |
| 2 | satzbau |
Word order: position 0 · 1 · subordinate clause | ترتيب الجملة | yes | 60 / 35 / 6 |
| 3 | verb-praeposition |
Verbs with prepositions | أفعال مع حروف الجر | no | 120 / 40 / 4 |
| 4 | reflexive-verben |
Reflexive verbs + preposition | الأفعال الانعكاسية | no | 60 / 30 / 4 |
| 5 | trennbare-verben |
Separable & inseparable verbs (by prefix) | الأفعال المنفصلة | no | 120 / 30 / 4 |
| 6 | adverbien |
100 adverbs | ١٠٠ ظرف | no | 100 / 30 / 3 |
| 7 | relativsaetze |
Relative clauses | جمل الوصل | no | 40 / 35 / 5 |
| 8 | b2-schreiben |
B2 writing phrases | عبارات الكتابة B2 | no | 80 / 25 / 5 |
| 9 | haeufige-fehler |
Common mistakes | أخطاء شائعة | partial (top 10) | 0 / 25 / 20 |
| 10 | pruefung |
Exam guide: Goethe · telc · ÖSD · DTZ | دليل الامتحان | yes | 0 / 0 / 12 |
| 11 | b1-schreiben |
B1 writing: emails & forum posts | كتابة B1 | no | 60 / 25 / 6 |
| 12 | sprechen |
Speaking: Teil 1 · 2 · 3 phrases | المحادثة | no | 80 / 20 / 6 |
| 13 | zeiten |
Tenses: Perfekt · Präteritum · Plusquamperfekt · Futur | الأزمنة | no | 120 / 35 / 5 |
| 14 | adjektivdeklination |
Adjective endings | تصريف الصفات | no | 60 / 40 / 4 |
| 15 | konjunktiv-ii |
Konjunktiv II: wishes, polite requests, irreal conditions | الشرط والتمني | no | 40 / 30 / 4 |
| 16 | passiv |
Passive voice (Vorgangs-/Zustandspassiv, modal + passive) | المبني للمجهول | no | 40 / 30 / 4 |
| 17 | temporale-nebensaetze |
Temporal clauses: als · wenn · nachdem · bevor · während · seit · bis | جمل الزمن | no | 40 / 30 / 3 |
| 18 | infinitiv-indirekte-fragen |
Infinitive with zu · um…zu · damit · indirect questions | المصدر والسؤال غير المباشر | no | 40 / 30 / 3 |
| 19 | genitiv-n-deklination |
Genitive & n-declension | المضاف إليه | no | 40 / 25 / 3 |
| 20 | wechselpraepositionen |
Two-way prepositions (Wo? Dat · Wohin? Akk) + local/temporal prepositions | حروف الجر المزدوجة | no | 60 / 35 / 3 |
| 21 | wortschatz-b1 |
B1 vocabulary by theme (Goethe Wortliste themes) with article & plural | مفردات B1 | partial (first 30) | 400 / 60 / 0 |
| 22 | nomen-verb-verbindungen |
B2 noun–verb collocations & Nominalstil | التعابير الاسمية B2 | no | 80 / 30 / 3 |
Totals ≈ 1 850 cards, 665 questions, 116 rules (topics 1–9 ≈ 670 / 295 / 57 including the photo-derived additions below; topics 10–22 added for exam coverage, generated by the same Phase 2 pipeline; topics 10–12 are prose-heavy and go through L5 + L6 only, since they have no closed-class facts to cross-check). konnektoren = the words (meaning, type Pos 0/1/Nebensatz, nominal counterpart wegen/trotz + Gen, two-part pairs je…desto, zwar…aber, nicht nur…sondern auch, …). satzbau = word-order rules and phrases: Position 0 (und aber denn oder sondern), Position 1 with inversion (deshalb trotzdem dann außerdem sonst …), Nebensatz verb-final (weil dass wenn obwohl …), Hauptsatz phrases ("Ich bin der Meinung, dass …", "Es ist wichtig, dass …"). haeufige-fehler = 20 rules, each one mistake cluster with 2–3 wrong → right pairs (e.g. weil + verb position, für vs auf after warten, reflexive Dativ sich die Hände waschen, seit vs vor, als vs wenn, Genitiv after wegen/trotz/während). pruefung = one rule per exam module per exam (Goethe B1, telc B1, DTZ, ÖSD B1, Goethe B2, telc B2): structure, timing, points and pass marks, grading criteria for Schreiben/Sprechen, task types, time-management tips, what to bring — facts taken from the official exam-provider pages (goethe.de, telc.net, osd.at, bamf.de) fetched during authoring and cited in bodyMd* with the URL and date; nothing from memory. b1-schreiben = templates for informal email, formal email/complaint, forum opinion post; Anrede/Grußformel; Leitpunkte checklist; 60 phrase cards. sprechen = Redemittel for Teil 1 (sich vorstellen / gemeinsam planen), Teil 2 (Präsentation: Einleitung → Situation im Heimatland → Situation in Deutschland → Vor-/Nachteile → Meinung → Schluss), Teil 3 (Diskussion, Rückfragen, Feedback). wortschatz-b1 = nouns with article + plural, verbs with Perfekt form, grouped by Goethe B1 themes (Person, Familie, Wohnen, Arbeit, Gesundheit, Reisen, Umwelt, Medien, Bildung, Einkaufen, Behörden).
Scope additions from the owner's reference photos (sent 2026-11-18; they are third-party worksheets — use them only as a topic checklist, never copy sentences): konnektoren gets (a) an explicit two-part-connector group — weder … noch, sowohl … als auch, entweder … oder, nicht nur … sondern auch, zwar … aber, je … desto, einerseits … andererseits — each as a PATTERN card with 3 examples plus 4 GAP/ORDER questions per pair, and (b) a "fixed phrases with conjunctions" group — soweit ich weiß / mich erinnere / das beurteilen kann, sofern, solange, sobald, indem, ohne dass, (an)statt dass, seitdem, bis — as PATTERN cards with 3 examples each (card targets rise to 90 / 45 / 6). trennbare-verben is organised by prefix (ab-, an-, auf-, aus-, ein-, mit-, zu-, zurück-, weg-, vor-, nach-, um- + inseparable be-, ver-, er-, ent-, zer-, emp-, ge-): each prefix is a PATTERN card (meaning tendency in En/Ar, 3 examples) followed by its verbs; extra.prefix must match the card's group. b2-schreiben and b1-schreiben tasks[] gain corrections:[{wrong, right, noteEn, noteAr}] (4–8 typical learner errors planted in a second version modelWithErrorsDe of the model text; the writing trainer shows "Find the mistakes" first, then the corrected modelDe). wortschatz-b1 themes include Familie (incl. Stief-/Schwieger-/Schwager/Enkel… with article + plural). Reflexive verbs with für/mit and the Akk/Dat verb lists in the photos are already covered by reflexive-verben and verb-praeposition.
Seed JSON schema (one file per topic; key is the stable upsert id)
{
"topic": {"slug":"verb-praeposition","titleEn":"Verbs with prepositions","titleAr":"أفعال مع حروف الجر","descriptionEn":"…","descriptionAr":"…","icon":"link","order":3,"isFree":false},
"cards": [{"key":"vp-001","kind":"VERB_PREP","front":"sich interessieren","back":"für + Akkusativ","meaningEn":"to be interested in","meaningAr":"اهتمّ بـ","examples":[{"de":"Ich interessiere mich für Musik.","en":"I am interested in music.","ar":"أنا مهتم بالموسيقى."},{"de":"Interessierst du dich für Politik?","en":"Are you interested in politics?","ar":"هل تهتم بالسياسة؟"},{"de":"Mein Bruder interessiert sich nicht für Sport.","en":"My brother is not interested in sport.","ar":"أخي لا يهتم بالرياضة."}],"extra":{"ref":"verb-prep:sich interessieren","prep":"für","case":"Akk","reflexive":true,"alt":null,"noteEn":null,"noteAr":null},"tags":["häufig"]}],
"questions": [{"key":"vp-q-001","type":"GAP","prompt":"Ich interessiere mich ___ Musik.","options":["für","an","auf","über"],"answers":["für"],"refs":["verb-prep:sich interessieren"],"explanationEn":"sich interessieren takes für + accusative.","explanationAr":"…","difficulty":1}],
"rules": [{"key":"vp-r-001","slug":"akkusativ-oder-dativ","titleEn":"Accusative or dative after the preposition?","titleAr":"…","bodyMdEn":"…","bodyMdAr":"…","examples":[{"de":"Ich warte auf den Bus.","en":"I am waiting for the bus.","ar":"أنتظر الحافلة."},{"de":"Er spricht mit dem Lehrer.","en":"He is talking to the teacher.","ar":"يتحدث مع المعلم."}],"mistakes":[{"wrong":"Ich warte für dich.","right":"Ich warte auf dich.","noteEn":"warten auf + accusative","noteAr":"warten auf + Akk"}],"order":1}]
}
kind∈WORD | NOUN | VERB_PREP | SEPARABLE | CONNECTOR | PHRASE | PATTERN.extraper kind:VERB_PREP/REFLEXIVE{prep, case:"Akk"|"Dat", reflexive};SEPARABLE{prefix, separable:boolean, partizip};CONNECTOR{position:"0"|"1"|"NS", nominal?};WORD{group:"temporal"|"lokal"|"modal"|"kausal"|"konzessiv"|"gradpartikel", partizip?, praeteritum?, aux?:"haben"|"sein"};NOUN{article:"der"|"die"|"das", plural, theme}(front shows the noun without article; back shows article + plural; both come from thenoun.jsonreference table);PHRASE{section:"Einleitung"|"Meinung"|"Vorteile"|"Nachteile"|"Beispiel"|"Schluss"|"Beschwerde"|"Bitte"|"Anrede"|"Gruss"|"Planen"|"Praesentation"|"Diskussion"};PATTERN{}.type∈GAP | MCQ | ORDER | MATCH | CLOZE. Every question (and every gap) has exactly one correct answer; there are no multi-select questions anywhere (no checkboxes, no "select all that apply"; options are single-choice).GAP: exactly one___inprompt, 4options,answershas length exactly 1 and is ∈options.MCQ: 3–4options,answershas length exactly 1 and is ∈options.ORDER:options= tokens (shuffled client-side),answershas length exactly 1 = the single intended sentence; authors must build the item so no other ordering is grammatical (fix the sentence-opening token or give a Position cue inprompt); compared after normalizing (collapse spaces, strip space before,.!?).MATCH:options=[{"left":"warten","right":"auf + Akk"}, …]4–5 pairs,answers=[], eachleftpairs with exactly oneright; 1 point only if all pairs matched.CLOZE(telc "Sprachbausteine" format, Pro only):prompt= one coherent text (email/notice, 80–150 words) with exactly 10 gaps___1___…___10___;options= either{"mode":"abc","gaps":[["a","b","c"], …×10]}(Sprachbausteine Teil 1: 3 choices per gap) or{"mode":"bank","bank":[15 words]}(Teil 2: 15-word bank, 10 used, 5 distractors, each used at most once);answers= array of exactly 10 strings,answers[i]∈ its gap's choices / ∈ bank; scored 1 point per gap;refslists every tested lemma. Validator: exactly 10 gaps in prompt, 10 answers, no duplicate bank entries.- Usage examples: every card has
exampleswith 2–3 items{"de","en","ar"}; every rule hasexampleswith 2–4 items. Each example is a distinct, complete, original sentence in a different everyday context;enis its English andarits MSA translation; the app showsdeplus the active UI locale's translation. Validator errors:examples: expected 2–3/2–4, emptyde,enorar, duplicatedeinside one entity. - Validator also rejects, per question:
answers.length !== 1(for GAP/MCQ/ORDER),answers[0] ∉ options, duplicate options (case-insensitive). That a wrong GAP option is not also grammatical is checked by the blind-solver layer of the correctness pipeline, not by the schema. extra.ref(cards) andrefs(questions) are ids intocontent/reference/*.json(format<file>:<lemma>, e.g.verb-prep:sich interessieren); required for kindsVERB_PREP,SEPARABLE,CONNECTORand for every question whose topic isverb-praeposition,reflexive-verben,trennbare-verben,konnektoren; otherwise optional.extra.alt,extra.noteEn,extra.noteArcarry the "also possible / special case" info for contested entries (null otherwise).difficulty1–3. All strings trimmed, non-empty; Arabic fields MSA, no transliteration; English fields plain, no German inside except quoted words. Validator:scripts/validate-content.ts(zod schema above + uniqueness ofkey,frontper topic,promptper topic; counts ≥ targets table minus 10 %).
Quiz engine (src/lib/quiz.ts)
- Topic quiz: all published questions of topic (free users: first
freeQuestionsPerTopicbyorder), shuffled, options shuffled;CLOZEitems are excluded from topic/All-topics/Quick quizzes and run only in Mock test mode. - Mock test (
/quiz/mock, Pro): the user's chosen exam (User.targetExam) picks the format — telc B1/B2 and DTZ: 2CLOZEtexts (oneabc, onebank) with the official timing (telc B1 Sprachbausteine: 15 min for both parts; telc B2: 20 min — confirm againsttelc.netduring authoring and store per exam incontent/exams/<exam>.json{sprachbausteineMinutes, parts}); Goethe/ÖSD (no Sprachbausteine module): 40 mixed GAP/MCQ in 20 min. Countdown timer, auto-submit at 0, result shows points and the exam's pass threshold for that part when the exam defines one, otherwise percent only. - "All topics": 40 questions stratified proportional to pool size over topics with ≥ 1 published question (
pruefunghas none and is skipped), min 2/topic, remainder by largest pool. - Quick test: user picks N ∈ {60,70,80}; stratified proportional over the same question-bearing topics, min 2/topic (21 topics × 2 = 42 ≤ 60), remainder proportional to pool size; exclude questions answered correctly in the user's last 3 attempts when the remaining pool still satisfies N; free users → N forced to
freeQuickQuizSize(20: min 0/topic, pure proportional) andfreeQuickQuizPerDayenforced server-side (QuizAttemptcount today, Europe/Berlin day). - Scoring: 1 point/question (1 per gap for
CLOZE). Result screen: percent ring, per-topic bars, weakest 3 topics → "Practise weak topics" starts a 20-question quiz from those topics' pools (Pro only). - Mistake notebook (
/quiz/mistakes, Pro): every question answered wrongly in any attempt is stored in Dexiemistakes{questionId, wrongCount, lastWrongAt, clearedAt?}(synced like attempts); the page lists them newest first with the explanation, "Retry all" runs them as a quiz, and a question is cleared after 2 consecutive correct answers. Quick test sampling includes every un-cleared mistake first (up to 25 % of N), then fills the rest as specified above. - Attempt persisted to Dexie immediately, queued in
outbox, POSTed to/api/sync(idempotent by client UUID).
Study plan & exam countdown (src/lib/plan.ts)
- Onboarding (first launch, skippable; also editable in the avatar sheet): target exam ∈
goethe-b1 | telc-b1 | dtz | oesd-b1 | goethe-b2 | telc-b2, exam date (optional), daily minutes ∈ {10, 20, 30}. Stored inUser.targetExam,User.examDate,User.dailyMinutes(guests: localStorage, merged at login). - Daily goal = due cards (all) + new cards (10/20/30 minutes → 10/20/30 new, capped by remaining) + 1 quiz (topic quiz of the weakest topic, or the Quick test on days divisible by 7). Shown as a "Today" panel at the top of the Cards tab: three checkmarks, countdown "N days to
", and "Readiness" per topic. - Readiness per topic = 0.5 × (cards with
interval ≥ 7 d/ cards) + 0.5 × (best topic-quiz score in the last 14 days, 0 if none); shown as a bar; topics ordered by readiness ascending on the Today panel; recommended new-card order follows the exam's module weights incontent/exams/<exam>.json{topicOrder:[slug…]}(e.g. telc B1 putskonnektoren,verb-praeposition,zeitenfirst because Sprachbausteine test them; Goethe B2 putsnomen-verb-verbindungen,b2-schreibenfirst). - Reminders: Web Push (VAPID keys in env
VAPID_PUBLIC_KEY/VAPID_PRIVATE_KEY,web-pushpackage) — opt-in toggle "Daily reminder at HH:MM" in the avatar sheet;PushSubscription(id, userId?, anonId?, endpoint @unique, keys Json, hour Int, minute Int, tz String); anode-cronjob inside the app process runs every 5 minutes and sends "You have N cards due · N days to your exam" to subscriptions whose local time matches. iOS requires the PWA to be installed (iOS ≥ 16.4) — the toggle explains this whennavigator.standaloneis false. Unsubscribe on 404/410 from the push service.
Writing & speaking trainer (Pro; no AI grading)
/write: pick a task type (B1 informal email, B1 formal email/complaint, B1 forum post, B2 Forumsbeitrag, B2 formal letter) → task prompt with 3–4 Leitpunkte generated fromcontent/seed/b1-schreiben.json/b2-schreiben.jsontasks[](new seed array{key, type, promptEn, promptAr, leitpunkte:[{de, keywords:[…]}], minWords, maxMinutes, modelDe}), editor with: live word count vsminWords, countdownmaxMinutes, a checklist that auto-ticks Anrede present, Grußformel present, every Leitpunkt mentioned (keyword match onkeywords[]), ≥ 3 connectors fromconnector.jsonused, and a side panel of phrase cards for the task's sections. Drafts saved in Dexiedrafts; "Compare with model answer" revealsmodelDe(an original model text that went through L3–L5). No grading, no upload./speak: Teil 2 presentation trainer — random topic fromtasks[]ofsprechen.json({key, topicDe, topicEn, topicAr, notesDe:[5 bullet cues]}), 1-minute prep timer, then a 3-minute speaking timer with the structure cue cards (Einleitung → … → Schluss) advancing every 30 s; optional local recording viaMediaRecorder(kept in Dexierecordings, max 5, never uploaded) for self-review against a checklist. Teil 1/3 phrase decks are ordinary cards insprechen.- Text-to-speech: a speaker icon on every German text (
front, examples, prompts, rule examples) callsspeechSynthesis.speak(new SpeechSynthesisUtterance(text))withlang="de-DE"and the first availablede-DEvoice; hidden when no German voice exists. Quality varies by device (unverified on iOS/Android — confirm first); no recorded audio is produced or stored.
Global search
- Search box in the header (all tabs): client-side over all loaded bundles (card fronts/backs/meanings, rule titles, mistake sentences, example sentences) using a simple normalized substring match (lowercase,
ß→ss, umlaut-insensitive); results grouped by type and deep-linked. Nothing server-side.
Spaced repetition (src/lib/srs.ts, SM-2 variant, unit-tested)
Ratings again=0 hard=1 good=2 easy=3. State {ease=2.5, interval=0 (days), due, reps, lapses}.
- New card: good → 1 d, easy → 3 d, hard → 10 min (requeue in session), again → 1 min.
- Review: again → interval 0, due +10 min, ease −0.20, lapses+1; hard → interval = max(1, round(interval×1.2)), ease −0.15; good → round(interval×ease); easy → round(interval×ease×1.3), ease +0.15. Ease floor 1.3, cap 3.0. due = now + interval days (minutes for the sub-day cases).
- Session: up to newPerSession=20 new + all due cards of the deck; order: due first by due, then new by order.
- Sync: CardProgress server rows keyed (userId, cardId); last-write-wins by updatedAt; guest reviews stored under anonId locally only and uploaded at first login.
Content delivery & gating
GET /api/content/[slug]→{topic, cards, questions, rules, version, locked:boolean}; server trims to free limits unlessuser.plan==='PRO' && (proUntil==null || proUntil>now). Paid rows never reach free clients.ETag=version(maxupdatedAtof topic's rows).- Client caches bundle in Dexie
bundles[slug]; refetch when online and ETag changed; works fully offline afterwards. GET /api/content/index→ topic list with counts, free flag, user progress summary.
Admin dashboard (/admin, role==='ADMIN', server-checked in src/middleware.ts + each route handler)
Pages: Overview (stats), Topics, Cards, Questions, Rules, Users, Orders, Reports, Settings — all English.
- CRUD tables with filters (Topic, Type/Kind, Status), inline status toggle DRAFT|PUBLISHED, right-side edit drawer, soft delete (deletedAt), "Preview" renders the card/question exactly as in the app.
- Import: upload one or many seed JSON files → validator → upsert by key (dry-run diff shown first: adds/updates/unchanged). Export: topic → seed JSON.
- Users: email, plan, proUntil, last seen, attempts, "Extend/revoke Pro" (writes Order of provider MANUAL).
- Reports: user "Report a mistake" reports on card/question/rule with deep link to edit; resolve.
- Settings: the gating keys above + maintenanceBanner.
- Overview: signups/day 30 d, DAU (distinct user/anon app_open events), Pro conversions + revenue 30 d, quiz attempts/day, 10 lowest correct-rate questions, open reports.
Data model (prisma/schema.prisma)
User(id, email @unique, name?, image?, role USER|ADMIN, plan FREE|PRO, proUntil DateTime?, locale en|ar @default(en), targetExam String?, examDate DateTime?, dailyMinutes Int @default(20), signupSource String?, refCode String @unique, anonId?, createdAt, lastSeenAt)
Topic(id, slug @unique, titleEn, titleAr, descriptionEn, descriptionAr, icon, order, isFree, status, deletedAt?)
Card(id, key @unique, topicId, kind, front, back, meaningEn, meaningAr, examples Json /* [{de,en,ar}] */, extra Json, tags String[], order, status, reviewState UNCHECKED|AI_CHECKED|HUMAN_APPROVED @default(UNCHECKED), contested Boolean @default(false), deletedAt?, updatedAt)
Question(id, key @unique, topicId, type, prompt, options Json, answers Json, refs String[], explanationEn, explanationAr, difficulty Int, order, status, reviewState UNCHECKED|AI_CHECKED|HUMAN_APPROVED @default(UNCHECKED), deletedAt?, updatedAt)
Rule(id, key @unique, topicId, slug, titleEn, titleAr, bodyMdEn, bodyMdAr, mistakes Json /* [{wrong,right,noteEn,noteAr}] */, examples Json /* [{de,en,ar}] */, order, status, reviewState UNCHECKED|AI_CHECKED|HUMAN_APPROVED @default(UNCHECKED), deletedAt?, updatedAt)
CardProgress(userId, cardId, ease Float, interval Int, due DateTime, reps Int, lapses Int, updatedAt) @@id([userId,cardId])
QuizAttempt(id = client uuid, userId?, anonId?, kind TOPIC|ALL|QUICK|WEAK|MOCK|MISTAKES, topicId?, total, correct, durationS, answers Json, createdAt)
Mistake(userId?, anonId?, questionId, wrongCount Int, lastWrongAt, clearedAt?, updatedAt) @@id([userId, questionId])
PushSubscription(id, userId?, anonId?, endpoint @unique, keys Json, hour Int, minute Int, tz String, createdAt)
Order(id, userId, provider LEMONSQUEEZY|MANUAL, providerOrderId? @unique, product, amountCents, currency, status, createdAt)
Referral(id, referrerId, referredId @unique, status PENDING|REWARDED, createdAt)
AdSpend(source, month /* "YYYY-MM" */, amountCents) @@id([source,month])
Report(id, userId?, anonId?, entityType CARD|QUESTION|RULE, entityId, message, status OPEN|RESOLVED, createdAt)
Event(id, type, userId?, anonId?, topicSlug?, meta Json, createdAt) @@index([type, createdAt])
Setting(key @id, value Json)
+ Auth.js tables (Account, Session, VerificationToken)
Content correctness policy
Honest limit: generated content cannot be proven 100 % correct by the generator or by AI reviewers. The plan therefore (a) removes every item it cannot back with two independent dictionary sources, (b) mechanically cross-checks all closed-class facts against a source-backed reference table, (c) has separate agents solve and attack every quiz item blind, and (d) only serves items stamped by that pipeline; HUMAN_APPROVED by the owner or a native-level German reader is the only "certified" state, and user reports auto-unpublish bad items.
Sources (verified reachable from the Pi on 2026-11-18)
Primary: Duden online https://www.duden.de/rechtschreibung/<lemma> and DWDS https://www.dwds.de/wb/<lemma>; both rendered via read with the "Grammatik"/Bedeutungen blocks and example sentences (checked with interessieren). They are not identical: Duden lists jemanden für ein Projekt/an einem Projekt interessieren (two constructions) where DWDS lists only jmd. interessiert jmdn. für etw.; Goethe level also differs (DWDS: A2, Duden: B1), so source-stated level is never used as a gate; topic scope comes from the owner's headline list.
Reference tables (content/reference/*.json) — built first, everything else is checked against them
Files: verb-prep.json, reflexive.json, separable.json, connector.json, relativpronomen.json (the fixed table in Mockup 3), noun.json ({lemma, article, plural, theme} for wortschatz-b1), verb-forms.json ({lemma, praeteritum, partizip, aux} for zeiten), adjective-endings.json (the fixed declension tables for adjektivdeklination). Entry shape (example): {"id":"verb-prep:sich interessieren","lemma":"sich interessieren","prep":"für","case":"Akk","reflexive":true,"contested":false,"alt":null,"sources":[{"name":"DWDS","url":"https://www.dwds.de/wb/interessieren","checkedOn":"2026-11-18"},{"name":"Duden","url":"https://www.duden.de/rechtschreibung/interessieren","checkedOn":"2026-11-18"}]}. Variants per file: separable.json {prefix, separable, partizip}; connector.json {position:"0"|"1"|"NS", governs?:"Gen"|"Dat"|…}; reflexive.json adds reflexivePronounCase:"Akk"|"Dat"; noun.json {article, plural} (both sources must agree on article and plural; nouns with two accepted plurals or articles are contested and only shown, never quizzed); verb-forms.json {praeteritum, partizip, aux} (same rule; verbs with haben/sein both accepted are contested).
Entry acceptance rule: Duden AND DWDS both fetched and agree on preposition/case/separability/position → contested:false. Any disagreement, any source listing more than one government (Akk/Dat or two prepositions), or a note such as "umgangssprachlich"/"landschaftlich" on the form → contested:true, alt = the other form, sources records both readings. If one source cannot be fetched or has no entry → the entry is NOT created and the lemma is dropped from all content (no guessing).
Handling disputed cases (Dativ vs Akkusativ, two prepositions, standard vs colloquial)
- Cards (flashcards/rules) MAY contain contested entries:
card.contested=true,extra.altset, front/back show the primary form (the form both sources list; if none, Duden's first), and the back shows an info line fromnoteEn/noteAr("Also possible: …" / "يُستخدم أيضًا: …", "colloquial: …" when a source says so). The owner sees these in the admin "Review queue" with the filter "contested". - Quizzes NEVER test a contested point:
verify-content.tsfails any question whoserefscontains a contested id, and fails any GAP/MCQ whose distractor equals a contested entry'salt. This is how the single-correct-answer rule stays true. - Standard-language rules (e.g.
wegen/trotz/während+ Genitiv, colloquially + Dativ) state the standard form as the exam answer and mention the colloquial form only as labelled "umgangssprachlich", only if Duden/DWDS label it so; questions test the standard form only and no distractor is the colloquial variant. - Wechselpräpositionen and similar rule-driven choices (Wo? → Dat, Wohin? → Akk) are not "contested": they are tested with prompts that contain the cue (
Wohin/Wo) so exactly one case is correct.
Pipeline (per topic, hard gates in this order)
| Layer | Who | Pass criterion |
|---|---|---|
| L1 reference | one task agent per reference file, uses read on Duden + DWDS for every lemma |
every entry has two source records or is dropped |
| L2 authoring | one task agent per topic |
uses only lemmas present in the reference tables; follows content/STYLE.md |
| L3 mechanical | scripts/verify-content.ts |
schema; extra.ref/refs resolve; card prep/case/prefix/position equal the reference; GAP/MCQ answer equals reference value; no contested ref in quizzes; LanguageTool (language=de-DE) returns zero GRAMMAR/TYPOS/CASING matches on every German sentence (each examples[].de, each GAP prompt with the answer inserted, each ORDER answer, each mistakes[].right) except entries in content/review/lt-allow.json that a human added |
| L4 blind solver | a separate task agent that receives only prompt + options (never answers/explanation) and writes content/review/<slug>.blind.json |
for each question: picks the same single answer AND marks every other option "ungrammatical/incorrect"; any "also grammatical" or different pick → item goes to needs-review |
| L5 adversarial reviewer | a third task agent with fresh context; checklist: German grammar of every sentence, English and Arabic MSA fidelity to the German, rule statements vs Duden/DWDS (fetch the page for every rule claim), ambiguity, exam relevance; writes content/review/<slug>.adversarial.json {key, status:"pass"|"fail", note} |
all pass; fail items are fixed by the author agent and re-run through L3–L5, or deleted if a source cannot confirm them |
| L6 human | owner or native-level German reader in admin "Review queue" | see launch gate |
verify-content.ts --stamp <slug> writes content/seed/<slug>.review.json entries {key, sha256, state:"AI_CHECKED", checkedAt} only for items that passed L3, L4 and L5 (files above must exist with pass) and only if the LanguageTool call actually ran (script prints LT: OK n sentences; LT: SKIPPED refuses to stamp). The importer applies AI_CHECKED only when the stored sha256 equals the sha256 of the item's current content; any edit (seed file or admin) resets reviewState=UNCHECKED.
LanguageTool access: first try the public API once (curl -s https://api.languagetool.org/v2/check -d language=de-DE --data-urlencode 'text=…' must return JSON with matches; public limits are unverified — confirm first). If rate-limited or unreachable, run sudo docker run --rm -p 127.0.0.1:8010:8010 erikvl87/languagetool (image name unverified; confirm it exists; needs ≥ 1.5 GB MemAvailable — stop the dev server first if needed) and point LT_URL=http://127.0.0.1:8010/v2/check; Docker egress rule from the hard rules stays untouched. LanguageTool false positives are recorded in content/review/lt-allow.json as {key, ruleId, reason} only after a human reads the sentence.
Serving and runtime controls
/api/content/*and the SEO pages serve only rows withstatus='PUBLISHED'ANDreviewState IN ('AI_CHECKED','HUMAN_APPROVED'). IfSetting requireHumanApproval=true, onlyHUMAN_APPROVED. NewSettingkeys:requireHumanApproval(defaultfalse),autoUnpublishReports(default3).- Auto-unpublish: when an item has OPEN
Reports from ≥autoUnpublishReportsdistinct users/anon ids, setstatus='DRAFT',reviewState='UNCHECKED'; it appears at the top of admin "Reports". - Admin "Review queue" (Phase 4): items in
AI_CHECKEDper topic with filters Topic / Type / "contested"; each row shows the item exactly as in the app, the reference entry (with clickable Duden/DWDS source URLs), the blind-solver verdict and the adversarial note; buttons "Approve" (→HUMAN_APPROVED) and "Reject" (→status='DRAFT'+ required note). Any admin edit resetsreviewState='UNCHECKED'. - Launch gate (checked in Phase 5 step 22, owner-run): every rule, every
contestedcard and a random 10 % sample of other items per topic areHUMAN_APPROVED; if the sample of any topic contains one wrong item, the pipeline (L3–L5) is re-run for that whole topic and a fresh 10 % sample is drawn; Pro checkout stays disabled until all topics pass. Then setrequireHumanApproval=trueonly if the owner/teacher has approved everything, otherwise leavefalse.
Advertising plan
Audience: Arabic-speaking adults (Syria, Iraq, Palestine, Egypt, Morocco, Algeria, Sudan, Gulf) living in Germany/Austria/Switzerland and preparing for B1 (integration, job) or B2 (Beruf, Studium), plus Arabic speakers abroad planning to move; the English UI also serves non-Arabic learners. Promise (Arabic first): "تحضير امتحان B1+ بالعربي: بطاقات، اختبارات، قواعد، وأمثلة — حتى بدون إنترنت". Funnel: short video / SEO page / Telegram post → opens PWA with no signup (free topics) → installs → daily due cards (habit) → Quick test result shows weak topics → paywall → Pro Pass.
| Channel | Role | Concrete action | Cost |
|---|---|---|---|
| TikTok / Instagram Reels / YouTube Shorts (Arabic voice-over) | main acquisition | 5 videos/week, 20–30 s: hook "خطأ شائع", wrong→right sentence, Arabic explanation, CTA "الرابط في البايو". Scripts come from haeufige-fehler rules via scripts/social-scripts.ts; bio link https://<domain>/?utm_source=tiktok&utm_medium=bio (instagram, youtube analogous) |
owner time |
| Telegram channel + Arabic-in-Germany Facebook groups | community, retention | daily "كلمة اليوم / Wort des Tages" post from scripts/word-of-day.ts with link /k/<cardKey>?utm_source=telegram; post in groups only where admins allow; no spam |
€0 |
| SEO | compounding | public pages /r/[topic]/[rule] (English UI) and /ar/r/[topic]/[rule] (Arabic UI) for free topics, plus /k/<cardKey> card pages, sitemap + hreflang; queries such as "حروف الجر مع الأفعال في الألمانية", "Konnektoren B1 Liste" |
€0 |
| Paid test | validate unit economics | Meta ads (Arabic language, DE/AT/CH + selected countries) using the best organic video; TikTok Spark Ads on the best organic post. €10/day for 14 days (€140) | €140 |
| Referral (in-app) | viral loop | "Invite friends": each friend who finishes a first quiz gives the inviter +7 days Pro, max 8 rewards | ≤ 56 Pro days per inviter |
| YouTuber / influencer partners | trust | link ?utm_source=partner-<name>; payout 25 % of Pro revenue of users with signupSource = partner-<name>, paid manually monthly from the admin "Sources" table |
25 % rev share |
Unit economics: Pro Pass €9.99 minus Lemon Squeezy fee ≈ €9 net → target blended CAC ≤ €4.5. Decision rule for paid: after ≥ 200 clicks, scale a campaign only if cost per Pro sale ≤ €4.5; otherwise pause it and keep organic only. Targets (not guarantees): visitor→signup ≥ 20 %, free→Pro ≥ 4 %, day-7 retention ≥ 25 %, refund rate ≤ 5 %. Exam-season promo: owner creates a Lemon Squeezy discount code before big exam dates and announces it on Telegram (no in-app code).
Timeline: weeks 1–2 bank 10 videos and open the Telegram channel; launch with free tier live; weeks 3–6 post daily; week 4 start the €140 paid test; evaluate with the admin "Sources" table (Phase 6 step 28). Implementation of attribution, referral, SEO pages, share images, scripts and legal pages is Phase 6.
Design
Design system
- Style: clean card-based, friendly but exam-serious; no emoji icons (lucide). Mobile-first, bottom nav with exactly the 3 tabs; settings/profile via header avatar sheet.
- Tokens (
src/app/globals.css, Tailwind v4@theme): primary indigo--c1(#4F46E5 light / #818CF8 dark), accent amber (#F59E0B) for streak/CTA, success #16A34A, error #DC2626, warning #D97706; surfaces neutral zinc; dark mode viaprefers-color-scheme+ manual toggle. Contrast ≥ 4.5:1 for all text pairs. - Type: Inter (Latin, variable) + Noto Sans Arabic for
lang="ar"nodes; base 16 px, line-height 1.5; card front 22–24 px. - Touch: all tappable ≥ 44×44, 8 px gaps; rating buttons full-width row; options are full-width buttons.
- Motion: card flip 250 ms
ease-out, option feedback 150 ms, respectprefers-reduced-motion. - Safe areas:
env(safe-area-inset-bottom)on tab bar;viewport-fit=cover. - Mixed direction: layout direction follows the locale (
ar→dir="rtl"on<html>, everything mirrors). German learning text (fronts, German examples, German rule text) is always wrappedlang="de" dir="ltr"withunicode-bidi: isolate; Arabic text is alwayslang="ar" dir="rtl". English UI text islang="en". Tailwind logical utilities only (ms-*,me-*,ps-*,pe-*,text-start,start-*), neverml/mr/pl/pr/left/right; directional icons (chevrons, back arrow) getrtl:-scale-x-100. Digits stay Western (0-9) in both locales.
Mockup 1 — Cards (deck list, study card back side)
Mockup 2 — Quiz (hub, gap question with feedback, result)
Mockup 3 — Rules (index, rule page with table + mistakes)
Mockup 4 — Admin dashboard (desktop; Fragen table + edit drawer)
Mockup 5 — Arabic locale (RTL), card back with usage examples
Mockups 1–4 are drawn in the English locale; in ar every screen mirrors exactly like this one (tab order, progress direction, rating-button order, back chevron).
Approach (ordered; each phase leaves a running app)
Phase 1 — Scaffold, data model, one topic end-to-end, staging on the Pi
0a. GitHub access (verified on the Pi: gh installed, gh auth status → "You are not logged into any GitHub hosts", no GH_TOKEN). Run gh auth login --hostname github.com --git-protocol https --web --scopes repo,workflow in a pty bash session; it prints a one-time code + https://github.com/login/device; relay that URL and code to the owner in chat and wait for him to approve on his phone. Then gh auth setup-git; verify gh auth status exits 0 and gh api user --jq .login prints the login. The token lives in ~/.config/gh/hosts.yml; never print it (hard rule 9). workflow scope is required to push .github/workflows/*. If login cannot complete, continue with local git only and skip the gh repo create in step 2; nothing before Phase 5 depends on the remote.
0b. Install vetted skills (found via web search 2026-11-18, third-party, so read before install): anthropics/skills → skills/frontend-design; mattiasgeniar/offline-first-pwa; mervick/lemonsqueezy-agent-skills (community, not affiliated with Lemon Squeezy); prisma/skills. Procedure per repo: git clone --depth 1 https://github.com/<repo> /tmp/skills-<name>; read every SKILL.md and any script it references; reject (do not install) anything that runs network installers, edits system config, or conflicts with the hard rules in ~/.omp/agent/RULES.md; copy accepted skill directories (each must contain SKILL.md) into ~/.omp/agent/skills-src/deutsch-b1/<skill-name>/. Before copying, run grep -n -A3 customDirectories ~/.omp/agent/config.yml and ls ~/.omp/agent/skills-src: if the config lists skills-src as a directory of skill folders (unverified whether it scans one level deeper), copy directly to ~/.omp/agent/skills-src/<skill-name>/ instead of the deutsch-b1/ subfolder. New skills load only in the next session (/new); the implementer reads them via skill://<name> then. Existing ui-ux-pro-max (already installed) supplies design-token queries; webapp-testing is NOT installed (needs Playwright; the built-in browser tool covers UI checks).
1. Preconditions on the Pi (verified 2026-11-18: no node, bun, npm on PATH; / has 13 GB free; Docker present at /usr/bin/docker): install Node 22 LTS via nvm per skill://dev-environment (into ~/.nvm, ~120 MB). Repo root ~/projects/deutsch-b1 (does not exist yet; node_modules ≈ 500 MB, allowed because ≥ 5 GB is free; if df -h / later shows < 5 GB free, move the checkout to an external path the owner names).
2. Scaffold: npx create-next-app@latest deutsch-b1 --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm; npx shadcn@latest init -d; add deps @serwist/next serwist prisma @prisma/client next-auth@beta @auth/prisma-adapter dexie dexie-react-hooks zustand zod lucide-react resend next-intl react-markdown; dev deps vitest @vitejs/plugin-react tsx. git init -b main, first commit on main, then gh repo create deutsch-b1 --private --source=. --remote=origin --description "German B1+ exam-prep PWA (de/ar)" --push (skip if step 0a was not completed); all later work on feature branches with pull requests (gh pr create).
3. compose.dev.yml: service db = postgres:16-alpine, ports: ["127.0.0.1:5433:5432"], named volume deutsch_b1_db, env POSTGRES_PASSWORD from .env (gitignored; .env.example committed). DATABASE_URL=postgresql://postgres:…@127.0.0.1:5433/deutsch_b1. Verify egress rule after first docker compose up: sudo docker run --rm curlimages/curl -s https://ifconfig.me equals host curl -s https://ifconfig.me.
4. prisma/schema.prisma exactly as in Data model (the inline UNCHECKED|AI_CHECKED|HUMAN_APPROVED becomes enum ContentCheck; SRS rows are the model CardProgress, never ReviewState); npx prisma migrate dev --name init. prisma/seed.ts = importer: reads every content/seed/*.json, runs the zod validator from scripts/validate-content.ts (shared module src/lib/content-schema.ts), upserts by key/slug, sets status=PUBLISHED for the two free topics and DRAFT otherwise (owner publishes in admin), and sets reviewState=AI_CHECKED only for items whose entry in content/seed/<slug>.review.json has a sha256 equal to the sha256 of the item's current JSON (otherwise UNCHECKED); it also sets Card.contested from the referenced reference entry. Setting defaults inserted if missing (requireHumanApproval=false, autoUnpublishReports=3 plus the gating keys).
5. Author content/STYLE.md (generation rules: original sentences only, B1+/B2 register, everyday exam-relevant contexts — Arbeit, Wohnen, Gesundheit, Umwelt, Bildung; English and Arabic (MSA) translations for every meaning, explanation, rule body and example; one idea per card; every card has 2–3 usage examples, every rule 2–4, each in a different context; use only lemmas present in content/reference/*.json; every question has exactly ONE correct answer and the three wrong options must be clearly wrong, never "also possible" (no multi-select, no two valid options, ORDER items allow one grammatical ordering only); never test a contested reference; explanation ≤ 2 sentences), the reference-table schema (zod, in src/lib/content-schema.ts) and scripts/verify-content.ts with L3 checks from the correctness policy (LanguageTool call included). Then build content/reference/connector.json and the first seed content/seed/konnektoren.json (60/30/5) through the full L1–L5 pipeline so every screen has real, verified data.
6. App shell: src/app/(app)/layout.tsx with bottom TabBar (Cards /cards, Quiz /quiz, Rules /rules), header avatar sheet (login/logout, Pro status, language switch, dark-mode toggle, "Install app"). src/app/manifest.ts (name "B1+ Deutsch", display: standalone, start_url: /cards, icons 192/512 maskable generated with a simple "B1+" glyph), src/app/sw.ts + next.config.ts with withSerwist. Install banner component shows after 2nd visit (localStorage counter) and on iOS shows the Share→"Add to Home Screen" sheet.
6b. i18n: next-intl config in src/i18n/request.ts reads cookie locale (en|ar, default per Decisions table) and loads messages/<locale>.json; no locale URL prefix for app routes. src/middleware.ts (the same file that sets the anonId cookie) also sets locale on first visit from Accept-Language (ar* → ar, else en). src/app/layout.tsx sets <html lang={locale} dir={locale==='ar'?'rtl':'ltr'}> and loads fonts with next/font (Inter + Noto Sans Arabic). Helper components De (lang="de" dir="ltr", isolate) wraps every piece of German learning text; T renders a translated content field for the active locale (T field="meaning" → meaningEn or meaningAr, lang/dir set accordingly). All UI strings (tabs, buttons, paywall, errors, quiz labels such as quiz.pickOne = "Choose the correct answer" / "اختر الإجابة الصحيحة", rating labels Again/Hard/Good/Easy) live in messages/*.json; no German string may appear in messages/*.json (src/i18n/messages.test.ts fails if the key sets differ or if a value matches /\b(und|der|die|das|nicht)\b/). Locale switch in the avatar sheet writes the cookie and, when logged in, PATCH /api/me {locale}.
7. Content client: src/lib/db.ts (Dexie schema bundles{slug,version,data}, reviews{cardId,…}, attempts{id,…,synced}, outbox{id,kind,payload}), src/lib/content.ts (loadBundle(slug): Dexie first, then GET /api/content/[slug] with If-None-Match), src/app/api/content/[slug]/route.ts and /index/route.ts with gating as specified.
8. Cards tab: /cards deck list (progress from Dexie reviews), /cards/[slug] study screen (flip card, 4 rating buttons with next-interval labels, "Report a mistake" sheet → POST /api/reports), src/lib/srs.ts + src/lib/srs.test.ts (vitest: new→good=1 d, again twice then good, ease floor, easy multiplier).
8b. Card back shows back (German, in De), the meaning in the active locale (meaningEn or meaningAr), then an "Examples" list rendering every entry of examples (German line in De, the active locale's translation underneath, 8 px gap); when contested it also shows noteEn/noteAr (active locale) in the warning color; front shows only front. A card with fewer than 2 examples cannot be published (validator + admin publish check).
9. Quiz tab: /quiz hub, /quiz/[slug], /quiz/all, /quiz/quick (size picker 60/70/80, free users see "20 questions · 1×/day"), /quiz/result/[attemptId]. Question renderers GapQuestion, McqQuestion, OrderQuestion (tap tokens, undo), MatchQuestion (tap left then right, lines drawn). src/lib/quiz.ts sampling + quiz.test.ts (stratification min per topic, exclusion of recent-correct, normalization of ORDER answers). Server sampling endpoint GET /api/quiz/quick?n= (needs the full published pool → server-side; free cap enforced here).
9b. Question UI is always single-choice: GAP and MCQ render one radio-style button list (never checkboxes, never "select all"), tapping an option locks the answer immediately, the chosen wrong option turns red, the correct one green, then the explanation in the active locale (explanationEn or explanationAr) appears above a "Next" button. quiz.pickOne label sits above the options. ORDER and MATCH also have exactly one correct solution each (answers length 1 / full pair set).
10. Rules tab: /rules index with search (client-side over loaded bundles) and chips, /rules/[slug] topic rules (bodyMdEn/bodyMdAr by locale via react-markdown, tables allowed; German examples in De), /rules/mistakes top mistakes list. Free topics' rule pages are also server-rendered at public /r/[topic]/[rule] with metadata for SEO.
11. Staging exposure: user unit ~/.config/systemd/user/deutsch-b1-dev.service (ExecStart=%h/.nvm/…/node … next dev -p 3850 -H 127.0.0.1, WorkingDirectory=%h/projects/deutsch-b1, Restart=on-failure, EnvironmentFile=%h/projects/deutsch-b1/.env); systemctl --user enable --now deutsch-b1-dev. Caddy: stage a copy of <caddy-config> in /tmp, append a block modeled on the existing :3847 block (read it first for exact syntax) for https://<pi-host>:3850 → reverse_proxy 127.0.0.1:3850, sudo -u caddy caddy validate --config /tmp/Caddyfile, sudo cp <caddy-config> <caddy-config>$(date +%F), sudo install -m 644 -o root -g root /tmp/Caddyfile <caddy-config>. Caddy restart requires the owner's explicit approval in the implementing conversation (hard rule 1); ask once, then sudo systemctl restart caddy, then verify curl -s -o /dev/null -w '%{http_code}' http://<meshnet-ip>/ = 200/308 and curl --cacert <caddy-config> -s -o /dev/null -w '%{http_code}' https://<pi-host>:3850/cards = 200.
Phase 2 — Content for all topics (parallel, one task agent per topic)
- Content generation and verification run per the correctness policy, in this order. (a) L1: one
taskagent per file incontent/reference/(verb-prep,reflexive,separable,connector,relativpronomen) fills it by reading Duden + DWDS for every lemma in the owner's headline list (the headlines are in the Topics table; lemma lists the agent proposes are reviewed by the owner in the PR before authoring starts); entries without two agreeing sources are dropped or markedcontested. (b) L2: onetaskagent per topic writescontent/seed/<slug>.jsononly (cards with 2–3examples{de,en,ar}, rules 2–4, every meaning/explanation/body/note in bothEnandAr, questions with exactly one answer andrefs), no agent touches app code. (c) L3:npx tsx scripts/verify-content.ts→ no errors. (d) L4: a different agent per topic producescontent/review/<slug>.blind.json. (e) L5: a third agent per topic producescontent/review/<slug>.adversarial.json; failed items are fixed or deleted and L3–L5 re-run until all pass. (f)npx tsx scripts/verify-content.ts --stamp <slug>per topic, thennpx prisma db seed. Counts after deletions must still be ≥ targets − 10 %; if fewer, the owner is told which topic is short instead of lowering the bar. - Owner review path: admin (Phase 4) is not yet there, so for this phase expose
/cards+/quiz+/ruleswithDRAFTtopics visible whenNEXT_PUBLIC_SHOW_DRAFTS=1on staging only. 13b. Exam-coverage topics (10–22 in the Topics table) run through the same step 12 pipeline after topics 1–9, plus:content/exams/<exam>.jsonfor the six exams ({id, nameEn, nameAr, provider, modules:[{name, minutes, points, passPoints?}], sprachbausteineMinutes?, topicOrder:[slug…], sourceUrl, checkedOn}) authored by onetaskagent that reads the official provider pages (goethe.de,telc.net,osd.at,bamf.de); any value not found on the provider page is leftnulland the UI hides it (never guessed).CLOZEitems (2 per exam format, 12 total, incontent/seed/sprachbausteine.json, topic slugsprachbausteine, hidden from the topic list, Pro) go through L3–L5 with the blind solver solving all 10 gaps.tasks[]arrays forb1-schreiben,b2-schreiben,sprechen(8 tasks each, withmodelDefor writing) are reviewed in L5 against the exam's Leitpunkte format.
Phase 3 — Auth, payments, sync
- Auth.js:
src/auth.tswithResendemail provider (EMAIL_FROM=login@<domain>; until the domain exists setAUTH_DEBUG_LINKS=1and log the magic link to the server console) + Google provider; Prisma adapter;roleandplan,proUntilin session callback. GuestanonIdcookie (uuid, 1 year) set insrc/middleware.ts; on first login,POST /api/sync/mergemoves Dexie reviews/attempts under the user. - Sync:
POST /api/syncbody{reviews:[…], attempts:[…]}idempotent (attemptid= client uuid, review LWW byupdatedAt),GET /api/sync?since=for pull;src/lib/sync.tsflushesoutboxononlineevent and app start. - Lemon Squeezy: products
pass-90,lifetimecreated by owner in LS dashboard (store + two products; variant ids into envLS_VARIANT_PASS90,LS_VARIANT_LIFETIME,LS_WEBHOOK_SECRET,LS_STORE). Checkout:/propage buildshttps://<store>.lemonsqueezy.com/checkout/buy/<variant>?checkout[custom][user_id]=<id>&checkout[email]=<email>(login required before purchase). Webhooksrc/app/api/webhooks/lemonsqueezy/route.ts: verifyX-Signature= HMAC-SHA256(raw body,LS_WEBHOOK_SECRET) constant-time compare; onorder_createdwithstatus==="paid"upsertOrderbyproviderOrderIdand setplan=PRO,proUntil = product==='pass-90' ? max(now, proUntil)+90 d : null; onorder_refundedsetplan=FREE,proUntil=null. Return 200 on duplicates. Gating readsplan/proUntilon every request (no client trust). - Free-limit UX: locked cards/questions show an "Unlock with Pro" card at the end of the free slice linking to
/pro; Quick test over the daily limit shows the same. 17b. Exam features (Phase 3, after 17): onboarding sheet (target exam, exam date, daily minutes) →PATCH /api/me; Today panel + readiness +src/lib/plan.tswithplan.test.ts(daily goal sizes, readiness formula, topicOrder); Mock test/quiz/mockwith timer and auto-submit (QuizAttempt.kind='MOCK'); Mistake notebook/quiz/mistakes+Mistakesync in/api/sync; Writing trainer/writeand speaking trainer/speakas specified; TTS button componentSpeak; global search; Web Push:POST/DELETE /api/push(subscription + reminder time),src/server/reminders.ts(node-cronevery 5 min,web-push), service workerpush/notificationclickhandlers insrc/app/sw.tsopening/cards.
Phase 4 — Admin dashboard
src/app/admin/*with shadcnDataTable; routes guarded byrole==='ADMIN'in middleware and in everysrc/app/api/admin/*handler (403 otherwise). Owner's email is promoted viascripts/make-admin.ts <email>.- Pages per spec (Overview, Topics, Cards, Questions, Rules, Users, Orders, Reports, Settings; English UI,
messages/en.jsonnamespaceadmin); edit drawer reuses the app'sCardView/QuestionView/RuleViewcomponents for "Preview" (with a locale toggle en/ar); import =POST /api/admin/import(multipart JSON files → validator → dry-run diff → confirm → upsert); export =GET /api/admin/export/[slug]returning the seed JSON shape so files round-trip intocontent/seed/. 19b. Edit drawers for Cards and Rules include an "Examples" editor: repeatable rows (German input + English input + Arabic input withdir="rtl"), add/remove, min 2 / max 3 (cards) or 4 (rules) enforced client- and server-side bycontent-schema.ts; every translated field (meaning,explanation,bodyMd,note,title,description) is edited as an En/Ar pair and both are required. The Questions drawer shows a single-select "Correct answer" radio over the options (no multi-select control exists). 19c. Correctness UI per the policy: "Review queue" page (AI_CHECKED items, filters Topic / Type / contested, reference entry + source links + blind/adversarial verdicts, buttons Approve →HUMAN_APPROVED/ Reject →DRAFTwith required note); every save in an edit drawer setsreviewState='UNCHECKED'; Reports shows auto-unpublished items first; Settings exposesrequireHumanApprovalandautoUnpublishReports./api/content/*filters byreviewStateas specified. - Events:
src/lib/events.tstrack(type, meta)→POST /api/events(batched, beacon on hide); typesapp_open, card_rated, quiz_started, quiz_finished, pro_viewed, checkout_started, install_prompt_shown, installed. Overview queries aggregate overEvent,QuizAttempt,Order.
Phase 5 — Production
Dockerfile(multi-stage,output: 'standalone'),compose.prod.yml(app,postgres:16,caddywith real domain + automatic TLS, volumes,restart: unless-stopped, healthchecks),.github/workflows/deploy.yml: on push tomainbuild the image and push to GHCR (ghcr.io/<login>/deutsch-b1), then deploy via SSH to the VPS (docker compose pull && up -d && exec app npx prisma migrate deploy) using repository secretsVPS_HOST,VPS_USER,VPS_SSH_KEY. Owner provisions VPS + domain + DNS and adds those secrets withgh secret set(never in chat/git);.envon the VPS holds app secrets. Only the SSH-deploy idea is borrowed from~/projects/albishara/backend/.gitlab-ci.yml; that file is GitLab syntax and is not copied.- Launch checklist in
README.md: LS webhook URL set tohttps://<domain>/api/webhooks/lemonsqueezy, Google OAuth redirect URI, Resend domain verified,make-admin, seed import, smoke tests from Verification, and the content launch gate from the correctness policy (all rules + contested cards + 10 % sample per topicHUMAN_APPROVED; Pro checkout stays disabled until that passes).
Phase 6 — Advertising & growth (after Phase 5)
- Attribution:
src/lib/attribution.tsparsesutm_source,utm_medium,utm_campaignandreffrom the landing URL once; first touch wins (never overwritten) inlocalStorage.attribution.track('app_open')meta includes it.POST /api/sync/merge(first login) sends it; server setsUser.signupSource = utm_source ?? 'direct'. - Public SEO pages:
/r/[topic]/[rule],/ar/r/[topic]/[rule],/k/[cardKey],/ar/k/[cardKey]for rules and cards of free topics only, statically generated (generateStaticParams,revalidate = 3600), each withgenerateMetadata, canonical URL,hreflangen/ar alternates and JSON-LDLearningResource; footer CTA "Practise for free" →/cards/<slug>?utm_source=seo.src/app/sitemap.ts+src/app/robots.ts. Paid,DRAFTorUNCHECKEDcontent is never emitted (paid-topic URLs return 404). The/ar/…routes render with thearlocale regardless of the cookie. - Referral:
User.refCode= 8 random lowercase base32 chars generated at user creation; share linkhttps://<domain>/?ref=<refCode>.POST /api/sync/mergewith a storedrefcreatesReferral{PENDING}if the code exists, differs from the user and the user has none. When the referred user's firstQuizAttemptis synced: setReferral.status=REWARDEDand extend the inviter — skip entirely if inviter isPROwithproUntil == null(lifetime) or already has 8REWARDEDreferrals; otherwiseplan='PRO',proUntil = max(now, proUntil) + 7 days, insertOrder{provider:MANUAL, product:'referral-7d', amountCents:0, status:'paid'}. Avatar sheet "Invite friends" uses Web Share API (fallback: copy link) and shows "n/8". - Share images:
src/app/api/og/result/[attemptId]/route.tsxandsrc/app/api/og/card/[key]/route.tsxusingnext/ogImageResponse(1080×1350, brand colors). "Share" on the result screen and card back shares the matching page URL with?utm_source=share&ref=<refCode>through Web Share API. Whether Satori shapes Arabic correctly is unverified — confirm first by renderingاهتمّ بـwith bundled Noto Sans Arabic TTF; if shaping is broken, the images contain German text only. - Social scripts (pure templating over seed JSON, no LLM calls, no integration with the existing gifbot):
scripts/social-scripts.ts <topicSlug> <n>prints n 30-second video scripts (hook, wrong→right sentence frommistakes, Arabic explanation fromnoteAr, CTA with the bio link) using onlyAI_CHECKED/HUMAN_APPROVEDitems;scripts/word-of-day.ts [YYYY-MM-DD]picks a non-contested free-topic card deterministically by date (dayNumber % cards.length) and prints the Telegram text (front,back,backAr, first example pair, link/k/<key>?utm_source=telegram). The owner posts manually. - Admin "Sources" page: table per
signupSourcefor the last 30 days — Source | Visitors (distinctanonId/userIdofapp_openwith thatmeta.attribution.source) | Signups | Pro (users with a paid non-MANUALOrder) | Revenue | Ad spend (fromAdSpend) | Cost per Pro (= Ad spend / Pro, blank when Pro = 0). A form on the page upsertsAdSpend(source, month, amountCents). - Legal pages
/imprint,/privacy,/termsper locale, rendered withreact-markdownfromcontent/legal/{imprint,privacy,terms}.{en,ar}.md, linked in the footer and avatar sheet (the German-law Impressum content lives on/imprint). The legal text must come from the owner (imprint/address data cannot be generated); until all six files exist/proshows "Coming soon" instead of the checkout button, and ad campaigns must not start.
Critical files & anchors
src/lib/content-schema.ts+scripts/verify-content.ts+content/reference/*.json— schema/seed shape is normative; reference tables are the single source of truth for government/position facts; verify-content enforces them and is the only writer of*.review.jsonstamps.src/app/api/content/[slug]/route.ts— the only place paid rows are trimmed; everything else trusts it.src/lib/srs.ts/src/lib/quiz.ts— pure functions with the exact numbers above; unit-tested.src/app/api/webhooks/lemonsqueezy/route.ts— HMAC verify on raw body (await req.text()), idempotent byproviderOrderId.<caddy-config>— append the:3850block modeled on:3847; validate, backup, install, restart only with approval.
Verification
- Phase 1:
cd ~/projects/deutsch-b1 && npx vitest run→ srs/quiz tests pass.npx tsx scripts/validate-content.ts→OK konnektoren: 60 cards, 30 questions, 5 rules.curl -s http://127.0.0.1:3850/api/content/konnektoren | jq '.cards|length'→60,.locked→false.curl -s http://127.0.0.1:3850/api/content/adverbien | jq '.cards|length, .locked'(anonymous, after Phase 2) →15,true. Phone: openhttps://<pi-host>:3850/cardsvia Collie/Meshnet, flip a card, rate "Good" → deck list shows 1 fewer due; airplane mode →/cards/konnektorenstill loads from Dexie.curl -s -o /dev/null -w '%{http_code}' http://<meshnet-ip>/→ 200/308 after the Caddy restart. Docker egress check equals host VPN IP. - Phase 2: validator totals ≥ 1 600 cards / 580 questions / 100 rules across all 22 topics (≥ 560 / 250 / 50 for topics 1–9 alone, which may ship first);
npx prisma db seedprints per-topic upsert counts; spot-check 10 random cards per topic in the app for grammar/translation correctness (owner review);content/exams/telc-b1.jsonhas non-nullsprachbausteineMinuteswithsourceUrlontelc.net. - Exam features: a fixture
CLOZEwith 9 gaps → validatorCLOZE: expected 10 gaps;/quiz/mockas a telc-b1 Pro user shows 2 texts and a 15:00 countdown that auto-submits at 0:00 and recordskind='MOCK'; answering one question wrongly twice then correctly twice → it appears in/quiz/mistakesand then disappears (clearedAtset); Today panel forexamDate = today + 30shows "30 days";npx vitest run src/lib/plan.test.tspasses;/writewith a B1 formal email task: typing a text without "Mit freundlichen Grüßen" leaves the Grußformel checkbox unticked, adding it ticks it;POST /api/pushwith a fake subscription +hour/minute= now + 5 min → the cron sends (log linepush sent 1), a 410 from the endpoint removes the row. - Phase 3: magic-link login via logged URL creates
User;curl -X POST …/api/webhooks/lemonsqueezy -H 'X-Signature: <hmac>' -d @fixture-order_created.json→ 200 andUser.plan='PRO',proUntil≈ +90 d; replaying the same body → 200 without a secondOrder; wrong signature → 401. Free userGET /api/quiz/quick?n=80→ 200 with 20 questions, second call same day → 429{"error":"daily_limit"}; Pro user → 80 questions, ≥ 2 per question-bearing topic and none frompruefung(jq '[.questions[].topicSlug]|group_by(.)|map(length)|min'≥ 2,jq '[.questions[].topicSlug]|unique|length'= 21). - Phase 4: non-admin
GET /api/admin/questions→ 403; admin import of an editedkonnektoren.jsonshows diffupdated: 1, confirm → the changed prompt appears in/quiz/konnektoren; a report from the phone appears under Reports with working deep link. - Phase 5:
https://<domain>/cards200 with HSTS;docker compose psall healthy; LS test-mode purchase flips plan to PRO on the live site. - English/Arabic UI:
curl -s -H 'Cookie: locale=ar' http://127.0.0.1:3850/cards | grep -o '<html[^>]*>'→ containslang="ar"anddir="rtl"; withlocale=en→lang="en"and nodir="rtl";curl -s -H 'Cookie: locale=en' http://127.0.0.1:3850/cards | grep -c -E '>(Karten|Regeln|Lernen)<'→ 0 (no German UI strings).npx vitest run src/i18n/messages.test.tspasses, and fails after deleting one key frommessages/ar.json. On the phone: switch to Arabic in the avatar sheet → tab bar mirrored (Cards rightmost), rating buttons mirrored, German example sentences remain left-to-right and readable inside the RTL card. - Examples: a fixture card with 1 example →
npx tsx scripts/validate-content.tsprintsexamples: expected 2–3; the card back ofsich interessierenshows 3 examples, each German + English withlocale=enand German + Arabic withlocale=ar. - Single answer: a fixture MCQ with
answers: ["a","b"]→ validator erroranswers: expected exactly 1; in the app, tapping a second option after the first is a no-op (answer locked) and the UI contains no checkbox inputs (document.querySelectorAll('input[type=checkbox]').length === 0on a quiz screen). - Correctness (planted-error fixtures in
content/fixtures/, all must be rejected): (1) cardwartenwithprep:"für"vs referenceauf→verify-content.tsprintsreference mismatch: verb-prep:warten prep für ≠ aufand exits non-zero; (2) question withrefs:["verb-prep:<contested lemma>"]→contested reference used in quiz; (3) GAP whose distractor equals a contested entry'salt→distractor equals contested alt; (4) GAP with two grammatical options → blind solver marks the second option "also grammatical" and the item lands inneeds-review,--stamprefuses it; (5) a sentence edited after stamping → importer setsreviewState=UNCHECKED(sha mismatch) and/api/content/<slug>no longer returns it.verify-content.ts --stampprintsLT: OK <n> sentencesbefore stamping. - Runtime controls: three distinct users POST
/api/reportsfor one question → itsstatusbecomesDRAFTand/api/content/<slug>stops returning it; admin "Approve" on a Review queue row setsreviewState=HUMAN_APPROVEDand, withrequireHumanApproval=true, only such rows are served (count viacurl -s …/api/content/<slug> | jq '.questions|length'). - Phase 6: in the browser open
/?utm_source=tiktok&utm_medium=bio, log in →SELECT "signupSource" FROM "User" WHERE email='<test>'returnstiktok. Referral: user B opens/?ref=<A.refCode>, logs in and finishes a quiz → A'sproUntil≈ now + 7 d,Referral.status='REWARDED'; finishing a second quiz as B does not extend again.curl -s http://127.0.0.1:3850/ar/r/konnektoren/<rule-slug> | grep -c hreflang≥ 2;/r/adverbien/<any>→ 404;curl -s http://127.0.0.1:3850/sitemap.xml | grep -c adverbien→ 0.npx tsx scripts/word-of-day.ts 2026-12-01prints the same card twice in a row. Admin "Sources" shows thetiktokrow with 1 signup after the test above.
Assumptions & contingencies
- Business model: freemium + one-time Pro passes (€9.99/90 d, €19.99 lifetime). If the owner prefers a subscription, replace the two LS products with one
monthlyvariant and handlesubscription_payment_success/subscription_expiredwebhooks settingproUntil = renews_at. - Payments: Lemon Squeezy as Merchant of Record. If the owner's payout country is unsupported by LS, use Paddle (same custom-data + webhook pattern;
paddle.jsoverlay checkout) — theOrdermodel and gating stay unchanged. - UI language: English + Arabic UI, no German UI (owner request). If the owner later wants Arabic as the only UI language, delete
messages/en.jsonand the switch and set the default locale toar; routes and content are unchanged. - Hosting: Hetzner VPS + Docker Compose. If Vercel is chosen instead: drop
Dockerfile/compose.prod.yml, use Neon Postgres, setoutputdefault; Serwist and webhooks work unchanged. Hosting production on the Pi is rejected (microSD, home Wi-Fi, no public ingress without a tunnel, NordVPN egress constraints). - Auth: magic link + Google with guest mode. If Google-only is chosen, drop Resend; guest mode stays.
- Repo remote: private GitHub repo
deutsch-b1created viaghafter the owner approves the device login (Phase 1 step 0a). If the login cannot be completed, work in local git and push later. - App name "B1+ Deutsch" and domain are placeholders; renaming touches
manifest.ts,messages/*.json, README only. - Advertising budget: €140 paid test (€10/day × 14 days) and a CAC ceiling of €4.5 are defaults; the owner may change both, the "pause above ceiling" rule stays. Partner rev share 25 % is a default.
- Legal pages (imprint, privacy, terms) need owner-supplied text; paid checkout and ads stay off until they exist (Phase 6 step 29).
- Correctness:
requireHumanApprovaldefaults tofalsebecause a single owner cannot hand-review ~1 000 items; the launch gate (all rules, all contested cards, 10 % sample per topic human-approved) replaces full review. If a native German teacher is available, setrequireHumanApproval=trueand have them approve everything in the Review queue. If Duden/DWDS ever become unfetchable during Phase 2, stop and tell the owner; do not substitute memory-based facts. - Exam coverage: topics 10–22, Mock test, mistake notebook, study plan/countdown, push reminders, writing/speaking trainer, TTS and global search were added because an exam candidate needs module coverage (Schreiben/Sprechen), telc Sprachbausteine practice, a timeline and error review, not only grammar lists. If the owner wants a faster first launch, ship topics 1–9 + study plan + mistake notebook first and keep the rest in Phase 3b; nothing else depends on them. Listening and reading modules are deliberately not built (they need licensed audio/text corpora); the exam guide covers them with strategy tips only. No teacher/class functionality exists (removed at the owner's request).