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/chat_pages.py ADDED
@@ -0,0 +1,291 @@
1
+ """Chat's typed answers read from the pages themselves (chat_facts routes to them, words them and
2
+ hands them to the model as its other facts are):
3
+
4
+ - inventory: "how many git repositories have I imported into Keepfold?", "list my projects": the
5
+ pages of one kind (`THINGS`), counted, newest first
6
+ - schedule: "what upcoming tests or interviews do I have scheduled?", "what's coming up?":
7
+ pending assessments dated today or later, soonest first, and imported calendar lines
8
+ (`calendar-*` resource pages, a `- YYYY-MM-DD ...` line per event, sources.py's month pages)
9
+ of the next CALENDAR_DAYS days
10
+ - decisions: "what did I decide about the storage engine?": decision pages holding the words,
11
+ newest first; a superseded or retired one says which later decision replaced it (one whose
12
+ page names its id, or that its own page names)
13
+
14
+ Pages come under Chat's source switches: a saved AI chat under `chats`, any other page under
15
+ `notes`, a private page (its own `private: true` or under a private subject) only under
16
+ `private`. Titles and calendar lines are untrusted page text, carried as data."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from datetime import date, timedelta
22
+
23
+ from keepfold import chat_study
24
+
25
+ _LEAD = chat_study._LEAD
26
+ _TAIL = chat_study._TAIL
27
+ SHOWN = 3 # as chat_facts.SHOWN: titles an answer names
28
+ ROWS = 31 # rows the facts keep
29
+ CALENDAR_DAYS = 30
30
+ FIRST_DAY = "0001-01-01" # as chat_facts.FIRST_DAY
31
+
32
+
33
+ def _resource(rtype: str):
34
+ return lambda i, n: n["kind"] == "resource" and n["fields"].get("resource_type") == rtype
35
+
36
+
37
+ # what "how many <thing>" names -> (singular, plural, the test on a page id and index entry)
38
+ _KINDS = {
39
+ "repo": ("git repository", "git repositories",
40
+ lambda i, n: n["kind"] == "resource" and (
41
+ n["fields"].get("resource_type") == "repo" or i.startswith("repo-"))),
42
+ "project": ("project", "projects", lambda i, n: n["kind"] == "project"),
43
+ "decision": ("decision", "decisions", lambda i, n: n["kind"] == "decision"),
44
+ "person": ("person", "people", lambda i, n: n["kind"] == "person"),
45
+ "assessment": ("assessment", "assessments", lambda i, n: n["kind"] == "assessment"),
46
+ "concept": ("concept", "concepts", lambda i, n: n["kind"] == "concept"),
47
+ "mistake": ("mistake", "mistakes", lambda i, n: n["kind"] == "mistake"),
48
+ "book": ("book", "books", _resource("book")),
49
+ "paper": ("paper", "papers", _resource("paper")),
50
+ "article": ("article", "articles", _resource("article")),
51
+ "video": ("video", "videos", _resource("video")),
52
+ "course": ("course", "courses", _resource("course")),
53
+ "resource": ("saved source", "saved sources", lambda i, n: n["kind"] == "resource"),
54
+ }
55
+ THINGS = {**{k: k for k in _KINDS}, **{k + "s": k for k in _KINDS},
56
+ "repository": "repo", "repositories": "repo", "people": "person", "persons": "person",
57
+ "contacts": "person", "sources": "resource", "pdfs": "paper"}
58
+ _THING = r"(?:(?:git|code|github|imported|saved) )?(?P<{}>[a-z]+)"
59
+ _VERB = r"(?:have|imported|import|saved|save|added|add|got|kept|stored)"
60
+ _INVENTORY = re.compile(
61
+ _LEAD + rf"(?:how many {_THING.format('a')}(?: (?:do|did|have) i {_VERB})?"
62
+ r"(?: (?:in|into|to) keepfold)?(?: so far| in total| altogether)?"
63
+ rf"|(?:(?:list|show)(?: me)?|what are|which are)(?: all)?(?: of)? my {_THING.format('b')}"
64
+ r"(?: in keepfold)?)" + _TAIL)
65
+ _EVENT = r"(?:tests?|exams?|interviews?|deadlines?|assessments?|oas?|online assessments?|quiz)"
66
+ _EVENTS = rf"{_EVENT}(?:(?: or| and|,)+ (?:any )?{_EVENT})*"
67
+ _SOON = r"(?: (?:scheduled|coming up|lined up|ahead|left|upcoming|planned|soon))?"
68
+ _SCHEDULE = re.compile(
69
+ _LEAD + rf"(?:(?:what|which|any)(?: are)?(?: my| the)?(?: upcoming| next| future| scheduled)?"
70
+ rf" {_EVENTS}(?: (?:do|have|are) (?:i|there))?(?: (?:have|got))?{_SOON}"
71
+ rf"|(?:do i have|are there|have i got) any(?: upcoming| more)? {_EVENTS}{_SOON}"
72
+ rf"|(?:list|show)(?: me)? my(?: upcoming| next)? {_EVENTS}"
73
+ r"|what is (?:coming up|ahead)(?: for me)?|what (?:do i have|have i got) coming up)" + _TAIL)
74
+ _DECIDE = re.compile(
75
+ _LEAD + r"(?:what (?:did|have|had) i (?:decide|decided|choose|chose|chosen|pick|picked)"
76
+ r"|(?:what (?:is|was|are|were) )?my (?:decisions?|choices?)"
77
+ r"|(?:what|which) decisions? (?:did|have) i (?:make|made|take|taken)"
78
+ r"|did i decide anything) (?:about|on|for|regarding) (?:the )?(?P<x>.+)")
79
+ _CAL_LINE = re.compile(r"- (\d{4}-\d{2}-\d{2})(?: (?:\d{1,2}:\d{2}(?: \([^)]*\))?|all day))?"
80
+ r"\s*[:·-]?\s*(.+)")
81
+ _WORD = re.compile(r"[a-z0-9]{4,}")
82
+
83
+
84
+ def route(text: str, rest: str, got, today: date) -> dict | None:
85
+ """{kind (inventory, schedule, decisions), term, lo, hi, focus, unit, today, and `thing`
86
+ for an inventory} for `text`, whose `rest` is chat_study._norm'd with its date phrase
87
+ (`got`, chat._when's) cut, or None. An inventory or decisions question with a date phrase is
88
+ left to the passages; a schedule keeps it, looking forward ("on Friday" is the next one,
89
+ chat_study._ahead) from today on: then lo and hi are its days."""
90
+ from keepfold import chat_facts
91
+
92
+ base = {"lo": FIRST_DAY, "hi": today.isoformat(), "focus": None, "unit": None,
93
+ "today": today.isoformat()}
94
+ if not got and (m := _INVENTORY.fullmatch(rest)):
95
+ thing = THINGS.get(m["a"] or m["b"])
96
+ return {**base, "kind": "inventory", "term": _KINDS[thing][1], "thing": thing} \
97
+ if thing else None
98
+ if _SCHEDULE.fullmatch(rest):
99
+ q = {**base, "kind": "schedule", "term": ""}
100
+ if got:
101
+ lo, hi, _ = chat_study._ahead(text, got, today)
102
+ if hi < today:
103
+ return None
104
+ q.update(lo=max(lo, today).isoformat(), hi=hi.isoformat())
105
+ q["period"] = [q["lo"], q["hi"]]
106
+ return q
107
+ if not got and (m := _DECIDE.fullmatch(rest)):
108
+ term = chat_facts._subject(m["x"])
109
+ return {**base, "kind": "decisions", "term": term} if chat_facts.words(term) else None
110
+ return None
111
+
112
+
113
+ def pages(vault, sources: dict) -> list[tuple[str, dict, bool]]:
114
+ """[(id, page as the index keeps it, private)] of every page under Chat's switches."""
115
+ from keepfold import ask, chat, semantic
116
+
117
+ with chat._INDEX_LOCK:
118
+ idx = chat._index(vault)
119
+ out = [(i, n, False) for i, n in idx._notes.items()]
120
+ if sources.get("private"):
121
+ out += [(i, n, True) for i, (_, n) in ask.private_pages(vault, idx).items()]
122
+ return [(i, n, p) for i, n, p in out
123
+ if p or sources.get("chats" if semantic.is_chat(n) else "notes")]
124
+
125
+
126
+ def _day(i: str, n: dict) -> str:
127
+ from keepfold.topics import page_date
128
+
129
+ return page_date(i, n["fields"], n["body"])
130
+
131
+
132
+ def _title(i: str, n: dict) -> str:
133
+ return chat_study._title(n["title"]) or i
134
+
135
+
136
+ def _out(q: dict, read: list, rows: list, sources: dict, **more) -> dict:
137
+ return {"kind": q["kind"], "query": q["term"], "period": q.get("period"),
138
+ "total": len(rows), "sources": {}, "rows": rows[:ROWS],
139
+ "more": max(0, len(rows) - ROWS),
140
+ "coverage": {"read": len(read), "matched": len(rows),
141
+ "off": [k for k, on in sources.items() if not on]}, **more}
142
+
143
+
144
+ def facts(vault, q: dict, sources: dict) -> dict:
145
+ """The facts of an inventory, schedule or decisions route: chat_facts' shape, with rows
146
+ {id, title, day} (and by kind days_left and source, or status and replaced_by)."""
147
+ every = pages(vault, sources)
148
+ if q["kind"] == "inventory":
149
+ test = _KINDS[q["thing"]][2]
150
+ rows = [{"id": i, "title": _title(i, n), "day": _day(i, n), "private": p}
151
+ for i, n, p in every if test(i, n) and not (
152
+ q["thing"] == "resource" and _is_chat(n))]
153
+ rows.sort(key=lambda r: (r["day"], r["title"]), reverse=True)
154
+ return _out(q, every, rows, sources)
155
+ if q["kind"] == "schedule":
156
+ return _schedule(q, every, sources)
157
+ return _decisions(q, every, sources)
158
+
159
+
160
+ def _is_chat(n: dict) -> bool:
161
+ from keepfold import semantic
162
+
163
+ return semantic.is_chat(n)
164
+
165
+
166
+ def _schedule(q: dict, every: list, sources: dict) -> dict:
167
+ today = date.fromisoformat(q["today"])
168
+ # no date phrase: every pending assessment from today on
169
+ lo, hi = (q["lo"], q["hi"]) if q.get("period") else (q["today"], None)
170
+ rows = []
171
+ for i, n, _ in every:
172
+ d = str(n["fields"].get("date") or "")[:10]
173
+ if n["kind"] == "assessment" and str(n["fields"].get("outcome") or "pending") \
174
+ == "pending" and lo <= d and (hi is None or d <= hi):
175
+ rows.append({"id": i, "title": _title(i, n), "day": d, "source": "assessment",
176
+ "what": chat_study._title(n["fields"].get("kind") or "")})
177
+ named = {(r["day"], w) for r in rows for w in _WORD.findall(r["title"].lower())}
178
+ cal_hi = (today + timedelta(days=CALENDAR_DAYS)).isoformat()
179
+ for i, n, _ in every:
180
+ if n["kind"] != "resource" or not i.startswith("calendar-"):
181
+ continue
182
+ for ln in n["body"].splitlines():
183
+ if not (m := _CAL_LINE.fullmatch(ln.strip())) or not (
184
+ lo <= m[1] <= (hi or cal_hi) and m[1] <= cal_hi):
185
+ continue
186
+ title = chat_study._title(m[2])[:120]
187
+ if title and not {(m[1], w) for w in _WORD.findall(title.lower())} & named:
188
+ rows.append({"id": i, "title": title, "day": m[1], "source": "calendar"})
189
+ for r in rows:
190
+ r["days_left"] = (date.fromisoformat(r["day"]) - today).days
191
+ rows.sort(key=lambda r: (r["day"], r["source"] != "assessment", r["title"]))
192
+ return _out(q, every, rows, sources, calendar_days=CALENDAR_DAYS)
193
+
194
+
195
+ def _names(text: str, i: str) -> bool:
196
+ return re.search(rf"(?<![\w-]){re.escape(i)}(?![\w-])", text) is not None
197
+
198
+
199
+ def replaced_by(i: str, d: str, body: str, decs: list) -> str | None:
200
+ """The id of the decision that replaced decision `i` (dated `d`, its page text `body`), of
201
+ `decs` [(day, id, body)]: a later one whose page names `i`, else one `i`'s page names; None.
202
+ Chat's decisions and the dashboard's Mind Mirror (R27a) both use it."""
203
+ later = [(d2, i2, b2) for d2, i2, b2 in decs if i2 != i and d2 >= d]
204
+ by = next((x for x in later if _names(x[2], i)), None) or next(
205
+ (x for x in later if _names(body, x[1])), None)
206
+ return by[1] if by else None
207
+
208
+
209
+ def _decisions(q: dict, every: list, sources: dict) -> dict:
210
+ from keepfold import chat_facts
211
+
212
+ match = chat_facts._matcher(chat_facts.words(q["term"]))[0]
213
+ decs = sorted(((_day(i, n), i, n) for i, n, _ in every if n["kind"] == "decision"),
214
+ key=lambda x: (x[0], x[1]))
215
+ bodies, node = [(d, i, n["body"]) for d, i, n in decs], {i: n for _, i, n in decs}
216
+ rows = []
217
+ for d, i, n in reversed(decs): # newest first
218
+ if not match(f"{n['title']}\n{n['body']}"):
219
+ continue
220
+ status = str(n["fields"].get("status") or "")
221
+ by = replaced_by(i, d, n["body"], bodies) if status in ("superseded", "retired") else None
222
+ rows.append({"id": i, "title": _title(i, n), "day": d, "status": status,
223
+ "replaced": status in ("superseded", "retired"),
224
+ "replaced_by": _title(by, node[by]) if by else None})
225
+ return _out(q, every, rows, sources)
226
+
227
+
228
+ # ---- words -------------------------------------------------------------------------------------
229
+
230
+ def _when(day: str, today: date) -> str:
231
+ return chat_study._day(date.fromisoformat(day), today) if day else "undated"
232
+
233
+
234
+ def _left(n: int) -> str:
235
+ return "today" if n == 0 else "tomorrow" if n == 1 else f"in {n} days"
236
+
237
+
238
+ def say(f: dict, today: date) -> str:
239
+ """The facts in plain words, with no model."""
240
+ out = _say(f, today)
241
+ if not f["total"] and "notes" in f["coverage"]["off"]:
242
+ out += " Notes are switched off in Chat settings."
243
+ return out
244
+
245
+
246
+ def _say(f: dict, today: date) -> str:
247
+ rows, n = f["rows"], f["total"]
248
+ if f["kind"] == "inventory":
249
+ if not n:
250
+ return f"I found no {f['query']} in Keepfold."
251
+ one = next(v for v in _KINDS.values() if v[1] == f["query"])[0]
252
+ names = "; ".join(f'"{r["title"]}" ({_when(r["day"], today)})' for r in rows[:SHOWN])
253
+ return (f"Keepfold holds {n} {one if n == 1 else f['query']}, newest first: {names}"
254
+ + (f"; and {n - SHOWN} more" if n > SHOWN else "") + ".")
255
+ if f["kind"] == "schedule":
256
+ tests = [r for r in rows if r["source"] == "assessment"]
257
+ cal = [r for r in rows if r["source"] == "calendar"]
258
+ if not rows:
259
+ return "I found no upcoming tests, interviews or calendar events in Keepfold."
260
+ out = [f"You have {chat_study._plural(len(tests), 'upcoming assessment')}" + (
261
+ ": " + "; ".join(f'"{r["title"]}" on {_when(r["day"], today)} '
262
+ f'({_left(r["days_left"])})' for r in tests) if tests else "")
263
+ + "."]
264
+ if cal:
265
+ out.append(f"From your calendar in the next {f['calendar_days']} days: " + "; ".join(
266
+ f'"{r["title"]}" on {_when(r["day"], today)}' for r in cal[:SHOWN * 2]) + (
267
+ f"; and {len(cal) - SHOWN * 2} more" if len(cal) > SHOWN * 2 else "") + ".")
268
+ return " ".join(out)
269
+ if not n:
270
+ return f'I found no decision about "{f["query"]}" in Keepfold.'
271
+ parts = []
272
+ for r in rows[:SHOWN]:
273
+ s = f'"{r["title"]}" ({_when(r["day"], today)}' + (
274
+ f', {r["status"]})' if r["status"] and not r["replaced"] else ")")
275
+ if r["replaced"]:
276
+ s += f', replaced by "{r["replaced_by"]}"' if r["replaced_by"] else ", replaced"
277
+ parts.append(s)
278
+ return (f'{chat_study._plural(n, "decision")} about "{f["query"]}", newest first: '
279
+ + "; ".join(parts) + (f"; and {n - SHOWN} more" if n > SHOWN else "") + ".")
280
+
281
+
282
+ def lines(f: dict) -> list[str]:
283
+ """Each row as a line for the model (chat_facts._lines puts `say` first)."""
284
+ if f["kind"] == "inventory":
285
+ return [f"- {r['day'] or 'undated'}: {r['title']}" for r in f["rows"]]
286
+ if f["kind"] == "schedule":
287
+ return [f"- {r['day']} ({_left(r['days_left'])}): {r['title']} ({r['source']})"
288
+ for r in f["rows"]]
289
+ return [f"- {r['day'] or 'undated'}: {r['title']} ({r['status'] or 'no status'}"
290
+ + (f", replaced by {r['replaced_by']}" if r["replaced_by"] else "") + ")"
291
+ for r in f["rows"]]
keepfold/chat_study.py ADDED
@@ -0,0 +1,371 @@
1
+ """Chat's study questions ("what should I study today?", "what's due?", "where am I weak?",
2
+ "what did I study yesterday?", "how am I doing?") answered from Keepfold's own learner model,
3
+ never from a few retrieved passages and never by a model. Each answer reuses the planner and
4
+ the levels fold, hides what the planner hides (private domains, areas, concepts, tracks and
5
+ mistake notes: D1) unless Chat's `private` switch is on (the local model may read them; today's
6
+ plan still hides them, as planner.today does) and shows state words, never internal numbers.
7
+ Anything else is None, so the passages and the local model answer it."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import calendar
12
+ import re
13
+ from collections import Counter
14
+ from datetime import date, datetime, time, timedelta
15
+
16
+ from keepfold import levels, planner, render
17
+ from keepfold.catalog import Catalog
18
+ from keepfold.events import EventLog
19
+ from keepfold.vault import Vault
20
+
21
+ _MD = re.compile(r"[*_`\[\]<>#|]") # Chat renders **bold**, `code` and [n]: titles stay text
22
+ SHOWN = 15
23
+ _STATES: dict = {} # vault root -> (the fold's inputs, its states): callers never change them
24
+
25
+ _LEAD = r"(?:(?:so|ok|okay|hey|hi|keepfold|please|and|then|now|alright)\s+)*"
26
+ _TAIL = r"(?:\s+(?:please|then|now|right now|today|for today|so far|overall|again))*"
27
+ _STUDY = r"(?:study|learn|work on|practi[cs]e|focus on)"
28
+ _ASKS = {
29
+ "plan": [
30
+ rf"what should i {_STUDY}(?: next| first)?",
31
+ rf"what (?:do|can) i {_STUDY}(?: next)?",
32
+ r"what is (?:my|the) (?:study )?plan",
33
+ r"(?:show|give|tell)(?: me)? (?:my|the) (?:study )?plan",
34
+ r"(?:my |the )?(?:study )?plan|today'?s (?:study )?plan",
35
+ r"what is on (?:my|the) plan",
36
+ ],
37
+ "due": [
38
+ r"what is due(?: for (?:review|revision))?",
39
+ r"(?:is )?anything due(?: for (?:review|revision))?",
40
+ r"what (?:should|do|must) i (?:review|revise)",
41
+ r"what do i (?:need|have) to (?:review|revise)",
42
+ r"what needs (?:review|reviewing|revision|revising|a refresh|refreshing)",
43
+ r"what (?:reviews|concepts|topics) are due",
44
+ r"what are my (?:reviews|due reviews|due concepts|due topics)",
45
+ ],
46
+ "weak": [
47
+ r"what are my weak(?:est)? (?:topics|areas|concepts|spots|points|subjects)",
48
+ r"(?:which|what) (?:topics|areas|concepts|subjects) am i weak(?:est)? (?:at|in|on)"
49
+ r"(?: or (?:need|have) to (?:refresh|review|revise))?",
50
+ r"where am i weak(?:est)?|what am i weak(?:est)? (?:at|in|on)",
51
+ r"what are my weak(?:ness|nesse)s|what am i bad at|what do i struggle with",
52
+ r"what mistakes do i keep making|what do i keep getting wrong",
53
+ r"what (?:are|were) my (?:(?:common|recurring|repeated|frequent|open|recent|usual) )?"
54
+ r"mistakes",
55
+ r"what (?:open )?mistakes do i (?:still )?(?:need|have) to fix",
56
+ ],
57
+ # "which concepts are solid?": the concepts the fold puts in one state (_STATE_WORD)
58
+ "state": [
59
+ r"(?:which|what) (?:topics|concepts|subjects) (?:are|am i) (?:solid|learning|unverified"
60
+ r"|not started|due for a refresh|in need of a refresh)",
61
+ ],
62
+ "progress": [
63
+ r"how am i (?:doing|progressing)(?: (?:with|in|on) (?:my )?(?:studies|studying|learning"
64
+ r"|prep|preparation))?",
65
+ r"how is my (?:progress|studying|learning|prep|preparation)(?: going)?",
66
+ r"how are my studies going|what is my progress|my progress|progress report",
67
+ r"(?:show|give|tell)(?: me)? my progress|how far (?:have i got|am i)",
68
+ ],
69
+ }
70
+ _ASKS = {k: re.compile(_LEAD + "(?:" + "|".join(v) + ")" + _TAIL) for k, v in _ASKS.items()}
71
+ # the question with its date phrase cut out; a topic left over ("what did I study about
72
+ # graphs yesterday?") does not match, so the passages answer it
73
+ _RANGE = re.compile(_LEAD + r"(?:what|which (?:topics|concepts)) (?:did|have) i (?:study|studied"
74
+ r"|practi[cs]ed?|revised?|reviewed|review|worked on|work on)|what was i "
75
+ r"(?:studying|practi[cs]ing|revising|reviewing)")
76
+ # "what did I do yesterday?", "summarize my week", "recap last week", "what have I been up to?":
77
+ # the question with its date phrase cut out, as _RANGE. Without a date phrase, "my day" is today,
78
+ # and "my week" or "what have I been up to" this week; any other leftover word ("what did I do
79
+ # on reddit yesterday?", "summarize this article") does not match.
80
+ _DIGEST = re.compile(
81
+ _LEAD + r"(?:(?P<upto>what (?:have|had) i been (?:up to|doing)|what was i (?:up to|doing))"
82
+ r"|what did i do|what (?:have|had) i done|what happened"
83
+ r"|what (?:did|have|had) i (?:learn|learned|learnt)" # studied and browsed: the digest
84
+ r"|(?:can you |could you )?(?:summari[sz]e|recap|sum up)(?: for me)?"
85
+ r"|(?:give|show|tell)(?: me)? (?:a |my )?(?:quick |short |brief )?(?:summary|recap|rundown"
86
+ r"|digest)|(?:a |my )?(?:quick |short |brief )?(?:summary|recap|digest))"
87
+ r"(?: (?:of|in|on|over|during|for|from|across|with))?(?: (?:my|the))?(?: (?P<unit>day|week))?"
88
+ + _TAIL)
89
+ # "what's next?" opens a chat with the plan; mid-chat it asks about the last answer
90
+ _NEXT = re.compile(_LEAD + r"what (?:is )?next" + _TAIL)
91
+ _RECENT = timedelta(days=366) # a digest ends within the last year; older is history
92
+ NO_STUDY = "Keepfold has no study recorded"
93
+ STEP = {"plan":"Reading your study plan", "due": "Reading your due reviews",
94
+ "weak": "Reading your weak spots and mistakes", "range": "Reading what you studied",
95
+ "progress": "Reading your progress", "state": "Reading your learning states"}
96
+ _STATE_WORD = {"solid": "solid", "learning": "learning", "unverified": "unverified",
97
+ "not started": "not_started", "refresh": "needs_refresh"}
98
+
99
+
100
+ def _norm(text: str) -> str:
101
+ s = text.lower().replace("’", "'")
102
+ s = re.sub(r"[^\w' ]+", " ", s)
103
+ for short, long in ((r"what'?s", "what is"), (r"how'?s", "how is"), (r"i'?m", "i am")):
104
+ s = re.sub(rf"\b{short}\b", long, s)
105
+ return " ".join(s.split())
106
+
107
+
108
+ def _digest(text: str, got):
109
+ """The _DIGEST match of `text` when it names its days (a date phrase, "my day", "my week",
110
+ "what have I been up to"), else None."""
111
+ m = _DIGEST.fullmatch(_norm(text[:got[2][0]] + " " + text[got[2][1]:] if got else text))
112
+ return m if m and (got or m["unit"] or m["upto"]) else None
113
+
114
+
115
+ def digest_days(text: str, got, today: date) -> tuple[date, date, str] | None:
116
+ """(first day, last day, "day", "week" or "days") a digest question asks about, or None
117
+ for any other question."""
118
+ if not (m := _digest(text, got)):
119
+ return None
120
+ if got: # "last week", "past week": a week; "two weeks ago", "last 3 days": days
121
+ week = re.search(r"\bweek\b(?!\s+ago)", text[got[2][0]:got[2][1]], re.I)
122
+ return got[0], got[1], "week" if week else "day" if got[0] == got[1] else "days"
123
+ if m["unit"] == "day":
124
+ return today, today, "day"
125
+ return today - timedelta(today.weekday()), today, "week"
126
+
127
+
128
+ def _due_by(text: str, got) -> date:
129
+ """The last day of a due question's range: "this week" runs to Sunday."""
130
+ phrase = text[got[2][0]:got[2][1]]
131
+ return got[0] + timedelta(6) if re.fullmatch(r"this\s+week", phrase, re.I) else got[1]
132
+
133
+
134
+ _BACK = re.compile(r"\b(?:last|past|previous|ago|yesterday|night|since)\b|\d{4}", re.I)
135
+ _DAYNAME = re.compile(r"\b(?:mon|tues|wednes|thurs|fri|satur|sun)day\b", re.I)
136
+
137
+
138
+ def _ahead(text: str, got, today: date):
139
+ """A due question looks forward: a weekday, weekend, month or day with no year that chat's
140
+ dates resolved to the past ("on Friday", "this weekend", "on 25 Nov", "in December") is the
141
+ next one. "last Friday", "3 days ago" and a stated year stay as said."""
142
+ phrase = text[got[2][0]:got[2][1]]
143
+ if _BACK.search(phrase):
144
+ return got
145
+ lo, hi = got[:2]
146
+ if re.search(r"weekend", phrase, re.I):
147
+ lo = today + timedelta((5 - today.weekday()) % 7 if today.weekday() != 6 else -1)
148
+ return lo, lo + timedelta(1), got[2] # this Saturday to Sunday, the due-by day
149
+ if hi >= today:
150
+ return got
151
+ if _DAYNAME.search(phrase):
152
+ return lo + timedelta(7), hi + timedelta(7), got[2]
153
+ # a day or month with no year: this year's, which _day/_month put a year back
154
+ if lo == hi: # a day: next year's; 29 Feb the next 29 Feb
155
+ for y in range(lo.year + 1, lo.year + 5):
156
+ if (lo.month, lo.day) != (2, 29) or calendar.isleap(y):
157
+ return lo.replace(year=y), lo.replace(year=y), got[2]
158
+ return got
159
+ y = lo.year + 1
160
+ if lo.day == 1 and (lo.year, lo.month) == (hi.year, hi.month) \
161
+ and hi.day == calendar.monthrange(hi.year, hi.month)[1]: # a whole month
162
+ return lo.replace(year=y), hi.replace(year=y, day=calendar.monthrange(y, hi.month)[1]), \
163
+ got[2]
164
+ try:
165
+ return lo.replace(year=y), hi.replace(year=hi.year + 1), got[2]
166
+ except ValueError: # a range ending 29 Feb into a common year
167
+ return got
168
+
169
+
170
+ def kind(text: str, got=None, today: date | None = None, first: bool = True) -> str | None:
171
+ """Which study question `text` is (plan, due, weak, range, progress), "digest" for a
172
+ question about everything done on some days within the last year (chat.digest answers
173
+ it), or None. `got` is chat._when's (first, last, span) for its own date phrase; a range
174
+ question needs one. `first`: the chat's first question ("what's next?" is the plan only
175
+ then)."""
176
+ rest = _norm(text[:got[2][0]] + " " + text[got[2][1]:]) if got else ""
177
+ if got and _RANGE.fullmatch(rest):
178
+ return "range"
179
+ if got and _ASKS["due"].fullmatch(rest):
180
+ return "due"
181
+ if _digest(text, got) and not (got and today and got[1] < today - _RECENT):
182
+ return "digest" # "what happened on 11 September 2001?" is history: the model's
183
+ s = _norm(text)
184
+ if _NEXT.fullmatch(s):
185
+ return "plan" if first else None
186
+ return next((k for k, rx in _ASKS.items() if rx.fullmatch(s)), None)
187
+
188
+
189
+ def _title(t) -> str:
190
+ return _MD.sub("", render.plain(str(t or ""))).strip()
191
+
192
+
193
+ def _plural(n: int, word: str) -> str:
194
+ return f"{n} {word}{'s' * (n != 1)}"
195
+
196
+
197
+ def _day(d: date, today: date) -> str:
198
+ """'17 Nov', or '11 Sep 2001' in a year other than `today`'s (chat._span uses it too)."""
199
+ return f"{d.day} {d:%b}" + (f" {d.year}" if d.year != today.year else "")
200
+
201
+
202
+ def _state(st) -> str:
203
+ s = st.state if st else "not_started"
204
+ return f"{levels.GLYPH[s]} {levels.LABEL[s]}"
205
+
206
+
207
+ def study_answer(vault: Vault, text: str, got, today: date, first: bool = True,
208
+ private: bool = False) -> str | None:
209
+ """The answer to a study question about the learner's own plan, due reviews, weak spots,
210
+ a date range's study, or progress; None for any other question."""
211
+ k = kind(text, got, today, first)
212
+ if k == "due" and got:
213
+ got = _ahead(text, got, today)
214
+ got = (got[0], _due_by(text, got), got[2])
215
+ return None if k in (None, "digest") else answer(vault, k, got, today, private, text)
216
+
217
+
218
+ def answer(vault: Vault, k: str, got, today: date, private: bool = False,
219
+ text: str = "") -> str:
220
+ """The answer for study question kind `k` (see `kind`) as of local day `today`. `private`
221
+ (Chat's switch, for the local model only) names private subjects and mistakes too. `text`:
222
+ the question, which names the state a "state" question asks about."""
223
+ day = today.isoformat()
224
+ catalog = Catalog.load(vault)
225
+ log = EventLog(vault)
226
+ stamps = [] # before the read: a change after it misses the memo next time
227
+ for path in sorted(log._dir().glob("*/*/*.jsonl")): # iter_events' files
228
+ try:
229
+ st = path.stat()
230
+ except OSError:
231
+ continue
232
+ stamps.append((str(path), st.st_mtime_ns, st.st_size))
233
+ events = list(log.iter_events())
234
+ pc = levels.problem_concepts(vault)
235
+ # planner.current_states, kept while its inputs are the same: the fold of a heavy user's
236
+ # events took over a second of every answer
237
+ high = planner.exam_concepts(vault, catalog, day)
238
+ key = (day, tuple(stamps), repr(sorted(pc.items())), tuple(sorted(high)))
239
+ hit = _STATES.get(vault.root)
240
+ if hit is None or hit[0] != key:
241
+ hit = _STATES[vault.root] = (key, levels.fold(events, day, pc, high))
242
+ states, mistakes = hit[1]
243
+ hide = set() if private else planner.hidden(vault, catalog)
244
+
245
+ def name(cid: str) -> str:
246
+ e = catalog.entries.get(cid)
247
+ return _title(e.title if e else cid) or cid
248
+
249
+ if k == "plan":
250
+ now = datetime.combine(today, time(12)).astimezone() # the planner's local `today`
251
+ items = [i for i in planner.today(vault, catalog, states, now=now, events=events)
252
+ if i["id"] not in hide]
253
+ if not items:
254
+ return "Nothing is planned for today: nothing is due and nothing new is ready."
255
+ lines = [f"**Today's plan** ({_plural(len(items), 'item')}):", ""]
256
+ for i in items[:SHOWN]:
257
+ head = f"{levels.GLYPH[i['state']]} " if i["state"] else ""
258
+ label = f" ({levels.LABEL[i['state']]})" if i["state"] else ""
259
+ why = _title(i["why"])
260
+ lines.append(f"- {head}**{_title(i['title'])}**{label}" + (f" · {why}" if why else ""))
261
+ if len(items) > SHOWN:
262
+ lines.append(f"- and {len(items) - SHOWN} more in Today.md")
263
+ return "\n".join(lines)
264
+
265
+ if k == "due": # by today, or by the last day of `got` ("what is due this week?")
266
+ by = got[1] if got else today
267
+ when = "today" if by == today else f"by {_day(by, today)}"
268
+ due = sorted(((c, st) for c, st in states.items()
269
+ if c not in hide and planner.is_due(st, by.isoformat())), # as home card
270
+ key=lambda kv: (kv[1].state != "needs_refresh", str(kv[1].next_due or ""),
271
+ kv[0]))
272
+ if not due:
273
+ later = min((str(st.next_due)[:10] for c, st in states.items()
274
+ if c not in hide and st.next_due), default=None)
275
+ return f"Nothing is due for review {when}." + (
276
+ f" The next review is due on {later}." if later else "")
277
+ lines = [f"**{_plural(len(due), 'concept')} due for review** {when}:", ""]
278
+ lines += [f"- {_state(st)}: **{name(c)}**" for c, st in due[:SHOWN]]
279
+ if len(due) > SHOWN:
280
+ lines.append(f"- and {len(due) - SHOWN} more")
281
+ return "\n".join(lines)
282
+
283
+ if k == "state":
284
+ s = next(v for w, v in _STATE_WORD.items() if w in _norm(text))
285
+ names = sorted(name(c) for c in (e.id for e in catalog.entries.values()
286
+ if e.kind == "concept" and e.id not in hide)
287
+ if (states[c].state if c in states else "not_started") == s)
288
+ if not names:
289
+ return f"No concepts are {levels.LABEL[s]} right now."
290
+ return "\n".join([f"**{_plural(len(names), 'concept')}** {levels.GLYPH[s]} "
291
+ f"{levels.LABEL[s]}:", "", *[f"- **{n}**" for n in names[:SHOWN]],
292
+ *([f"- and {len(names) - SHOWN} more"] if len(names) > SHOWN else [])])
293
+
294
+ notes = list(vault.iter_notes("mistake"))
295
+ # D1 unless `private`: private mistakes and, OQ-22, those about a private subject
296
+ hush = set() if private else planner.hidden_mistakes(mistakes, hide)
297
+ open_m = sorted((m for m in mistakes.values() if m.status == "open" and m.id not in hush),
298
+ key=lambda m: (-m.count, m.id)) # as the start card
299
+
300
+ if k == "weak":
301
+ titles = {n.id: _title(n.fields.get("title") or n.id) for n in notes}
302
+ weak = []
303
+ for c, st in sorted(states.items()):
304
+ if c in hide:
305
+ continue
306
+ why = [f"a confident miss on {st.confident_miss}"] if st.confident_miss else []
307
+ if n := len([m for m in st.open_mistakes if m not in hush]):
308
+ why.append(_plural(n, "open mistake"))
309
+ if st.state == "needs_refresh":
310
+ why.append("needs a refresh")
311
+ if why:
312
+ weak.append((not st.confident_miss, -n, c, st, why))
313
+ if not weak and not open_m:
314
+ return "No weak spots yet: no confident misses, open mistakes or concepts to refresh."
315
+ lines = []
316
+ if weak:
317
+ lines += [f"**{_plural(len(weak), 'weak concept')}**, most urgent first:", ""]
318
+ lines += [f"- {_state(st)}: **{name(c)}** · {', '.join(why)}"
319
+ for *_, c, st, why in sorted(weak, key=lambda w: w[:3])[:SHOWN]]
320
+ if open_m:
321
+ lines += [*([""] if lines else []),
322
+ f"**{_plural(len(open_m), 'open mistake')}**, most often first:", ""]
323
+ lines += [f"- ⚑ {titles.get(m.id, _title(m.id))} · seen {m.count}×"
324
+ + (f", last on {m.last_day}" if m.last_day else "") for m in open_m[:SHOWN]]
325
+ return "\n".join(lines)
326
+
327
+ if k == "range":
328
+ lo, hi = got[0].isoformat(), got[1].isoformat()
329
+ when = f"on {_day(got[0], today)}" if lo == hi else \
330
+ f"from {_day(got[0], today)} to {_day(got[1], today)}"
331
+ did: dict[str, Counter] = {}
332
+ for it in levels._items(events, pc): # void, regrade and remap applied, as the fold
333
+ c, d = it.concept, str(it.ev.get("day") or "")
334
+ if c is None or c in hide or not lo <= d <= hi:
335
+ continue
336
+ tally = did.setdefault(c, Counter())
337
+ if it.taught:
338
+ tally["taught"] += 1
339
+ if it.ev.get("kind") == "ask":
340
+ tally["asked"] += 1
341
+ if it.verdict is not None:
342
+ tally[it.verdict] += 1
343
+ if not did:
344
+ return f"{NO_STUDY} {when}."
345
+ lines = [f"**{_plural(len(did), 'concept')}** studied {when}:", ""]
346
+ for c in sorted(did, key=lambda c: (-sum(did[c].values()), c))[:SHOWN]:
347
+ t = did[c]
348
+ graded = t["correct"] + t["partial"] + t["wrong"]
349
+ parts = (["taught"] if t["taught"] else []) + (
350
+ [f"asked {_plural(t['asked'], 'question')}"] if t["asked"] else [])
351
+ if graded:
352
+ parts.append(_plural(graded, "answer") + " graded (" + ", ".join(
353
+ f"{t[v]} {v}" for v in ("correct", "partial", "wrong") if t[v]) + ")")
354
+ lines.append(f"- {_state(states.get(c))}: **{name(c)}** · {'; '.join(parts)}")
355
+ if len(did) > SHOWN:
356
+ lines.append(f"- and {len(did) - SHOWN} more")
357
+ return "\n".join(lines)
358
+
359
+ # progress: the dashboard's counts over the concepts it shows
360
+ tally = Counter(states[e.id].state if e.id in states else "not_started"
361
+ for e in catalog.entries.values() if e.kind == "concept" and e.id not in hide)
362
+ if not tally:
363
+ return "No concepts yet: add a subject or import your notes to start."
364
+ lines = [f"**{_plural(sum(tally.values()), 'concept')}** in Keepfold:", ""]
365
+ lines += [f"- {levels.GLYPH[s]} {levels.LABEL[s]}: {tally[s]}"
366
+ for s in ("solid", "learning", "needs_refresh", "unverified", "not_started")
367
+ if tally[s]]
368
+ due = sum(1 for c, st in states.items() if c not in hide and planner.is_due(st, day))
369
+ lines += ["", f"{_plural(due, 'concept')} due for review today, "
370
+ f"{_plural(len(open_m), 'open mistake')}."]
371
+ return "\n".join(lines)