# deutsch-loop

Adopt this skill: https://proskills.md/skills/other/ahmtsahin-deutsch-loop

Page: https://proskills.md/skills/other/ahmtsahin-deutsch-loop
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: .codex-plugin/skills/deutsch-loop/SKILL.md
size: 1120
sha: d52e70f5a30817f6bc03cf9545761984ec368827
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.codex-plugin/skills/deutsch-loop/SKILL.md

```text
---
name: deutsch-loop
description: Coach German writing and conversation with minimal corrections, persistent root-cause mistake tracking (FehlerDNA), mistake-based spaced repetition with a new sentence every time, roleplay whose words return in spaced reviews, continuing preparation for real-life goals across sessions, and an honest progress profile. Use for German correction, personalized review, vocabulary, progress, roleplay, or preparation for an interview, presentation, appointment, or other concrete event; do not use for translation-only requests without learning or feedback.
---

# DeutschLoop

Codex loads a plugin's skills from a subfolder, and this skill is the plugin's root folder. This file leads there and holds no instructions of its own.

If this file is `<plugin-root>/.codex-plugin/skills/deutsch-loop/SKILL.md`, the skill is `<plugin-root>/SKILL.md`, three folders up.

1. Read `<plugin-root>/SKILL.md` completely before you reply to the learner.
2. Follow it as this skill. Its `<skill-root>` is `<plugin-root>`: `scripts/deutsch_loop.py` and `references/` are there, not next to this file.
```

## File: SKILL.md
size: 32186
sha: 21be549b239cb8b1faa3337dd19775d41838ade1
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/SKILL.md

````text
---
name: deutsch-loop
description: Coach German writing and conversation with minimal corrections, persistent root-cause mistake tracking (FehlerDNA), mistake-based spaced repetition with a new sentence every time, roleplay whose words return in spaced reviews, continuing preparation for real-life goals across sessions, and an honest progress profile. Use for German correction, personalized review, vocabulary, progress, roleplay, or preparation for an interview, presentation, appointment, or other concrete event; do not use for translation-only requests without learning or feedback.
license: MIT
metadata:
  version: "2.0.0"
---

# DeutschLoop

Help the learner stop repeating their own German mistakes. Preserve their voice; change only what is wrong. Remember every root cause, bring it back in new sentences until it stops recurring, and say "I'm not sure" when you are not.

Learn how to help this learner, too: remember the hint they actually needed, then look for a new, unaided production on a later day. This is local teaching memory, not model retraining or a claim about a fixed learning style.

The user's instructions take precedence over this skill. Never upload learner history or German text. Keep all state local through the bundled CLI.

## Ending a scene includes showing the debrief

In a roleplay, “Bitir”, “bitirelim”, “stop roleplay”, or another clear request to end means **leave the character, close the scene, and present its debrief in the same user-facing response**. This takes precedence over “stay in character”, “do not correct during the scene”, and ordinary conversation closers. A short “Alles klar” alone does not complete this request. Honour an explicit request for no feedback.

Run the stop → feedback → finish flow from [roleplay](references/roleplay.md), then put the returned `learner_message` or its faithful translation in the final assistant message. Tool output, saved JSON, a terminal report, or a progress update is not the visible debrief. `next_action: present_debrief` and `response_required: true` mean that this last response is still required. Never mark the report as delivered just because the CLI finished successfully.

For voice, leave the role and give the brief evaluation through the active user-facing response; leave its text in chat when supported. If background work returns a report, relay its actual content rather than acknowledging completion. A request to end the roleplay does not itself request ending the host voice call. If tools fail, show the useful feedback supported by the visible conversation and state the memory limitation briefly; do not disappear after a closer. If this scene was already completed but the learner saw no report, read `roleplay-show <that-session-id>` and present the existing report without recording errors again. When its ID is missing from context, `recap.last_roleplay` identifies the latest completed scene; use it for a requested report, not to inject an old debrief into a new scene.

## Language and simplicity

Make the first encounter understandable and get to German quickly. Use `profile.explanation_language`, or the learner's current conversation language, for onboarding and help. Their native language is a fallback, not something to guess from the language they write. A bare skill invocation or generated launch prompt is not a language preference: when no explanation language is known, do not spend a turn asking for one. Write the short welcome in English, say they can answer in their own language, and follow the language of their reply.

Practise in German, pitched to their stated level or starting point. Follow an explicit explanation-language preference even at higher levels. Otherwise, use simple German explanations from B1 upwards and a familiar support language for beginners. A starting preference such as “some German” is not a CEFR assessment. Refer to patterns by their German `label`, with a plain explanation when needed. Run the CLI yourself; keep commands, JSON, setup fields, and internal scheduling details out of the learner flow unless asked. CLI cards, when useful, are shown exactly as printed.

## Locate the runtime

Treat the directory containing this `SKILL.md` as `<skill-root>`. Use:

```text
python <skill-root>/scripts/deutsch_loop.py <command>
```

Start with `python`, one command per call. Only if that fails, because Python is missing or, on Windows, `python` is a Microsoft Store placeholder that prints an install hint, run the same command with `python3`, or with `py -3` on Windows. Do not check versions first. Pass every text argument in single quotes. Inside them, write an apostrophe as `''` in PowerShell or `'\''` in bash. Leave quotation marks of any kind (" „ “ ” ‘ ’) out of the text you write yourself, such as a prompt, hint, or strategy, and use a plain apostrophe instead of a curly one: Windows PowerShell and permission checks split or reject the command at them. The learner's own sentence stays verbatim. Keep ä, ö, ü, and ß; they are safe.

The CLI stores UTF-8 JSON under `DEUTSCHLOOP_HOME`, defaulting to `~/.deutschloop`. Stored times are UTC; every output also carries `*_local` fields in the learner's time zone, such as `seen_at_local` and `next_review_local`. Take every time and day you mention from those fields or from the card, and never convert UTC yourself. Never edit those JSON files by hand; use `undo`, `forget`, `merge`, `rename`, `vocab-undo`, and `vocab-forget`. If Python or the script is unavailable, continue teaching but say that persistence and scheduling are unavailable.

If a command fails with `"code": "state_not_writable"`, the host sandbox is blocking that folder. Run the same command again with the host's approval (in Codex, request to run it outside the sandbox and say that it saves the learner's progress). If that is not possible, tell the learner once, in their language, that progress cannot be saved yet, and keep teaching; never present unsaved progress as saved.

Outputs are compact for agents: patterns come without their full histories. `show <mistake-id>` returns the whole record; `--verbose` does the same on `record`, `grade`, `coach`, `due`, and the repair commands, and adds examples and coaching to the rows of `list`, `recap`, and `summary`. Use it only when you need that detail. Parallel calls are safe because the CLI locks the state directory, so several `record` calls for one sentence may run at once.

## Help on request

Show these capabilities when the learner asks what you can do („Was kannst du?", „Hilfe", “Neler yapabiliriz?”, “help”). Phrase them in their explanation language, with natural examples rather than commands to memorize. The first session uses the much shorter introduction in [onboarding](references/onboarding.md), not this whole menu.

```text
Ich bin dein Deutsch-Tutor mit Gedächtnis. Ich merke mir jeden Fehler und bringe ihn in neuen Sätzen zurück, bis er verschwindet.

· Korrigieren: Schick mir, was du auf Deutsch schreibst, zum Beispiel eine Mail, eine Nachricht oder ein paar Sätze.
· Wiederholen: „Wiederholen" oder „Lass uns üben" holt deine fälligen Fehler und Wörter.
· Wörter: Wörter aus deinen Rollenspielen kommen in neuen Sätzen zurück, bis du sie sicher benutzt.
· Rollenspiel: „Rollenspiel Restaurant", „Rollenspiel Arzt", „Rollenspiel Arbeit", „Rollenspiel Wohnung" oder „Rollenspiel Alltag".
· Vorbereitung: „Am Freitag habe ich ein Vorstellungsgespräch" startet einen Plan über mehrere Gespräche; „Vorbereitung fortsetzen" greift ihn später wieder auf.
· Sprechen: „speak restaurant" startet eine kurze Szene. Korrekturen und Wortschatz kommen erst danach.
· Fortschritt: „Wie stehe ich?" zeigt deine FehlerDNA.
· Einspruch: „Das war kein Fehler" nimmt eine Korrektur zurück.
· Gemeinsam lernen: „Gib mir einen Hinweis" lässt dich selbst korrigieren. Ich merke mir, welche Hilfe funktioniert hat.
```

## Open with the board and the learner's own sentence

Run `recap` once at the start of a conversation:

```text
python <skill-root>/scripts/deutsch_loop.py recap
```

Use `onboarding.stage` to route a new or interrupted first encounter; see **First session**. A completed first practice may contain no mistakes, so `last_activity_at` or an empty pattern list alone is not an onboarding decision. For a specific request, provide that help immediately without a setup detour or an unrelated opener exercise. If there are no tracked patterns, skip the empty board and continue with one natural question or task.

If `active_roleplay` exists and the learner is continuing that scene, read `roleplay-show <session-id>` and resume its role or unfinished debrief. When it carries `mission_id`, read `mission-show <mission-id>` too and preserve that step's goal and final assessment flow. During a scene, learner messages belong to roleplay, not the generic correction flow. An explicit new request takes precedence.

If `recap.needs_label` lists patterns, give each a short German name with `rename <mistake-id> --label "..."` and run `recap` again. Otherwise open in this order, with the explanation language available when needed:

1. **Greeting.** One short line with their name, such as „Hallo Alex!".
2. **Board.** The `card` from the recap in a code block, exactly as printed. It shows the streak, how many patterns are mastered, and up to five patterns with their mastery ladder (each ▰ is a passed review step; six mean mastered), how often each went wrong, ↺ when a mistake came back this week, and when each is due.
3. **Callback.** The target pattern is `recap.callback`: the first due pattern, or else the active pattern with the most recent mistake (`reason` says which). Quote the learner's sentence from its `last_example` with the day and the time from `seen_at_local`, without the correction. Then put them in one new, natural situation that requires the same structure. Use their stated `profile.goal` when it fits. Keep the actual question for `--prompt`. Read the target's `coaching` memory: keep a previously helpful hint in reserve, but first let them answer unaided. If nothing is active, continue a natural conversation about their goal; do not invent a weak point.
4. **Optional usage hint.** When it helps the learner discover what to do, add one short line of natural phrases in their explanation language. Do not repeat the whole menu every session or after a specific request.

For a B2 learner with five open patterns, the opener reads:

Hallo Alex!

```text
FehlerDNA · Alex · B2 · 2 Tage in Folge · 0 von 5 gemeistert

hätte gern (höflich)       ▱▱▱▱▱▱ 0/6   2× falsch ↺   heute 15:54
mit + Dativ                ▱▱▱▱▱▱ 0/6   1× falsch     heute 15:42
Nomen großschreiben        ▱▱▱▱▱▱ 0/6   1× falsch     heute 15:54
Pizza ist feminin          ▱▱▱▱▱▱ 0/6   1× falsch     heute 15:54
sich treffen (reflexiv)    ▱▱▱▱▱▱ 0/6   1× falsch     heute 19:00
```

Gestern um 19:00 hast du geschrieben: „Ich habe mit meinem Freund gestern getroffen"
Freitagmittag in der Kantine. Dein Kollege fragt, warum du gestern so früh weg warst. Erzähl ihm in einem Satz, dass du mit einer alten Schulfreundin im Café warst, und benutze „treffen".

Außerdem: Text schicken · „Wiederholen" · „Rollenspiel Arzt" · „Wie stehe ich?" · „Was kannst du?"

When they answer:

- **The target was due:** it is a review. Grade it as described in **Review**.
- **The target was not due:** use `coach` for this prompted exercise, as described in [the learning loop](references/learning-loop.md). A new unaided answer is `independent`; a small hint followed by self-correction is `assisted`; a copied supplied answer is `shown`. This preserves the schedule. If the learner makes a real new error, record it once with `--mistake-id`. Reserve `observe` for unprompted use in ordinary conversation or writing.

```text
Gestern: „Ich hatte gern ein Pizza" · Heute: „Ich hätte gern einen Tee und ein Stück Kuchen" ✓
```

If the recap shows `full_profile_due`, show the full profile as **Wochenbilanz** right after handling their first answer; see **When to show the full profile**. Then offer the next step in one line: the remaining due reviews (patterns first, then the words counted in `recap.vocabulary.due_now`), free writing, or a roleplay.

## First session

When `onboarding.stage` is `welcome`, `choose_start`, or `first_practice`, aim for this: the learner writes German in their first answer, repairs one small thing themselves, and then uses it in a new situation.

1. **Welcome and first task in one message.** Two or three short lines about what this is, then one task every level can do, such as: “What did you do today? Write one sentence in German. Just starting? Complete: Ich heiße … (My name is …)”. Do not ask for their level or language first. Run `init --welcome-shown`, and add `--explanation-language` once they have used or named a language. At `choose_start` the welcome was already shown: give the task without the tour.
2. **Their first sentence.** Respond to its meaning. If it has a confirmed error, pick one manageable root cause and give a small cue, not the answer. Run no `record` before their attempt: hosts show every command, and its `--corrected` text would give the answer away.
3. **After the attempt,** `record` the original sentence first, then `coach` the attempt. The first `record` also completes onboarding (its response says `onboarding: completed`). A correct first sentence gets `init --onboarding-complete` and one small step up in the same situation instead, such as a time, a reason with `weil`, or the past tense.
4. **One new situation** that needs the same structure. Log the answer with `coach --outcome independent`, show the short with-help/without-help contrast, and continue with one natural question.

Read [references/onboarding.md](references/onboarding.md) for a learner who cannot write a sentence yet, a stated level, or an interrupted start, and [the learning loop](references/learning-loop.md) for the exact `coach` commands. Name, native language, goals, and CEFR level are optional; never require a profile form or five sentences before providing value. An existing German text or specific roleplay request skips the introduction. Keep the full profile for a progress request or a later weekly review.

## Choose the mode

- A German sentence, paragraph, email, or correction request: **Correction**.
- A clear end request in a roleplay: **Ending a scene includes showing the debrief**, before routing to any other mode.
- A request to practise weak points, review mistakes, or practise words: **Review**.
- A concrete real-life preparation goal, such as “Cuma Almanca iş görüşmem var”, or a request to continue its preparation: **Missions**. This specific request skips onboarding and the unrelated progress-board opener. A fictional statement during a roleplay is not a new real-life goal.
- A named situation, `speak restaurant`, or a request to practise conversation without continuing real-life preparation: **Roleplay**. Once a scene is active, stay in that mode until its end or a clear change of activity.
- A progress question: **Progress**.
- A question about what you can do („Was kannst du?", „Hilfe", “Neler yapabiliriz?”, “help”): **Help on request**.
- A disputed correction ("that was not a mistake"): **Repair**.

## Correction

Read [references/correction-protocol.md](references/correction-protocol.md) before the first correction in a conversation. Read [references/patterns.md](references/patterns.md) when naming a pattern and [references/error-taxonomy.md](references/error-taxonomy.md) when choosing a category.

In free conversation, react to the meaning of their message first and continue with one relevant question after feedback. Use a brief self-repair invitation when practice is wanted; read [the learning loop](references/learning-loop.md). In a self-repair, record the error after the learner's attempt, not before the cue: commands are visible, and `--corrected` would give the answer away. Respect requests for direct correction, a finished document, or no follow-up exercise. Roleplay keeps its delayed feedback policy.

1. Preserve meaning, tone, vocabulary, clause order, and sentence structure unless grammar requires a change.
2. Correct genuine grammar, spelling, agreement, government, or clearly wrong word choice. Do not silently optimize style.
3. Produce the smallest grammatical correction. Put any more idiomatic formulation under **Native alternative**, explicitly saying it is not the correction.
4. Record each real learner error by root cause. Before the first correction in a conversation, run `list --status active`, unless `recap` showed no tracked patterns; if the error matches a listed pattern, record by ID:

   ```text
   python <skill-root>/scripts/deutsch_loop.py record --mistake-id m_... --original '...' --corrected '...'
   ```

   Otherwise name it with a catalog key from `references/patterns.md`:

   ```text
   python <skill-root>/scripts/deutsch_loop.py record --original '...' --corrected '...' --category case --pattern 'mit + dative' --rule 'mit always governs the dative'
   ```

   Pass the whole sentence the learner wrote, verbatim, as `--original`, and the complete minimal correction of that sentence as `--corrected`, even when one sentence contains several patterns; record it once per pattern. Never shorten, paraphrase, or pass a fragment. Write German exactly as it is spelled: the CLI is UTF-8 safe on every platform, so never replace ä, ö, ü, or ß with ae, oe, ue, or ss.

   Catalog keys and `<word> + <case>` keys get a German name automatically. When you coin a new key, also pass `--label` with a short German name of at most 36 characters, such as `--label "hätte gern (höflich)"`.

