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/chat.py ADDED
@@ -0,0 +1,1464 @@
1
+ """The app's local chat: multi-turn questions over the archive (notes, saved AI chats, mistakes
2
+ and browsing, private notes and browsing included under the `private` switch), answered by a
3
+ LOCAL model only (`localllm`, never cloudllm). Each turn retrieves afresh through
4
+ `ask._passages`, wrapped as untrusted data; the earlier turns go to the model as plain text only.
5
+
6
+ History is kept in `<vault>/.keepfold/browse/chat/<ulid>.jsonl`, one JSON line per message. That
7
+ folder is inside the private browse tree on purpose (an answer can quote private browsing):
8
+ never served over MCP, never on the dashboard, never logged."""
9
+
10
+ from __future__ import annotations
11
+
12
+ import bisect
13
+ import builtins
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ import threading
19
+ import time
20
+ from collections import Counter
21
+ from collections.abc import Callable
22
+ from datetime import UTC, date, datetime
23
+ from typing import NamedTuple
24
+
25
+ from keepfold import (
26
+ access,
27
+ ask,
28
+ askfile,
29
+ chat_facts,
30
+ chat_study,
31
+ chats,
32
+ dates,
33
+ events,
34
+ localllm,
35
+ prime,
36
+ render,
37
+ semantic,
38
+ taint,
39
+ xray,
40
+ )
41
+ from keepfold.chat_study import study_answer # noqa: F401 chat.study_answer, beside site_list
42
+
43
+ # dates in a question: the rules live in keepfold.dates (`pin` shares them); chat._when and the
44
+ # rest are still read from here
45
+ from keepfold.dates import ( # noqa: F401
46
+ _D,
47
+ _DATE,
48
+ _M,
49
+ _MONTHS,
50
+ _NUM,
51
+ _PAD,
52
+ _RULES,
53
+ _UNIT,
54
+ _WEEKDAYS,
55
+ _WORDS,
56
+ _ago,
57
+ _day,
58
+ _last,
59
+ _monday,
60
+ _month,
61
+ _n,
62
+ _weekday,
63
+ _weekend,
64
+ _when,
65
+ )
66
+ from keepfold.index import STOPWORDS, _wrap, aliases
67
+ from keepfold.vault import PRIVATE_BROWSE_DIR, Vault, VaultError
68
+
69
+ when = dates.when # chat.when, as before the move
70
+
71
+ DIR = ".keepfold/browse/chat"
72
+ ID_RE = re.compile(r"[0-9A-HJKMNP-TV-Z]{26}") # a ULID, so a path can never leave DIR
73
+ MAX_TEXT = 4000
74
+ TITLE = 60
75
+ TURNS = 6 # earlier messages the model sees
76
+ HISTORY_BUDGET = 3000 # their characters, on top of ask.BUDGET of passages: a 2B model's context
77
+ ABOUT_MAX = 600 # the "About the user" block (`about`); out of HISTORY_BUDGET, not on top of it
78
+ ABOUT = ("\n\nAbout the user, the person asking (data, not a passage): use it only to understand "
79
+ "who is asking; answer facts only from the passages, and never cite it.\n")
80
+ LENGTH = {"short": 300, "normal": 700, "long": 1500} # answer length -> max_tokens
81
+ DEFAULTS = {"length": "normal", "temperature": 0.2, "passages": 5, # of ask.PASSAGE characters
82
+ "sources": dict(ask.SOURCES), "history": True}
83
+ NO_ANSWER = "I don't know from your archive."
84
+ SEARCHED = 5 # pages listed as "searched, not cited" when the answer cites none
85
+ PAGES_READ = 4 # pages of an inventory, schedule or decisions answer the model reads
86
+ FRONT_MAX = 2000 # characters of a routed half's data answer (a site list) the model gets
87
+ # the app's Chat only: semantic.NOT_SET_UP names a CLI command (fine for agents, not here)
88
+ NO_SEARCH_MODEL = ("Search by meaning is off: download the search model in Setup to find notes by "
89
+ "meaning.")
90
+ SAID_NOTHING = ("{model} gave no answer, twice. These are the pages it searched; open one to "
91
+ "read it, or ask again in other words.")
92
+ CITE = "\n\n(Answer from the passages above and cite each one you use as [n].)" # 2B models forget
93
+ SYSTEM = ask.SYSTEM + (" Earlier messages are the conversation so far: use them to understand a "
94
+ "follow-up question, but answer only from the passages in the latest "
95
+ "message. Today is {today}.")
96
+ _live: dict[str, list] = {} # chats of a session with history off: memory only, never written
97
+ _LIVE_LOCK = threading.Lock() # the stream thread writes _live while the page lists chats
98
+
99
+
100
+ # ---- settings (`chat:` in ~/.keepfold/config.yaml) -------------------------------------------
101
+
102
+ def _valid(key: str, v) -> bool:
103
+ num = isinstance(v, int | float) and not isinstance(v, bool) and math.isfinite(v)
104
+ return {"length": lambda: v in LENGTH,
105
+ "temperature": lambda: num and 0 <= v <= 1,
106
+ "passages": lambda: num and v == int(v) and 4 <= v <= 12,
107
+ "history": lambda: isinstance(v, bool),
108
+ "sources": lambda: isinstance(v, dict) and set(v) <= set(ask.SOURCES)
109
+ and all(isinstance(x, bool) for x in v.values())}.get(key, lambda: False)()
110
+
111
+
112
+ def get_settings(config: dict | None = None) -> dict:
113
+ """The chat settings; a missing or bad value is its default."""
114
+ cfg = (taint.config() if config is None else config).get("chat")
115
+ cfg = cfg if isinstance(cfg, dict) else {}
116
+ out = {k: cfg[k] if k in cfg and _valid(k, cfg[k]) else v for k, v in DEFAULTS.items()}
117
+ out["sources"] = {**ask.SOURCES, **out["sources"]}
118
+ out["passages"] = int(out["passages"])
119
+ return out
120
+
121
+
122
+ def save_settings(body: dict) -> dict:
123
+ """Validate `body` (some of DEFAULTS' keys), merge it into the saved settings and return
124
+ them; ValueError names the first bad field."""
125
+ if extra := set(body) - set(DEFAULTS):
126
+ raise ValueError(f"unknown setting {sorted(extra)[0]!r}")
127
+ for k, v in body.items():
128
+ if not _valid(k, v):
129
+ raise ValueError({"length": "length must be short, normal or long",
130
+ "temperature": "temperature must be a number from 0 to 1",
131
+ "passages": "passages must be a whole number from 4 to 12",
132
+ "history": "history must be true or false",
133
+ "sources": "sources must map notes, chats, browsing and private "
134
+ "to true or false"}[k])
135
+
136
+ def merge(cfg: dict) -> dict: # under the config lock
137
+ cur, old = get_settings(cfg), cfg.get("chat")
138
+ new = {**cur, **body, "sources": {**cur["sources"], **body.get("sources", {})}}
139
+ return {"chat": {**(old if isinstance(old, dict) else {}), **new}}
140
+ taint.write_config(merge)
141
+ return get_settings()
142
+
143
+
144
+ _GENERIC = frozenset(
145
+ "which what when where who whom did do does done i me my mine visit visited visiting see "
146
+ "saw seen look looked looking site sites website websites page pages web read reading "
147
+ "watched go went browse browsed open opened about on at the a an any anything something "
148
+ "tell show find found was were have has had in of to for from there that this ago day "
149
+ "days week weeks month months give example examples explain elaborate detail details "
150
+ "please again".split())
151
+
152
+
153
+ def topic(text: str, span: tuple[int, int]) -> str:
154
+ """`text` without the date phrase at `span` and without generic words: '' for "which
155
+ sites did I visit yesterday?"."""
156
+ rest = text[:span[0]] + " " + text[span[1]:]
157
+ return " ".join(w for w in re.findall(r"\w+", rest.lower())
158
+ if w not in _GENERIC and w not in STOPWORDS)
159
+
160
+
161
+ _POINTS_BACK = frozenset(
162
+ "it its it's that this these those they them their he she him his her same also else "
163
+ "more former latter".split())
164
+ _OPENS_FOLLOW_UP = re.compile(r"\s*(?:and|but|so|also|what\s+about|how\s+about)\b", re.I)
165
+ # "the second one", "which one", "can a list be one?": a pick from the last answer ("one"
166
+ # elsewhere is too common: "one-hot encoding")
167
+ _PICKS_ONE = re.compile(
168
+ r"\b(?:first|second|third|last|other|previous|which)\s+ones?\b|\bones?\W*$", re.I)
169
+ # "the algorithms that I know": a relative clause, not "that" pointing back
170
+ _RELATIVE_THAT = re.compile(r"\bthat\s+(?:i|you|we|they|he|she|my|your|our|their)\b", re.I)
171
+ # "this year" is a date (chat_facts reads years; _when does not), never "this" pointing back
172
+ _THIS_YEAR = re.compile(r"\bthis\s+year\b", re.I)
173
+
174
+
175
+ def follow_up(text: str, got=None) -> bool:
176
+ """Whether `text` leans on the previous question ("and its running time?", "why?", "what
177
+ about heaps"): then both are searched together. A question that names its own topic is
178
+ searched alone, so a new subject is not mixed with the last one. `got`: its date phrase,
179
+ whose words ("this month") never point back."""
180
+ own = text[:got[2][0]] + " " + text[got[2][1]:] if got else text
181
+ own = _THIS_YEAR.sub(" ", _RELATIVE_THAT.sub(" ", own))
182
+ if _OPENS_FOLLOW_UP.match(text) or _PICKS_ONE.search(own) \
183
+ or _POINTS_BACK & set(re.findall(r"[\w']+", own.lower())):
184
+ return True
185
+ return not got and not topic(text, (0, 0)) # nothing of its own to search for
186
+
187
+
188
+ _ITEM = re.compile(r"(?:\d{1,2}[.)]|[-*•])\s+(\S.*)")
189
+ _CITES = re.compile(r"\s*\[\d{1,3}(?:\s*,\s*\d{1,3})*\]")
190
+ _ORDS = {"first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4,
191
+ "4th": 4, "fifth": 5, "5th": 5, "sixth": 6, "6th": 6, "seventh": 7, "7th": 7,
192
+ "eighth": 8, "8th": 8, "ninth": 9, "9th": 9, "tenth": 10, "10th": 10, "last": -1}
193
+ _ORD = "|".join(_ORDS)
194
+ # "the second one", "the 2nd", "number 2", "#2", "the last one", "the first", "the other one";
195
+ # never "the first time I ..." or "the last week"; a bare "the first" picks only when at most one
196
+ # word ends the clause ("what does the 2nd cover?"), never "what was the first course I took?"
197
+ _PICK = re.compile(
198
+ rf"\bthe\s+({_ORD})\b(?!\s+(?:times?|days?|weeks?|months?|years?|steps?|part|half|place"
199
+ rf"|things?)\b)(?=\s*(?:[\w'-]+\s*)?(?:[?.!,;:]|$))|\b({_ORD})\s+one\b"
200
+ rf"|\bnumber\s+(\d{{1,2}})\b|#(\d{{1,2}})\b|\bthe\s+other\s+one\b", re.I)
201
+
202
+
203
+ def list_items(answer: str) -> list[str]:
204
+ """The items of the list in an assistant's `answer`: top-level lines starting 1. 1) - * or
205
+ •, as plain text (citations, links and markup out; a trailing "(...)" kept)."""
206
+ out = []
207
+ for ln in answer.splitlines():
208
+ if len(ln) - len(ln.lstrip()) < 2 and (m := _ITEM.fullmatch(ln.strip())) \
209
+ and (item := chat_study._title(_CITES.sub("", m[1]))):
210
+ out.append(item)
211
+ return out
212
+
213
+
214
+ def picked(text: str, got, items: list[str], prev: str) -> str | None:
215
+ """The item of the assistant's last list (`items`) that `text` picks ("the second one",
216
+ "#2", "the last one", "the other one" of two: the one `prev` did not name), or with a pronoun
217
+ and no pick the only item of a one-item list; None otherwise. `got`: `text`'s date phrase."""
218
+ m = _PICK.search(text)
219
+ if m and m[0].lower().startswith("the other"):
220
+ named = [i for i in items if i.split(" (")[0].casefold() in prev.casefold()]
221
+ return next(i for i in items if i not in named) if len(items) == 2 and len(named) == 1 \
222
+ else None
223
+ if m:
224
+ w = (m[1] or m[2] or "").lower()
225
+ n = _ORDS[w] if w else int(m[3] or m[4])
226
+ return items[n - 1 if n > 0 else n] if items and -1 <= n <= len(items) and n else None
227
+ own = text[:got[2][0]] + " " + text[got[2][1]:] if got else text
228
+ own = _THIS_YEAR.sub(" ", _RELATIVE_THAT.sub(" ", own))
229
+ if len(items) == 1 and _POINTS_BACK & set(re.findall(r"[\w']+", own.lower())):
230
+ return items[0]
231
+ return None
232
+
233
+
234
+ # ---- storage ---------------------------------------------------------------------------------
235
+
236
+ def _path(vault: Vault, id: str):
237
+ if not isinstance(id, str) or not ID_RE.fullmatch(id):
238
+ raise ValueError("not a chat id")
239
+ return vault.root / DIR / f"{id}.jsonl"
240
+
241
+
242
+ def _now() -> str:
243
+ return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
244
+
245
+
246
+ def new() -> str:
247
+ from ulid import ULID # lazy, as in events: its import is slow
248
+ return str(ULID())
249
+
250
+
251
+ def load(vault: Vault, id: str) -> list:
252
+ """The messages of chat `id` ([] for a new one); torn or odd lines are skipped."""
253
+ p = _path(vault, id)
254
+ with _LIVE_LOCK:
255
+ live = _live.get(id)
256
+ if live is not None:
257
+ return [*live]
258
+ try:
259
+ raw = p.read_text(encoding="utf-8")
260
+ except FileNotFoundError:
261
+ return []
262
+ out = []
263
+ for line in raw.splitlines():
264
+ try:
265
+ m = json.loads(line)
266
+ except ValueError:
267
+ continue
268
+ if isinstance(m, dict) and m.get("role") in ("user", "assistant") \
269
+ and isinstance(m.get("text"), str):
270
+ out.append(m)
271
+ return out
272
+
273
+
274
+ def _save(vault: Vault, id: str, msgs: list, keep: bool) -> None:
275
+ with _LIVE_LOCK:
276
+ # a chat touched while history was off stays in memory for the session, even after
277
+ # history is turned on again: writing it then would save the history-off turns
278
+ if not keep or id in _live:
279
+ _live[id] = msgs
280
+ while len(_live) > 50:
281
+ _live.pop(next(iter(_live)))
282
+ return
283
+ vault.write_text(_path(vault, id), "".join( # a <private> span stays in memory only
284
+ json.dumps({**m, "text": chats.drop_private(m["text"])} if isinstance(
285
+ m.get("text"), str) else m, ensure_ascii=False) + "\n" for m in msgs))
286
+
287
+
288
+ def _summary(id: str, msgs: list) -> dict | None:
289
+ first = next((m["text"] for m in msgs if m["role"] == "user"), None)
290
+ if first is None:
291
+ return None
292
+ return {"id": id, "title": " ".join(first.split())[:TITLE],
293
+ "updated": msgs[-1].get("ts", ""), "count": len(msgs)}
294
+
295
+
296
+ def list(vault: Vault) -> list: # shadows the builtin on purpose: chat.list
297
+ """[{id, title (the first question cut to TITLE characters), updated, count}], newest
298
+ first."""
299
+ folder = vault.root / DIR
300
+ ids = {p.stem for p in folder.glob("*.jsonl") if ID_RE.fullmatch(p.stem)} \
301
+ if folder.is_dir() else set()
302
+ with _LIVE_LOCK:
303
+ live = set(_live)
304
+ out = [s for i in ids | live if (s := _summary(i, load(vault, i)))]
305
+ return sorted(out, key=lambda s: (s["updated"], s["id"]), reverse=True)
306
+
307
+
308
+ def delete(vault: Vault, id: str) -> bool:
309
+ p = _path(vault, id)
310
+ with _LIVE_LOCK:
311
+ gone = _live.pop(id, None) is not None
312
+ return vault.remove(p) or gone
313
+
314
+
315
+ def delete_all(vault: Vault) -> int:
316
+ folder = vault.root / DIR
317
+ with _LIVE_LOCK:
318
+ n = len(_live)
319
+ _live.clear()
320
+ for p in folder.glob("*.jsonl") if folder.is_dir() else ():
321
+ if ID_RE.fullmatch(p.stem) and vault.remove(p):
322
+ n += 1
323
+ return n
324
+
325
+
326
+ # ---- a turn ------------------------------------------------------------------------------------
327
+
328
+ # "which sites did I visit in the past 4 months?": answered from the stored day counts, every
329
+ # site in the range, never from a few passages (a small model lists some and repeats them)
330
+ _SITES_Q = re.compile(r"\b(?:sites?|websites?|domains?)\b", re.I)
331
+ # "which sites did I visit", "sites I've been on", "my most visited sites": the person's own
332
+ # browsing, never "the domain of every function" or "the binding sites used by hemoglobin"
333
+ _LIST_Q = re.compile(r"\b(?:i|i've|ive|me|my)\b[\w\s',-]{0,40}?\b(?:visit\w*|went|go|gone|been"
334
+ r"|open\w*|brows\w*|use[ds]?|surf\w*)\b", re.I)
335
+ # a browser filter only as "in Comet", "on Edge": "sites to learn edge detection" is no browser
336
+ _BROWSER = re.compile(r"\b(?:in|on|using|from|with)\s+(?:the\s+)?(?:google\s+|microsoft\s+)?"
337
+ r"(chrome|edge|brave|comet|firefox|opera|vivaldi|arc)\b", re.I)
338
+ # "what's a good site to practise SQL?", "can you suggest websites I could use?": advice
339
+ _SUGGEST = re.compile(r"\b(?:good|best|better|suggest\w*|recommend\w*|should\s+i\s+use"
340
+ r"|could\s+use)\b", re.I)
341
+ # words a plain "list my sites" question holds besides its date and browser; any other word is
342
+ # a topic ("which sites do I use for DSA?"), for the passages
343
+ _LIST_WORDS = frozenset("list all unique distinct every most top many often frequently usually "
344
+ "visits use used using been ve s go gone surf surfed browser".split())
345
+ NOTES_OFF = ("Notes and mistakes are switched off in Chat settings, so I can't read your study "
346
+ "plan.")
347
+ SITES_SHOWN = 2000 # "all the sites": every one, short of a runaway answer
348
+ _MD = re.compile(r"[*_`\[\]<>#|]") # a model-written description stays plain text
349
+
350
+
351
+ def _count(x) -> int | None:
352
+ """A stored count as an int (missing: 0), or None when it is not a number."""
353
+ try:
354
+ return int(x or 0)
355
+ except (TypeError, ValueError, OverflowError):
356
+ return None
357
+
358
+
359
+ def _site_counts(vault: Vault, got, sources: dict, browser: str | None = None):
360
+ """(seen {site: {n, days, hidden, cat}}, visits left out for want of a stored browser,
361
+ days, llm cache, browse settings) for `got`'s days (None: all days), under Chat's
362
+ `browsing` and `private` switches and the browsing settings (`sites._sides`): the one count
363
+ behind the site list and the digest."""
364
+ from keepfold.browse import load_settings, sites
365
+
366
+ days = sites.lean_days(vault)
367
+ llm = sites.load_cache(vault)["llm"]
368
+ settings = load_settings()
369
+ side, scat = sites._sides(settings, llm, days)
370
+ lo, hi = (got[0].isoformat(), got[1].isoformat()) if got else ("", "9999")
371
+ seen: dict[str, dict] = {}
372
+ meta: dict[str, tuple[str, str]] = {} # key -> (site, category)
373
+ unknown = 0 # visits of a named browser's range stored before Keepfold kept the browser
374
+ for day, keys in days.items():
375
+ if not lo <= day <= hi or not isinstance(keys, dict):
376
+ continue
377
+ for key, a in keys.items():
378
+ h = side(day, key) if isinstance(a, dict) else None
379
+ if h is None or not sources.get("private" if h else "browsing"):
380
+ continue
381
+ n = a.get("n", 0)
382
+ if type(n) is not int and (n := _count(n)) is None:
383
+ continue # a malformed entry is skipped, never the whole answer
384
+ if browser:
385
+ w = a.get("w")
386
+ if not isinstance(w, dict):
387
+ unknown += n
388
+ continue
389
+ # ids are source keys ("comet/Default"); a bare browser name is accepted too
390
+ per = [_count(c) for k, c in w.items()
391
+ if isinstance(k, str) and k.split("/")[0] == browser]
392
+ if None in per:
393
+ continue
394
+ b = sum(per)
395
+ n = min(n, b) # a forget lowers "n" only
396
+ if n <= 0:
397
+ continue
398
+ if (m := meta.get(key)) is None:
399
+ site, cat, _pd = sites._split(key)
400
+ m = meta[key] = (site, cat or scat(site))
401
+ if (e := seen.get(m[0])) is None:
402
+ e = seen[m[0]] = {"n": 0, "days": set(), "hidden": False, "cat": m[1]}
403
+ e["n"] += n
404
+ e["days"].add(day)
405
+ e["hidden"] |= bool(h)
406
+ return seen, unknown, days, llm, settings
407
+
408
+
409
+ def asks_sites(text: str, today: date | None = None) -> bool:
410
+ """Whether `text` asks for a list of the sites the person visited (`site_list`): their own
411
+ browsing, not a suggestion ("a good site for SQL") and no topic beyond dates and a browser."""
412
+ if not (_SITES_Q.search(text) and _LIST_Q.search(text)) or _SUGGEST.search(text):
413
+ return False
414
+ b = _BROWSER.search(text)
415
+ rest = text[:b.start()] + " " + text[b.end():] if b else text
416
+ dated = _when(rest, today or _today())
417
+ words = {w for w in topic(rest, dated[2] if dated else (0, 0)).split() if not w.isdigit()}
418
+ return not words - _LIST_WORDS # "top 3 sites": a number is no topic
419
+
420
+
421
+ def site_list(vault: Vault, text: str, got, sources: dict,
422
+ today: date | None = None) -> str | None:
423
+ """The answer to a question asking for a list of sites, or None for any other question:
424
+ every site visited in `got`'s days (None: all days), most visits first, with its category
425
+ and the local model's one-line description, under Chat's own source switches (`browsing`,
426
+ `private`) and the browsing settings (a denied or Don't save site is never stored)."""
427
+ today = today or _today()
428
+ if not asks_sites(text, today):
429
+ return None
430
+ b = _BROWSER.search(text)
431
+ if not (sources.get("browsing") or sources.get("private")):
432
+ return "Browsing is switched off in Chat settings, so I cannot list sites."
433
+ browser = b[1].lower() if b else None
434
+ seen, unknown, days, llm, settings = _site_counts(vault, got, sources, browser)
435
+ lo = got[0].isoformat() if got else ""
436
+ when = f"from {_span(got[0], got[1], today)}" if got else "in everything Keepfold has stored"
437
+ if browser:
438
+ when = f"in {browser.title()} {when}"
439
+ notes = []
440
+ if unknown:
441
+ notes.append(f"{unknown} visit{'s' * (unknown != 1)} in this range were imported "
442
+ "before Keepfold kept which browser they came from, so they are left out. "
443
+ "Days your browsers no longer fully hold cannot get it back.")
444
+ stored = min((d for d in days if isinstance(days[d], dict)), default=None)
445
+ if stored and lo < stored:
446
+ notes.append(f"Keepfold has browsing from {stored} on; browsers keep about 90 days of "
447
+ "history, so older days are here only if they were imported then.")
448
+ if skipped := sorted(settings.skip_categories):
449
+ notes.append(f"Categories set to Don't save ({', '.join(skipped)}) are never stored, so "
450
+ "they cannot be listed; change that under Browsing in the app.")
451
+ if not seen:
452
+ return " ".join([f"No sites are stored {when}."] + notes)
453
+ order = sorted(seen.items(), key=lambda kv: (-kv[1]["n"], kv[0]))
454
+ lines = [f"**{len(order)} site{'s' * (len(order) != 1)}** {when}, most visits first:", ""]
455
+ for site, e in order[:SITES_SHOWN]:
456
+ entry = llm.get(site) if isinstance(llm.get(site), dict) else {}
457
+ # a visible site never shows what the model wrote from private titles ("h")
458
+ said = (entry.get("h") or entry.get("v")) if e["hidden"] else entry.get("v")
459
+ said = said if isinstance(said, dict) else {}
460
+ desc = _MD.sub("", str(said.get("desc") or "")).strip()
461
+ cat = "" if e["cat"] in ("", "other") else f" · {e['cat']}"
462
+ nd = len(e["days"])
463
+ lines.append(f"- **{site}**{cat} · {e['n']} visit{'s' * (e['n'] != 1)} on {nd} "
464
+ f"day{'s' * (nd != 1)}" + (f": {desc}" if desc else ""))
465
+ if len(order) > SITES_SHOWN:
466
+ lines.append(f"- and {len(order) - SITES_SHOWN} more with fewer visits")
467
+ return "\n".join(lines + ([""] + notes if notes else []))
468
+
469
+
470
+ DIGEST_SHOWN = 10 # lines per digest section
471
+ _plural = chat_study._plural
472
+ _NOTE_KINDS = ("note", "resource", "decision", "project", "loop") # resource: chats too
473
+ _JOURNAL_LINE = re.compile(r"- (?:\d\d:\d\d|—) ") # as reflect.portrait; — is back-dated
474
+ _INDEX: dict = {} # vault root -> the digest's Index, kept between answers
475
+ _INDEX_LOCK = threading.Lock() # two chat streams may digest at once
476
+ _DAYS: dict = {} # vault root -> {(path, its stat): (ask._note_day, semantic.is_chat)}
477
+
478
+
479
+ def _capped(head: str, items: list, more: str = "more") -> list:
480
+ return [head, "", *[f"- {x}" for x in items[:DIGEST_SHOWN]],
481
+ *([f"- and {len(items) - DIGEST_SHOWN} {more}"] if len(items) > DIGEST_SHOWN else [])]
482
+
483
+
484
+ FRESH = 5.0 # UX-B: seconds the "#" list and Review's related lines reuse an unrefreshed index
485
+ _REFRESHED: dict = {} # vault root -> time.monotonic() of its index's last refresh
486
+
487
+
488
+ def _index(vault: Vault, max_age: float = 0.0):
489
+ """The kept Index of `vault` (the pages ask._passages searches), refreshed, not rebuilt
490
+ (~3 s a build). `max_age`: skip the refresh (~90 ms at 5k) when the last one is that
491
+ recent. Call it under _INDEX_LOCK."""
492
+ from keepfold.catalog import Catalog
493
+ from keepfold.index import Index
494
+
495
+ idx, now = _INDEX.get(vault.root), time.monotonic()
496
+ if idx is not None and now - _REFRESHED.get(vault.root, -1e9) < max_age:
497
+ return idx
498
+ catalog = Catalog.load(vault)
499
+ if idx is None:
500
+ idx = _INDEX[vault.root] = Index(vault, catalog)
501
+ else:
502
+ idx.catalog = catalog
503
+ idx.refresh()
504
+ _REFRESHED[vault.root] = time.monotonic()
505
+ return idx
506
+
507
+
508
+ def _page_days(vault: Vault, sources: dict) -> list:
509
+ """[(day, id, page, is_chat, is_private, switches)] of every page the index holds and,
510
+ under the `private` switch, every private one (`ask.private_pages`), each dated as
511
+ `ask._passages(between=…)` dates it (`ask._note_day`; '' undated), with the switches its
512
+ passages fall under there (`ask._switch`; any one on lets the search return it)."""
513
+ with _INDEX_LOCK:
514
+ idx = _index(vault)
515
+ paths = {i: p for p, i in idx._ids.items()}
516
+ stats = dict(idx._stats)
517
+ private = {i: n for i, (_, n) in ask.private_pages(vault, idx).items()} \
518
+ if sources.get("private") else {}
519
+ pages = [*idx._notes.items(), *private.items()] # chat.list shadows the builtin
520
+ # (day, is_chat) per file version: both read the whole body (~1 ms a note), so they are
521
+ # kept between answers for the files that did not change
522
+ old, memo = _DAYS.get(vault.root, {}), {}
523
+ out = []
524
+ for i, n in pages:
525
+ if i not in paths:
526
+ continue
527
+ k = (paths[i], stats.get(paths[i]))
528
+ d, is_chat = memo[k] = old.get(k) or (ask._note_day(vault, i, n, paths[i]),
529
+ semantic.is_chat(n))
530
+ own = "private" if i in private else "chats" if is_chat else "notes"
531
+ # a browse/ page is a browse passage as a search hit, a note or chat as `ask._dated`'s
532
+ switches = (own, "browsing") if own != "private" and idx._rel(
533
+ paths[i]).startswith("browse/") else (own,)
534
+ out.append((d, i, n, is_chat, i in private, switches))
535
+ _DAYS[vault.root] = memo
536
+ return out
537
+
538
+
539
+ def _pages_in(vault: Vault, lo: str, hi: str, sources: dict) -> list:
540
+ """[(day, kind, id, title, body, is_chat, is_private, aliases)] of notes, saved AI chats and
541
+ journal pages dated in [lo, hi] (`ask._note_day`: a date, else a note's last change), under
542
+ Chat's `notes` and `chats` switches. Private pages (`ask.private_pages`: their own
543
+ `private: true`, or under a private subject) come under the `private` switch instead: the
544
+ local model may read them (owner's decision, 19 Nov 2026). `aliases`: index.aliases."""
545
+ out = [(d, n["kind"], i, chat_study._title(n["title"]) or i, n["body"], is_chat, priv,
546
+ aliases(n["fields"]))
547
+ for d, i, n, is_chat, priv, _ in _page_days(vault, sources)
548
+ if n["kind"] in (*_NOTE_KINDS, "journal") and lo <= d <= hi
549
+ and (priv or sources.get("chats" if is_chat else "notes"))]
550
+ return sorted(out, key=lambda p: (p[0], p[3]))
551
+
552
+
553
+ _HORIZON: dict = {} # vault root -> (stamp, sorted days): `_horizon_days`
554
+
555
+
556
+ def _private_names(vault: Vault) -> tuple:
557
+ """The files under browse/private/ (home.version leaves them out): their days are their
558
+ names, so names alone stamp them."""
559
+ top = vault.root / PRIVATE_BROWSE_DIR
560
+ return tuple(sorted(os.path.join(d, f) for d, _, fs in os.walk(top) for f in fs))
561
+
562
+
563
+ def _horizon_days(vault: Vault, sources: dict) -> list[str]:
564
+ """Every day (sorted, unique) that holds a page `ask._passages(between=…)` could return
565
+ under `sources`: indexed and private pages as `_page_days` dates them, and browse pages by
566
+ their file name (`ask._browse_day`; vectors.search embeds every browse/**/*.md first). Kept
567
+ per home.version (its listings: browse/sites/ site pages are left out, but they are
568
+ undated), the private browse names and the switches."""
569
+ from keepfold import home # lazy: home pulls in the dashboard
570
+
571
+ key = (home.version(vault), _private_names(vault) if sources.get("private") else (),
572
+ tuple(sorted((k, bool(v)) for k, v in sources.items())))
573
+ hit = _HORIZON.get(vault.root)
574
+ if hit and hit[0] == key:
575
+ return hit[1]
576
+ days = {d for d, _, _, _, _, switches in _page_days(vault, sources)
577
+ if d and any(sources.get(k) for k in switches)}
578
+ top = vault.root / "browse"
579
+ hidden = os.path.normcase(str(vault.root / PRIVATE_BROWSE_DIR))
580
+ for folder, _, files in os.walk(top):
581
+ nc = os.path.normcase(folder)
582
+ if sources.get("private" if nc == hidden or nc.startswith(hidden + os.sep)
583
+ else "browsing"):
584
+ days |= {d for f in files if f.endswith(".md") and (d := ask._browse_day(f))}
585
+ days = sorted(days)
586
+ _HORIZON[vault.root] = (key, days)
587
+ return days
588
+
589
+
590
+ def horizon(vault: Vault, sources: dict) -> dict | None:
591
+ """{first, last, months: ["YYYY-MM", ...]}: the months holding any page Chat's search could
592
+ read under `sources` (`_horizon_days`), or None when it could read none."""
593
+ return _horizon(_horizon_days(vault, sources))
594
+
595
+
596
+ def _horizon(days: list[str]) -> dict | None:
597
+ months = sorted({d[:7] for d in days})
598
+ return {"first": months[0], "last": months[-1], "months": months} if months else None
599
+
600
+
601
+ def _month_name(ym: str) -> str:
602
+ try:
603
+ return f"{date.fromisoformat(ym + '-01'):%b %Y}"
604
+ except ValueError: # a page id's odd day ("2026-13-40") still counts, as the search's
605
+ return ym
606
+
607
+
608
+ def _nothing(lo: date, hi: date, days: list[str], today: date) -> str | None:
609
+ """Keepfold's own answer when no page `ask._passages(between=(lo, hi))` could return is
610
+ dated in [lo, hi] (`days`: `_horizon_days`), else None. The same day check as the search's
611
+ filter, so it never hides a page the search would find."""
612
+ a, b = lo.isoformat(), hi.isoformat()
613
+ i = bisect.bisect_left(days, a)
614
+ if i < len(days) and days[i] <= b:
615
+ return None
616
+ when = f"on {_span(lo, hi, today)}" if lo == hi else f"from {_span(lo, hi, today)}"
617
+ out = f"Keepfold has nothing {when}."
618
+ if days and (a > days[-1] or b < days[0]):
619
+ out += f" Your data covers {_month_name(days[0][:7])} – {_month_name(days[-1][:7])}."
620
+ return out
621
+
622
+
623
+ def digest(vault: Vault, lo: date, hi: date, sources: dict, today: date,
624
+ unit: str | None = None) -> str:
625
+ """What Keepfold holds about the days `lo` to `hi`, read from its own data with no model: what
626
+ was studied (chat_study's range answer), the most visited sites (`_site_counts`), notes,
627
+ saved AI chats and private notes written or changed, and journal lines, each section capped
628
+ and only when it has something, then one line on what is left out. `unit`: "day", "week" or
629
+ "days" for the heading (chat_study.digest_days), else by the range."""
630
+ when = f"on {_span(lo, hi, today)}" if lo == hi else f"from {_span(lo, hi, today)}"
631
+ unit = unit or ("day" if lo == hi else "days")
632
+ if unit == "week" and (lo, hi) == (_monday(today), today):
633
+ unit = "week so far" # on a Monday too, when it is one day so far
634
+ sections = []
635
+ studied = chat_study.answer(vault, "range", (lo, hi, None), today,
636
+ bool(sources.get("private"))) \
637
+ if sources.get("notes") else chat_study.NO_STUDY
638
+ if not studied.startswith(chat_study.NO_STUDY):
639
+ sections.append(studied.splitlines())
640
+ skipped: list = []
641
+ if sources.get("browsing") or sources.get("private"):
642
+ seen, _, _, _, settings = _site_counts(vault, (lo, hi), sources)
643
+ skipped = sorted(settings.skip_categories)
644
+ if seen:
645
+ order = sorted(seen.items(), key=lambda kv: (-kv[1]["n"], kv[0]))
646
+ visits = sum(e["n"] for e in seen.values())
647
+ sections.append(_capped(
648
+ f"**{_plural(len(order), 'site')}** visited ({_plural(visits, 'visit')}), "
649
+ "most first:",
650
+ [f"**{s}**" + ("" if e["cat"] in ("", "other") else f" · {e['cat']}")
651
+ + f" · {_plural(e['n'], 'visit')}" for s, e in order], "more sites"))
652
+ pages = _pages_in(vault, lo.isoformat(), hi.isoformat(), sources)
653
+ notes = [p[3] for p in reversed(pages) if p[1] != "journal" and not p[5] and not p[6]]
654
+ if notes:
655
+ sections.append(_capped(f"**{_plural(len(notes), 'note')}** written or changed:", notes))
656
+ chats = [p[3] for p in reversed(pages) if p[5] and not p[6]]
657
+ if chats:
658
+ sections.append(_capped(f"**{_plural(len(chats), 'saved AI chat')}**:", chats))
659
+ private = [p[3] for p in reversed(pages) if p[6]] # any kind: under the private switch only
660
+ if private:
661
+ sections.append(_capped(f"**{_plural(len(private), 'private note')}** written or "
662
+ "changed:", private))
663
+ journal = [(_span(d := date.fromisoformat(p[0]), d, today) + " " if lo != hi else "")
664
+ + chat_study._title(ln[2:].strip())
665
+ for p in pages if p[1] == "journal" and not p[6]
666
+ for ln in p[4].splitlines() if _JOURNAL_LINE.match(ln)]
667
+ if journal:
668
+ sections.append(_capped(f"**Journal** ({_plural(len(journal), 'line')}):", journal))
669
+ off = [label for k, label in (("notes", "notes, studying and journal"),
670
+ ("chats", "saved AI chats"),
671
+ ("browsing", "browsing"),
672
+ ("private", "private notes, subjects and browsing"))
673
+ if not sources.get(k)]
674
+ left = [f"{', '.join(off)} (switched off in Chat settings)"] if off else []
675
+ if skipped:
676
+ left.append(f"site categories set to Don't save ({', '.join(skipped)}), never stored")
677
+ tail = ["Not included: " + "; ".join(left) + "."] if left else []
678
+ if not sections:
679
+ return " ".join([f"Keepfold has nothing recorded {when}.", *tail])
680
+ out = [f"**Your {unit}** {when}:"]
681
+ for sec in sections:
682
+ out += ["", *sec]
683
+ return "\n".join([*out, *([""] + tail if tail else [])])
684
+
685
+
686
+ def _looping(text: str) -> bool:
687
+ """A small model caught in a loop: some line of 20+ characters said three times."""
688
+ seen = Counter(ln.strip() for ln in text.splitlines() if len(ln.strip()) >= 20)
689
+ return bool(seen) and seen.most_common(1)[0][1] >= 3
690
+
691
+
692
+ def _once(text: str) -> str:
693
+ """`text` with each repeated line of 20+ characters kept only the first time."""
694
+ out, seen = [], set()
695
+ for ln in text.splitlines():
696
+ k = ln.strip()
697
+ if len(k) >= 20 and k in seen:
698
+ continue
699
+ seen.add(k)
700
+ out.append(ln)
701
+ return "\n".join(out)
702
+
703
+
704
+ def _today(now: datetime | None = None) -> date:
705
+ """The local day as events, site days and the dashboard count it: it starts at 04:00."""
706
+ return date.fromisoformat(events.local_day(now or datetime.now(UTC)))
707
+
708
+
709
+ def _span(a: date, b: date, today: date | None = None) -> str:
710
+ """'17 Nov', '10 Nov to 16 Nov' or '11 Sep 2001' (a year other than `today`'s)."""
711
+ today = today or _today()
712
+ day = chat_study._day
713
+ return day(a, today) if a == b else f"{day(a, today)} to {day(b, today)}"
714
+
715
+
716
+ def _local(runner) -> bool:
717
+ """Only a plain loopback localllm.Runner hears private passages: cloudllm's CloudRunner
718
+ subclasses Runner, so isinstance would let it through."""
719
+ if type(runner) is not localllm.Runner:
720
+ return False
721
+ try:
722
+ localllm._check_url(runner.base)
723
+ except ValueError:
724
+ return False
725
+ return True
726
+
727
+
728
+ def _facts_runner(runner):
729
+ """The local runner to word a typed answer's facts, or None (then `chat_facts.say` words
730
+ them): the app passes localllm.find, looked up only now that facts were found."""
731
+ if callable(runner) and not isinstance(runner, localllm.Runner):
732
+ try:
733
+ runner = runner()
734
+ except ValueError: # a refused localllm setting: the facts in plain words instead
735
+ return None
736
+ return runner if _local(runner) else None
737
+
738
+
739
+ def _made_with_off(m: dict, sources: dict) -> bool:
740
+ """Was answer `m` made with a source switch on that `sources` now has off? An answer saved
741
+ before switches were recorded counts as made with every switch on."""
742
+ was = m.get("switches")
743
+ was = was if isinstance(was, dict) else {}
744
+ return any(was.get(k, True) and not on for k, on in sources.items())
745
+
746
+
747
+ def about(vault: Vault, sources: dict, today: date) -> str:
748
+ """The system message's "About the user" block: prime's pinned core (me/core.md) and
749
+ Profile, wrapped as untrusted data and unnumbered (never a citable [n]), within ABOUT_MAX;
750
+ "" when there is nothing to say. A page comes in only when Chat would show it as a passage
751
+ (`access.may_see("chat_local", ...)` under the source switches), never on a weaker rule."""
752
+ def shown(page: str) -> bool:
753
+ note = prime.me(vault, page)
754
+ return note is not None and access.may_see(
755
+ "chat_local", access.audience_of_note(note), "note", sources)
756
+ withheld = {p for p in ("core", "profile") if not shown(p)}
757
+ if len(withheld) == 2:
758
+ return ""
759
+ evs, day = [*events.EventLog(vault).iter_events()], today.isoformat() # chat.list shadows
760
+ served, waits = prime.served_claims(vault, evs), prime.held(vault, evs, day)
761
+ lines = prime.core_lines(vault, served, day, withheld, prime.claim_ids(vault),
762
+ xray.settings(vault)["mute"] | waits) # as prime.core does
763
+ if "profile" not in withheld and (summary := prime.profile_summary(vault, day, served,
764
+ waits)):
765
+ lines.append(summary)
766
+ text = "\n".join(lines).strip()
767
+ while text: # trim until the wrapped block fits (escaping can lengthen the text)
768
+ block = ABOUT + _wrap("about the user", text)
769
+ if (over := len(block) - ABOUT_MAX) <= 0:
770
+ return block
771
+ if len(text) - over < 40:
772
+ return ""
773
+ text = text[: len(text) - over - 1].rstrip() + "…"
774
+ return ""
775
+
776
+
777
+ def history(msgs: list, sources: dict | None = None, spent: int = 0) -> list:
778
+ """The last TURNS messages as plain {role, content}, oldest dropped first to fit
779
+ HISTORY_BUDGET, same-role neighbours joined (a failed turn leaves two user messages; some
780
+ chat templates refuse that), starting with a user message. With `sources` (the switches
781
+ now), an answer made with a switch now off is left out with the question(s) before it, so
782
+ a private site listed earlier never reaches the model after Private is turned off. A turn
783
+ the model never answered (`unanswered`: Keepfold's note, not the model's words) is left out."""
784
+ out: list = []
785
+ for _, m in _sent(msgs, sources, spent):
786
+ text = m["text"].strip()
787
+ if out and out[-1]["role"] == m["role"]:
788
+ out[-1]["content"] += "\n\n" + text
789
+ else:
790
+ out.append({"role": m["role"], "content": text})
791
+ return out
792
+
793
+
794
+ def _sent(msgs: list, sources: dict | None, spent: int = 0) -> list:
795
+ """[(index in `msgs`, message)] of the messages `history` sends, oldest first; `spent`
796
+ characters of HISTORY_BUDGET are taken already (the `about` block)."""
797
+ pairs = [(i, m) for i, m in enumerate(msgs) if not m.get("unanswered")]
798
+ if sources is not None:
799
+ kept: list = []
800
+ for i, m in pairs:
801
+ if m["role"] == "assistant" and _made_with_off(m, sources):
802
+ while kept and kept[-1][1]["role"] == "user":
803
+ kept.pop()
804
+ continue
805
+ kept.append((i, m))
806
+ pairs = kept
807
+ out, left = [], HISTORY_BUDGET - spent
808
+ for i, m in reversed(pairs[-TURNS:]):
809
+ text = m["text"].strip()
810
+ if not text:
811
+ continue
812
+ if len(text) > left:
813
+ break
814
+ left -= len(text)
815
+ out.append((i, m))
816
+ out.reverse()
817
+ while out and out[0][1]["role"] != "user":
818
+ out.pop(0)
819
+ return out
820
+
821
+
822
+ def remembers(msgs: list, sources: dict | None = None) -> int:
823
+ """The index of the oldest message of `msgs` the model still gets on the next turn
824
+ (`history`), for the Chat page's "The model remembers from here" line: 0 when it gets them
825
+ all (no line), len(msgs) when it gets none."""
826
+ sent = _sent(msgs, sources, ABOUT_MAX) # the most `about` may take: never too generous
827
+ return sent[0][0] if sent else len(msgs)
828
+
829
+
830
+ _HEADING = re.compile(r"^#{1,6}\s+(.+)$", re.M)
831
+
832
+
833
+ RELATIVES = 3 # names one "my <relation>" may add to the search
834
+ _MY = re.compile(r"\bmy\s+\w", re.I)
835
+
836
+
837
+ def relatives(vault: Vault, text: str) -> list[str]:
838
+ """Names of the people pages whose `relation` field `text` names as "my <relation>" ("my
839
+ sister", "my study-partner"), for the search: the question rarely holds the name itself.
840
+ Public people pages only: the index never holds a private one, and none is read here."""
841
+ if not _MY.search(text):
842
+ return []
843
+ with _INDEX_LOCK:
844
+ people = sorted((n["title"], str(n["fields"].get("relation") or ""))
845
+ for n in _index(vault)._notes.values() if n["kind"] == "person")
846
+ out = []
847
+ for title, rel in people:
848
+ tag = re.escape(rel).replace(r"\-", r"[\s-]")
849
+ if rel and re.search(rf"\bmy\s+{tag}s?\b", text, re.I) and (name := chat_study._title(
850
+ title)) and name not in out:
851
+ out.append(name)
852
+ return out[:RELATIVES]
853
+
854
+
855
+ PICK = 8 # UX-B: rows of the "#" list
856
+ PICKED = 3 # pages one message may carry
857
+
858
+
859
+ def _may_read(idx, i: str, paths: dict, sources: dict) -> bool:
860
+ """UX-B: may Chat read page `i` under its switches `sources` now? The one rule for "#",
861
+ the list and the send: the switch `passage` asks (`ask._switch`) must be on; a private
862
+ page (left out of `idx._notes`) only under `private`. An id the index lacks: never."""
863
+ if i not in paths:
864
+ return False
865
+ if i in idx._private:
866
+ return bool(sources.get("private"))
867
+ if (n := idx._notes.get(i)) is None:
868
+ return False
869
+ rel = idx._rel(paths[i])
870
+ kind = "browse" if rel.startswith("browse/") else "chat" if semantic.is_chat(n) else "note"
871
+ return bool(sources.get(ask._switch({"path": rel, "kind": kind})))
872
+
873
+
874
+ def pick_list(vault: Vault, q: str, sources: dict) -> list[dict]:
875
+ """UX-B: the "#" list, [{id, title, kind}] of at most PICK pages Chat may read
876
+ (`_may_read`): those whose title or aliases hold every word of `q` (the index's
877
+ `title_matches`), or with no words the most recently changed. The shared index holds no
878
+ private page, so none is offered."""
879
+ from keepfold.index import fts_query
880
+ with _INDEX_LOCK:
881
+ idx = _index(vault, FRESH)
882
+ paths = {i: p for p, i in idx._ids.items()}
883
+ ids = idx.title_matches(q, None, 10 * PICK) if fts_query(q) else (
884
+ idx._ids[p] for p in sorted(idx._ids, key=lambda p: idx._stats[p], reverse=True))
885
+ out = []
886
+ for i in ids:
887
+ if i in idx._notes and _may_read(idx, i, paths, sources):
888
+ n = idx._notes[i]
889
+ out.append({"id": i, "title": chat_study._title(n["title"]) or i,
890
+ "kind": n["kind"]})
891
+ if len(out) == PICK:
892
+ break
893
+ return out
894
+
895
+
896
+ def picked_pages(vault: Vault, ids, sources: dict) -> list[dict]:
897
+ """UX-B: the pages picked with "#" (at most PICKED ids) as passages led like an attached
898
+ file's (`_page_passages`, up to askfile.CHUNK_MAX characters each); an id Chat may not
899
+ read now (`_may_read`) is dropped before any page is read."""
900
+ ids = [*dict.fromkeys(i for i in ids if isinstance(i, str))][:PICKED] \
901
+ if isinstance(ids, builtins.list) else [] # chat.list shadows the builtin
902
+ if not ids:
903
+ return []
904
+ with _INDEX_LOCK:
905
+ idx = _index(vault)
906
+ paths = {i: p for p, i in idx._ids.items()}
907
+ ok = [i for i in ids if _may_read(idx, i, paths, sources)]
908
+ return _page_passages(vault, ok, askfile.CHUNK_MAX)
909
+
910
+
911
+ def _page_passages(vault: Vault, ids: list, cap: int = ask.PASSAGE) -> list[dict]:
912
+ """The start of each page in `ids` (up to `cap` characters) as a passage
913
+ (`ask._passages`' shape), for a compare's top pages and the pages picked with "#". The
914
+ callers named them under Chat's switches, so a private one (only there under `private`)
915
+ is read as `ask.private_pages` reads it."""
916
+ with _INDEX_LOCK:
917
+ idx = _index(vault)
918
+ paths = {i: p for p, i in idx._ids.items()}
919
+ private = set(idx._private)
920
+ out = []
921
+ for i in dict.fromkeys(ids):
922
+ if i not in paths or (n := ask._page(vault, paths[i], i)) is None:
923
+ continue
924
+ p = ask._note(vault, i, n, paths[i].relative_to(vault.root).as_posix(),
925
+ semantic._chunk_text(n, 0)[:cap],
926
+ "chat" if semantic.is_chat(n) else "note",
927
+ **({"private": True} if i in private else {}))
928
+ p["at"], p["len"] = ask._span(p.pop("_body"), p["text"], p["title"])
929
+ out.append(p)
930
+ return out
931
+
932
+
933
+ def _clean(text: str) -> str:
934
+ """Untrusted page text, line by line, without links, images, URLs or HTML."""
935
+ return "\n".join(render.plain(ln, 10_000) for ln in text.splitlines()).strip()
936
+
937
+
938
+ def passage(vault: Vault, path, at, size, sources: dict) -> dict:
939
+ """The passage an answer cited (`ask._passages`' path, at and len): {path, title, kind,
940
+ heading (the last heading above it, "" at the top), text}, at most ask.PASSAGE characters
941
+ from `at` of the page's body, links and images stripped. Under Chat's switches of now, as an
942
+ answer reads (`ask._switch`): a page whose switch is off, a private one with `private` off,
943
+ raises PermissionError, never shows. A path outside the vault or not a page: ValueError."""
944
+ from keepfold.browse import vectors
945
+
946
+ if not isinstance(path, str) or not path.endswith(".md") or "\\" in path \
947
+ or path.startswith("/") or ".." in path.split("/"):
948
+ raise ValueError("Not a page of this vault.")
949
+ try:
950
+ at, size = max(0, int(at)), int(size)
951
+ except (TypeError, ValueError):
952
+ raise ValueError("at and len must be whole numbers.") from None
953
+ size = min(size, ask.PASSAGE) if size > 0 else ask.PASSAGE
954
+ try:
955
+ full = vault._contained(path)
956
+ except VaultError as e:
957
+ raise ValueError(str(e)) from None
958
+ with _INDEX_LOCK:
959
+ idx = _index(vault)
960
+ id_ = idx._ids.get(full)
961
+ private = id_ in idx._private
962
+ n = idx._notes.get(id_) if id_ is not None and not private else None
963
+ if id_ is not None and n is None:
964
+ n = ask._page(vault, full, id_)
965
+ if path.startswith("browse/") and n is None: # a browse page the private search reads
966
+ try:
967
+ title, body = vectors._body(full.read_bytes().decode("utf-8", "replace"))
968
+ except OSError:
969
+ raise ValueError("That page is gone.") from None
970
+ n = {"title": title or full.stem, "body": body, "kind": "browse"}
971
+ if n is None:
972
+ raise ValueError("That page is gone.")
973
+ kind = "browse" if path.startswith("browse/") else "chat" if semantic.is_chat(n) else "note"
974
+ if not sources.get(ask._switch({"path": path, "kind": kind, "private": private})):
975
+ raise PermissionError("That page is under a source switch that is off in Chat now.")
976
+ body = n["body"]
977
+ heads = [m for m in _HEADING.finditer(body) if m.start() <= at]
978
+ return {"path": path, "title": chat_study._title(n["title"]), "kind": kind,
979
+ "heading": chat_study._title(heads[-1][1]) if heads else "",
980
+ "text": _clean(body[at:at + size])}
981
+
982
+
983
+ def _inert(text: str) -> str:
984
+ """An attached file's passage shown as an answer: untrusted text (`_clean`) whose brackets,
985
+ stars and backticks never become citations or markup in the app's renderer."""
986
+ return _clean(text).translate({ord("["): "(", ord("]"): ")", ord("*"): None, ord("`"): "'"})
987
+
988
+
989
+ class Route(NamedTuple):
990
+ """A question Keepfold answers from its own data: the step line, and either `data` (its
991
+ words, no model) or `fq` (a chat_facts query: counted by code, a model may word it)."""
992
+ step: str
993
+ data: Callable[[], str] | None = None
994
+ fq: dict | None = None
995
+
996
+
997
+ def _route(vault: Vault, text: str, own, today: date, first: bool, s: dict,
998
+ leans: bool = False) -> Route | None:
999
+ """The data answer for `text`, or None (the passages answer it): a site list, a digest, a
1000
+ study answer, then chat_facts' typed answers (not for a follow-up). `own`: chat._when of
1001
+ `text`'s own date phrase; `first`: the chat's first question."""
1002
+ span = f" from {_span(own[0], own[1], today)}" if own else ""
1003
+ if asks_sites(text, today):
1004
+ return Route("Counting the sites you visited" + span,
1005
+ lambda: site_list(vault, text, own, s["sources"], today))
1006
+ if (asked := chat_study.kind(text, own, today, first)) == "digest":
1007
+ lo, hi, unit = chat_study.digest_days(text, own, today)
1008
+ return Route("Putting together your " + ("day" if (unit, lo) == ("day", today) else
1009
+ f"{unit} {'on' if lo == hi else 'from'} "
1010
+ f"{_span(lo, hi, today)}"),
1011
+ lambda: digest(vault, lo, hi, s["sources"], today, unit))
1012
+ if asked is not None:
1013
+ return Route(chat_study.STEP[asked] + (span if asked == "range" else ""),
1014
+ lambda: chat_study.study_answer(vault, text, own, today, first,
1015
+ bool(s["sources"].get("private")))
1016
+ if s["sources"].get("notes") else NOTES_OFF)
1017
+ if not leans and (fq := chat_facts.route(text, own, today)) is not None:
1018
+ return Route(chat_facts.step(fq, today), fq=fq) # a model, if any, only words it
1019
+ return None
1020
+
1021
+
1022
+ def _by_code(vault: Vault, r: Route, sources: dict, today: date) -> str:
1023
+ """Route `r`'s answer in Keepfold's own words, no model."""
1024
+ return r.data() if r.data else chat_facts.say(chat_facts.facts(vault, r.fq, sources), today)
1025
+
1026
+
1027
+ _SPLIT = re.compile(r",?\s+and\s+|\s*;\s+", re.I)
1028
+ _WH = re.compile(r"\b(?:what|which|who|whom|whose|when|where|why|how)\b", re.I)
1029
+ _AUX = re.compile(r"\s*(?:is|are|was|were|do|does|did|can|could|should|would|will|have|has"
1030
+ r"|had)\b", re.I)
1031
+ _NO_SPLIT = re.compile(r"^\s*compare\b|\bvs\.?(?!\w)|\bversus\b", re.I)
1032
+ HALF_WORDS = 3 # "where and when ...?" is one question
1033
+
1034
+
1035
+ def _asks(half: str) -> bool:
1036
+ return len(re.findall(r"[\w'.-]+", half)) >= HALF_WORDS and bool(
1037
+ _WH.search(half) or _AUX.match(half))
1038
+
1039
+
1040
+ def halves(text: str, routes) -> list[str]:
1041
+ """`text` as its two questions ("what does X use and how many times did I visit Y?"), split
1042
+ at the first " and " or "; " where both halves read as questions (a question word, or the
1043
+ second half `routes`), else []. "compare X and Y", "X vs Y" and an "and" inside one noun
1044
+ phrase ("the pros and cons of B-trees") are never split."""
1045
+ if _NO_SPLIT.search(text):
1046
+ return []
1047
+ for m in _SPLIT.finditer(text):
1048
+ a, b = text[:m.start()].strip(" ,"), text[m.end():].strip()
1049
+ if _asks(a) and (_asks(b) or routes(b)):
1050
+ return [a, b]
1051
+ return []
1052
+
1053
+
1054
+ # a data answer that found nothing: site_list, digest and `_nothing`, the study answers
1055
+ _EMPTY = ("No sites are stored", "Browsing is switched off", "Keepfold has nothing", NOTES_OFF,
1056
+ chat_study.NO_STUDY, "No concepts yet")
1057
+
1058
+
1059
+ def certainty(*, data: bool = False, empty: bool = False, read: int = 0, cited: int = 0,
1060
+ quoted: bool = False, unquoted: bool = False, unanswered: bool = False,
1061
+ stopped: bool = False) -> str | None:
1062
+ """How far an answer can be trusted, from what `reply` already knows (no model call):
1063
+
1064
+ | answer | certainty |
1065
+ |----------------------------------------------------------------|------------|
1066
+ | stopped | None |
1067
+ | nothing found, an empty data/facts answer, a switch off | "none" |
1068
+ | a data or facts answer counted by code, with a result | "exact" |
1069
+ | model: unanswered, cites nothing, or a quote no passage holds | "thin" |
1070
+ | model: cites, quotes at least one span, every quote found | "exact" |
1071
+ | model: cites, no quote, read 2+ passages | "grounded" |
1072
+ | model: cites, no quote, read 1 passage | "thin" |
1073
+
1074
+ `data`: counted by code (site list, digest, study answer, chat_facts); `empty`: it (or the
1075
+ search) found nothing; `read`/`cited`: passages; `quoted`/`unquoted`: any quoted span /
1076
+ any one no passage holds (`ask.unquoted`)."""
1077
+ if stopped:
1078
+ return None
1079
+ if empty:
1080
+ return "none"
1081
+ if data:
1082
+ return "exact"
1083
+ if unanswered or not cited or unquoted:
1084
+ return "thin"
1085
+ if quoted:
1086
+ return "exact"
1087
+ return "grounded" if read >= 2 else "thin"
1088
+
1089
+
1090
+ def _conflicts(vault: Vault, ps: list[dict]) -> list[tuple[dict, dict]]:
1091
+ """[(old passage, new passage)] for each two of `ps` whose me/ pages hold a recorded pair
1092
+ (claims.recorded_pairs: `update_of`, `supersedes`), once per two pages: the newer is the
1093
+ later day, a tie the recorded direction."""
1094
+ from pathlib import PurePosixPath
1095
+
1096
+ me = {PurePosixPath(p["path"]).stem: p for p in ps if p["path"].startswith("me/")}
1097
+ if len(me) < 2: # the event log is read only when a pair could be there
1098
+ return []
1099
+ from keepfold import claims
1100
+
1101
+ pairs, _ = claims.recorded_pairs(events.EventLog(vault).iter_events())
1102
+ out, seen = [], set()
1103
+ for old, new, _ in pairs.values():
1104
+ a, b = me.get(old[0]), me.get(new[0])
1105
+ if a is None or b is None or a is b or (two := frozenset((a["path"], b["path"]))) in seen:
1106
+ continue
1107
+ seen.add(two)
1108
+ out.append((b, a) if (a.get("day") or "") > (b.get("day") or "") else (a, b))
1109
+ return out
1110
+
1111
+
1112
+ def reply(vault: Vault, convo_id: str | None, text: str, runner, emit, cancel,
1113
+ settings: dict | None = None, today: date | None = None,
1114
+ files: list | None = None, pages: list | None = None) -> str:
1115
+ """One turn of chat `convo_id` (None: a new chat). Saves the question, retrieves, streams
1116
+ the answer through `emit`: {"t": "start", id, model}, {"t": "step", "s"} as it searches and
1117
+ as the model starts reading (the app shows each with a live count), {"t": "think"} while a
1118
+ reasoning model only thinks, {"t": "facts", facts} before any words of a typed data answer
1119
+ (`chat_facts`: count, first, last, timeline, about, compare, gaps; the model then only
1120
+ words them (a compare also reads each side's top page), or
1121
+ `chat_facts.say` does with no model; saved on the answer as `facts`), {"t": "tok", "s"}
1122
+ per piece, {"t": "src", sources: [{n, path, title, kind, at, len}] (the passages cited;
1123
+ `passage` shows one), searched (the same without n, when none is cited), coverage: {read,
1124
+ matched, more (true when a search was full: "matched" is a floor), also (names
1125
+ `relatives` added, when any)} when passages were searched (how many
1126
+ the model read of how many the search found; saved on the answer too), unquoted (quoted
1127
+ spans no cited passage holds, `ask.unquoted`; saved too) when any, certainty (`certainty`:
1128
+ exact, grounded, thin or none; saved too) unless stopped, horizon {first, last, months}
1129
+ ("YYYY-MM": `horizon`, what the search could read; saved as {first, last}) on an answer
1130
+ from the passage search, conflicts [{old, new}: {path, title, day}] when two pages it cited
1131
+ (read, when none cited) hold a recorded pair (`_conflicts`; saved too)}; {"t": "text", "s"}
1132
+ replaces the words so far (a loop cut, leaked tokens dropped, a retry). A model that says
1133
+ nothing is asked once more; still nothing, the answer is SAID_NOTHING with the pages it
1134
+ searched (saved with `unanswered`). A past date range (the question's or a follow-up's)
1135
+ that holds no page the search could read is answered at once by Keepfold (`_nothing`), with
1136
+ no search model or runner. Then {"t": "done", id, model, seconds, stopped,
1137
+ remembers (`remembers` of the chat now)}; or {"t": "err", code (not_set_up,
1138
+ no_local_model, no_answer), message}. A set `cancel` stops the stream; the partial answer
1139
+ is saved with `stopped: true`. Returns the chat id. `runner` is a local `localllm.Runner`
1140
+ or None; never a cloud one.
1141
+
1142
+ `files` (C1, askfile): files attached in the app. Then every question searches them (no
1143
+ data answer): their matching chunks lead (at most askfile.LEAD) and the vault's passages
1144
+ fill the rest (none without the search model). A file is read only by a local runner: with
1145
+ none (or a refused setting) the answer is the askfile.SHOWN best passages under
1146
+ askfile.NO_MODEL (with askfile.LOCAL_ONLY first, once, when Chat's model is a cloud one),
1147
+ saved as their labels only, never the file's text.
1148
+
1149
+ `pages` (UX-B): ids picked with "#", read as `picked_pages` reads them (an id Chat may not
1150
+ read now is dropped unread); they lead the passages as a file's do and, like a file,
1151
+ mean no data answer and no need of the search model."""
1152
+ if not isinstance(text, str) or not text.strip() or len(text) > MAX_TEXT:
1153
+ raise ValueError(f"Type a message (up to {MAX_TEXT:,} characters).")
1154
+ s = settings or get_settings()
1155
+ read = picked_pages(vault, pages, s["sources"]) if pages else []
1156
+ convo_id = convo_id or new()
1157
+ msgs = load(vault, convo_id) # validates the id
1158
+ t0, today = time.monotonic(), today or _today()
1159
+ prev = next((m["text"] for m in reversed(msgs) if m["role"] == "user"), "")
1160
+ # the last answer as the model would still see it (`history`): its list, if any, is what
1161
+ # "the second one" points at
1162
+ last = next((m["text"] for m in reversed(msgs) if m["role"] == "assistant"
1163
+ and not m.get("unanswered") and not _made_with_off(m, s["sources"])), "")
1164
+ got, said = _when(text, today), text
1165
+ item = picked(text, got, list_items(last), prev)
1166
+ leans = item is not None or follow_up(text, got)
1167
+ if leans and not got and prev and (got_prev := _when(prev, today)):
1168
+ got, said = got_prev, prev # "which of those was hardest?": the last dates still hold
1169
+ query = f"{text.strip()}\n{item or prev}".strip() if leans else text.strip()
1170
+ # a site list or a study answer is read from Keepfold's own data with no model, so it needs
1171
+ # neither the search model nor a local runner; it keeps to its own dates (a follow-up's
1172
+ # borrowed ones are for passages only), and so does its step line
1173
+ own = got if said is text else None
1174
+ # which data answer, if any, is decided first and cheaply; it is read after `start` and its
1175
+ # step are sent, so the app shows the step (and Stop) while a heavy vault is counted
1176
+ # (an attached file is asked about: passages, never a data answer)
1177
+ # a two-part question ("what does X use and how many times did I visit Y?"; not one that
1178
+ # leans on the last turn): each half routed on its own, both by code, one in front of the
1179
+ # other half's passages, or two searches. A half that routes wins over the whole question
1180
+ # routing ("how many times did I visit X and how many times did I visit Y?")
1181
+ def half(h: str) -> Route | None:
1182
+ return _route(vault, h, _when(h, today), today, not prev, s)
1183
+ split = [(h, half(h)) for h in halves(text, lambda h: half(h) is not None)] \
1184
+ if not files and not read and not (leans and prev) else []
1185
+ route = None if files or read or any(r for _, r in split) else \
1186
+ _route(vault, text, own, today, not prev, s, leans)
1187
+ split = split if route is None else []
1188
+ codes = [route] if route and route.fq is None else \
1189
+ [r for _, r in split] if split and all(r for _, r in split) else []
1190
+ front = next((r for _, r in split if r), None) if split and not codes else None
1191
+ if front: # the other half is searched alone, with its own dates
1192
+ query = said = next(h for h, r in split if r is None)
1193
+ got = _when(said, today)
1194
+ searches = [(h, _when(h, today), n) for (h, _), n in zip(
1195
+ split, ((s["passages"] + 1) // 2, s["passages"] // 2), strict=True)] \
1196
+ if split and not codes and not front else None
1197
+ fq = route.fq if route else None
1198
+ listed = "" if codes else None # a data answer: filled in after its step
1199
+ passages = listed is None and fq is None # the search model and a runner are needed
1200
+ searched_pages = passages # the answer the horizon is for; sent with its sources
1201
+ days = None
1202
+ # a past range (pages are dated by when they were written: a future one keeps no page)
1203
+ # that holds no page the search could return is answered at once: no model, no embedder
1204
+ if passages and not files and not read and not split and got and got[0] <= today:
1205
+ days = _horizon_days(vault, s["sources"])
1206
+ end = min(got[1], today)
1207
+ if none := _nothing(got[0], end, days, today):
1208
+ codes, listed, passages = [Route(
1209
+ f"Searching your notes and browsing from {_span(got[0], end, today)}",
1210
+ lambda: none)], "", False
1211
+ blocked = None # with a routed half: why its other half gets no model answer
1212
+ if passages and not files and not read and semantic.load_embedder() is None:
1213
+ if front is None:
1214
+ emit({"t": "err", "code": "not_set_up", "message": NO_SEARCH_MODEL,
1215
+ "id": convo_id})
1216
+ return convo_id
1217
+ blocked = NO_SEARCH_MODEL
1218
+ if passages and not blocked and callable(runner) \
1219
+ and not isinstance(runner, localllm.Runner):
1220
+ try: # the app passes localllm.find: it may start LM Studio, so only when needed
1221
+ runner = runner()
1222
+ except ValueError as e: # a refused localllm setting (cloud model, non-loopback url)
1223
+ if not files and front is None:
1224
+ emit({"t": "err", "code": "no_local_model", "message": str(e), "id": convo_id})
1225
+ return convo_id
1226
+ runner, blocked = None, None if files else str(e)
1227
+ if passages and not blocked and not _local(runner):
1228
+ if not files and front is None:
1229
+ emit({"t": "err", "code": "no_local_model", "message": ask.NO_MODEL,
1230
+ "id": convo_id})
1231
+ return convo_id
1232
+ # a file never reaches any other runner: its passages are shown instead
1233
+ runner, blocked = None, None if files else ask.NO_MODEL
1234
+ if blocked: # the routed half by code, and why the rest has no answer
1235
+ codes, listed, passages = [front], "", False
1236
+ model = runner.model if passages and runner is not None else "Keepfold"
1237
+ msgs.append({"role": "user", "text": text.strip(), "ts": _now()})
1238
+ _save(vault, convo_id, msgs, s["history"])
1239
+ emit({"t": "start", "id": convo_id, "model": model})
1240
+ found: list = []
1241
+ also: list = [] # people's names `relatives` added to the search
1242
+ stats: dict = {} # ask._passages' match count, for the coverage line
1243
+ parts: list = []
1244
+ messages = facts = kept = None
1245
+ max_tokens = LENGTH[s["length"]]
1246
+ front_text = "" # a routed half's answer, in front of the other half's passages
1247
+ if listed is not None:
1248
+ for r in codes:
1249
+ emit({"t": "step", "s": r.step})
1250
+ listed = _by_code(vault, r, s["sources"], today)
1251
+ if cancel is not None and cancel.is_set(): # Stop while counting: nothing shown
1252
+ break
1253
+ piece = ("\n\n" if parts else "") + listed
1254
+ parts.append(piece)
1255
+ emit({"t": "tok", "s": piece})
1256
+ if blocked and parts:
1257
+ parts.append("\n\n" + blocked)
1258
+ emit({"t": "tok", "s": parts[-1]})
1259
+ elif fq is not None:
1260
+ emit({"t": "step", "s": route.step})
1261
+ facts = chat_facts.facts(vault, fq, s["sources"])
1262
+ if cancel is not None and cancel.is_set():
1263
+ pass
1264
+ elif chat_facts.empty(facts) or (runner := _facts_runner(runner)) is None:
1265
+ emit({"t": "facts", "facts": facts}) # before the words, for the facts box
1266
+ parts.append(chat_facts.say(facts, today))
1267
+ emit({"t": "tok", "s": parts[0]})
1268
+ else:
1269
+ emit({"t": "facts", "facts": facts})
1270
+ if fq["kind"] == "about" and semantic.load_embedder() is not None:
1271
+ found = ask._passages(vault, fq["term"], 4, sources=s["sources"], stats=stats,
1272
+ between=None if fq["lo"] == chat_facts.FIRST_DAY
1273
+ else (fq["lo"], fq["hi"]), # the period the facts cover
1274
+ topic=fq["term"])
1275
+ elif fq["kind"] == "compare": # each side's top page, read from its start
1276
+ found = _page_passages(vault, [r["page"]["id"] for r in facts["rows"]
1277
+ if r["page"] and r["page"]["id"]])
1278
+ elif fq["kind"] in chat_facts.PAGE_KINDS: # the pages counted, read to be cited
1279
+ found = _page_passages(vault, [*dict.fromkeys(
1280
+ r["id"] for r in facts["rows"])][:PAGES_READ])
1281
+ model, max_tokens = runner.model, LENGTH["short"] # 1 to 3 sentences
1282
+ emit({"t": "step", "s": f"Wording the facts with {runner.model}" + (
1283
+ f" and reading {len(found)} page{'s' * (len(found) != 1)}" if found else "")})
1284
+ messages = [{"role": "system", "content": chat_facts.SYSTEM.format(
1285
+ today=f"{today:%A}, {today.isoformat()}")},
1286
+ {"role": "user", "content": chat_facts.prompt(facts, found, text, today)}]
1287
+ else:
1288
+ if front:
1289
+ emit({"t": "step", "s": front.step})
1290
+ if front.fq:
1291
+ facts = chat_facts.facts(vault, front.fq, s["sources"])
1292
+ emit({"t": "facts", "facts": facts})
1293
+ front_text = "\n".join(chat_facts._lines(facts, today))
1294
+ else:
1295
+ front_text = front.data()[:FRONT_MAX]
1296
+ # pages are dated by when they were written: a future range ("tomorrow's exam") keeps
1297
+ # no page, so it does not narrow the search; a range running past today stops at today
1298
+ past = got and got[0] <= today
1299
+ names = ", ".join([*(f.name for f in files or []), *(p["title"] for p in read)])
1300
+ emit({"t": "step", "s": "Searching " + (f"{names} and " if names else "")
1301
+ + "your notes and browsing" + (
1302
+ f" from {_span(got[0], min(got[1], today), today)}" if past else "")})
1303
+ hits = askfile.rank(files, query) if files else []
1304
+ if files and runner is None: # no local model: the file's best passages, shown as found
1305
+ found = [askfile.passage(f, n, t) for _, _, f, n, t in hits[:askfile.SHOWN]]
1306
+ else:
1307
+ found = read + [askfile.passage(f, n, t) for _, ok, f, n, t in hits
1308
+ if ok][:askfile.LEAD]
1309
+ k = s["passages"] - len(found)
1310
+ if k > 0 and (not (files or read) or semantic.load_embedder() is not None):
1311
+ left = ask.BUDGET - sum(len(p["text"]) for p in found)
1312
+ seen = {p["path"] for p in found}
1313
+ # two halves: half the passages each, merged; a half leaning on the other
1314
+ # ("... and what course does he teach?") is searched with it
1315
+ for q, g, n in searches or [(query, got, k)]:
1316
+ if searches and follow_up(q, g):
1317
+ q = f"{q}\n{next(h for h, _ in split if h != q)}"
1318
+ more = relatives(vault, q) # "my sister": her name is searched too
1319
+ also += [a for a in more if a not in also]
1320
+ pg, st = g and g[0] <= today, {}
1321
+ for p in ask._passages(vault, "\n".join([q, *more]), n,
1322
+ between=(g[0].isoformat(),
1323
+ min(g[1], today).isoformat())
1324
+ if pg else None, sources=s["sources"],
1325
+ topic=topic(said if g is got else q, g[2])
1326
+ if g else "", stats=st):
1327
+ if p["path"] in seen:
1328
+ continue
1329
+ if len(p["text"]) > left: # the file's passages took their share
1330
+ break
1331
+ seen.add(p["path"])
1332
+ left -= len(p["text"])
1333
+ found.append(p)
1334
+ if "matched" in st:
1335
+ stats["matched"] = stats.get("matched", 0) + st["matched"]
1336
+ if st.get("more"): # C14: a full search makes the whole count a floor
1337
+ stats["more"] = True
1338
+ if files:
1339
+ stats["matched"] = stats.get("matched", 0) + sum(h[1] for h in hits)
1340
+ if listed is not None or fq is not None:
1341
+ pass
1342
+ elif files and runner is None:
1343
+ said_once = askfile.cloud_set() and not all(f.told for f in files)
1344
+ for f in files if said_once else []:
1345
+ f.told = True
1346
+ head = [askfile.LOCAL_ONLY] * said_once + [askfile.NO_MODEL]
1347
+ parts.append("\n\n".join(head + ([f"**{p['title']}** [{n}]\n{_inert(p['text'])}"
1348
+ for n, p in enumerate(found, 1)]
1349
+ or [askfile.NO_MATCH])))
1350
+ emit({"t": "tok", "s": parts[0]})
1351
+ # the saved chat names the file's passages, never their text
1352
+ kept = "\n\n".join(head + (["\n".join(f"- {p['title']} [{n}]" for n, p in
1353
+ enumerate(found, 1))] if found
1354
+ else [askfile.NO_MATCH]))
1355
+ elif not found and not front_text:
1356
+ parts.append(NO_ANSWER)
1357
+ emit({"t": "tok", "s": NO_ANSWER})
1358
+ else:
1359
+ emit({"t": "step", "s": f"Reading {len(found)} page{'s' * (len(found) != 1)} with "
1360
+ f"{runner.model}"})
1361
+ me = about(vault, s["sources"], today)
1362
+ # a routed half's answer goes first, as data the model words with the passages
1363
+ head = _wrap("facts", "Facts computed by Keepfold:\n" + front_text) + "\n\n" \
1364
+ if front_text else ""
1365
+ messages = [{"role": "system",
1366
+ "content": SYSTEM.format(today=f"{today:%A}, {today.isoformat()}") + me},
1367
+ *history(msgs[:-1], s["sources"], len(me)),
1368
+ {"role": "user", "content": head + ask.prompt(found, text) + CITE}]
1369
+ if messages:
1370
+ thought = []
1371
+
1372
+ def thinking():
1373
+ if not thought and not parts:
1374
+ thought.append(1)
1375
+ emit({"t": "think"})
1376
+ for attempt in range(2): # a small model now and then says nothing: ask once more
1377
+ if attempt:
1378
+ if parts: # only whitespace or leaked tokens came
1379
+ parts.clear()
1380
+ emit({"t": "text", "s": ""})
1381
+ emit({"t": "step", "s": f"{runner.model} said nothing; asking once more"})
1382
+ try:
1383
+ for piece in runner.stream(messages, temperature=s["temperature"],
1384
+ max_tokens=max_tokens, cancel=cancel,
1385
+ on_thinking=thinking):
1386
+ parts.append(piece)
1387
+ emit({"t": "tok", "s": piece})
1388
+ if "\n" in piece and _looping("".join(parts)): # stop a loop, each line once
1389
+ parts[:] = [_once("".join(parts))]
1390
+ emit({"t": "text", "s": parts[0]})
1391
+ break
1392
+ except (OSError, ValueError): # no answer, a timeout, a refused url
1393
+ pass
1394
+ said_raw = "".join(parts)
1395
+ if (said := localllm._clean(said_raw)) != said_raw.strip(): # a leaked </think>
1396
+ parts[:] = [said]
1397
+ emit({"t": "text", "s": said})
1398
+ if said or (cancel is not None and cancel.is_set()):
1399
+ break
1400
+ answer = "".join(parts).strip()
1401
+ stopped = cancel is not None and cancel.is_set()
1402
+ # only the model's words: Keepfold's own (a digest, a site list, its fallbacks) quote titles
1403
+ by_model = bool(answer) and messages is not None
1404
+ if not answer and not stopped and facts is not None: # the model said nothing: plain words
1405
+ answer = chat_facts.say(facts, today)
1406
+ emit({"t": "tok", "s": answer})
1407
+ unanswered = not answer and not stopped and bool(found)
1408
+ if unanswered: # still nothing: the pages it searched, listed below, instead of an error
1409
+ answer = SAID_NOTHING.format(model=runner.model)
1410
+ emit({"t": "tok", "s": answer})
1411
+ if not answer and not stopped:
1412
+ emit({"t": "err", "code": "no_answer", "id": convo_id,
1413
+ "message": f"{runner.describe()} did not answer; try again."})
1414
+ return convo_id
1415
+ cited = ask.cites(answer)
1416
+
1417
+ def pill(p): # titles are untrusted page text: no links, images or markup
1418
+ return {"path": p["path"], "title": chat_study._title(p["title"]) or p["path"],
1419
+ "kind": p["kind"], "at": p.get("at", 0), "len": p.get("len", 0)}
1420
+ sources = [{"n": n, **pill(p)} for n, p in enumerate(found, 1) if n in cited]
1421
+ # a small model often cites nothing: then show what it read, marked as not cited
1422
+ searched = [] if sources else [pill(p) for p in found[:SEARCHED]]
1423
+ coverage = {"read": len(found), "matched": stats["matched"],
1424
+ **({"more": True} if stats.get("more") else {}),
1425
+ **({"also": also} if also else {})} if "matched" in stats else None
1426
+ # quote proof: a quoted span must be in a cited passage (any read one when none is cited)
1427
+ unquoted = ask.unquoted(answer, [text, *(f"{p['title']}\n{p['text']}" for n, p in
1428
+ enumerate(found, 1) if n in cited or not sources),
1429
+ *(chat_facts._lines(facts, today) if facts else []),
1430
+ front_text]
1431
+ ) if by_model else []
1432
+ sure = certainty(data=listed is not None or facts is not None,
1433
+ empty=listed.startswith(_EMPTY) if listed is not None else
1434
+ chat_facts.empty(facts) if facts is not None else not found,
1435
+ read=len(found), cited=len(sources),
1436
+ quoted=bool(ask.unquoted(answer, [])), # every quote, none to match
1437
+ unquoted=bool(unquoted), unanswered=unanswered, stopped=stopped)
1438
+
1439
+ def side(p):
1440
+ return {"path": p["path"], "title": pill(p)["title"], "day": p.get("day") or ""}
1441
+ clash = [{"old": side(a), "new": side(b)} for a, b in _conflicts(
1442
+ vault, [p for n, p in enumerate(found, 1) if n in cited or not sources])]
1443
+ hz = _horizon(days if days is not None else _horizon_days(vault, s["sources"])) \
1444
+ if searched_pages else None
1445
+ extra = {**({"certainty": sure} if sure else {}),
1446
+ **({"horizon": {"first": hz["first"], "last": hz["last"]}} if hz else {}),
1447
+ **({"conflicts": clash} if clash else {})}
1448
+ msgs.append({"role": "assistant", "text": kept or answer, "ts": _now(), "sources": sources,
1449
+ **({"searched": searched} if searched else {}),
1450
+ **({"unquoted": unquoted} if unquoted else {}),
1451
+ **({"facts": facts} if facts is not None else {}),
1452
+ **({"coverage": coverage} if coverage else {}),
1453
+ "model": model, "switches": dict(s["sources"]),
1454
+ **({"unanswered": True} if unanswered else {}),
1455
+ **({"stopped": True} if stopped else {}), **extra})
1456
+ _save(vault, convo_id, msgs, s["history"])
1457
+ emit({"t": "src", "sources": sources, "searched": searched,
1458
+ **({"unquoted": unquoted} if unquoted else {}),
1459
+ **({"coverage": coverage} if coverage else {}), **extra,
1460
+ **({"horizon": hz} if hz else {})})
1461
+ emit({"t": "done", "id": convo_id, "model": model, "stopped": stopped,
1462
+ "seconds": round(time.monotonic() - t0, 1),
1463
+ "remembers": remembers(msgs, s["sources"])})
1464
+ return convo_id