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
@@ -0,0 +1,326 @@
1
+ """Private browse search for local AIs (browse-brain.md, "Private search for local AIs").
2
+
3
+ Embeds every `browse/**/*.md` page, `browse/private/` included, into its own store
4
+ `.keepfold/browse/vectors-private.db` (`keepfold.vecstore`: a row per page path with its content
5
+ hash), apart from the main index's `.keepfold/vectors.db` (which never holds a private page).
6
+ Only `keepfold mcp --private` searches it, and that server refuses to start unless
7
+ `browse.private_mcp` is on. The embedder is semantic's (fastembed in ~/.keepfold/models, never
8
+ downloaded here; tests inject a fake one as `semantic._embedder`). A page is cut into
9
+ line-aligned chunks and scores by its best one; pages are re-embedded only when their content
10
+ hash changes, and removed pages drop out. An update saves every GROUP chunks, so one stopped by
11
+ its budget (the background runs) goes on where it stopped. The older
12
+ `.keepfold/browse/vectors-private.npz` is read into the store once by `keepfold.browse.legacy`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import io
19
+ import json
20
+ import logging
21
+ import re
22
+ import sqlite3
23
+ import time
24
+ from contextlib import closing
25
+
26
+ import numpy as np
27
+
28
+ from keepfold import semantic, vecstore
29
+ from keepfold.vault import Vault, VaultError, _split
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ CACHE = ".keepfold/browse/vectors-private.db"
34
+ NPZ = ".keepfold/browse/vectors-private.npz" # the cache before the store: `legacy.migrate`
35
+ CHUNK_CHARS = 1000
36
+ SNIPPET = 240
37
+ VERSION = 1 # bump when the chunking changes, so the cache is rebuilt
38
+ MAX_K = 20
39
+ BATCH = 16 # long chunks: as fast as 64 a call, and a progress line every few seconds
40
+ GROUP = 256 # chunks embedded between saves
41
+ # vault root -> (the store's stamp as last seen, {path: (hash, full, starts, vecs)}, stack)
42
+ _MEM: dict = {}
43
+
44
+
45
+ def _body(text: str) -> tuple[str, str]:
46
+ """(title, body) of a page: the `title` field, else the first `# ` heading."""
47
+ parts = _split(text)
48
+ body = parts[3] if parts else text
49
+ title = ""
50
+ if parts:
51
+ for line in parts[1].splitlines():
52
+ if line.startswith("title:"):
53
+ title = line[6:].strip().strip("'\"")
54
+ break
55
+ if not title:
56
+ title = next((ln[2:].strip() for ln in body.splitlines() if ln.startswith("# ")), "")
57
+ return title, body
58
+
59
+
60
+ def _chunks(body: str) -> list[int]:
61
+ """Start offsets of line-aligned chunks of about CHUNK_CHARS (always at least one)."""
62
+ starts, at, size = [0], 0, 0
63
+ for line in body.splitlines(keepends=True):
64
+ if size and size + len(line) > CHUNK_CHARS:
65
+ starts.append(at)
66
+ size = 0
67
+ at += len(line)
68
+ size += len(line)
69
+ return starts
70
+
71
+
72
+ def _files(vault: Vault, say=None) -> dict[str, tuple[str, str]]:
73
+ """{rel path: (sha256, text)} of every browse page."""
74
+ out, top = {}, vault.root / "browse"
75
+ last = time.monotonic()
76
+ for p in sorted(top.rglob("*.md")) if top.is_dir() else []:
77
+ if say and time.monotonic() - last >= semantic.PROGRESS_S:
78
+ say(f"private search: {len(out)} browse pages read")
79
+ last = time.monotonic()
80
+ try:
81
+ raw = p.read_bytes()
82
+ except OSError:
83
+ continue
84
+ rel = p.relative_to(vault.root).as_posix()
85
+ out[rel] = (hashlib.sha256(raw).hexdigest(), raw.decode("utf-8", errors="replace"))
86
+ return out
87
+
88
+
89
+ def signature(vault: Vault) -> str:
90
+ """A cheap fingerprint of the browse pages (path, size and mtime of each; no read, no
91
+ hash), stored with the vectors so a search re-reads the pages only when it changed
92
+ (review C12)."""
93
+ top = vault.root / "browse"
94
+ rows = []
95
+ for p in sorted(top.rglob("*.md")) if top.is_dir() else []:
96
+ try:
97
+ st = p.stat()
98
+ except OSError:
99
+ continue
100
+ rows.append((p.relative_to(vault.root).as_posix(), st.st_size, st.st_mtime_ns))
101
+ return hashlib.sha256(json.dumps(rows).encode("utf-8")).hexdigest()[:20]
102
+
103
+
104
+ def _want(dim: int) -> dict:
105
+ return {"model": semantic.MODEL, "version": VERSION, "dim": dim}
106
+
107
+
108
+ def _ours(con, dim: int | None = None) -> int | None:
109
+ """The store's dim when its rows were made by this model and chunking (and `dim`)."""
110
+ s = vecstore.get_meta(con, "settings") or {}
111
+ ok = [s.get("model"), s.get("version")] == [semantic.MODEL, VERSION]
112
+ return s.get("dim") if ok and dim in (None, s.get("dim")) else None
113
+
114
+
115
+ def _npz(vault: Vault, dim: int | None = None, rel: str = NPZ
116
+ ) -> tuple[dict, str | None, int | None]:
117
+ """The .npz cache from before the store (or its `.migrated` backup, `rel`): ({path: (hash,
118
+ starts, vecs)}, its signature, its dim), or ({}, None, None) when missing, unreadable or
119
+ built otherwise."""
120
+ try:
121
+ with np.load(vault.root / rel, allow_pickle=False) as z:
122
+ meta = json.loads(z["meta"].item())
123
+ if [meta.get("model"), meta.get("version")] != [semantic.MODEL, VERSION] or (
124
+ dim is not None and meta.get("dim") != dim):
125
+ return {}, None, None
126
+ paths, page = [str(p) for p in z["paths"]], z["page"]
127
+ start, vecs = z["start"], z["vecs"]
128
+ cut = np.searchsorted(page, np.arange(len(paths) + 1))
129
+ return ({p: (meta["hashes"][k], start[cut[k]:cut[k + 1]], vecs[cut[k]:cut[k + 1]])
130
+ for k, p in enumerate(paths)}, meta.get("sig"), meta.get("dim"))
131
+ except (OSError, ValueError, KeyError) as e:
132
+ if not isinstance(e, FileNotFoundError):
133
+ log.warning("the old private browse vectors are unreadable: %s", type(e).__name__)
134
+ return {}, None, None
135
+
136
+
137
+ def _npz_write(vault: Vault, cache: dict, dim: int, sig: str | None = None,
138
+ rel: str = NPZ) -> None:
139
+ """Rewrite the .npz at `rel` with `cache` ({path: (hash, starts, vecs)}) only."""
140
+ paths = list(cache)
141
+ rows = [cache[p] for p in paths]
142
+ buf = io.BytesIO()
143
+ np.savez(buf, paths=np.array(paths, dtype=str),
144
+ page=np.repeat(np.arange(len(paths), dtype=np.int32), [len(e[1]) for e in rows]),
145
+ start=np.concatenate([e[1] for e in rows] or [np.zeros(0, np.int32)]),
146
+ vecs=np.concatenate([e[2] for e in rows] or [np.zeros((0, dim))]).astype(np.float16),
147
+ meta=np.array(json.dumps({"model": semantic.MODEL, "version": VERSION, "dim": dim,
148
+ "hashes": [e[0] for e in rows], "sig": sig})))
149
+ with vault.lock():
150
+ vault._atomic_write(vault.root / rel, buf.getvalue())
151
+
152
+
153
+ def _connect(vault: Vault, dim: int):
154
+ """The store for `dim` (other settings empty it and its signature)."""
155
+ con = vecstore.connect(vault.root / CACHE, vault=vault)
156
+ try:
157
+ if vecstore.prepare(con, _want(dim)):
158
+ with vecstore.tx(con):
159
+ vecstore.set_meta(con, "sig", None)
160
+ except BaseException:
161
+ con.close()
162
+ raise
163
+ return con
164
+
165
+
166
+ def _load(vault: Vault, dim: int | None = None) -> tuple[dict, tuple | None]:
167
+ """({path: (hash, full, starts, vecs)}, stacked rows) as stored; this process keeps them
168
+ and reads only what other processes saved since. ({}, None) when there is no store or it
169
+ was built otherwise."""
170
+ root, p = vault.root, vault.root / CACHE
171
+ if not p.is_file():
172
+ _MEM.pop(root, None)
173
+ return {}, None
174
+ st, cache, stack = _MEM.get(root, (None, {}, None))
175
+ cache = dict(cache)
176
+ try:
177
+ with closing(vecstore.connect(p, create=False)) as con:
178
+ if (d := _ours(con, dim)) is None:
179
+ return {}, None
180
+ st, moved = vecstore.sync(con, d, st, cache, str)
181
+ except sqlite3.DatabaseError as e:
182
+ log.warning("private browse vectors not read: %s", type(e).__name__)
183
+ return {}, None
184
+ if moved or stack is None:
185
+ stack = vecstore.stack(cache, d)
186
+ _MEM[root] = (st, cache, stack)
187
+ return cache, stack
188
+
189
+
190
+ def _stored_signature(vault: Vault) -> str | None:
191
+ if not (vault.root / CACHE).is_file():
192
+ return None
193
+ try:
194
+ with closing(vecstore.connect(vault.root / CACHE, create=False)) as con:
195
+ return vecstore.get_meta(con, "sig") if _ours(con) else None
196
+ except sqlite3.DatabaseError:
197
+ return None
198
+
199
+
200
+ def _read(vault: Vault, dim: int | None = None) -> dict:
201
+ """{rel path: (hash, starts, unit vectors)}, or {} when missing or built otherwise."""
202
+ return {p: (e[0], e[2], e[3]) for p, e in _load(vault, dim)[0].items()}
203
+
204
+
205
+ def update(vault: Vault, progress=None, budget: float | None = None, gate=None) -> dict:
206
+ """Bring the private browse vectors up to date. Returns counts only: {pages, embedded,
207
+ removed, chunks}, and `left` (pages still to embed) when `budget` (seconds) ran out or
208
+ `gate()` turned False; what was embedded is saved, so the next run goes on.
209
+ `progress(str)` gets counts-only lines. Raises VaultError `not_set_up` when the embedding
210
+ model is not downloaded."""
211
+ embed = semantic.load_embedder()
212
+ if embed is None:
213
+ raise VaultError("not_set_up", semantic.NOT_SET_UP)
214
+ say = progress or (lambda s: None)
215
+ say("private search: reading the browse pages")
216
+ dim = semantic._embed(embed, ["keepfold"]).shape[1] # a cache from another embedder is redone
217
+ sig = signature(vault) # before reading: a page changed meanwhile is read again next time
218
+ files = _files(vault, say)
219
+ with closing(_connect(vault, dim)) as con:
220
+ old = vecstore.manifests(con)
221
+ gone = [p for p in old if p not in files]
222
+ todo = [p for p in files if old.get(p) != files[p][0]]
223
+ vecstore.delete(con, gone)
224
+ plan = [] # (path, chunk starts, chunk texts): embedded in groups across pages
225
+ for p in todo:
226
+ title, body = _body(files[p][1])
227
+ starts = _chunks(body)
228
+ ends = [*starts[1:], len(body)]
229
+ plan.append((p, starts, [f"{title}\n{body[s:e]}"
230
+ for s, e in zip(starts, ends, strict=True)]))
231
+ total = sum(len(ts) for _, _, ts in plan)
232
+ say(f"{len(files)} browse pages; {len(todo)} to embed ({total} chunks), "
233
+ f"{len(gone)} removed")
234
+ t0 = last = time.monotonic()
235
+ done = pages = 0
236
+ while pages < len(plan):
237
+ if pages and ((budget is not None and time.monotonic() - t0 >= budget)
238
+ or (gate is not None and not gate())):
239
+ break
240
+ group, n = [], 0
241
+ while pages + len(group) < len(plan) and (not group or n < GROUP):
242
+ group.append(plan[pages + len(group)])
243
+ n += len(group[-1][2])
244
+ vecs = semantic.embed_all(embed, [t for _, _, ts in group for t in ts], BATCH)
245
+ at, items = 0, {}
246
+ for p, starts, ts in group: # every page has at least one chunk
247
+ items[p] = (files[p][0], True, np.array(starts, np.int32), vecs[at:at + len(ts)])
248
+ at += len(ts)
249
+ vecstore.put(con, items)
250
+ pages, done = pages + len(group), done + n
251
+ if time.monotonic() - last >= semantic.PROGRESS_S:
252
+ say(f"embedded {done} of {total} chunks")
253
+ last = time.monotonic()
254
+ left = len(plan) - pages
255
+ if not left and vecstore.get_meta(con, "sig") != sig:
256
+ with vecstore.tx(con):
257
+ vecstore.set_meta(con, "sig", sig)
258
+ chunks = con.execute("SELECT COALESCE(SUM(n), 0) FROM vecs").fetchone()[0]
259
+ out = {"pages": len(files), "embedded": pages, "removed": len(gone), "chunks": chunks,
260
+ **({"left": left} if left else {})}
261
+ say(f"done: {out['pages']} pages, {out['chunks']} chunks"
262
+ + (f", {left} pages left for the next run" if left else ""))
263
+ return out
264
+
265
+
266
+ def prune(vault: Vault) -> int:
267
+ """Drop the rows of pages that went or changed, with no model needed (a forget or a
268
+ settings change must not leave a page's vectors and path behind); the .npz backup
269
+ `legacy.migrate` left loses them too. Rows dropped from the store."""
270
+ from keepfold.browse import legacy
271
+
272
+ root, n, files, kept = vault.root, 0, None, NPZ + legacy.DONE
273
+ if (root / CACHE).is_file():
274
+ with closing(vecstore.connect(root / CACHE, vault=vault)) as con:
275
+ if have := vecstore.manifests(con):
276
+ files = _files(vault)
277
+ n = vecstore.delete(con, [p for p, h in have.items()
278
+ if p not in files or files[p][0] != h])
279
+ old, sig, dim = _npz(vault, rel=kept)
280
+ if old:
281
+ files = _files(vault) if files is None else files
282
+ keep = {p: e for p, e in old.items() if p in files and files[p][0] == e[0]}
283
+ if len(keep) < len(old):
284
+ _npz_write(vault, keep, dim, sig, kept)
285
+ return n
286
+
287
+
288
+ def search(vault: Vault, query: str, k: int = 8) -> list[dict]:
289
+ """Top `k` browse pages for `query`: [{path, title, score, snippet, text}], best first;
290
+ `text` is the best chunk (CHUNK_CHARS). Updates the vectors first when the pages'
291
+ signature changed. Title, snippet and text are untrusted page text: wrap them before a
292
+ model reads them."""
293
+ if not isinstance(query, str) or not query.strip():
294
+ return []
295
+ if _stored_signature(vault) != signature(vault):
296
+ update(vault)
297
+ cache, stack = _load(vault)
298
+ if not cache:
299
+ return []
300
+ embed = semantic.load_embedder()
301
+ if embed is None:
302
+ raise VaultError("not_set_up", semantic.NOT_SET_UP)
303
+ q = semantic._embed(embed, [semantic.QUERY_PREFIX + query.strip()])[0]
304
+ ids, page, start, m = stack
305
+ best, where = semantic.best_chunks(page, start, m @ q, len(ids))
306
+ words = [t for t in re.findall(r"\w+", query.lower()) if len(t) > 2
307
+ and t not in semantic.STOPWORDS]
308
+ out = []
309
+ for j in np.argsort(-best, kind="stable")[:max(1, min(int(k), MAX_K))]:
310
+ score, p, at = float(best[j]), ids[j], int(where[j])
311
+ if score <= 0:
312
+ break
313
+ try:
314
+ title, body = _body((vault.root / p).read_bytes().decode("utf-8", errors="replace"))
315
+ except OSError:
316
+ continue
317
+ # from the chunk's first line holding a query word (semantic.passage), else its start
318
+ low = body.lower()
319
+ hit = min((i for w in words if (i := low.find(w, at, at + CHUNK_CHARS)) >= 0), default=at)
320
+ s = max(body.rfind("\n", at, hit) + 1, at)
321
+ snippet = " ".join(body[s:s + SNIPPET * 2].split())[:SNIPPET]
322
+ text = body[at:at + CHUNK_CHARS]
323
+ out.append({"path": p, "title": title or p.rsplit("/", 1)[-1][:-3],
324
+ "score": round(score, 3), "snippet": snippet, "text": text.strip(),
325
+ "at": at + len(text) - len(text.lstrip())}) # where `text` starts in body
326
+ return out
@@ -0,0 +1,332 @@
1
+ """The browse receiver: `keepfold browse serve` (and `keepfold-receiver.exe`, which Start at login
2
+ runs) imports new browser history in the background. It opens no window and no network port.
3
+
4
+ From AUTO_FIRST_S after start, then every AUTO_EVERY_S, it checks whether the last import is older
5
+ than `browse.auto_import_hours`; when it is, it imports the new visits of the browsers and profiles
6
+ the user imported before (`run_import`). Once per start, from DEEPEN_IDLE_S after start, the
7
+ local model's deepen pass runs when that model is already loaded and the PC is idle (it never
8
+ loads one); until then it asks again every AUTO_EVERY_S. Nothing that holds a URL or a title is
9
+ ever logged.
10
+
11
+ It was also the capture extension's endpoint on 127.0.0.1:8799 until 0.3.2, which removed the
12
+ extension. The inbox files the extension wrote still import (keepfold.browse.build), but no new
13
+ ones arrive.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import threading
19
+ import time
20
+ from datetime import UTC, datetime, timedelta
21
+ from functools import partial
22
+ from pathlib import Path
23
+
24
+ from keepfold.browse import Settings, load_settings
25
+ from keepfold.vault import Vault, VaultError
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ DEEPEN_IDLE_S = 30 * 60 # the local LLM's deepen pass runs once, from this long after start
30
+ AUTO_IMPORT_HOURS = 6 # browse.auto_import_hours default; 0 turns the automatic import off
31
+ AUTO_FIRST_S = 60 # the first automatic-import check after a start
32
+ AUTO_EVERY_S = 10 * 60 # then this often
33
+
34
+
35
+ def _vault(vault) -> Vault:
36
+ return vault if isinstance(vault, Vault) else Vault(Path(vault))
37
+
38
+
39
+ # ---- the import and the deepen pass ------------------------------------------------------------
40
+
41
+
42
+ def local_runner(budget_s: float | None = None):
43
+ """(runner, budget) when config enables the local LLM and one answers, else (None, None).
44
+ The budget is `budget_s`, else `localllm.budget_s` (default 300)."""
45
+ from keepfold import localllm
46
+
47
+ if not localllm.enabled():
48
+ return None, None
49
+ try:
50
+ runner = localllm.find(background=True)
51
+ except ValueError: # a non-loopback localllm.url is refused
52
+ return None, None
53
+ if runner is None:
54
+ return None, None
55
+ return runner, _budget(budget_s)
56
+
57
+
58
+ def idle_runner(budget_s: float | None = None):
59
+ """(runner, budget) for the imports' title checks: the configured local model only when
60
+ it is already loaded and the PC is idle (`titles.may_run`: it never starts a runner or
61
+ loads a model), else (None, None)."""
62
+ from keepfold.browse import titles
63
+
64
+ runner, _ = titles.may_run()
65
+ return (runner, _budget(budget_s)) if runner is not None else (None, None)
66
+
67
+
68
+ def check_titles(v: Vault, runner, settings: Settings, budget) -> dict:
69
+ """C1's background pass: up to titles.CAP titles and search terms with no verdict yet,
70
+ newest visit first (`store.pending`), to the loaded local model in batches with a pause
71
+ between them, while the PC stays idle. Each batch's labels are saved as it comes (their
72
+ days are made again by the import that follows); a Don't-save verdict takes what it
73
+ matches out of every store. Counts only."""
74
+ from contextlib import closing
75
+
76
+ from keepfold.browse import build, forget, privacy, sites, store, titles
77
+
78
+ if not store.exists(v):
79
+ return {}
80
+ with closing(store.connect(v)) as con:
81
+ texts = store.pending(con, settings, sites.load_verdicts(v), titles.CAP)
82
+ got, c = titles.check(texts, runner, list(build.VET_LABELS), budget,
83
+ save=lambda lab: store.put_verdicts(con, lab), gate=titles.idle,
84
+ pause=titles.PAUSE_S)
85
+ skip = frozenset(x for x in got.values() if privacy.audience(x, settings) == "skip")
86
+ if skip:
87
+ forget.purge(v, forget.Rule(cats=skip), write=False)
88
+ return {"titles_checked": c["answered"], "titles_calls": c["calls"]}
89
+
90
+
91
+ def _budget(budget_s: float | None):
92
+ from keepfold import localllm, taint
93
+
94
+ if budget_s is None:
95
+ cfg = taint.config().get("localllm")
96
+ budget_s = cfg.get("budget_s", 300) if isinstance(cfg, dict) else 300
97
+ return localllm.Budget(budget_s if isinstance(budget_s, (int, float)) else 300)
98
+
99
+
100
+ def runner_for(audience: str, local, cloud, settings: Settings | None = None):
101
+ """The only place a runner is picked for browse work (docs/design/data-access.md §2): the
102
+ cloud runner for a "cloud" item with browse.cloud_processing on; else the local runner.
103
+ "local" never gets the cloud runner, even with no local one (no fallback); "skip" gets
104
+ none. `settings` default to a fresh read, so turning cloud processing off stops the next
105
+ call (the kill switch)."""
106
+ if audience == "skip":
107
+ return None
108
+ settings = load_settings() if settings is None else settings
109
+ if audience == "cloud" and cloud is not None and settings.cloud_processing:
110
+ return cloud
111
+ return local
112
+
113
+
114
+ def auto_sources(v: Vault) -> list:
115
+ """The automatic import's browsers and profiles: those `sources.chosen` finds now that the
116
+ user imported before (keys in the browse state), never one they never ticked."""
117
+ from keepfold.browse import build, sources
118
+
119
+ try: # a profile folder the OS refuses (PermissionError) must not stop the receiver
120
+ done = build.load_state(v).get("sources") or {}
121
+ return [s for s in sources.chosen(load_settings()) if s.key in done]
122
+ except OSError as e:
123
+ log.warning("browse: browsers not listed (%s)", type(e).__name__)
124
+ return []
125
+
126
+
127
+ def run_import(v: Vault, progress=None, say=None, srcs: list | None = None) -> dict:
128
+ """The background import (the receiver's runs, the app's live import every
129
+ AUTO_EVERY_S), with every browser found (or `srcs`) and no `since`: the import itself
130
+ reads only what is new and makes the days it changed. The local model only when it is
131
+ already loaded and the PC idle (`idle_runner`): then first the titles waiting for its
132
+ verdict (`check_titles`); never a download or a model load. It rests build.PAUSE_S after
133
+ each chunk, so the machine stays quick. Then the private browse vectors, while the PC is
134
+ idle. Its embedding is background work (`semantic.background`)."""
135
+ from keepfold import semantic
136
+ from keepfold.browse import build, sites, sources
137
+
138
+ say = say or _say
139
+ runner, budget = idle_runner()
140
+ settings = load_settings()
141
+ srcs = sources.chosen(settings) if srcs is None else srcs
142
+ checked = (check_titles(v, runner, settings, budget)
143
+ if runner is not None and settings.visible_to_claude else {})
144
+ go = partial(build.run, v, srcs, settings, runner=runner, budget=budget,
145
+ progress=progress, say=say, pause=build.PAUSE_S)
146
+ with semantic.background():
147
+ try:
148
+ r = go(embed=semantic.load_embedder())
149
+ except semantic.NotLoaded: # the files do not load: as with no model (its days stay
150
+ r = go(embed=None) # dirty until their pages are saved, so this run makes them)
151
+ r.update(checked)
152
+ r["model"] = runner is not None
153
+ sites.update_vectors(v, say, background=True)
154
+ return r
155
+
156
+
157
+ def run_deepen(v: Vault, say=None, budget_s: float | None = None,
158
+ background: bool = False) -> dict | None:
159
+ """The local LLM's pass over the site pages (keepfold.browse.sites.deepen), each page's runner
160
+ picked by `runner_for` (visible pages may go to the cloud runner when cloud processing is
161
+ on), then the private browse vectors while the PC is idle (background work); None when
162
+ neither runner is available. The cloud runner's run leaves one counts-only audit line.
163
+ `background` (the receiver): the local model only when it is already loaded and the PC is
164
+ idle (`idle_runner`); while a local model is set up but not ready, None, so it waits. The
165
+ manual command may start the runner and load the model (`local_runner`)."""
166
+ from keepfold import cloudllm, localllm, semantic
167
+ from keepfold.browse import sites
168
+
169
+ say = say or _say
170
+ if background:
171
+ local, budget = idle_runner(budget_s)
172
+ if local is None and localllm.enabled():
173
+ return None # not loaded or not idle: a cloud-only run now would leave the hidden pages
174
+ else:
175
+ local, budget = local_runner(budget_s)
176
+ cloud = cloudllm.find() if load_settings().cloud_processing else None
177
+ if local is None and cloud is None:
178
+ return None
179
+ try:
180
+ r = sites.deepen(v, local, budget or _budget(budget_s), load_settings(), say=say,
181
+ pick=lambda audience: runner_for(audience, local, cloud),
182
+ fresh=lambda: load_settings())
183
+ finally:
184
+ if cloud is not None:
185
+ cloudllm.audit(v, cloud)
186
+ with semantic.background():
187
+ sites.update_vectors(v, say, background=True)
188
+ return r
189
+
190
+
191
+ def auto_import_hours(config: dict | None = None) -> float:
192
+ """`browse.auto_import_hours` (0-168; 0 = off); a missing or bad value is the default."""
193
+ if config is None:
194
+ from keepfold.taint import config as read
195
+ config = read()
196
+ b = config.get("browse") if isinstance(config, dict) else None
197
+ h = b.get("auto_import_hours", AUTO_IMPORT_HOURS) if isinstance(b, dict) else None
198
+ ok = isinstance(h, (int, float)) and not isinstance(h, bool) and 0 <= h <= 168
199
+ return h if ok else AUTO_IMPORT_HOURS
200
+
201
+
202
+ def auto_import_due(v: Vault, now: datetime | None = None, *, live: bool = False) -> bool:
203
+ """True when the last import is older than `auto_import_hours` and the browse-wide lock is
204
+ free (no import, deepen or forget runs). Never before the user's first import: a fresh
205
+ install reads no history until they ask once. `live` (the app's live import, every
206
+ AUTO_EVERY_S): any age; auto_import_hours 0 still turns it off."""
207
+ from keepfold import taint
208
+ from keepfold.browse import build, sites
209
+
210
+ cfg, err = taint._read()
211
+ hours = auto_import_hours(cfg)
212
+ last = build.load_state(v).get("last_run")
213
+ if not hours or not isinstance(last, str):
214
+ return False
215
+ if err: # fail closed: the file may hold the deny list and the skipped profiles
216
+ log.warning("browse: automatic import skipped: %s", err)
217
+ return False
218
+ try:
219
+ t = datetime.strptime(last, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
220
+ except ValueError:
221
+ return False
222
+ if not live and (now or datetime.now(UTC)) - t < timedelta(hours=hours):
223
+ return False
224
+ try:
225
+ with sites.busy(v, 0): # a peek: the import takes it again for its whole run
226
+ return True
227
+ except (VaultError, OSError):
228
+ return False
229
+
230
+
231
+ def _say(text: str) -> None:
232
+ """One line on the receiver's terminal: counts and states only, never a URL or title."""
233
+ print(f"{time.strftime('%H:%M:%S')} {text}", flush=True)
234
+
235
+
236
+ def summary(r: dict, took: float) -> str:
237
+ """The counts-only line for a finished run (the receiver's terminal or log)."""
238
+ if "days_from" not in r:
239
+ return f"done in {took:.0f} s: nothing new since the last run"
240
+ return (f"done in {took:.0f} s: {r.get('private_written', 0)} private day pages written "
241
+ f"(kept {r.get('kept', 0)} visits, private {r.get('private', 0)}, dropped "
242
+ f"{r.get('dropped', 0)}); local model {'used' if r.get('model') else 'not used'}")
243
+
244
+
245
+ class Processor:
246
+ """Runs `run_import` on the sources imported before (`auto_sources`) when the last import is
247
+ older than browse.auto_import_hours (checked AUTO_FIRST_S after start, then every
248
+ AUTO_EVERY_S), and the local LLM's deepen pass once, from DEEPEN_IDLE_S after start, when
249
+ the model is loaded and the PC idle (else asked again every AUTO_EVERY_S); `tick` is the
250
+ only runner and never overlaps itself. `clock` (monotonic) and `now` (wall time, for the last
251
+ import's age) are injectable for tests."""
252
+
253
+ def __init__(self, v: Vault, clock=time.monotonic, say=_say, now=None):
254
+ self.v, self.clock, self.say = v, clock, say
255
+ self.now = now or (lambda: datetime.now(UTC))
256
+ self._auto_at = clock() + AUTO_FIRST_S
257
+ self._deepen_at = clock() + DEEPEN_IDLE_S
258
+ self.processing = False
259
+ self.last: str = "" # the last run's counts-only summary
260
+ self._lock = threading.Lock()
261
+ self._deepened = False # once per start
262
+
263
+ def tick(self) -> bool:
264
+ """Run the import if it is due and none is running, else the local LLM's deepen pass
265
+ once, from DEEPEN_IDLE_S after start; True if either ran."""
266
+ with self._lock:
267
+ now = self.clock()
268
+ picked = None
269
+ if not self.processing and now >= self._auto_at:
270
+ self._auto_at = now + AUTO_EVERY_S
271
+ if auto_import_due(self.v, self.now()):
272
+ picked = auto_sources(self.v)
273
+ deep = not picked and not self._deepened and now >= self._deepen_at
274
+ if self.processing or not (picked or deep):
275
+ return False
276
+ self.processing = True
277
+ if deep: # spent only when it ran (`_deepen`); else asked again after this long
278
+ self._deepen_at = now + AUTO_EVERY_S
279
+ if deep:
280
+ return self._deepen()
281
+ self.say(f"last import over {auto_import_hours():g} hours ago: importing new history")
282
+ self.say("processing your browsing (the first run reads your whole history and can "
283
+ "take several minutes)…")
284
+ t0 = time.perf_counter()
285
+
286
+ def progress(key, n, new, err):
287
+ self.say(f" {key}: not read ({type(err).__name__}); the others go on" if err
288
+ else f" {key}: {n} visits read, {new} new")
289
+
290
+ try:
291
+ # nothing here is a click: only the browsers and profiles imported before are read
292
+ self.last = summary(run_import(self.v, progress=progress, srcs=picked),
293
+ time.perf_counter() - t0)
294
+ except Exception as e: # logged by type only: a message may hold a URL or title
295
+ self.last = f"failed: {type(e).__name__}"
296
+ log.warning("browse: processing failed: %s", type(e).__name__)
297
+ finally:
298
+ with self._lock:
299
+ self.processing = False
300
+ self.say(self.last)
301
+ return True
302
+
303
+ def _deepen(self) -> bool:
304
+ """The deepen pass with the loaded model on an idle PC only (never a model load); False
305
+ when it could not run yet, so `tick` tries again AUTO_EVERY_S later."""
306
+ r = None
307
+ try:
308
+ r = run_deepen(self.v, say=self.say, background=True)
309
+ if r is not None:
310
+ self.say(f"deepen done: {r.get('described', 0)} sites described, "
311
+ f"{r.get('left', 0)} left")
312
+ except Exception as e: # by type only, like the import
313
+ log.warning("browse: deepen failed: %s", type(e).__name__)
314
+ self.say(f"deepen failed: {type(e).__name__}")
315
+ r = {}
316
+ finally:
317
+ with self._lock:
318
+ self.processing = False
319
+ self._deepened = r is not None # once per start, counted only when it ran
320
+ return r is not None
321
+
322
+ def loop(self, stop: threading.Event, every: float = 1.0) -> None:
323
+ while not stop.wait(every):
324
+ try:
325
+ self.tick()
326
+ except Exception as e: # noqa: BLE001 one bad tick never ends the receiver's runs
327
+ log.warning("browse: background check failed: %s", type(e).__name__)
328
+
329
+
330
+ def serve(vault, *, stop: threading.Event | None = None) -> None:
331
+ """Run the background import until `stop` is set (or Ctrl+C)."""
332
+ Processor(_vault(vault)).loop(stop or threading.Event())