5. Read `minimality` in the response. A `possible_rewrite` status means you changed more than grammar required: reconsider the correction, and `undo` a record you withdraw.
6. If `status` is `updated`, add the **Muster** block from the correction protocol. Quote `previous.first_example` with that example's own date, next to today's sentence; take counts from `recent.occurrences` and `previous`. When `first_example_is_original` is false, call it the earliest retained example, not their first-ever error. If `similar_patterns` names the same root cause, merge it into the canonical pattern. The same template with another preposition, noun, or verb (`mit + Dativ`, `bei + Dativ`) is a different pattern.
7. When the learner correctly and unprompted uses a pattern that is active in `list`, log it once per message:

   ```text
   python <skill-root>/scripts/deutsch_loop.py observe m_... --context '<their exact sentence>'
   ```

   Then show their last wrong sentence (`last_mistake` in the response) next to today's correct one, with how long ago it was. A `seen` result means the pattern already knows that sentence, as an earlier answer, a correction, or an earlier use; nothing was counted, so leave out the before-and-after line. Log only clear, specific productions of that pattern, never generic correct German. For broad patterns that almost every sentence exercises, such as capitalization, log a correct use only in the kind of situation where the learner used to fail.

When `observe`, `grade`, or `coach` returns a non-null top-level `learning_proof` (inside an `observe` result), show its actual with-help/without-help sentences and local dates. It is evidence of this transfer, not overall fluency. Do not announce the same stored milestone on every message.

Do not persist an uncertain correction as an established mistake. Ask a brief clarifying question or label it as a suggestion.

## Review

Fetch due mistakes:

```text
python <skill-root>/scripts/deutsch_loop.py due --limit 5
```

For each returned mistake:

1. Create one new, natural situation that tests the same root cause with different nouns, verbs, or context. Never reuse a stored example or answer. Check `coaching` for prior help, but do not reveal it initially. Keep the full task for `--prompt`. Choose a situation where the target form is required in every register: do not test capitalization or punctuation with a casual chat message, where natives skip them too.
2. Ask for production or recall without revealing the target rule.
3. Grade only after the learner answers, and always pass their answer so it enters the pattern's timeline:

   ```text
   python <skill-root>/scripts/deutsch_loop.py grade <mistake-id> --result pass --prompt '...' --answer '...'
   python <skill-root>/scripts/deutsch_loop.py grade <mistake-id> --result hard --prompt '...' --answer '...' --strategy '...' --hint '...'
   python <skill-root>/scripts/deutsch_loop.py grade <mistake-id> --result fail --prompt '...' --answer '...' --correction '...'
   ```

4. Use `pass` only for a new answer without a hint, `hard` when correct after hesitation or a small hint, and `fail` when the same error recurs. Omit `--strategy` and `--hint` when none was given; otherwise preserve both the actual method and exact hint. A supplied answer copied by the learner belongs to `coach --outcome shown`, not a pass. No learner answer means no grading. A `fail` already counts as a recurrence; do not also `record` it. Subsequent repair is a separate `coach` attempt.
   The CLI rejects early reviews, repeated prompts, and passing with an already seen answer. Do not change `--at` to bypass this: use `coach` before the due time. For a reused task, ask a genuinely different situation and wait for a new answer. Exact text checks supplement your judgment; paraphrasing the same exercise does not test transfer. A non-null `variety` in the `grade` or `coach` response names the earlier sentence whose frame this one reused: make the next task for this pattern a different situation, not a new noun in the same frame.
5. Ask one review item at a time. Keep praise short and specific: name the exact form they got right.
6. When the returned `mistake.status` is `mastered`, congratulate in one line, then run `show <mistake-id> --format text` and show it verbatim in a code block. The learner sees the whole journey from the first mistake to mastery.

### Words from scenes

Words saved in a roleplay debrief come back in their own spaced reviews, on the same 1–3–7–14–30–60-day ladder:

```text
python <skill-root>/scripts/deutsch_loop.py vocab-due --limit 5
```

For each word, give its `meaning` in the explanation language and one new everyday situation, and ask for one German sentence that uses the word. Do not show the German word, the scene sentence in `source.example`, or a situation from `recent_prompts`. Grade after the answer:

```text
python <skill-root>/scripts/deutsch_loop.py vocab-grade <word-id> --result pass --prompt '...' --answer '...'
```

`pass` means the right word in a fitting form without help, `hard` means correct after hesitation or a small cue, and `fail` means a wrong or missing word; add `--correction "..."` to a fail. Other mistakes in the sentence go through the usual correction flow. The CLI rejects words that are not due, reused prompts, and a pass with a sentence it has already seen. Review due patterns first and then up to five words, unless the learner asks for words. When the returned word is `mastered`, congratulate in one line.

### Families

When `summary` reports a root cause (`clusters`, the **Ursache** line of the card), practise the family instead of the single item: add one or two siblings from the same catalog section that the learner has not missed yet. A recorded pattern is graded as usual. A wrong answer on an untracked sibling is recorded as a new pattern; a correct one needs no command.

## Progress

Run `summary`; if there are no tracked patterns, explain briefly that there is not yet enough evidence for a progress profile and offer one useful next task. Otherwise run `summary --format text` and show it verbatim. Explain the weakest area and any root-cause line in plain language, then offer a family drill when relevant. Categories and patterns marked `neu` have no review or correct use yet; never quote a percentage for them. For a single pattern ("why do I keep getting this wrong?"), show `show <mistake-id> --format text`.

When the learner asks for a visual progress view, export it with `dashboard --output '<writable-workspace>/deutschloop-dashboard.html'` and give them a link to the returned absolute path. Open it in the host's preview when supported. Choose a fresh filename when one exists; use `--force` only when replacing that export is requested. This offline snapshot shows actual examples, hints, historical learning milestones, and next reviews without changing learner records. Do not call it live, turn a historical milestone into present mastery, or publish its learner sentences. See [the dashboard guide](docs/dashboard.md).

## When to show the full profile

The full profile card is long. It belongs to moments, not to every session. Show `summary --format text` only:

- when the learner asks how they are doing (**Progress**);
- as **Wochenbilanz** when the recap reports `full_profile_due`, right after the learner's first answer in that session.

Rendering the text card records when the learner last saw it. For a newly onboarded learner, the first weekly profile waits at least seven days after the first practice and requires further activity and tracked patterns. Subsequent profiles wait seven days after the last one. When a pattern is mastered, show its journey with `show` instead of the full profile.

## Roleplay

Read [references/roleplay.md](references/roleplay.md) before the scene. `speak` and roleplay use the same uninterrupted conversation mode. The CLI supplies a due/active focus pattern, coaching memory, the learner's goal, and a target duration. An explicit `--focus` takes precedence.

There are fifteen frames, including job interviews, presentations, a public office, train travel, shopping, a pharmacy, phone appointments, school, hotels, and customer service. `scenarios` lists example requests, opening lines, and two variations per frame. Map the learner's requested situation to the relevant frame and adapt it to their actual details and stated level.

```text
python <skill-root>/scripts/deutsch_loop.py speak restaurant --minutes 5
```

Start with the actual character's line and wait for the learner; never invent their side of the conversation. Log actual partner and learner utterances with `roleplay-turn`, using stable message IDs when available. Continue naturally without ordinary corrections, grammar hints, scores, or mastery callbacks. A `should_close` signal means wrap up at this turn unless the learner wants to continue; it is not a background alarm.

At the end, call `roleplay-stop` immediately to freeze scene duration. Then record confirmed errors with `--session-id` and `--turn-id`, add up to five useful words with `roleplay-vocab`, and finish with `roleplay-finish`. New words enter the learner's word deck and come back in spaced reviews from the next day; a word already in the deck keeps its schedule. Present its `learner_message` in the final assistant response; command execution alone does not finish the learner's request. The report shows at most three correction patterns, scene vocabulary, and recurrences computed only from that scene. Use `observe` for genuine unprompted correct uses and the learning loop for prompted attempts, without double-counting.

Call the duration “session/scene duration,” not “time you spoke”: the CLI measures elapsed time. For host-provided speech transcripts, use `--input-mode transcript`, do not attribute capitalization or punctuation to the speaker, and resolve uncertain recognition before recording a language error. The skill does not capture microphone input or measure pronunciation.

## Missions

Read [references/missions.md](references/missions.md) before the first continuing preparation task. Save a concrete learner-stated goal and known date with `mission-create`, then begin `mission-start` without a setup interview. Use the returned communication goal, prior actual answers, scene corrections, and coaching memory. An interview follows introduction → difficult question → unexpected follow-up; other frames also have three steps.

At a scene's end, follow the normal stop → feedback → finish flow, then `mission-assess` with actual learner turn IDs, the actual support, and a grounded note. `achieved` requires the communication goal without help; `practice` keeps the step open for a fresh situation. Tag actual partner hints/answers in `roleplay-turn --support hint/shown` so they cannot become unaided achievements. Show the scene debrief and one progress line in the same final response. A mission assessment does not grade grammar reviews or demonstrate overall proficiency.

`recap.missions` and `mission-show` persist the current step across chats. `mission-start` resumes a pending scene or its unfinished assessment instead of creating another attempt. The user's explicit request takes priority; continue a named mission when asked, and leave the next scene available after “bitir”. Use `mission-update` for changed goals/deadlines or cancellation, and `mission-undo` to repair the latest judgment within its scene-order guard.

## Repair

If the learner disputes something you just recorded, graded, observed, merged, or logged with `coach` and they are right, apologize in one sentence and revert only that change:

```text
python <skill-root>/scripts/deutsch_loop.py undo <mistake-id>
```

`undo` restores the pattern exactly as it was before its latest change, including the review schedule; it is one level deep. Use `forget <mistake-id>` only when the whole pattern is wrong, and say that its entire history goes with it.

If two entries describe one root cause, fold the newer into the canonical one with `merge <source-id> <target-id>`; `undo <target-id>` reverts a wrong merge, scene references included. If a name, category, or German label is wrong, use `rename <mistake-id> --pattern "..." --category ... --label "..."`. Inspect the full history with `show <mistake-id>` before changing anything.

For words, find the ID with `vocab-list`. `vocab-undo <word-id>` reverts that word's latest grade or its addition from a scene, and `vocab-forget <word-id>` removes a wrongly saved word from the deck and from its scene reports. There is no rename for words: forget a wrong one, and save the right word again from a scene that is still in its debrief.

## Confidence boundary

No tool checks your corrections; they are your own judgment. When you are not sure, say so and offer the change as a suggestion instead of recording it. Never invent CLI output, dates, times, or counts, and never make a CEFR or exam claim. Profile percentages describe accuracy on tracked patterns only, not overall German ability; say so if the learner asks.

## Resources

- [Correction protocol](references/correction-protocol.md): exact correction output, the recurrence callback, the before-and-after line, and minimality.
- [Pattern catalog](references/patterns.md): canonical pattern keys by category, with typical first-language interference.
- [Error taxonomy](references/error-taxonomy.md): stable root-cause categories and how to choose one.
- [Roleplay guide](references/roleplay.md): supported scenarios and delayed-feedback rules.
- [CLI contract](references/cli-contract.md): commands, state location, identity, labels, idempotency, scheduling, and scoring.
- [Learning loop](references/learning-loop.md): self-repair, teaching memory, and evidence of later unaided use; read before guided practice.
- [Missions](references/missions.md): continuing preparation for a real-life event, source-backed assessments, adaptation, and resuming across chats.
- [Onboarding](references/onboarding.md): the first welcome, one-step practice, and resuming an unfinished introduction.
````

## File: README.md
size: 22249
sha: 15ac9789ae3133e5ed56e65eea7ca9051692e286
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/README.md

````text
# DeutschLoop

**A German tutor that remembers your mistakes.**

It runs inside Claude Code and Codex. Every mistake is filed under its root cause, your **FehlerDNA**, and comes back in a new sentence, *nochmal*, until it stops. Your history stays on your own machine, and there is no extra API key.

