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}]
}

Quiz engine (src/lib/quiz.ts)

Study plan & exam countdown (src/lib/plan.ts)

Writing & speaking trainer (Pro; no AI grading)

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

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)

  1. Cards (flashcards/rules) MAY contain contested entries: card.contested=true, extra.alt set, front/back show the primary form (the form both sources list; if none, Duden's first), and the back shows an info line from noteEn/noteAr ("Also possible: …" / "يُستخدم أيضًا: …", "colloquial: …" when a source says so). The owner sees these in the admin "Review queue" with the filter "contested".
  2. Quizzes NEVER test a contested point: verify-content.ts fails any question whose refs contains a contested id, and fails any GAP/MCQ whose distractor equals a contested entry's alt. This is how the single-correct-answer rule stays true.
  3. 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.
  4. 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

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

Mockup 1 — Cards (deck list, study card back side)

9:41 · B1+ German Cards M Search topics… Due today: 37 cards Streak: 6 days Study Connectors 60 cards · 12 due · 48 % learned free Word order: pos. 0 · 1 · clause 60 cards · 8 due · 30 % learned free Verbs with prepositions 120 cards · 15 free · Pro Reflexive verbs + prep. 60 cards · 15 free · Pro 100 adverbs 100 cards · 15 free · Pro … 4 more topics Cards Quiz Rules 9:41 ‹ Verbs + preposition 12/40 Back sich interessieren für + Akkusativ اهتمّ بـ Ich interessiere mich für Musik. أنا مهتم بالموسيقى. Tap to flip How well did you know it? Again 1 min Hard 10 min Good 1 day Easy 3 days Report a mistake Cards Quiz Rules

Mockup 2 — Quiz (hub, gap question with feedback, result)

Quiz Quick test 60–80 random questions from all topics Pro · 1 free test of 20 questions today 60 70 80 Start All topics · mixed 40 questions · best 78 % › BY TOPIC Connectors Gap fill 30 · best 85 % › Word order Order 35 · best 70 % › Verbs with prepositions Gap fill 40 · 10 free Relative clauses Pick pronoun 35 · 10 free … 5 more topics Cards Quiz Rules ✕ Question 7/20 04:12 Connectors · gap fill Er hat die Prüfung bestanden, ___ er wenig gelernt hat. obwohl ✓ weil deshalb trotzdem ✕ Correct: obwohl Subordinate clause → verb at the end. trotzdem = position 1 in a main clause. Next Report a mistake Result 72 % 58 / 80 correct · 38 min BY TOPIC Connectors 90 % Word order 80 % Adverbs 70 % Relative clauses 60 % Verbs + prep. 45 % Practise weak topics Review mistakes (22) Retry Share

Mockup 3 — Rules (index, rule page with table + mistakes)

Rules Search rules or mistakes… All Common mistakes Tables Word order: pos. 0 · 1 · clause 6 rules · 9 mistakes Relative clauses 5 rules · 8 mistakes · table Connectors 5 rules · 7 mistakes Verbs with prepositions 4 rules · 6 mistakes B2 writing: letter structure 5 rules · 4 mistakes Common mistakes · top 20 10 free · 20 with Pro … 4 more topics Cards Quiz Rules ‹ Relative clauses جمل الوصل RELATIVE PRONOUNS m f n Pl Nom der die das die Akk den die das die Dat dem der dem denen Gen dessen deren dessen deren REMEMBER Like the definite article – except dative plural (denen) and genitive (dessen / deren). COMMON MISTAKE ✕ Der Mann, der ich gesehen habe. ✓ Der Mann, den ich gesehen habe. الفعل sehen يأخذ مفعولاً به ← Akkusativ Ask: Wen habe ich gesehen? → den WITH A PREPOSITION Die Frau, mit der ich arbeite, … Das Haus, in dem wir wohnen, … Practise now · 35 questions Cards Quiz Rules

Mockup 4 — Admin dashboard (desktop; Fragen table + edit drawer)

B1+ Admin Overview Topics Cards Questions Rules Users Orders Reports 3 Settings omp-pi · Admin Questions Import JSON Export Users 1 248 +32 Pro 143 11,5 % Revenue 30 d € 1 390 Quizzes today 312 Topic: all ▾ Type: gap fill ▾ Status: all ▾ Search… KEY TOPIC QUESTION CORRECT STATUS kn-q-007 Connect. Er hat die Prüfung bestanden, ___ er … 81 % Published kn-q-008 Connect. ___ es regnet, gehen wir spazieren. 31 % Published vp-q-012 Verb+prep Sie wartet ___ den Bus. 74 % Draft rs-q-003 Relative Das Buch, ___ ich lese, ist spannend. 66 % Published sb-q-021 Word order Order: deshalb / er / bleibt / zu Hause 58 % Published tv-q-004 Separable Ich ___ morgen um 6 Uhr ___. (aufstehen) — Draft 280 questions · page 1 / 12 ‹ 1 2 3 … 12 › Edit question ✕ Topic Connectors ▾ Type Gap fill (GAP) ▾ Question · exactly one ___ Er hat die Prüfung bestanden, ___ er wenig gelernt hat. Options · mark the correct one ● obwohl ○ weil ○ deshalb ○ trotzdem Explanation (EN) Subordinate clause → verb at the end. Explanation (AR) الجملة التابعة: الفعل في النهاية Difficulty 1 ● 2 3 Status Live Save Preview Delete (soft) 2 reports →

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).

