Skip to content

Commit 17deb61

Browse files
committed
Add spaced-repetition flashcards, quiz mode, and run history cap
- mentor cards <learner> --add/--generate to build cards from a session - mentor quiz <learner> reviews due cards with an SM-2-lite scheduler - new scripts/mentor_cards.py and templates/cards_prompt.md - mentor run keeps only the last --history-turns turns in context
1 parent 9e930dd commit 17deb61

5 files changed

Lines changed: 489 additions & 4 deletions

File tree

‎SKILL.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ Commands:
128128
| `mentor learners` | list persisted learner profiles |
129129
| `mentor progress NAME [...]` | view/update a learner's mastered/shaky/misconception lists |
130130
| `mentor review NAME [--apply]` | assess the latest transcript and update the learner profile |
131+
| `mentor cards NAME [--add "Q :: A"] [--generate]` | manage spaced-repetition flashcards |
132+
| `mentor quiz NAME [--all] [--n N]` | review due flashcards (again/hard/good/easy) |
131133
| `mentor sessions [NAME]` | list recorded sessions |
132134
| `mentor transcript ID` | print a session transcript |
133135
| `mentor fields` | list curated field profiles |
@@ -235,6 +237,20 @@ next lesson), and merges it — promoting anything newly mastered out of *shaky*
235237
This closes the loop: run → transcript → assessment → updated profile, with no
236238
manual bookkeeping.
237239

240+
**Spaced repetition.** Turn a session into flashcards and review them over time:
241+
242+
```bash
243+
mentor cards rust --generate # build cards from the latest session
244+
mentor cards rust --add "What is ownership? :: Each value has one owner."
245+
mentor cards rust # list, with due counts
246+
mentor quiz rust # review what is due (again/hard/good/easy)
247+
mentor quiz rust --all --n 20 # review ahead
248+
```
249+
250+
Cards use an SM-2-lite scheduler (interval, ease, reps) stored in
251+
`~/.config/expert-mentor/learners/<name>.cards.json`, so review scheduling
252+
carries across sessions and machines.
253+
238254
## Step 4 — Run the session (or hand off the prompt)
239255

240256
If teaching inline, obey the loaded prompt's **Teaching Contract** without
@@ -261,9 +277,11 @@ the temperature (the script prints a recommended value).
261277
- `templates/compact_prompt.md` — short variant for small local models.
262278
- `templates/curriculum_prompt.md` — curriculum-designer prompt.
263279
- `templates/review_prompt.md` — session-assessment (progress review) prompt.
280+
- `templates/cards_prompt.md` — flashcard-generation prompt.
264281
- `scripts/expert_mentor.py` — the CLI: provider-aware prompt/Modelfile/JSON generator.
265282
- `scripts/mentor_runtime.py` — dependency-free streaming chat adapters (Ollama, llama.cpp, OpenAI, Anthropic).
266283
- `scripts/mentor_memory.py` — persistent learner profiles and session transcripts.
284+
- `scripts/mentor_cards.py` — spaced-repetition flashcards (SM-2-lite scheduler).
267285
- `scripts/selftest.py` — dependency-free test suite (`make test`).
268286
- `references/pedagogy.md` — the teaching methods the mentor draws on.
269287
- `references/fields.md` — curated field profiles + how to add your own.

‎scripts/expert_mentor.py‎

Lines changed: 212 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import argparse
2020
import json
2121
import os
22+
import random
2223
import re
2324
import shutil
2425
import subprocess
@@ -30,13 +31,15 @@
3031
try:
3132
import mentor_runtime
3233
import mentor_memory
34+
import mentor_cards
3335
except ImportError: # when imported without scripts/ on sys.path
3436
sys.path.insert(0, str(Path(__file__).resolve().parent))
3537
import mentor_runtime
3638
import mentor_memory
39+
import mentor_cards
3740

3841
APP_NAME = "expert-mentor"
39-
__version__ = "0.5.0"
42+
__version__ = "0.6.0"
4043

4144

4245
def _resource_dir(*parts: str) -> Path:
@@ -629,6 +632,10 @@ def get_memory() -> "mentor_memory.Memory":
629632
return mentor_memory.Memory(CONFIG_DIR)
630633

631634

