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/rollups.py ADDED
@@ -0,0 +1,412 @@
1
+ """Rollup pages: one compact page per ISO week, month and year that holds anything, built by
2
+ code only, so the local Chat model and recall answer "what did I do in March / last week / in
3
+ 2025" from one page instead of hundreds of passages.
4
+
5
+ Each page counts, per source, what Keepfold holds for its days and lists the top items: notes and
6
+ saved AI chats written or changed (`chat._pages_in`, linked as [[id]]), journal lines, study
7
+ events per concept with their verdicts (event counts, never levels), and the most visited sites
8
+ by days visited (`chat_facts._visits`). Month and year pages also list their weeks or months.
9
+ A week page (R3-6) fits WEEK_MAX characters in fixed sections (`render_week`): totals and
10
+ hubs; projects and decisions; themes and searches; people (person pages its pages link to) and
11
+ calendar (the calendar import's events dated in the week); learning and journal.
12
+
13
+ Privacy: a public page (`rollups/rollup-2026-11.md`) holds only what non-private surfaces show:
14
+ no private notes or journals, no hidden subjects (`planner.hidden`). Private or local-only
15
+ browsing never reaches any rollup page (the store's own verdict; Chat reads it live). A period
16
+ with private notes, journals or hidden subjects gets a second page, `rollup-2026-11-private.md`
17
+ with `private: true`, holding only that material: the index keeps it out, so only the local
18
+ model under Chat's private switch reads it.
19
+
20
+ Writes go through `keepfold.vault`; a page is rewritten only when its text changes, and the text
21
+ is a pure function of the items. `run` skips the whole pass when a stamp of the inputs (event,
22
+ note and store files, the catalog and the config) and of the rollup pages is unchanged. No model
23
+ is ever loaded or called."""
24
+
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import json
29
+ import os
30
+ import re
31
+ from collections import Counter, defaultdict
32
+ from datetime import date, timedelta
33
+
34
+ from keepfold import chat, chat_facts, chat_study, planner, render
35
+ from keepfold.catalog import CATALOG, Catalog
36
+ from keepfold.events import EventLog
37
+ from keepfold.vault import Vault, VaultError
38
+
39
+ KIND = "rollup"
40
+ STAMP = ".keepfold/rollups.json"
41
+ FORMAT = 2 # part of the stamp (2: R3-6's weeks): a new page format rebuilds every page once
42
+ TOP = 5 # items listed per section
43
+ CUT = 60 # characters of a title or journal line
44
+ SOURCES = ("notes", "chats", "journal", "study", "browsing")
45
+ NOUN = {"notes": "note", "chats": "saved AI chat", "journal": "journal line",
46
+ "study": "study event", "browsing": "visit"}
47
+ HEAD = {"notes": "Notes", "chats": "Saved AI chats", "journal": "Journal", "study": "Study",
48
+ "browsing": "Browsing"}
49
+ _INPUT_KINDS = ("note", "resource", "decision", "project", "loop", "journal", "domain", "area",
50
+ "concept", "person") # the pages read, and the ones whose private flag hides
51
+ # subjects; a person page's name links the week's people
52
+ WEEK_MAX = 1600 # R3-6: a week page's characters; lists are cut, never padded
53
+ WEEK_ROWS = 4 # rows per list on a week page before the cut
54
+ _CALENDAR = re.compile(r"^Source: Calendar · Date: ", re.M) # sources' month page header
55
+ _EVENT = re.compile(r"^- (\d{4}-\d\d-\d\d)\b.*$", re.M)
56
+ _LINK = re.compile(r"\[\[([^\]|#]+)")
57
+
58
+
59
+ # ---- the items ---------------------------------------------------------------------------------
60
+
61
+ def _items(vault: Vault, lo: str, hi: str) -> list[tuple]:
62
+ """Every dated item in [lo, hi]: (day, source, key, label, n, extra, private). Notes and
63
+ chats: key the page id; journal: the line; study: the concept id, extra the verdict;
64
+ browsing: key the site, n its visits that day."""
65
+ out = []
66
+ with chat._INDEX_LOCK: # person pages of the shared index (a private one is not in it)
67
+ people = {i: n["title"] for i, n in chat._index(vault)._notes.items()
68
+ if n["kind"] == "person"}
69
+ named = {i: re.compile(rf"(?<!\w){re.escape(t)}(?!\w)") for i, t in people.items()
70
+ if len(t) >= 4}
71
+ pages = chat._pages_in(vault, lo, hi, {"notes": True, "chats": True, "private": True})
72
+ for d, kind, id_, title, body, is_chat, private, _ in pages:
73
+ if kind == "journal":
74
+ js = [ln for ln in body.splitlines() if chat._JOURNAL_LINE.match(ln)]
75
+ out += [(d, "journal", ln[2:].strip(), "", 1, "", private) for ln in js]
76
+ body = "\n".join(js)
77
+ else:
78
+ cal = _CALENDAR.search(body[:2000]) # extra: the kind, "calendar" for a calendar page
79
+ out.append((d, "chats" if is_chat else "notes", id_, title, 1,
80
+ "calendar" if cal else kind, private))
81
+ if cal: # R3-6: each event on its own day, for the week pages
82
+ out += [(m[1], "calendar", m[0][2:].strip(), "", 1, "", private)
83
+ for m in _EVENT.finditer(body) if lo <= m[1] <= hi]
84
+ continue
85
+ # people: the person pages the period's own pages and journal lines link to or name
86
+ met = {m[1].strip() for m in _LINK.finditer(body)} & people.keys()
87
+ out += [(d, "people", p, people[p], 1, "", private)
88
+ for p in sorted(met | {i for i, rx in named.items() if rx.search(body)})
89
+ if p != id_]
90
+ # visible browsing only: private or local-only sites never reach a page outside the store
91
+ # (Chat reads them live under its private switch)
92
+ _, visits = chat_facts._visits(vault, lo, hi, {"browsing": True}, [], lambda _h: True)
93
+ out += [(d, "browsing", site, site, n, "", False) for d, _ts, _s, _t, n, _m, site in visits]
94
+ catalog = Catalog.load(vault)
95
+ hide = planner.hidden(vault, catalog)
96
+ events = list(EventLog(vault).iter_events())
97
+ voided = {e.get("ref") for e in events if e.get("kind") == "void"}
98
+ for ev in events:
99
+ obj, d = str(ev.get("object") or ""), str(ev.get("day") or "")
100
+ if not obj.startswith("concept:") or not lo <= d <= hi or ev.get("id") in voided \
101
+ or ev.get("kind") in chat_facts.BOOKKEEPING:
102
+ continue
103
+ c = obj[8:]
104
+ e = catalog.entries.get(c)
105
+ title = chat_study._title(e.title if e else c) or c
106
+ private = c in hide or any(str(a).split(":", 1)[-1] in hide for a in ev.get("also") or [])
107
+ out.append((d, "study", c, title, 1, str(ev.get("verdict") or ""), private))
108
+ return out
109
+
110
+
111
+ # ---- the periods -------------------------------------------------------------------------------
112
+
113
+ def _periods(day: str) -> list[tuple[str, str, str, str]]:
114
+ """(id, unit, first day, last day) of the week, month and year holding `day`."""
115
+ d = date.fromisoformat(day)
116
+ y, w, _ = d.isocalendar()
117
+ mon = d - timedelta(days=d.weekday())
118
+ nxt = date(d.year + (d.month == 12), d.month % 12 + 1, 1)
119
+ return [(f"rollup-{y}-w{w:02d}", "week", mon.isoformat(),
120
+ (mon + timedelta(days=6)).isoformat()),
121
+ (f"rollup-{day[:7]}", "month", day[:8] + "01", (nxt - timedelta(days=1)).isoformat()),
122
+ (f"rollup-{day[:4]}", "year", day[:4] + "-01-01", day[:4] + "-12-31")]
123
+
124
+
125
+ def _title(id_: str, unit: str, lo: str, hi: str) -> str:
126
+ a, b = date.fromisoformat(lo), date.fromisoformat(hi)
127
+ if unit == "year":
128
+ return f"{a.year} in review"
129
+ if unit == "month":
130
+ return f"{a:%B %Y}"
131
+ return f"Week {int(id_.rsplit('w', 1)[1])} of {id_.split('-')[1]} " \
132
+ f"({a.day} {a:%b} to {b.day} {b:%b %Y})"
133
+
134
+
135
+ # ---- the page ---------------------------------------------------------------------------------
136
+
137
+ def _esc(text: str) -> str:
138
+ return render.esc(text, CUT)
139
+
140
+
141
+ def _totals(its: list) -> dict:
142
+ by: Counter = Counter()
143
+ for it in its:
144
+ by[it[1]] += it[4]
145
+ return {s: by[s] for s in SOURCES if by[s]}
146
+
147
+
148
+ def _say(by: dict) -> str:
149
+ return ", ".join(chat_study._plural(n, NOUN[s]) for s, n in by.items())
150
+
151
+
152
+ def _section(src: str, its: list) -> list[str]:
153
+ """A source's lines: its top TOP items and how many more."""
154
+ rows, more = _rows(src, its, TOP)
155
+ n = sum(it[4] for it in its)
156
+ head = f"## {HEAD[src]} ({n})" if src != "browsing" else \
157
+ f"## {HEAD[src]} ({chat_study._plural(n, 'visit')}, " \
158
+ f"{chat_study._plural(len({it[2] for it in its}), 'site')})"
159
+ return [head, *rows, *([f"- and {more} more"] if more > 0 else []), ""]
160
+
161
+
162
+ def _rows(src: str, its: list, top: int) -> tuple[list[str], int]:
163
+ """A source's top `top` rows and how many more it has."""
164
+ if src in ("notes", "chats", "people"):
165
+ seen = {}
166
+ for it in sorted(its, key=lambda it: (it[0], it[2])):
167
+ seen[it[2]] = it # a page once, at its day
168
+ rows = [f"- {it[0] + ' ' if src != 'people' else ''}[[{it[2]}]] {_esc(it[3])}"
169
+ for it in list(seen.values())[-top:]]
170
+ more = len(seen) - len(rows)
171
+ elif src in ("journal", "calendar"):
172
+ picked = sorted(its, key=lambda it: (it[0], it[2]))[-top:]
173
+ rows = [f"- {it[0]} {_esc(chat_study._title(it[2]))}" if src == "journal"
174
+ else f"- {_esc(it[2])}" for it in picked]
175
+ more = len(its) - len(rows)
176
+ elif src == "study":
177
+ per: dict = defaultdict(Counter)
178
+ names, days = {}, defaultdict(set)
179
+ for it in its:
180
+ per[it[2]][it[5] or "other"] += 1
181
+ names[it[2]] = it[3]
182
+ days[it[2]].add(it[0])
183
+ order = sorted(per, key=lambda c: (-sum(per[c].values()), c))
184
+ rows = []
185
+ for c in order[:top]:
186
+ v = per[c]
187
+ res = ", ".join(f"{v[k]} {k}" for k in ("correct", "partial", "wrong") if v[k])
188
+ n = chat_study._plural(sum(v.values()), 'event')
189
+ rows.append(f"- [[{c}]] {_esc(names[c])}: {n}"
190
+ f" on {chat_study._plural(len(days[c]), 'day')}"
191
+ + (f" ({res})" if res else ""))
192
+ more = len(order) - len(rows)
193
+ else: # browsing: sites by days visited, then visits
194
+ visits, days = Counter(), defaultdict(set)
195
+ for it in its:
196
+ visits[it[2]] += it[4]
197
+ days[it[2]].add(it[0])
198
+ order = sorted(visits, key=lambda s: (-len(days[s]), -visits[s], s))
199
+ rows = [f"- {_esc(s)}: {chat_study._plural(len(days[s]), 'day')}, "
200
+ f"{chat_study._plural(visits[s], 'visit')}" for s in order[:top]]
201
+ more = len(order) - len(rows)
202
+ return rows, more
203
+
204
+
205
+ # R3-6: a week page's fixed sections, each (heading, its lists in order)
206
+ WEEK_SECTIONS = (("Totals and hubs", ("browsing",)),
207
+ ("Projects and decisions", ("decisions",)),
208
+ ("Themes and searches", ("notes", "chats")),
209
+ ("People and calendar", ("people", "calendar")),
210
+ ("Learning and journal", ("study", "journal")))
211
+
212
+
213
+ def render_week(id_: str, lo: str, hi: str, its: list, private: bool,
214
+ up: str | None = None) -> str:
215
+ """A week page in WEEK_SECTIONS, at most WEEK_MAX characters: each list starts at
216
+ WEEK_ROWS rows and the longest loses its last row until the page fits ("- and N more").
217
+ Totals and hubs: the counts, the active days and the most visited sites; projects and
218
+ decisions: project and decision pages; themes and searches: the other notes and saved AI
219
+ chats; people: person pages the week's pages link to; calendar: the events dated in it.
220
+ Every row comes from the items: an empty list says "none", nothing is padded."""
221
+ by = defaultdict(list)
222
+ for it in its:
223
+ src = "decisions" if it[1] == "notes" and it[5] in ("project", "decision") else it[1]
224
+ if not (src == "notes" and it[5] == "calendar"): # its events are listed instead
225
+ by[src].append(it)
226
+ lists = {src: list(_rows("notes" if src == "decisions" else src, by[src], WEEK_ROWS))
227
+ for _, srcs in WEEK_SECTIONS for src in srcs}
228
+ title = _title(id_, "week", lo, hi) + (": private items" if private else "")
229
+ fm = [f"title: {json.dumps(title)}", f"kind: {KIND}", "period: week", f"date: {lo}",
230
+ f"end: {hi}"] + (["private: true"] if private else [])
231
+ days = sorted({it[0] for it in its})
232
+ totals = _say(_totals(its))
233
+ head = ["---", *fm, "---", f"# {title}", "", *([f"Up: [[{up}]]", ""] if up else []),
234
+ "Built by Keepfold from your data: counts and titles only, written by code, no model."
235
+ + (" Private material only; the public page leaves it out." if private else ""), ""]
236
+
237
+ def text() -> str:
238
+ out = list(head)
239
+ for name, srcs in WEEK_SECTIONS:
240
+ out.append(f"## {name}")
241
+ if name == "Totals and hubs":
242
+ out += [f"- {totals or 'nothing counted'}",
243
+ f"- Active on {chat_study._plural(len(days), 'day')}, first {days[0]}, "
244
+ f"last {days[-1]}"]
245
+ rows = [r for s in srcs for r in [*lists[s][0], *(
246
+ [f"- and {lists[s][1]} more"] if lists[s][1] > 0 else [])]]
247
+ out += rows or ([] if name == "Totals and hubs" else ["- none"])
248
+ out.append("")
249
+ return "\n".join(out).rstrip() + "\n"
250
+
251
+ page = text()
252
+ while len(page) > WEEK_MAX:
253
+ src = max(lists, key=lambda s: len(lists[s][0]))
254
+ if not lists[src][0]:
255
+ break
256
+ lists[src][0].pop(-1 if src in ("study", "browsing") else 0) # the least or oldest
257
+ lists[src][1] += 1
258
+ page = text()
259
+ return page
260
+
261
+
262
+ def render_page(id_: str, unit: str, lo: str, hi: str, its: list, private: bool,
263
+ parts: list | None = None, up: str | None = None) -> str:
264
+ """The page text for one period variant: a pure function of its arguments. `parts`:
265
+ (id, items) of the weeks of a month or the months of a year, each listed with its totals."""
266
+ title = _title(id_, unit, lo, hi) + (": private items" if private else "")
267
+ fm = [f"title: {json.dumps(title)}", f"kind: {KIND}", f"period: {unit}", f"date: {lo}",
268
+ f"end: {hi}"] + (["private: true"] if private else [])
269
+ days = sorted({it[0] for it in its})
270
+ lines = ["---", *fm, "---", f"# {title}", ""]
271
+ if up:
272
+ lines += [f"Up: [[{up}]]", ""]
273
+ lines += ["Built by Keepfold from your data: counts and titles only, written by code, no model."
274
+ + (" Private material only; the public page leaves it out." if private else ""),
275
+ "",
276
+ f"- {_say(_totals(its))}",
277
+ f"- Active on {chat_study._plural(len(days), 'day')}, first {days[0]}, "
278
+ f"last {days[-1]}", ""]
279
+ if parts:
280
+ lines.append("## " + ("Weeks" if unit == "month" else "Months"))
281
+ lines += [f"- [[{pid}]]: {_say(_totals(pits))}" for pid, pits in parts]
282
+ lines.append("")
283
+ by = defaultdict(list)
284
+ for it in its:
285
+ by[it[1]].append(it)
286
+ for src in SOURCES:
287
+ if by[src]:
288
+ lines += _section(src, by[src])
289
+ return "\n".join(lines).rstrip() + "\n"
290
+
291
+
292
+ def build(items: list) -> dict[str, str]:
293
+ """{page id: text} of every period variant that holds items."""
294
+ groups: dict = defaultdict(list)
295
+ meta = {}
296
+ for it in items:
297
+ for pid, unit, lo, hi in _periods(it[0]):
298
+ groups[pid, it[6]].append(it)
299
+ meta[pid] = (unit, lo, hi)
300
+ # a month or year page needs a counted source; calendar events and people alone make only
301
+ # week pages (an upcoming exam's week)
302
+ groups = {k: its for k, its in groups.items()
303
+ if meta[k[0]][0] == "week" or any(it[1] in SOURCES for it in its)}
304
+ out = {}
305
+ for (pid, private), its in groups.items():
306
+ unit, lo, hi = meta[pid]
307
+ up = None
308
+ if not private and unit != "year":
309
+ up = _periods(lo)[1 if unit == "week" else 2][0]
310
+ up = up if (up, False) in groups else None
311
+ name = pid + ("-private" if private else "")
312
+ if unit == "week":
313
+ out[name] = render_week(pid, lo, hi, its, private, up)
314
+ continue
315
+ sub = 0 if unit == "month" else 1
316
+ its = [it for it in its if it[1] in SOURCES]
317
+ kids: dict = defaultdict(list)
318
+ for it in its:
319
+ kids[_periods(it[0])[sub][0]].append(it)
320
+ out[name] = render_page(pid, unit, lo, hi, its, private, sorted(kids.items()), up)
321
+ return out
322
+
323
+
324
+ # ---- writing ----------------------------------------------------------------------------------
325
+
326
+ def _listing(vault: Vault, inputs: bool) -> list:
327
+ """The input files (`inputs`), else the rollup pages, as (name, mtime_ns, size) listings,
328
+ as the home's version stamp reads them: cheap, no file is opened."""
329
+ from keepfold import home, taint
330
+ from keepfold.browse import store
331
+
332
+ r = str(vault.root)
333
+ if not inputs:
334
+ return sorted(home._md(os.path.join(r, Vault.KIND_DIRS[KIND])))
335
+ db = os.path.join(r, *store.PATH.split("/"))
336
+ return [FORMAT, sorted(home._events(r)), home._stat(os.path.join(r, CATALOG)),
337
+ home._stat(db), home._stat(db + "-wal"), home._stat(str(taint._config_path())),
338
+ *(sorted(x for d in Vault.dirs(k) for x in home._md(os.path.join(r, *d.split("/"))))
339
+ for k in _INPUT_KINDS)]
340
+
341
+
342
+ def _stamp(inputs: list, pages: list) -> str:
343
+ return hashlib.sha256(repr([inputs, pages]).encode()).hexdigest()[:32]
344
+
345
+
346
+ def _read_stamp(vault: Vault) -> dict:
347
+ try:
348
+ return json.loads((vault.root / STAMP).read_text(encoding="utf-8"))
349
+ except (OSError, ValueError):
350
+ return {}
351
+
352
+
353
+ def run(vault: Vault, since: str | None = None) -> dict | None:
354
+ """Write the rollup pages whose text changed and remove the ones whose period holds nothing
355
+ now; `since` ("YYYY-MM") limits both to periods ending on or after that month's first day.
356
+ {written, removed, kept} counts, or None when the stamp says nothing changed."""
357
+ first = f"{since}-01" if since else chat_facts.FIRST_DAY
358
+ if since:
359
+ try:
360
+ date.fromisoformat(first)
361
+ except ValueError:
362
+ raise VaultError("invalid_argument", "--since must be a month like 2026-03.") \
363
+ from None
364
+ old = _read_stamp(vault)
365
+ inputs = _listing(vault, True) # before reading: a change during the run is seen next time
366
+ covered = old.get("since") is None or bool(since and old["since"] <= since)
367
+ if covered and old.get("stamp") == _stamp(inputs, _listing(vault, False)):
368
+ return None
369
+ # a year page needs the whole year, and a week may start in the year before
370
+ jan = date(int(first[:4]), 1, 1)
371
+ lo = (jan - timedelta(days=jan.weekday())).isoformat() if since else first
372
+ pages = build(_items(vault, lo, "9999-12-31"))
373
+
374
+ folder = vault.root / Vault.KIND_DIRS[KIND]
375
+ written = kept = removed = 0
376
+ for name, text in sorted(pages.items()):
377
+ if _end(text) < first:
378
+ continue
379
+ path = folder / f"{name}.md"
380
+ try:
381
+ if path.read_bytes().decode("utf-8") == text:
382
+ kept += 1
383
+ continue
384
+ except OSError:
385
+ pass
386
+ try:
387
+ vault.write_text(path, text)
388
+ except VaultError as e: # a title that looks like a key: that page waits for an edit
389
+ if e.code != "secret_detected":
390
+ raise
391
+ continue
392
+ written += 1
393
+ for path in sorted(folder.glob("rollup-*.md")) if folder.is_dir() else []:
394
+ if path.stem not in pages and _end_of(path) >= first:
395
+ vault.remove(path)
396
+ removed += 1
397
+ stamp = _stamp(inputs, _listing(vault, False))
398
+ vault.write_text(vault.root / STAMP, json.dumps({"stamp": stamp, "since": since}))
399
+ return {"written": written, "kept": kept, "removed": removed}
400
+
401
+
402
+ def _end(text: str) -> str:
403
+ return next(ln[5:].strip() for ln in text.splitlines() if ln.startswith("end: "))
404
+
405
+
406
+ def _end_of(path) -> str:
407
+ """The last day of a rollup page's period, from its file; '9999' (always in range) when it
408
+ cannot be read."""
409
+ try:
410
+ return _end(path.read_text(encoding="utf-8"))
411
+ except (OSError, StopIteration, UnicodeDecodeError):
412
+ return "9999"