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/render.py ADDED
@@ -0,0 +1,406 @@
1
+ """Rendering of the brief, chat cards and Today.md. Pure text in, text out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+ from datetime import date
8
+
9
+ from keepfold.levels import GLYPH, LABEL
10
+ from keepfold.planner import CAP
11
+ from keepfold.vault import Vault
12
+
13
+ MODE_LABEL = {
14
+ "home": "Home",
15
+ "learn": "Learning session",
16
+ "short": "Short session (5 steps)",
17
+ "review": "Refresh session",
18
+ "log": "Logging",
19
+ "about": "Lookup (read-only)",
20
+ "week": "Weekly review (read-only)",
21
+ "capture": "Capture",
22
+ "reflect": "Reflect",
23
+ "project": "Project",
24
+ "save": "Save this chat",
25
+ "history": "Chat history",
26
+ "sweep": "Sweep",
27
+ "mock": "Mock interview",
28
+ }
29
+ MODE_HINT = {
30
+ "home": "What would you like to do?",
31
+ "capture": "Share the source; Keepfold files it as a resource with linked notes.",
32
+ "reflect": "Review what is unconfirmed, emerging or old in the vault.",
33
+ "project": "Name the project to work on; Keepfold loads its notes.",
34
+ "save": "Keepfold files what is worth keeping from this conversation.",
35
+ "history": "Pick past chats to save (ones already saved are marked), or distil imported "
36
+ "chats a bundle at a time (/keepfold harvest).",
37
+ }
38
+ PLAN_LINES, COMING_UP, MISTAKES_SHOWN, MOVED_SHOWN, NEXT_SHOWN = 8, 3, 3, 6, 3
39
+ CHANGED_SHOWN = 15
40
+ HOME_SHOWN, FOLLOW_UPS_SHOWN, DUE_SLICE = 3, 2, CAP # home card caps (UX-7, COACH-3, COACH-6)
41
+ NO_CONCEPT = "▫"
42
+ CUE_KINDS, CUE_CHARS = ("confident_miss", "warmup", "refresh"), 140 # Today.md past-question cue
43
+ TODAY_HEADER = "<!-- generated by keepfold; safe to delete -->"
44
+ INDEX_HEADER = TODAY_HEADER
45
+
46
+ _URL_PART = r"\((?:[^()]|\([^()]*\))*\)" # one level of balanced parens: (http://x/(y))
47
+ _IMAGE_RE = re.compile(r"!\[[^\]]*\]" + _URL_PART)
48
+ _LINK_RE = re.compile(r"\[([^\]]*)\]" + _URL_PART)
49
+ # C0/C1 controls (terminal escape sequences, NUL) and bidi overrides that reorder a line
50
+ _CTRL_RE = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f‪-‮⁦-⁩]")
51
+ _WIKI_RE = re.compile(r"\[\[([^\]|]*)(?:\|([^\]]*))?\]\]")
52
+ _TAG_RE = re.compile(r"<[^>]*>")
53
+ _URL_RE = re.compile(r"(?:https?://|www\.)\S*", re.I)
54
+ _MD_CHARS = re.compile(r"([\\`*_\[\]#|~])")
55
+
56
+
57
+ def term(text) -> str:
58
+ """Untrusted text for a terminal: control and bidi characters dropped, newline and tab
59
+ kept. The CLI prints note titles, chat lines and model answers through this."""
60
+ return _CTRL_RE.sub("", str(text))
61
+
62
+
63
+ def plain(text: str, limit: int = 120) -> str:
64
+ """Untrusted note text as one line with images, links, URLs, HTML tags, control and bidi
65
+ characters stripped."""
66
+ s = _IMAGE_RE.sub("", term(text or ""))
67
+ s = _LINK_RE.sub(r"\1", s)
68
+ s = _WIKI_RE.sub(lambda m: m.group(2) or m.group(1), s)
69
+ s = _TAG_RE.sub("", s)
70
+ s = _URL_RE.sub("", s)
71
+ s = " ".join(s.replace("](", "] (").split())
72
+ if len(s) > limit:
73
+ s = s[: limit - 1].rstrip() + "…"
74
+ return s
75
+
76
+
77
+ def esc(text: str, limit: int = 120) -> str:
78
+ """Make untrusted note text safe for Markdown: no images, links, URLs, HTML or markup."""
79
+ s = _MD_CHARS.sub(r"\\\1", plain(text, limit))
80
+ # entities, not backslashes, so no "<" survives for HTML-aware renderers
81
+ return s.replace("<", "&lt;").replace(">", "&gt;")
82
+
83
+
84
+ def brief_text(brief_md: str, budget_tokens: int = 1500) -> str:
85
+ """BRIEF.md capped at budget_tokens (chars/4), cut at a line boundary."""
86
+ cap = budget_tokens * 4
87
+ if len(brief_md) <= cap:
88
+ return brief_md
89
+ marker = "[brief truncated]"
90
+ cut = brief_md[: cap - len(marker) - 1]
91
+ nl = cut.rfind("\n")
92
+ return (cut[:nl] if nl > 0 else cut).rstrip() + "\n" + marker
93
+
94
+
95
+ def _glyph(item: Mapping) -> str:
96
+ return GLYPH.get(item.get("state"), NO_CONCEPT)
97
+
98
+
99
+ def _label(a: Mapping) -> str:
100
+ company, kind = str(a.get("company") or ""), str(a.get("kind") or "")
101
+ if kind.lower() in company.lower().split(): # "Practice OA" + "oa" says OA once
102
+ kind = ""
103
+ return f"{company} {kind}".strip() or a.get("id", "")
104
+
105
+
106
+ def _assessment(a: Mapping) -> str:
107
+ what = esc(_label(a))
108
+ return f"{what} · {esc(a.get('date') or '') or 'date not set'}"
109
+
110
+
111
+ def _pending(assessments: list[dict]) -> list[dict]:
112
+ """Pending, non-private assessments: a private one's company and date never reach Claude."""
113
+ return [a for a in assessments
114
+ if (a.get("outcome") or "pending") == "pending" and not a.get("private")]
115
+
116
+
117
+ def _deadline(d: Mapping) -> str:
118
+ n = d["days"]
119
+ left = "due today" if n == 0 else "1 day left" if n == 1 else f"{n} days left"
120
+ return f"{esc(d['title'])}: {left}"
121
+
122
+
123
+ def _coming(assessments: list[dict], deadlines: list[dict]) -> list[str]:
124
+ """Coming up: pending assessments and plan deadlines by date, undated tests last."""
125
+ rows = [(a.get("date") or "~", _assessment(a)) for a in _pending(assessments)] + [
126
+ (d["date"], _deadline(d)) for d in deadlines]
127
+ return [text for _, text in sorted(rows, key=lambda r: r[0])]
128
+
129
+
130
+ def _unchecked_titles(today: list[dict]) -> list[str]:
131
+ return [esc(i["title"]) for i in today if i.get("kind") == "unchecked"]
132
+
133
+
134
+ def _few(items, sep: str = " · ", n: int = HOME_SHOWN, more: str = " more") -> str:
135
+ """At most n items (escaped here) and "+N more"."""
136
+ items = list(items)
137
+ tail = f" +{len(items) - n}{more}" if len(items) > n else ""
138
+ return sep.join(esc(x) for x in items[:n]) + tail
139
+
140
+
141
+ def _when(days: int) -> str:
142
+ return "today" if days == 0 else "tomorrow" if days == 1 else f"in {days} days"
143
+
144
+
145
+ def home_card(*, domains: list[tuple], due: list[str], open_mistakes: int,
146
+ projects: list[str] = (), loops: list[str] = (), ideas: list[str] = (),
147
+ coming_up: Mapping | None = None, solid: list[str] = (), back: list[str] = (),
148
+ resolved: int = 0, unconfirmed: int = 0, revisit: list[str] = (),
149
+ edits: list[Mapping] = (), unlearned: int = 0,
150
+ undated: list[str] = (), studies: bool = True) -> str:
151
+ """The lean /keepfold card, at most 10 lines (UX-7). `domains` are (title, in_progress, solid,
152
+ not_started); `due` the due concept titles, most urgent first; `coming_up` an assessment
153
+ dict with `days`, `solid`, `total`, `more` and an optional `forecast` (recall on its
154
+ `date`, 0..1) or `calibrating` ({n, need} history pairs); `solid`/`back` concept titles
155
+ that reached
156
+ Solid / came back from Needs refresh this week; `revisit` decision ids; `edits` ambient
157
+ contract/profile edits {session, day, pages}, latest first;
158
+ `undated` ids of pending assessments with no date or a past one; without `studies`
159
+ (dashboard.studies) no concept map, Due line or study menu.
160
+ Optional lines show only when non-empty; every item is raw text, escaped here."""
161
+ parts = [f"{t} {GLYPH['learning']} {a} {GLYPH['solid']} {b} {GLYPH['not_started']} {c}"
162
+ for t, a, b, c in domains]
163
+ life = [f"**{head}:** " + _few(items)
164
+ for head, items in (("Projects", projects), ("Open loops", loops),
165
+ ("From your notes", ideas)) if items]
166
+ lines = ["### Keepfold"]
167
+ if coming_up:
168
+ a = coming_up
169
+ bits = [esc(_label(a)), _when(a["days"])]
170
+ if a.get("total"):
171
+ bits.append(f"{a['solid']} of {a['total']} tested topics solid")
172
+ if a.get("forecast") is not None: # beside the Solid count, never instead of it
173
+ d = date.fromisoformat(str(a["date"])[:10])
174
+ bits.append(f"forecast recall on {d.day} {d:%b}: {round(100 * a['forecast'])}%")
175
+ elif a.get("calibrating") and a.get("total"): # why no number yet
176
+ c = a["calibrating"]
177
+ bits.append(f"forecast after {c['need']} checked reviews ({c['n']} so far)"
178
+ if c["n"] < c["need"] else "forecast still calibrating") # B5: no skill
179
+ more = f" (+{a['more']} more)" if a.get("more") else ""
180
+ lines.append("**Coming up:** " + " · ".join(bits) + more)
181
+ if due: # never the raw backlog above a slice (COACH-3)
182
+ tail = (f" +{len(due) - HOME_SHOWN}" if HOME_SHOWN < len(due) <= DUE_SLICE
183
+ else f" · a slice of {DUE_SLICE} is plenty today" if len(due) > DUE_SLICE
184
+ else "")
185
+ due_s = ", ".join(esc(t) for t in due[:HOME_SHOWN]) + tail
186
+ else:
187
+ due_s = "nothing today"
188
+ lately = [*([f"now solid: {_few(solid, ', ')}"] if solid else []),
189
+ *([f"back to solid: {_few(back, ', ')}"] if back else []),
190
+ *([f"{resolved} mistake{'s' * (resolved != 1)} resolved"] if resolved else [])]
191
+ wait = [*([f"{unconfirmed} about-me line{'s' * (unconfirmed != 1)} to confirm"]
192
+ if unconfirmed else []),
193
+ *([f"decisions to revisit: {_few(revisit, ', ', n=FOLLOW_UPS_SHOWN)}"]
194
+ if revisit else []),
195
+ *([f"{len(undated)} test{'s' * (len(undated) != 1)} "
196
+ f"need{'s' * (len(undated) == 1)} a date (or a result): "
197
+ + ", ".join(f"[[{esc(i)}]]" for i in undated[:HOME_SHOWN])] if undated else []),
198
+ *([f"{unlearned} past chat{'s' * (unlearned != 1)} to learn from"]
199
+ if unlearned else [])]
200
+ if edits:
201
+ e = edits[0]
202
+ wait.append(f"{' and '.join(e['pages'])} edited in another chat on {esc(e['day'])} · "
203
+ f"undo: `keepfold undo {e['session']}`" # ids checked by the caller
204
+ + (f" (+{len(edits) - 1} more)" if len(edits) > 1 else ""))
205
+ return "\n".join([
206
+ *lines, *life,
207
+ *(["**Your map:** " + (_few(parts) or "no concepts yet")] if studies else []),
208
+ *([f"**Due:** {due_s} · **Open mistakes:** {open_mistakes}"] if studies else []),
209
+ *(["**Lately:** " + " · ".join(lately)] if lately else []),
210
+ *(["**Waiting for you:** " + " · ".join(wait)] if wait else []),
211
+ "**What would you like to do?** recall something · save this chat · a project · "
212
+ "open the graph · today's plan"
213
+ + (" · study: learn a topic, review what's due, a 10-question sweep" if studies else "")])
214
+
215
+
216
+ def start_card(*, mode: str, today: list[dict], assessments: list[dict],
217
+ open_mistakes: list[tuple[str, int]], date: str,
218
+ deadlines: list[dict] = ()) -> str:
219
+ """Plan steps carry no day or date (v8: a plan is an ordered list per subject); only
220
+ assessments and plan deadlines (planner.deadlines) under Coming up have dates."""
221
+ head = ["Keepfold", MODE_LABEL.get(mode, esc(mode))]
222
+ if mode == "sweep" and today: # dogfood r4 #7: the plan's length, not a promised 10
223
+ head[1] += f" ({len(today)} cold question{'s' if len(today) > 1 else ''})"
224
+ head.append(esc(date))
225
+ lines = ["### " + " · ".join(head)]
226
+ if mode in MODE_HINT: # no quiz plan: the brief (returned beside the card) and one hint
227
+ return "\n".join([*lines, MODE_HINT[mode]])
228
+ shown = today if mode == "sweep" else today[:PLAN_LINES] # a sweep is not in Today.md
229
+ if today:
230
+ lines.append(f"**Today's plan** ({len(shown)} of {len(today)})")
231
+ lines += [f"- {_glyph(i)} {esc(i['title'])} · {esc(i.get('why') or '')}".rstrip(" ·")
232
+ for i in shown]
233
+ if len(today) > len(shown):
234
+ lines.append(f"+{len(today) - len(shown)} more in Today.md")
235
+ elif mode != "mock": # a mock has no plan; its card keeps assessments and mistakes
236
+ lines.append("**Today's plan:** nothing planned yet")
237
+ unchecked = _unchecked_titles(today) # the plan's lane: privacy-filtered, 7-day rule
238
+ if unchecked:
239
+ lines.append("**Taught, not yet checked:** " + ", ".join(unchecked))
240
+ coming = _coming(assessments, deadlines)[:COMING_UP]
241
+ if coming:
242
+ lines.append("**Coming up:** " + "; ".join(coming))
243
+ if open_mistakes:
244
+ lines.append("**Open mistakes:** " + ", ".join(
245
+ f"⚑ {esc(t)} ({n}×)" for t, n in open_mistakes[:MISTAKES_SHOWN]))
246
+ return "\n".join(lines)
247
+
248
+
249
+ def _change(c: Mapping) -> str:
250
+ kind, op, target = c.get("kind") or "", c.get("op"), c.get("target")
251
+ if kind == "person": # V4: session notes are indexed, so never name a private person
252
+ return "changed a people page"
253
+ ref = esc(f"{Vault.KIND_DIRS.get(kind, kind)}/{c.get('id')}")
254
+ if c.get("tool") == "patch":
255
+ if op == "set_field":
256
+ return f"set {ref} {esc(target or '')}"
257
+ if op == "set_topics":
258
+ return f"set topics on {ref}"
259
+ verb = "checked an item in" if op == "check_item" else "patched"
260
+ tail = " (append)" if op == "append_to_section" else ""
261
+ return f"{verb} {ref} § {esc(target or '')}{tail}"
262
+ if c.get("tool") == "split":
263
+ return f"split {ref} into sub-topics ({esc(str(target))} pages moved)"
264
+ if c.get("tool") == "void":
265
+ return f"voided {esc(kind)} {esc(c.get('id'))} ({esc((c.get('reason') or '')[:200])})"
266
+ if c.get("tool") == "journal":
267
+ return "journal line added"
268
+ if c.get("tool") == "add":
269
+ return f"{'adopted' if op == 'adopt' else 'added'} {esc(kind)} {esc(c.get('id'))}"
270
+ return f"{esc(c.get('tool'))} {ref}"
271
+
272
+
273
+ def changed_lines(changes: list[dict]) -> list[str]:
274
+ """One Markdown bullet per distinct vault change, repeats as ×N, capped."""
275
+ seen: dict[str, int] = {}
276
+ for c in changes:
277
+ line = _change(c)
278
+ seen[line] = seen.get(line, 0) + 1
279
+ lines = [f"- {k}" + (f" ×{n}" if n > 1 else "") for k, n in seen.items()]
280
+ if len(lines) > CHANGED_SHOWN:
281
+ lines = lines[:CHANGED_SHOWN] + [f"+{len(lines) - CHANGED_SHOWN} more"]
282
+ return lines
283
+
284
+
285
+ def end_card(*, counts: dict, moved: list[dict], unchecked: list[str], new_mistakes: list[str],
286
+ next_items: list[dict], plan_cleared: bool, duration_min: int,
287
+ changes: list[dict] = (), not_committed: list[str] = ()) -> str:
288
+ """`moved` items are {title, before, after} with state keys; `counts` has graded, logged;
289
+ `not_committed` holds session close's "<path>: <pattern>" entries (files held back)."""
290
+ lines = [f"### Session closed · {duration_min} min · {counts.get('graded', 0)} answers · "
291
+ f"{counts.get('logged', 0)} logged"]
292
+ if moved:
293
+ parts = [f"{esc(m['title'])} {GLYPH.get(m.get('before'), NO_CONCEPT)} → "
294
+ f"{GLYPH.get(m.get('after'), NO_CONCEPT)} {LABEL.get(m.get('after'), '')}".rstrip()
295
+ for m in moved[:MOVED_SHOWN]]
296
+ if len(moved) > MOVED_SHOWN:
297
+ parts.append(f"+{len(moved) - MOVED_SHOWN} more")
298
+ lines.append("**Moved:** " + "; ".join(parts))
299
+ else:
300
+ lines.append("**Moved:** nothing changed this time")
301
+ if new_mistakes:
302
+ lines.append("**New mistakes:** " + "; ".join(f"⚑ {esc(t)}" for t in new_mistakes))
303
+ if unchecked:
304
+ lines.append("**Taught, not yet checked:** " + ", ".join(esc(t) for t in unchecked)
305
+ + " — first in your next plan")
306
+ if changes:
307
+ lines += ["**Changed:**", *changed_lines(changes)]
308
+ types: dict[str, int] = {}
309
+ for c in changes:
310
+ if c.get("tool") == "add" and c.get("kind") == "note" and c.get("op") == "create":
311
+ t = str(c.get("note_type") or "untyped")
312
+ types[t] = types.get(t, 0) + 1
313
+ if types:
314
+ lines.append(f"**New notes this session:** {sum(types.values())} ("
315
+ + ", ".join(f"{n} {esc(t)}" for t, n in sorted(types.items())) + ")")
316
+ # the pattern holds no ": " (vault.SECRET_RES), so the path is what precedes it
317
+ lines += [f"Not committed: {esc(w.rpartition(': ')[0] or w)} (looks like a key)"
318
+ for w in not_committed]
319
+ if next_items:
320
+ lines.append("**Next:** " + ", ".join(esc(i["title"]) for i in next_items[:NEXT_SHOWN]))
321
+ if plan_cleared:
322
+ lines.append("Done for today ✓")
323
+ return "\n".join(lines)
324
+
325
+
326
+ def today_md(*, today: list[dict], assessments: list[dict], as_of: str,
327
+ cues: Mapping[str, str] | None = None, deadlines: list[dict] = ()) -> str:
328
+ """`cues` maps concept -> last question asked on it (raw); re-check items show it.
329
+ `deadlines` (planner.deadlines) join the assessments under Coming up."""
330
+ cues = cues or {}
331
+ lines = [TODAY_HEADER, f"# Today · {esc(as_of)}", "", "## Plan"]
332
+ for i in today:
333
+ state = i.get("state")
334
+ mark = f"{GLYPH[state]} {LABEL[state]}" if state in GLYPH else NO_CONCEPT
335
+ why = esc(i.get("why") or "")
336
+ # the planner's "more steps" pointer links its track page (a vault id, ID_RE-safe)
337
+ title = f"More steps are in [[{esc(i['more'])}]]" if i.get("more") \
338
+ else esc(i["title"])
339
+ lines.append(f"- {mark} · {title}" + (f" · {why}" if why else ""))
340
+ if i.get("model"): # a vault id, ID_RE-safe like `more`
341
+ lines.append(f" - Re-derive [[{esc(i['model'])}]]: approach and complexity in "
342
+ "2 minutes, no code")
343
+ if i["kind"] in CUE_KINDS and cues.get(i["id"]):
344
+ lines.append(" - Past question (answer in your own words first): "
345
+ + esc(cues[i["id"]], CUE_CHARS))
346
+ if not today:
347
+ lines.append("Nothing planned yet.")
348
+ unchecked = _unchecked_titles(today)
349
+ if unchecked:
350
+ lines += ["", "## Taught but not checked"] + [f"- {t}" for t in unchecked]
351
+ coming = _coming(assessments, deadlines)
352
+ if coming:
353
+ lines += ["", "## Coming up"] + [f"- {c}" for c in coming]
354
+ lines += ["", "Refresh with /keepfold or `keepfold brief`", ""]
355
+ return "\n".join(lines)
356
+
357
+
358
+ INDEX_KINDS = (("project", "Projects"), ("resource", "Resources"), ("decision", "Decisions"),
359
+ ("problem", "Problems"), ("mistake", "Mistakes"), ("assessment", "Assessments"),
360
+ ("application", "Applications"), ("track", "Tracks"))
361
+ NOTE_SECTIONS = (("permanent", "Permanent notes"), ("structure", "Structure notes"))
362
+ INDEX_JOURNAL = 30 # latest journal pages listed, newest first
363
+
364
+
365
+ def index_md(notes: list, entries: Mapping, states: Mapping[str, str]) -> str:
366
+ """index.md: non-private notes by kind, concepts domain > area.
367
+
368
+ `entries` is Catalog.entries (for titles and grouping), `states` maps concept id to state.
369
+ """
370
+ def line(n, glyph: str = "") -> str:
371
+ label = esc(n.fields.get("summary") or "") or esc(n.fields.get("title") or n.id)
372
+ return f"- {glyph}[[{n.id}]] — {label}"
373
+
374
+ def title(id: str) -> str:
375
+ return esc(entries[id].title) if id in entries else esc(id)
376
+
377
+ out = [INDEX_HEADER, "# Index"]
378
+ tree: dict[str, dict[str, list]] = {}
379
+ for n in sorted((n for n in notes if n.kind == "concept"), key=lambda n: n.id):
380
+ e = entries.get(n.id)
381
+ dom = e.domain if e else ""
382
+ area = e.parent if e and e.parent and e.parent != dom else ""
383
+ tree.setdefault(dom, {}).setdefault(area, []).append(n)
384
+ if tree:
385
+ out += ["", "## Concepts"]
386
+ for dom, areas in sorted(tree.items()):
387
+ out += ["", f"### {title(dom) if dom else 'No domain'}"]
388
+ for area, cs in sorted(areas.items()):
389
+ if area:
390
+ out += ["", f"#### {title(area)}"]
391
+ out += [line(n, GLYPH.get(states.get(n.id), NO_CONCEPT) + " ") for n in cs]
392
+ wiki = sorted((n for n in notes if n.kind == "note"), key=lambda n: n.id)
393
+ typed = {t for t, _ in NOTE_SECTIONS}
394
+ sections = [(h, [n for n in wiki if n.fields.get("note_type") == t])
395
+ for t, h in NOTE_SECTIONS]
396
+ sections.append(("Other notes", [n for n in wiki if n.fields.get("note_type") not in typed]))
397
+ sections += [(h, sorted((n for n in notes if n.kind == k), key=lambda n: n.id))
398
+ for k, h in INDEX_KINDS]
399
+ sections.append(("About me", sorted((n for n in notes if n.kind == "me"),
400
+ key=lambda n: n.id)))
401
+ sections.append(("Journal", sorted((n for n in notes if n.kind == "journal"),
402
+ key=lambda n: n.id, reverse=True)[:INDEX_JOURNAL]))
403
+ for heading, items in sections:
404
+ if items:
405
+ out += ["", f"## {heading}", *[line(n) for n in items]]
406
+ return "\n".join(out) + "\n"