635+
def get_card_store() -> "mentor_cards.CardStore":
636+
return mentor_cards.CardStore(CONFIG_DIR)
637+
638+
632639
def shape_prompt(text: str, provider: str, mode: str = "auto") -> str:
633640
"""Adapt the prompt to the target model's preferred structure.
634641
@@ -1132,6 +1139,197 @@ def run_review_command(rest: List[str]) -> int:
11321139
return 0
11331140

11341141

1142+
def _cards_system_prompt(field_name: str, provider: str) -> str:
1143+
path = TEMPLATES_DIR / "cards_prompt.md"
1144+
text = extract_prompt(path.read_text(encoding="utf-8"))
1145+
profile = resolve_profile(field_name, load_profiles()) if field_name else None
1146+
values = {
1147+
"MENTOR_NAME": (profile.mentor_name if profile and profile.mentor_name
1148+
else (generate_mentor_name(field_name) if field_name else "the teacher")),
1149+
"FIELD": field_name or "the subject",
1150+
"CAPABILITY_NOTES": PROVIDERS[provider].capability_notes,
1151+
}
1152+
return render(text, values)
1153+
1154+
1155+
def run_cards_command(rest: List[str]) -> int:
1156+
parser = argparse.ArgumentParser(
1157+
prog="mentor cards", add_help=True,
1158+
description="Manage spaced-repetition flashcards for a learner.")
1159+
parser.add_argument("learner")
1160+
parser.add_argument("--add", metavar="FRONT :: BACK", help="add a card manually")
1161+
parser.add_argument("--tags", default="", help="comma-separated tags for --add")
1162+
parser.add_argument("--generate", action="store_true", help="build cards from the latest session")
1163+
parser.add_argument("--session", help="specific session id for --generate")
1164+
parser.add_argument("--remove", metavar="ID", help="remove a card by id")
1165+
parser.add_argument("--reset", action="store_true", help="delete all cards for the learner")
1166+
parser.add_argument("--provider", choices=PROVIDER_CHOICES)
1167+
parser.add_argument("--model")
1168+
parser.add_argument("--host")
1169+
parser.add_argument("--temperature", type=float)
1170+
parser.add_argument("--dry-run", action="store_true", help="show the generation prompt, call nothing")
1171+
opts = parser.parse_args(rest)
1172+
store = get_card_store()
1173+
1174+
if opts.reset:
1175+
store.save(opts.learner, [])
1176+
print(f"cleared cards for '{opts.learner}'")
1177+
return 0
1178+
if opts.remove:
1179+
print("removed" if store.remove(opts.learner, opts.remove) else "no such card")
1180+
return 0
1181+
if opts.add:
1182+
if "::" not in opts.add:
1183+
print('expected: --add "FRONT :: BACK"', file=sys.stderr)
1184+
return 2
1185+
front, _, back = opts.add.partition("::")
1186+
tags = [t.strip() for t in opts.tags.split(",") if t.strip()]
1187+
card = store.add(opts.learner, front, back, tags)
1188+
print(f"added card {card.id}: {card.front}")
1189+
return 0
1190+
if opts.generate:
1191+
return _generate_cards(opts, store)
1192+
1193+
cards = store.load(opts.learner)
1194+
stats = store.stats(opts.learner)
1195+
if not cards:
1196+
print(f"no cards for '{opts.learner}' yet. Try:")
1197+
print(f' mentor cards {opts.learner} --add "What is ownership? :: ..."')
1198+
print(f" mentor cards {opts.learner} --generate")
1199+
return 0
1200+
print(f"{opts.learner}: {stats['total']} cards · {stats['due']} due · {stats['learned']} learned"
1201+
f" · {stats['lapses']} lapses\n")
1202+
for card in cards:
1203+
mark = "*" if card.is_due() else " "
1204+
done = f"due {card.due[:10]}"
1205+
print(f" [{mark}] {card.id} {card.front} (reps={card.reps}, {done})")
1206+
print("\n* = due now. Review with: mentor quiz " + opts.learner)
1207+
return 0
1208+
1209+
1210+
def _generate_cards(opts: argparse.Namespace, store: "mentor_cards.CardStore") -> int:
1211+
memory = get_memory()
1212+
if opts.session:
1213+
path = memory.transcript_path(opts.session)
1214+
else:
1215+
sessions = memory.list_sessions(opts.learner)
1216+
if not sessions:
1217+
print(f"no sessions recorded for '{opts.learner}' — run a session first", file=sys.stderr)
1218+
return 1
1219+
path = memory.transcript_path(sessions[-1]["id"])
1220+
if path is None:
1221+
print("could not find a transcript to generate from", file=sys.stderr)
1222+
return 1
1223+
1224+
meta: Dict = {}
1225+
meta_path = path.with_suffix(".json")
1226+
if meta_path.exists():
1227+
try:
1228+
meta = json.loads(meta_path.read_text(encoding="utf-8"))
1229+
except json.JSONDecodeError:
1230+
meta = {}
1231+
learner = memory.load(opts.learner)
1232+
field_name = (learner.field if learner else "") or meta.get("field", "")
1233+
1234+
provider = canonical_provider(opts.provider or meta.get("provider") or "ollama")
1235+
if provider not in ("ollama", "llamacpp", "openai", "anthropic"):
1236+
print(f"provider '{provider}' has no runtime backend; pass --provider", file=sys.stderr)
1237+
return 2
1238+
model = opts.model or meta.get("model") or mentor_runtime.DEFAULT_MODELS.get(provider, "")
1239+
temperature = opts.temperature if opts.temperature is not None else 0.3
1240+
system = _cards_system_prompt(field_name, provider)
1241+
transcript = path.read_text(encoding="utf-8")
1242+
1243+
if opts.dry_run:
1244+
print("=== system ===")
1245+
print(system)
1246+
print("\n=== user (transcript) ===")
1247+
print(transcript)
1248+
return 0
1249+
1250+
kwargs: Dict = {}
1251+
if provider in ("ollama", "llamacpp") and opts.host:
1252+
kwargs["host"] = opts.host
1253+
try:
1254+
raw = mentor_runtime.complete(provider, model, system,
1255+
[{"role": "user", "content": transcript}],
1256+
temperature=temperature, **kwargs)
1257+
except mentor_runtime.MentorRuntimeError as exc:
1258+
print(f"[error] {exc}", file=sys.stderr)
1259+
return 1
1260+
1261+
data = mentor_memory.extract_json(raw)
1262+
if not data or not isinstance(data.get("cards"), list):
1263+
print("could not parse flashcards from the model output. Raw output:\n")
1264+
print(raw)
1265+
return 1
1266+
1267+
added = 0
1268+
for item in data["cards"]:
1269+
if not isinstance(item, dict):
1270+
continue
1271+
front = str(item.get("front", "")).strip()
1272+
back = str(item.get("back", "")).strip()
1273+
if front and back:
1274+
store.add(opts.learner, front, back, item.get("tags") or [])
1275+
added += 1
1276+
print(f"generated {added} card(s) for '{opts.learner}' (from {path.name})")
1277+
print(f"review with: mentor quiz {opts.learner}")
1278+
return 0
1279+
1280+
1281+
def run_quiz_command(rest: List[str]) -> int:
1282+
parser = argparse.ArgumentParser(
1283+
prog="mentor quiz", add_help=True,
1284+
description="Review due flashcards with spaced repetition.")
1285+
parser.add_argument("learner")
1286+
parser.add_argument("--n", type=int, default=10, help="maximum cards this session (default: 10)")
1287+
parser.add_argument("--all", action="store_true", help="include cards that are not due yet")
1288+
parser.add_argument("--shuffle", action="store_true", help="randomise the order")
1289+
opts = parser.parse_args(rest)
1290+
1291+
store = get_card_store()
1292+
cards = store.load(opts.learner)
1293+
queue = cards if opts.all else [c for c in cards if c.is_due()]
1294+
if opts.shuffle:
1295+
random.shuffle(queue)
1296+
queue = queue[:max(0, opts.n)]
1297+
1298+
if not queue:
1299+
stats = store.stats(opts.learner)
1300+
if stats["total"] == 0:
1301+
print(f"no cards for '{opts.learner}'. Create some with 'mentor cards {opts.learner} --generate'.")
1302+
else:
1303+
print(f"nothing due for '{opts.learner}' ({stats['total']} cards). Use --all to review anyway.")
1304+
return 0
1305+
1306+
print(f"quiz · {opts.learner} · {len(queue)} card(s)\n")
1307+
reviewed = 0
1308+
try:
1309+
for index, card in enumerate(queue, 1):
1310+
print(f"[{index}/{len(queue)}] {card.front}")
1311+
try:
1312+
input(" (Enter to reveal) ")
1313+
except EOFError:
1314+
break
1315+
print(f" → {card.back}")
1316+
try:
1317+
raw = input(" grade [again/hard/good/easy] (Enter=good, q=quit): ").strip().lower()
1318+
except EOFError:
1319+
raw = "good"
1320+
if raw in ("q", "quit", "exit"):
1321+
break
1322+
grade = raw if raw in mentor_cards.GRADES else "good"
1323+
mentor_cards.review(card, grade)
1324+
reviewed += 1
1325+
print()
1326+
except KeyboardInterrupt:
1327+
print()
1328+
store.save(opts.learner, cards)
1329+
print(f"reviewed {reviewed} card(s). Next due dates updated.")
1330+
return 0
1331+
1332+
11351333
def _load_saved_prompt(name: str) -> tuple:
11361334
slug = slugify(name)
11371335
path = PROMPTS_DIR / f"{slug}.md"
@@ -1272,9 +1470,11 @@ def run_run_command(rest: List[str]) -> int:
12721470
return 0
12731471

12741472
def turn(messages: List[Dict]) -> tuple:
1473+
limit = max(2, args.history_turns * 2)
1474+
payload = messages[-limit:] if len(messages) > limit else messages
12751475
chunks: List[str] = []
12761476
usage: Dict = {}
1277-
for event in mentor_runtime.stream(provider, model, system_prompt, messages,
1477+
for event in mentor_runtime.stream(provider, model, system_prompt, payload,
12781478
temperature=temperature, max_tokens=args.max_tokens,
12791479
**kwargs):
12801480
kind = event.get("type")
@@ -1353,7 +1553,8 @@ def save_progress(session_messages: List[Dict]) -> None:
13531553

13541554
COMMANDS = ("version", "fields", "providers", "doctor", "interactive", "prompt",
13551555
"save", "show", "saved", "ollama", "curriculum", "run", "models",
1356-
"learners", "progress", "sessions", "transcript", "review", "config")
1556+
"learners", "progress", "sessions", "transcript", "review", "config",
1557+
"cards", "quiz")
13571558

13581559

13591560
# --------------------------------------------------------------------------- #
@@ -1373,7 +1574,8 @@ def build_parser() -> argparse.ArgumentParser:
13731574
" mentor run --field 'Rust' --provider chatgpt --remember\n"
13741575
" mentor curriculum --field 'Rust' --duration '6 weeks'\n"
13751576
" mentor models --provider claude --refresh\n"
1376-
" mentor learners | progress <name> | sessions | review <name>\n"
1577+
" mentor learners | progress <name> | review <name> | quiz <name>\n"
1578+
" mentor cards <name> [--add \"Q :: A\"] [--generate]\n"
13771579
" mentor config | fields | providers | saved | doctor | interactive | version\n",
13781580
)
13791581
p.add_argument("--version", action="version", version=f"{APP_NAME} {__version__}")
@@ -1423,6 +1625,8 @@ def build_parser() -> argparse.ArgumentParser:
14231625
help="Anthropic: do not mark the system prompt for prompt caching")
14241626
p.add_argument("--show-thinking", action="store_true",
14251627
help="'run': show model reasoning/thinking as it streams (dimmed, stderr)")
1628+
p.add_argument("--history-turns", type=int, default=40,
1629+
help="'run': max past turns kept in context (default: 40)")
14261630
# persistent learner
14271631
p.add_argument("--learner", default=cfg.get("learner"),
14281632
help="'run'/'prompt': load and update a named learner profile")
@@ -1486,6 +1690,10 @@ def main(argv: Optional[List[str]] = None) -> int:
14861690
return run_transcript_command(rest)
14871691
elif command == "review":
14881692
return run_review_command(rest)
1693+
elif command == "cards":
1694+
return run_cards_command(rest)
1695+
elif command == "quiz":
1696+
return run_quiz_command(rest)
14891697
elif command == "config":
14901698
return run_config_command(rest)
14911699
elif command == "curriculum":

0 commit comments

Comments
 (0)