› أفعال مع حروف الجر 12/40 DE | AR الوجه الخلفي sich interessieren für + Akkusativ اهتمّ بـ أمثلة Ich interessiere mich für Musik. أنا مهتم بالموسيقى. Interessierst du dich für Politik? هل تهتم بالسياسة؟ Mein Bruder interessiert sich nicht für Sport. أخي لا يهتم بالرياضة. اضغط للقلب مرة أخرى 1 min صعب 10 min جيد 1 d سهل 3 d الإبلاغ عن خطأ البطاقات الاختبارات القواعد

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)

  1. Content generation and verification run per the correctness policy, in this order. (a) L1: one task agent per file in content/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 marked contested. (b) L2: one task agent per topic writes content/seed/<slug>.json only (cards with 2–3 examples {de,en,ar}, rules 2–4, every meaning/explanation/body/note in both En and Ar, questions with exactly one answer and refs), no agent touches app code. (c) L3: npx tsx scripts/verify-content.ts → no errors. (d) L4: a different agent per topic produces content/review/<slug>.blind.json. (e) L5: a third agent per topic produces content/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, then npx 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.
  2. Owner review path: admin (Phase 4) is not yet there, so for this phase expose /cards + /quiz + /rules with DRAFT topics visible when NEXT_PUBLIC_SHOW_DRAFTS=1 on 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>.json for the six exams ({id, nameEn, nameAr, provider, modules:[{name, minutes, points, passPoints?}], sprachbausteineMinutes?, topicOrder:[slug…], sourceUrl, checkedOn}) authored by one task agent that reads the official provider pages (goethe.de, telc.net, osd.at, bamf.de); any value not found on the provider page is left null and the UI hides it (never guessed). CLOZE items (2 per exam format, 12 total, in content/seed/sprachbausteine.json, topic slug sprachbausteine, hidden from the topic list, Pro) go through L3–L5 with the blind solver solving all 10 gaps. tasks[] arrays for b1-schreiben, b2-schreiben, sprechen (8 tasks each, with modelDe for writing) are reviewed in L5 against the exam's Leitpunkte format.

Phase 3 — Auth, payments, sync

  1. Auth.js: src/auth.ts with Resend email provider (EMAIL_FROM=login@<domain>; until the domain exists set AUTH_DEBUG_LINKS=1 and log the magic link to the server console) + Google provider; Prisma adapter; role and plan, proUntil in session callback. Guest anonId cookie (uuid, 1 year) set in src/middleware.ts; on first login, POST /api/sync/merge moves Dexie reviews/attempts under the user.
  2. Sync: POST /api/sync body {reviews:[…], attempts:[…]} idempotent (attempt id = client uuid, review LWW by updatedAt), GET /api/sync?since= for pull; src/lib/sync.ts flushes outbox on online event and app start.
  3. Lemon Squeezy: products pass-90, lifetime created by owner in LS dashboard (store + two products; variant ids into env LS_VARIANT_PASS90, LS_VARIANT_LIFETIME, LS_WEBHOOK_SECRET, LS_STORE). Checkout: /pro page builds https://<store>.lemonsqueezy.com/checkout/buy/<variant>?checkout[custom][user_id]=<id>&checkout[email]=<email> (login required before purchase). Webhook src/app/api/webhooks/lemonsqueezy/route.ts: verify X-Signature = HMAC-SHA256(raw body, LS_WEBHOOK_SECRET) constant-time compare; on order_created with status==="paid" upsert Order by providerOrderId and set plan=PRO, proUntil = product==='pass-90' ? max(now, proUntil)+90 d : null; on order_refunded set plan=FREE, proUntil=null. Return 200 on duplicates. Gating reads plan/proUntil on every request (no client trust).
  4. 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.ts with plan.test.ts (daily goal sizes, readiness formula, topicOrder); Mock test /quiz/mock with timer and auto-submit (QuizAttempt.kind='MOCK'); Mistake notebook /quiz/mistakes + Mistake sync in /api/sync; Writing trainer /write and speaking trainer /speak as specified; TTS button component Speak; global search; Web Push: POST/DELETE /api/push (subscription + reminder time), src/server/reminders.ts (node-cron every 5 min, web-push), service worker push/notificationclick handlers in src/app/sw.ts opening /cards.

