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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/browse/sites.py
ADDED
|
@@ -0,0 +1,1068 @@
|
|
|
1
|
+
"""One page per website and the browsing profile (docs/design/browse-brain.md §3a).
|
|
2
|
+
|
|
3
|
+
`record` folds a run's filtered items into per-day, per-site counts, rows of the browsing
|
|
4
|
+
store's `site_days` table (the browser forgets old history; these counts do not; the older
|
|
5
|
+
`.keepfold/browse/site-days.json` is read in once by `keepfold.browse.legacy`), keyed
|
|
6
|
+
`site|category|private-domain`, so who may see a site is decided when the pages are written,
|
|
7
|
+
from the settings of that moment. `write` makes, through `keepfold.vault` only:
|
|
8
|
+
- a visible page per site, `browse/sites/<category>/browse-<site>.md`, from the items of no
|
|
9
|
+
hidden category only; a hidden page, `<private>/sites/<category>/browse-private-<site>.md`
|
|
10
|
+
(`private: true`), from the rest. A site with both gets both pages;
|
|
11
|
+
- `browse/sites/browse-sites.md`, `browse/sites.csv` and `browse/browse-profile.md` from the
|
|
12
|
+
visible pages only, and their private twins from every page plus the hidden categories;
|
|
13
|
+
- with `browse.visible_to_claude: false` every page is a hidden one.
|
|
14
|
+
Once `keepfold.browse.store.migrate` moved the site pages out of the vault, `write` saves them as
|
|
15
|
+
rows in the browsing store instead (`store.site_rows` reads them), a live read only the rows
|
|
16
|
+
of the sites its days hold, and makes only the CSVs and the profiles (from the rows), whose
|
|
17
|
+
site lines then carry no link.
|
|
18
|
+
A visible file never holds a host, title, search term, count or link that came from a hidden
|
|
19
|
+
item: led-by searches and co-visited sites are filtered by the same rule. Ids carry the
|
|
20
|
+
`browse-` prefix (ids are unique across kinds). Unchanged pages are never rewritten (a content
|
|
21
|
+
hash in `.keepfold/browse/sites.json`, next to the local LLM's cached output).
|
|
22
|
+
`deepen` is the local LLM's long, resumable pass: per site, most visits first, a category for
|
|
23
|
+
sites the table does not know, a one-line description, related sites and topic hubs; it can
|
|
24
|
+
move a site INTO a sensitive category, never out of one.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import csv
|
|
30
|
+
import functools
|
|
31
|
+
import hashlib
|
|
32
|
+
import io
|
|
33
|
+
import json
|
|
34
|
+
import logging
|
|
35
|
+
import re
|
|
36
|
+
import time
|
|
37
|
+
from collections import Counter, defaultdict
|
|
38
|
+
from contextlib import closing
|
|
39
|
+
from dataclasses import dataclass, field
|
|
40
|
+
from datetime import UTC, date, datetime
|
|
41
|
+
from functools import cached_property
|
|
42
|
+
from urllib.parse import urlsplit
|
|
43
|
+
|
|
44
|
+
from keepfold.browse import lists, privacy
|
|
45
|
+
from keepfold.browse.privacy import Settings
|
|
46
|
+
from keepfold.events import local_day
|
|
47
|
+
from keepfold.render import esc
|
|
48
|
+
from keepfold.vault import Vault, VaultError, secret_pattern
|
|
49
|
+
|
|
50
|
+
log = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
DIR = "browse"
|
|
53
|
+
HIDDEN = DIR + "/private" # never read by the index, the dashboard or any chat
|
|
54
|
+
CACHE = ".keepfold/browse/sites.json" # the local LLM's output and the page hashes
|
|
55
|
+
# a description made with an older prompt is made again on the next deepen
|
|
56
|
+
DESC_PROMPT = 2
|
|
57
|
+
DAYS = ".keepfold/browse/site-days.json" # the counts before the store: `legacy.migrate` only
|
|
58
|
+
VERDICTS = ".keepfold/browse/verdicts.json" # the labels before the store: `legacy.migrate` only
|
|
59
|
+
SITES_DIR, HIDDEN_SITES_DIR = DIR + "/sites", HIDDEN + "/sites"
|
|
60
|
+
INDEX_ID, HIDDEN_INDEX_ID = "browse-sites", "browse-private-sites"
|
|
61
|
+
PROFILE_ID, HIDDEN_PROFILE_ID = "browse-profile", "browse-private-profile"
|
|
62
|
+
CSV_PATH, HIDDEN_CSV = DIR + "/sites.csv", HIDDEN + "/sites.csv"
|
|
63
|
+
LED_S = 10 * 60 # a search this soon before a visit to another site "led there"
|
|
64
|
+
SESSION_GAP = 30 * 60
|
|
65
|
+
CO_KEYS = 30 # site keys per session counted as visited together
|
|
66
|
+
TOP_PAGES, TOP_SEARCHES, TOP_RELATED, TOP_SITES, PER_CATEGORY = 15, 10, 8, 25, 200
|
|
67
|
+
LLM_TITLES, LLM_CANDIDATES = 20, 40
|
|
68
|
+
SAVE_EVERY = 20 # deepen saves its cache this often, so a stop loses little
|
|
69
|
+
WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
|
70
|
+
LABELS = (*lists.SITE_CATEGORIES, *lists.CATEGORIES)
|
|
71
|
+
_IP = re.compile(r"^[0-9.]+$|:")
|
|
72
|
+
# one browse-wide lock: an import, a deepen pass and a forget each load the stores and save
|
|
73
|
+
# them, so one running across another would bring back what the other took out
|
|
74
|
+
LOCK = ".keepfold/browse/lock"
|
|
75
|
+
BUSY = "Browsing is being processed; try again in a minute."
|
|
76
|
+
WAIT_S = 60.0 # an import or deepen pass waits this long for another to finish
|
|
77
|
+
VECTOR_BUDGET_S = 120.0 # a background run's private-search embedding; the next run goes on
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def busy(vault: Vault, wait: float | None = None):
|
|
81
|
+
"""The browse-wide lock (`Vault.job_lock`); VaultError("busy", BUSY) after `wait`."""
|
|
82
|
+
return vault.job_lock(LOCK, WAIT_S if wait is None else wait, BUSY)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def held(fn):
|
|
86
|
+
"""Run `fn(vault, ...)` under the browse-wide lock."""
|
|
87
|
+
@functools.wraps(fn)
|
|
88
|
+
def wrapper(vault: Vault, *a, **kw):
|
|
89
|
+
with busy(vault):
|
|
90
|
+
return fn(vault, *a, **kw)
|
|
91
|
+
return wrapper
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---- sites and ids ------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def site_of(host: str, path: str = "/") -> str:
|
|
97
|
+
"""The website a host belongs to: its registrable domain ("en.m.wikipedia.org" ->
|
|
98
|
+
wikipedia.org), a listed host as itself ("docs.google.com"), the user's own subdomain on a
|
|
99
|
+
multi-tenant host ("ana.github.io"), or "medium.com/@user"."""
|
|
100
|
+
h = host.lower().rstrip(".")
|
|
101
|
+
if _IP.search(h):
|
|
102
|
+
return h
|
|
103
|
+
for p in ("www.", "m.", "mobile."):
|
|
104
|
+
if h.startswith(p) and h.count(".") > 1:
|
|
105
|
+
h = h[len(p):]
|
|
106
|
+
if h == "medium.com":
|
|
107
|
+
seg = path.strip("/").split("/")[0].lower()
|
|
108
|
+
return f"medium.com/{seg}" if re.fullmatch(r"@[a-z0-9._-]{1,60}", seg) else h
|
|
109
|
+
for t in lists.MULTI_TENANT:
|
|
110
|
+
if h.endswith("." + t):
|
|
111
|
+
return h[: -len(t) - 1].rsplit(".", 1)[-1] + "." + t
|
|
112
|
+
if h in lists.SITE_HOSTS or h in lists.WEBMAIL_HOSTS:
|
|
113
|
+
return h
|
|
114
|
+
labels = h.split(".")
|
|
115
|
+
n = 3 if len(labels) > 2 and len(labels[-1]) == 2 and labels[-2] in lists.SECOND_LEVEL \
|
|
116
|
+
else 2
|
|
117
|
+
return ".".join(labels[-n:])
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def host_of(site: str) -> str:
|
|
121
|
+
return site.split("/", 1)[0]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def page_id(site: str, hidden: bool) -> str:
|
|
125
|
+
"""`browse-<site>` (`browse-private-<site>` for a hidden page): a valid, prefixed id."""
|
|
126
|
+
s = re.sub(r"[^a-z0-9.-]+", "-", site.lower()).strip("-.")
|
|
127
|
+
pid = ("browse-private-" if hidden else "browse-") + s
|
|
128
|
+
if len(pid) > 81:
|
|
129
|
+
pid = pid[:74].rstrip("-.") + "-" + hashlib.sha1(site.encode()).hexdigest()[:6]
|
|
130
|
+
return pid
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@functools.lru_cache(maxsize=1 << 16)
|
|
134
|
+
def _host_category(host: str) -> str | None:
|
|
135
|
+
"""`site_category` from the built-in lists alone (constants, so cached across calls: the
|
|
136
|
+
word check took ~0.4 ms a host, seconds over a heavy user's sites)."""
|
|
137
|
+
sens, _ = privacy.category(host, "/", "")
|
|
138
|
+
if sens:
|
|
139
|
+
return sens
|
|
140
|
+
labels = host.split(".")
|
|
141
|
+
for i in range(len(labels) - 1): # the most specific listed host first
|
|
142
|
+
if c := lists.SITE_HOSTS.get(".".join(labels[i:])):
|
|
143
|
+
return c
|
|
144
|
+
if labels[-1] == "edu" or "ac" in labels[-2:-1] or "edu" in labels[-2:-1]:
|
|
145
|
+
return "learning"
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def site_category(site: str, llm: dict) -> str:
|
|
150
|
+
"""A sensitive category of the host wins; then the built-in table; then the local LLM's
|
|
151
|
+
(validated) label; else "other"."""
|
|
152
|
+
if c := _host_category(host_of(site)):
|
|
153
|
+
return c
|
|
154
|
+
e = llm.get(site)
|
|
155
|
+
c = e.get("category") if isinstance(e, dict) else None
|
|
156
|
+
return c if c in LABELS else "other"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _key(site: str, cat: str | None, pd: bool) -> str:
|
|
160
|
+
return f"{site}|{cat or ''}|{int(pd)}"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _split(key: str) -> tuple[str, str, bool]:
|
|
164
|
+
site, cat, pd = key.rsplit("|", 2)
|
|
165
|
+
return site, cat, pd == "1"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# ---- state --------------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def _load(vault: Vault, rel: str) -> dict:
|
|
171
|
+
try:
|
|
172
|
+
d = json.loads((vault.root / rel).read_text(encoding="utf-8"))
|
|
173
|
+
except (OSError, ValueError):
|
|
174
|
+
return {}
|
|
175
|
+
return d if isinstance(d, dict) else {}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _save(vault: Vault, rel: str, data: dict) -> None:
|
|
179
|
+
text = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
180
|
+
p = vault.root / rel
|
|
181
|
+
if not (p.is_file() and p.read_text(encoding="utf-8") == text):
|
|
182
|
+
vault.write_text(p, text)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def load_days(vault: Vault, only_days: set[str] | None = None,
|
|
186
|
+
only_sites: set[str] | None = None) -> tuple[dict, str | None]:
|
|
187
|
+
"""The per-day counts {day: {key: counts}}: all of them, those of the days `only_days` or
|
|
188
|
+
of the sites `only_sites`, from the browsing store ({} without one); and None (a torn
|
|
189
|
+
site-days.json is set aside by `legacy.migrate` now, never here)."""
|
|
190
|
+
from keepfold.browse import store
|
|
191
|
+
|
|
192
|
+
con = _days_store(vault)
|
|
193
|
+
if con is None:
|
|
194
|
+
return {}, None
|
|
195
|
+
|
|
196
|
+
with closing(con):
|
|
197
|
+
rows = store.day_rows(con, "counts", only_days, only_sites)
|
|
198
|
+
out: dict = {}
|
|
199
|
+
for d, k, c in rows:
|
|
200
|
+
out.setdefault(d, {})[k] = json.loads(c)
|
|
201
|
+
return out, None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def stored_days(vault: Vault) -> set[str]:
|
|
205
|
+
"""Every day the site counts hold."""
|
|
206
|
+
con = _days_store(vault)
|
|
207
|
+
if con is None:
|
|
208
|
+
return set()
|
|
209
|
+
with closing(con):
|
|
210
|
+
return {d for (d,) in con.execute("SELECT DISTINCT day FROM site_days")}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def days_gen(vault: Vault) -> int:
|
|
214
|
+
"""A count that moves whenever the stored site counts change; 0 without a store."""
|
|
215
|
+
from keepfold.browse import store
|
|
216
|
+
|
|
217
|
+
con = _days_store(vault)
|
|
218
|
+
if con is None:
|
|
219
|
+
return 0
|
|
220
|
+
with closing(con):
|
|
221
|
+
return int(store.get_meta(con, "days_gen", 0) or 0)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _days_store(vault: Vault, create: bool = False):
|
|
225
|
+
"""The browsing store, or None when there is none and `create` is False."""
|
|
226
|
+
from keepfold.browse import store
|
|
227
|
+
|
|
228
|
+
return store.connect(vault) if create or store.exists(vault) else None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _key_site(key: str) -> str:
|
|
232
|
+
return key.rsplit("|", 2)[0]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _lean(a: dict) -> dict:
|
|
236
|
+
"""What `lean_days` keeps of a key's counts: its visits, visits per browser ("w") and its
|
|
237
|
+
page URLs' hosts ("h", in place of the page map "p": all `_sides` reads of it)."""
|
|
238
|
+
return {**{f: a[f] for f in ("n", "w") if f in a},
|
|
239
|
+
**({"h": sorted({url_host(u) for u in _urls(a["p"])})} if a.get("p") else {})}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _rows(days: dict) -> list:
|
|
243
|
+
"""The store rows (day, key, site, lean, counts) of `days`; a malformed day or entry is
|
|
244
|
+
left out (`record` drops it too)."""
|
|
245
|
+
def dump(x):
|
|
246
|
+
return json.dumps(x, ensure_ascii=False, separators=(",", ":"))
|
|
247
|
+
return [(d, k, _key_site(k), dump(_lean(a)), dump(a))
|
|
248
|
+
for d, keys in days.items() if isinstance(keys, dict)
|
|
249
|
+
for k, a in keys.items() if isinstance(k, str) and isinstance(a, dict)]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _put_days(vault: Vault, days: dict, checkpoint: bool = False) -> None:
|
|
253
|
+
"""Replace the stored counts of every day in `days` (an empty day's go). `checkpoint`
|
|
254
|
+
(a forget): the old rows' page images leave the WAL too."""
|
|
255
|
+
from keepfold.browse import store
|
|
256
|
+
|
|
257
|
+
con = _days_store(vault, create=True)
|
|
258
|
+
with closing(con):
|
|
259
|
+
store.put_days(con, days, _rows(days))
|
|
260
|
+
if checkpoint:
|
|
261
|
+
con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _json_days(vault: Vault) -> tuple[dict, str | None]:
|
|
265
|
+
"""site-days.json's counts, and the name an unreadable file was set aside as (R2-7): a
|
|
266
|
+
torn file is never read as empty, since it holds the days the browsers forgot. Only
|
|
267
|
+
`legacy.migrate` reads it."""
|
|
268
|
+
p = vault.root / DAYS
|
|
269
|
+
try:
|
|
270
|
+
text = p.read_text(encoding="utf-8", errors="replace")
|
|
271
|
+
except FileNotFoundError:
|
|
272
|
+
return {}, None
|
|
273
|
+
try:
|
|
274
|
+
days = json.loads(text)
|
|
275
|
+
except ValueError:
|
|
276
|
+
days = None
|
|
277
|
+
if isinstance(days, dict):
|
|
278
|
+
return days, None
|
|
279
|
+
bad = f"{p.name}.bad-{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}"
|
|
280
|
+
with vault.lock():
|
|
281
|
+
vault.write_text(p.with_name(bad), text)
|
|
282
|
+
vault.remove(p)
|
|
283
|
+
log.warning("browse: an unreadable %s was set aside as %s", p.name, bad)
|
|
284
|
+
return {}, bad
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
_LEAN: dict = {} # vault root -> (the counts' version, their lean counts)
|
|
288
|
+
_HOSTS: dict[tuple, str] = {} # a URL's text up to its third "/" -> url_host; ~one per host
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def url_host(url: str) -> str:
|
|
292
|
+
"""`(urlsplit(url).hostname or "").rstrip(".")`, memoized by the URL's text up to its third
|
|
293
|
+
"/" (scheme and authority: all the hostname depends on), as urlsplit took most of a heavy
|
|
294
|
+
user's answer."""
|
|
295
|
+
k = tuple(url.split("/", 3)[:3])
|
|
296
|
+
if (h := _HOSTS.get(k)) is None:
|
|
297
|
+
h = _HOSTS[k] = (urlsplit(url).hostname or "").rstrip(".")
|
|
298
|
+
return h
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _urls(p) -> list:
|
|
302
|
+
"""The URLs of a stored page map; anything malformed is skipped."""
|
|
303
|
+
return [u for u in p if isinstance(u, str)] if isinstance(p, dict | list) else []
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def lean_days(vault: Vault) -> dict:
|
|
307
|
+
"""{day: {key: {"n", "w", "h"}}}: `load_days` with only the visit and browser counts and
|
|
308
|
+
the page URLs' hosts ("h", in place of the page map "p": all `_sides` reads of it), read
|
|
309
|
+
once per version of the store (the store's own column: the page maps are never parsed)
|
|
310
|
+
and shared, so callers must not change it. Chat's answers read this."""
|
|
311
|
+
from keepfold.browse import store
|
|
312
|
+
|
|
313
|
+
if not store.exists(vault):
|
|
314
|
+
return {}
|
|
315
|
+
stamp = store.version(vault) # before the read: a change after it misses the cache next time
|
|
316
|
+
hit = _LEAN.get(vault.root)
|
|
317
|
+
if hit is None or hit[0] != stamp:
|
|
318
|
+
lean: dict = {}
|
|
319
|
+
with closing(store.connect(vault)) as con:
|
|
320
|
+
for d, k, a in store.day_rows(con, "lean"):
|
|
321
|
+
lean.setdefault(d, {})[k] = json.loads(a)
|
|
322
|
+
hit = _LEAN[vault.root] = (stamp, lean)
|
|
323
|
+
return hit[1]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def load_verdicts(vault: Vault) -> dict[str, str]:
|
|
327
|
+
"""{privacy.text_key(text): label}: the local model's verdicts on titles and search terms
|
|
328
|
+
(a sensitive category or "ordinary"); hashes only, never the text. From the store
|
|
329
|
+
(`keepfold.browse.store`; the older verdicts.json is read in by `legacy.migrate`)."""
|
|
330
|
+
from keepfold.browse import store
|
|
331
|
+
|
|
332
|
+
return store.verdicts(vault)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def load_cache(vault: Vault) -> dict:
|
|
336
|
+
c = _load(vault, CACHE)
|
|
337
|
+
return {"llm": c.get("llm") if isinstance(c.get("llm"), dict) else {},
|
|
338
|
+
"hashes": c.get("hashes") if isinstance(c.get("hashes"), dict) else {}}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
# ---- recording ----------------------------------------------------------------------------
|
|
342
|
+
|
|
343
|
+
def record(vault: Vault, items: list, where: dict, settings: Settings, tz, start: str,
|
|
344
|
+
held: set[str] | None, days: dict | None = None, save: bool = True) -> dict:
|
|
345
|
+
"""Replace the counts of every day from `start` on that a source still holds (`held`;
|
|
346
|
+
None: every day) with those of `items`; a day no source holds (forgotten by the browser,
|
|
347
|
+
or from Takeout only) keeps its counts, and save (`save_days`; with `save` False the
|
|
348
|
+
caller does). `days`: the counts already loaded (`load_days`; the days it may replace are
|
|
349
|
+
enough). Returns the per-day counts; a day replaced stays in them, empty when nothing is
|
|
350
|
+
left of it (so saving them drops its stored counts)."""
|
|
351
|
+
days = load_days(vault)[0] if days is None else days
|
|
352
|
+
for d in list(days):
|
|
353
|
+
if not isinstance(days[d], dict) or (d >= start and (held is None or d in held)):
|
|
354
|
+
days[d] = {}
|
|
355
|
+
last: tuple | None = None # the last search: (time, term, key)
|
|
356
|
+
sessions: dict[str, list[list[str]]] = defaultdict(list)
|
|
357
|
+
end = None
|
|
358
|
+
for it in sorted(items, key=lambda i: (i.start, i.k.url)):
|
|
359
|
+
k = it.k
|
|
360
|
+
site = site_of(k.host, urlsplit(k.url).path)
|
|
361
|
+
# a record kept local for want of a verdict (C1) stays on the hidden side, like a
|
|
362
|
+
# private domain's
|
|
363
|
+
key = _key(site, k.category, privacy.in_domains(k.host, settings.private) or k.local)
|
|
364
|
+
ts = int(it.start.timestamp())
|
|
365
|
+
a = days.setdefault(it.day, {}).setdefault(key, {"n": 0, "s": 0, "a": ts, "b": ts})
|
|
366
|
+
a["n"] += 1
|
|
367
|
+
a["a"], a["b"] = min(a["a"], ts), max(a["b"], ts)
|
|
368
|
+
if it.browser: # visits per source ("w"); a forget lowers "n" only, so "n" caps these
|
|
369
|
+
w = a.setdefault("w", {})
|
|
370
|
+
w[it.browser] = w.get(it.browser, 0) + 1
|
|
371
|
+
hr = a.setdefault("hr", {})
|
|
372
|
+
h = str(it.start.astimezone(tz).hour)
|
|
373
|
+
hr[h] = hr.get(h, 0) + 1
|
|
374
|
+
if k.search:
|
|
375
|
+
q = a.setdefault("q", {})
|
|
376
|
+
q[k.search] = q.get(k.search, 0) + 1
|
|
377
|
+
last = (it.start, k.search, key)
|
|
378
|
+
else:
|
|
379
|
+
a["s"] += round(it.secs)
|
|
380
|
+
p = a.setdefault("p", {}).setdefault(k.url, ["", 0, 0])
|
|
381
|
+
p[0], p[1], p[2] = k.title or p[0], p[1] + 1, p[2] + round(it.secs)
|
|
382
|
+
if last and _split(last[2])[0] != site and \
|
|
383
|
+
0 <= (it.start - last[0]).total_seconds() <= LED_S:
|
|
384
|
+
r = a.setdefault("r", {}).setdefault(last[2], {})
|
|
385
|
+
r[last[1]] = r.get(last[1], 0) + 1
|
|
386
|
+
last = None # one search leads to one site
|
|
387
|
+
w = where.get((k.url, k.private))
|
|
388
|
+
if w and w[0] == "hub":
|
|
389
|
+
t = a.setdefault("t", {})
|
|
390
|
+
t[w[1]] = t.get(w[1], 0) + 1
|
|
391
|
+
if end is None or (it.start - end).total_seconds() >= SESSION_GAP or \
|
|
392
|
+
not sessions[it.day]:
|
|
393
|
+
sessions[it.day].append([])
|
|
394
|
+
sessions[it.day][-1].append(key)
|
|
395
|
+
end = it.start if end is None or it.start > end else end
|
|
396
|
+
for day, ss in sessions.items():
|
|
397
|
+
for s in ss:
|
|
398
|
+
keys = [k for k, _ in Counter(s).most_common(CO_KEYS)]
|
|
399
|
+
for a in keys:
|
|
400
|
+
co = days[day][a].setdefault("co", {})
|
|
401
|
+
for b in keys:
|
|
402
|
+
if _split(b)[0] != _split(a)[0]:
|
|
403
|
+
co[b] = co.get(b, 0) + 1
|
|
404
|
+
if save:
|
|
405
|
+
save_days(vault, days, settings)
|
|
406
|
+
return days
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def save_days(vault: Vault, days: dict, settings: Settings) -> None:
|
|
410
|
+
"""Save the counts of every day in `days`, each replacing that day's stored ones (an empty
|
|
411
|
+
day's go), without any key of a category now in skip_categories."""
|
|
412
|
+
skip = set(settings.skip_categories)
|
|
413
|
+
for d in days.values():
|
|
414
|
+
for key in [k for k in d if _split(k)[1] in skip]:
|
|
415
|
+
del d[key]
|
|
416
|
+
_put_days(vault, days)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# ---- the pages ----------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
@dataclass
|
|
422
|
+
class Page:
|
|
423
|
+
site: str
|
|
424
|
+
hidden: bool
|
|
425
|
+
category: str = "other"
|
|
426
|
+
visits: int = 0
|
|
427
|
+
secs: int = 0
|
|
428
|
+
first: int = 0
|
|
429
|
+
last: int = 0
|
|
430
|
+
pages: dict = field(default_factory=dict) # url -> [title, visits, secs]
|
|
431
|
+
here: Counter = field(default_factory=Counter) # searches made on this site
|
|
432
|
+
led: Counter = field(default_factory=Counter) # searches that led here
|
|
433
|
+
hubs: Counter = field(default_factory=Counter)
|
|
434
|
+
co: Counter = field(default_factory=Counter) # other page ids visited in the same session
|
|
435
|
+
cats: Counter = field(default_factory=Counter) # item categories, by visits
|
|
436
|
+
hours: Counter = field(default_factory=Counter)
|
|
437
|
+
weekdays: Counter = field(default_factory=Counter)
|
|
438
|
+
months: Counter = field(default_factory=Counter)
|
|
439
|
+
month_secs: Counter = field(default_factory=Counter)
|
|
440
|
+
searches: list = field(default_factory=list) # [(item category, term, n)] made here
|
|
441
|
+
src: list = field(default_factory=list) # [(day, key)] its counts came from
|
|
442
|
+
|
|
443
|
+
@cached_property
|
|
444
|
+
def id(self) -> str:
|
|
445
|
+
return page_id(self.site, self.hidden)
|
|
446
|
+
|
|
447
|
+
def titles(self, n: int) -> list[str]:
|
|
448
|
+
rows = sorted(self.pages.items(), key=lambda x: (-x[1][1], -x[1][2], x[0]))
|
|
449
|
+
return list(dict.fromkeys(t for _, (t, *_) in rows if t))[:n]
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _sides(settings: Settings, llm: dict, days: dict):
|
|
453
|
+
"""(side, scat): `side(day, key)` is True when that day's counts of the key are hidden,
|
|
454
|
+
False when visible, None when not shown at all, as `settings` decide it. The domain lists
|
|
455
|
+
are checked against the site and every page URL those counts hold (R2-1): a subdomain made
|
|
456
|
+
private hides the day's whole key and a denied one drops it, since its counts (visits,
|
|
457
|
+
hours) cannot be split by URL."""
|
|
458
|
+
scats: dict[str, str] = {}
|
|
459
|
+
keys: dict[str, bool | None] = {}
|
|
460
|
+
hosts: dict[str, bool | None] = {}
|
|
461
|
+
seen: dict[tuple[str, str], bool | None] = {}
|
|
462
|
+
deep: dict[str, bool] = {}
|
|
463
|
+
|
|
464
|
+
def scat(site: str) -> str:
|
|
465
|
+
if site not in scats:
|
|
466
|
+
scats[site] = site_category(site, llm)
|
|
467
|
+
return scats[site]
|
|
468
|
+
|
|
469
|
+
def host_side(host: str) -> bool | None:
|
|
470
|
+
if host not in hosts:
|
|
471
|
+
hosts[host] = None if privacy.in_domains(host, settings.deny) or (
|
|
472
|
+
settings.allow and not privacy.in_domains(host, settings.allow)) \
|
|
473
|
+
else privacy.in_domains(host, settings.private)
|
|
474
|
+
return hosts[host]
|
|
475
|
+
|
|
476
|
+
def where(key: str) -> bool | None:
|
|
477
|
+
site, cat, pd = _split(key)
|
|
478
|
+
h = host_side(host_of(site))
|
|
479
|
+
# a Don't-save category drops the counts whether the key carries it or only the site's
|
|
480
|
+
# category says so (the local model may file a site under adult after it was stored)
|
|
481
|
+
if h is None or "skip" in (privacy.audience(cat or None, settings),
|
|
482
|
+
privacy.audience(scat(site), settings)):
|
|
483
|
+
return None
|
|
484
|
+
return (pd or h or privacy.audience(cat or None, settings) == "local"
|
|
485
|
+
or privacy.audience(scat(site), settings) != "cloud")
|
|
486
|
+
|
|
487
|
+
def side(day: str, key: str) -> bool | None:
|
|
488
|
+
if key not in keys:
|
|
489
|
+
ok = isinstance(key, str) and key.count("|") >= 2 # else a malformed key
|
|
490
|
+
keys[key] = where(key) if ok else None
|
|
491
|
+
deep[key] = ok and _deep(settings, key)
|
|
492
|
+
if not deep[key]:
|
|
493
|
+
return keys[key] # the same every day: no per-day entry to keep
|
|
494
|
+
if (day, key) not in seen:
|
|
495
|
+
h = keys[key]
|
|
496
|
+
a = (days.get(day) or {}).get(key)
|
|
497
|
+
a = a if isinstance(a, dict) else {}
|
|
498
|
+
for host in a["h"] if "h" in a else map(url_host, _urls(a.get("p"))):
|
|
499
|
+
if h is None:
|
|
500
|
+
break
|
|
501
|
+
u = host_side(host)
|
|
502
|
+
h = None if u is None else h or u
|
|
503
|
+
seen[(day, key)] = h
|
|
504
|
+
return seen[(day, key)]
|
|
505
|
+
|
|
506
|
+
return side, scat
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _deep(settings: Settings, key: str) -> bool:
|
|
510
|
+
"""Whether `_sides` reads the page URLs' hosts of site key `key`. A page URL's host is its
|
|
511
|
+
site's host or a subdomain of it (`record`), so it can only decide differently from the
|
|
512
|
+
site when a listed domain is a strict subdomain of the site; else they are left unread."""
|
|
513
|
+
host = host_of(_split(key)[0])
|
|
514
|
+
return any(d.endswith("." + host) for d in (*settings.deny, *settings.allow,
|
|
515
|
+
*settings.private))
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _shown(settings: Settings, verdicts: dict[str, str]):
|
|
519
|
+
"""`shown(text, search)`: may a visible page show this title or search term (C1)? Not when
|
|
520
|
+
the word lists (as they are now) or the local model put it in a category that is not
|
|
521
|
+
cloud; a search term only with the local model's "ordinary" verdict."""
|
|
522
|
+
seen: dict[tuple[str, bool], bool] = {}
|
|
523
|
+
|
|
524
|
+
def shown(text: str, search: bool = False) -> bool:
|
|
525
|
+
if (text, search) not in seen:
|
|
526
|
+
cat = privacy.category("", "/", text)[0]
|
|
527
|
+
v = verdicts.get(privacy.text_key(text))
|
|
528
|
+
seen[(text, search)] = ((cat is None or privacy.audience(cat, settings) == "cloud")
|
|
529
|
+
and v not in lists.CATEGORIES
|
|
530
|
+
and (not search or v == "ordinary"))
|
|
531
|
+
return seen[(text, search)]
|
|
532
|
+
return shown
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def pages(vault: Vault, settings: Settings, days: dict | None = None,
|
|
536
|
+
llm: dict | None = None, verdicts: dict | None = None
|
|
537
|
+
) -> dict[tuple[str, bool], Page]:
|
|
538
|
+
"""Every site page as the settings of now decide it: {(site, hidden): Page}. A visible
|
|
539
|
+
page holds only the titles and search terms `_shown` allows."""
|
|
540
|
+
days = load_days(vault)[0] if days is None else days
|
|
541
|
+
llm = load_cache(vault)["llm"] if llm is None else llm
|
|
542
|
+
shown = _shown(settings, load_verdicts(vault) if verdicts is None else verdicts)
|
|
543
|
+
side, scat = _sides(settings, llm, days)
|
|
544
|
+
out: dict[tuple[str, bool], Page] = {}
|
|
545
|
+
for day in sorted(days):
|
|
546
|
+
try:
|
|
547
|
+
d = date.fromisoformat(day)
|
|
548
|
+
except ValueError:
|
|
549
|
+
continue
|
|
550
|
+
for key, a in days[day].items():
|
|
551
|
+
h = side(day, key)
|
|
552
|
+
if h is None:
|
|
553
|
+
continue
|
|
554
|
+
site, cat, _ = _split(key)
|
|
555
|
+
p = out.setdefault((site, h), Page(site, h))
|
|
556
|
+
p.src.append((day, key))
|
|
557
|
+
n, s = int(a.get("n", 0)), int(a.get("s", 0))
|
|
558
|
+
p.visits += n
|
|
559
|
+
p.secs += s
|
|
560
|
+
p.first = min(p.first or a["a"], a["a"])
|
|
561
|
+
p.last = max(p.last, a["b"])
|
|
562
|
+
p.cats[cat] += n
|
|
563
|
+
p.weekdays[d.weekday()] += n
|
|
564
|
+
p.months[day[:7]] += n
|
|
565
|
+
p.month_secs[day[:7]] += s
|
|
566
|
+
for hr, c in (a.get("hr") or {}).items():
|
|
567
|
+
p.hours[int(hr)] += c
|
|
568
|
+
for url, (t, c, x) in (a.get("p") or {}).items():
|
|
569
|
+
if t and not h and not shown(t):
|
|
570
|
+
continue
|
|
571
|
+
row = p.pages.setdefault(url, ["", 0, 0])
|
|
572
|
+
row[0], row[1], row[2] = t or row[0], row[1] + c, row[2] + x
|
|
573
|
+
for t, c in (a.get("q") or {}).items():
|
|
574
|
+
if not h and not shown(t, True):
|
|
575
|
+
continue
|
|
576
|
+
p.here[t] += c
|
|
577
|
+
p.searches.append((cat, t, c))
|
|
578
|
+
for skey, terms in (a.get("r") or {}).items():
|
|
579
|
+
# a search shows where its own key may be seen: never a hidden one on a visible page
|
|
580
|
+
if (sh := side(day, skey)) is None or (sh and not h):
|
|
581
|
+
continue
|
|
582
|
+
for t, c in terms.items():
|
|
583
|
+
if h or shown(t, True):
|
|
584
|
+
p.led[t] += c
|
|
585
|
+
for hub, c in (a.get("t") or {}).items():
|
|
586
|
+
p.hubs[hub] += c
|
|
587
|
+
for other, c in (a.get("co") or {}).items():
|
|
588
|
+
if (oh := side(day, other)) is None or (oh and not h):
|
|
589
|
+
continue
|
|
590
|
+
p.co[page_id(_split(other)[0], oh)] += c
|
|
591
|
+
for p in out.values():
|
|
592
|
+
sc = scat(p.site)
|
|
593
|
+
if p.hidden and sc not in lists.CATEGORIES:
|
|
594
|
+
hidden_cats = Counter({c: n for c, n in p.cats.items() if c})
|
|
595
|
+
sc = hidden_cats.most_common(1)[0][0] if hidden_cats else sc
|
|
596
|
+
p.category = sc
|
|
597
|
+
return out
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _fm(fields: dict, body: str) -> str:
|
|
601
|
+
"""Frontmatter for flat str/int/bool fields (ruamel took 5 ms a page), then the body."""
|
|
602
|
+
def val(v):
|
|
603
|
+
if isinstance(v, bool):
|
|
604
|
+
return "true" if v else "false"
|
|
605
|
+
return str(v) if isinstance(v, int) else json.dumps(str(v), ensure_ascii=False)
|
|
606
|
+
|
|
607
|
+
return "---\n" + "".join(f"{k}: {val(v)}\n" for k, v in fields.items()) + "---\n" + body
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _dur(secs: float) -> str:
|
|
611
|
+
m = max(1, round(secs / 60))
|
|
612
|
+
h, m = divmod(m, 60)
|
|
613
|
+
return f"{m} min" if not h else f"{h} h {m} min" if m else f"{h} h"
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _day(ts: int, tz) -> str:
|
|
617
|
+
return local_day(datetime.fromtimestamp(ts, UTC), tz) # the 04:00 study day, as Item.day
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _valid_desc(entry: dict | None, p: Page) -> str | None:
|
|
621
|
+
"""The cached description, when every title it was made from is still on this page (a
|
|
622
|
+
title that has since become hidden voids it on a visible page)."""
|
|
623
|
+
if not isinstance(entry, dict) or not isinstance(entry.get("desc"), str):
|
|
624
|
+
return None
|
|
625
|
+
have = {_h(t) for t, *_ in p.pages.values() if t}
|
|
626
|
+
return entry["desc"] if set(entry.get("fed") or []) <= have else None
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _h(text: str) -> str:
|
|
630
|
+
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _page_text(p: Page, ids: dict[str, Page], llm: dict, tz) -> tuple[str, str]:
|
|
634
|
+
"""(relative path, text) of one site page."""
|
|
635
|
+
entry = (llm.get(p.site) or {}).get("h" if p.hidden else "v")
|
|
636
|
+
up = HIDDEN_INDEX_ID if p.hidden else INDEX_ID
|
|
637
|
+
fields = {"id": p.id, "title": p.site, "kind": "browse", "host": p.site,
|
|
638
|
+
"category": p.category, "visits": p.visits, "first_seen": _day(p.first, tz),
|
|
639
|
+
"last_seen": _day(p.last, tz)}
|
|
640
|
+
if p.hidden:
|
|
641
|
+
fields["private"] = True
|
|
642
|
+
out = [f"# {p.site}", "", f"Up: [[{up}]]", ""]
|
|
643
|
+
if desc := _valid_desc(entry, p):
|
|
644
|
+
out += [esc(desc, 200), ""]
|
|
645
|
+
out += [f"Category: {p.category} · {p.visits} visit{'s' if p.visits != 1 else ''} · "
|
|
646
|
+
f"{_dur(p.secs)} · first seen {fields['first_seen']} · last seen "
|
|
647
|
+
f"{fields['last_seen']}"]
|
|
648
|
+
hubs = Counter(p.hubs)
|
|
649
|
+
for hub in (entry or {}).get("topics") or []:
|
|
650
|
+
hubs.setdefault(hub, 0)
|
|
651
|
+
if hubs:
|
|
652
|
+
out += ["", "## Topics", *[f"- [[{h}]]" + (f" · {n} visits" if n else "")
|
|
653
|
+
for h, n in sorted(hubs.items(), key=lambda x: (-x[1], x[0]))]]
|
|
654
|
+
rows = sorted(p.pages.items(), key=lambda x: (-x[1][1], -x[1][2], x[0]))
|
|
655
|
+
if rows:
|
|
656
|
+
out += ["", "## Top pages"]
|
|
657
|
+
for url, (t, n, s) in rows[:TOP_PAGES]:
|
|
658
|
+
out.append(f"- {esc(t) or esc(urlsplit(url).path, 80) or '/'} · {n} visit"
|
|
659
|
+
f"{'s' if n != 1 else ''} · {_dur(s)}")
|
|
660
|
+
if len(rows) > TOP_PAGES:
|
|
661
|
+
out.append(f"- and {len(rows) - TOP_PAGES} more")
|
|
662
|
+
for head, c in (("## Searches that led here", p.led), ("## Searches on this site", p.here)):
|
|
663
|
+
if c:
|
|
664
|
+
out += ["", head, *[f"- {esc(t)} · {n}" for t, n in
|
|
665
|
+
sorted(c.items(), key=lambda x: (-x[1], x[0]))[:TOP_SEARCHES]]]
|
|
666
|
+
rel: list[str] = []
|
|
667
|
+
for s in (entry or {}).get("related") or []: # the LLM's first, then visited together
|
|
668
|
+
for pid in (page_id(s, False), page_id(s, True)):
|
|
669
|
+
if pid in ids and (p.hidden or not ids[pid].hidden) and pid not in rel:
|
|
670
|
+
rel.append(pid)
|
|
671
|
+
for pid, _ in sorted(p.co.items(), key=lambda x: (-x[1], x[0])):
|
|
672
|
+
if pid in ids and pid != p.id and (p.hidden or not ids[pid].hidden) and pid not in rel:
|
|
673
|
+
rel.append(pid)
|
|
674
|
+
rel = [r for r in rel if r != p.id][:TOP_RELATED]
|
|
675
|
+
if rel:
|
|
676
|
+
out += ["", "## Related sites", *[f"- [[{r}]]" for r in rel]]
|
|
677
|
+
root = HIDDEN_SITES_DIR if p.hidden else SITES_DIR
|
|
678
|
+
return f"{root}/{p.category}/{p.id}.md", _fm(fields, "\n".join(out) + "\n")
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _index_text(shown: list[Page], hidden_index: bool) -> str:
|
|
682
|
+
pid = HIDDEN_INDEX_ID if hidden_index else INDEX_ID
|
|
683
|
+
fields = {"id": pid, "title": "Sites (private)" if hidden_index else "Sites",
|
|
684
|
+
"kind": "browse"}
|
|
685
|
+
if hidden_index:
|
|
686
|
+
fields["private"] = True
|
|
687
|
+
up = HIDDEN_PROFILE_ID if hidden_index else PROFILE_ID
|
|
688
|
+
out = [f"# {fields['title']}", "", f"Up: [[{up}]]"]
|
|
689
|
+
by: dict[str, list[Page]] = defaultdict(list)
|
|
690
|
+
for p in shown:
|
|
691
|
+
by[p.category].append(p)
|
|
692
|
+
for cat in sorted(by, key=lambda c: (-sum(p.visits for p in by[c]), c)):
|
|
693
|
+
ps = sorted(by[cat], key=lambda p: (-p.visits, p.site))
|
|
694
|
+
out += ["", f"## {cat}", *[f"- [[{p.id}]] · {p.visits} visits · {_dur(p.secs)}"
|
|
695
|
+
+ (" · hidden" if p.hidden and hidden_index else "")
|
|
696
|
+
for p in ps[:PER_CATEGORY]]]
|
|
697
|
+
if len(ps) > PER_CATEGORY:
|
|
698
|
+
out.append(f"- and {len(ps) - PER_CATEGORY} more")
|
|
699
|
+
return _fm(fields, "\n".join(out) + "\n")
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _csv(shown: list[Page], tz, hidden_col: bool) -> str:
|
|
703
|
+
buf = io.StringIO()
|
|
704
|
+
w = csv.writer(buf, lineterminator="\n")
|
|
705
|
+
w.writerow(["site", "category", "visits", "minutes", "first_seen", "last_seen", "page",
|
|
706
|
+
*(["hidden"] if hidden_col else [])])
|
|
707
|
+
for p in sorted(shown, key=lambda p: (-p.visits, p.site, p.hidden)):
|
|
708
|
+
w.writerow([p.site, p.category, p.visits, round(p.secs / 60), _day(p.first, tz),
|
|
709
|
+
_day(p.last, tz), p.id, *([int(p.hidden)] if hidden_col else [])])
|
|
710
|
+
return buf.getvalue()
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _profile_text(shown: list[Page], hidden_profile: bool, settings: Settings,
|
|
714
|
+
linked: bool = True) -> str:
|
|
715
|
+
pid = HIDDEN_PROFILE_ID if hidden_profile else PROFILE_ID
|
|
716
|
+
fields = {"id": pid, "title": "Browsing profile" + (" (private)" if hidden_profile else ""),
|
|
717
|
+
"kind": "browse"}
|
|
718
|
+
if hidden_profile:
|
|
719
|
+
fields["private"] = True
|
|
720
|
+
hours, weekdays, months, msecs, hubs = Counter(), Counter(), Counter(), Counter(), Counter()
|
|
721
|
+
msites: dict[str, set] = defaultdict(set)
|
|
722
|
+
cats: dict[str, list] = defaultdict(lambda: [0, 0, 0])
|
|
723
|
+
for p in shown:
|
|
724
|
+
hours.update(p.hours)
|
|
725
|
+
weekdays.update(p.weekdays)
|
|
726
|
+
months.update(p.months)
|
|
727
|
+
msecs.update(p.month_secs)
|
|
728
|
+
hubs.update(p.hubs)
|
|
729
|
+
for mo in p.months:
|
|
730
|
+
msites[mo].add(p.id)
|
|
731
|
+
c = cats[p.category]
|
|
732
|
+
c[0], c[1], c[2] = c[0] + p.visits, c[1] + p.secs, c[2] + 1
|
|
733
|
+
total = sum(p.visits for p in shown)
|
|
734
|
+
out = [f"# {fields['title']}", "",
|
|
735
|
+
*([f"Up: [[{HIDDEN_INDEX_ID if hidden_profile else INDEX_ID}]]", ""] if linked
|
|
736
|
+
else []), f"{total} visits to {len(shown)} sites."]
|
|
737
|
+
out += ["", "## When I browse", "", "### By hour",
|
|
738
|
+
*[f"- {h:02d}:00 · {hours[h]} visits" for h in range(24) if hours[h]],
|
|
739
|
+
"", "### By weekday", *[f"- {WEEKDAYS[d]} · {weekdays[d]} visits"
|
|
740
|
+
for d in range(7) if weekdays[d]]]
|
|
741
|
+
out += ["", "## Top categories", *[
|
|
742
|
+
f"- {c} · {v} visits · {_dur(s)} · {n} site{'s' if n != 1 else ''}"
|
|
743
|
+
for c, (v, s, n) in sorted(cats.items(), key=lambda x: (-x[1][0], x[0]))]]
|
|
744
|
+
out += ["", "## Top sites", *[f"- {f'[[{p.id}]]' if linked else p.site} · {p.category} · "
|
|
745
|
+
f"{p.visits} visits · "
|
|
746
|
+
f"{_dur(p.secs)}" for p in
|
|
747
|
+
sorted(shown, key=lambda p: (-p.visits, p.site))[:TOP_SITES]]]
|
|
748
|
+
if hubs:
|
|
749
|
+
out += ["", "## Interests", *[f"- [[{h}]] · {n} visits"
|
|
750
|
+
for h, n in sorted(hubs.items(),
|
|
751
|
+
key=lambda x: (-x[1], x[0]))[:20]]]
|
|
752
|
+
out += ["", "## Months", *[f"- {mo} · {months[mo]} visits · {_dur(msecs[mo])} · "
|
|
753
|
+
f"{len(msites[mo])} sites" for mo in sorted(months, reverse=True)]]
|
|
754
|
+
if hidden_profile:
|
|
755
|
+
hide = [c for c in lists.CATEGORIES if c in settings.hidden_from_claude]
|
|
756
|
+
rows = []
|
|
757
|
+
for c in hide:
|
|
758
|
+
ps = [p for p in shown if p.hidden and p.category == c]
|
|
759
|
+
terms = Counter()
|
|
760
|
+
for p in shown:
|
|
761
|
+
if p.hidden:
|
|
762
|
+
for cat, t, n in p.searches:
|
|
763
|
+
if cat == c:
|
|
764
|
+
terms[t] += n
|
|
765
|
+
if not ps and not terms:
|
|
766
|
+
continue
|
|
767
|
+
rows += ["", f"### {c}", f"{sum(p.visits for p in ps)} visits · "
|
|
768
|
+
f"{_dur(sum(p.secs for p in ps))} · {len(ps)} sites", "", "Top sites:",
|
|
769
|
+
*([f"- [[{p.id}]] · {p.visits} visits · {_dur(p.secs)}" for p in
|
|
770
|
+
sorted(ps, key=lambda p: (-p.visits, p.site))[:TOP_SITES]] or ["- none"]),
|
|
771
|
+
"", "Top searches:",
|
|
772
|
+
*([f"- {esc(t)} · {n}" for t, n in
|
|
773
|
+
sorted(terms.items(), key=lambda x: (-x[1], x[0]))[:TOP_SITES]]
|
|
774
|
+
or ["- none"])]
|
|
775
|
+
if rows:
|
|
776
|
+
out += ["", "## Hidden categories", *rows]
|
|
777
|
+
return _fm(fields, "\n".join(out) + "\n")
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
_OURS = re.compile(r'\A---\nid: "?(browse-[a-z0-9.-]+)"?\n(?:[^\n]*\n)*?kind: "?browse"?\n')
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def _ours(path) -> bool:
|
|
784
|
+
"""A file this module made (R2-2): a CSV with its header row, or a `browse-*.md` whose
|
|
785
|
+
frontmatter starts with its own id and says kind browse. An owner's own note under
|
|
786
|
+
browse/sites/ is never one."""
|
|
787
|
+
try:
|
|
788
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
789
|
+
head = f.read(1000)
|
|
790
|
+
except OSError:
|
|
791
|
+
return False
|
|
792
|
+
if path.suffix == ".csv":
|
|
793
|
+
return head.startswith("site,category,visits,minutes,first_seen,last_seen,page")
|
|
794
|
+
m = _OURS.match(head)
|
|
795
|
+
return bool(m) and m.group(1) == path.stem
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def on_disk(vault: Vault) -> list:
|
|
799
|
+
"""Every file this module makes that is on disk now."""
|
|
800
|
+
out = [p for d in (SITES_DIR, HIDDEN_SITES_DIR) for p in (vault.root / d).rglob("*.md")]
|
|
801
|
+
return out + [p for rel in (CSV_PATH, HIDDEN_CSV, f"{DIR}/{PROFILE_ID}.md",
|
|
802
|
+
f"{HIDDEN}/{HIDDEN_PROFILE_ID}.md")
|
|
803
|
+
if (p := vault.root / rel).is_file()]
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
WRITE_CHUNK = 200 # about 1 s of pages per lock hold
|
|
807
|
+
PROGRESS_S = 5.0 # a longer write says how far it got (counts only)
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def write(vault: Vault, settings: Settings, tz=None, *, say=None, days: dict | None = None,
|
|
811
|
+
bad: str | None = None, only: set[str] | None = None) -> dict:
|
|
812
|
+
"""Write every site page, the indexes, CSVs and profiles that changed, and remove the ones
|
|
813
|
+
no longer made (a site that moved category or side), never a file this module did not
|
|
814
|
+
make. `bad`: the name an unreadable site-days.json was set aside as this run
|
|
815
|
+
(`load_days`); then nothing is removed. `only` (a live read: the sites of the days it
|
|
816
|
+
made again): once the site pages are store rows, only those sites' rows are made again,
|
|
817
|
+
and the CSVs and profiles are made from the rows. Counts only."""
|
|
818
|
+
from keepfold.browse import store
|
|
819
|
+
|
|
820
|
+
say = say or (lambda s: None)
|
|
821
|
+
md = not store.migrated(vault) # else the site pages are the store's rows
|
|
822
|
+
if only is not None and not md:
|
|
823
|
+
with closing(store.connect(vault)) as con:
|
|
824
|
+
only = None if store.unprofiled(con) else only # rows from before `prof`: all
|
|
825
|
+
# shortcut: the Markdown site pages (a vault not migrated) are all made every time; the
|
|
826
|
+
# app migrates first, so only an old CLI-only vault pays that
|
|
827
|
+
only = None if md else only
|
|
828
|
+
if days is None:
|
|
829
|
+
days, b = load_days(vault, only_sites=only)
|
|
830
|
+
bad = bad or b
|
|
831
|
+
cache = load_cache(vault)
|
|
832
|
+
say("sites: making the site pages")
|
|
833
|
+
allp = pages(vault, settings, days, cache["llm"])
|
|
834
|
+
files: dict[str, str] = {}
|
|
835
|
+
ids = {p.id: p for p in allp.values()}
|
|
836
|
+
for p in allp.values() if md else ():
|
|
837
|
+
rel, text = _page_text(p, ids, cache["llm"], tz)
|
|
838
|
+
files[rel] = text
|
|
839
|
+
every = list(allp.values())
|
|
840
|
+
if not md:
|
|
841
|
+
with closing(store.connect(vault)) as con:
|
|
842
|
+
if not bad: # with the counts set aside (a torn file) the rows stay as they are
|
|
843
|
+
store.put_pages(con, allp, cache["llm"], only)
|
|
844
|
+
every = store.pages_for_lists(con)
|
|
845
|
+
vis = [p for p in every if not p.hidden]
|
|
846
|
+
if vis:
|
|
847
|
+
if md:
|
|
848
|
+
files[f"{SITES_DIR}/{INDEX_ID}.md"] = _index_text(vis, False)
|
|
849
|
+
files[CSV_PATH] = _csv(vis, tz, False)
|
|
850
|
+
files[f"{DIR}/{PROFILE_ID}.md"] = _profile_text(vis, False, settings, md)
|
|
851
|
+
if every:
|
|
852
|
+
if md:
|
|
853
|
+
files[f"{HIDDEN_SITES_DIR}/{HIDDEN_INDEX_ID}.md"] = _index_text(every, True)
|
|
854
|
+
files[HIDDEN_CSV] = _csv(every, tz, True)
|
|
855
|
+
files[f"{HIDDEN}/{HIDDEN_PROFILE_ID}.md"] = _profile_text(every, True, settings, md)
|
|
856
|
+
old: dict = cache["hashes"]
|
|
857
|
+
new: dict[str, str] = {}
|
|
858
|
+
c: Counter = Counter()
|
|
859
|
+
items = sorted(files.items())
|
|
860
|
+
say(f"sites: checking {len(items)} files")
|
|
861
|
+
last = time.monotonic()
|
|
862
|
+
# a short lock per chunk, never one for the whole run (R2-3: 20k pages held it 114 s,
|
|
863
|
+
# so every other writer timed out); each file is still written atomically
|
|
864
|
+
for i in range(0, len(items), WRITE_CHUNK):
|
|
865
|
+
with vault.lock():
|
|
866
|
+
for rel, text in items[i:i + WRITE_CHUNK]:
|
|
867
|
+
h = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20]
|
|
868
|
+
path = vault.root / rel
|
|
869
|
+
if old.get(rel) == h and path.is_file():
|
|
870
|
+
new[rel] = h
|
|
871
|
+
c["same"] += 1
|
|
872
|
+
continue
|
|
873
|
+
if secret_pattern(text): # a line that looks like a secret is left out
|
|
874
|
+
text = "\n".join(ln for ln in text.split("\n") if not secret_pattern(ln))
|
|
875
|
+
try:
|
|
876
|
+
vault.write_text(path, text)
|
|
877
|
+
except VaultError as e:
|
|
878
|
+
log.warning("browse: a site page was not written: %s", e.code)
|
|
879
|
+
c["failed"] += 1
|
|
880
|
+
continue
|
|
881
|
+
new[rel] = h
|
|
882
|
+
c["written"] += 1
|
|
883
|
+
if time.monotonic() - last >= PROGRESS_S:
|
|
884
|
+
say(f"sites: {min(i + WRITE_CHUNK, len(items))} of {len(items)} files checked, "
|
|
885
|
+
f"{c['written']} written")
|
|
886
|
+
last = time.monotonic()
|
|
887
|
+
with vault.lock():
|
|
888
|
+
# reconcile with the disk, not the hashes: a page this run did not make (a site now
|
|
889
|
+
# hidden, visibility turned off, a lost cache) goes, if this module made it; with the
|
|
890
|
+
# counts set aside (a torn file), nothing goes this run
|
|
891
|
+
for p in [] if bad else on_disk(vault):
|
|
892
|
+
if p.relative_to(vault.root).as_posix() in files:
|
|
893
|
+
continue
|
|
894
|
+
if _ours(p):
|
|
895
|
+
c["removed"] += vault.remove(p)
|
|
896
|
+
else:
|
|
897
|
+
c["not_ours"] += 1
|
|
898
|
+
_save(vault, CACHE, {"llm": cache["llm"], "hashes": new})
|
|
899
|
+
r = {"sites_visible": len(vis), "sites_hidden": len(every) - len(vis),
|
|
900
|
+
"sites_written": c["written"], "sites_same": c["same"], "sites_removed": c["removed"],
|
|
901
|
+
"sites_failed": c["failed"], "sites_not_ours": c["not_ours"],
|
|
902
|
+
"sites_days_bad": int(bool(bad))}
|
|
903
|
+
if bad:
|
|
904
|
+
say(f"sites: the site counts file was unreadable and is set aside as {bad}; no site "
|
|
905
|
+
"page was removed this run")
|
|
906
|
+
say(f"sites: {r['sites_visible']} visible, {r['sites_hidden']} hidden; written "
|
|
907
|
+
f"{r['sites_written']}, unchanged {r['sites_same']}, removed {r['sites_removed']}"
|
|
908
|
+
+ (f"; {r['sites_not_ours']} files not made by Keepfold left alone"
|
|
909
|
+
if r["sites_not_ours"] else ""))
|
|
910
|
+
return r
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
# ---- the local LLM's pass -----------------------------------------------------------------
|
|
914
|
+
|
|
915
|
+
def _hubs(vault: Vault) -> dict[str, str]:
|
|
916
|
+
"""{hub title (lowercased): hub id} of the owner's topic hubs."""
|
|
917
|
+
from keepfold import topics
|
|
918
|
+
from keepfold.catalog import Catalog
|
|
919
|
+
from keepfold.index import Index
|
|
920
|
+
|
|
921
|
+
try:
|
|
922
|
+
t = topics.tree(Index(vault, Catalog.load(vault)))
|
|
923
|
+
except Exception as e: # a vault the index cannot read: no topic links, the rest goes on
|
|
924
|
+
log.warning("browse: topic hubs not read: %s", type(e).__name__)
|
|
925
|
+
return {}
|
|
926
|
+
return {str(t.title.get(h, h)).strip().lower(): h for h in t.parent if h != topics.ROOT}
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _clean(text) -> str | None:
|
|
930
|
+
if not isinstance(text, str):
|
|
931
|
+
return None
|
|
932
|
+
s = re.sub(r"https?://\S+|www\.\S+|<[^>]*>|[*_`#>\[\]|]", "", text)
|
|
933
|
+
s = " ".join(s.split())[:200].strip()
|
|
934
|
+
return s if s and not secret_pattern(s) else None
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
@held
|
|
938
|
+
def deepen(vault: Vault, runner, budget, settings: Settings, *, tz=None, say=None,
|
|
939
|
+
pick=None, fresh=None) -> dict:
|
|
940
|
+
"""For each site page, most visits first, until `budget` runs out: ask the local LLM once
|
|
941
|
+
for a category (kept only for a site the table and the sensitive rules do not place), a
|
|
942
|
+
one-line description, related sites (from the candidates it was shown) and topic hubs.
|
|
943
|
+
A visible page's call hears only that page's titles and visible candidate sites. With
|
|
944
|
+
`pick(audience)` (browse_serve.runner_for) the runner is chosen per page: a hidden page is
|
|
945
|
+
"local", a visible one "cloud" while the settings of that moment (`fresh()`, default
|
|
946
|
+
`settings`) still show all of it, else "local"; a page with no runner is left for next
|
|
947
|
+
time. A call to a runner other than `runner` (the cloud) hears only the topic hubs the
|
|
948
|
+
local index linked that site to, and only candidate sites still visible. The answers are
|
|
949
|
+
saved to `.keepfold/browse/sites.json` as they come, so a stopped pass resumes where it
|
|
950
|
+
was; then the pages are rewritten. Counts only."""
|
|
951
|
+
say = say or (lambda s: None)
|
|
952
|
+
cache = load_cache(vault)
|
|
953
|
+
llm = cache["llm"]
|
|
954
|
+
days, bad = load_days(vault)
|
|
955
|
+
allp = pages(vault, settings, days, llm)
|
|
956
|
+
hubs = _hubs(vault)
|
|
957
|
+
names = {h: t for t, h in hubs.items()}
|
|
958
|
+
now: list = [None, None, {}] # the settings last judged with, their side(), page verdicts
|
|
959
|
+
|
|
960
|
+
def shown(q: Page) -> bool:
|
|
961
|
+
"""Every count of visible page `q` is still visible under the settings of now."""
|
|
962
|
+
s = fresh() if fresh else settings
|
|
963
|
+
if s != now[0]:
|
|
964
|
+
now[:] = [s, _sides(s, llm, days)[0], {}]
|
|
965
|
+
if q.id not in now[2]:
|
|
966
|
+
now[2][q.id] = all(now[1](d, k) is False for d, k in q.src)
|
|
967
|
+
return now[2][q.id]
|
|
968
|
+
order = sorted(allp.values(), key=lambda p: (-p.visits, p.site, p.hidden))
|
|
969
|
+
todo = [p for p in order if p.titles(1) and (
|
|
970
|
+
_valid_desc(e := (llm.get(p.site) or {}).get("h" if p.hidden else "v"), p) is None
|
|
971
|
+
or e.get("pv") != DESC_PROMPT)]
|
|
972
|
+
say(f"deepen: {len(order)} site pages, {len(todo)} to describe")
|
|
973
|
+
c: Counter = Counter()
|
|
974
|
+
for n, p in enumerate(todo):
|
|
975
|
+
if budget is not None and not budget.ok():
|
|
976
|
+
c["left"] = len(todo) - n
|
|
977
|
+
break
|
|
978
|
+
# S3: who may see the page is asked again before every call, as runner_for does
|
|
979
|
+
r = pick("local" if p.hidden or not shown(p) else "cloud") if pick else runner
|
|
980
|
+
if r is None:
|
|
981
|
+
c["no_runner"] += 1
|
|
982
|
+
continue
|
|
983
|
+
c["asked"] += 1
|
|
984
|
+
cloud = r is not runner
|
|
985
|
+
titles = p.titles(LLM_TITLES)
|
|
986
|
+
pool = [q for q in order if q.site != p.site and (p.hidden or not q.hidden)]
|
|
987
|
+
near = sorted(pool, key=lambda q: (-p.co.get(q.id, 0), q.category != p.category,
|
|
988
|
+
-q.visits, q.site))
|
|
989
|
+
cands = list(dict.fromkeys(q.site for q in near if not cloud or shown(q))
|
|
990
|
+
)[:LLM_CANDIDATES]
|
|
991
|
+
# S6: the cloud hears only the hubs this site is linked to, never the owner's list
|
|
992
|
+
topics = sorted(names[h] for h in p.hubs if h in names) if cloud \
|
|
993
|
+
else sorted(hubs)[:60]
|
|
994
|
+
got = r.site(p.site, titles, list(LABELS), cands, topics, budget=budget)
|
|
995
|
+
entry = llm.setdefault(p.site, {})
|
|
996
|
+
if not isinstance(got, dict):
|
|
997
|
+
c["failed"] += 1
|
|
998
|
+
continue
|
|
999
|
+
cat = got.get("category")
|
|
1000
|
+
cat = cat.strip().lower() if isinstance(cat, str) else None
|
|
1001
|
+
# the LLM may place a site the rules do not; it never moves one out of a sensitive
|
|
1002
|
+
# category (site_category checks the host first), and only names a known category
|
|
1003
|
+
if cat in LABELS and site_category(p.site, {}) == "other":
|
|
1004
|
+
entry["category"] = cat
|
|
1005
|
+
rel = got.get("related") if isinstance(got.get("related"), list) else []
|
|
1006
|
+
# a small model pads the list: keep a site only if it shares the category or a hub
|
|
1007
|
+
like = {q.site for q in pool if q.category == p.category or set(q.hubs) & set(p.hubs)}
|
|
1008
|
+
by = {s.lower(): s for s in cands if s in like}
|
|
1009
|
+
tops = got.get("topics") if isinstance(got.get("topics"), list) else []
|
|
1010
|
+
entry["h" if p.hidden else "v"] = {
|
|
1011
|
+
"desc": _clean(got.get("description")) or "",
|
|
1012
|
+
"fed": [_h(t) for t in titles],
|
|
1013
|
+
"pv": DESC_PROMPT,
|
|
1014
|
+
"related": list(dict.fromkeys(by[x.strip().lower()] for x in rel
|
|
1015
|
+
if isinstance(x, str) and x.strip().lower() in by)
|
|
1016
|
+
)[:3],
|
|
1017
|
+
"topics": list(dict.fromkeys(hubs[x.strip().lower()] for x in tops
|
|
1018
|
+
if isinstance(x, str) and x.strip().lower() in hubs))[:3]}
|
|
1019
|
+
c["described"] += 1
|
|
1020
|
+
if c["asked"] % SAVE_EVERY == 0:
|
|
1021
|
+
_save(vault, CACHE, {"llm": llm, "hashes": cache["hashes"]})
|
|
1022
|
+
say(f"deepen: {c['asked']} of {len(todo)} asked, {c['described']} described")
|
|
1023
|
+
_save(vault, CACHE, {"llm": llm, "hashes": cache["hashes"]})
|
|
1024
|
+
say(f"deepen: {c['described']} described, {c['failed']} unanswered, "
|
|
1025
|
+
f"{c.get('left', 0)} left for next time")
|
|
1026
|
+
s = fresh() if fresh else settings
|
|
1027
|
+
# a site the model filed under a Don't-save category after it was stored leaves every
|
|
1028
|
+
# store now (the private day pages too), not at the next settings change; any such entry
|
|
1029
|
+
# counts, so a pass stopped after saving the category is caught by the next one
|
|
1030
|
+
skip = frozenset(cat for site, e in llm.items() if isinstance(e, dict) and e.get("category")
|
|
1031
|
+
and privacy.audience(cat := site_category(site, llm), s) == "skip")
|
|
1032
|
+
gone: Counter = Counter()
|
|
1033
|
+
if skip:
|
|
1034
|
+
from keepfold.browse import forget # forget imports this module
|
|
1035
|
+
|
|
1036
|
+
# the browse lock is reentrant per Vault and thread, so purge's own take passes
|
|
1037
|
+
gone = forget.purge(vault, forget.Rule(cats=skip), write=False)
|
|
1038
|
+
days, bad = load_days(vault)
|
|
1039
|
+
r = write(vault, s, tz, say=say, days=days, bad=bad)
|
|
1040
|
+
if gone:
|
|
1041
|
+
from keepfold.browse import build, forget
|
|
1042
|
+
|
|
1043
|
+
build.write_index(vault, visible=s.visible_to_claude)
|
|
1044
|
+
gone.update(forget.prune_vectors(vault))
|
|
1045
|
+
return {"asked": c["asked"], "described": c["described"], "failed": c["failed"],
|
|
1046
|
+
"left": c.get("left", 0), "no_runner": c["no_runner"], **r,
|
|
1047
|
+
**{f"purged_{k}": n for k, n in gone.items()}}
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def update_vectors(vault: Vault, say=None, background: bool = False) -> dict | None:
|
|
1051
|
+
"""The private browse vectors (keepfold.browse.vectors), brought up to date; a failure is
|
|
1052
|
+
reported by type, never raised (the pages are already written). `background` (the
|
|
1053
|
+
receiver's and the app's runs): only while the PC is idle, for at most VECTOR_BUDGET_S,
|
|
1054
|
+
stopping when the owner is back; the next run goes on."""
|
|
1055
|
+
say = say or (lambda s: None)
|
|
1056
|
+
try:
|
|
1057
|
+
from keepfold.browse import titles, vectors
|
|
1058
|
+
|
|
1059
|
+
if not background:
|
|
1060
|
+
return vectors.update(vault, progress=say)
|
|
1061
|
+
if not titles.idle():
|
|
1062
|
+
say("private search: left for when the PC is idle")
|
|
1063
|
+
return None
|
|
1064
|
+
return vectors.update(vault, progress=say, budget=VECTOR_BUDGET_S, gate=titles.idle)
|
|
1065
|
+
except Exception as e:
|
|
1066
|
+
say("private browse search not updated: "
|
|
1067
|
+
+ (str(e) if isinstance(e, VaultError) else type(e).__name__))
|
|
1068
|
+
return None
|