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/dashboard.py ADDED
@@ -0,0 +1,959 @@
1
+ """The dashboard: the app's live home (`render_live`) and the offline snapshot.
2
+
3
+ The snapshot (Export snapshot) is one self-contained page: the data blob, d3 v7 and the page
4
+ script are inlined, and the CSP allows only those scripts by hash. Note text reaches the page as
5
+ plain strings (links, images and tags stripped) and the page script inserts it with
6
+ `textContent`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import hashlib
13
+ import json
14
+ import operator
15
+ import re
16
+ import statistics
17
+ import string
18
+ from collections import Counter
19
+ from contextlib import contextmanager
20
+ from datetime import date, datetime, timedelta
21
+ from pathlib import Path
22
+ from types import SimpleNamespace
23
+
24
+ from keepfold import (
25
+ brainmap,
26
+ chat_pages,
27
+ claims,
28
+ index,
29
+ know,
30
+ learning_eval,
31
+ levels,
32
+ loops,
33
+ planner,
34
+ profiles,
35
+ reflect,
36
+ taint,
37
+ topics,
38
+ )
39
+ from keepfold import vault as vault_mod
40
+ from keepfold.catalog import Catalog
41
+ from keepfold.events import EventLog, local_day
42
+ from keepfold.index import _edge_targets, link_targets
43
+ from keepfold.render import index_md, plain
44
+ from keepfold.vault import TOOL_PROPS, Vault, is_private
45
+
46
+ ASSETS = Path(__file__).parent / "assets"
47
+ YOU = "@you" # not a valid note id, so it never collides with one
48
+ EVIDENCE_SHOWN, WEEKS, MISTAKE_DAYS = 10, 8, 30
49
+ # answer time, display only (never a rating): the median of the last 10 ask-to-grade gaps, from
50
+ # 3 gaps, leaving out gaps over 15 minutes (the person left)
51
+ ANSWER_LAST, ANSWER_MIN, ANSWER_CUT = 10, 3, 15 * 60
52
+ ITEM_TYPE = {"problem_status": "problem", "self_report": "self report"}
53
+ _SLOT = re.compile(r"\{\{(\w+)\}\}")
54
+ BODY_MAX = 20 * 1024
55
+ TRUNCATED = "\n\n*… truncated here; open the note in Obsidian for the rest.*\n"
56
+ SHOWN_PROPS = 30 # list items and characters below are capped too, to keep the blob small
57
+ REPO = Path(__file__).resolve().parents[2] # a source checkout; installed, assets/help instead
58
+ GLOSSARY = "The names, in plain words" # the GUIDE heading after its number
59
+ _NAME_RE = re.compile(r"\*\*Name:\*\*\s*(\S+)")
60
+ # an import's header (doctor._IMPORT_HEAD): `Source: <label> · Date:`, maybe on a Timeline line
61
+ _IMPORTED = re.compile(r"^(?:Timeline: [^\n]*?)?Source: ([^·\n]+?) · Date: ", re.M)
62
+ UNFILED = "unfiled"
63
+ GROUP_TITLES = {"journal": "Journal", "you": "About you", "sessions": "Study sessions",
64
+ "placements": "Tests and applications",
65
+ "projects": "Projects, decisions and loops", "people": "People",
66
+ "media": "YouTube and NotebookLM", "chats": "Unsorted chats",
67
+ "browsing": "Browsing"}
68
+ GROUPS = {"journal": "journal", "me": "you", "session": "sessions", # page kind -> group lobe
69
+ "browse": "browsing", # private browse pages are never read
70
+ "rollup": "journal", # generated week, month and year pages: time, like the journal
71
+ **dict.fromkeys(("assessment", "application", "track"), "placements")}
72
+ NO_HUB = {"project": "projects", "decision": "projects", "loop": "projects", "person": "people"}
73
+ MEDIA = {"youtube", "notebooklm"}
74
+ CHATS = {"claude", "claude code", "chatgpt", "gemini", "perplexity"} # page_source, lowercased
75
+
76
+
77
+ _SESSION_ID = re.compile(r"(\d{4}-\d{2}-\d{2})-([\w-]+)-\w{8}")
78
+ _STARTED = re.compile(r"^- Started: \d{4}-\d{2}-\d{2} (\d{1,2}:\d{2})\s*$", re.M)
79
+
80
+
81
+ def _is_ambient(kind: str, nid: str) -> bool:
82
+ """A receipt session.py saved when an AI chat wrote to the vault (`<day>-ambient-<8>`)
83
+ or when Keepfold tidied the about-me lines (`<day>-tidy-<8>`) or saved some from imported
84
+ chats (`<day>-harvest-<8>`)."""
85
+ m = _SESSION_ID.fullmatch(nid)
86
+ return kind == "session" and bool(m) and m[2] in ("ambient", "tidy", "harvest")
87
+
88
+
89
+ def _title(note) -> str:
90
+ if note.kind == "me" and not note.fields.get("title"): # me/teaching-contract -> words
91
+ return note.id.replace("-", " ").capitalize()
92
+ if note.kind == "session" and not note.fields.get("title") and (
93
+ m := _SESSION_ID.fullmatch(note.id)): # a receipt has no title: say what it was
94
+ t = _STARTED.search(note.body)
95
+ when = t[1] if t else m[1]
96
+ return (f"Chat with an AI app, {when}" if m[2] == "ambient"
97
+ else f"Keepfold tidied lines about you, {when}" if m[2] == "tidy"
98
+ else f"Keepfold saved lines about you from your chats, {when}"
99
+ if m[2] == "harvest"
100
+ else f"Study session ({m[2]}), {when}")
101
+ return plain(note.fields.get("title") or note.id) or note.id
102
+
103
+
104
+ def _plans(vault, catalog, hidden, pc) -> list[dict]:
105
+ """Each non-private plan without dates (v8): its title, next undone steps and counts."""
106
+ return [{"id": p["id"], "title": plain(p["title"]) or p["id"],
107
+ "next": [plain(s["title"], 200) for s in p["steps"][:planner.STEPS_SHOWN]],
108
+ "done": p["done"], "left": len(p["steps"])}
109
+ for p in planner.plans(vault, catalog, hidden, pc)]
110
+
111
+
112
+ STUDY_KINDS = ("concept", "track", "assessment")
113
+ SUGGEST_DAYS, SUGGESTED = 60, 3
114
+ _EXAM_WORD = re.compile(rf"\b{chat_pages._EVENT}\b", re.I)
115
+ _DEADLINE_WORD = re.compile(r"\bdeadlines?\b", re.I)
116
+
117
+
118
+ def exam_suggestions(notes: dict, today: date, shut: set) -> list[dict]:
119
+ """R31: up to SUGGESTED imported calendar events (`calendar-*` month pages' lines, as
120
+ chat_pages reads them) in the next SUGGEST_DAYS days whose title looks like an exam or a
121
+ deadline (chat_pages._EVENT) and that no assessment page holds on the same day by the same
122
+ name (case-folded), soonest first: {day, title, kind (exam or deadline), page}. A fold over
123
+ the pages, never stored; a page in `shut` (private, or under a private subject) is never
124
+ read, and an added one goes because its assessment page now exists."""
125
+ have = {(str(n.fields.get("date") or "")[:10], str(n.fields.get("title") or "").casefold())
126
+ for n in notes["assessment"]}
127
+ lo, hi, out = today.isoformat(), (today + timedelta(days=SUGGEST_DAYS)).isoformat(), {}
128
+ for n in notes["resource"]:
129
+ if not n.id.startswith("calendar-") or n.id in shut or is_private(n):
130
+ continue
131
+ for ln in n.body.splitlines():
132
+ if not (m := chat_pages._CAL_LINE.fullmatch(ln.strip())) or not lo <= m[1] <= hi:
133
+ continue
134
+ title = plain(m[2].split(" · ")[0], 120)
135
+ key = (m[1], title.casefold())
136
+ if title and _EXAM_WORD.search(title) and key not in have and key not in out:
137
+ out[key] = {"day": m[1], "title": title, "page": n.id,
138
+ "kind": "deadline" if _DEADLINE_WORD.search(title) else "exam"}
139
+ return sorted(out.values(), key=lambda r: (r["day"], r["title"]))[:SUGGESTED]
140
+
141
+
142
+ def studies(vault: Vault, events: list[dict], notes: dict | None = None) -> bool:
143
+ """Whether the person studies: any concept, track (study plan) or assessment page, private
144
+ ones too, or any grade not voided (a removed sample's seed grades are voided). A fold over
145
+ pages and events, never stored. `notes`, build_data's parsed notes by kind; without them
146
+ the kind folders are only listed."""
147
+ if any(notes[k] if notes is not None else vault.note_paths(k) for k in STUDY_KINDS):
148
+ return True
149
+ voided = {e.get("ref") for e in events if e.get("kind") == "void"}
150
+ return any(e.get("kind") == "grade" and e.get("id") not in voided for e in events)
151
+
152
+
153
+ # UX-E: Home's boards by the signal they serve (dashboard.js homeGroups)
154
+ HOME_GROUPS = ("study", "build", "research")
155
+ RECENT_DAYS = 30 # a page or event this recent counts twice
156
+ BUILD_KINDS = ("project", "decision", "loop") # the "Projects, decisions and loops" lobe
157
+ STUDY_EVENTS = ("taught", "ask", "grade")
158
+ CODING_LABELS = ("Claude Code", "Git") # `Source:` labels of coding apps' chats and repo pages
159
+ # MCP client names of coding apps, normalised (profiles.norm), as profiles.DEFAULT matches them
160
+ CODING_CLIENTS = ("claudecode", "cursor", "codex", "visualstudiocode", "copilot", "geminicli",
161
+ "windsurf", "antigravity", "cline", "opencode", "jetbrains")
162
+ # a resource saved by hand (no label: a link, a paper) or from Zotero, documents, highlights or
163
+ # notes; not calendar, mail, photos, chats and the like
164
+ RESEARCH_LABELS = ("", "Zotero", "Documents", "Highlights", "Pocket", "Obsidian", "Notion",
165
+ "Notes")
166
+ NEW_PAGES = 10 # Get started: a vault with fewer pages of its own is new
167
+ # page id -> (its row's body, its import `Source:` label): a build reuses an unchanged page's
168
+ # row and body, so `signals` scans each body once (the scan cost ~8 ms on 5k pages every build)
169
+ _LABELS: dict[str, tuple[str, str]] = {}
170
+
171
+
172
+ def _label(p: dict) -> str:
173
+ body = p["body"]
174
+ hit = _LABELS.get(p["id"])
175
+ if hit is not None and hit[0] is body: # the same string object: the page did not change
176
+ return hit[1]
177
+ if len(_LABELS) > 100_000: # many vaults in one process (tests): start again
178
+ _LABELS.clear()
179
+ x = ("Source: " in body and (m := _IMPORTED.search(body)) and m[1]) or ""
180
+ _LABELS[p["id"]] = (body, x)
181
+ return x
182
+
183
+
184
+ def signals(pages: list[dict], events: list[dict], day: str, study: bool) -> dict:
185
+ """How much of the vault serves study, build and research: pages and events, those of the
186
+ last RECENT_DAYS days counted twice. Study: concept, track and assessment pages and taught,
187
+ ask, grade and self-report events, 0 for someone who does not study (`studies`). Build:
188
+ project, decision and loop pages, coding apps' chats and repo pages, chats opened from a
189
+ coding app. Research: resources saved by hand or from a research source, and notes that
190
+ link one. A fold over the page rows and events, never stored."""
191
+ cut = (date.fromisoformat(day) - timedelta(days=RECENT_DAYS)).isoformat()
192
+ out = dict.fromkeys(HOME_GROUPS, 0)
193
+ by_kind = {**dict.fromkeys(STUDY_KINDS, "study"), **dict.fromkeys(BUILD_KINDS, "build")}
194
+ found, notes = set(), [] # research resources' ids; notes that may link one (counted after)
195
+ for p in pages: # one plain pass: it runs over every page on each build
196
+ g = by_kind.get(k := p["kind"])
197
+ if g is None and ((res := k == "resource") or p["source"]):
198
+ x = p["source"] or _label(p) # a resource or chat page's `Source:` label
199
+ if x in CODING_LABELS:
200
+ g = "build"
201
+ elif res and x in RESEARCH_LABELS:
202
+ g = "research"
203
+ found.add(p["id"])
204
+ if g is None:
205
+ if k == "note" and p["links"]:
206
+ notes.append(p)
207
+ continue
208
+ out[g] += 2 if (p["date"] or p["updated"]) > cut else 1 # both ISO day strings
209
+ for p in notes if found else ():
210
+ if not found.isdisjoint(p["links"]):
211
+ out["research"] += 2 if (p["date"] or p["updated"]) > cut else 1
212
+ coding: dict[str, bool] = {} # client name -> a coding app's, asked once per name
213
+ for e in events:
214
+ if (k := e.get("kind")) in STUDY_EVENTS:
215
+ g = "study"
216
+ elif k in ("log", "open") and isinstance(pl := e.get("payload"), dict):
217
+ if k == "log" and pl.get("kind") == "self_report":
218
+ g = "study"
219
+ elif k == "open" and isinstance(c := pl.get("client"), str) and (
220
+ coding[c] if c in coding else coding.setdefault(
221
+ c, any(x in profiles.norm(c) for x in CODING_CLIENTS))):
222
+ g = "build"
223
+ else:
224
+ continue
225
+ else:
226
+ continue
227
+ out[g] += 2 if str(e.get("day") or "") > cut else 1
228
+ if not study:
229
+ out["study"] = 0
230
+ return out
231
+
232
+
233
+ def get_started(pages: list[dict], known: dict) -> dict | None:
234
+ """A new vault's first steps, or None: fewer than NEW_PAGES pages besides me/, rollups
235
+ and Keepfold's session receipts. `fact`: a live line on a me/ page; `imported`: any page an
236
+ import or an AI app's chat import wrote. Derived on each build, never stored; the app adds
237
+ whether an AI app is connected."""
238
+ own = 0
239
+ for p in pages: # stops at NEW_PAGES: a big vault costs nothing here
240
+ if p["kind"] not in ("me", "rollup") and not (
241
+ p["kind"] == "session" and _is_ambient(p["kind"], p["id"])):
242
+ own += 1
243
+ if own >= NEW_PAGES:
244
+ return None
245
+ return {"fact": known["total"]["live"] > 0, "imported": any(map(_imported, pages))}
246
+
247
+
248
+ def home_layout(cfg: dict | None = None) -> list[str] | None:
249
+ """`app.home_layout` in config.yaml: Home's pinned group order, or None (automatic)."""
250
+ a = (taint.config() if cfg is None else cfg).get("app")
251
+ v = a.get("home_layout") if isinstance(a, dict) else None
252
+ ok = isinstance(v, list) and 0 < len(v) == len(set(v)) and all(x in HOME_GROUPS for x in v)
253
+ return v if ok else None
254
+
255
+
256
+ def build_data(vault: Vault, *, now: datetime, relayout: bool = False,
257
+ auto_relayout: bool = True, memo: dict | None = None) -> dict:
258
+ """The dashboard blob; private notes never enter it.
259
+ `relayout` lays the brain out from scratch (brainmap); `auto_relayout=False` never does it
260
+ by itself. `memo`, a dict the caller keeps between builds (the app's home), reuses the pages
261
+ and the brain while their notes are the same objects, and receives the build's pieces
262
+ under "parts" for the home's own sections."""
263
+ catalog = Catalog.load(vault)
264
+ day = local_day(now)
265
+ today_d = date.fromisoformat(day)
266
+ events = list(EventLog(vault).iter_events())
267
+ notes = {k: list(vault.iter_notes(k)) for k in Vault.KIND_DIRS} # parsing dominates; once
268
+ pc = levels.problem_concepts(vault)
269
+ if memo is not None and memo.get("events") != events: # a generation per event log content
270
+ memo["events"], memo["gen"] = events, memo.get("gen", 0) + 1
271
+ gen = memo["gen"] if memo is not None else None
272
+ exam = planner.exam_concepts(vault, catalog, day)
273
+ states, mstates = _once(memo, "fold", (gen, day, pc, exam),
274
+ lambda: levels.fold(events, day, pc, exam))
275
+ private = {n.id for ns in notes.values() for n in ns if is_private(n)}
276
+ hidden = planner.hidden(vault, catalog, private)
277
+ private |= planner.hidden_mistakes(mstates, hidden) # OQ-22: mistakes about private subjects
278
+ entries = [e for e in catalog.entries.values() if e.id not in hidden]
279
+ concepts = [e for e in entries if e.kind == "concept"]
280
+ visible = {e.id for e in concepts}
281
+ shown = {e.id for e in entries}
282
+
283
+ def state(c):
284
+ return states[c].state if c in states else "not_started"
285
+
286
+ tally = Counter(state(e.id) for e in concepts)
287
+ counts = {s: tally[s] for s in ("solid", "learning", "needs_refresh", "unverified",
288
+ "not_started")}
289
+
290
+ items = [i for i in planner.today(vault, catalog, states, now=now, events=events)
291
+ if i["id"] not in hidden]
292
+ today = [{"kind": i["kind"], "id": i["id"], "title": plain(i["title"]),
293
+ "state": i["state"], "why": plain(i["why"])} for i in items]
294
+
295
+ scores = {n.id: n.fields.get("score") for n in notes["assessment"]}
296
+ titles = {n.id: plain(str(n.fields.get("title") or "")) for n in notes["assessment"]}
297
+ pairs, calibrated = _once(memo, "calibrated", (gen, pc),
298
+ lambda: learning_eval.calibrated(events, pc))
299
+
300
+ def assessment(a):
301
+ d = planner._day(a["date"]) if a["date"] else None
302
+ tested = [c for c in planner._weights(catalog, a["tests"]) if c in visible]
303
+ doms = {catalog.entries[c].domain for c in tested}
304
+ score = scores.get(a["id"])
305
+ share = planner.readiness(vault, catalog, states, a)
306
+ return {"id": a["id"], "company": plain(a["company"] or "") or None,
307
+ "title": titles.get(a["id"]) or None,
308
+ "kind": plain(a["kind"] or "") or None, "date": d.isoformat() if d else None,
309
+ "days_left": (d - today_d).days if d else None,
310
+ "outcome": a["outcome"] or "pending",
311
+ "score": plain(str(score)) if score is not None else None,
312
+ "readiness": {"solid": sum(state(c) == "solid" for c in tested),
313
+ "total": len(tested),
314
+ # `weighted` names the weighted share; `share` stays for
315
+ # old readers
316
+ "share": share, "weighted": share,
317
+ # a forecast beside the Solid share, only for a day still ahead
318
+ # and once calibrated, as on the home card; until then, why not
319
+ "forecast": planner.recall_on_day(vault, catalog, states, a, now)
320
+ if d and d >= today_d and calibrated else None,
321
+ "calibrating": None if calibrated or not d or d < today_d
322
+ else {"n": pairs, "need": learning_eval.MIN_PAIRS}},
323
+ "domains": sorted(catalog.entries[x].title for x in doms if x in catalog.entries)}
324
+
325
+ rows = [assessment(a) for a in planner.assessments(vault) if a["id"] not in private]
326
+ coming = [a for a in rows if a["outcome"] == "pending"
327
+ and (a["days_left"] is None or a["days_left"] >= 0)]
328
+ # a plan's real deadline sits beside the exams (plan steps themselves have no dates)
329
+ coming += [{"id": d["id"], "company": plain(d["title"]) or d["id"], "kind": "deadline",
330
+ "date": d["date"], "days_left": d["days"], "outcome": "pending", "score": None,
331
+ "readiness": {"solid": 0, "total": 0, "share": None, "weighted": None,
332
+ "forecast": None, "calibrating": None}, "domains": []}
333
+ for d in planner.deadlines(vault, today_d)]
334
+ coming.sort(key=lambda a: (a["days_left"] is None, a["days_left"] or 0))
335
+
336
+ mtitle = {n.id: _title(n) for n in notes["mistake"]}
337
+ mistakes = sorted(({"id": m.id, "title": mtitle.get(m.id, m.id), "count": m.count,
338
+ "last_day": m.last_day, "status": m.status}
339
+ for m in mstates.values() if m.id not in private),
340
+ key=lambda m: (m["status"] != "open", -_ord(m["last_day"]), m["id"]))
341
+
342
+ # graph
343
+ nodes = [{"id": YOU, "kind": "you", "title": "You", "state": None, "domain": None,
344
+ "area": None, "degree": 0, "open_mistakes": 0, "next_due": None}]
345
+ links = []
346
+ for e in entries:
347
+ st = states.get(e.id)
348
+ nodes.append({"id": e.id, "kind": e.kind, "title": plain(e.title) or e.id,
349
+ "state": state(e.id) if e.kind == "concept" else None,
350
+ "domain": e.domain, "area": e.parent if e.kind == "concept" else
351
+ e.id if e.kind == "area" else None, "degree": 0,
352
+ "open_mistakes": len([m for m in st.open_mistakes if m not in private])
353
+ if st else 0, "next_due": st.next_due if st else None})
354
+ links.append({"s": YOU if e.kind == "domain" else e.parent, "t": e.id,
355
+ "type": "you" if e.kind == "domain" else "hier"})
356
+ links += [{"s": e.id, "t": r, "type": "requires"} for r in e.requires
357
+ if r in visible and r != e.id]
358
+ # extra areas are thin non-tree links; the parent edge above stays the tree
359
+ links += [{"s": a, "t": e.id, "type": "area"} for a in e.areas if a in shown]
360
+ degree = Counter([lk["s"] for lk in links] + [lk["t"] for lk in links])
361
+ for n in nodes:
362
+ n["degree"] = degree[n["id"]]
363
+
364
+ # concept details
365
+ def evidence():
366
+ asks = {e["id"]: e for e in events if e.get("kind") == "ask"}
367
+ trail: dict[str, list[dict]] = {}
368
+ answers = Counter()
369
+ took: dict[str, list[float]] = {} # concept -> seconds from each ask to its grade
370
+ for it in levels._items(events, pc): # void and remap applied, as in the levels fold
371
+ ev = it.ev
372
+ if ev.get("kind") == "grade" and it.concept not in hidden:
373
+ answers[ev.get("day")] += 1
374
+ if it.concept in visible and ev.get("ref") in asks:
375
+ try: # a hand-edited stamp skips this gap, never the dashboard
376
+ took.setdefault(it.concept, []).append(
377
+ (datetime.fromisoformat(ev["ts"])
378
+ - datetime.fromisoformat(asks[ev["ref"]]["ts"])).total_seconds())
379
+ except (KeyError, TypeError, ValueError):
380
+ pass
381
+ if it.concept in visible and it.verdict is not None:
382
+ payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
383
+ kind = (ev.get("item_type") or asks.get(ev.get("ref"), {}).get("item_type")
384
+ or ITEM_TYPE.get(payload.get("kind")))
385
+ trail.setdefault(it.concept, []).append({
386
+ "day": ev.get("day"), "verdict": it.verdict,
387
+ "item_type": plain(kind) if kind else None,
388
+ "source": plain(ev.get("source") or "") or None})
389
+ return trail, answers, {c: n for c, xs in took.items()
390
+ if (n := _answer_secs(xs)) is not None}
391
+
392
+ trail, answers, answer_secs = _once(memo, "evidence", (gen, pc, hidden, visible), evidence)
393
+ study = studies(vault, events, notes)
394
+ leeches = sorted(({"id": e.id, "title": plain(e.title) or e.id, "lapses": states[e.id].lapses}
395
+ for e in concepts if study and levels.is_leech(states.get(e.id))),
396
+ key=lambda r: (-r["lapses"], r["id"]))
397
+ leech_ids = {r["id"] for r in leeches}
398
+ required_by: dict[str, list[str]] = {}
399
+ for lk in links:
400
+ if lk["type"] == "requires":
401
+ required_by.setdefault(lk["t"], []).append(lk["s"])
402
+ problems: dict[str, list[dict]] = {}
403
+ for p in notes["problem"]:
404
+ if p.id in private:
405
+ continue
406
+ row = {"id": p.id, "title": _title(p), "status": plain(p.fields.get("status") or "")
407
+ or None}
408
+ for c in dict.fromkeys(pc.get(p.id, [])):
409
+ if c in visible:
410
+ problems.setdefault(c, []).append(row)
411
+ details = {}
412
+ for e in concepts:
413
+ st = states.get(e.id)
414
+ d = {"evidence": trail.get(e.id, [])[-EVIDENCE_SHOWN:][::-1],
415
+ "requires": [r for r in e.requires if r in visible and r != e.id],
416
+ "required_by": required_by.get(e.id, []),
417
+ "problems": problems.get(e.id, []),
418
+ "mistakes": [m for m in st.open_mistakes if m not in private] if st else []}
419
+ if e.id in leech_ids:
420
+ d["leech"] = planner.leech_why(st)
421
+ if e.id in answer_secs:
422
+ d["answer_secs"] = answer_secs[e.id]
423
+ if any(d.values()):
424
+ details[e.id] = d
425
+
426
+ # history
427
+ monday = today_d - timedelta(days=today_d.weekday())
428
+ weeks = []
429
+ for i in range(WEEKS - 1, -1, -1):
430
+ start = monday - timedelta(weeks=i)
431
+ week = {(start + timedelta(days=j)).isoformat() for j in range(7)}
432
+ weeks.append({"start": start.isoformat(),
433
+ "answers": sum(n for d, n in answers.items() if d in week)})
434
+ cut = (today_d - timedelta(days=MISTAKE_DAYS)).isoformat()
435
+ old = [e for e in events if str(e.get("day", "")) <= cut]
436
+ exam_cut = planner.exam_concepts(vault, catalog, cut)
437
+ _, before = _once(memo, "before", (old, cut, pc, exam_cut),
438
+ lambda: levels.fold(old, cut, pc, exam_cut))
439
+
440
+ def moved(status):
441
+ return sum(1 for m in mstates.values() if m.id not in private and m.status == status
442
+ and getattr(before.get(m.id), "status", None) != status)
443
+
444
+ pages, clusters = _pages(vault, notes, hidden, catalog, pc, memo)
445
+ if memo is not None:
446
+ memo["parts"] = {"notes": notes, "events": events, "states": states, "hidden": hidden,
447
+ "private": private, "catalog": catalog, "items": items}
448
+ parsed = _Parsed(vault.root, notes) # loops and know read notes through this: parsed once
449
+ created = _created(memo)
450
+ loop_notes = {n.id: n for n in notes["loop"]}
451
+ # it reads only the events, the me notes and the claim pages' text (even one that won't parse)
452
+ claimed = [p.read_bytes() if p.is_file() else None
453
+ for p in (vault.root / "me" / f"{c}.md" for c in claims.PAGES)]
454
+ known = _once(memo, "know", (gen, day, notes["me"], claimed),
455
+ lambda: know.report(parsed, events, day))
456
+ profile = next((n for n in notes["me"] if n.id == "profile" and not is_private(n)), None)
457
+ m = _NAME_RE.search(profile.body) if profile else None
458
+ name = plain(m.group(1).strip(string.punctuation)) if m else ""
459
+
460
+ return {
461
+ "as_of": now.astimezone().isoformat(timespec="seconds"),
462
+ "day": day, # the 04:00 Keepfold day, which the calendar date in `as_of` is not
463
+ "plans": _plans(vault, catalog, hidden, pc),
464
+ "counts": counts,
465
+ "today": today,
466
+ # an empty plan is "done" only after work today; never graded at all is a first run
467
+ "plan_cleared": not today and any(e.get("day") == day for e in events),
468
+ "first_run": not today and not any(e.get("kind") == "grade" for e in events),
469
+ # study features (the Study tab, exams, Tomorrow) show only for someone who studies
470
+ "studies": study,
471
+ # UX-E: what Home's boards are ordered by, and a new vault's Get started
472
+ "signals": signals(pages, events, day, study),
473
+ "get_started": get_started(pages, known),
474
+ # concepts forgotten LEECH_LAPSES+ times after they were learned, most lapses first
475
+ "leeches": leeches,
476
+ # any imported page yet (chats, notes, calendar, browsing), which ends the everyone
477
+ # Start here; only someone who does not study is asked (a body scan: ~20 µs a page)
478
+ "imported": not study and any(map(_imported, pages)),
479
+ "assessments": coming,
480
+ # R31: calendar events that look like exams, offered on Home's board to add as one
481
+ "exam_suggestions": exam_suggestions(notes, today_d, private | hidden),
482
+ "mistakes": mistakes,
483
+ "graph": {"nodes": nodes, "links": links},
484
+ "vault_name": vault.root.name,
485
+ "pages": pages,
486
+ "details": details,
487
+ "history": {"weeks": weeks, "assessments": rows,
488
+ "mistakes": {"opened": moved("open"), "resolved": moved("resolved")}},
489
+ # how often each stated confidence (1-4) was right; display-only
490
+ "confidence": _once(memo, "mirror", (gen, pc, hidden),
491
+ lambda: learning_eval.confidence_mirror(events, pc, hidden)),
492
+ "owner": {"name": name} if name else None,
493
+ "clusters": clusters,
494
+ "brain": brainmap.build(vault, pages, clusters, relayout=relayout,
495
+ auto_relayout=auto_relayout,
496
+ memo=None if memo is None else memo.setdefault("brain", {})),
497
+ "counts_by_kind": dict(Counter(p["kind"] for p in pages)),
498
+ # pages the owner worked on today, for the brain's Today (the feed adds the events)
499
+ "today_ids": _today_ids(pages, notes["note"], day),
500
+ "loops": [_plained(r, "title", "summary", "loop_type")
501
+ | {"created": created(loop_notes[r["id"]]).isoformat()}
502
+ for r in loops.loops(parsed)],
503
+ "follow_ups": [_plained(r, "title") for r in loops.follow_ups(parsed, day)],
504
+ "resurface": [_plained(r, "title", "summary")
505
+ for r in loops.resurface(parsed, day, limit=5, events=events,
506
+ created_of=created)],
507
+ "you": {"know": known, "unconfirmed": reflect.unconfirmed(vault, day)[0],
508
+ # R27a Mind Mirror: replaced lines and decisions, a fold (nothing stored)
509
+ "changes": changes(notes, events, private | hidden, day)},
510
+ "help": _help(),
511
+ }
512
+
513
+
514
+ def _claim_rows(notes: dict, shut: set) -> tuple[dict, set]:
515
+ """({(page, claim id): row} of the live and past claims of every shown me/ page, the claim
516
+ ids of the private or hidden ones)."""
517
+ rows, closed = {}, set()
518
+ for n in notes["me"]:
519
+ got = claims.parse(n.id, n.body)
520
+ if n.id in shut or is_private(n):
521
+ closed |= {r["id"] for r in got}
522
+ continue
523
+ rows |= {(n.id, r["id"]): r for r in got if r["status"] in ("live", "past")}
524
+ return rows, closed
525
+
526
+
527
+ def _chain(start, nxt: dict) -> list:
528
+ out, seen = [], set()
529
+ while start is not None and start not in seen:
530
+ seen.add(start)
531
+ out.append(start)
532
+ start = nxt.get(start)
533
+ return out
534
+
535
+
536
+ def changes(notes: dict, events: list, shut: set, today: str) -> list[dict]:
537
+ """R27a Mind Mirror: each chain of versions, newest change first: {kind: line|decision,
538
+ page, versions: [{id, page, text, from, until, open_start, status}]}, oldest version first.
539
+ A line chain is a me/ claim and every line its `## Past` line points to (`→ ^id`, on its own
540
+ page first, else on another); a decision chain is a decision and the ones that replaced it
541
+ (chat_pages.replaced_by). Only chains with a past or retired version. A line starts on its
542
+ `(since …)` day, else the day of the first change event that wrote its id, else when the
543
+ one before it ended, else at its page's earliest known day (`open_start`). A pure fold over
544
+ pages and events; pages in `shut` and private pages never show, and a line that went on to
545
+ one ends as past, never retired."""
546
+ voided = {e.get("ref") for e in events if e.get("kind") == "void"}
547
+ wrote, first = {}, {} # (page, claim id) -> first day written; page -> earliest day seen
548
+ for e in events:
549
+ pl = e.get("payload") if e.get("kind") == "change" else None
550
+ c = pl.get("change") if isinstance(pl, dict) else None
551
+ day = str(e.get("day") or "")
552
+ if not isinstance(c, dict) or e.get("id") in voided or not day:
553
+ continue
554
+ page = str(c.get("id"))
555
+ first[page] = min(first.get(page, day), day)
556
+ for cid in c["claim"] if isinstance(c.get("claim"), list) else [c.get("claim")]:
557
+ if isinstance(cid, str):
558
+ wrote[(page, cid)] = min(wrote.get((page, cid), day), day)
559
+ rows, closed = _claim_rows(notes, shut)
560
+ by_id, link, nxt = {}, {}, {}
561
+ for k in rows:
562
+ by_id.setdefault(k[1], k)
563
+ for k, r in rows.items():
564
+ if r["status"] == "past":
565
+ link[k] = until, to = claims.past_link(r["text"])
566
+ t = (k[0], to) if (k[0], to) in rows else by_id.get(to)
567
+ if to and t:
568
+ nxt[k] = t
569
+ for d in (claims.since(r["text"]), link.get(k, (None,))[0]):
570
+ if d:
571
+ first[k[0]] = min(first.get(k[0], d), d)
572
+ out = []
573
+ for head in rows.keys() - set(nxt.values()):
574
+ keys = _chain(head, nxt)
575
+ if len(keys) == 1 and rows[head]["status"] == "live":
576
+ continue
577
+ versions, prev = [], None
578
+ for n, k in enumerate(keys):
579
+ r, (until, to) = rows[k], link.get(k, (None, None))
580
+ start = claims.since(r["text"]) or wrote.get(k) or prev
581
+ status = ("live" if r["status"] == "live" else "past" if n < len(keys) - 1
582
+ or to in closed else "retired")
583
+ versions.append({"id": k[1], "page": k[0], "text": plain(claims.bare(r["text"]), 300),
584
+ "from": start or first.get(k[0]) or until or today,
585
+ "open_start": start is None, "status": status})
586
+ versions[-1]["until"] = prev = None if status == "live" else max(
587
+ until or versions[-1]["from"], versions[-1]["from"])
588
+ out.append({"kind": "line", "page": keys[-1][0], "versions": versions})
589
+ out += _decision_changes(notes, shut)
590
+ out.sort(key=lambda c: (max(v["until"] or v["from"] for v in c["versions"]), c["page"],
591
+ c["versions"][0]["id"]), reverse=True)
592
+ return out
593
+
594
+
595
+ def _decision_changes(notes: dict, shut: set) -> list[dict]:
596
+ """`changes`' decision chains: a superseded or retired decision and the later shown one
597
+ that replaced it, in turn; a last one that holds no more is retired, on its file's day."""
598
+ decs = {n.id: n for n in notes["decision"] if n.id not in shut and not is_private(n)}
599
+ day = {i: topics.page_date(i, n.fields, n.body) for i, n in decs.items()}
600
+ bodies = sorted((day[i], i, n.body) for i, n in decs.items())
601
+ gone = {i for i, n in decs.items() if str(n.fields.get("status")) in ("superseded", "retired")}
602
+ nxt = {i: by for i in gone if (by := chat_pages.replaced_by(i, day[i], decs[i].body, bodies))}
603
+ out = []
604
+ for head in gone - set(nxt.values()):
605
+ ids, versions = _chain(head, nxt), []
606
+ for n, i in enumerate(ids):
607
+ known = day[i] or None
608
+ start = max(known or _file_day(decs[i]), versions[-1]["from"] if versions else "")
609
+ versions.append({"id": i, "page": i, "text": _title(decs[i]), "from": start,
610
+ "open_start": known is None, "until": None,
611
+ "status": "past" if n < len(ids) - 1
612
+ else "retired" if i in gone else "live"})
613
+ for a, b in zip(versions, versions[1:], strict=False):
614
+ a["until"] = b["from"]
615
+ if versions[-1]["status"] == "retired":
616
+ versions[-1]["until"] = max(_file_day(decs[ids[-1]]), versions[-1]["from"])
617
+ out.append({"kind": "decision", "page": ids[-1], "versions": versions})
618
+ return out
619
+
620
+
621
+ def _file_day(n) -> str:
622
+ """The Keepfold day a page's file was last saved: the only day an undated decision has."""
623
+ return local_day(datetime.fromtimestamp(n.path.stat().st_mtime).astimezone())
624
+
625
+
626
+ def _answer_secs(gaps: list[float]) -> int | None:
627
+ """Median seconds of the last ANSWER_LAST gaps under ANSWER_CUT; None under ANSWER_MIN."""
628
+ kept = [g for g in gaps[-ANSWER_LAST:] if 0 <= g <= ANSWER_CUT]
629
+ return round(statistics.median(kept)) if len(kept) >= ANSWER_MIN else None
630
+
631
+
632
+ def _once(memo: dict | None, name: str, key, fn):
633
+ """fn() once per `key` while the caller keeps `memo` (the app's home); without it, fn()."""
634
+ if memo is None:
635
+ return fn()
636
+ hit = memo.get(name)
637
+ if hit is None or hit[0] != key:
638
+ hit = memo[name] = (key, fn())
639
+ return hit[1]
640
+
641
+
642
+ def _created(memo: dict | None):
643
+ """loops.created (a file stat each), once per note object while the caller keeps `memo`."""
644
+ if memo is None:
645
+ return loops.created
646
+ old, new = memo.get("created", {}), {}
647
+ memo["created"] = new
648
+
649
+ def created(n):
650
+ hit = old.get(n.path)
651
+ new[n.path] = hit = hit if hit is not None and hit[0] is n else (n, loops.created(n))
652
+ return hit[1]
653
+ return created
654
+
655
+
656
+ class _Parsed(SimpleNamespace):
657
+ """A read-only stand-in for the vault that serves the notes build_data already parsed."""
658
+
659
+ def __init__(self, root: Path, notes: dict):
660
+ super().__init__(root=root, notes=notes)
661
+
662
+ def iter_notes(self, kind: str | None = None):
663
+ return iter(self.notes[kind] if kind else [n for ns in self.notes.values() for n in ns])
664
+
665
+
666
+ def _plained(row: dict, *keys: str) -> dict:
667
+ return row | {k: plain(row[k], 300) for k in keys if row.get(k) is not None}
668
+
669
+
670
+ def _read_help(name: str, *repo_path: str) -> str | None:
671
+ """A help file: the wheel's copy (pyproject force-include), else the checkout's."""
672
+ for p in (ASSETS / "help" / name, REPO.joinpath(*repo_path)):
673
+ if p.is_file():
674
+ return p.read_text(encoding="utf-8")
675
+ return None
676
+
677
+
678
+ def _help() -> dict:
679
+ """The `/keepfold help` reference and the GUIDE glossary table (trusted shipped files)."""
680
+ cmds = _read_help("help.md", "skills", "keepfold", "modes", "help.md")
681
+ text = _read_help("GUIDE.md", "docs", "GUIDE.md") or ""
682
+ # match the heading by name, so renumbering the guide's sections can't lose the glossary
683
+ head = next((ln[3:].strip() for ln in text.splitlines()
684
+ if ln.startswith("## ") and ln.rstrip().endswith(GLOSSARY)), None)
685
+ rows = [ln for ln in loops.section_text(text, head).splitlines()
686
+ if ln.startswith("|")] if head else []
687
+ return {"commands_md": cmds,
688
+ "glossary_md": "\n".join(rows) or None}
689
+
690
+
691
+ def _lobes(keep: dict, catalog: Catalog, hidden: set, pc: dict, facts: dict | None = None
692
+ ) -> tuple[dict[str, str], list[dict]]:
693
+ """Page id -> its brain lobe id, and the lobes [{id, title, kind, count}], biggest first.
694
+ A lobe is a top hub (no parent, or a child of the topic map; never the map itself) under its
695
+ hub id, a catalog domain as `domain:<id>`, a GROUPS lobe, or `unfiled`. A hub sits in its
696
+ top hub's lobe; a concept, area or domain page in its domain's; a problem or mistake in the
697
+ domain of its first visible concept; journal, me, session, placement and browse pages in
698
+ their group; any other page in the lobe of its first hub under a top hub, else (projects,
699
+ decisions, loops, people, media and chat resources) in a group; the rest are unfiled.
700
+ A group lobe id that a hub already uses gets a `-group` suffix. `facts`: each page's
701
+ `_facts`, when the caller kept them."""
702
+ facts = facts or {i: _facts(n) for i, n in keep.items()}
703
+ idx = {i: {"kind": n.kind, "title": facts[i][0], "fields": n.fields} for i, n in keep.items()}
704
+ t = topics.tree(SimpleNamespace(_notes=idx)) # tree reads only `_notes`; no search index
705
+
706
+ def top(h):
707
+ p = t.path(h)
708
+ return p[1] if p[0] == topics.ROOT and len(p) > 1 else p[0]
709
+
710
+ def domain(i, fields=None):
711
+ e = catalog.entries.get(i)
712
+ d = (e.domain if e else "") or str((fields or {}).get("domain") or "")
713
+ return f"domain:{d}" if d in catalog.entries and not {d, i} & hidden else None
714
+
715
+ gid = {g: g + "-group" if g in t.parent else g for g in GROUP_TITLES}
716
+
717
+ lobe = {}
718
+ for i, n in idx.items():
719
+ k, f = n["kind"], n["fields"]
720
+ if i in t.parent:
721
+ lobe[i] = top(i)
722
+ elif k in ("concept", "area", "domain"):
723
+ lobe[i] = domain(i, f)
724
+ elif k in ("problem", "mistake"):
725
+ cs = pc.get(i, []) if k == "problem" else _edge_targets(f.get("concepts") or [])
726
+ lobe[i] = next(filter(None, map(domain, cs)), None)
727
+ elif k in GROUPS:
728
+ lobe[i] = gid[GROUPS[k]]
729
+ else:
730
+ hubs = (h for h in dict.fromkeys(facts[i][1]) if h in t.parent) # page_hubs
731
+ lobe[i] = next((x for x in map(top, hubs) if x != topics.ROOT), None) \
732
+ or gid.get(facts[i][2])
733
+ if lobe[i] in (None, topics.ROOT):
734
+ lobe[i] = UNFILED
735
+
736
+ titles = {gid[g]: title for g, title in GROUP_TITLES.items()}
737
+
738
+ def row(c, k):
739
+ if c == UNFILED:
740
+ return {"id": c, "title": "Unfiled", "kind": UNFILED, "count": k}
741
+ if c in titles and c not in t.parent:
742
+ return {"id": c, "title": titles[c], "kind": "group", "count": k}
743
+ if c.startswith("domain:"):
744
+ return {"id": c, "title": plain(catalog.entries[c[7:]].title) or c[7:],
745
+ "kind": "domain", "count": k}
746
+ return {"id": c, "title": idx[c]["title"], "kind": "topic", "count": k}
747
+
748
+ count = Counter(lobe.values())
749
+ return lobe, [row(c, k) for c, k in sorted(count.items(), key=lambda x: (-x[1], x[0]))]
750
+
751
+
752
+ def _facts(n) -> tuple[str, list[str], str | None]:
753
+ """What `_lobes` reads of one note: its title, its `related` targets and the group it
754
+ joins when it has no hub."""
755
+ f = n.fields
756
+ if n.kind != "resource":
757
+ group = NO_HUB.get(n.kind)
758
+ else:
759
+ src = topics.page_source(n.body).lower()
760
+ tags = f.get("tags")
761
+ tags = tags if isinstance(tags, list) else str(tags or "").replace(",", " ").split()
762
+ group = "media" if src in MEDIA or MEDIA & {str(x).lstrip("#").lower() for x in tags} \
763
+ else "chats" if src in CHATS else None
764
+ return _title(n), _edge_targets(f.get("related") or []), group
765
+
766
+
767
+ def _prop(v):
768
+ if isinstance(v, list):
769
+ return [str(x)[:300] for x in v[:SHOWN_PROPS]]
770
+ return str(v)[:300]
771
+
772
+
773
+ def _pages(vault: Vault, notes: dict, hidden: set, catalog: Catalog, pc: dict,
774
+ memo: dict | None = None) -> tuple[list[dict], list[dict]]:
775
+ """Every non-private note for the reader view (`raw/` is not a kind), and
776
+ the brain lobes (`_lobes`). With `memo`, the same note objects and catalog give the same
777
+ result, and a note object seen before keeps its row (the app's home reuses unchanged
778
+ notes; a changed file is a new object)."""
779
+ flat = [n for ns in notes.values() for n in ns]
780
+ hit = memo.get("pages") if memo is not None else None
781
+ if (hit and hit[1] == catalog.entries and hit[2] == hidden and len(hit[0]) == len(flat)
782
+ and all(map(operator.is_, hit[0], flat))):
783
+ return hit[3]
784
+ keep = {}
785
+ for n in flat:
786
+ if n.id not in hidden and not is_private(n):
787
+ keep.setdefault(n.id, n) # an id clash keeps the first kind, as wikilinks do
788
+ old = memo.get("rows", {}) if memo is not None else {}
789
+ got = {}
790
+ for i, n in keep.items():
791
+ hit = old.get(n.path)
792
+ got[i] = hit if hit is not None and hit[0] is n else (n, *_row(vault, n), None)
793
+ lobe, clusters = _lobes(keep, catalog, hidden, pc, {i: g[3] for i, g in got.items()})
794
+ rows, pages = {}, []
795
+ for i, (n, base, raw, facts, last) in got.items():
796
+ links = [x for x in raw if x in keep and x != i]
797
+ row = last if last and last["links"] == links and last["cluster"] == lobe[i] else \
798
+ {**base, "links": links, "cluster": lobe[i]}
799
+ rows[n.path] = (n, base, raw, facts, row)
800
+ pages.append(row)
801
+ if memo is not None:
802
+ memo["rows"] = rows
803
+ memo["pages"] = (flat, catalog.entries, hidden, (pages, clusters))
804
+ return pages, clusters
805
+
806
+
807
+ def _row(vault: Vault, n) -> tuple[dict, list[str], tuple]:
808
+ """A page's row without `links` and `cluster`, every link target its text names, and its
809
+ `_facts`."""
810
+ f = n.fields
811
+ tags = f.get("tags")
812
+ tags = tags if isinstance(tags, list) else str(tags or "").replace(",", " ").split()
813
+ body = n.body
814
+ if len(body.encode()) > BODY_MAX:
815
+ body = body.encode()[:BODY_MAX].decode(errors="ignore") + TRUNCATED
816
+ text = " ".join(str(v) for v in f.values()) + n.body
817
+ facts = _facts(n)
818
+ return {
819
+ "id": n.id, "kind": n.kind, "title": facts[0],
820
+ "summary": plain(f.get("summary") or "", 300) or None,
821
+ "tags": [str(t).lstrip("#") for t in tags if str(t).strip("#")][:SHOWN_PROPS],
822
+ "props": {str(k): _prop(v) for k, v in f.items()
823
+ if k not in TOOL_PROPS | {"id", "title", "summary", "private"}},
824
+ "body": body,
825
+ "links": None,
826
+ "path": n.path.relative_to(vault.root).as_posix(),
827
+ # the 04:00 Keepfold day, so a page saved at 1 a.m. counts as that night's Today
828
+ "updated": local_day(datetime.fromtimestamp(n.path.stat().st_mtime).astimezone()),
829
+ "date": topics.page_date(n.id, f, n.body) or None,
830
+ "source": plain(topics.page_source(n.body)) or None,
831
+ "cluster": None}, list(dict.fromkeys(link_targets(text))), facts
832
+
833
+
834
+ def _today_ids(pages: list[dict], notes: list, day: str) -> list[str]:
835
+ """The shown pages the owner worked on today, not ones a Keepfold job rewrote: never a
836
+ rollup or a topic hub (Keepfold builds and rewrites those); an imported page (a `Source:`
837
+ line) or a browse page only when its own item is dated today, since an import rewrites
838
+ the file; any other page by the Keepfold day it was last saved."""
839
+ hubs = {n.id for n in notes if topics.is_hub({"kind": n.kind, "fields": n.fields})}
840
+ # an AI chat's session receipt neither: the pages it changed are in Today already
841
+ return [p["id"] for p in pages
842
+ if p["kind"] != "rollup" and p["id"] not in hubs
843
+ and not _is_ambient(p["kind"], p["id"])
844
+ and (p["date"] if _imported(p) else p["updated"]) == day]
845
+
846
+
847
+ def _imported(p: dict) -> bool:
848
+ """A page row an import wrote: a `Source:` line (an AI chat, notes, calendar) or browsing."""
849
+ return bool(p["source"] or p["kind"] == "browse" or _IMPORTED.search(p["body"]))
850
+
851
+
852
+ def _ord(day) -> int:
853
+ return date.fromisoformat(day).toordinal() if day else 0
854
+
855
+
856
+ def _sha(script: str) -> str:
857
+ return "'sha256-" + base64.b64encode(hashlib.sha256(script.encode()).digest()).decode() + "'"
858
+
859
+
860
+ def render_html(data: dict) -> str:
861
+ """One self-contained page: the template with the CSS, data blob and scripts inlined."""
862
+ read = lambda name: (ASSETS / name).read_text(encoding="utf-8") # noqa: E731
863
+ lic = read("LICENSE-d3.txt").strip()
864
+ # The XML namespace strings are not fetched; `\/` keeps them from reading as URLs.
865
+ d3 = f"/*! d3 v7.9.0 | ISC License\n{lic}\n*/\n" + read("d3.v7.min.js").replace(
866
+ '"http://www.w3.org', '"http:\\/\\/www.w3.org')
867
+ brain, app = read("brain3d.js"), read("dashboard.js")
868
+ csp = (f"default-src 'none'; script-src {_sha(d3)} {_sha(brain)} {_sha(app)}; "
869
+ "style-src 'unsafe-inline'; img-src data:")
870
+ # `:\/\/` is the same JSON string; note URLs then never read as fetchable URLs in the page
871
+ blob = (json.dumps(data, ensure_ascii=False, separators=(",", ":"))
872
+ .replace("<", "\\u003c").replace("://", ":\\/\\/"))
873
+ slots = {"CSPMETA": f'<meta http-equiv="Content-Security-Policy" content="{csp}">',
874
+ "STYLE": f"<style>{read('dashboard.css')}</style>",
875
+ "SCRIPTS": f'<script type="application/json" id="data">{blob}</script>\n'
876
+ f"<script>{d3}</script>\n<script>{brain}</script>\n<script>{app}</script>"}
877
+ return _SLOT.sub(lambda m: slots[m.group(1)], read("dashboard.html.tmpl"))
878
+
879
+
880
+ LIVE_FILES = ("d3.v7.min.js", "brain3d.js", "dashboard.js")
881
+
882
+
883
+ def render_live(key: str) -> str:
884
+ """The app's live home: the same template with the CSS and scripts served by the app (its
885
+ CSP header holds); no data blob, dashboard.js fetches /api/home. `key` busts the cache as
886
+ on the app's other pages ('' when the page was opened without it)."""
887
+ q = f"?t={key}"
888
+ slots = {"CSPMETA": "", "STYLE": f'<link rel="stylesheet" href="/dashboard.css{q}">',
889
+ "SCRIPTS": "\n".join(f'<script src="/{n}{q}" defer></script>' for n in LIVE_FILES)}
890
+ return _SLOT.sub(lambda m: slots[m.group(1)],
891
+ (ASSETS / "dashboard.html.tmpl").read_text(encoding="utf-8"))
892
+
893
+
894
+ @contextmanager
895
+ def _snapshot_parses(vault: Vault):
896
+ """Serve notes whose (mtime, size) still match the search index's snapshot from it, instead
897
+ of opening and YAML-parsing every file again (most of a big vault's build time). Scoped:
898
+ the entries leave the parse cache afterwards, so a later write in this process reads the
899
+ file itself. Snapshot values are JSON (a date is its ISO string); the build reads them as
900
+ text. Private entries hold no fields and are parsed as usual."""
901
+ added = {}
902
+ try:
903
+ files = json.loads((vault.root / index.SNAPSHOT).read_bytes())
904
+ files = files["files"] if files.get("schema") == index.SNAPSHOT_SCHEMA else {}
905
+ except (OSError, ValueError, AttributeError, KeyError):
906
+ files = {}
907
+ for rel, e in files.items() if isinstance(files, dict) else ():
908
+ if not (isinstance(e, list) and len(e) == 6 and isinstance(e[4], dict)
909
+ and isinstance(e[5], str) and e[2] in Vault.KIND_DIRS and e[2] != "browse"):
910
+ continue
911
+ # the key is "<folder name>/<id>.md" (Index._rel): "chats/<id>.md" in archive/chats/
912
+ d = next((d for d in Vault.dirs(e[2]) if d.rsplit("/", 1)[-1] == rel.split("/")[0]),
913
+ Vault.KIND_DIRS[e[2]])
914
+ path = vault.root / d / f"{e[3]}.md"
915
+ if path not in vault_mod._PARSED:
916
+ added[path] = vault_mod._PARSED[path] = ((e[0], e[1]), e[4], e[5])
917
+ try:
918
+ yield
919
+ finally:
920
+ for path, hit in added.items():
921
+ if vault_mod._PARSED.get(path) is hit:
922
+ del vault_mod._PARSED[path]
923
+
924
+
925
+ def build(vault: Vault, *, now: datetime, relayout: bool = False) -> dict:
926
+ """build_data, reading unchanged notes from the search index's snapshot."""
927
+ with _snapshot_parses(vault):
928
+ return build_data(vault, now=now, relayout=relayout)
929
+
930
+
931
+ def snapshot(vault: Vault, *, now: datetime) -> str:
932
+ """The self-contained page Export snapshot saves where the owner chooses (never in the
933
+ vault): non-private items only, CSP default-src 'none'. A pinned Home layout is baked in."""
934
+ return render_html({**build(vault, now=now), "home_layout": home_layout()})
935
+
936
+
937
+ def retire_old(vault: Vault) -> Path | None:
938
+ """`.keepfold/dashboard.html`, which Keepfold no longer writes, moves to `.keepfold/backups/`
939
+ once (copied, then removed; never deleted outright). The new path, or None."""
940
+ old = vault.root / ".keepfold" / "dashboard.html"
941
+ if not old.is_file():
942
+ return None
943
+ day = datetime.fromtimestamp(old.stat().st_mtime).strftime("%Y-%m-%d")
944
+ new = vault.write_text(vault.root / ".keepfold" / "backups" / f"dashboard-{day}.html",
945
+ old.read_bytes().decode("utf-8", "replace"))
946
+ vault.remove(old)
947
+ return new
948
+
949
+
950
+ def write_index(vault: Vault, *, now: datetime) -> Path:
951
+ """Regenerate `<vault>/index.md`, the one-file text map of every non-private page. Built
952
+ on demand (`keepfold dashboard`), never at session close."""
953
+ catalog = Catalog.load(vault)
954
+ with _snapshot_parses(vault):
955
+ after, _ = planner.current_states(vault, local_day(now), catalog)
956
+ private = planner.hidden(vault, catalog)
957
+ notes = [n for n in vault.iter_notes() if not is_private(n) and n.id not in private]
958
+ text = index_md(notes, catalog.entries, {c: s.state for c, s in after.items()})
959
+ return vault.write_text(vault.root / "index.md", text)