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/topics.py ADDED
@@ -0,0 +1,1072 @@
1
+ """The topic tree behind `keepfold topics` (docs/design/v5-research/REVIEW-1005.md §5).
2
+
3
+ A hub is a `kind: note` page tagged `topic`; its parent is the first hub in its `related`, and
4
+ the root is `my-topic-map`. A resource's or note's topics are the hub ids in its `related`,
5
+ mirrored by its body `Topics:` line (frontmatter wins). `attach` files a page under the hub
6
+ nearest its chunk-0 vector, backing off to the lowest common ancestor of the hubs within
7
+ `margin` of the best. `build` rewrites only the generated hub parts (the `Part of` line under
8
+ the H1, `## Sub-topics` / `## Subtopics` / `## Areas` and `## Conversations` / `## Other
9
+ conversations`) and the month pages' `## Links`; everything else on a hub belongs to the user or
10
+ the assistant. Private pages are never members, never listed and never edited. Every write goes
11
+ through `keepfold.vault`.
12
+
13
+ Split proposals (REVIEW-1005 §6): `propose_split` clusters a big hub's direct pages (spherical
14
+ k-means, k by mean cosine silhouette) and labels each cluster by c-TF-IDF over member titles; the
15
+ assistant names the clusters and `apply_split` creates the child hubs and moves the pages.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import json
22
+ import logging
23
+ import math
24
+ import random
25
+ import re
26
+ from collections import Counter, defaultdict
27
+ from dataclasses import dataclass
28
+ from functools import lru_cache
29
+
30
+ import numpy as np
31
+
32
+ from keepfold.catalog import page_slug
33
+ from keepfold.index import STOPWORDS, Index, _edge_targets, _target
34
+ from keepfold.relink import TOPIC_MAP as ROOT
35
+ from keepfold.vault import (
36
+ HEADING_RE,
37
+ Vault,
38
+ VaultError,
39
+ _dump_fm,
40
+ _load_fm,
41
+ _newline,
42
+ _section,
43
+ _split,
44
+ _to_yaml,
45
+ invalid,
46
+ is_private,
47
+ scan_secrets,
48
+ )
49
+
50
+ log = logging.getLogger(__name__)
51
+
52
+ MARGIN = 0.02 # REVIEW-1005 §1.7: 72% attached at 0.93 precision
53
+ FLOOR = 0.80 # the top-1 cosine p50 is 0.87, min 0.68
54
+ TOUCH_FLOOR = 0.71 # prime's bare prompt vector to a hub centroid; see arena/touch-final.md
55
+ MIN_MEMBERS = 3
56
+ MAX_HUBS = 4
57
+ SPLIT_N = 25 # spec 3: a hub with more direct pages is a split candidate
58
+ MIN_CHILD = 4 # a smaller cluster's members stay on the parent
59
+ MAX_K = 8
60
+ MAX_SHARE = 0.45 # a bigger cluster gets one k+1 retry
61
+ SIL_MIN = 0.06 # p25 of `keepfold topics eval --splits`: 0.058 over 68 hand splits, 2026-11-15
62
+ MAX_DEPTH = 4 # no proposals for hubs this deep
63
+ RESTARTS, ITERS = 10, 30
64
+ LABEL_STOP = STOPWORDS | frozenset("about into using vs via not new".split())
65
+ PAGE_KINDS = ("resource", "note")
66
+ CONV = ("Conversations", "Other conversations")
67
+ WATCHED = "Watched & searched"
68
+ TOP_RE = re.compile(r"^Topics: [^\r\n]*", re.M)
69
+ TL_RE = re.compile(r"^Timeline: [^\r\n]*", re.M)
70
+ DAY_RE = re.compile(r"\d{4}-\d{2}-\d{2}")
71
+ MONTH_RE = re.compile(r"^\d{4}-\d{2}-01$")
72
+
73
+
74
+ # ---- the tree ---------------------------------------------------------------------------
75
+
76
+ @dataclass
77
+ class Tree:
78
+ parent: dict[str, str | None] # every hub; None at the top
79
+ kids: dict[str, list[str]]
80
+ title: dict[str, str]
81
+
82
+ def path(self, id: str) -> list[str]:
83
+ """Top hub .. id."""
84
+ out: list[str] = []
85
+ x: str | None = id
86
+ while x is not None and x not in out:
87
+ out.append(x)
88
+ x = self.parent.get(x)
89
+ return out[::-1]
90
+
91
+ def depth(self, id: str) -> int:
92
+ return len(self.path(id)) - 1
93
+
94
+ def lca(self, ids) -> str | None:
95
+ out = None
96
+ for level in zip(*(self.path(i) for i in ids), strict=False):
97
+ if len(set(level)) != 1:
98
+ break
99
+ out = level[0]
100
+ return out
101
+
102
+
103
+ def is_hub(n: dict) -> bool:
104
+ tags = n["fields"].get("tags")
105
+ return n["kind"] == "note" and isinstance(tags, list) and "topic" in tags
106
+
107
+
108
+ def tree(index: Index) -> Tree:
109
+ hubs = {i: n for i, n in index._notes.items() if is_hub(n)}
110
+ parent: dict[str, str | None] = {}
111
+ for i, n in hubs.items():
112
+ rel = n["fields"].get("related") or []
113
+ parent[i] = None if i == ROOT else next(
114
+ (t for t in _edge_targets(rel) if t in hubs and t != i), None)
115
+ for i in sorted(hubs): # break cycles at the first repeat
116
+ seen, x = [i], parent[i]
117
+ while x is not None:
118
+ if x in seen:
119
+ parent[seen[-1]] = None
120
+ break
121
+ seen.append(x)
122
+ x = parent[x]
123
+ kids: dict[str, list[str]] = defaultdict(list)
124
+ for i in sorted(hubs):
125
+ if parent[i] is not None:
126
+ kids[parent[i]].append(i)
127
+ return Tree(parent, dict(kids), {i: n["title"] for i, n in hubs.items()})
128
+
129
+
130
+ def page_hubs(n: dict, hubs) -> list[str]:
131
+ return list(dict.fromkeys(t for t in _edge_targets(n["fields"].get("related") or [])
132
+ if t in hubs))
133
+
134
+
135
+ def _pages(index: Index):
136
+ """Non-private resources and notes that are not hubs (the index holds no private page)."""
137
+ return ((i, n) for i, n in sorted(index._notes.items())
138
+ if n["kind"] in PAGE_KINDS and not is_hub(n))
139
+
140
+
141
+ def members(index: Index, t: Tree) -> dict[str, set[str]]:
142
+ out: dict[str, set[str]] = defaultdict(set)
143
+ for i, n in _pages(index):
144
+ for h in page_hubs(n, t.parent):
145
+ out[h].add(i)
146
+ return dict(out)
147
+
148
+
149
+ def unfiled(index: Index, t: Tree) -> list[str]:
150
+ return [i for i, n in _pages(index) if not page_hubs(n, t.parent)]
151
+
152
+
153
+ # ---- attach -------------------------------------------------------------------------------
154
+
155
+ def heads(stack) -> dict[str, np.ndarray]:
156
+ """Page id -> its chunk-0 unit vector (the first row per page in `semantic.vectors`)."""
157
+ ids, page, _, vecs = stack
158
+ first = np.searchsorted(page, np.arange(len(ids)))
159
+ return {i: vecs[r] for i, r in zip(ids, first.tolist(), strict=True)}
160
+
161
+
162
+ def centroids(index: Index, t: Tree, stack):
163
+ """(hub ids, member chunk-0 sums (h x d), member counts) for hubs with MIN_MEMBERS."""
164
+ hv = heads(stack)
165
+ ids, sums, counts = [], [], []
166
+ for h, ps in sorted(members(index, t).items()):
167
+ vs = [hv[p] for p in sorted(ps) if p in hv]
168
+ if len(vs) >= MIN_MEMBERS:
169
+ ids.append(h)
170
+ sums.append(np.sum(vs, axis=0))
171
+ counts.append(len(vs))
172
+ dim = stack[3].shape[1]
173
+ return ids, np.asarray(sums, np.float32).reshape(len(ids), dim), np.asarray(counts)
174
+
175
+
176
+ @dataclass
177
+ class Attach:
178
+ hub: str | None # None: not attached
179
+ score: float # the best hub's cosine
180
+ near: list[tuple[str, float]] # hubs within margin of the best
181
+ top: list[tuple[str, float]] # the best 3 hubs, for suggestions
182
+
183
+
184
+ def attach(vec, t: Tree, cents, exclude=(), margin: float = MARGIN,
185
+ floor: float = FLOOR) -> Attach:
186
+ """The hub for unit vector `vec`: the LCA of every hub within `margin` of the best cosine
187
+ to a member centroid; none under `floor` or at the root. A hub in `exclude` (the page's
188
+ own) loses the page's vector first (leave-one-out)."""
189
+ ids, sums, counts = cents
190
+ if not ids:
191
+ return Attach(None, 0.0, [], [])
192
+ if exclude:
193
+ sums, counts = sums.copy(), counts.copy()
194
+ for k, h in enumerate(ids):
195
+ if h in exclude:
196
+ sums[k] -= vec
197
+ counts[k] -= 1
198
+ norms = np.linalg.norm(sums, axis=1)
199
+ ok = (counts >= MIN_MEMBERS) & (norms > 1e-9)
200
+ cos = np.where(ok, sums @ vec / np.where(ok, norms, 1.0), -np.inf)
201
+ order = [k for k in np.argsort(-cos, kind="stable").tolist() if ok[k]]
202
+ if not order:
203
+ return Attach(None, 0.0, [], [])
204
+ best = float(cos[order[0]])
205
+ near = [(ids[k], float(cos[k])) for k in order if cos[k] >= best - margin - 1e-9]
206
+ top = [(ids[k], float(cos[k])) for k in order[:3]]
207
+ hub = t.lca([h for h, _ in near]) if best >= floor else None
208
+ return Attach(None if hub in (None, ROOT) else hub, best, near, top)
209
+
210
+
211
+ def head_stack(index: Index, embed):
212
+ """`semantic.vectors` with every page's chunk 0 and no extra chunks."""
213
+ from keepfold import semantic
214
+
215
+ dim = len(semantic._embed(embed, ["topic"])[0])
216
+ return semantic.vectors(index, embed, dim, budget=0.0)
217
+
218
+
219
+ def attach_text(index: Index, embed, text: str) -> Attach:
220
+ """The hub `text` belongs under (also Part 1's hook for linking a topic touch)."""
221
+ from keepfold import semantic
222
+
223
+ vec = semantic._embed(embed, [text])[0]
224
+ t = tree(index)
225
+ stack = semantic.vectors(index, embed, len(vec), budget=0.0)
226
+ return attach(vec, t, centroids(index, t, stack))
227
+
228
+
229
+ _PRIMED: tuple = (None, None, None) # prompt_hub's (vector stack, tree, centroids)
230
+
231
+
232
+ def prompt_hub(index: Index, embed, prompt: str, hits: list[dict],
233
+ save: bool = True) -> str | None:
234
+ """The hub a chat prompt is about (keepfold_prime's `touch`), or None. Two views must agree:
235
+ `attach` of the prompt's bare vector to the member centroids (floor TOUCH_FLOOR, the same
236
+ margin and LCA back-off) and recall, where a hit that is not a mere graph neighbour must be
237
+ that hub, under it, or filed at or under it. No embedder or no hits, no hub. With `save`
238
+ False (the app's dry run) the vector cache is read, never written."""
239
+ from keepfold import semantic
240
+
241
+ global _PRIMED
242
+ if embed is None or not hits:
243
+ return None
244
+ # bare, like the page vectors: the bge query prefix compresses the lead of the best hub
245
+ q = semantic._embed(embed, [prompt])[0]
246
+ # the recall that made `hits` just brought the vectors up to date; vectors() again costs
247
+ # ~0.5 s on 5k pages (its manifest walk), and tree + centroids another ~60 ms
248
+ stack = semantic._MEM.get(index.vault.root, (None, None, None))[2]
249
+ if stack is None or stack[3].shape[1] != len(q):
250
+ stack = semantic.vectors(index, embed, len(q), budget=0.0, save=save)
251
+ if _PRIMED[0] is not stack: # any page change re-embeds that page, so a new stack
252
+ t = tree(index)
253
+ _PRIMED = (stack, t, centroids(index, t, stack))
254
+ _, t, cents = _PRIMED
255
+ hub = attach(q, t, cents, floor=TOUCH_FLOOR).hub
256
+ for h in hits if hub else ():
257
+ n = index._notes.get(h["id"])
258
+ if n is None or h.get("match") == "linked":
259
+ continue
260
+ if any(hub in t.path(x) for x in ([h["id"]] if is_hub(n) else page_hubs(n, t.parent))):
261
+ return hub
262
+ return None
263
+
264
+
265
+ def attach_unfiled(index: Index, embed, margin: float = MARGIN, floor: float = FLOOR,
266
+ limit: int | None = None) -> tuple[int, list[tuple[str, Attach]]]:
267
+ """(pages tried, [(page, Attach)]) over the unfiled pages; `limit` tries a seeded sample."""
268
+ t = tree(index)
269
+ stack = head_stack(index, embed)
270
+ cents, hv = centroids(index, t, stack), heads(stack)
271
+ scope = [p for p in unfiled(index, t) if p in hv]
272
+ if limit is not None:
273
+ random.Random(0).shuffle(scope)
274
+ scope = scope[:max(0, limit)]
275
+ return len(scope), [(p, attach(hv[p], t, cents, (), margin, floor)) for p in scope]
276
+
277
+
278
+ def evaluate(index: Index, t: Tree, stack, margins=(0.01, 0.02, 0.03),
279
+ floor: float = FLOOR) -> list[dict]:
280
+ """Leave-one-out over pages with hubs (REVIEW-1005 §1.7): per margin the share attached,
281
+ and of those the share on one of the page's hubs or an ancestor (precision) or exactly
282
+ on one (exact), plus attachments by depth."""
283
+ hv, cents = heads(stack), centroids(index, t, stack)
284
+ pages = [(i, set(hs)) for i, n in _pages(index)
285
+ if i in hv and (hs := page_hubs(n, t.parent))]
286
+ rows = []
287
+ for m in margins:
288
+ att = ok = exact = 0
289
+ depth: Counter = Counter()
290
+ for i, hs in pages:
291
+ a = attach(hv[i], t, cents, hs, m, floor)
292
+ if a.hub is None:
293
+ continue
294
+ att += 1
295
+ depth[t.depth(a.hub)] += 1
296
+ exact += a.hub in hs
297
+ ok += any(a.hub in t.path(h) for h in hs)
298
+ rows.append({"margin": m, "pages": len(pages),
299
+ "attached": att / len(pages) if pages else 0.0,
300
+ "precision": ok / att if att else 0.0,
301
+ "exact": exact / att if att else 0.0, "depth": dict(sorted(depth.items()))})
302
+ return rows
303
+
304
+
305
+ def status(index: Index, t: Tree) -> dict:
306
+ mem = members(index, t)
307
+ return {"hubs": len(t.parent),
308
+ "by_depth": dict(sorted(Counter(t.depth(h) for h in t.parent).items())),
309
+ "over_split": sum(len(ps) > SPLIT_N for ps in mem.values()),
310
+ "pages": sum(1 for _ in _pages(index)), "unfiled": len(unfiled(index, t))}
311
+
312
+
313
+ # ---- page facts ---------------------------------------------------------------------------
314
+
315
+ def alias(s: str, n: int = 80) -> str:
316
+ """Link text must not contain [ ] |."""
317
+ return " ".join(str(s).translate(str.maketrans("[]|", "()/")).split())[:n]
318
+
319
+
320
+ @lru_cache(maxsize=1 << 15) # the app's home asks for the same unchanged bodies on every build
321
+ def _timeline(body: str) -> str:
322
+ m = TL_RE.search(body)
323
+ return m.group(0) if m else ""
324
+
325
+
326
+ def page_date(id: str, fields, body: str) -> str:
327
+ """`date`, else `Date:` on the Timeline line, else a day in the id; '' without one."""
328
+ d = fields.get("date")
329
+ if d and DAY_RE.match(str(d)):
330
+ return str(d)[:10]
331
+ m = re.search(r"Date: (\d{4}-\d{2}-\d{2})", _timeline(body)) or DAY_RE.search(id)
332
+ return m.group(1) if m and m.groups() else m.group(0) if m else ""
333
+
334
+
335
+ def page_source(body: str) -> str:
336
+ """`Source:` on an imported chat page's Timeline line ('' without one)."""
337
+ m = re.search(r"Source: ([^·\r\n]+?)\s*(?:·|$)", _timeline(body))
338
+ return m.group(1) if m else ""
339
+
340
+
341
+ def conv_line(id: str, title: str, date: str, source: str) -> str:
342
+ return "- " + " · ".join(x for x in (date, source, f"[[{id}|{alias(title)}]]") if x)
343
+
344
+
345
+ def _links(line: str, id: str) -> bool:
346
+ return re.search(r"\[\[" + re.escape(id) + r"[|#^\]]", line) is not None
347
+
348
+
349
+ # ---- body editing -------------------------------------------------------------------------
350
+
351
+ def _parts(text: str) -> tuple[str, str]:
352
+ p = _split(text)
353
+ return ("".join(p[:3]), p[3]) if p else ("", text)
354
+
355
+
356
+ def _find(lines: list[str], names) -> tuple[int, int] | None:
357
+ for name in names:
358
+ try:
359
+ return _section(lines, name)
360
+ except VaultError:
361
+ continue
362
+ return None
363
+
364
+
365
+ def _blank_tail(lines: list[str]) -> list[str]:
366
+ n = 0
367
+ while n < len(lines) and not lines[-1 - n].strip():
368
+ n += 1
369
+ return lines[len(lines) - n:]
370
+
371
+
372
+ def _set_section(body: str, heading: str, rows: list[str], nl: str, alts=(),
373
+ before=()) -> str:
374
+ """`## heading` (found under it or an alternative name, then renamed) holding `rows`, its
375
+ trailing blank lines kept; no rows removes the section. A missing one goes before the first
376
+ `before` heading present, else at the end."""
377
+ lines = body.splitlines(keepends=True)
378
+ sec = _find(lines, (heading, *alts))
379
+ block = [f"## {heading}{nl}", *(r + nl for r in rows)] if rows else []
380
+ if sec:
381
+ s, e = sec
382
+ tail = _blank_tail(lines[s:e])
383
+ if block:
384
+ block += tail or ([nl] if e < len(lines) else [])
385
+ if block and lines[e - 1:e] and not lines[e - 1].endswith("\n") and e == len(lines):
386
+ block[-1] = block[-1].rstrip("\r\n") # the file had no final newline
387
+ lines[s - 1:e] = block
388
+ elif block:
389
+ at = next((i for i, ln in enumerate(lines) if (m := HEADING_RE.match(ln.rstrip("\r\n")))
390
+ and m.group(2) in before), len(lines))
391
+ if at < len(lines):
392
+ block.append(nl)
393
+ if at and lines[at - 1].strip():
394
+ if not lines[at - 1].endswith("\n"):
395
+ lines[at - 1] += nl
396
+ block.insert(0, nl)
397
+ lines[at:at] = block
398
+ return "".join(lines)
399
+
400
+
401
+ def _set_partof(body: str, line: str, nl: str) -> str:
402
+ """`line` as the `Part of …` line under the H1 (replaced, else inserted)."""
403
+ lines = body.splitlines(keepends=True)
404
+ h = next((i for i, ln in enumerate(lines) if ln.startswith("# ")), None)
405
+ if h is None:
406
+ return body
407
+ j = h + 1
408
+ while j < len(lines) and not lines[j].strip():
409
+ j += 1
410
+ if j < len(lines) and lines[j].startswith("Part of "):
411
+ lines[j] = line + (lines[j][len(lines[j].rstrip("\r\n")):] or nl)
412
+ return "".join(lines)
413
+ if not lines[h].endswith("\n"):
414
+ lines[h] += nl
415
+ new = [nl, line + nl]
416
+ if h + 1 < len(lines) and lines[h + 1].strip():
417
+ new.append(nl)
418
+ lines[h + 1:h + 1] = new
419
+ return "".join(lines)
420
+
421
+
422
+ def _owned(body: str, headings) -> list[str]:
423
+ """The body without the generated parts, blank lines dropped: what `build` must keep."""
424
+ lines = body.splitlines(keepends=True)
425
+ for name in headings:
426
+ if sec := _find(lines, (name,)):
427
+ del lines[sec[0] - 1:sec[1]]
428
+ h = next((i for i, ln in enumerate(lines) if ln.startswith("# ")), None)
429
+ if h is not None:
430
+ part = next((j for j in range(h + 1, len(lines)) if lines[j].strip()), None)
431
+ if part is not None and lines[part].startswith("Part of "):
432
+ del lines[part]
433
+ return [ln.rstrip() for ln in lines if ln.strip()]
434
+
435
+
436
+ def _topics_line(body: str, line: str | None, nl: str) -> str:
437
+ m = TOP_RE.search(body)
438
+ if m:
439
+ if line is not None:
440
+ return body[:m.start()] + line + body[m.end():]
441
+ end = m.end() + (len(nl) if body.startswith(nl, m.end()) else 0)
442
+ return body[:m.start()] + body[end:]
443
+ if line is None:
444
+ return body
445
+ if t := TL_RE.search(body):
446
+ return body[:t.end()] + nl + line + body[t.end():]
447
+ lines = body.splitlines(keepends=True)
448
+ if lines and lines[0].startswith("# "):
449
+ if not lines[0].endswith("\n"):
450
+ lines[0] += nl
451
+ new = [nl, line + nl]
452
+ if len(lines) > 1 and lines[1].strip():
453
+ new.append(nl)
454
+ lines[1:1] = new
455
+ return "".join(lines)
456
+ return line + nl + (nl if body.strip() and body[:1] not in "\r\n" else "") + body
457
+
458
+
459
+ # ---- place --------------------------------------------------------------------------------
460
+
461
+ def _hub_page(vault: Vault, id: str):
462
+ """The public hub note `id`, else None."""
463
+ try:
464
+ n = vault.read("note", id)
465
+ except VaultError:
466
+ return None
467
+ tags = n.fields.get("tags")
468
+ return n if isinstance(tags, list) and "topic" in tags and not is_private(n) else None
469
+
470
+
471
+ def page_kind(vault: Vault, id: str) -> str:
472
+ for k in PAGE_KINDS:
473
+ if vault.path_for(k, id).is_file():
474
+ return k
475
+ raise VaultError("unknown_id", f"No resource or note '{id}'; check the id with find.")
476
+
477
+
478
+ def _page_change(old: list[str], hubs: list[str]):
479
+ line = "Topics: " + " · ".join(f"[[{h}]]" for h in hubs) if hubs else None
480
+
481
+ def change(text: str) -> str:
482
+ parts = _split(text)
483
+ if parts is None:
484
+ raise VaultError("invalid_argument", "The page has no frontmatter.")
485
+ head, fm, close, body = parts
486
+ nl = _newline(text)
487
+ if old != hubs:
488
+ data = _load_fm(fm)
489
+ cur = data.get("related")
490
+ items = list(cur) if isinstance(cur, list) else [cur] if cur else []
491
+ keep = [str(x) for x in items if _target(x) not in old]
492
+ data["related"] = _to_yaml(keep + [f"[[{h}]]" for h in hubs])
493
+ fm = _dump_fm(data, nl)
494
+ return head + fm + close + _topics_line(body, line, nl)
495
+
496
+ return change
497
+
498
+
499
+ def _hub_add(id: str, line: str):
500
+ def change(text: str) -> str:
501
+ prefix, body = _parts(text)
502
+ nl = _newline(text)
503
+ lines = body.splitlines(keepends=True)
504
+ sec = _find(lines, CONV[::-1])
505
+ if sec is None:
506
+ kids = _find(lines, ("Sub-topics", "Subtopics"))
507
+ return prefix + _set_section(body, CONV[1] if kids else CONV[0], [line], nl,
508
+ before=(WATCHED,))
509
+ s, e = sec
510
+ if any(_links(ln, id) for ln in lines[s:e]):
511
+ return text
512
+ at = next((j + 1 for j in range(e - 1, s - 1, -1) if lines[j].strip()), s)
513
+ if at and not lines[at - 1].endswith("\n"):
514
+ lines[at - 1] += nl
515
+ lines.insert(at, line + nl)
516
+ if at + 1 < len(lines) and HEADING_RE.match(lines[at + 1].rstrip("\r\n")):
517
+ lines.insert(at + 1, nl)
518
+ return prefix + "".join(lines)
519
+
520
+ return change
521
+
522
+
523
+ def _hub_drop(id: str):
524
+ def change(text: str) -> str:
525
+ prefix, body = _parts(text)
526
+ lines = body.splitlines(keepends=True)
527
+ sec = _find(lines, CONV[::-1])
528
+ if sec is None:
529
+ return text
530
+ s, e = sec
531
+ return prefix + "".join(ln for k, ln in enumerate(lines)
532
+ if not (s <= k < e and _links(ln, id)))
533
+
534
+ return change
535
+
536
+
537
+ def place(vault: Vault, page_id: str, hubs: list[str], kind: str | None = None) -> bool:
538
+ """Set a resource's or note's topics to `hubs` (0 to MAX_HUBS hub ids): the hub ids in
539
+ `related` (other ids kept) and the body `Topics:` line (under `Timeline:`, else the H1);
540
+ the page's line is added to each new hub's conversation section and dropped from hubs it
541
+ left. Returns whether anything changed. Private pages and hubs are refused."""
542
+ hubs = list(dict.fromkeys(str(h).strip() for h in hubs if str(h).strip()))
543
+ if len(hubs) > MAX_HUBS:
544
+ raise VaultError("invalid_argument", f"A page takes at most {MAX_HUBS} topics.")
545
+ with vault.lock():
546
+ kind = kind or page_kind(vault, page_id)
547
+ if kind not in PAGE_KINDS:
548
+ raise VaultError("invalid_argument", "Only resources and notes take topics.")
549
+ note = vault.read(kind, page_id)
550
+ if is_private(note):
551
+ raise VaultError("invalid_argument", "A private page is never filed under a topic: "
552
+ "hub pages list their pages.")
553
+ tags = note.fields.get("tags")
554
+ if isinstance(tags, list) and "topic" in tags:
555
+ raise VaultError("invalid_argument", f"'{page_id}' is a topic hub; its parent is "
556
+ "the first hub in its related list.")
557
+ bad = [h for h in hubs if _hub_page(vault, h) is None]
558
+ if bad:
559
+ raise VaultError("invalid_argument", f"Not topic hubs: {', '.join(bad)}; use hub "
560
+ "ids (notes tagged topic).")
561
+ old = [t for t in dict.fromkeys(_edge_targets(note.fields.get("related") or []))
562
+ if _hub_page(vault, t) is not None]
563
+ changed = vault._mutate(note.path, _page_change(old, hubs))
564
+ line = conv_line(page_id, str(note.fields.get("title") or page_id),
565
+ page_date(page_id, note.fields, note.body), page_source(note.body))
566
+ for h in hubs:
567
+ changed |= vault._mutate(vault.path_for("note", h), _hub_add(page_id, line))
568
+ for h in old:
569
+ if h not in hubs:
570
+ changed |= vault._mutate(vault.path_for("note", h), _hub_drop(page_id))
571
+ return changed
572
+
573
+
574
+ # ---- build --------------------------------------------------------------------------------
575
+
576
+ def _watched(body: str) -> list[str]:
577
+ lines = body.splitlines()
578
+ sec = _find(lines, (WATCHED,))
579
+ return [ln[2:].strip() for ln in lines[sec[0]:sec[1]] if ln.startswith("- ")] if sec else []
580
+
581
+
582
+ def build(vault: Vault, index: Index, dry_run: bool = False, only=None) -> Counter:
583
+ """Regenerate the generated hub parts and the month pages' `## Links` in place. A page whose
584
+ hand-owned text would change is skipped and counted as `unsafe`. Returns counts: hubs and
585
+ months changed, unchanged, unsafe. `only` limits it to those hubs and skips the months."""
586
+ t = tree(index)
587
+ mem = members(index, t)
588
+ notes = index._notes
589
+ info = {p: (page_date(p, notes[p]["fields"], notes[p]["body"]), page_source(notes[p]["body"]),
590
+ notes[p]["title"]) for ps in mem.values() for p in ps}
591
+ acts = {h: _watched(notes[h]["body"]) for h in t.parent}
592
+ kids = t.kids
593
+ memo: dict[str, frozenset] = {}
594
+
595
+ def sub(h: str) -> frozenset:
596
+ if h not in memo:
597
+ memo[h] = frozenset(mem.get(h, ())).union(*(sub(k) for k in kids.get(h, [])))
598
+ return memo[h]
599
+
600
+ def span(h: str) -> tuple[str, str, int]:
601
+ a = [x for k in [h, *kids.get(h, [])] for x in acts[k]]
602
+ ds = sorted([info[p][0] for p in sub(h) if info[p][0]]
603
+ + [x[1:8] for x in a if x.startswith("[")]) or ["?"]
604
+ return ds[0], ds[-1], len(sub(h)) + len(a)
605
+
606
+ def convs(h: str) -> list[str]:
607
+ return [conv_line(p, info[p][2], info[p][0], info[p][1])
608
+ for p in sorted(mem.get(h, ()), key=lambda p: (info[p][0], p))]
609
+
610
+ def subs_of(h: str) -> list[str]:
611
+ return sorted((s for s in kids.get(h, []) if sub(s) or acts[s]), key=lambda s: -span(s)[2])
612
+
613
+ plans: dict[str, tuple] = {} # hub -> (Part of line or None, [(heading, rows, alts)])
614
+ for h in t.parent:
615
+ p = t.parent[h]
616
+ if h == ROOT:
617
+ rows = []
618
+ for d in kids.get(h, []):
619
+ if ss := subs_of(d):
620
+ rows.append(f"- [[{d}|{alias(t.title[d])}]]: {len(ss)} subtopics, "
621
+ f"{sum(span(s)[2] for s in ss)} items")
622
+ plans[h] = (None, [("Areas", rows, ())])
623
+ continue
624
+ if p == ROOT:
625
+ ss = subs_of(h)
626
+ rows = []
627
+ for s in ss:
628
+ a, b, c = span(s)
629
+ nk = len([k for k in kids.get(s, []) if sub(k)])
630
+ rows.append(f"- [[{s}|{alias(t.title[s])}]]: {c} items, {a[:7]} to {b[:7]}"
631
+ + (f" ({nk} sub-topics)" if nk else ""))
632
+ partof = f"Part of [[{ROOT}]]."
633
+ plans[h] = (partof, [("Subtopics", rows, ()),
634
+ (CONV[1] if ss else CONV[0], convs(h), CONV)])
635
+ continue
636
+ first, last, count = span(h)
637
+ ks = sorted((k for k in kids.get(h, []) if sub(k)), key=lambda k: -span(k)[2])
638
+ by_src = Counter(info[x][1] or "other" for x in sub(h))
639
+ if acts[h]:
640
+ by_src["YouTube/Google"] = len(acts[h])
641
+ partof = None
642
+ if p is not None:
643
+ partof = f"Part of [[{p}|{alias(t.title[p])}]]" + (
644
+ f" · first explored {first} · last {last} · "
645
+ + ", ".join(f"{c} {n}" for c, n in by_src.most_common()) if count else "")
646
+ rows = [f"- [[{k}|{alias(t.title[k])}]]: {span(k)[2]} conversations, "
647
+ f"{span(k)[0][:7]} to {span(k)[1][:7]}" for k in ks]
648
+ plans[h] = (partof, [("Sub-topics", rows, ()),
649
+ (CONV[1] if ks else CONV[0], convs(h), CONV)])
650
+
651
+ def hub_change(plan):
652
+ partof, secs = plan
653
+ heads_ = [x for name, _, alts in secs for x in (name, *alts)]
654
+
655
+ def change(text: str) -> str:
656
+ prefix, body = _parts(text)
657
+ nl = _newline(text)
658
+ new = _set_partof(body, partof, nl) if partof else body
659
+ for name, rows, alts in secs:
660
+ new = _set_section(new, name, rows, nl, tuple(a for a in alts if a != name),
661
+ before=(*CONV, WATCHED) if name not in CONV else (WATCHED,))
662
+ if _owned(new, heads_) != _owned(body, heads_):
663
+ raise _Unsafe
664
+ return prefix + new
665
+
666
+ return change
667
+
668
+ done: Counter = Counter()
669
+ jobs = [(vault.path_for("note", h), hub_change(plans[h]), "hubs") for h in sorted(plans)
670
+ if only is None or h in only]
671
+ if only is None:
672
+ jobs += _month_jobs(vault, index, t, mem, info)
673
+ with _maybe_lock(vault, dry_run):
674
+ for path, change, what in jobs:
675
+ try:
676
+ text = path.read_bytes().decode("utf-8")
677
+ if change(text) == text:
678
+ done["unchanged"] += 1
679
+ continue
680
+ if not dry_run:
681
+ vault._mutate(path, change)
682
+ except _Unsafe:
683
+ done["unsafe"] += 1
684
+ continue
685
+ done[what] += 1
686
+ return done
687
+
688
+
689
+ class _Unsafe(Exception):
690
+ """A rebuild would change text that `build` does not own."""
691
+
692
+
693
+ def _maybe_lock(vault: Vault, dry_run: bool):
694
+ from contextlib import nullcontext
695
+
696
+ return nullcontext() if dry_run else vault.lock() # a dry run writes nothing, not even a lock
697
+
698
+
699
+ def _month_jobs(vault: Vault, index: Index, t: Tree, mem: dict, info: dict) -> list:
700
+ """`## Links` on each month page: topics that month rolled up to depth 2, most pages first,
701
+ and projects its digest lines name (ported from the import's build_hubs)."""
702
+ def top(h: str) -> str:
703
+ while t.depth(h) > 2:
704
+ h = t.parent[h]
705
+ return h
706
+
707
+ by_page: dict[str, set[str]] = defaultdict(set)
708
+ for h, ps in mem.items():
709
+ for p in ps:
710
+ by_page[p].add(top(h))
711
+ month_topics: dict[str, Counter] = defaultdict(Counter)
712
+ for p, tops in sorted(by_page.items()):
713
+ if info[p][0]:
714
+ month_topics[info[p][0][:7]].update(sorted(tops))
715
+ projects = []
716
+ for pid, n in sorted(index._notes.items()):
717
+ if n["kind"] == "project":
718
+ words = [w for w in re.split(r"[-_]", pid) if len(w) > 3]
719
+ if words:
720
+ projects.append((pid, re.compile("|".join(map(re.escape, words)), re.I)))
721
+ jobs = []
722
+ for mid, n in sorted(index._notes.items()):
723
+ if n["kind"] != "journal" or not MONTH_RE.match(mid):
724
+ continue
725
+ links = [f"- [[{h}|{t.title[h]}]] ({c})" for h, c in month_topics[mid[:7]].most_common(15)]
726
+
727
+ def change(text: str, links=links) -> str:
728
+ base = re.split(r"\n## Links\n", text)[0].rstrip() + "\n"
729
+ digest = "\n".join(ln for ln in base.splitlines() if " digest " in ln)
730
+ proj = [f"- [[{pid}]]" for pid, rx in projects
731
+ if digest and len({x.lower() for x in rx.findall(digest)}) >= 2]
732
+ if not (links or proj):
733
+ return text
734
+ return base + "\n## Links\n" + (
735
+ "Topics this month:\n" + "\n".join(links) + "\n" if links else "") + (
736
+ "Projects mentioned:\n" + "\n".join(proj) + "\n" if proj else "")
737
+
738
+ jobs.append((vault.path_for("journal", mid), change, "months"))
739
+ return jobs
740
+
741
+
742
+ # ---- split proposals (REVIEW-1005 §6) ------------------------------------------------------
743
+
744
+ def _kmeans(X: np.ndarray, k: int, seed: int) -> np.ndarray:
745
+ """Spherical k-means with k-means++ starts: labels of the best of RESTARTS seeded runs by
746
+ total cosine to the centroids. A cluster that empties keeps its old centroid."""
747
+ rng = np.random.default_rng([seed, k])
748
+ best, best_score = None, -np.inf
749
+ for _ in range(RESTARTS):
750
+ C = [X[rng.integers(len(X))]]
751
+ for _ in range(k - 1):
752
+ w = np.clip(1.0 - np.max(X @ np.asarray(C).T, axis=1), 0.0, None).astype(float) ** 2
753
+ C.append(X[rng.choice(len(X), p=w / w.sum())] if w.sum() > 1e-12
754
+ else X[rng.integers(len(X))])
755
+ C = np.asarray(C)
756
+ for _ in range(ITERS):
757
+ lab = np.argmax(X @ C.T, axis=1)
758
+ S = np.zeros_like(C)
759
+ np.add.at(S, lab, X)
760
+ norm = np.linalg.norm(S, axis=1)
761
+ new = np.where((norm > 1e-9)[:, None], S / np.maximum(norm, 1e-9)[:, None], C)
762
+ if np.allclose(new, C):
763
+ break
764
+ C = new
765
+ sims = X @ C.T
766
+ lab = np.argmax(sims, axis=1)
767
+ score = float(sims[np.arange(len(X)), lab].sum())
768
+ if score > best_score + 1e-9:
769
+ best, best_score = lab, score
770
+ return best
771
+
772
+
773
+ def _silhouette(X: np.ndarray, lab: np.ndarray) -> np.ndarray:
774
+ """Per-point cosine silhouette; 0 for a point alone in its cluster or with one cluster."""
775
+ ks, own = np.unique(lab, return_inverse=True)
776
+ n = len(X)
777
+ if len(ks) < 2:
778
+ return np.zeros(n)
779
+ D = np.clip(1.0 - X @ X.T, 0.0, None)
780
+ np.fill_diagonal(D, 0.0)
781
+ sums = np.stack([D[:, own == j].sum(axis=1) for j in range(len(ks))], axis=1)
782
+ sizes = np.bincount(own)
783
+ alone = sizes[own] == 1
784
+ a = sums[np.arange(n), own] / np.maximum(sizes[own] - 1, 1)
785
+ mean = sums / sizes
786
+ mean[np.arange(n), own] = np.inf
787
+ b = mean.min(axis=1)
788
+ s = (b - a) / np.maximum(np.maximum(a, b), 1e-12)
789
+ s[alone] = 0.0
790
+ return s
791
+
792
+
793
+ def _cluster(X: np.ndarray, seed: int):
794
+ """(k, labels, per-point silhouette, mean silhouette, note) for the k in 3..min(MAX_K,
795
+ n // MIN_CHILD) with the best mean silhouette, else None. A cluster over MAX_SHARE gets one
796
+ k+1 retry, kept when it fixes that and still clears SIL_MIN."""
797
+ n = len(X)
798
+ best = None
799
+ for k in range(3, min(MAX_K, n // MIN_CHILD) + 1):
800
+ lab = _kmeans(X, k, seed)
801
+ s = _silhouette(X, lab)
802
+ if best is None or s.mean() > best[3] + 1e-9:
803
+ best = (k, lab, s, float(s.mean()))
804
+ if best is None:
805
+ return None
806
+ k, lab, s, sil = best
807
+ note = ""
808
+ if np.bincount(lab).max() > MAX_SHARE * n:
809
+ lab2 = _kmeans(X, k + 1, seed) if k + 1 <= min(MAX_K, n) else None
810
+ s2 = _silhouette(X, lab2) if lab2 is not None else None
811
+ if lab2 is not None and np.bincount(lab2).max() <= MAX_SHARE * n and s2.mean() >= SIL_MIN:
812
+ k, lab, s, sil = k + 1, lab2, s2, float(s2.mean())
813
+ else:
814
+ note = (f"one cluster holds {np.bincount(lab).max() / n:.0%} of the pages; k+1 did not "
815
+ "split it")
816
+ return k, lab, s, sil, note
817
+
818
+
819
+ def _terms(titles: list[list[str]]) -> list[list[str]]:
820
+ """c-TF-IDF: per cluster the top 3 title words by tf x log(1 + mean cluster words / the
821
+ word's count over all clusters); stopwords and digits never count."""
822
+ tf = [Counter(w for t in ts for w in re.findall(r"[a-z]+", t.lower())
823
+ if len(w) > 1 and w not in LABEL_STOP) for ts in titles]
824
+ total: Counter = Counter()
825
+ for c in tf:
826
+ total.update(c)
827
+ avg = sum(total.values()) / max(len(tf), 1)
828
+ return [[w for w, _ in sorted(c.items(), key=lambda x: (
829
+ -x[1] * math.log(1 + avg / total[x[0]]), x[0]))[:3]] for c in tf]
830
+
831
+
832
+ def _proposal(index: Index, hub: str, ids: list[str], hv: dict, seed: int = 0,
833
+ gate: bool = True) -> dict | None:
834
+ """The split proposal over pages `ids` (sorted): clusters of at least MIN_CHILD pages with a
835
+ non-negative silhouette, the rest in `stay`. None under SIL_MIN or with fewer than 2
836
+ clusters, unless `gate` is off (the eval)."""
837
+ if len(ids) < 3 * MIN_CHILD:
838
+ return None
839
+ X = np.stack([hv[p] for p in ids])
840
+ c = _cluster(X, seed)
841
+ if c is None or (gate and c[3] < SIL_MIN):
842
+ return None
843
+ k, lab, s, sil, note = c
844
+ stay = [i for i in range(len(ids)) if s[i] < 0]
845
+ groups = []
846
+ for j in range(k):
847
+ g = [i for i in range(len(ids)) if lab[i] == j and s[i] >= 0]
848
+ if len(g) >= MIN_CHILD:
849
+ groups.append(g)
850
+ else:
851
+ stay += g
852
+ if gate and len(groups) < 2:
853
+ return None
854
+ groups.sort(key=lambda g: (-len(g), g[0]))
855
+ title = {p: str(index._notes[p]["title"]) for p in ids}
856
+ terms = _terms([[title[ids[i]] for i in g] for g in groups])
857
+ clusters = []
858
+ for g, words in zip(groups, terms, strict=True):
859
+ cen = X[g].sum(axis=0)
860
+ near = sorted(g, key=lambda i: (-float(X[i] @ cen), ids[i]))[:5]
861
+ clusters.append({"members": [ids[i] for i in g], "terms": words,
862
+ "sample_titles": [title[ids[i]] for i in near]})
863
+ digest = hashlib.sha256(json.dumps([hub, ids, k, seed]).encode()).hexdigest()[:16]
864
+ return {"hub": hub, "hash": digest, "k": k, "silhouette": round(sil, 4),
865
+ "clusters": clusters, "stay": sorted(ids[i] for i in stay),
866
+ **({"note": note} if note else {})}
867
+
868
+
869
+ def propose_split(index: Index, t: Tree, stack, hub: str, seed: int = 0) -> dict | None:
870
+ """{hub, hash, k, silhouette, clusters[{members, terms, sample_titles}], stay[], note?} for
871
+ the hub's direct non-private pages, or None (no such hub, depth >= MAX_DEPTH, too few pages,
872
+ silhouette under SIL_MIN). The hash covers the hub, the sorted member ids, k and the seed."""
873
+ if hub not in t.parent or t.depth(hub) >= MAX_DEPTH:
874
+ return None
875
+ hv = heads(stack)
876
+ ids = sorted(p for p in members(index, t).get(hub, ()) if p in hv)
877
+ return _proposal(index, hub, ids, hv, seed)
878
+
879
+
880
+ def split_candidates(index: Index, t: Tree) -> list[tuple[str, int]]:
881
+ """(hub, direct pages): hubs over SPLIT_N above MAX_DEPTH, biggest first, then parents of
882
+ children still marked `names: provisional`."""
883
+ mem = members(index, t)
884
+ over = sorted((h for h, ps in mem.items() if len(ps) > SPLIT_N and t.depth(h) < MAX_DEPTH),
885
+ key=lambda h: (-len(mem[h]), h))
886
+ prov = sorted({p for h, p in t.parent.items() if p is not None and p not in over
887
+ and index._notes[h]["fields"].get("names") == "provisional"})
888
+ return [(h, len(mem.get(h, ()))) for h in over + prov]
889
+
890
+
891
+ def proposal_path(vault: Vault, hub: str):
892
+ return vault.root / ".keepfold" / "proposals" / f"split-{hub}.json"
893
+
894
+
895
+ def write_proposal(vault: Vault, prop: dict) -> None:
896
+ """`.keepfold/proposals/split-<hub>.json` (git-ignored); a failure only logs."""
897
+ path = proposal_path(vault, prop["hub"])
898
+ try:
899
+ vault.write_text(path, json.dumps(prop, indent=1, ensure_ascii=False) + "\n")
900
+ except (VaultError, OSError) as e:
901
+ log.warning("split proposal not saved: %s", e)
902
+
903
+
904
+ def auto_children(prop: dict) -> list[dict]:
905
+ """Offline names for `--apply --auto-names`: the c-TF-IDF terms."""
906
+ return [{"title": " ".join(c["terms"]).title() or f"Group {k + 1}",
907
+ "desc": "Provisional name from the page titles: " + (", ".join(c["terms"]) or "none")
908
+ + "."} for k, c in enumerate(prop["clusters"])]
909
+
910
+
911
+ def apply_split(vault: Vault, index: Index, embed, hub: str, hash: str, children,
912
+ provisional: bool = False) -> dict:
913
+ """Create the named child hubs of `hub` and move their pages there, after recomputing the
914
+ proposal and checking its hash. Everything is validated before the first write. Returns
915
+ {children[{id, title, n}], stayed, moved}."""
916
+ index.refresh()
917
+ t = tree(index)
918
+ if hub not in t.parent:
919
+ raise invalid(f"'{hub}' is not a topic hub.")
920
+ prop = propose_split(index, t, head_stack(index, embed), hub)
921
+ if prop is None or prop["hash"] != hash:
922
+ raise invalid("The split proposal no longer matches: pages changed; run keepfold_reflect "
923
+ "again.")
924
+ if not isinstance(children, list) or not children or len(children) > MAX_K:
925
+ raise invalid(f"children must be a list of 1 to {MAX_K} {{title, desc, members?}}.")
926
+ if not all(isinstance(c, dict) for c in children):
927
+ raise invalid("Each child is an object {title, desc, members?}.")
928
+ own = all(c.get("members") is not None for c in children)
929
+ if not own and len(children) != len(prop["clusters"]):
930
+ raise invalid(f"Give {len(prop['clusters'])} children, one per cluster in order, or a "
931
+ "members list on every child.")
932
+ direct = set(members(index, t).get(hub, ()))
933
+ plan, uses = [], Counter()
934
+ for k, c in enumerate(children):
935
+ title, desc = (" ".join(str(c.get(f) or "").split()) for f in ("title", "desc"))
936
+ if not page_slug(title) or not desc:
937
+ raise invalid("Each child needs a title (with a letter or digit) and a desc.")
938
+ ms = c.get("members")
939
+ if ms is None:
940
+ ms = prop["clusters"][k]["members"]
941
+ if not isinstance(ms, list) or not ms:
942
+ raise invalid("members must be a non-empty list of page ids.")
943
+ ms = list(dict.fromkeys(str(m) for m in ms))
944
+ if bad := [m for m in ms if m not in direct]:
945
+ raise invalid(f"Not direct pages of {hub}: {', '.join(bad[:5])}.")
946
+ scan_secrets(f"{title}\n{desc}")
947
+ uses.update(ms)
948
+ plan.append((title, desc, ms))
949
+ if over := sorted(m for m, n in uses.items() if n > 2):
950
+ raise invalid(f"A page goes in at most 2 children: {', '.join(over[:5])}.")
951
+ ids: list[str] = []
952
+ for title, _, _ in plan:
953
+ base = f"{hub}-{page_slug(title)}"[:70].rstrip("-.")
954
+ cid, n = base, 2
955
+ while cid in ids or any((vault.root / d / f"{cid}.md").exists()
956
+ for k in vault.KIND_DIRS for d in vault.dirs(k)):
957
+ cid = f"{base[:66].rstrip('-.')}-{n}"
958
+ n += 1
959
+ ids.append(cid)
960
+ moves = {}
961
+ for m in sorted(uses):
962
+ hs = [h for h in page_hubs(index._notes[m], t.parent) if h != hub]
963
+ hs += [cid for cid, (_, _, ms) in zip(ids, plan, strict=True) if m in ms]
964
+ if len(hs) > MAX_HUBS:
965
+ raise invalid(f"'{m}' would have more than {MAX_HUBS} topics.")
966
+ moves[m] = (hs, index._notes[m]["kind"])
967
+ with vault.lock():
968
+ for cid, (title, desc, _) in zip(ids, plan, strict=True):
969
+ fields = {"title": title, "kind": "note", "note_type": "structure", "tags": ["topic"],
970
+ "related": [f"[[{hub}]]"], "summary": desc}
971
+ if provisional:
972
+ fields["names"] = "provisional"
973
+ vault.create_note("note", cid, fields, f"# {title}\n\n{desc}\n")
974
+ for m, (hs, kind) in moves.items():
975
+ place(vault, m, hs, kind)
976
+ index.refresh()
977
+ build(vault, index, only={hub, *ids})
978
+ return {"children": [{"id": cid, "title": title, "n": len(ms)}
979
+ for cid, (title, _, ms) in zip(ids, plan, strict=True)],
980
+ "stayed": len(direct - set(uses)), "moved": len(uses)}
981
+
982
+
983
+ def _browse(sizes: list[int], left: int, n: int) -> float:
984
+ """Share of the flat list's scan saved: a page costs the child list plus its child's list
985
+ (or the parent's leftover list), against n."""
986
+ nc = len(sizes)
987
+ cost = (sum(s * (nc + s) for s in sizes) + left * (nc + left)) / n
988
+ return 1.0 - cost / n
989
+
990
+
991
+ def _cohesion(X: np.ndarray, groups: list[list[int]]) -> float:
992
+ """Mean pairwise cosine within each group, weighted by group size."""
993
+ num = den = 0.0
994
+ for g in groups:
995
+ m = len(g)
996
+ if m >= 2:
997
+ s = X[g].sum(axis=0)
998
+ num += m * (float(s @ s) - m) / (m * (m - 1))
999
+ den += m
1000
+ return num / den if den else 0.0
1001
+
1002
+
1003
+ def _ari(a, b) -> float:
1004
+ """Adjusted Rand index of two labelings."""
1005
+ _, ai = np.unique(a, return_inverse=True)
1006
+ _, bi = np.unique(b, return_inverse=True)
1007
+ M = np.zeros((ai.max() + 1, bi.max() + 1))
1008
+ np.add.at(M, (ai, bi), 1)
1009
+
1010
+ def c2(x):
1011
+ return float((x * (x - 1) / 2).sum())
1012
+
1013
+ s, sa, sb = c2(M), c2(M.sum(axis=1)), c2(M.sum(axis=0))
1014
+ exp = sa * sb / c2(np.array([len(ai)]))
1015
+ top = (sa + sb) / 2
1016
+ return (s - exp) / (top - exp) if abs(top - exp) > 1e-12 else 1.0
1017
+
1018
+
1019
+ def evaluate_splits(index: Index, t: Tree, stack, seed: int = 0) -> dict:
1020
+ """REVIEW-1005 §6.4 on the hand-split hubs (children holding pages, at least 10 pages in
1021
+ all): the manual split's silhouette (its p25 calibrates SIL_MIN), browse-cost reduction
1022
+ manual vs automatic, cohesion, and ARI at the chosen k. Read-only."""
1023
+ hv, mem = heads(stack), members(index, t)
1024
+ rows = []
1025
+ for h in sorted(t.parent):
1026
+ label: dict[str, int] = {}
1027
+ for j, kid in enumerate(t.kids.get(h, [])):
1028
+ for p in sorted(mem.get(kid, ())):
1029
+ if p in hv:
1030
+ label.setdefault(p, j)
1031
+ if not label:
1032
+ continue
1033
+ for p in mem.get(h, ()):
1034
+ if p in hv:
1035
+ label.setdefault(p, -1) # the parent's leftover list
1036
+ ids = sorted(label)
1037
+ if len(ids) < 10:
1038
+ continue
1039
+ X = np.stack([hv[p] for p in ids])
1040
+ man = np.array([label[p] for p in ids])
1041
+ inside = man >= 0
1042
+ msil = (float(_silhouette(X[inside], man[inside]).mean())
1043
+ if len(set(man[inside].tolist())) > 1 else 0.0)
1044
+ mgroups = [np.flatnonzero(man == j).tolist() for j in sorted(set(man[inside].tolist()))]
1045
+ row = {"hub": h, "n": len(ids), "manual_sil": msil,
1046
+ "manual_browse": _browse([len(g) for g in mgroups], int((~inside).sum()), len(ids)),
1047
+ "manual_cohesion": _cohesion(X, mgroups)}
1048
+ prop = _proposal(index, h, ids, hv, seed, gate=False)
1049
+ if prop is not None:
1050
+ pos = {p: i for i, p in enumerate(ids)}
1051
+ agroups = [[pos[p] for p in c["members"]] for c in prop["clusters"]]
1052
+ auto = np.full(len(ids), -1)
1053
+ for j, g in enumerate(agroups):
1054
+ auto[g] = j
1055
+ row.update(auto_sil=prop["silhouette"], k=prop["k"],
1056
+ auto_browse=_browse([len(g) for g in agroups], len(prop["stay"]), len(ids)),
1057
+ auto_cohesion=_cohesion(X, agroups), ari=_ari(man, auto))
1058
+ rows.append(row)
1059
+ done = [r for r in rows if "auto_browse" in r]
1060
+
1061
+ def med(key, rs):
1062
+ return float(np.median([r[key] for r in rs])) if rs else 0.0
1063
+
1064
+ man_b, auto_b = med("manual_browse", done), med("auto_browse", done)
1065
+ return {"hubs": len(rows), "compared": len(done),
1066
+ "manual_sil_p25": float(np.percentile([r["manual_sil"] for r in rows], 25))
1067
+ if rows else 0.0,
1068
+ "manual_sil_median": med("manual_sil", rows),
1069
+ "manual_browse": man_b, "auto_browse": auto_b,
1070
+ "browse_ratio": auto_b / man_b if man_b > 0 else 0.0,
1071
+ "manual_cohesion": med("manual_cohesion", done),
1072
+ "auto_cohesion": med("auto_cohesion", done), "ari": med("ari", done), "rows": rows}