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/harvest.py ADDED
@@ -0,0 +1,334 @@
1
+ """Harvest the imported chat pages into the wiki (docs/design/v6/arena/harvest-verdict.md).
2
+
3
+ No LLM here: an attended agent session asks `keepfold_chats(action="harvest")` for a bundle,
4
+ writes notes, decisions, hub lines and about-me proposals itself, then logs `harvested`.
5
+ A bundle packs whole topic hubs (a chat belongs to its first hub; unfiled chats come last, one
6
+ unit per month) up to chats.PART_CHARS of the user's own redacted turns, best hub first: the
7
+ hub's member centroid against its nearest concept head. Same-day, same-app copies are folded
8
+ under the longest page. Progress is a fold over live `harvested` events, so a void or
9
+ `keepfold undo` re-queues chats; nothing else is stored and no imported page is edited.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import datetime as dt
15
+ import hashlib
16
+ from collections import defaultdict
17
+
18
+ import numpy as np
19
+
20
+ from keepfold import chats, claims, topics
21
+ from keepfold.chat_import import MINE
22
+ from keepfold.events import live
23
+ from keepfold.index import GLYPHS, _wrap, link_targets
24
+ from keepfold.reflect import unconfirmed
25
+ from keepfold.render import plain
26
+ from keepfold.semantic import is_chat
27
+ from keepfold.vault import ID_RE, VaultError, is_private
28
+
29
+ DUPE_COS = 0.97 # REVIEW-1005 §1.5: same-day re-logs, not cross-app copies
30
+ CONCEPT_COS = 0.68 # above the everyday hubs' p90 (0.64) to their nearest concept head
31
+ CONCEPTS_MAX = 5
32
+ QUIET_WEIGHT = 0.4 # replaces semantic.CHAT_WEIGHT (0.6) for a harvested chat
33
+ KNOW_CHARS = 1200
34
+ CHATS_MAX, PAGES_MAX, FOUND_MAX = 80, 50, 50 # per bundle / harvested event
35
+ OUTCOMES = ("harvested", "empty", "skipped")
36
+ KNOW = "What I explored" # the user's questions show interest, not knowledge
37
+ OLD_KNOW = "What I know" # hand- or LLM-written on older hubs: read, never written or renamed
38
+ KEEP_DAYS = 7
39
+ ME = "**Me:**"
40
+
41
+
42
+ def user_turns(body: str) -> list[str] | None:
43
+ """The text of each `**Me:**` turn of an imported chat page, up to the page app's own
44
+ speaker line (`**Gemini:**` on a Gemini page). None when a turn's end cannot be found (no
45
+ `Source:` app, no turn, or a `**Me:**` with no reply before the next one or the end): the
46
+ caller then serves the title only, never a guess that could hold assistant text. A page
47
+ whose Timeline line says MINE (chat_import's) holds no reply: a turn ends at the next
48
+ `### ` or `**Me:**` line, or the end."""
49
+ app = topics.page_source(body)
50
+ if not app:
51
+ return None
52
+ mine = MINE in (topics.TL_RE.search(body) or [""])[0]
53
+ them, out, cur = f"**{app}:**", [], None
54
+ for ln in body.splitlines():
55
+ if mine and cur is not None and ln.startswith(("### ", ME)):
56
+ out.append("\n".join(cur).strip())
57
+ cur = None
58
+ if ln.startswith(ME):
59
+ if cur is not None:
60
+ return None
61
+ cur = [ln[len(ME):]]
62
+ elif ln.startswith(them):
63
+ if cur is not None:
64
+ out.append("\n".join(cur).strip())
65
+ cur = None
66
+ elif cur is not None:
67
+ cur.append(ln)
68
+ if mine and cur is not None:
69
+ out.append("\n".join(cur).strip())
70
+ cur = None
71
+ return None if cur is not None or not out else out
72
+
73
+
74
+ def fold(events) -> tuple[set[str], set[str], dict[str, str]]:
75
+ """(chats done, hubs skipped, {copy: keeper}) over the live `harvested` log events."""
76
+ done, skipped, dupes = set(), set(), {}
77
+ for e in live(events):
78
+ p = e.get("payload")
79
+ if e.get("kind") != "log" or not isinstance(p, dict) or p.get("kind") != "harvested":
80
+ continue
81
+ if p.get("outcome") == "skipped":
82
+ skipped.add(p.get("hub"))
83
+ else:
84
+ done.update(p.get("chats") or ())
85
+ dupes.update(p.get("dupes") or {})
86
+ return done, skipped, dupes
87
+
88
+
89
+ def quiet(events) -> dict[str, float]:
90
+ """Recall weights for semantic's `quiet`: 0 hides a folded copy, QUIET_WEIGHT a harvested
91
+ (or empty) chat."""
92
+ done, _, dupes = fold(events)
93
+ return {**dict.fromkeys(done, QUIET_WEIGHT), **dict.fromkeys(dupes, 0.0)}
94
+
95
+
96
+ def _hub_sims(index, t, hv) -> tuple[list[str], list[str], np.ndarray]:
97
+ """(hub ids, concept ids, hub x concept cosine): member chunk-0 centroid to concept head."""
98
+ mem = topics.members(index, t)
99
+ hubs = [h for h in sorted(mem) if any(p in hv for p in mem[h])]
100
+ cids = sorted(i for i, n in index._notes.items() if n["kind"] == "concept" and i in hv)
101
+ if not hubs or not cids:
102
+ return hubs, cids, np.zeros((len(hubs), len(cids)), np.float32)
103
+ cent = np.stack([np.sum([hv[p] for p in mem[h] if p in hv], axis=0) for h in hubs])
104
+ cent /= np.maximum(np.linalg.norm(cent, axis=1, keepdims=True), 1e-9)
105
+ return hubs, cids, cent @ np.stack([hv[c] for c in cids]).T
106
+
107
+
108
+ def private_hub(vault, id: str, notes) -> bool:
109
+ """True for a topic hub on disk that the index leaves out: a private one (review r4 L3)."""
110
+ if id in notes or not isinstance(id, str) or not ID_RE.fullmatch(id) \
111
+ or not vault.path_for("note", id).is_file():
112
+ return False
113
+ try:
114
+ n = vault.read("note", id)
115
+ except VaultError: # unreadable frontmatter: the index skipped it for that, not privacy
116
+ return False
117
+ tags = n.fields.get("tags")
118
+ return is_private(n) and isinstance(tags, list) and "topic" in tags
119
+
120
+
121
+ def queue(index, t, stack, done, skipped, within: str | None = None) -> list[dict]:
122
+ """Units to harvest, best first: [{unit, chats (newest first), newest, score, concepts
123
+ [(id, cos)]}]. A hub's score is its centroid's best concept cosine (then its newest chat);
124
+ unfiled chats come last as `month:YYYY-MM` units, newest month first. Done chats, chats
125
+ under a skipped hub, chats whose `Topics:` line names a private hub and, with `within`
126
+ (a hub), chats outside its subtree are left out."""
127
+ hubs, cids, sims = _hub_sims(index, t, topics.heads(stack))
128
+ row = {h: k for k, h in enumerate(hubs)}
129
+ units: dict[str, list[tuple[str, str]]] = defaultdict(list)
130
+ private: dict[str, bool] = {} # a hub id named on a Topics: line -> private on disk
131
+ for i, n in index._notes.items():
132
+ if i in done or not is_chat(n):
133
+ continue
134
+ line = topics.TOP_RE.search(n["body"])
135
+ if line and any(private.setdefault(h, private_hub(index.vault, h, index._notes))
136
+ for h in link_targets(line.group(0))):
137
+ continue
138
+ home = next(iter(topics.page_hubs(n, t.parent)), None)
139
+ path = t.path(home) if home else []
140
+ if skipped.intersection(path) or (within and within not in path):
141
+ continue
142
+ day = topics.page_date(i, n["fields"], n["body"])
143
+ units[home or f"month:{day[:7]}"].append((day, i))
144
+ out = []
145
+ for u, rows in units.items():
146
+ rows.sort(reverse=True)
147
+ s = sims[row[u]] if u in row else np.zeros(0)
148
+ top = [(cids[j], float(s[j])) for j in np.argsort(-s, kind="stable")[:CONCEPTS_MAX]
149
+ if s[j] >= CONCEPT_COS]
150
+ out.append({"unit": u, "chats": [i for _, i in rows], "newest": rows[0][0],
151
+ "score": float(s.max()) if len(s) else 0.0, "concepts": top})
152
+ month = [x for x in out if x["unit"].startswith("month:")]
153
+ return (sorted((x for x in out if x not in month), reverse=True,
154
+ key=lambda x: (round(x["score"], 2), x["newest"], x["unit"]))
155
+ + sorted(month, key=lambda x: x["unit"], reverse=True))
156
+
157
+
158
+ def _norm_turns(body: str) -> set[str] | None:
159
+ turns = user_turns(body)
160
+ return None if turns is None else {" ".join(x.split()).lower() for x in turns}
161
+
162
+
163
+ def dupes(index, hv, ids) -> dict[str, str]:
164
+ """{copy: keeper} among `ids`: the same day and app, chunk-0 cosine >= DUPE_COS, and every
165
+ user turn of the copy also in the keeper (chunk 0 sees only the first 1,500 characters, so
166
+ two chats that open alike and then diverge stay apart). The longest page keeps."""
167
+ notes = index._notes
168
+ info = {i: (topics.page_date(i, notes[i]["fields"], notes[i]["body"]),
169
+ topics.page_source(notes[i]["body"]), _norm_turns(notes[i]["body"]))
170
+ for i in ids}
171
+ out: dict[str, str] = {}
172
+ keepers: list[str] = []
173
+ for i in sorted(ids, key=lambda i: (-len(notes[i]["body"]), i)):
174
+ day, app, turns = info[i]
175
+ k = next((k for k in keepers if day and turns is not None and info[k][:2] == (day, app)
176
+ and info[k][2] is not None and turns <= info[k][2] and i in hv and k in hv
177
+ and float(hv[i] @ hv[k]) >= DUPE_COS), None)
178
+ if k is None:
179
+ keepers.append(i)
180
+ else:
181
+ out[i] = k
182
+ return out
183
+
184
+
185
+ def _line(turn: str) -> str:
186
+ s = "Me: " + " ".join(chats.redact(turn).split())
187
+ return s if len(s) <= chats.LINE_CHARS else s[:chats.LINE_CHARS - 1] + "…"
188
+
189
+
190
+ def _block(index, i: str, n: int, copies: list[str]) -> tuple[str, dict]:
191
+ """One chat's text block and its row in the bundle's `chats`."""
192
+ note = index._notes[i]
193
+ day, app = topics.page_date(i, note["fields"], note["body"]), topics.page_source(note["body"])
194
+ turns = user_turns(note["body"])
195
+ head = f"[{n}] {day} {app} [[{i}]]" + (f" (×{len(copies) + 1} same day)" if copies else "")
196
+ row = {"id": i, "date": day, "source": app, "turns": len(turns or ()), "dupes": copies}
197
+ if turns is None: # Y: refuse rather than guess where the user's turn ends
198
+ row["title_only"] = True
199
+ return f"{head} (turns unreadable: title only)\nTitle: {chats.redact(note['title'])}", row
200
+ return "\n".join([head, *(_line(x) for x in turns if x.strip())]), row
201
+
202
+
203
+ def _know(index, h: str) -> str:
204
+ """The tail of a hub's `## What I know` and `## What I explored`, wrapped; '' without
205
+ either."""
206
+ lines = index._notes[h]["body"].splitlines(keepends=True)
207
+ secs = [s for name in (OLD_KNOW, KNOW) if (s := topics._find(lines, (name,)))]
208
+ text = "\n".join("".join(lines[a:b]).strip() for a, b in secs).strip()
209
+ return _wrap(f"know:{h}", text[-KNOW_CHARS:]) if text else ""
210
+
211
+
212
+ def bundle(index, t, stack, done, skipped, within: str | None = None,
213
+ stamp: str = "") -> dict | None:
214
+ """The next bundle, or None when nothing is left: whole units in queue order while their
215
+ text fits chats.PART_CHARS and CHATS_MAX ids; a first unit too big alone is cut by date
216
+ and the rest comes next time. Returns {bundle, hubs [{id, title, path, know, concepts}],
217
+ chats [{id, hub, date, source, turns, dupes, title_only?}], text (wrapped), progress}.
218
+ `bundle` hashes `stamp` (the serve time) with the ids, so a key never outlives a void."""
219
+ hv = topics.heads(stack)
220
+ units = queue(index, t, stack, done, skipped, within)
221
+ if not units:
222
+ return None
223
+ hubs, rows, text, size, count = [], [], [], 0, 0
224
+ for u in units:
225
+ h = u["unit"]
226
+ month = h.startswith("month:")
227
+ head = f"## Unfiled chats, {h[6:] or 'undated'}" if month else f"## {h}: {_path(t, h)}"
228
+ folded = dupes(index, hv, u["chats"])
229
+ blocks = []
230
+ for i in u["chats"]:
231
+ if i not in folded:
232
+ copies = sorted(c for c, k in folded.items() if k == i)
233
+ b, r = _block(index, i, len(rows) + len(blocks) + 1, copies)
234
+ blocks.append((b, {**r, "hub": None if month else h}))
235
+ need = len(head) + 1 + sum(len(b) + 1 for b, _ in blocks)
236
+ ids = sum(1 + len(r["dupes"]) for _, r in blocks)
237
+ if size + need > chats.PART_CHARS or count + ids > CHATS_MAX:
238
+ if rows:
239
+ break
240
+ blocks = _page(blocks, chats.PART_CHARS - len(head) - 1)
241
+ text += [head, *(b for b, _ in blocks)]
242
+ rows += [r for _, r in blocks]
243
+ size += need
244
+ count += ids
245
+ if not month:
246
+ hubs.append({"id": h, "title": plain(t.title[h], 80),
247
+ "path": plain(_path(t, h), 200),
248
+ "know": _know(index, h),
249
+ "concepts": [{"id": c, "title": plain(index._notes[c]["title"], 80),
250
+ "state": GLYPHS[index._state(c)]}
251
+ for c, _ in u["concepts"]]})
252
+ if len(blocks) < len(u["chats"]) - len(folded):
253
+ break # a paged unit fills the bundle
254
+ ids = [i for r in rows for i in (r["id"], *r["dupes"])]
255
+ left = sum(len(u["chats"]) for u in units)
256
+ total = sum(1 for n in index._notes.values() if is_chat(n))
257
+ return {"bundle": hashlib.sha256(f"{stamp}|{' '.join(ids)}".encode()).hexdigest()[:16],
258
+ "hubs": hubs, "chats": rows, "text": _wrap("harvest", "\n".join(text)),
259
+ "progress": {"chats": total, "harvested": len(done & set(index._notes)),
260
+ "left": left}}
261
+
262
+
263
+ def _path(t, h: str) -> str:
264
+ return " › ".join(t.title[x] for x in t.path(h) if x != topics.ROOT)
265
+
266
+
267
+ def _page(blocks: list, cap: int) -> list:
268
+ """The blocks (newest first) that fit `cap` characters and CHATS_MAX ids; at least the
269
+ first, cut to fit."""
270
+ out, size, ids = [], 0, 0
271
+ for b, r in blocks:
272
+ n = 1 + len(r["dupes"])
273
+ if size + len(b) + 1 > cap or ids + n > CHATS_MAX:
274
+ if not out:
275
+ out.append((b[:cap - 2] + "…", r))
276
+ break
277
+ out.append((b, r))
278
+ size, ids = size + len(b) + 1, ids + n
279
+ return out
280
+
281
+
282
+ def status(index, t, stack, events, today: str, since: str | None = None) -> dict:
283
+ """The `keepfold harvest status` numbers, read-only. Placement chats sit in a hub with a concept
284
+ at CONCEPT_COS (None without `stack`, the vectors); a hub is bridged when it links a concept
285
+ page (index edges); the yes-rate counts live me/ lines citing a [[chat-…]] against
286
+ `## Not me` ones; `waiting` is the about-me backlog; the keep share is the share of pages
287
+ that harvested events at least KEEP_DAYS old name and that still exist; `since` (a day)
288
+ limits the event-based numbers (keep share, empty rate per app, runs)."""
289
+ events = list(events)
290
+ done, skipped, _ = fold(events)
291
+ evs = [e for e in live(events) if e.get("kind") == "log"
292
+ and isinstance(p := e.get("payload"), dict) and p.get("kind") == "harvested"
293
+ and (since is None or str(e.get("day", "")) >= since)]
294
+ ids = {i for i, n in index._notes.items() if is_chat(n)}
295
+ concepts = {i for i, n in index._notes.items() if n["kind"] == "concept"}
296
+ bridged = {s for s, d in index.db.execute("SELECT src, dst FROM edges")
297
+ if s in t.parent and d in concepts}
298
+ out: dict = {"chats": len(ids), "harvested": len(done & ids), "placement": None,
299
+ "hubs": len(t.parent), "bridged_hubs": len(bridged),
300
+ "waiting": len(unconfirmed(index.vault, today)[0])}
301
+ if stack is not None:
302
+ units = [u for u in queue(index, t, stack, set(), skipped) if u["concepts"]]
303
+ place = {i for u in units for i in u["chats"]}
304
+ out["placement"] = {"hubs": len(units), "chats": len(place),
305
+ "harvested": len(place & done),
306
+ "coverage": round(len(place & done) / len(place), 3) if place else 0.0,
307
+ "bridged": len(bridged & {u["unit"] for u in units})}
308
+ cited = [r for r in claims.rows(index.vault) if "[[chat-" in r["text"]]
309
+ yes, no = (sum(r["status"] == s for r in cited) for s in ("live", "not_me"))
310
+ out["yes_rate"] = {"yes": yes, "no": no,
311
+ "rate": round(yes / (yes + no), 3) if yes + no else None}
312
+ cut = (dt.date.fromisoformat(today) - dt.timedelta(days=KEEP_DAYS)).isoformat()
313
+ old = [p for e in evs if str(e.get("day", "")) <= cut for p in e["payload"].get("pages") or ()]
314
+ kept = sum(p in index._notes for p in old)
315
+ out["keep"] = {"pages": len(old), "kept": kept,
316
+ "share": round(kept / len(old), 3) if old else None}
317
+ apps: dict[str, list[int]] = defaultdict(lambda: [0, 0])
318
+ runs: dict[str, dict] = {}
319
+ for e in evs:
320
+ p, sid = e["payload"], str(e.get("session"))
321
+ for c in p.get("chats") or ():
322
+ n = index._notes.get(c)
323
+ a = apps[topics.page_source(n["body"]) if n else "?"]
324
+ a[0] += 1
325
+ a[1] += p.get("outcome") == "empty"
326
+ r = runs.setdefault(sid, {"session": sid, "day": e.get("day"), "bundles": 0, "chats": 0,
327
+ "pages": [], "undo": f"keepfold undo {sid}"})
328
+ r["bundles"] += 1
329
+ r["chats"] += len(p.get("chats") or ())
330
+ r["pages"] += [x for x in p.get("pages") or () if x not in r["pages"]]
331
+ out["empty"] = {a: {"chats": c, "empty": k, "rate": round(k / c, 3)}
332
+ for a, (c, k) in sorted(apps.items())}
333
+ out["runs"] = list(runs.values())
334
+ return out