Phase 4 — Admin dashboard

  1. src/app/admin/* with shadcn DataTable; routes guarded by role==='ADMIN' in middleware and in every src/app/api/admin/* handler (403 otherwise). Owner's email is promoted via scripts/make-admin.ts <email>.
  2. Pages per spec (Overview, Topics, Cards, Questions, Rules, Users, Orders, Reports, Settings; English UI, messages/en.json namespace admin); edit drawer reuses the app's CardView/QuestionView/RuleView components 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 into content/seed/. 19b. Edit drawers for Cards and Rules include an "Examples" editor: repeatable rows (German input + English input + Arabic input with dir="rtl"), add/remove, min 2 / max 3 (cards) or 4 (rules) enforced client- and server-side by content-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 → DRAFT with required note); every save in an edit drawer sets reviewState='UNCHECKED'; Reports shows auto-unpublished items first; Settings exposes requireHumanApproval and autoUnpublishReports. /api/content/* filters by reviewState as specified.
  3. Events: src/lib/events.ts track(type, meta) → POST /api/events (batched, beacon on hide); types app_open, card_rated, quiz_started, quiz_finished, pro_viewed, checkout_started, install_prompt_shown, installed. Overview queries aggregate over Event, QuizAttempt, Order.

Phase 5 — Production

  1. Dockerfile (multi-stage, output: 'standalone'), compose.prod.yml (app, postgres:16, caddy with real domain + automatic TLS, volumes, restart: unless-stopped, healthchecks), .github/workflows/deploy.yml: on push to main build 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 secrets VPS_HOST, VPS_USER, VPS_SSH_KEY. Owner provisions VPS + domain + DNS and adds those secrets with gh secret set (never in chat/git); .env on 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.
  2. Launch checklist in README.md: LS webhook URL set to https://<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 topic HUMAN_APPROVED; Pro checkout stays disabled until that passes).

Phase 6 — Advertising & growth (after Phase 5)

  1. Attribution: src/lib/attribution.ts parses utm_source, utm_medium, utm_campaign and ref from the landing URL once; first touch wins (never overwritten) in localStorage.attribution. track('app_open') meta includes it. POST /api/sync/merge (first login) sends it; server sets User.signupSource = utm_source ?? 'direct'.
  2. 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 with generateMetadata, canonical URL, hreflang en/ar alternates and JSON-LD LearningResource; footer CTA "Practise for free" → /cards/<slug>?utm_source=seo. src/app/sitemap.ts + src/app/robots.ts. Paid, DRAFT or UNCHECKED content is never emitted (paid-topic URLs return 404). The /ar/… routes render with the ar locale regardless of the cookie.
  3. Referral: User.refCode = 8 random lowercase base32 chars generated at user creation; share link https://<domain>/?ref=<refCode>. POST /api/sync/merge with a stored ref creates Referral{PENDING} if the code exists, differs from the user and the user has none. When the referred user's first QuizAttempt is synced: set Referral.status=REWARDED and extend the inviter — skip entirely if inviter is PRO with proUntil == null (lifetime) or already has 8 REWARDED referrals; otherwise plan='PRO', proUntil = max(now, proUntil) + 7 days, insert Order{provider:MANUAL, product:'referral-7d', amountCents:0, status:'paid'}. Avatar sheet "Invite friends" uses Web Share API (fallback: copy link) and shows "n/8".
  4. Share images: src/app/api/og/result/[attemptId]/route.tsx and src/app/api/og/card/[key]/route.tsx using next/og ImageResponse (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.
  5. 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 from mistakes, Arabic explanation from noteAr, CTA with the bio link) using only AI_CHECKED/HUMAN_APPROVED items; 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.
  6. Admin "Sources" page: table per signupSource for the last 30 days — Source | Visitors (distinct anonId/userId of app_open with that meta.attribution.source) | Signups | Pro (users with a paid non-MANUAL Order) | Revenue | Ad spend (from AdSpend) | Cost per Pro (= Ad spend / Pro, blank when Pro = 0). A form on the page upserts AdSpend(source, month, amountCents).
  7. Legal pages /imprint, /privacy, /terms per locale, rendered with react-markdown from content/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 /pro shows "Coming soon" instead of the checkout button, and ad campaigns must not start.

Critical files & anchors

Verification

Assumptions & contingencies