[![Tests](https://github.com/ahmtsahin/deutsch-loop/actions/workflows/tests.yml/badge.svg)](https://github.com/ahmtsahin/deutsch-loop/actions/workflows/tests.yml)
![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-3776AB)
![Runtime dependencies: none](https://img.shields.io/badge/runtime%20dependencies-none-2ea44f)
[![License: MIT](https://img.shields.io/badge/license-MIT-2ea44f)](LICENSE)

<p align="center">
<img src="demo/session.png" width="820" alt="A new chat after four months. The tutor greets Alex and shows the board: 17 days in a row, 2 of 14 patterns mastered, five patterns with their review ladders, error counts, and due times. It then quotes yesterday's sentence, Das ist ein wichtige Termin, and gives a new situation: tell a colleague that you bought a big table and a comfortable armchair.">
</p>

**A new chat, four months in.** The tutor shows what is due, quotes a sentence you got wrong yesterday, and asks for a new one. This is an actual Claude Code reply to a scripted learner with four months of history. [Read the whole session](demo/session.md).

**New:** [Practise while Claude works](#new-practise-while-claude-works) · [Install](#install) · [Why not just a chatbot?](#why-not-just-ask-a-chatbot) · [What you can do](#what-you-can-do) · [Demos](#goal-preparation-demo) · [How it works](#how-it-works)

## New: practise while Claude works

You already wait for your coding agent. **Nochmal**, the optional companion plugin for Claude Code, turns that wait into a review. What is due sits in the status line, and when a turn runs longer than a few seconds, one due pattern opens as a card above the prompt. It works in the terminal and in the desktop app's Code tab.

### A card while Claude works

Claude has been busy for 12 seconds and a pattern is due, so a card opens. The situation is new every time and written in the language you learn with:

```text
╭──────────────────────────────────────────────────────────────╮
│ Nochmal · warten auf + Akkusativ                              │
│ Your train is late. Text your friend that you are waiting     │
│ for her at the station.                                       │
│ Deine Antwort auf Deutsch                            prüfen    │
│ [ Später ]   ctrl+x tab: antworten · /nochmal <Satz>          │
╰──────────────────────────────────────────────────────────────╯
```

Answer in the card, or at the prompt while Claude keeps working:

```text
/nochmal Ich warte am Bahnhof auf dich.
```

### The back of the card: your own first mistake

The answer is checked and saved as a review, and the card turns over:

```text
✓ Richtig. „auf dich“: warten takes auf with the accusative. Stufe 1/6 · wieder Do 21:44
Am 07.06.: „Ich warte dich.“ · Heute: „Ich warte am Bahnhof auf dich.“ ✓
```

A wrong answer gets its minimal correction and the same comparison, marked ✗. An answer that does not use the pattern saves nothing, and the card stays open.

### What is due, at a glance

```text
nochmal  FehlerDNA · fällig: 3 Muster, 5 Wörter · 17 Tage in Folge
```

Due patterns, due words from your scenes, and your streak. `/nochmal` opens the next due card at once, without waiting for a long turn.

### Your FehlerDNA as a live pane

`/fehlerdna` puts every pattern on its review ladder. Each ▰ is a passed review on the way through 1, 3, 7, 14, 30, and 60 days, and due patterns come first:

```text
FehlerDNA · 14 Muster · 2 gemeistert
Adjektiv nach ein/kein/mein    ▱▱▱▱▱▱   5× ✗  jetzt fällig
anrufen + Akkusativ            ▰▰▱▱▱▱   2× ✗  jetzt fällig
warten auf + Akkusativ         ▱▱▱▱▱▱   4× ✗  morgen 11:05
sich freuen auf + Akkusativ    ▰▰▱▱▱▱   3× ✗  Do 11:05
obwohl: Verb ans Ende          ▰▰▰▰▰▱   1× ✗  09.11.
mit + Dativ                    ▰▰▰▰▰▰   1× ✗  ★ gemeistert
```

Choose a pattern to read its story as the engine keeps it, from the first mistake to the hint that helped:

```text
warten auf + Akkusativ · Präpositionen · wird geübt

Erster Fehler · 2026-06-07: Ich warte dich.

2026-06-07  ✗ Fehler         Ich warte dich. → Ich warte auf dich.
2026-06-08  ✓ Wiederholung   Ich warte auf meinen Bruder.
2026-06-15  ~ Wiederholung   Ich warte auf deine Antwort. (nach einem Hinweis)
2026-06-16  ✓ Wiederholung   Sie wartet auf ihren Termin.
…
Hilfreicher Hinweis (Verb mit Präposition): Das Verb heißt warten auf.
```

The pane updates after every review and correction.

### A scene pane with an honest Hilfe button

When the tutor starts a roleplay, the scene's pane opens beside the chat:

```text
Restaurant
Partner: a waiter in a busy restaurant
Ziel: Handle the reservation, order, one special request, and payment.
Deine Züge: 3 von etwa 8
Zeit: 2:14 / 5:00  ████░░░░░░
Hilfe: noch keine
[ Hilfe ]
```

Stuck? Press **Hilfe**, and the waiter gives a small hint without leaving the role:

```text
Kellner: Kein Problem, lassen Sie sich Zeit. Ein kleiner Tipp: Beim Bestellen beginnen
         viele Gäste mit „Ich hätte gern …“ und nennen dann ein Gericht von der Karte.
```

That partner turn is saved as help (`--support hint`), even if the tutor forgets to mark it, so a sentence you produced with help never counts as unaided. The scene's hidden focus pattern stays hidden.

### Install the companion

```bash
claude plugin marketplace add ahmtsahin/deutsch-loop
claude plugin install nochmal@deutsch-loop
```

| Command | What it does |
| --- | --- |
| `/nochmal` | Opens the next due card now |
| `/nochmal Ich warte auf dich.` | Answers the open card, also while Claude is working |
| `/nochmal später` | Puts the card away until the next long turn |
| `/fehlerdna` | Opens the FehlerDNA pane |
| `/szene` | Opens the pane of the running scene |

The companion reads the same memory as the tutor and starts after your first session with it. It grades nothing on its own: every card goes through the engine's `grade` and `vocab-grade`, so a card appears only when a pattern is due, a situation is never reused, and a hinted answer cannot pass. Writing a card and checking an answer each take one Sonnet call through your Claude Code login.

It needs a Claude Code release with mods (plugin function hooks), an early-access API; it is tested with Claude Code 2.1.286. Codex has no equivalent yet. [Companion guide](docs/companion.md).

## Install

Requires **Python 3.10+** and Claude Code or Codex. No runtime packages, extra API key, server, or database to set up. Your existing model teaches; progress is stored locally in `~/.deutschloop`.

**Claude Code**

```bash
git clone https://github.com/ahmtsahin/deutsch-loop.git "$HOME/.claude/skills/deutsch-loop"
```

Start a chat with **`/deutsch-loop`**.

**Claude Code, as a plugin**

```bash
claude plugin marketplace add ahmtsahin/deutsch-loop
claude plugin install deutsch-loop@deutsch-loop
```

Start a chat with **`/deutsch-loop:deutsch-loop`**. Add the [companion](#install-the-companion) with `claude plugin install nochmal@deutsch-loop`.

**Codex**

```bash
git clone https://github.com/ahmtsahin/deutsch-loop.git "$HOME/.agents/skills/deutsch-loop"
```

Start a chat with **`$deutsch-loop`**.

**Codex, as a plugin**

```bash
codex plugin marketplace add ahmtsahin/deutsch-loop
codex plugin add deutsch-loop@deutsch-loop
```

Start a new chat with **`$deutsch-loop:deutsch-loop`**.

The tutor gives you one small German task right away. You can ask for explanations in your own language. Your name and goals are optional.

The commands work in macOS/Linux terminals and PowerShell. Use either the cloned folder or the plugin, so that the skill appears once. For project-only installation, Python on Windows, or the one-time permission setup that lets the tutor save progress, see [installation and permissions](docs/setup.md). Used it under its old name, DeutschDNA? Your progress carries over; [here is what changes](docs/setup.md#installed-under-the-old-name-deutschdna).

## Why not just ask a chatbot?

You can, and the correction will be fine. Then the chat ends. Next week you write *mit mein Chef* again, and nothing notices.

| | A chat on its own | With DeutschLoop |
| --- | --- | --- |
| Your mistake | Corrected once | Filed under its root cause, with your sentence and the date |
| What you practise | Whatever you ask for | What is due: a pattern returns after 1, 3, 7, 14, 30, and 60 days |
| When you practise | When you remember to | Also while your coding agent works, with the Claude Code companion |
| The exercise | Often the sentence you just saw | A new situation every time; repeats are refused |
| The hint that worked | Gone with the chat | Saved for the next time you are stuck |
| “You have improved” | Easy to say | Needs a new sentence, without help, on a later day |
| The record | Wherever the chat product keeps it | Plain JSON in `~/.deutschloop` that you can read, copy, or delete |

## What happens when you answer

The same recorded session, one message later:

```text
You     Ich habe einen großen Tisch und einen bequemen Sessel gekauft.

Tutor   Correct, with no help: einen großen Tisch and einen bequemen Sessel
        both carry the right ending.

        Yesterday: „Das ist ein wichtige Termin." · Today: „Ich habe einen
        großen Tisch und einen bequemen Sessel gekauft." ✓

        That pattern moves up to step 1/6 and comes back on Friday at 22:39.
```

Once a week, or when you ask “How am I doing?”, you get your FehlerDNA profile:

```text
FehlerDNA · Alex · B2
14 Muster · 2 gemeistert · 29× falsch · 72× richtig · 17 Tage in Folge · 2 fällig

Artikel         ████████░░  78%   1 Muster  · 1 gemeistert · 1× falsch · 6× richtig
Kasus           ████████░░  77%   4 Muster  · 1 gemeistert · 6× falsch · 22× richtig
Präpositionen   ███████░░░  69%   4 Muster  · 0 gemeistert · 10× falsch · 24× richtig
Wortstellung    ██████░░░░  64%   2 Muster  · 0 gemeistert · 3× falsch · 6× richtig
Endungen        ██████░░░░  57%   2 Muster  · 0 gemeistert · 8× falsch · 11× richtig   ← schwach
Plural          ███████░░░  67%   1 Muster  · 0 gemeistert · 1× falsch · 3× richtig

Ursache: Präpositionen · 5 von 15 Fehlern der letzten 30 Tage · 4 verwandte Muster
  → sich freuen auf + Akkusativ
  → warten auf + Akkusativ
  → sich interessieren für + Akkusativ
  → Angst haben vor + Dativ
```

The tutor reads it for you, in the language you chose:

> **Biggest root cause: verbs with fixed prepositions.** Four related patterns (*sich freuen auf, warten auf, sich interessieren für, Angst haben vor*) produce another 5 of those 15 mistakes. The issue is remembering which preposition and case each verb takes, so it is worth practising them as a family.

Both excerpts are shortened from the recorded session; the tutor's words are unchanged.

## The engine keeps the tutor honest

Language models are generous graders. Here the model teaches, and a small local program keeps the books. It decides what is due and what counts, and it refuses shortcuts. These are its actual replies:

```text
A review before its due date
→ This pattern is not due; use coach for practice without advancing the schedule

An answer you have written before
→ This answer was already seen; test transfer with a new sentence

The same exercise a second time
→ This review prompt was already used; ask a new situation

A pass, although you needed a hint
→ A hinted answer cannot pass; use hard or coach
```

A pattern is mastered after six passed reviews. A failed review sends it back to the first step. If the tutor got it wrong, “That wasn't a mistake” undoes the correction and restores the schedule. The same rules apply to every card the companion saves.

## What you can do

| Say this | What happens |
| --- | --- |
| “Correct my German: *Gestern ich habe mit mein Chef gesprochen.*” | Minimal corrections, with related mistakes grouped by their root cause. |
| “Give me a hint.” | You repair the sentence; the tutor remembers the help you needed. |
| “Let's review.” | Due patterns return in fresh situations. Copying the old answer cannot advance mastery. |
| “I have a meeting tomorrow.” | A roleplay can use your goal and a pattern you are practising. |
| “I have a German job interview on Friday.” | A saved three-step preparation plan, adapted across scenes and chats to your actual answers, help used, and recorded mistakes. |
| “Continue my interview preparation.” | Resume the current scene, unfinished assessment, or next communication task. |
| “Let's practise words.” | Vocabulary from your scenes returns in spaced reviews. |
| “How am I doing?” | Your recorded progress, with the sentences behind it. Ask for a visual view to get an offline, interactive learning story. |
| “That wasn't a mistake.” | The tutor can undo the correction and restore its schedule. |
| `/nochmal`, `/fehlerdna`, `/szene` | With the [companion](#new-practise-while-claude-works): a card, your FehlerDNA, the running scene. |

During a roleplay, ordinary corrections wait until the debrief. Start with “Restoranda konuşalım” or “Roleplay Restaurant”; finish with “bitir” or “stop roleplay”. The reply includes up to three corrections and useful vocabulary:

```text
Kellner: Guten Abend. Haben Sie reserviert?
You:     Ja, für zwei Personen, auf den Namen Alex.
Kellner: Wunderbar. Ein Tisch am Fenster. Möchten Sie schon etwas trinken?
```

There are fifteen roleplay frames, including interviews, presentations, train travel, hotels, a public office, phone appointments, shopping, school, and customer service. [Example requests for every frame](docs/practice.md#more-roleplay-situations) · [Continuing preparation for a real event](docs/missions.md).

[Your first minute, roleplays, and more examples](docs/practice.md).

## One mistake over time

<table>
<tr>
<td width="330"><img src="demo/conversation.gif" width="300" alt="Real Claude Code conversation excerpts: a learner writes mit mein Chef, receives a hint, repairs it to mit meinem Chef, and opens a fresh chat where the tutor recalls the same hint from saved memory."></td>
<td><b>The first day: a hint, not the answer.</b><br>You repair the sentence yourself. A new chat remembers the hint that helped.<br><br>Actual Claude Code replies. <a href="demo/conversation.md">Full conversation</a> · <a href="demo/conversation.png">Static view</a></td>
</tr>
<tr>
<td width="330"><img src="demo/learning-loop.gif" width="300" alt="Yesterday, Ich spreche mit meinem Chef needed a hint; today, Wir haben mit unseren Kunden gesprochen is produced without help. The replay then shows the original mistake and self-repair."></td>
<td><b>The next day: a new sentence, without help.</b><br>Yesterday you needed the hint. Today the same pattern works in a sentence you have never written.<br><br>Scripted learner, real engine. <a href="demo/learning-loop.png">Static view</a></td>
</tr>
<tr>
<td width="330"><img src="demo/history.gif" width="300" alt="An old mistake returns after 103 days. DeutschLoop still has the first sentence, its correction, and the hint that helped, ready for renewed practice."></td>
<td><b>103 days later: the mistake returns.</b><br>Your first sentence, its correction, and the hint that helped are still there.<br><br>Scripted learner, real engine. <a href="demo/history.png">Static view</a></td>
</tr>
</table>

## Goal-preparation demo

Open **[demo/missions.html](demo/missions.html)** in your browser after cloning or downloading the repository. This is the **Real-life goals** demo: it follows a Friday job interview across scenes, from a hinted introduction to difficult questions and an unexpected follow-up shaped by the previous answer.

<p align="center">
<a href="demo/missions.png"><img src="demo/missions.png" width="820" alt="The Real-life goals demo, with its selected navigation tab and A real goal, A plan that remembers heading. Alex's Friday interview plan has two of three communication-practice steps completed. The next follow-up carries the previous saved answer and its weil word-order error."></a>
</p>

**Preparation that carries over.** Two communication tasks are complete; the next scene receives the previous answer and its recorded error. Screenshot of the demo with a scripted learner and scripted assessments, backed by real engine snapshots.

## Explore your learning story

Open **[demo/index.html](demo/index.html)** for the separate **Pattern memory** demo. Choose a pattern to see its first mistake, the hint that helped, and a later unaided sentence. Move between four days to watch a mistake return with its memory intact. Search sentences, filter grammar families, or open the saved timeline.

Both demos are self-contained offline HTML files: no installation, account, API key, or server is needed to open them. Both include fifteen roleplay frames with example situations and opening lines. Alex's messages are scripted; each day's counts, schedules, and learning milestones are captured from the real engine before later events happen. GitHub's file viewer shows HTML source; download the files to interact with the example histories.

For your own saved learning history:

```bash
python scripts/deutsch_loop.py dashboard --output my-progress.html
```

Open the resulting file in your browser. It contains your exported sentences, stays offline, and leaves your learning records and review schedule unchanged. Export again to refresh it; replacing an existing HTML file requires `--force`. [Dashboard guide](docs/dashboard.md).

## How it works

```mermaid
flowchart LR
    you(["You"]) -- "German" --> agent["Claude Code or Codex<br/>teaches and judges the language"]
    agent -- "record · grade · coach · recap" --> engine["deutsch_loop.py<br/>schedules, counts, refuses shortcuts"]
    engine -- "board, due patterns, evidence" --> agent
    engine <--> state[("~/.deutschloop<br/>plain JSON")]
    you -. "/nochmal · /fehlerdna · Hilfe" .-> companion["Nochmal companion<br/>status line, cards, panes"]
    companion -- "recap · due · grade" --> engine
```

- **The skill** is [`SKILL.md`](SKILL.md) and eight [references](references): how to correct minimally, when to give a hint instead of the answer, how to continue real-life preparation, and what may be claimed about progress.
- **The engine** is one Python file with no dependencies, plus a bundled scenario catalog and dashboard template. It stores patterns and preparation plans, schedules reviews, remembers helpful cues, supports undo, and exports an offline dashboard. 190 tests run on Linux, macOS, and Windows.
- **The companion** is an optional Claude Code plugin in [`mods/nochmal`](mods/nochmal). It drives the same CLI, never edits the memory files, and has 15 tests of its own. [Companion guide](docs/companion.md).
- **The catalog** names [about a hundred root causes](references/patterns.md) of typical mistakes, so that *mit mein Chef* and *mit meine Schwester* count as one problem and not two.
- **Nothing else.** No account, server, or telemetry. Your messages go to the model you already use, as in any other chat there. Only the memory is new, and it is a folder of JSON files.

## Try the engine

From the cloned skill folder, without an agent:

```bash
python scripts/demo.py --learning-loop
```

This uses a fresh demo directory. For the four-month story, run `python scripts/demo.py`; for the restaurant scene, add `--speak`.

[CLI guide](docs/cli.md) · [Command contract](references/cli-contract.md) · [Tests, recording, and image generation](docs/development.md)

## About the demos

Learner messages are scripted so that every demo can be reproduced. The opening image and the first-day story show actual Claude Code replies. They were recorded under the project's old name, DeutschDNA, and only the name was changed afterwards; the board in the opening image now reads FehlerDNA. Boards, dates, counts, and histories come from the engine. The four-month history is seeded through the engine by `scripts/demo.py`; nobody waited four months for it.

In the companion section, the FehlerDNA rows and the pattern story are real engine output for that scripted learner, with due times from the day they were rendered. The card, the status line, and the scene pane show the companion's layouts with example text, as does the short restaurant exchange; the Hilfe hint is the tutor's reply from a real session.

The first example and teaching milestones survive the rolling history limits. Progress scores describe tracked patterns, not overall German proficiency. Text practice works directly; microphone capture and pronunciation scoring are not included.

## Contributing

The easiest place to help is the [pattern catalog](references/patterns.md). It has notes on typical mistakes for speakers of Turkish and English. If your first language leads to a German mistake that is missing, open an issue with two example sentences.

## Roadmap

- Available: the Claude Code companion, with a status line, cards while Claude works, and live FehlerDNA and scene panes.
- Available: three-step preparation for real-life goals across scenes and chats, with fifteen roleplay frames.
- Available: an offline local dashboard and an interactive example history.
- Planned: Goethe B1/B2, telc B1/B2, and telc Deutsch Beruf exam modes.
- Exploring: voice practice and pronunciation fingerprint.

## License

[MIT](LICENSE)
````

## File: scripts/dashboard.html
size: 49613
sha: 0d38a66c8d861077bd4417751c3acbe4f8e47582
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/dashboard.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/dashboard.html

## File: scripts/demo.py
size: 31808
sha: 1dcd6733c0a8106802968deb0b8244d145f0748f
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/demo.py

```text
#!/usr/bin/env python3
"""Replay a four-month learner story through the real DeutschLoop engine.

The story only scripts what the learner wrote and how each review went. When a
review happens is decided by the engine's own schedule, and every number in the
output is computed from the stored events. Nothing on screen is hard-coded.
"""

from __future__ import annotations

import argparse
import re
import sys
import tempfile
from datetime import datetime, timedelta
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import deutsch_loop as dna  # noqa: E402

STORY_DAYS = 120
TICK = timedelta(minutes=3)

PATTERNS = {
    "mit": ("case", "mit + dative", "mit always governs the dative"),
    "warten": ("preposition", "warten auf + accusative", "warten takes auf + accusative"),
    "ung": ("article", "-ung nouns are feminine", "Nouns ending in -ung are feminine"),
    "interessieren": ("preposition", "sich interessieren für + accusative", "sich interessieren takes für + accusative"),
    "obwohl": ("word-order", "obwohl sends finite verb to end", "In an obwohl clause the finite verb goes last"),
    "helfen": ("case", "helfen + dative", "helfen takes a dative object"),
    "hund": ("case", "masculine accusative -en", "A masculine direct object needs -en: einen, keinen, meinen, den"),
    "freuen": ("preposition", "sich freuen auf + accusative", "sich freuen auf for something ahead, über for something here"),
    "adj": ("agreement", "adjective ending after ein-word", "After ein, kein, mein the adjective shows the gender: ein wichtiger Termin"),
    "personen": ("plural", "Person plural is Personen", "die Person, die Personen"),
    "anrufen": ("case", "anrufen + accusative", "anrufen takes an accusative object: Ich rufe dich an"),
    "adjdef": ("agreement", "adjective ending after der-word", "After der, die, das the adjective ends in -e or -en: den neuen Film"),
    "angst": ("preposition", "Angst haben vor + dative", "Angst haben takes vor + dative"),
    "weil": ("word-order", "weil sends finite verb to end", "In a weil clause the finite verb goes last"),
}

# What the learner wrote and its minimal correction: (days ago, pattern, sentence, correction).
WRITING = [
    (120, "mit", "Ich spreche mit mein Chef.", "Ich spreche mit meinem Chef."),
    (120, "warten", "Ich warte dich.", "Ich warte auf dich."),
    (118, "ung", "Ich habe ein Reservierung für zwei Personen.", "Ich habe eine Reservierung für zwei Personen."),
    (100, "interessieren", "Ich interessiere mich an Fußball.", "Ich interessiere mich für Fußball."),
    (80, "obwohl", "Obwohl ich bin müde, arbeite ich weiter.", "Obwohl ich müde bin, arbeite ich weiter."),
    (80, "helfen", "Ich helfe meinen Bruder.", "Ich helfe meinem Bruder."),
    (45, "hund", "Ich habe ein Hund.", "Ich habe einen Hund."),
    (45, "freuen", "Ich freue mich über das Wochenende.", "Ich freue mich auf das Wochenende."),
    (45, "adj", "Ich habe einen neue Job.", "Ich habe einen neuen Job."),
    (20, "interessieren", "Ich interessiere mich an Geschichte.", "Ich interessiere mich für Geschichte."),
    (15, "anrufen", "Ich rufe dir morgen an.", "Ich rufe dich morgen an."),
    (14, "personen", "Wir sind vier Person.", "Wir sind vier Personen."),
    (12, "freuen", "Ich freue mich über meinen Urlaub nächste Woche.", "Ich freue mich auf meinen Urlaub nächste Woche."),
    (10, "adjdef", "Ich mag den neue Film.", "Ich mag den neuen Film."),
    (4, "angst", "Ich habe Angst von Hunden.", "Ich habe Angst vor Hunden."),
    (2, "weil", "Ich bleibe zu Hause, weil ich bin krank.", "Ich bleibe zu Hause, weil ich krank bin."),
    (0, "warten", "Ich warte meine Freundin.", "Ich warte auf meine Freundin."),
    (0, "weil", "Ich nehme den Bus, weil es regnet stark.", "Ich nehme den Bus, weil es stark regnet."),
]

# How each review went, in order: ("pass", answer), ("hard", answer), ("fail", answer, correction).
# Reviews beyond the end of a list pass. Every review uses a new sentence.
REVIEWS = {
    "mit": [
        ("pass", "Ich arbeite mit meinem Kollegen."),
        ("pass", "Ich fahre mit dem Bus zur Arbeit."),
        ("pass", "Ich telefoniere mit meiner Mutter."),
        ("pass", "Wir essen mit unseren Nachbarn."),
        ("pass", "Ich spreche mit einem Kunden."),
        ("pass", "Ich bin mit dem Projekt zufrieden."),
    ],
    "warten": [
        ("pass", "Ich warte auf meinen Bruder."),
        ("fail", "Ich warte den Zug.", "Ich warte auf den Zug."),
        ("pass", "Wir warten auf das Paket."),
        ("hard", "Ich warte auf deine Antwort."),
        ("pass", "Sie wartet auf ihren Termin."),
        ("fail", "Wir warten den Bus.", "Wir warten auf den Bus."),
        ("pass", "Ich warte auf eine E-Mail."),
        ("pass", "Warte bitte auf mich!"),
        ("pass", "Er wartet auf den Arzt."),
        ("pass", "Wie lange wartest du schon auf mich?"),
        ("pass", "Wir warten auf besseres Wetter."),
    ],
    "helfen": [("pass", None), ("fail", "Ich helfe dich gern.", "Ich helfe dir gern.")],
    "freuen": [("pass", None)] * 5
    + [("fail", "Ich freue mich über die Party am Samstag.", "Ich freue mich auf die Party am Samstag.")],
    "adj": [
        ("pass", None),
        ("fail", "mit meinem neue Kollegen", "mit meinem neuen Kollegen"),
        ("pass", None),
        ("fail", "ein interessante Buch", "ein interessantes Buch"),
        ("pass", None),
        ("pass", None),
        ("fail", "Ich trinke einen kalte Kaffee.", "Ich trinke einen kalten Kaffee."),
        ("pass", None),
        ("pass", None),
        ("pass", None),
        ("fail", "Das ist ein wichtige Termin.", "Das ist ein wichtiger Termin."),
    ],
    "adjdef": [
        ("fail", "die neue Filme", "die neuen Filme"),
        ("pass", None),
        ("fail", "mit dem neue Auto", "mit dem neuen Auto"),
    ],
    "anrufen": [("pass", None), ("fail", "Ruf mir bitte an.", "Ruf mich bitte an.")],
}

# Correct, unprompted uses of tracked patterns in later writing.
OBSERVATIONS = [
    (6, "hund", "Wir haben einen Hund und eine Katze."),
    (4, "helfen", "Ich helfe dir gern beim Umzug."),
    (1, "mit", "mit unseren Kunden"),
]
ROLEPLAYS = [(2, "restaurant", 8, timedelta(minutes=6, seconds=42))]

# These tasks are story inputs, just like the learner's answers. The engine still
# decides when each may be graded and refuses copied prompts or answers.
REVIEW_PROMPTS = {
    "Ich arbeite mit meinem Kollegen.": "Dein Kollege und du erledigen das Projekt gemeinsam. Mit wem arbeitest du?",
    "Ich fahre mit dem Bus zur Arbeit.": "Dein Verkehrsmittel zur Arbeit ist der Bus. Wie kommst du hin?",
    "Ich telefoniere mit meiner Mutter.": "Deine Mutter ist am Telefon. Mit wem telefonierst du?",
    "Wir essen mit unseren Nachbarn.": "Eure Nachbarn kommen zum Abendessen. Mit wem esst ihr?",
    "Ich spreche mit einem Kunden.": "Ein Kunde ist bei dir im Büro. Mit wem sprichst du?",
    "Ich bin mit dem Projekt zufrieden.": "Das Projekt ist gut gelungen. Womit bist du zufrieden?",
    "Ich warte auf meinen Bruder.": "Dein Bruder verspätet sich. Auf wen wartest du?",
    "Ich warte den Zug.": "Der Zug kommt erst später. Sage mit warten, warum du noch am Bahnhof bist.",
    "Wir warten auf das Paket.": "Das Paket ist noch nicht da. Worauf wartet ihr?",
    "Ich warte auf deine Antwort.": "Deine Freundin hat noch nicht geantwortet. Worauf wartest du?",
    "Sie wartet auf ihren Termin.": "Eine Frau sitzt vor dem Sprechzimmer. Ihr Termin beginnt später. Was macht sie?",
    "Wir warten den Bus.": "Euer Bus verspätet sich. Sagt mit warten, was ihr gerade macht.",
    "Ich warte auf eine E-Mail.": "Du erwartest eine E-Mail. Worauf wartest du gerade?",
    "Warte bitte auf mich!": "Dein Freund läuft zu schnell. Bitte ihn mit warten, bei dir zu bleiben.",
    "Er wartet auf den Arzt.": "Der Arzt fehlt noch. Was macht der Patient im Wartezimmer?",
    "Wie lange wartest du schon auf mich?": "Du kommst zu spät. Frage, seit wann dein Freund auf dich wartet.",
    "Wir warten auf besseres Wetter.": "Ihr wollt erst bei besserem Wetter losfahren. Worauf wartet ihr?",
    "Ich helfe dich gern.": "Dein Freund bittet dich um Hilfe. Biete ihm mit helfen deine Unterstützung an.",
    "Ich freue mich über die Party am Samstag.": "Die Party findet erst am Samstag statt. Drücke deine Vorfreude aus.",
    "mit meinem neue Kollegen": "Du triffst einen neuen Kollegen. Mit wem sprichst du?",
    "ein interessante Buch": "Du liest ein Buch und findest es interessant. Beschreibe das Buch mit ein.",
    "Ich trinke einen kalte Kaffee.": "Dein Kaffee ist kalt. Beschreibe mit trinken, was du trinkst.",
    "Das ist ein wichtige Termin.": "Du zeigst auf einen Termin im Kalender. Sage, dass er wichtig ist.",
    "die neue Filme": "Im Kino laufen mehrere neue Filme. Benenne sie mit dem bestimmten Artikel.",
    "mit dem neue Auto": "Das Auto ist neu. Sage, womit du heute fährst.",
    "Ruf mir bitte an.": "Du möchtest später einen Anruf erhalten. Bitte deinen Freund darum.",
}

# Reviews without a scripted answer take the next task here. Each one is a different
# situation and sentence frame, the way the skill asks for reviews: swapping one noun
# in the same sentence would test recall of that sentence, not transfer.
FRESH_TASKS = {
    "mit": [
        ("Du fährst in den Urlaub. Wer kommt mit?", "Ich fahre mit meiner Familie in den Urlaub."),
        ("Womit schreibst du deine Notizen?", "Meine Notizen schreibe ich mit einem Bleistift."),
        ("Wie bezahlst du im Restaurant?", "Im Restaurant bezahle ich meistens mit der Karte."),
        ("Mit wem gehst du am Samstag ins Kino?", "Am Samstag gehe ich mit zwei Kolleginnen ins Kino."),
        ("Womit kommst du bei Schnee zur Arbeit?", "Bei Schnee komme ich mit der Straßenbahn."),
        ("Mit wem hast du über die Gehaltserhöhung gesprochen?", "Darüber habe ich mit der Personalabteilung gesprochen."),
        ("Womit putzt du die Fenster?", "Die Fenster putze ich mit einem alten Tuch."),
        ("Mit wem feierst du Silvester?", "Silvester feiern wir mit unseren Freunden aus Köln."),
    ],
    "warten": [
        ("Die Ampel ist rot. Was machen die Fußgänger?", "Die Fußgänger warten auf das grüne Licht."),
        ("Du hast eine Bewerbung geschickt. Worauf wartest du jetzt?", "Jetzt warte ich auf eine Antwort der Firma."),
        ("Im Restaurant ist es voll. Was macht ihr?", "Wir warten an der Bar auf einen freien Tisch."),
        ("Deine Tochter hat gleich Schulschluss. Wo bist du?", "Ich stehe vor der Schule und warte auf meine Tochter."),
        ("Warum stehst du am Fenster?", "Ich schaue raus, weil ich auf den Postboten warte."),
        ("Das Paket kommt heute. Was fragst du deinen Mitbewohner?", "Kannst du heute auf das Paket warten?"),
        ("Der Film beginnt erst um acht. Was macht ihr im Kino?", "Im Foyer warten wir auf den Beginn des Films."),
        ("Wann kommt endlich der Techniker?", "Wir warten schon seit Montag auf den Techniker."),
    ],
    "ung": [
        ("Du hast eine Wohnung gefunden. Wie ist sie?", "Die Wohnung ist hell und ruhig."),
        ("Was lag heute in deinem Briefkasten?", "Heute lag eine Einladung zur Hochzeit im Briefkasten."),
        ("Wie war das Meeting?", "Die Besprechung hat viel zu lange gedauert."),
        ("Warum bist du so nervös?", "Morgen schreibe ich eine wichtige Prüfung."),
        ("Was fehlt noch für die Reise?", "Für die Reise brauche ich noch eine Versicherung."),
        ("Was sagt dein Chef zu deinem Vorschlag?", "Er findet, dass die Lösung zu teuer ist."),
        ("Wo genau liegt das Hotel?", "Das Hotel liegt direkt an der Kreuzung."),
        ("Was hat die Ärztin dir gegeben?", "Sie hat mir eine Überweisung zum Facharzt gegeben."),
    ],
    "interessieren": [
        ("Was liest du in der Zeitung zuerst?", "Ich interessiere mich vor allem für den Sportteil."),
        ("Deine Schwester studiert Biologie. Warum?", "Sie interessiert sich schon lange für Tiere."),
        ("Frag deinen neuen Kollegen nach seinen Hobbys.", "Wofür interessierst du dich in deiner Freizeit?"),
        ("Warum hast du den Vortrag besucht?", "Weil ich mich für künstliche Intelligenz interessiere."),
        ("Was fragt die Personalerin im Gespräch?", "Sie fragt, ob ich mich für eine Stelle im Vertrieb interessiere."),
        ("Deine Kinder schauen jeden Abend Nachrichten. Warum?", "Meine Kinder interessieren sich sehr für Politik."),
        ("Warum wart ihr auf der Automesse?", "Mein Mann und ich interessieren uns für ein neues Auto."),
        ("Spielst du Tennis?", "Nein, für Tennis interessiere ich mich überhaupt nicht."),
    ],
    "obwohl": [
        ("Es regnet, aber du gehst joggen. Sag es mit obwohl.", "Obwohl es regnet, gehe ich joggen."),
        ("Dein Kollege ist krank und kommt trotzdem ins Büro.", "Er kommt ins Büro, obwohl er krank ist."),
        ("Du hast wenig Geld und kaufst doch ein Konzertticket.", "Obwohl ich wenig Geld habe, kaufe ich das Ticket."),
        ("Die Wohnung ist teuer. Ihr nehmt sie trotzdem.", "Wir nehmen die Wohnung, obwohl sie teuer ist."),
        ("Du hast lange gelernt und die Prüfung trotzdem nicht bestanden.", "Obwohl ich lange gelernt habe, habe ich nicht bestanden."),
        ("Es wird dunkel, aber deine Tochter spielt draußen weiter.", "Sie spielt draußen weiter, obwohl es schon dunkel wird."),
        ("Der Zug hatte Verspätung, aber du warst pünktlich.", "Obwohl der Zug Verspätung hatte, war ich pünktlich."),
        ("Du verstehst den Film nicht ganz, aber er gefällt dir.", "Der Film gefällt mir, obwohl ich nicht alles verstehe."),
    ],
    "helfen": [
        ("Deine Nachbarin trägt schwere Einkaufstüten. Was fragst du sie?", "Darf ich Ihnen mit den Tüten helfen?"),
        ("Dein Kollege versteht das neue Programm nicht. Was machst du?", "Ich zeige es ihm und helfe ihm bei den ersten Schritten."),
        ("Deine kleine Schwester hat Hausaufgaben. Wer unterstützt sie?", "Mein Vater hilft ihr jeden Abend dabei."),
        ("Ein Tourist sucht den Bahnhof. Wie reagierst du?", "Ich helfe dem Touristen und zeige ihm den Weg."),
        ("Deine Freunde ziehen um. Was machst du am Samstag?", "Am Samstag helfen wir unseren Freunden beim Umzug."),
        ("Deine Oma kommt mit dem Handy nicht klar. Was sagst du?", "Oma, soll ich dir mit dem Handy helfen?"),
        ("Wer hat dir bei der Bewerbung geholfen?", "Meine Lehrerin hat mir bei der Bewerbung sehr geholfen."),
        ("Der Ball der Kinder hängt im Baum. Was tust du?", "Ich helfe den Kindern und hole den Ball herunter."),
    ],
    "hund": [
        ("Was hast du zum Geburtstag bekommen?", "Ich habe einen neuen Rucksack bekommen."),
        ("Was brauchst du noch für die Suppe?", "Ich brauche noch einen großen Topf."),
        ("Was siehst du im Garten?", "Im Baum sehe ich einen kleinen Vogel."),
        ("Wen triffst du heute Abend?", "Heute Abend treffe ich meinen Bruder zum Essen."),
        ("Was bestellst du im Café?", "Für mich einen Cappuccino, bitte."),
        ("Fährst du selbst zur Arbeit?", "Nein, ich habe keinen Führerschein."),
        ("Was sucht ihr im Möbelhaus?", "Wir suchen einen Esstisch für sechs Leute."),
        ("Wen hast du auf der Party kennengelernt?", "Auf der Party habe ich einen Kollegen von Anna kennengelernt."),
    ],
    "freuen": [
        ("Nächste Woche beginnt dein Urlaub. Wie fühlst du dich?", "Ich freue mich schon sehr auf die freien Tage."),
        ("Deine Freundin kommt am Freitag zu Besuch. Was schreibst du ihr?", "Ich freue mich auf deinen Besuch!"),
        ("Die Kinder haben bald Ferien. Wie sind sie?", "Die Kinder freuen sich riesig auf die Ferien."),
        ("Worauf freust du dich am Wochenende?", "Am Wochenende freue ich mich aufs Ausschlafen."),
        ("Nächsten Monat fängt ein neuer Kollege an. Was sagt das Team?", "Wir freuen uns auf die Zusammenarbeit."),
        ("Morgen spielt deine Lieblingsband in der Stadt.", "Morgen ist das Konzert, darauf freue ich mich total."),
        ("Frag deine Nachbarin nach ihren Plänen für den Sommer.", "Worauf freuen Sie sich im Sommer am meisten?"),
        ("Bald ist Weihnachten. Was ist mit deinem Sohn?", "Er freut sich schon wochenlang auf die Geschenke."),
    ],
    "adj": [
        ("Beschreibe dein neues Handy.", "Es ist ein neues Modell mit einer guten Kamera."),
        ("Wie ist das Wetter heute?", "Heute ist ein schöner, sonniger Tag."),
        ("Was suchst du auf dem Wohnungsmarkt?", "Ich suche eine kleine Wohnung mit einem großen Balkon."),
        ("Wie findest du den neuen Kollegen?", "Er ist ein sehr freundlicher Mensch."),
        ("Was hast du deiner Mutter geschenkt?", "Ich habe ihr einen warmen Schal geschenkt."),
        ("Was für ein Auto fährst du?", "Ich fahre einen alten roten Golf."),
        ("Was trinkst du am Morgen?", "Morgens brauche ich einen starken Tee."),
        ("In was für einer Gegend wohnst du?", "Ich wohne in einem ruhigen Viertel am Stadtrand."),
    ],
    "personen": [
        ("Du reservierst einen Tisch. Für wie viele?", "Für vier Personen, bitte."),
        ("Wie viele Leute passen in den Aufzug?", "In den Aufzug passen höchstens acht Personen."),
        ("Wie viele Gäste kommen zur Feier?", "Zur Feier kommen ungefähr zwanzig Personen."),
        ("Wer war beim Meeting?", "Beim Meeting waren nur drei Personen."),
        ("Wie groß ist das Ferienhaus?", "Das Ferienhaus hat Platz für sechs Personen."),
        ("Ist die Schlange an der Kasse lang?", "Nein, vor mir stehen nur zwei Personen."),
        ("Wie groß ist dein Team?", "In meinem Team arbeiten zehn Personen."),
        ("Wie viele Tickets kaufst du?", "Ich kaufe Tickets für fünf Personen."),
    ],
    "anrufen": [
        ("Deine Mutter hat heute Geburtstag.", "Ich rufe meine Mutter gleich nach dem Frühstück an."),
        ("Die Praxis hat angerufen, als du nicht da warst.", "Ich rufe die Praxis morgen früh an."),
        ("Dein Freund wartet auf deinen Anruf. Was versprichst du?", "Ich rufe dich heute Abend an."),
        ("Die Heizung ist kaputt. Wen kontaktierst du?", "Ich rufe sofort den Vermieter an."),
        ("Ruft dein Chef dich oft an?", "Ja, er ruft mich fast jeden Tag an."),
        ("Du bist krank und kannst nicht arbeiten.", "Zuerst rufe ich meine Chefin an."),
        ("Deine Kollegin hat eine Frage zum Projekt.", "Ruf mich doch kurz an, dann erkläre ich es dir."),
        ("Wen hast du gestern angerufen?", "Gestern habe ich meine Großeltern angerufen."),
    ],
    "adjdef": [
        ("Welche Jacke nimmst du, die blaue oder die schwarze?", "Ich nehme die blaue Jacke."),
        ("Welchen Film habt ihr gestern gesehen?", "Wir haben den französischen Film im Kino gesehen."),
        ("Wem gehört das rote Fahrrad?", "Das rote Fahrrad gehört meinem Bruder."),
        ("In welchem Hotel übernachtet ihr?", "Wir übernachten in dem kleinen Hotel am See."),
        ("Mit welchem Zug fährst du?", "Ich fahre mit dem frühen Zug um sechs."),
        ("Welche Schuhe passen zum Anzug?", "Die schwarzen Schuhe passen am besten."),
        ("Welcher Vorschlag gefällt dir?", "Der letzte Vorschlag gefällt mir besser."),
        ("Wo steht die Vase?", "Die Vase steht auf dem alten Tisch im Flur."),
    ],
    "angst": [
        ("Warum fliegst du nicht gern?", "Beim Fliegen habe ich immer Angst vor Turbulenzen."),
        ("Warum ist dein Sohn nachts wach?", "Er hat Angst vor der Dunkelheit."),
        ("Warum bist du vor der Präsentation nervös?", "Ich habe ein bisschen Angst vor dem Publikum."),
        ("Warum tragen Wanderer im Sommer lange Hosen?", "Viele Wanderer haben Angst vor Zecken."),
        ("Was macht dir an der neuen Stelle Sorgen?", "Ehrlich gesagt habe ich Angst vor den vielen Überstunden."),
        ("Warum geht deine Oma im Winter nicht allein raus?", "Sie hat Angst vor dem Glatteis."),
        ("Warum sagst du deinem Chef nichts?", "Ich habe Angst vor seiner Reaktion."),
        ("Wovor hat deine Katze Angst?", "Meine Katze hat Angst vor dem Staubsauger."),
    ],
    "weil": [
        ("Warum trinkst du so viel Kaffee?", "Ich trinke viel Kaffee, weil ich nachts schlecht schlafe."),
        ("Warum lernst du Deutsch?", "Weil ich in Deutschland arbeiten möchte."),
        ("Warum kommst du heute später?", "Ich komme später, weil mein Zug ausgefallen ist."),
        ("Warum ist das Restaurant geschlossen?", "Es ist geschlossen, weil heute Feiertag ist."),
        ("Warum nimmst du einen Regenschirm mit?", "Weil es am Nachmittag regnen soll."),
        ("Warum sucht ihr eine neue Wohnung?", "Wir ziehen um, weil unsere Wohnung zu klein ist."),
        ("Warum rufst du den Vermieter an?", "Ich rufe ihn an, weil die Heizung nicht funktioniert."),
        ("Warum bist du so gut gelaunt?", "Ich bin gut gelaunt, weil ich die Prüfung bestanden habe."),
    ],
}

def fallback_tasks(key: str) -> list[tuple[str, str]]:
    if key not in FRESH_TASKS:
        raise ValueError(f"No demo exercises for {key}")
    return FRESH_TASKS[key]

class Clock:
    """Hands out increasing moments inside one story day."""

    def __init__(self, day_start: datetime):
        self.moment = day_start

    def next(self) -> datetime:
        current = self.moment
        self.moment += TICK
        return current

def seed_learning_loop(home: Path) -> None:
    """A scripted first win and next-day transfer, with all evidence stored by the CLI engine."""
    store = dna.StateStore(home)
    today = dna.utc_now() - timedelta(minutes=1)
    # Keep every first-session attempt on the previous local day, even when
    # this demo is rendered just before midnight.
    yesterday = dna.to_local(today).replace(hour=9, minute=0, second=0, microsecond=0) - timedelta(days=1)
    store.init_profile(name="Alex", level="B2", native_language="tr",
                       goal="Im Gespräch mit Kunden sicherer werden", at=yesterday)
    mistake, _, _ = store.record(original="Ich spreche mit mein Chef.", corrected="Ich spreche mit meinem Chef.",
                                 category="case", pattern="mit + dative", rule="mit verlangt den Dativ", at=yesterday)
    store.coach(mistake["id"], outcome="assisted", prompt="Schau noch einmal auf mit mein Chef.",
                answer="Ich spreche mit meinem Chef.", strategy="Kasusfrage", hint="Frage dich: mit wem?",
                at=yesterday + timedelta(minutes=5))
    store.coach(mistake["id"], outcome="independent", prompt="Dein Verkehrsmittel ist der Bus. Wie kommst du zur Arbeit?",
                answer="Ich fahre mit dem Bus.", at=yesterday + timedelta(minutes=8))
    store.observe([mistake["id"]], context="Wir haben mit unseren Kunden gesprochen.", at=today)

def seed(home: Path) -> None:
    store = dna.StateStore(home)
    anchor = dna.utc_now() - timedelta(hours=1)
    ids: dict[str, str] = {}
    keys_by_id: dict[str, str] = {}
    queues = {key: list(outcomes) for key, outcomes in REVIEWS.items()}
    tasks = {key: iter(fallback_tasks(key)) for key in PATTERNS}
    store.init_profile(name="Alex", level="B2", native_language="tr", at=anchor - timedelta(days=STORY_DAYS, minutes=10))

    for days_ago in range(STORY_DAYS, -1, -1):
        day_start = anchor - timedelta(days=days_ago)
        clock = Clock(day_start)
        # Morning: whatever the engine says is due. Nothing is reviewed on the last day,
        # so the demo ends with reviews waiting, exactly as a learner would find it.
        if days_ago > 0:
            for mistake in store.due(at=day_start + timedelta(hours=1), limit=100):
                key = keys_by_id[mistake["id"]]
                outcome = queues[key].pop(0) if queues.get(key) else ("pass", None)
                answer = outcome[1]
                if answer is None:
                    prompt, answer = next(tasks[key])
                else:
                    prompt = REVIEW_PROMPTS[answer]
                review_at = max(clock.next(), dna.parse_moment(mistake["next_review"]))
                clock.moment = review_at + TICK
                if outcome[0] == "fail":
                    store.grade(mistake["id"], result="fail", prompt=prompt, answer=answer, correction=outcome[2], at=review_at)
                else:
                    help_used = {"strategy": "Verb mit Präposition", "hint": "Das Verb heißt warten auf."} if outcome[0] == "hard" else {}
                    store.grade(mistake["id"], result=outcome[0], prompt=prompt, answer=answer, at=review_at, **help_used)
        for day, key, original, corrected in WRITING:
            if day != days_ago:
                continue
            category, pattern, rule = PATTERNS[key]
            mistake, _, _ = store.record(
                original=original,
                corrected=corrected,
                category=category,
                pattern=pattern,
                rule=rule,
                at=clock.next(),
            )
            ids[key] = mistake["id"]
            keys_by_id[mistake["id"]] = key
        for day, key, context in OBSERVATIONS:
            if day == days_ago:
                store.observe([ids[key]], context=context, at=clock.next())
        for day, scenario, turns, duration in ROLEPLAYS:
            if day == days_ago:
                started_at = clock.next()
                started = store.roleplay_start(scenario, at=started_at)
                store.roleplay_finish(
                    started["session"]["id"],
                    turns=turns,
                    notes="Reservation, order, one complaint, payment.",
                    at=started_at + duration,
                )

def seed_speaking_scene(home: Path) -> str:
    """Scripted restaurant exchange; duration, corrections and recurrence counts come from stored events."""
    store = dna.StateStore(home)
    started_at = dna.utc_now() - timedelta(minutes=10)
    store.init_profile(name="Alex", level="B2", explanation_language="tr", at=started_at)
    identifier = store.roleplay_start("restaurant", at=started_at)["session"]["id"]
    dialogue = [
        (0, "partner", "Guten Abend. Haben Sie reserviert?"),
        (30, "learner", "Ja, wir haben eine reservierung für zwei Person."),
        (60, "partner", "Auf welchen Namen?"),
        (85, "learner", "Die Reservierung ist auf dem Namen Sahin."),
        (120, "partner", "Ich habe die Reservierung auf den Namen Sahin gefunden. Kommen später noch Gäste dazu?"),
        (150, "learner", "Ja, noch zwei Person kommen später."),
        (180, "partner", "Möchten Sie schon Getränke bestellen?"),
        (210, "learner", "Für drei Person bitte Wasser."),
        (245, "partner", "Wie viele Personen möchten eine Vorspeise?"),
        (280, "learner", "Vier Person möchten eine Suppe."),
        (310, "partner", "Alles klar. Möchten Sie sonst noch etwas?"),
        (355, "learner", "Nein, danke. Das ist alles."),
        (402, "partner", "Sehr gern. Ich bringe gleich die Getränke."),
    ]
    turns = []
    for index, (seconds, speaker, text) in enumerate(dialogue):
        turn = store.roleplay_turn(identifier, speaker=speaker, text=text, event_id=f"demo-message-{index}",
                                    at=started_at + timedelta(seconds=seconds))["utterance"]
        turns.append(turn)
    store.roleplay_stop(identifier, at=started_at + timedelta(seconds=402))
    for turn in turns:
        if turn["speaker"] != "learner":
            continue
        original = turn["text"]
        corrected = re.sub(r"\bPerson\b", "Personen", original.replace("reservierung", "Reservierung").replace("auf dem Namen", "auf den Namen"))
        patterns = []
        if re.search(r"\bPerson\b", original):
            patterns.append(("plural", "Person plural is Personen", "Der Plural von Person ist Personen.", None))
        if "reservierung" in original:
            patterns.append(("spelling", "German nouns are capitalized", "Nomen schreibt man groß.", None))
        if "auf dem Namen" in original:
            patterns.append(("preposition", "auf den Namen for reservations", "Eine Reservierung ist auf den Namen einer Person.", "auf den Namen"))
        for category, pattern, rule, label in patterns:
            store.record(original=original, corrected=corrected, category=category, pattern=pattern, rule=rule, label=label,
                         session_id=identifier, turn_id=turn["id"])
    for term, surface, meaning, index in [
        ("reservieren", "reserviert", "rezervasyon yapmak", 0),
        ("die Reservierung", "die Reservierung", "rezervasyon", 4),
        ("auf den Namen", "auf den Namen", "… adına", 4),
    ]:
        store.roleplay_vocab(identifier, term=term, surface=surface, meaning=meaning, turn_id=turns[index]["id"])
    store.roleplay_finish(identifier, at=started_at + timedelta(minutes=8))
    return identifier

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Seed and show a DeutschLoop demo profile")
    parser.add_argument("--home", help="State directory to seed (default: a fresh temporary directory)")
    parser.add_argument("--quiet", action="store_true", help="Only seed; print nothing but the state path")
    story = parser.add_mutually_exclusive_group()
    story.add_argument("--learning-loop", action="store_true", help="Show self-repair, remembered help, and next-day unaided use")
    story.add_argument("--speak", action="store_true", help="Show an uninterrupted restaurant scene and its recorded debrief")
    arguments = parser.parse_args(argv)
    dna._configure_streams()

    home = Path(arguments.home).expanduser() if arguments.home else Path(tempfile.mkdtemp(prefix="deutschloop-demo-"))
    if any(home.glob("*.json")):
        print(f"Refusing to seed a non-empty state directory: {home}", file=sys.stderr)
        return 2
    if arguments.speak:
        scene_id = seed_speaking_scene(home)
    else:
        (seed_learning_loop if arguments.learning_loop else seed)(home)
    if arguments.quiet:
        print(str(home))
        return 0

    if arguments.speak:
        result = dna.StateStore(home).roleplay_show(scene_id)
        print("DeutschLoop speaking demo: scripted dialogue, real engine evidence.")
        print(f"State directory: {home}")
        for turn in result["session"]["utterances"]:
            speaker = "Kellner" if turn["speaker"] == "partner" else "Alex"
            print(f"{speaker}: {turn['text']}")
        print()
        print(dna.render_roleplay_text(result))
        # The scene's words now wait in the deck for their first review tomorrow.
        print()
        print("$ python scripts/deutsch_loop.py vocab-list --format text")
        dna.main(["--home", str(home), "vocab-list", "--format", "text"])
        return 0

    mit_id = dna.mistake_id("case", "mit + dative")
    warten_id = dna.mistake_id("preposition", "warten auf + accusative")
    print("DeutschLoop demo: scripted learner, real engine — "
          + ("self-repair and next-day transfer." if arguments.learning_loop else "four months of learning."))
    print(f"State directory: {home}")
    screens = (
        ["recap", "--format", "card"],
        ["summary", "--format", "text"],
        ["show", mit_id, "--format", "text"],
        ["show", warten_id, "--format", "text"],
        ["due", "--format", "text"],
    )
    if arguments.learning_loop:
        screens = (["recap", "--format", "card"], ["show", mit_id, "--format", "text"])
    for command in screens:
        print()
        print(f"$ python scripts/deutsch_loop.py {' '.join(command)}")
        dna.main(["--home", str(home), *command])
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/demo_missions.py
size: 7377
sha: 1dc9148f3f5bc4821c99cddca77bccd6108484e2
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/demo_missions.py

```text
#!/usr/bin/env python3
"""Replay continuing interview preparation with scripted answers and real mission state."""

from __future__ import annotations

import argparse
import sys
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any

import deutsch_loop as dna

START = datetime(2026, 5, 20, 9, 0, tzinfo=timezone.utc)

def mission_demo_payload(home: Path) -> dict[str, Any]:
    if home.exists() and any(home.iterdir()):
        raise dna.DeutschLoopError("The mission demo requires an empty, isolated state directory")
    store = dna.StateStore(home)
    store.init_profile(name="Alex", level="B1", explanation_language="en", at=START - timedelta(days=1))
    mit, _, _ = store.record(original="Ich spreche mit mein Chef.", corrected="Ich spreche mit meinem Chef.",
                             category="case", pattern="mit + dative", rule="mit always governs the dative.",
                             at=START - timedelta(days=1))
    mission_id = store.mission_create(goal="I have a German-language job interview on Friday.",
                                       scenario="interview", deadline="friday", at=START)["mission"]["id"]
    frames = []

    def capture(at: datetime, chapter: str, title: str, story: str) -> None:
        frame = dna.dashboard_snapshot(store, at=at)
        frame.update(chapter=chapter, title=title, story=story)
        frames.append(frame)

    def scene(at: datetime, answer: str, *, hint: bool = False, corrected: str | None = None,
              outcome: str = "achieved", note: str) -> None:
        started = store.mission_start(mission_id, at=at)
        sid = started["session"]["id"]
        store.roleplay_turn(sid, speaker="partner", text=started["contract"]["opening"], at=at)
        turn = store.roleplay_turn(sid, speaker="learner", text=answer, at=at + timedelta(minutes=1))["utterance"]
        evidence = turn
        if hint:
            store.roleplay_turn(sid, speaker="partner", text="Schau auf mit mein Team. Frage dich: mit wem?",
                                 support="hint", at=at + timedelta(minutes=2))
            evidence = store.roleplay_turn(sid, speaker="learner", text=corrected,
                                            at=at + timedelta(minutes=3))["utterance"]
        store.roleplay_stop(sid, at=at + timedelta(minutes=4))
        if corrected:
            pattern = mit if hint else None
            params = {"mistake_id": pattern["id"]} if pattern else {
                "category": "word-order", "pattern": "weil sends finite verb to end", "rule": "After weil the finite verb goes last."}
            store.record(original=answer, corrected=corrected, session_id=sid, turn_id=turn["id"], **params)
            if hint:
                store.coach(mit["id"], outcome="assisted", prompt="Schau auf mit mein Team.", answer=evidence["text"],
                            strategy="Kasusfrage", hint="Schau auf mit mein Team. Frage dich: mit wem?", at=dna.parse_moment(evidence["at"]))
        else:
            # These scripted, unprompted productions use the known pattern in a new sentence.
            if "mit " in answer.casefold():
                store.observe([mit["id"]], context=answer, at=dna.parse_moment(turn["at"]))
            weil_id = dna.mistake_id("word-order", "weil sends finite verb to end")
            if "weil " in answer.casefold() and any(row["id"] == weil_id for row in store.list()):
                store.observe([weil_id], context=answer, at=dna.parse_moment(turn["at"]))
        store.roleplay_finish(sid, at=at + timedelta(minutes=5))
        store.mission_assess(mission_id, session_id=sid, result=outcome, support="hint" if hint else "none",
                             evidence_turn_ids=[evidence["id"]], note=note, at=at + timedelta(minutes=6))

    capture(START, "The goal", "Friday has a plan",
            "Alex's interview date and three communication goals are saved locally. Creating the plan earns no learning points.")
    original = "Ich bin Entwickler. Ich habe mit mein Team ein Kundenportal gebaut. Ich möchte Ihre Projekte unterstützen."
    correction = "Ich bin Entwickler. Ich habe mit meinem Team ein Kundenportal gebaut. Ich möchte Ihre Projekte unterstützen."
    scene(START + timedelta(minutes=10), original, hint=True, corrected=correction, outcome="practice",
          note="Alex introduced a role, a project, and motivation after a hint. The introduction stays open for a new unaided attempt.")
    capture(START + timedelta(minutes=20), "With help", "A smaller next attempt",
            "The first introduction needed a hint. The next scene keeps the goal, changes the opening, and carries the actual sentence and helpful cue.")
    scene(START + timedelta(days=1),
          "Ich entwickle Backend-Systeme. Mit meinen Kolleginnen habe ich ein Buchungssystem gebaut. Ich möchte diese Erfahrung in Ihr Team einbringen.",
          note="Alex independently described a role, a relevant project, and motivation in a new introduction.")
    difficult = "Einmal kam eine Anfrage zu spät. Weil der Termin war knapp, habe ich die Aufgaben mit dem Team neu verteilt. Danach konnten wir pünktlich liefern."
    scene(START + timedelta(days=1, hours=3), difficult,
          corrected="Einmal kam eine Anfrage zu spät. Weil der Termin knapp war, habe ich die Aufgaben mit dem Team neu verteilt. Danach konnten wir pünktlich liefern.",
          note="Alex explained a difficult situation, an action, and the result without help. A recorded weil word-order error becomes a focus for the follow-up.")
    capture(START + timedelta(days=1, hours=3, minutes=10), "The next session", "A follow-up shaped by history",
            "Two communication steps are complete. The next follow-up receives Alex's previous answer and the recorded weil error, alongside the earlier case pattern.")
    scene(START + timedelta(days=2),
          "Wenn die erste Lösung nicht funktioniert, spreche ich mit meinen Kollegen über eine Alternative, weil wir gemeinsam schneller eine Lösung finden.",
          note="Alex responded to the changed situation with a concrete alternative and a reason, without a hint.")
    capture(START + timedelta(days=2, minutes=10), "The result", "Three practice steps completed",
            "The communication-practice plan is complete. This is evidence from the scripted scenes, not a claim of interview readiness or overall fluency.")
    return {"version": 1, "demo": True, "experience": "missions", "frames": frames}

def main(argv: list[str] | None = None) -> int:
    dna._configure_streams()
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parents[1] / "demo" / "missions.html")
    parser.add_argument("--force", action="store_true")
    arguments = parser.parse_args(argv)
    try:
        with tempfile.TemporaryDirectory(prefix="deutschloop-mission-demo-") as temporary:
            payload = mission_demo_payload(Path(temporary))
            result = dna.write_dashboard(payload, arguments.output, force=arguments.force)
        dna._print_json(result)
        return 0
    except dna.DeutschLoopError as exc:
        dna._print_json({"error": str(exc)}, stream=sys.stderr)
        return 2

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/deutsch_loop.py
size: 198876
sha: 48c11194fea378151aba89ac18fff1c968347eae
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/deutsch_loop.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/deutsch_loop.py

## File: scripts/render_dashboard_demo.py
size: 7795
sha: 39e8904a2785c9a98bdc4ebba9fbb8915f06dd7c
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/render_dashboard_demo.py

```text
#!/usr/bin/env python3
"""Build an offline, explorable story from isolated snapshots of the real engine."""

from __future__ import annotations

import argparse
import sys
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any

import deutsch_loop as dna

STORY_START = datetime(2026, 5, 20, 9, 0, tzinfo=timezone.utc)

def demo_payload(home: Path) -> dict[str, Any]:
    """Capture each chapter before later events exist; never reconstruct old scores."""
    if home.exists() and any(home.iterdir()):
        raise dna.DeutschLoopError("The dashboard demo requires an empty, isolated state directory")
    store = dna.StateStore(home)
    start = STORY_START
    store.init_profile(name="Alex", level="B2", at=start - timedelta(days=120))

    # Alex already has one older pattern. Its six reviews take the full scheduled time.
    article, _, _ = store.record(original="Der Rechnung ist hoch.", corrected="Die Rechnung ist hoch.",
                                 category="article", pattern="-ung nouns are feminine",
                                 rule="Nouns ending in -ung are feminine.", at=start - timedelta(days=120))
    article_tasks = [
        ("Was ist im Briefkasten angekommen? Nutze Rechnung.", "Heute ist die Rechnung angekommen."),
        ("Du hast das Büro gemietet. Was fehlt noch? Nutze Versicherung.", "Die Versicherung fehlt noch."),
        ("Du suchst eine neue Bleibe. Beschreibe die Wohnung.", "Die Wohnung ist hell und ruhig."),
        ("Was hast du heute gelesen? Nutze Zeitung.", "Ich habe die Zeitung im Zug gelesen."),
        ("Das Team bekommt eine neue Leitung. Wie findest du sie?", "Die neue Leitung ist sehr freundlich."),
        ("Wie war die Besprechung heute?", "Die Besprechung war kurz und hilfreich."),
    ]
    for prompt, answer in article_tasks:
        article, _ = store.grade(article["id"], result="pass", prompt=prompt, answer=answer,
                                 at=dna.parse_moment(article["next_review"]))

    mit, _, _ = store.record(original="Ich spreche mit mein Chef.", corrected="Ich spreche mit meinem Chef.",
                             category="case", pattern="mit + dative", rule="mit always governs the dative.", at=start)
    store.coach(mit["id"], outcome="assisted", prompt="Schau noch einmal auf mit mein Chef.",
                answer="Ich spreche mit meinem Chef.", strategy="Kasusfrage", hint="Frage dich: mit wem?",
                at=start + timedelta(minutes=2))
    warten, _, _ = store.record(original="Ich warte für den Bus.", corrected="Ich warte auf den Bus.",
                                category="preposition", pattern="warten auf + accusative",
                                rule="warten takes auf + accusative.", at=start + timedelta(minutes=3))
    store.coach(warten["id"], outcome="assisted", prompt="Welche Präposition gehört zu warten?",
                answer="Ich warte auf den Bus.", strategy="Verb und Präposition", hint="Denk an warten auf.",
                at=start + timedelta(minutes=4))
    weil, _, _ = store.record(original="Ich bleibe zu Hause, weil ich bin müde.",
                              corrected="Ich bleibe zu Hause, weil ich müde bin.", category="word-order",
                              pattern="weil sends finite verb to end", rule="In a weil clause the finite verb goes last.",
                              at=start + timedelta(minutes=5))
    store.record(original="Das ist ein wichtige Termin.", corrected="Das ist ein wichtiger Termin.",
                 category="agreement", pattern="adjective ending after ein-word",
                 rule="After ein, kein, mein the adjective shows the gender: ein wichtiger Termin.",
                 at=start + timedelta(minutes=6))
    frames = []

    def capture(days: int, minutes: int, chapter: str, title: str, story: str) -> None:
        snapshot = dna.dashboard_snapshot(store, at=start + timedelta(days=days, minutes=minutes))
        snapshot.update(chapter=chapter, title=title, story=story)
        frames.append(snapshot)

    capture(0, 8, "First try", "A hint, then self-repair",
            "Alex repairs mit mein Chef after a small hint. Useful practice; there is no later-day milestone yet.")
    store.grade(mit["id"], result="pass", prompt="Du telefonierst mit einer Kollegin. Erzähle davon in der Vergangenheit.",
                answer="Ich habe mit meiner Kollegin gesprochen.", at=start + timedelta(days=1, minutes=10))
    store.observe([warten["id"]], context="Vor dem Büro warte ich auf meinen Kollegen.",
                  at=start + timedelta(days=1, minutes=11))
    capture(1, 15, "Next day", "A new sentence, unaided",
            "A new review answer earns mit + Dativ its first milestone. warten auf also appears in Alex's own writing.")

    store.grade(weil["id"], result="hard", prompt="Warum bleibst du heute zu Hause?",
                answer="Ich bleibe zu Hause, weil ich krank bin.", strategy="Verbposition",
                hint="Nach weil steht das konjugierte Verb am Ende.", at=start + timedelta(days=2, minutes=20))
    store.grade(mit["id"], result="pass", prompt="Du reist nicht allein. Dein Bruder kommt mit. Mit wem reist du?",
                answer="Am Wochenende reise ich mit meinem Bruder nach Hamburg.", at=start + timedelta(days=4, minutes=10))
    store.record(mistake_id=warten["id"], original="Ich warte für meinen Kollegen.",
                 corrected="Ich warte auf meinen Kollegen.", at=start + timedelta(days=4, minutes=12))
    store.coach(warten["id"], outcome="assisted", prompt="Denk noch einmal an das Verb warten.",
                answer="Ich warte auf meinen Kollegen.", strategy="Verb und Präposition", hint="warten gehört zu auf.",
                at=start + timedelta(days=4, minutes=14))
    store.grade(weil["id"], result="pass", prompt="Es regnet stark. Erkläre, warum ihr zu Hause bleibt.",
                answer="Wir bleiben zu Hause, weil es stark regnet.", at=start + timedelta(days=5, minutes=10))
    store.grade(warten["id"], result="pass", prompt="Du bist am Bahnhof. Dein Bruder kommt mit dem Zug. Was machst du?",
                answer="Am Bahnsteig warte ich auf meinen Bruder.", at=start + timedelta(days=7, minutes=20))
    capture(7, 30, "One week later", "The pattern travels with you",
            "mit + Dativ now works in a travel situation too. Three patterns have saved learning milestones; they are still in practice.")

    store.record(mistake_id=mit["id"], original="Heute habe ich mit mein Nachbar gesprochen.",
                 corrected="Heute habe ich mit meinem Nachbarn gesprochen.", at=start + timedelta(days=103))
    capture(103, 5, "103 days later", "A return, with memory intact",
            "The mistake comes back. The engine resets its review ladder, while the earlier hint and learning milestone remain part of the story.")
    return {"version": 1, "demo": True, "frames": frames}

def main(argv: list[str] | None = None) -> int:
    dna._configure_streams()
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parents[1] / "demo" / "index.html")
    parser.add_argument("--force", action="store_true", help="Replace an existing demo HTML file")
    arguments = parser.parse_args(argv)
    try:
        with tempfile.TemporaryDirectory(prefix="deutschloop-dashboard-demo-") as temporary:
            result = dna.write_dashboard(demo_payload(Path(temporary)), arguments.output, force=arguments.force)
        dna._print_json(result)
        return 0
    except dna.DeutschLoopError as exc:
        dna._print_json({"error": str(exc)}, stream=sys.stderr)
        return 2

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/render_demo_gif.py
size: 23648
sha: 259eee210c7005c6ca1f6e0784846a3bea557680
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/render_demo_gif.py

````text
#!/usr/bin/env python3
"""Render readable README stories from engine records or a captured conversation.

Pillow is only needed for this contributor tool. The learning and history stories
use scripted learner inputs; the conversation and session stories replay real host replies.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
import re
import sys
import tempfile

try:
    from PIL import Image, ImageDraw, ImageFont
except ModuleNotFoundError as exc:
    raise SystemExit("Install the renderer dependency: python -m pip install pillow") from exc

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import demo  # noqa: E402
import deutsch_loop as dna  # noqa: E402

WIDTH, HEIGHT = 720, 800
QUOTE_SIZE = 42  # 18 CSS px when GitHub displays this image at 309 px wide.
QUOTATION_MARKS = "„“”\"‚‘’'«»"
COLORS = {
    "page": "#11111b", "panel": "#1b1b2b", "border": "#45475a",
    "text": "#e4e7f5", "muted": "#b2b8ce", "accent": "#d9ff45",
    "blue": "#9ac6ff", "green": "#b5edb0", "red": "#ff97b4",
}
FONT_CANDIDATES = (
    Path("C:/Windows/Fonts/consola.ttf"),
    Path("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"),
    Path("/usr/share/fonts/truetype/liberation2/LiberationMono-Regular.ttf"),
    Path("/System/Library/Fonts/SFNSMono.ttf"),
)

def find_font(explicit: str | None) -> Path:
    for path in (Path(explicit).expanduser(),) if explicit else FONT_CANDIDATES:
        if path.is_file():
            return path
    raise ValueError("No monospaced font found; pass --font PATH")

def row(label: str, text: str, color: str = "text", *highlight: str) -> dict:
    return {"label": label, "text": text, "color": color, "highlight": highlight}

def collect_learning_screens() -> list[dict]:
    with tempfile.TemporaryDirectory(prefix="deutschloop-learning-gif-") as directory:
        demo.seed_learning_loop(Path(directory))
        mistake = dna.StateStore(Path(directory)).show(dna.mistake_id("case", "mit + dative"))
    proof = dna.learning_proof_view(mistake["learning_proof"])
    if not proof or proof["independent"]["source"] != "spontaneous":
        raise ValueError("The opening frame requires recorded later, unaided use")
    support, independent = proof["with_help"], proof["independent"]
    practice = next(item for item in mistake["coaching_history"] if item["outcome"] == "independent")
    return [
        {"stage": "THE NEXT DAY", "title": "You did it yourself.", "duration": 4200,
         "rows": [row("YESTERDAY / WITH A HINT", support["answer"], "text", "meinem"),
                  row("TODAY / WITHOUT HELP", independent["answer"], "green", "unseren")],
         "footer": "Same pattern. A new sentence."},
        {"stage": "HOW IT STARTED", "title": "A hint. Your turn.", "duration": 3400,
         "rows": [row("YOU WROTE", mistake["first_example"]["original"], "red", "mein"),
                  row("YOUR TUTOR", support["hint"], "blue", "wem")],
         "footer": "You get room to find the fix."},
        {"stage": "YOU FOUND THE FIX", "title": "Now try it again.", "duration": 3400,
         "rows": [row("YOUR REPAIR", support["answer"], "green", "meinem"),
                  row("NEW PRACTICE / NO HINT", practice["answer"], "green", "dem")],
         "footer": "Your tutor remembers what helped."},
    ]

def collect_history_screens() -> list[dict]:
    with tempfile.TemporaryDirectory(prefix="deutschloop-history-gif-") as directory:
        demo.seed(Path(directory))
        mistake = dna.StateStore(Path(directory)).show(dna.mistake_id("preposition", "warten auf + accusative"))
    wrong = sorted(mistake["examples"], key=lambda item: dna.parse_moment(item["seen_at"]))
    gap = (dna.parse_moment(wrong[-1]["seen_at"]) - dna.parse_moment(wrong[-2]["seen_at"])).days
    original = mistake["first_example"]
    hint = mistake["helpful_hint"]
    return [
        {"stage": "AN OLD MISTAKE RETURNS", "title": f"{gap} days later.", "duration": 4500,
         "rows": [row("YOUR FIRST MISTAKE", original["original"], "red", "warte"),
                  row("IT COMES BACK", wrong[-1]["original"], "red", "warte")],
         "footer": "The first sentence is still saved."},
        {"stage": "YOUR TUTOR REMEMBERS", "title": "Pick up from here.", "duration": 4500,
         "rows": [row("THE ORIGINAL CORRECTION", original["corrected"], "green", "auf"),
                  row("THE HINT THAT HELPED", hint["hint"], "blue", "auf")],
         "footer": "Back in practice, with your history."},
    ]

def collect_board() -> tuple[str, str]:
    """The session board of the four-month demo learner, exactly as `recap --format card` prints it."""
    with tempfile.TemporaryDirectory(prefix="deutschloop-board-") as directory:
        demo.seed(Path(directory))
        recap = dna.StateStore(Path(directory)).recap()
    return recap["profile"]["name"], dna.render_recap_card(recap)

def draw_comeback(draw: ImageDraw.ImageDraw, x: float, y: int, cell: float, color: str, scale: float = 1) -> None:
    """Draw ↺ inside one character cell; common monospaced fonts such as Consolas lack the glyph."""
    size = min(cell, 20 * scale)
    left, top = x + (cell - size) / 2, y + 12 * scale
    # Open at the upper right, like the font glyph; the arrowhead sits on the top end.
    draw.arc((left, top, left + size, top + size), start=315, end=270, fill=COLORS[color], width=round(3 * scale))
    middle = left + size / 2
    draw.polygon([(middle + 7 * scale, top + scale), (middle - 2 * scale, top - 5 * scale),
                  (middle - 2 * scale, top + 7 * scale)], fill=COLORS[color])

def draw_header(draw: ImageDraw.ImageDraw, width: int, stage: str, heading: str,
                label: ImageFont.FreeTypeFont, title: ImageFont.FreeTypeFont) -> None:
    draw.text((64, 44), "DeutschLoop", font=label, fill=COLORS["accent"])
    link = "github.com/ahmtsahin/deutsch-loop"
    draw.text((width - 64 - label.getlength(link), 44), link, font=label, fill=COLORS["muted"])
    draw.text((64, 112), stage, font=label, fill=COLORS["accent"])
    draw.text((64, 156), heading, font=title, fill=COLORS["text"])

def draw_card(draw: ImageDraw.ImageDraw, lines: list[str], left: int, top: int,
              mono: ImageFont.FreeTypeFont, line_height: int, scale: float = 1) -> None:
    """Draw the board as the engine prints it, with the ladders and comeback markers as shapes.

    The shapes are sized for 34 px type; `scale` adapts them to another size.
    """
    cell = mono.getlength(" ")

    def paint(x: float, y: int, text: str, color: str) -> float:
        draw.text((x, y), text, font=mono, fill=COLORS[color])
        return x + mono.getlength(text)

    for index, line in enumerate(lines):
        x, y = left, top + index * line_height
        ladder = re.search(r"[▰▱]+", line)
        if index == 0:
            head, _, rest = line.partition(" · ")
            paint(paint(x, y, head, "accent"), y, f" · {rest}", "text")
        elif not ladder:
            paint(x, y, line, "muted")
        else:
            # Label, review ladder drawn as boxes, then counts, the comeback marker, and the due time.
            x = paint(x, y, line[: ladder.start()], "text")
            steps = ladder.group(0)
            gap = 4 * scale
            box = (cell * len(steps) - 2 * gap) / len(steps) - gap
            for number, step in enumerate(steps):
                start = x + gap + number * (box + gap)
                shape = (start, y + 12 * scale, start + box, y + 32 * scale)
                if step == "▰":
                    draw.rounded_rectangle(shape, radius=3, fill=COLORS["accent"])
                else:
                    draw.rounded_rectangle(shape, radius=3, outline=COLORS["border"], width=2)
            x += cell * len(steps)
            for part in re.findall(r"↺|jetzt fällig|[^↺]+?(?=↺|jetzt fällig|$)", line[ladder.end():]):
                if part == "↺":
                    draw_comeback(draw, x, y, cell, "red", scale)
                    x += cell
                else:
                    x = paint(x, y, part, "accent" if part == "jetzt fällig" else "muted")

def render_board(name: str, card: str, font_path: Path) -> Image.Image:
    width, height = 1600, 900
    label = ImageFont.truetype(str(font_path), 30)
    title = ImageFont.truetype(str(font_path), 64)
    mono = ImageFont.truetype(str(font_path), 34)
    lines = card.splitlines()
    image = Image.new("RGB", (width, height), COLORS["page"])
    draw = ImageDraw.Draw(image)
    draw_header(draw, width, "HOW EVERY SESSION STARTS", f"Hallo {name}!", label, title)

    top, line_height, pad = 262, 50, 48
    bottom = top + 80 + line_height * len(lines) - 14
    if max(mono.getlength(line) for line in lines) > width - 128 - 2 * pad or bottom > height - 110:
        raise ValueError("The board does not fit the image; shorten the demo board")
    draw.rounded_rectangle((64, top, width - 64, bottom), radius=24, fill=COLORS["panel"], outline=COLORS["border"], width=2)
    draw_card(draw, lines, 64 + pad, top + 40, mono, line_height)
    draw.text((64, bottom + 34), "Your own mistakes, ordered by what is due today.", font=label, fill=COLORS["text"])
    draw.text((64, bottom + 78), "Scripted learner / real engine output", font=label, fill=COLORS["muted"])
    return image

def render_social(card: str, font_path: Path) -> Image.Image:
    """The board at GitHub's social preview size, 1280 × 640."""
    width, height = 1280, 640
    label = ImageFont.truetype(str(font_path), 24)
    title = ImageFont.truetype(str(font_path), 54)
    mono = ImageFont.truetype(str(font_path), 26)
    lines = card.splitlines()
    image = Image.new("RGB", (width, height), COLORS["page"])
    draw = ImageDraw.Draw(image)
    draw.text((56, 34), "DeutschLoop", font=label, fill=COLORS["accent"])
    hosts = "for Claude Code and Codex"
    draw.text((width - 56 - label.getlength(hosts), 34), hosts, font=label, fill=COLORS["muted"])
    draw.text((56, 78), "A German tutor that", font=title, fill=COLORS["text"])
    draw.text((56, 140), "remembers your mistakes.", font=title, fill=COLORS["text"])

    top, line_height, pad = 232, 36, 40
    bottom = top + 2 * 30 + line_height * len(lines) - 8
    if max(mono.getlength(line) for line in lines) > width - 112 - 2 * pad or bottom > height - 56:
        raise ValueError("The board does not fit the social preview; shorten the demo board")
    draw.rounded_rectangle((56, top, width - 56, bottom), radius=20, fill=COLORS["panel"], outline=COLORS["border"], width=2)
    draw_card(draw, lines, 56 + pad, top + 30, mono, line_height, scale=26 / 34)
    draw.text((56, bottom + 16), "Local memory. No API key. Scripted learner, real engine output.",
              font=label, fill=COLORS["muted"])
    return image

def collect_session(source: Path) -> dict:
    """The opening reply of a recorded chat: greeting, engine board, quoted sentence, and new task."""
    recording = json.loads(source.read_text(encoding="utf-8"))
    reply, card, quoted = recording["exchanges"][0]["tutor"], recording["card"], recording["evidence"]["quoted"]
    if card not in reply:
        raise ValueError("The recorded reply does not show the engine's board")
    before, _, after = reply.partition(card)
    # plain() removes the code fence, which leaves its paragraph empty.
    paragraphs = [text for text in map(plain, after.split("\n\n")) if text]
    if len(paragraphs) < 2 or quoted["original"] not in paragraphs[0]:
        raise ValueError("The recorded reply does not quote the stored sentence before its task")
    lead, sentence, rest = paragraphs[0].partition(quoted["original"])
    lead, rest = lead.rstrip(), rest.strip()
    if lead[-1:] in QUOTATION_MARKS and rest[:1] in QUOTATION_MARKS:
        # The quotation marks around the sentence stay with it.
        lead, sentence = lead[:-1].rstrip(), f"{lead[-1]}{sentence}{rest[0]}"
    changed = [word for word in quoted["original"].rstrip(".").split()
               if word not in quoted["corrected"].rstrip(".").split()]
    return {"greeting": plain(before.replace("```text", "")), "card": card.splitlines(),
            "lead": lead, "sentence": sentence, "changed": changed, "task": paragraphs[1]}

def render_session(session: dict, font_path: Path) -> Image.Image:
    width = 1600
    label = ImageFont.truetype(str(font_path), 30)
    title = ImageFont.truetype(str(font_path), 64)
    mono = ImageFont.truetype(str(font_path), 34)
    top, line_height, pad = 262, 50, 48
    inner = width - 128 - 2 * pad
    task = wrap_text(session["task"], mono, inner)
    card = session["card"]
    if max(mono.getlength(line) for line in card + [session["lead"], session["sentence"]]) > inner:
        raise ValueError("The recorded opening does not fit the image")
    # Greeting, board, quoted sentence, and task, separated by one empty line each.
    rows = 1 + 1 + len(card) + 1 + 2 + 1 + len(task)
    bottom = top + 80 + line_height * rows - 14
    image = Image.new("RGB", (width, bottom + 140), COLORS["page"])
    draw = ImageDraw.Draw(image)
    draw_header(draw, width, "A NEW CHAT / FOUR MONTHS IN", "It starts with your own sentence.", label, title)
    draw.rounded_rectangle((64, top, width - 64, bottom), radius=24, fill=COLORS["panel"], outline=COLORS["border"], width=2)

    left, y = 64 + pad, top + 40
    draw.text((left, y), session["greeting"], font=mono, fill=COLORS["text"])
    y += 2 * line_height
    draw_card(draw, card, left, y, mono, line_height)
    y += (len(card) + 1) * line_height
    draw.text((left, y), session["lead"], font=mono, fill=COLORS["muted"])
    y += line_height
    x = left
    for part in re.findall(r"\s+|\S+", session["sentence"]):
        marked = part.strip(".,?!:;" + QUOTATION_MARKS) in session["changed"]
        draw.text((x, y), part, font=mono, fill=COLORS["red"])
        if marked:
            draw.line((x, y + 40, x + mono.getlength(part), y + 40), fill=COLORS["red"], width=3)
        x += mono.getlength(part)
    y += 2 * line_height
    for line in task:
        draw.text((left, y), line, font=mono, fill=COLORS["text"])
        y += line_height
    draw.text((64, bottom + 34), "Your patterns, a sentence you got wrong, and a new situation for it.",
              font=label, fill=COLORS["text"])
    draw.text((64, bottom + 78), "Actual Claude Code reply / scripted learner history", font=label, fill=COLORS["muted"])
    return image

def plain(text: str) -> str:
    """Remove emphasis markers for the visual replay, preserving the actual words."""
    return re.sub(r"[*_`]", "", text).strip()

def checked_excerpt(text: str, excerpt: str) -> str:
    if excerpt not in plain(text):
        raise ValueError(f"The recording does not contain this excerpt: {excerpt!r}")
    return excerpt

def collect_conversation_screens(source: Path) -> list[dict]:
    recording = json.loads(source.read_text(encoding="utf-8"))
    first, repair, fresh = recording["exchanges"]
    # Excerpts are checked against the captured replies, never invented by the renderer.
    return [
        {"stage": "CLAUDE CODE / CHAT 1", "title": "A real exchange.", "duration": 5000,
         "rows": [row("SCRIPTED LEARNER", checked_excerpt(first["learner"], "Ich spreche mit mein Chef."), "red", "mein"),
                  row("TUTOR / EXCERPT", checked_excerpt(first["tutor"], "Which case does mit take?"), "blue", "mit")],
         "footer": "Actual reply. Time compressed."},
        {"stage": "CLAUDE CODE / CHAT 1", "title": "You make the repair.", "duration": 4500,
         "rows": [row("SCRIPTED LEARNER", checked_excerpt(repair["learner"], "Ich spreche mit meinem Chef."), "green", "meinem"),
                  row("TUTOR / EXCERPT", checked_excerpt(repair["tutor"], "mein becomes meinem"), "blue", "meinem")],
         "footer": "The hint and repair are saved."},
        {"stage": "CLAUDE CODE / A NEW CHAT", "title": "The memory carries on.", "duration": 6500,
         "rows": [row("SCRIPTED LEARNER", checked_excerpt(fresh["learner"], "Heute habe ich mit unseren Kunden gesprochen."), "green", "unseren"),
                  row("IT RECALLS THE SAME HINT", checked_excerpt(fresh["tutor"], recording["evidence"]["coaching_history"][0]["hint"]), "blue")],
         "footer": "New chat. Same day. Shared memory."},
    ]

def wrap_text(text: str, font: ImageFont.FreeTypeFont, width: int) -> list[str]:
    lines, current = [], ""
    for word in text.split():
        if font.getlength(word) > width:
            raise ValueError(f"A word does not fit: {word!r}")
        candidate = f"{current} {word}".strip()
        if current and font.getlength(candidate) > width:
            lines.append(current)
            current = word
        else:
            current = candidate
    return lines + ([current] if current else [])

def draw_quote(draw: ImageDraw.ImageDraw, text: str, position: tuple[int, int],
               font: ImageFont.FreeTypeFont, color: str, highlights: tuple[str, ...]) -> None:
    lines = wrap_text(text, font, WIDTH - 112)
    if len(lines) > 3:
        raise ValueError(f"Quote exceeds three readable lines; shorten the excerpt: {text!r}")
    left, top = position
    for index, line in enumerate(lines):
        x, y = left, top + index * 50
        for part in re.findall(r"\s+|\S+", line):
            marked = part.strip(".,?!:;„“\"'").casefold() in {word.casefold() for word in highlights}
            draw.text((x, y), part, font=font, fill=COLORS[color] if marked or not highlights else COLORS["text"])
            width = font.getlength(part)
            if marked:
                draw.line((x, y + 44, x + width, y + 44), fill=COLORS[color], width=3)
            x += width

def render_frame(screen: dict, index: int, count: int, font_path: Path, *,
                 second_row: bool = True, conversation: bool = False) -> Image.Image:
    heading = ImageFont.truetype(str(font_path), 50)
    quote = ImageFont.truetype(str(font_path), QUOTE_SIZE)
    label = ImageFont.truetype(str(font_path), 28)
    image = Image.new("RGB", (WIDTH, HEIGHT), COLORS["page"])
    draw = ImageDraw.Draw(image)
    draw.text((32, 22), "DeutschLoop", font=label, fill=COLORS["accent"])
    step = f"{index + 1} / {count}"
    draw.text((WIDTH - 32 - label.getlength(step), 22), step, font=label, fill=COLORS["muted"])
    for text, font, y, color in ((screen["stage"], label, 76, "accent"),
                               (screen["title"], heading, 115, "text")):
        if font.getlength(text) > WIDTH - 64:
            raise ValueError(f"Heading is too wide: {text!r}")
        draw.text((32, y), text, font=font, fill=COLORS[color])

    for number, item in enumerate(screen["rows"]):
        if number == 1 and not second_row:
            continue
        top = 195 + number * 240
        draw.rounded_rectangle((32, top, WIDTH - 32, top + 222), radius=20,
                               fill=COLORS["panel"], outline=COLORS["border"], width=2)
        if conversation:
            draw.line((33, top + 22, 33, top + 200), fill=COLORS[item["color"]], width=4)
        if label.getlength(item["label"]) > WIDTH - 112:
            raise ValueError(f"Row label is too wide: {item['label']!r}")
        draw.text((56, top + 16), item["label"], font=label, fill=COLORS["muted"])
        draw_quote(draw, item["text"], (56, top + 66), quote, item["color"], item["highlight"])

    if label.getlength(screen["footer"]) > WIDTH - 64:
        raise ValueError(f"Footer is too wide: {screen['footer']!r}")
    draw.text((32, 692), screen["footer"], font=label, fill=COLORS["text"])
    disclosure = "Recorded chat / excerpt replay" if conversation else "Scripted learner / real engine"
    draw.text((32, 731), disclosure, font=label, fill=COLORS["muted"])
    track = (WIDTH - 64 - (count - 1) * 10) / count
    for step_index in range(count):
        x = 32 + step_index * (track + 10)
        draw.rounded_rectangle((x, 777, x + track, 781), radius=2,
                               fill=COLORS["accent"] if step_index == index else COLORS["border"])
    return image

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--story", choices=("history", "learning-loop", "conversation", "board", "session", "social"),
                        default="learning-loop")
    parser.add_argument("--output", type=Path,
                        help="Output GIF; a static PNG is saved beside it (board, session, social: the PNG itself)")
    parser.add_argument("--font", help="Path to a monospaced TrueType font")
    parser.add_argument("--frames-dir", type=Path, help="Save full-size and 309 px wide PNGs for review")
    parser.add_argument("--transcript", type=Path,
                        help="Recording to replay (default: demo/conversation.json, or demo/session.json for session)")
    arguments = parser.parse_args(argv)
    font = find_font(arguments.font)
    if arguments.story in ("board", "session", "social"):
        output = arguments.output or ROOT / "demo" / f"{arguments.story}.png"
        output.parent.mkdir(parents=True, exist_ok=True)
        if arguments.story == "board":
            image, name = render_board(*collect_board(), font), "session board"
        elif arguments.story == "social":
            image, name = render_social(collect_board()[1], font), "social preview"
        else:
            source = arguments.transcript or ROOT / "demo" / "session.json"
            image, name = render_session(collect_session(source), font), "recorded opening"
        image.save(output)
        print(f"Rendered the {name} to {output}")
        return 0
    if arguments.story == "learning-loop":
        screens, filename = collect_learning_screens(), "learning-loop"
    elif arguments.story == "history":
        screens, filename = collect_history_screens(), "history"
    else:
        screens, filename = collect_conversation_screens(arguments.transcript or ROOT / "demo" / "conversation.json"), "conversation"
    frames, durations, complete = [], [], []
    for index, screen in enumerate(screens):
        conversation = arguments.story == "conversation"
        full = render_frame(screen, index, len(screens), font, conversation=conversation)
        complete.append(full)
        # Let the learner message arrive before the recorded tutor reply.
        if conversation:
            frames.append(render_frame(screen, index, len(screens), font, second_row=False, conversation=True))
            durations.append(600)
        frames.append(full)
        durations.append(screen["duration"] - (600 if conversation else 0))
    output = arguments.output or ROOT / "demo" / f"{filename}.gif"
    output.parent.mkdir(parents=True, exist_ok=True)
    frames[0].save(output, save_all=True, append_images=frames[1:], duration=durations,
                   loop=0, optimize=True, disposal=2)
    # The first complete frame is also the opening result, so no waiting is needed.
    complete[0].save(output.with_suffix(".png"))
    if arguments.frames_dir:
        arguments.frames_dir.mkdir(parents=True, exist_ok=True)
        for index, frame in enumerate(complete, 1):
            frame.save(arguments.frames_dir / f"{filename}-{index}.png")
            frame.resize((309, round(HEIGHT * 309 / WIDTH)), Image.Resampling.LANCZOS).save(
                arguments.frames_dir / f"{filename}-{index}-mobile.png")
    print(f"Rendered {len(screens)} scenes / {sum(durations) / 1000:g}s to {output}")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
````

## File: scripts/scenario_catalog.py
size: 13118
sha: 69df1c4b33a99970df0f486af6c71296706b9ca3
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/scenario_catalog.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/scripts/scenario_catalog.py

## File: references/cli-contract.md
size: 33562
sha: 0d2f47dc369b0578e83d5cebcbc0a6f4b621a4bc
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/cli-contract.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/cli-contract.md

## File: references/correction-protocol.md
size: 5398
sha: bc871e821ad9bcb9c965061d5c2fea62b039a3b1
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/correction-protocol.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/correction-protocol.md

## File: references/error-taxonomy.md
size: 3095
sha: e9585c8d6d71382215476a2d7c5a9c20d840d010
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/error-taxonomy.md

```text
# FehlerDNA taxonomy

Choose one primary category. Put cross-cutting detail in the `pattern` and `rule` fields rather than duplicating the same event in several categories. Canonical pattern keys for each category are in [patterns.md](patterns.md).

| Category | Use for | Pattern-key examples |
| --- | --- | --- |
| `article` | noun gender and article selection | `-ung nouns are feminine`, `Tisch is masculine`, `no article before profession or nationality` |
| `case` | case marking after prepositions, verbs, and in noun phrases | `mit + dative`, `helfen + dative`, `masculine accusative -en` |
| `preposition` | which preposition a verb, adjective, or expression takes, and preposition choice | `warten auf + accusative`, `seit vs vor`, `nach vs zu for destinations` |
| `word-order` | verb position, clause order, sentence fields | `weil sends finite verb to end`, `finite verb in second position` |
| `verb` | conjugation, tense, auxiliary, participle, separable or reflexive form | `sein as perfect auxiliary for motion and change`, `sich erinnern is reflexive` |
| `agreement` | adjective, determiner, or subject-verb agreement | `adjective ending after ein-word`, `possessive agrees with the possessed noun` |
| `plural` | plural formation | `Person plural is Personen`, `-ung plural adds -en` |
| `spelling` | spelling, capitalization, compound boundaries | `German nouns are capitalized`, `dass vs das` |
| `vocabulary` | wrong lexical item, false friend, or fixed collocation | `kennen vs wissen`, `eine Entscheidung treffen` |
| `register` | situationally inappropriate formality | `Sie in formal exchanges` |
| `punctuation` | commas and punctuation that affect correctness | `comma before subordinate clause` |
| `other` | genuine errors that fit none of the above | keep the pattern precise |

## Deciding between `case` and `preposition`

- The learner chose the right preposition but the wrong case after it: `case` (`mit mein Chef` → `mit + dative`).
- The learner omitted or chose the wrong preposition that a verb or adjective requires: `preposition` (`Ich warte dich` → `warten auf + accusative`).
- The learner used the right verb-preposition pair with the wrong case: still `preposition`, because the key already carries the case (`warten auf + accusative`).

## Stable pattern keys

- Name the reusable rule: `mit + dative`, not `mit meinem Chef`.
- Keep the same wording for the same root cause; the CLI normalizes case names, spacing, and `takes/governs` phrasings, but a catalog key keeps the record clean.
- Separate patterns when their remediation differs. `warten auf + accusative` and `helfen + dative` are not one pattern, even though both involve government.
- Prefer the deepest useful cause. For `mit meine Kunde`, track `mit + dative` and mention the n-declension in the rule; add `n-declension nouns take -n/-en` only when it recurs on its own.
- When `record` reports `similar_patterns`, read them before continuing. Merge only when the remediation is identical; `der-word` and `ein-word` adjective endings are similar strings but different lessons.
```

## File: references/learning-loop.md
size: 6170
sha: 9620c629de729db53cddb60363fd0f87437fa111
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/learning-loop.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/learning-loop.md

## File: references/missions.md
size: 8505
sha: 7453bf6ecc765dbe8bb6b71e7431c9196ec1df85
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/missions.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/missions.md

## File: references/onboarding.md
size: 6389
sha: 3b0f2cdf3b7773fcd9458d71679ff94c5a955704
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/onboarding.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/onboarding.md

## File: references/patterns.md
size: 13820
sha: c964c076ed0990842030146f49dfccd1f8e3f5c3
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/patterns.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/patterns.md

## File: references/roleplay.md
size: 12794
sha: 4357ac526850ff67f2c3bd55067363cec69c560e
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/roleplay.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/references/roleplay.md

## File: .claude-plugin/marketplace.json
size: 663
sha: fac26a763b3510336445a96a7bfef47dcd65b2c9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.claude-plugin/marketplace.json

```text
{
  "name": "deutsch-loop",
  "description": "DeutschLoop, a German tutor with memory for Claude Code and Codex",
  "owner": {
    "name": "Ahmet Sahin",
    "url": "https://github.com/ahmtsahin"
  },
  "plugins": [
    {
      "name": "deutsch-loop",
      "source": "./",
      "description": "A German tutor that remembers your mistakes, brings each one back in a new sentence, and keeps the hint that helped."
    },
    {
      "name": "nochmal",
      "source": "./mods/nochmal",
      "description": "Claude Code companion: what is due in the status line, a FehlerDNA card while Claude works, a live FehlerDNA pane, and a roleplay scene pane."
    }
  ]
}
```

## File: .claude-plugin/plugin.json
size: 562
sha: 670902036450c793b6a4dfa4aa3a8cb6c9c64dc8
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.claude-plugin/plugin.json

```text
{
  "name": "deutsch-loop",
  "displayName": "DeutschLoop",
  "version": "2.0.0",
  "description": "A German tutor that remembers your mistakes, brings each one back in a new sentence, and keeps the hint that helped. Local memory, no API key.",
  "author": {
    "name": "Ahmet Sahin",
    "url": "https://github.com/ahmtsahin"
  },
  "homepage": "https://github.com/ahmtsahin/deutsch-loop",
  "repository": "https://github.com/ahmtsahin/deutsch-loop",
  "license": "MIT",
  "keywords": ["german", "language-learning", "spaced-repetition", "tutor", "deutsch"]
}
```

## File: .codex-plugin/plugin.json
size: 1406
sha: 675ec0ed8445331f9250b05fd3f43a239140e44d
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.codex-plugin/plugin.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.codex-plugin/plugin.json

## File: .github/workflows/tests.yml
size: 718
sha: cf798c9bb9d5d03e85f5b1534eb7e9dcd7301c66
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.github/workflows/tests.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.github/workflows/tests.yml

## File: .gitignore
size: 117
sha: aba5515b6e1b22fb56c4e44d552f36e9d51590e6
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/.gitignore

```text
__pycache__/
*.py[cod]
.pytest_cache/
.coverage
htmlcov/
.venv/
venv/
.deutschloop/
.deutschdna/
demo-home/
.claude/
```

## File: agents/openai.yaml
size: 262
sha: d25db6028c11bab5be96c5afd1b9f01900744268
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/agents/openai.yaml

```text
interface:
  display_name: "DeutschLoop"
  short_description: "Simple German practice that remembers what helps"
  brand_color: "#D9FF45"
  default_prompt: "Use $deutsch-loop to help me start practising German, with a short explanation and one easy first step."
```

## File: demo/board.png
size: 115877
sha: c0556d03313aee9dd01bfb39bfcc8b3cd8a985be
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/board.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/board.png

## File: demo/conversation.gif
size: 162034
sha: ee56181042927531c1be8840890c55f927f210a9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.gif

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.gif

## File: demo/conversation.json
size: 3189
sha: 3536c87e0000f19d7c2dd501a78d5083ef4b08ca
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.json

## File: demo/conversation.md
size: 2792
sha: 6ece8de4d6ea277c71731d4428615360d0136aad
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.md

## File: demo/conversation.png
size: 45397
sha: b118c6920a05ea08789079fc52823bc1be30e58f
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/conversation.png

## File: demo/history.gif
size: 55549
sha: 56c27ea5ef66a8a8471ca0b40b38d7cebff3394c
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.gif

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.gif

## File: demo/history.png
size: 43552
sha: 9d9a0f9707632b8985a95bfa29e958bcc7b7569e
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.png

## File: demo/history.tape
size: 1247
sha: e0ac6dd8a007adf5ceec24538124b8ba486210e2
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.tape

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/history.tape

## File: demo/index.html
size: 120628
sha: 1853789d690b30b5faa209b10e1cf32d5bb8d6d0
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/index.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/index.html

## File: demo/learning-loop.gif
size: 85733
sha: 0e431aec6eae52b79ad6d4fddf8db60cdb0439db
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/learning-loop.gif

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/learning-loop.gif

## File: demo/learning-loop.png
size: 49906
sha: 1824c2c7cb76e4194896e0611c24c2be980681d4
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/learning-loop.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/learning-loop.png

## File: demo/missions.html
size: 96801
sha: 05b5191966ed32633f44ac157b6d9bbc924b5f37
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/missions.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/missions.html

## File: demo/missions.png
size: 261447
sha: a70c57a6bceadc80887919a1e3cdc14b80de0130
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/missions.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/missions.png

## File: demo/session.json
size: 5644
sha: 97145d11ad9ea1cc7771e1218710d46808dfe1ff
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.json

## File: demo/session.md
size: 4957
sha: 29af5eb59dec8b65d48a77a921b3f1996cc6ab21
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.md

## File: demo/session.png
size: 170693
sha: 3c2fc49f351925dc4863033fcab81ce9aaf84e4f
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/session.png

## File: demo/social.png
size: 84076
sha: 56c6f45fdfb4076ae898631d3918ca2aefef4db9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/social.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/demo/social.png

## File: docs/cli.md
size: 4602
sha: ac6572d933e94630fe5d6f03f064480421c86cd9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/cli.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/cli.md

## File: docs/companion.md
size: 10097
sha: 7acea475727a92f12c52a609596ba0326e404e87
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/companion.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/companion.md

## File: docs/dashboard.md
size: 4558
sha: 8f5cad598055b97f40340394c19db84d103a45c3
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/dashboard.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/dashboard.md

## File: docs/development.md
size: 9669
sha: 363325f9685194d5a8ac489e37ea6dd7252e856b
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/development.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/development.md

## File: docs/missions.md
size: 4435
sha: 5d28faa8a9925f20e59e13c533f94734e80d02fb
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/missions.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/missions.md

## File: docs/practice.md
size: 6599
sha: bd1efe89126d0334faca442a6eaa75c41fff1727
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/practice.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/practice.md

## File: docs/setup.md
size: 5510
sha: 7fc2c5268b4a5778460ad1bd4b9774ee4d1120b4
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/setup.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/docs/setup.md

## File: evals/first_session.py
size: 31435
sha: d4fe7a0a66caf98fd3778bd737c33b19c3080f7d
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/first_session.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/first_session.py

## File: evals/interrupted_lesson.py
size: 12848
sha: 8a32c0e8063039d88e4ea58f2bd9bdddd09efe9e
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/interrupted_lesson.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/interrupted_lesson.py

## File: evals/record_conversation.py
size: 9051
sha: def70822424cc843e3d314a84e780de1bb6843f9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/record_conversation.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/record_conversation.py

## File: evals/record_session.py
size: 10624
sha: 3f293c3ee466a45eeb58273a078e79a917078760
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/record_session.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/evals/record_session.py

## File: LICENSE
size: 1082
sha: 45ee0967e7a602ef7589c64eb9561c1d118e52d5
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/LICENSE

## File: mods/nochmal/.claude-plugin/plugin.json
size: 636
sha: 1fa15084987860e30a985d455e3479f03a7e4646
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/.claude-plugin/plugin.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/.claude-plugin/plugin.json

## File: mods/nochmal/hooks/hooks.json
size: 34
sha: 5a63f649593a5d89af8775a8e3d12db0f0940b12
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/hooks/hooks.json

```text
{ "modules": ["./register.tsx"] }
```

## File: mods/nochmal/hooks/register.tsx
size: 33379
sha: 89ca5852d2e2854bf2e15e1db838062fa6a346dc
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/hooks/register.tsx

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/hooks/register.tsx

## File: mods/nochmal/tests/band.test.tsx
size: 4879
sha: f17666d218eb8336c00b5d4a6e4a1ab08900813c
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/band.test.tsx

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/band.test.tsx

## File: mods/nochmal/tests/panes.test.tsx
size: 5528
sha: df3b54d7ca87ca80eaea558e33ba00d71b2e2601
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/panes.test.tsx

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/panes.test.tsx

## File: mods/nochmal/tests/stand-ins.tsx
size: 7382
sha: eccb43c5b25f4efc9f292348a969a2d488cdaced
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/stand-ins.tsx

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tests/stand-ins.tsx

## File: mods/nochmal/tsconfig.json
size: 56
sha: 8681ec01da419175c87f8c968c6a5af2d2b4e5ae
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/tsconfig.json

```text
{
  "extends": "./.claude-plugin/types/tsconfig.json"
}
```

## File: mods/nochmal/types/index.d.ts
size: 2439
sha: 00545982767e6eb7cdc5293aa80542a77a365233
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/types/index.d.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/mods/nochmal/types/index.d.ts

## File: tests/test_agent_contract.py
size: 10894
sha: 3bb1870471a51097231fab7e5e8c375224110d03
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_agent_contract.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_agent_contract.py

## File: tests/test_dashboard.py
size: 9600
sha: 56edb5fad7ab8d96d3742673cef40fbec152aa5f
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_dashboard.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_dashboard.py

## File: tests/test_deutsch_loop.py
size: 55401
sha: 393b8351d36804a47ff925ef2da23068227bac9e
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_deutsch_loop.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_deutsch_loop.py

## File: tests/test_learning_loop.py
size: 19482
sha: 4148e0ce5b889f9c160c8f4de1c39c37fa5ca505
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_learning_loop.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_learning_loop.py

## File: tests/test_missions.py
size: 19271
sha: 0db9341134a72c811e904c4a96d0e04c6ad533f8
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_missions.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_missions.py

## File: tests/test_onboarding.py
size: 10604
sha: e1bd4bba92e80476c072a397f3fdf5c7c5be74f4
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_onboarding.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_onboarding.py

## File: tests/test_packaging.py
size: 5981
sha: c65005e84d567cd3e8c30268c82f77a726180808
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_packaging.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_packaging.py

## File: tests/test_speaking.py
size: 26757
sha: c33aec3dec6a4bad4c7d34b130a7a9cdd7c13fc5
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_speaking.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_speaking.py

## File: tests/test_vocabulary.py
size: 17429
sha: aeb6b7f8f31638aca4d9f00e9b84a8cdb33066e9
upstream: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_vocabulary.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/ahmtsahin/deutsch-loop/blob/HEAD/tests/test_vocabulary.py
