keepfold 0.6.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/levels.py ADDED
@@ -0,0 +1,595 @@
1
+ """Levels as pure folds over events (SPEC §5, §15a.13, §15a.15-16, §15a.21, §0 U1).
2
+
3
+ Nothing here is stored: every state is recomputed from the event log on demand.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import hashlib
10
+ from collections.abc import Iterable, Iterator
11
+ from dataclasses import dataclass, field, replace
12
+ from datetime import UTC, date, datetime, time, timedelta
13
+
14
+ from fsrs import Card, Rating, Scheduler, State
15
+
16
+ from keepfold import events as _events
17
+ from keepfold.events import EventLog
18
+
19
+ STATES = ("not_started", "unverified", "learning", "needs_refresh", "solid")
20
+ GLYPH = {"not_started": "○", "unverified": "◌", "learning": "◐", "needs_refresh": "↻",
21
+ "solid": "●"}
22
+ LABEL = {"not_started": "Not started", "unverified": "Unverified", "learning": "Learning",
23
+ "needs_refresh": "Needs refresh", "solid": "Solid"}
24
+ RETENTION, HIGH_RETENTION = 0.85, 0.90
25
+ RESOLVE_EXPOSURES, RESOLVE_DAYS = 3, 2
26
+ SOLID_STABILITY, SOLID_PASS_DAYS = 10.0, 2 # Solid needs FSRS stability ≥ 10 d and 2 pass days
27
+ SOLID_GAP_DAYS = 7 # (default) Solid also needs a pass day ≥ 7 days after the first pass day
28
+ SOLID_REST_DAYS = 3 # (default) ... and ≥ 3 days after the previous graded day
29
+ REMEDIATION_MAX_STABILITY = 10.0 # wrong-then-fixed is Hard only below this stability
30
+ JITTER = 0.05 # deterministic ± spread of due dates for intervals ≥ 3 d
31
+ DEPTH = ("application", "transfer")
32
+ # `log` payload kinds _items folds into learning evidence; keep in step with its checks.
33
+ # The planner's warm-up gap counts only these logs, not always-on ledger lines (touch, need...).
34
+ EVIDENCE_LOG_KINDS = ("taught", "self_report", "problem_status")
35
+ LEECH_LAPSES = 5 # Anki's leech: forgotten this often after it was learned; rewrite, don't drill
36
+
37
+
38
+ @dataclass
39
+ class ConceptState:
40
+ id: str
41
+ state: str = "not_started"
42
+ stability: float | None = None
43
+ pass_days: int = 0
44
+ depth_pass: bool = False
45
+ last_pass_day: str | None = None
46
+ interval_days: int | None = None
47
+ next_due: str | None = None
48
+ retrievability: float | None = None
49
+ last_review: datetime | None = None # the FSRS card's last review (in memory only)
50
+ open_mistakes: list[str] = field(default_factory=list)
51
+ unchecked: bool = False
52
+ last_taught_day: str | None = None # local day of the latest `taught` event
53
+ asked_not_graded: int = 0
54
+ attempts: int = 0
55
+ last_seen: str | None = None
56
+ confident_miss: str | None = None # day of a recent confidence-4 wrong not yet passed
57
+ gap_pass: bool = False # a pass day ≥ SOLID_GAP_DAYS after the first, ≥ SOLID_REST_DAYS rest
58
+ solid_after: str | None = None # only the gap blocks Solid: a pass from this day would do
59
+ lapses: int = 0 # days rated Again after the card was learned (`_schedule`); never cleared
60
+
61
+
62
+ def is_leech(st) -> bool:
63
+ return getattr(st, "lapses", 0) >= LEECH_LAPSES
64
+
65
+
66
+ def gap_note(st) -> str:
67
+ """The learner-facing reason when only the gap rule keeps a concept from Solid."""
68
+ when = getattr(st, "solid_after", None)
69
+ return f"one more check after a break (from {when})" if when else ""
70
+
71
+
72
+ @dataclass
73
+ class MistakeState:
74
+ id: str
75
+ status: str = "open"
76
+ count: int = 0
77
+ last_day: str | None = None
78
+ concepts: list[str] = field(default_factory=list)
79
+ exposures: list[str] = field(default_factory=list, repr=False) # days since last occurrence
80
+
81
+
82
+ @dataclass
83
+ class _Item:
84
+ """One normalised event: the concept it lands on and its verdict, if any."""
85
+ ev: dict
86
+ concept: str | None
87
+ verdict: str | None = None
88
+ hints: int = 0
89
+ confidence: int | None = None
90
+ taught: bool = False
91
+ item_type: str | None = None # recall | application | transfer; None reads as recall
92
+ also: list[str] = field(default_factory=list) # secondary concepts a correct credits
93
+ credit: bool = False # an `also` copy on a secondary concept: one Hard review, nothing else
94
+ warm: bool = False # the concept was already taught or exercised earlier this local day
95
+ primed: bool = False # ... taught or `also`-credited, not just graded (ends the cold block)
96
+
97
+
98
+ def _prefixed(value, prefix: str) -> str | None:
99
+ if not isinstance(value, str) or not value:
100
+ return None
101
+ return value if ":" in value else f"{prefix}:{value}"
102
+
103
+
104
+ def placed(events: Iterable[dict]) -> list[dict]:
105
+ """The live events in (ts, id) order, each regrade (a self_report whose payload
106
+ `regrade_of` names a voided grade: a spot-check flip, written by the server) moved to that
107
+ grade's day, ts and place, so a verdict fixed later rates the day it was answered (B4)."""
108
+ raw = sorted(events, key=lambda e: (e["ts"], e["id"]))
109
+ voided = {e.get("ref") for e in raw if e.get("kind") == "void"}
110
+ grades = {e["id"]: e for e in raw if e.get("kind") == "grade" and e["id"] in voided}
111
+ out = []
112
+ for e in _events.live(raw):
113
+ pl = e.get("payload")
114
+ r = pl.get("regrade_of") if e.get("kind") == "log" and isinstance(pl, dict) \
115
+ and pl.get("kind") == "self_report" else None
116
+ o = grades.get(r) if isinstance(r, str) else None
117
+ out.append(((o or e)["ts"], (o or e)["id"],
118
+ {**e, "day": o["day"], "ts": o["ts"]} if o else e))
119
+ return [e for *_, e in sorted(out, key=lambda t: t[:2])]
120
+
121
+
122
+ def _items(events: Iterable[dict], problem_concepts: dict[str, str | list[str]] | None,
123
+ ) -> Iterator[_Item]:
124
+ """Apply void, regrade and remap, resolve each event's concept, and pull out its verdict."""
125
+ evs = placed(events)
126
+ remap = {e["ref"]: e["object"] for e in evs
127
+ if e.get("kind") == "remap" and e.get("ref") and e.get("object")}
128
+ asks = {e["id"]: e for e in evs if e.get("kind") == "ask"}
129
+ problems = problem_concepts or {}
130
+ touched: set[tuple[str | None, str | None]] = set() # (concept, day) taught or graded
131
+ primed: set[tuple[str | None, str | None]] = set() # (concept, day) taught or also-credited
132
+ solved: dict[str, str] = {} # problem id -> first day it had a correct item
133
+ graded: set[tuple[str | None, str | None]] = set() # (problem id, day) with a grade
134
+
135
+ def follow(obj: str | None) -> str | None:
136
+ seen = set()
137
+ while obj in remap and obj not in seen: # transitive, cycle-safe
138
+ seen.add(obj)
139
+ obj = remap[obj]
140
+ return obj
141
+
142
+ def concept_of(obj: str | None) -> str | None:
143
+ obj = follow(obj)
144
+ return obj.split(":", 1)[1] if isinstance(obj, str) and obj.startswith(
145
+ "concept:") else None
146
+
147
+ def linked(pid: str | None) -> list[str]: # a problem's concepts, primary first
148
+ cs = problems.get(pid.split(":", 1)[1]) if pid else None
149
+ return [cs] if isinstance(cs, str) else list(cs or [])
150
+
151
+ for ev in evs:
152
+ kind = ev.get("kind")
153
+ if kind in ("remap", "resume", "close", "open", "change"):
154
+ continue
155
+ if kind == "grade" and ev.get("ref") in asks: # grade of a registered ask item
156
+ ask = asks[ev["ref"]]
157
+ ev = {**{k: ask[k] for k in ("object", "problem", "also", "targets_mistakes",
158
+ "item_type") if k in ask}, **ev}
159
+ if ask.get("targets_mistakes"): # a grade may name its own too: take the union
160
+ ev["targets_mistakes"] = list(dict.fromkeys(
161
+ [*ask["targets_mistakes"], *(ev.get("targets_mistakes") or [])]))
162
+ payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
163
+ pkind = payload.get("kind") if kind == "log" else None
164
+ if pkind is not None and pkind not in EVIDENCE_LOG_KINDS:
165
+ pkind = None # touch, need, journal...: never taught, verdict or problem evidence
166
+
167
+ def get(name, ev=ev, payload=payload):
168
+ return ev.get(name, payload.get(name))
169
+
170
+ obj = (ev.get("object") or _prefixed(payload.get("concept"), "concept")
171
+ or ev.get("problem") or _prefixed(payload.get("problem"), "problem"))
172
+ obj = follow(obj)
173
+ on_problem = isinstance(obj, str) and obj.startswith("problem:")
174
+ pid = obj if on_problem else _prefixed(get("problem"), "problem")
175
+ concept = concept_of(_prefixed((linked(pid) or [None])[0], "concept") if on_problem
176
+ else obj)
177
+ raw = get("also") if isinstance(get("also"), list) else []
178
+ also = [concept_of(_prefixed(a, "concept")) for a in [*raw, *linked(pid)[1:]]]
179
+
180
+ item = _Item(ev, concept, taught=kind == "taught" or pkind == "taught",
181
+ also=[a for a in dict.fromkeys(also) if a and a != concept])
182
+ day = ev.get("day")
183
+ if kind == "grade" or pkind == "self_report":
184
+ item.verdict = get("verdict")
185
+ graded.add((pid, day))
186
+ elif pkind == "problem_status" and payload.get("status") == "solved":
187
+ # after that day's graded answer (a mock code phase) it is bookkeeping (board L2)
188
+ item.verdict = None if pid and (pid, day) in graded else "correct"
189
+ elif pkind == "problem_status" and payload.get("status") == "todo":
190
+ continue # a plan, not evidence
191
+ if item.verdict not in ("correct", "partial", "wrong"):
192
+ item.verdict = None
193
+ item.hints = get("hints") if isinstance(get("hints"), int) else 0
194
+ item.confidence = get("confidence")
195
+ item.item_type = ev.get("item_type")
196
+ if item.item_type is None and (get("problem") or pkind == "problem_status"):
197
+ # solving a problem applies the concept; re-solving one already solved correctly
198
+ # on an earlier day recalls a remembered solution (LEARN-7)
199
+ item.item_type = ("recall" if day and pid in solved and solved[pid] < day
200
+ else "application")
201
+ if kind != "ask":
202
+ item.warm = (concept, day) in touched
203
+ item.primed = (concept, day) in primed
204
+ if item.taught or item.verdict is not None:
205
+ touched.add((concept, day))
206
+ if item.taught:
207
+ primed.add((concept, day))
208
+ if item.verdict == "correct":
209
+ touched.update((a, day) for a in item.also)
210
+ primed.update((a, day) for a in item.also)
211
+ if pid:
212
+ solved.setdefault(pid, day)
213
+ yield item
214
+
215
+
216
+ def _score(it: _Item) -> float:
217
+ if it.verdict == "correct":
218
+ return 1.0 if it.hints <= 1 else 0.5
219
+ return 0.5 if it.verdict == "partial" else 0.0
220
+
221
+
222
+ def _rating(it: _Item) -> Rating:
223
+ if it.verdict == "wrong":
224
+ return Rating.Again
225
+ if it.verdict == "partial" or it.hints >= 2:
226
+ return Rating.Hard
227
+ if it.hints == 0 and (it.confidence == 4 or (
228
+ it.item_type == "transfer" and isinstance(it.confidence, int) and it.confidence >= 3)):
229
+ return Rating.Easy
230
+ return Rating.Good
231
+
232
+
233
+ def _pass_day(primary: list[_Item]) -> bool:
234
+ """Primary share ≥ 0.8 and no confidence-4 wrong."""
235
+ return (sum(map(_score, primary)) / len(primary) >= 0.8
236
+ and not any(i.verdict == "wrong" and i.confidence == 4 for i in primary))
237
+
238
+
239
+ def _review_at(day: str) -> datetime:
240
+ """One FSRS review per local day at 12:00 UTC of that day, so consecutive days are exactly
241
+ 1 d apart (py-fsrs floors elapsed days; under 24 h is a same-day review)."""
242
+ return datetime.combine(date.fromisoformat(day), time(12), UTC)
243
+
244
+
245
+ def _cold_block(primary: list[_Item]) -> list[_Item]:
246
+ """The leading primary items before the first teaching (a `taught` or `also` credit on
247
+ the concept that day); empty when the day starts warm."""
248
+ if primary[0].warm:
249
+ return []
250
+ n = 1
251
+ while n < len(primary) and not primary[n].primed:
252
+ n += 1
253
+ return primary[:n]
254
+
255
+
256
+ def _day_rating(items: list[_Item], card: Card) -> Rating:
257
+ """Rate the day by its cold retrieval (LEARN-2, G1): the cold block is every primary item
258
+ before the first teaching that day (a `taught` or `also` credit on the concept), starting
259
+ only when nothing on the concept came earlier that local day. Later quiz questions are
260
+ usually different questions, not retries, so the block is rated by its pass share: all Easy
261
+ → Easy, ≥ 0.8 → Good, ≥ 0.5 → Hard, else Again; items after the teaching do not cap it.
262
+ Items after teaching follow it, so they do not measure retention across the gap. A single
263
+ cold item is rated alone (hints ≥ 2 already make it Hard), and Good/Easy on a day that is
264
+ not a pass day is capped at Hard. With no cold item (taught first) the worst primary rating
265
+ is used, as before. A day of `also` credit only is Hard. A day with a confidence-4 wrong is
266
+ Again: a confident miss is never softened, so it never lengthens the interval. A wrong
267
+ fixed later the same day (last primary correct at hints ≤ 1, after the cold block) is Hard
268
+ while the card is new or below REMEDIATION_MAX_STABILITY and the last review is under
269
+ SOLID_GAP_DAYS old: Hard after a long gap is read by FSRS as a hard-won recall at low R and
270
+ inflates stability, so a lapse across a gap or on a mature card stays Again. The same guards
271
+ hold inside the block: a Hard share that includes a wrong is Again across a gap or on a
272
+ mature card (a cold right-then-wrong pair is still a lapse there)."""
273
+ primary = [i for i in items if not i.credit]
274
+ if not primary:
275
+ return Rating.Hard
276
+ if any(i.verdict == "wrong" and i.confidence == 4 for i in primary):
277
+ return Rating.Again
278
+ after_gap = card.last_review is not None and ( # last_review is `_review_at` its day
279
+ date.fromisoformat(primary[0].ev["day"]) - card.last_review.date()).days >= SOLID_GAP_DAYS
280
+ guarded = after_gap or (card.stability or 0) >= REMEDIATION_MAX_STABILITY
281
+ batch = _cold_block(primary)
282
+ if len(batch) >= 2:
283
+ share = sum(map(_score, batch)) / len(batch)
284
+ rating = (Rating.Easy if all(_rating(i) == Rating.Easy for i in batch)
285
+ else Rating.Good if share >= 0.8
286
+ else Rating.Hard if share >= 0.5 else Rating.Again)
287
+ if rating == Rating.Hard and guarded and any(i.verdict == "wrong" for i in batch):
288
+ rating = Rating.Again # a lapse in the block: the same guards as remediation
289
+ elif primary[0].warm:
290
+ rating = min(map(_rating, primary))
291
+ else:
292
+ rating = _rating(primary[0])
293
+ if rating > Rating.Hard and not _pass_day(primary):
294
+ rating = Rating.Hard
295
+ if (rating == Rating.Again and len(primary) > len(batch) # the fix came after the block
296
+ and primary[-1].verdict == "correct" and primary[-1].hints <= 1
297
+ and not guarded):
298
+ return Rating.Hard
299
+ return rating
300
+
301
+
302
+ def _schedule(per_day: dict[str, list[_Item]], retention: float = RETENTION,
303
+ ) -> tuple[Scheduler, Card, int]:
304
+ """One FSRS-6 card replayed with one review per local day (see `_day_rating`), and its
305
+ lapses: days rated Again on a card in Review state that had a day rated above Again before.
306
+ With no learning steps py-fsrs puts a card in Review after its first day whatever the
307
+ rating, so the earlier non-Again day is what marks it learned (a miss while learning is not
308
+ a lapse)."""
309
+ scheduler = Scheduler(desired_retention=retention, learning_steps=(), relearning_steps=(),
310
+ enable_fuzzing=False)
311
+ card = Card(card_id=1)
312
+ lapses, learned = 0, False
313
+ for day in sorted(per_day):
314
+ rating = _day_rating(per_day[day], card)
315
+ lapses += rating == Rating.Again and learned and card.state == State.Review
316
+ learned = learned or rating != Rating.Again
317
+ card, _ = scheduler.review_card(card, rating, _review_at(day))
318
+ return scheduler, card, lapses
319
+
320
+
321
+ def _jitter(concept: str, review_count: int, interval: int) -> int:
322
+ """Days to shift a due date: ±JITTER of the interval, seeded by sha256 (`hash()` changes
323
+ per process), only for intervals of 3 days or more."""
324
+ if interval < 3:
325
+ return 0
326
+ u = int(hashlib.sha256(f"{concept}:{review_count}".encode()).hexdigest()[:8], 16) / 0xFFFFFFFF
327
+ return round(interval * (2 * u - 1) * JITTER)
328
+
329
+
330
+ def _credit(it: _Item, concept: str) -> _Item:
331
+ return replace(it, concept=concept, verdict=None, also=[], credit=True)
332
+
333
+
334
+ def _retrievability(scheduler: Scheduler, card: Card, now: datetime) -> float:
335
+ """FSRS-6 forgetting curve over fractional elapsed days (py-fsrs floors to whole days,
336
+ so a review under 24 h ago would read R = 1)."""
337
+ if card.last_review is None or card.stability is None:
338
+ return 0.0
339
+ t = max((now - card.last_review).total_seconds() / 86400, 0.0)
340
+ decay = -scheduler.parameters[20]
341
+ factor = 0.9 ** (1 / decay) - 1
342
+ return (1 + factor * t / card.stability) ** decay
343
+
344
+
345
+ _CURVE = Scheduler() # default FSRS-6 parameters: retention changes intervals, not the curve
346
+
347
+
348
+ def recall_at(st: ConceptState | None, when: datetime) -> float:
349
+ """Retrievability of the fold's card (unjittered) at `when`; 0 with no reviews (no memory
350
+ to forecast; `predicted_p` keeps its 0.5 prior for single-item forecasts)."""
351
+ if st is None or st.last_review is None or st.stability is None:
352
+ return 0.0
353
+ card = Card(card_id=1, stability=st.stability, last_review=st.last_review)
354
+ return _retrievability(_CURVE, card, when.replace(tzinfo=UTC) if when.tzinfo is None else when)
355
+
356
+
357
+ def fold(events: Iterable[dict], today: str,
358
+ problem_concepts: dict[str, str | list[str]] | None = None,
359
+ high_retention: set[str] | None = None,
360
+ ) -> tuple[dict[str, ConceptState], dict[str, MistakeState]]:
361
+ """Replay events into concept and mistake states as of local day `today`.
362
+
363
+ `problem_concepts` maps a problem id to its concepts (primary first) or just its primary.
364
+
365
+ Concepts in `high_retention` (tested by an exam soon) are scheduled at 0.90, others 0.85.
366
+ """
367
+ events = list(events)
368
+ concepts: dict[str, ConceptState] = {}
369
+ mistakes: dict[str, MistakeState] = {}
370
+ days: dict[str, dict[str, list[_Item]]] = {} # concept -> day -> verdict/credit items
371
+ evidence: set[str] = set()
372
+ last_taught: dict[str, int] = {}
373
+ last_verdict: dict[str, int] = {}
374
+ # a voided grade still settles its ask (B1): a void or a flip must not reopen it for good
375
+ graded_asks = {e.get("ref") for e in events if e.get("kind") == "grade"}
376
+ asks: list[_Item] = []
377
+
378
+ for n, it in enumerate(_items(events, problem_concepts)):
379
+ ev, c = it.ev, it.concept
380
+ kind, day = ev.get("kind"), ev.get("day")
381
+ if c is None:
382
+ st = None
383
+ else:
384
+ st = concepts.setdefault(c, ConceptState(c))
385
+ st.last_seen = max(filter(None, (st.last_seen, day)), default=None)
386
+ if kind == "ask":
387
+ asks.append(it)
388
+ continue
389
+ if c is not None:
390
+ evidence.add(c)
391
+ if it.taught and c is not None:
392
+ last_taught[c] = n
393
+ st.last_taught_day = day
394
+ if it.verdict is None:
395
+ continue
396
+ if st is not None:
397
+ st.attempts += 1
398
+ last_verdict[c] = n
399
+ days.setdefault(c, {}).setdefault(day, []).append(it)
400
+ if it.verdict == "correct": # a wrong never touches the also-concepts
401
+ for a in it.also:
402
+ sa = concepts.setdefault(a, ConceptState(a))
403
+ sa.last_seen = max(filter(None, (sa.last_seen, day)), default=None)
404
+ evidence.add(a)
405
+ days.setdefault(a, {}).setdefault(day, []).append(_credit(it, a))
406
+ if it.verdict in ("wrong", "partial"):
407
+ for m in ev.get("mistakes") or []:
408
+ ms = mistakes.setdefault(m, MistakeState(m))
409
+ ms.status, ms.count, ms.last_day, ms.exposures = "open", ms.count + 1, day, []
410
+ if c is not None and c not in ms.concepts:
411
+ ms.concepts.append(c)
412
+ elif it.verdict == "correct":
413
+ for m in ev.get("targets_mistakes") or []:
414
+ ms = mistakes.get(m)
415
+ if ms is None or ms.status != "open":
416
+ continue
417
+ ms.exposures.append(day)
418
+ if (len(ms.exposures) >= RESOLVE_EXPOSURES
419
+ and len(set(ms.exposures)) >= RESOLVE_DAYS):
420
+ ms.status = "resolved"
421
+
422
+ for it in asks:
423
+ if it.concept is not None and it.ev["id"] not in graded_asks:
424
+ concepts[it.concept].asked_not_graded += 1
425
+
426
+ today_d = date.fromisoformat(today)
427
+ noon = datetime.combine(today_d, time(12)).astimezone(UTC) # naive -> system zone
428
+ high = high_retention or set()
429
+ for c, st in concepts.items():
430
+ last_graded = None # last day with primary items; `also` credit never passes a day
431
+ first_pass = None
432
+ for day in sorted(days.get(c, {})):
433
+ items = [i for i in days[c][day] if not i.credit]
434
+ if not items:
435
+ continue
436
+ d = date.fromisoformat(day)
437
+ # a gap pass: ≥ 7 days after the first pass day and ≥ 3 days off before it (§15a.25)
438
+ gap = first_pass is not None and (
439
+ (d - date.fromisoformat(first_pass)).days >= SOLID_GAP_DAYS
440
+ and (d - date.fromisoformat(last_graded)).days >= SOLID_REST_DAYS)
441
+ last_graded = day
442
+ for i in items: # a correct on a later day clears a confident miss (§15a.20)
443
+ if i.verdict == "wrong" and i.confidence == 4:
444
+ st.confident_miss = day
445
+ elif (i.verdict == "correct" and i.hints <= 1 and st.confident_miss
446
+ and day > st.confident_miss):
447
+ st.confident_miss = None
448
+ if i.verdict == "correct" and i.hints <= 1 and i.item_type in DEPTH:
449
+ st.depth_pass = True
450
+ if _pass_day(items):
451
+ st.pass_days, st.last_pass_day = st.pass_days + 1, day
452
+ st.gap_pass = st.gap_pass or gap
453
+ first_pass = first_pass or day
454
+ if st.confident_miss and (today_d - date.fromisoformat(st.confident_miss)).days >= 7:
455
+ st.confident_miss = None
456
+ if c in days:
457
+ scheduler, card, st.lapses = _schedule(days[c],
458
+ HIGH_RETENTION if c in high else RETENTION)
459
+ last = date.fromisoformat(max(days[c]))
460
+ interval = (card.due.date() - last).days # due is _review_at(last) + interval
461
+ st.interval_days = interval + _jitter(c, len(days[c]), interval)
462
+ st.next_due = (last + timedelta(days=st.interval_days)).isoformat()
463
+ st.stability = round(card.stability, 2)
464
+ st.retrievability = round(_retrievability(scheduler, card, noon), 3) # unjittered
465
+ st.last_review = card.last_review
466
+ st.unchecked = c in last_taught and last_taught[c] > last_verdict.get(c, -1)
467
+ st.open_mistakes = sorted(m for m, ms in mistakes.items()
468
+ if ms.status == "open" and c in ms.concepts)
469
+ if c not in evidence:
470
+ st.state = "not_started"
471
+ elif c not in days:
472
+ st.state = "unverified"
473
+ elif (st.stability >= SOLID_STABILITY and st.pass_days >= SOLID_PASS_DAYS
474
+ and last_graded is not None and st.last_pass_day == last_graded
475
+ and st.depth_pass):
476
+ if st.gap_pass: # Solid is shown after a real gap, not only predicted (LEARN-1)
477
+ st.state = ("solid" if today_d <= date.fromisoformat(st.next_due)
478
+ else "needs_refresh")
479
+ else: # the label waits for the check, and the check is due on solid_after
480
+ st.state = "learning"
481
+ st.solid_after = max(
482
+ date.fromisoformat(first_pass) + timedelta(days=SOLID_GAP_DAYS),
483
+ date.fromisoformat(last_graded) + timedelta(days=SOLID_REST_DAYS)).isoformat()
484
+ if st.solid_after < st.next_due: # one place, so every due view agrees
485
+ st.next_due = st.solid_after
486
+ st.interval_days = (date.fromisoformat(st.next_due)
487
+ - date.fromisoformat(max(days[c]))).days
488
+ else:
489
+ st.state = "learning"
490
+ return concepts, mistakes
491
+
492
+
493
+ def predicted_p(events: Iterable[dict], concept: str, now: datetime,
494
+ problem_concepts: dict[str, str | list[str]] | None = None) -> float:
495
+ """Retrievability of the same FSRS-6 card `fold` builds (unjittered) from the days before
496
+ `now`'s local day; 0.5 with no reviews. Today's items are left out: they follow feedback, so
497
+ they do not measure what was retained (board L6)."""
498
+ now = now.replace(tzinfo=UTC) if now.tzinfo is None else now
499
+ today = _events.local_day(now)
500
+ per_day: dict[str, list[_Item]] = {}
501
+ for it in _items(events, problem_concepts):
502
+ if it.verdict is None or it.ev.get("kind") == "ask" or it.ev["day"] >= today:
503
+ continue
504
+ if it.concept == concept:
505
+ per_day.setdefault(it.ev["day"], []).append(it)
506
+ elif it.verdict == "correct" and concept in it.also:
507
+ per_day.setdefault(it.ev["day"], []).append(_credit(it, concept))
508
+ if not per_day:
509
+ return 0.5
510
+ scheduler, card, _ = _schedule(per_day)
511
+ return _retrievability(scheduler, card, now)
512
+
513
+
514
+ def calibration(events: Iterable[dict],
515
+ problem_concepts: dict[str, str | list[str]] | None = None,
516
+ ) -> dict[str, tuple[int, int]]:
517
+ """state -> (concept-days, passes): for each local day with a graded primary item on a
518
+ concept, its state from the events before that day, and whether the day's first item was
519
+ a pass (correct at hints ≤ 1). Read-only; one fold per graded day.
520
+
521
+ shortcut: exam-aware retention is ignored for past states, fine for a coarse table."""
522
+ events = list(events)
523
+ first: dict[str, dict[str, _Item]] = {} # day -> concept -> first primary graded item
524
+ for it in _items(events, problem_concepts):
525
+ if it.verdict is not None and it.concept and it.ev.get("kind") != "ask":
526
+ first.setdefault(it.ev["day"], {}).setdefault(it.concept, it)
527
+ out = {s: (0, 0) for s in STATES}
528
+ evs = placed(events) # voids and remaps apply whenever they were logged
529
+ for day in sorted(first):
530
+ before, _ = fold([e for e in evs if (e.get("day") or "") < day
531
+ or e.get("kind") == "remap"], day, problem_concepts)
532
+ for c, it in first[day].items():
533
+ s = before[c].state if c in before else "not_started"
534
+ n, ok = out[s]
535
+ out[s] = (n + 1, ok + (it.verdict == "correct" and it.hints <= 1))
536
+ return out
537
+
538
+
539
+ # F1, in memory only, one vault at a time (a server has one; tests make hundreds), each slot
540
+ # replaced whole by one assignment:
541
+ # "replay": (every input of the last whole-log fold, that fold). The inputs are the vault root,
542
+ # the event files' stat keys, problem_concepts, today and high_retention; our own writes and
543
+ # edits outside Keepfold change a stat key, so the next call folds again.
544
+ # "problems": ((the vault root, its problem files' (path, mtime_ns, size)), problem_concepts)
545
+ _LAST: dict[str, tuple] = {}
546
+
547
+
548
+ def replay(vault, today: str | None = None, events: Iterable[dict] | None = None,
549
+ high_retention: set[str] | None = None,
550
+ ) -> tuple[dict[str, ConceptState], dict[str, MistakeState]]:
551
+ """Fold the vault's event log (or `events`); problem primaries come from problems/*.md."""
552
+ today = today or _events.local_day(datetime.now(UTC))
553
+ if events is not None:
554
+ return fold(events, today, problem_concepts(vault), high_retention)
555
+ log = EventLog(vault)
556
+ # keys are read before the files: a change in between only makes the next call miss
557
+ key = (vault.root, log.signature(), problem_concepts(vault), today,
558
+ frozenset(high_retention or ()))
559
+ hit = _LAST.get("replay")
560
+ if hit is None or hit[0] != key:
561
+ hit = _LAST["replay"] = (key, fold(log.iter_events(), today, key[2], high_retention))
562
+ return _own(hit[1][0]), _own(hit[1][1])
563
+
564
+
565
+ def _own(states: dict) -> dict:
566
+ """A copy the caller may change (new state objects, their own lists, dicts and sets): the
567
+ cache keeps its states as folded. A fraction of deepcopy's cost; the field types are pinned
568
+ by tests/test_replay_cache.py so a new mutable kind cannot slip past."""
569
+ out = {}
570
+ for k, st in states.items():
571
+ st = out[k] = copy.copy(st)
572
+ for name, v in vars(st).items():
573
+ if isinstance(v, (list, dict, set)):
574
+ setattr(st, name, copy.copy(v))
575
+ return out
576
+
577
+
578
+ def problem_concepts(vault) -> dict[str, list[str]]:
579
+ """problem id -> its concept ids, primary first (the rest earn `also` credit)."""
580
+ from keepfold.index import _edge_targets # index imports levels
581
+
582
+ files = []
583
+ for e in vault.note_entries("problem"): # the listing's data, as Index._scan reads it
584
+ try:
585
+ st = e.stat() # before the parse: a change after it misses next time
586
+ except OSError:
587
+ continue
588
+ files.append((e.path, st.st_mtime_ns, st.st_size))
589
+ sig = (vault.root, files)
590
+ hit = _LAST.get("problems")
591
+ if hit is None or hit[0] != sig:
592
+ hit = _LAST["problems"] = (sig, {
593
+ note.id: cs for note in vault.iter_notes("problem")
594
+ if (cs := _edge_targets(note.fields.get("concepts") or []))})
595
+ return {k: list(v) for k, v in hit[1].items()} # the caller's own copy