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/build.py
ADDED
|
@@ -0,0 +1,1320 @@
|
|
|
1
|
+
"""`keepfold browse import` and `status` (docs/design/browse-brain.md §3, §4).
|
|
2
|
+
|
|
3
|
+
Visits from the browsers (and the `.keepfold/browse/inbox-*.jsonl` files the capture extension
|
|
4
|
+
wrote before 0.3.2 removed it; no new ones arrive) pass the §2 filter first; only derived pages
|
|
5
|
+
are written, through `keepfold.vault`:
|
|
6
|
+
- `browse/browse-YYYY-MM-DD.md` (kind browse) per day, rebuilt whole from that day's visits:
|
|
7
|
+
no third-party text at all (second privacy review), only the owner's topic hubs as links
|
|
8
|
+
with time and counts, from items with no sensitive category that sit under a hub, and the
|
|
9
|
+
number of other pages;
|
|
10
|
+
- `browse/private/browse-private-YYYY-MM-DD.md` (`private: true`) with every kept item of the
|
|
11
|
+
day (titles by topic, searches, videos, sites); it sits in a subfolder, so the index,
|
|
12
|
+
dashboard and chats never even list it; only the LOCAL LLM (localllm.enabled) hears its
|
|
13
|
+
page titles, for its "What I was into" line and a line per browsing session;
|
|
14
|
+
- `browse/browse-index.md`: months and days, and the hubs by time; the sites returned to most
|
|
15
|
+
go to `browse/private/browse-private-index.md`;
|
|
16
|
+
- per topic hub and week with >= 30 min or >= 3 days: a journal line and a `touch` event.
|
|
17
|
+
The public day pages, the public index, journal lines and touches are written only with
|
|
18
|
+
`browse.visible_to_claude: true`. By default (false) only the private pages are written (the
|
|
19
|
+
hub lines move to their top) and a rebuild removes the public pages of the days it rebuilds.
|
|
20
|
+
The extension's inbox files a run consumed are deleted afterwards. Every run then rewrites the
|
|
21
|
+
site pages and the profile (`keepfold.browse.sites`); when the visibility settings changed since
|
|
22
|
+
the last run (`fingerprint`), every day still held is rebuilt and the public day pages that
|
|
23
|
+
cannot be are removed.
|
|
24
|
+
Ids carry a `browse-` prefix: a bare `YYYY-MM-DD` is the journal page's id, and ids are unique
|
|
25
|
+
across kinds. The state file `.keepfold/browse/state.json` holds timestamps, sizes and mtimes.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import hashlib
|
|
31
|
+
import json
|
|
32
|
+
import logging
|
|
33
|
+
import re
|
|
34
|
+
import time
|
|
35
|
+
from collections import Counter, defaultdict
|
|
36
|
+
from contextlib import ExitStack, closing
|
|
37
|
+
from dataclasses import dataclass, replace
|
|
38
|
+
from datetime import UTC, date, datetime, timedelta, tzinfo
|
|
39
|
+
|
|
40
|
+
import numpy as np
|
|
41
|
+
|
|
42
|
+
from keepfold import topics
|
|
43
|
+
from keepfold.browse import forget, lists, privacy, sites, sources
|
|
44
|
+
from keepfold.browse.legacy import migrate as migrate_legacy
|
|
45
|
+
from keepfold.browse.privacy import Kept, Settings
|
|
46
|
+
from keepfold.events import EventLog, live, local_day, void_event
|
|
47
|
+
from keepfold.render import esc, plain
|
|
48
|
+
from keepfold.vault import (
|
|
49
|
+
PRIVATE_BROWSE_DIR,
|
|
50
|
+
Vault,
|
|
51
|
+
VaultError,
|
|
52
|
+
_dump_fm,
|
|
53
|
+
_to_yaml,
|
|
54
|
+
secret_pattern,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
log = logging.getLogger(__name__)
|
|
58
|
+
|
|
59
|
+
DIR, PRIVATE_DIR = "browse", PRIVATE_BROWSE_DIR
|
|
60
|
+
EXPIRING_DAYS = 85 # a browser's oldest day this old is being expired (Chromium keeps 90)
|
|
61
|
+
STATE = ".keepfold/browse/state.json"
|
|
62
|
+
INDEX_ID, PRIVATE_INDEX_ID = "browse-index", "browse-private-index"
|
|
63
|
+
# a page goes under its nearest hub only from this cosine: the floor calibrated for short text
|
|
64
|
+
# (prime's prompt vector) against the same member centroids; below it, an "Other" cluster
|
|
65
|
+
HUB_FLOOR = topics.TOUCH_FLOOR
|
|
66
|
+
JOIN = 0.75 # far pages join a cluster at this cosine to its centroid
|
|
67
|
+
INTEREST_SECS, INTEREST_DAYS = 30 * 60, 3
|
|
68
|
+
SHOWN, SITES, INDEX_SITES, SEARCHES = 20, 10, 30, 50
|
|
69
|
+
SUMMARY_TITLES = 15
|
|
70
|
+
DAY_TITLES = 60 # page titles a private summary may hear
|
|
71
|
+
SESSION_GAP = 30 * 60 # a browsing session ends after this long with no visit
|
|
72
|
+
SUMMARY_HEAD = "What I was into: "
|
|
73
|
+
EMBED_BATCH = 256
|
|
74
|
+
PROGRESS_S = 5.0 # a phase longer than this says how far it got (counts only)
|
|
75
|
+
_DUR = re.compile(r"^(?:(\d+) h)?\s*(?:(\d+) min)?$")
|
|
76
|
+
_SITE = re.compile(r"^- ([a-z0-9.-]+) · (.+)$")
|
|
77
|
+
_DAY_FILE = re.compile(r"^browse-(\d{4}-\d{2}-\d{2})\.md$")
|
|
78
|
+
_PDAY_FILE = re.compile(r"^browse-private-(\d{4}-\d{2}-\d{2})\.md$")
|
|
79
|
+
# the journal line `signals` writes, so Q12 can take it out again
|
|
80
|
+
_JOURNAL_LINE = re.compile(r"^- \d{2}:\d{2} Browsing: spent .+ this week \(\d+ days?\)"
|
|
81
|
+
r"(?:\r?\n|\Z)", re.M)
|
|
82
|
+
_HUB_LINE = re.compile(r"^- \[\[([^\]|]+)\]\] · ([^·]+?)(?: · |$)")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Item:
|
|
87
|
+
day: str
|
|
88
|
+
start: datetime
|
|
89
|
+
secs: float
|
|
90
|
+
k: Kept
|
|
91
|
+
excerpt: str = ""
|
|
92
|
+
channel: str = ""
|
|
93
|
+
browser: str = "" # the Visit's source: a browser, "extension" or "takeout/…"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _dur(secs: float) -> str:
|
|
97
|
+
m = max(1, round(secs / 60))
|
|
98
|
+
h, m = divmod(m, 60)
|
|
99
|
+
return f"{m} min" if not h else f"{h} h {m} min" if m else f"{h} h"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _secs(text: str) -> float:
|
|
103
|
+
m = _DUR.match(text.strip())
|
|
104
|
+
return (int(m.group(1) or 0) * 60 + int(m.group(2) or 0)) * 60.0 if m else 0.0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _monday(day: str) -> str:
|
|
108
|
+
d = date.fromisoformat(day)
|
|
109
|
+
return (d - timedelta(days=d.weekday())).isoformat()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---- state --------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def load_state(vault: Vault) -> dict:
|
|
115
|
+
try:
|
|
116
|
+
s = json.loads((vault.root / STATE).read_text(encoding="utf-8"))
|
|
117
|
+
except (OSError, ValueError):
|
|
118
|
+
return {"sources": {}, "inbox": {}}
|
|
119
|
+
return s if isinstance(s, dict) else {"sources": {}, "inbox": {}}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---- the extension's inbox ----------------------------------------------------------------
|
|
123
|
+
# The capture extension (removed in 0.3.2) wrote these through the receiver. No new files
|
|
124
|
+
# arrive, but the inbox files and the archive it left still import, so its visits, time on
|
|
125
|
+
# screen and excerpts stay in the store, the day pages, Chat and search.
|
|
126
|
+
|
|
127
|
+
def _inbox_time(v) -> datetime | None:
|
|
128
|
+
try:
|
|
129
|
+
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
130
|
+
return datetime.fromtimestamp(v / 1000, UTC)
|
|
131
|
+
if isinstance(v, str):
|
|
132
|
+
t = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
|
133
|
+
return t if t.tzinfo else t.replace(tzinfo=UTC)
|
|
134
|
+
except (ValueError, OverflowError, OSError):
|
|
135
|
+
pass
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
ARCHIVE = ".keepfold/browse/inbox-archive" # consumed inbox files, filtered (review C5)
|
|
140
|
+
# kept at least this long (Chrome keeps about this long): a browser not read this run (unticked,
|
|
141
|
+
# not chosen, not imported yet) or Takeout may bring back an older day, whose rebuild needs it
|
|
142
|
+
ARCHIVE_DAYS = 90
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_inbox(vault: Vault, folder: str = ".keepfold/browse"
|
|
146
|
+
) -> tuple[list[sources.Visit], dict[str, list[int]]]:
|
|
147
|
+
"""The old extension's inbox records as visits (secs = active time), and each file's
|
|
148
|
+
[size, mtime].
|
|
149
|
+
`folder=ARCHIVE` reads the archive of consumed files instead."""
|
|
150
|
+
out, stats = [], {}
|
|
151
|
+
for p in sorted((vault.root / folder).glob("inbox-*.jsonl")):
|
|
152
|
+
try:
|
|
153
|
+
st = p.stat()
|
|
154
|
+
lines = p.read_bytes().decode("utf-8", "replace").splitlines()
|
|
155
|
+
except OSError:
|
|
156
|
+
continue
|
|
157
|
+
stats[p.name] = [st.st_size, st.st_mtime_ns]
|
|
158
|
+
recs = []
|
|
159
|
+
for line in lines:
|
|
160
|
+
try:
|
|
161
|
+
recs.append(json.loads(line))
|
|
162
|
+
except ValueError:
|
|
163
|
+
continue
|
|
164
|
+
out += inbox_visits(recs)
|
|
165
|
+
return out, stats
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def inbox_stats(vault: Vault) -> dict[str, list[int]]:
|
|
169
|
+
"""read_inbox's [size, mtime] per inbox file, without reading them."""
|
|
170
|
+
out = {}
|
|
171
|
+
for p in sorted((vault.root / ".keepfold" / "browse").glob("inbox-*.jsonl")):
|
|
172
|
+
try:
|
|
173
|
+
st = p.stat()
|
|
174
|
+
except OSError:
|
|
175
|
+
continue
|
|
176
|
+
out[p.name] = [st.st_size, st.st_mtime_ns]
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def inbox_visits(records: list) -> list[sources.Visit]:
|
|
181
|
+
"""The old extension's inbox records as visits (secs = active time); a malformed one is
|
|
182
|
+
skipped."""
|
|
183
|
+
out = []
|
|
184
|
+
for r in records:
|
|
185
|
+
if not isinstance(r, dict) or not isinstance(r.get("url"), str):
|
|
186
|
+
continue
|
|
187
|
+
start = _inbox_time(r.get("start"))
|
|
188
|
+
ms = r.get("active_ms")
|
|
189
|
+
if start is None:
|
|
190
|
+
continue
|
|
191
|
+
out.append(sources.Visit(
|
|
192
|
+
start, r["url"], str(r.get("title") or ""),
|
|
193
|
+
ms / 1000 if isinstance(ms, (int, float)) and not isinstance(ms, bool)
|
|
194
|
+
and ms >= 0 else 0.0, source="extension",
|
|
195
|
+
excerpt=str(r.get("excerpt") or "")[:2000],
|
|
196
|
+
channel=str(r.get("channel") or "")[:200]))
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---- the local model's verdict (C1) -------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
VET_LABELS = (*lists.CATEGORIES, "ordinary")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def local_only(runner):
|
|
206
|
+
"""`runner` when it is the loopback local model, else None: never cloudllm's CloudRunner
|
|
207
|
+
(a Runner subclass, so `isinstance` would pass it) nor a stand-in. The app's Cancel
|
|
208
|
+
wrapper (`_inner`) is looked through."""
|
|
209
|
+
from keepfold import localllm
|
|
210
|
+
|
|
211
|
+
inner = getattr(runner, "_inner", runner)
|
|
212
|
+
if type(inner) is not localllm.Runner:
|
|
213
|
+
return None
|
|
214
|
+
try:
|
|
215
|
+
localllm._check_url(inner.base)
|
|
216
|
+
except ValueError:
|
|
217
|
+
return None
|
|
218
|
+
return runner
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def vet(vault: Vault, items: list[Item], settings: Settings, runner, budget, *,
|
|
222
|
+
ask: bool = True, save: bool = True, con=None, keep_local: bool | None = None,
|
|
223
|
+
step=None) -> tuple[list[Item], Counter]:
|
|
224
|
+
"""C1, before any page is written: an uncategorised record's title or search term goes
|
|
225
|
+
to the local model (`local_only(runner)`; only when `ask`), newest first, in batches
|
|
226
|
+
(`titles.check`), and each batch's labels are saved by text hash in the store (`con`; a
|
|
227
|
+
stop keeps them). A sensitive label makes it that category (skip drops it, a hidden one
|
|
228
|
+
makes it private); "ordinary" clears it. With a local model set up (`keep_local`: default,
|
|
229
|
+
a local runner given) and no verdict (not loaded, budget spent, no answer) a title stays
|
|
230
|
+
local (`Kept.local`); without one, a title is judged by the word lists only. A search
|
|
231
|
+
term is never shown on a visible page without an "ordinary" verdict (`sites._shown`).
|
|
232
|
+
`step(done, total)` per batch. Counts only."""
|
|
233
|
+
local = local_only(runner)
|
|
234
|
+
keep = local is not None if keep_local is None else keep_local
|
|
235
|
+
verdicts = sites.load_verdicts(vault)
|
|
236
|
+
c: Counter = Counter()
|
|
237
|
+
need = _unvetted(items, verdicts, {}) if local is not None and ask else {}
|
|
238
|
+
c.update(_ask(vault, need, local, budget, verdicts, save=save, con=con, step=step))
|
|
239
|
+
return _apply(items, verdicts, settings, keep, c), c
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _unvetted(items: list[Item], verdicts: dict, need: dict[str, str]) -> dict[str, str]:
|
|
243
|
+
"""Add to `need` the texts of `items` (newest first) the local model has no verdict on:
|
|
244
|
+
{text hash: text}. Only uncategorised, not private records."""
|
|
245
|
+
from keepfold.browse import store
|
|
246
|
+
|
|
247
|
+
for it in reversed(items):
|
|
248
|
+
k = it.k
|
|
249
|
+
text = store.text_of(k)
|
|
250
|
+
if k.category is None and not k.private and text \
|
|
251
|
+
and (h := privacy.text_key(text)) not in verdicts:
|
|
252
|
+
need.setdefault(h, text)
|
|
253
|
+
return need
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _ask(vault: Vault, need: dict[str, str], local, budget, verdicts: dict, *, save: bool,
|
|
257
|
+
con, step) -> Counter:
|
|
258
|
+
"""The local model's verdicts on `need` (`titles.check`), each batch's saved in the store
|
|
259
|
+
(`con`) as it comes, and added to `verdicts`. Counts."""
|
|
260
|
+
from keepfold.browse import store, titles
|
|
261
|
+
|
|
262
|
+
c: Counter = Counter()
|
|
263
|
+
if not need:
|
|
264
|
+
return c
|
|
265
|
+
got, n = titles.check(need, local, list(VET_LABELS), budget, step=step, save=(
|
|
266
|
+
(lambda lab: store.put_verdicts(con, lab)) if save and con is not None else None))
|
|
267
|
+
c["vet_asked"] += n["asked"]
|
|
268
|
+
c["vet_calls"] += n["calls"]
|
|
269
|
+
verdicts.update(got)
|
|
270
|
+
if save and con is None and got:
|
|
271
|
+
with closing(store.connect(vault)) as c2:
|
|
272
|
+
store.put_verdicts(c2, got)
|
|
273
|
+
return c
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _apply(items: list[Item], verdicts: dict, settings: Settings, keep: bool, c: Counter
|
|
277
|
+
) -> list[Item]:
|
|
278
|
+
"""`items` with the local model's `verdicts` applied (see `vet`); counts into `c`."""
|
|
279
|
+
from keepfold.browse import store
|
|
280
|
+
|
|
281
|
+
out = []
|
|
282
|
+
for it in items:
|
|
283
|
+
k = it.k
|
|
284
|
+
text = store.text_of(k)
|
|
285
|
+
if k.category is not None or k.private or not text:
|
|
286
|
+
out.append(it)
|
|
287
|
+
continue
|
|
288
|
+
v = verdicts.get(privacy.text_key(text))
|
|
289
|
+
if v in lists.CATEGORIES:
|
|
290
|
+
k = privacy.apply(replace(k, category=v, maybe=True), settings=settings)
|
|
291
|
+
c["vet_sensitive"] += 1
|
|
292
|
+
if k is None:
|
|
293
|
+
c["dropped"] += 1
|
|
294
|
+
continue
|
|
295
|
+
elif v != "ordinary" and keep and not k.search:
|
|
296
|
+
k = replace(k, private=True, local=True)
|
|
297
|
+
c["vet_unsure"] += 1
|
|
298
|
+
it.k = k
|
|
299
|
+
out.append(it)
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# ---- topics -------------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
def hubs(vault: Vault, embed, save: bool = True) -> tuple[list[str], np.ndarray, dict[str, str]]:
|
|
306
|
+
"""(hub ids, unit member centroids, hub titles) for hubs with enough members; the root
|
|
307
|
+
topic map is left out (it is not a topic). `save=False` (a dry run) keeps the embedded
|
|
308
|
+
heads out of the vault's vector cache."""
|
|
309
|
+
from keepfold import semantic
|
|
310
|
+
from keepfold.catalog import Catalog
|
|
311
|
+
from keepfold.index import Index
|
|
312
|
+
|
|
313
|
+
idx = Index(vault, Catalog.load(vault))
|
|
314
|
+
t = topics.tree(idx)
|
|
315
|
+
dim = len(semantic._embed(embed, ["topic"])[0])
|
|
316
|
+
# only the hub members' heads: the import never pays for embedding every page it wrote
|
|
317
|
+
need = set().union(*topics.members(idx, t).values())
|
|
318
|
+
ids, sums, _ = topics.centroids(idx, t, semantic.vectors(idx, embed, dim, budget=0.0,
|
|
319
|
+
only=need, save=save))
|
|
320
|
+
keep = [n for n, h in enumerate(ids) if h != topics.ROOT]
|
|
321
|
+
sums = sums[keep]
|
|
322
|
+
unit = sums / np.maximum(np.linalg.norm(sums, axis=1, keepdims=True), 1e-9)
|
|
323
|
+
return [ids[n] for n in keep], unit, {ids[n]: t.title.get(ids[n], ids[n]) for n in keep}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _text(it: Item) -> str:
|
|
327
|
+
return " ".join(f"{it.k.search or it.k.title or it.k.host} {it.excerpt[:500]}".split())
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _embed_all(embed, texts: list[str], say=None) -> np.ndarray:
|
|
331
|
+
from keepfold import semantic
|
|
332
|
+
|
|
333
|
+
return semantic.embed_all(embed, texts, EMBED_BATCH,
|
|
334
|
+
say and (lambda s: say(f"topics: {s}")), "page titles")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _label(titles: list[str], hosts: list[str]) -> str:
|
|
338
|
+
from keepfold.topics import _terms
|
|
339
|
+
|
|
340
|
+
words = _terms([titles])[0]
|
|
341
|
+
return " ".join(words) or Counter(hosts).most_common(1)[0][0]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _clusters(vec: np.ndarray, far: list[int], say=None) -> list[list[int]]:
|
|
345
|
+
"""Greedy "Other" clusters of rows `far` of `vec`, in order: a row joins the group whose
|
|
346
|
+
member-sum centroid is nearest at cosine >= JOIN, else starts its own. One matvec per row
|
|
347
|
+
over running sums and norms (a Python loop over the groups was O(far x groups))."""
|
|
348
|
+
groups: list[list[int]] = []
|
|
349
|
+
cents = np.zeros((len(far), vec.shape[1]), vec.dtype)
|
|
350
|
+
norms = np.zeros(len(far), vec.dtype)
|
|
351
|
+
last = time.monotonic()
|
|
352
|
+
for k, n in enumerate(far):
|
|
353
|
+
if say and time.monotonic() - last >= PROGRESS_S:
|
|
354
|
+
say(f"topics: grouped {k} of {len(far)} pages")
|
|
355
|
+
last = time.monotonic()
|
|
356
|
+
g = len(groups)
|
|
357
|
+
sims = cents[:g] @ vec[n] / np.where(norms[:g] > 0, norms[:g], 1.0)
|
|
358
|
+
j = int(np.argmax(sims)) if g else -1
|
|
359
|
+
if j >= 0 and sims[j] >= JOIN:
|
|
360
|
+
groups[j].append(n)
|
|
361
|
+
cents[j] += vec[n]
|
|
362
|
+
else:
|
|
363
|
+
j = g
|
|
364
|
+
groups.append([n])
|
|
365
|
+
cents[j] = vec[n]
|
|
366
|
+
norms[j] = np.linalg.norm(cents[j])
|
|
367
|
+
return groups
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def place(items: list[Item], embed, hub_ids: list[str], unit: np.ndarray, say=None
|
|
371
|
+
) -> dict[tuple[str, bool], tuple]:
|
|
372
|
+
"""Section per (scrubbed URL, private), so a private title never shapes a public one:
|
|
373
|
+
("hub", id) at cosine >= HUB_FLOOR to its nearest hub (searches by their term). Anything
|
|
374
|
+
else is private (`public`) and keyed (url, True): ("other", label) of its cluster, or
|
|
375
|
+
("site", host) with no embedder or no hubs."""
|
|
376
|
+
first: dict[tuple[str, bool], Item] = {}
|
|
377
|
+
for i in items:
|
|
378
|
+
first.setdefault((i.k.url, i.k.private), i)
|
|
379
|
+
if embed is None or not hub_ids or not first:
|
|
380
|
+
return {(u, True): ("site", i.k.host) for (u, _), i in first.items()}
|
|
381
|
+
keys = list(first)
|
|
382
|
+
texts = [_text(first[k]) for k in keys]
|
|
383
|
+
uniq = list(dict.fromkeys(texts)) # one title on many URLs is embedded once
|
|
384
|
+
at = {t: n for n, t in enumerate(uniq)}
|
|
385
|
+
vec = _embed_all(embed, uniq, say)[[at[t] for t in texts]]
|
|
386
|
+
cos = vec @ unit.T
|
|
387
|
+
best = cos.argmax(axis=1)
|
|
388
|
+
out: dict[tuple[str, bool], tuple] = {}
|
|
389
|
+
far: list[int] = []
|
|
390
|
+
for n, key in enumerate(keys):
|
|
391
|
+
if cos[n, best[n]] >= HUB_FLOOR:
|
|
392
|
+
out[key] = ("hub", hub_ids[best[n]])
|
|
393
|
+
else:
|
|
394
|
+
far.append(n)
|
|
395
|
+
if say:
|
|
396
|
+
say(f"topics: grouping {len(far)} pages under no topic hub")
|
|
397
|
+
groups = _clusters(vec, far, say)
|
|
398
|
+
for g in groups:
|
|
399
|
+
ks = [first[keys[n]].k for n in g]
|
|
400
|
+
label = _label([k.search or k.title for k in ks], [k.host for k in ks])
|
|
401
|
+
for n in g:
|
|
402
|
+
out.setdefault((keys[n][0], True), ("other", label))
|
|
403
|
+
return out
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def public(i: Item, where: dict) -> bool:
|
|
407
|
+
"""Public is the exception (privacy review H1): no sensitive category, maybe or private
|
|
408
|
+
domain, and placed under an existing topic hub. Everything else goes to the private page."""
|
|
409
|
+
return not i.k.private and (where.get((i.k.url, False)) or ("",))[0] == "hub"
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# ---- pages --------------------------------------------------------------------------------
|
|
413
|
+
|
|
414
|
+
def _hub_rows(items: list[Item], where: dict) -> list[tuple[str, float, int, int, int]]:
|
|
415
|
+
"""[(hub id, seconds, pages, videos, searches)] over the public items, longest first.
|
|
416
|
+
Searches add no time."""
|
|
417
|
+
rows: dict[str, list] = {}
|
|
418
|
+
for i in items:
|
|
419
|
+
if not public(i, where):
|
|
420
|
+
continue
|
|
421
|
+
r = rows.setdefault(where[(i.k.url, False)][1], [0.0, set(), set(), set()])
|
|
422
|
+
if i.k.search:
|
|
423
|
+
r[3].add(i.k.search)
|
|
424
|
+
else:
|
|
425
|
+
r[0] += i.secs
|
|
426
|
+
(r[2] if i.k.video else r[1]).add(i.k.video or i.k.url)
|
|
427
|
+
out = [(h, s, len(p), len(v), len(t)) for h, (s, p, v, t) in rows.items()]
|
|
428
|
+
return sorted(out, key=lambda r: (-r[1], r[0]))
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _counts(pages: int, videos: int, searches: int) -> str:
|
|
432
|
+
return ", ".join(f"{n} {w if n == 1 else pl}" for n, w, pl in (
|
|
433
|
+
(pages, "page", "pages"), (videos, "video", "videos"), (searches, "search", "searches"))
|
|
434
|
+
if n)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _hub_lines(rows: list, others: int) -> list[str]:
|
|
438
|
+
out = [f"- [[{h}]] · " + (f"{_dur(s)} · " if s else "") + _counts(p, v, t)
|
|
439
|
+
for h, s, p, v, t in rows]
|
|
440
|
+
return out + ([f"- {others} other page{'s' if others > 1 else ''}"] if others else [])
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def public_body(day: str, rows: list, others: int, summary: str) -> str:
|
|
444
|
+
"""The public day page (second privacy review): the owner's own topic hubs as links with
|
|
445
|
+
time and counts, the number of other pages, and nothing a site, a title or a search wrote."""
|
|
446
|
+
out = [f"# Browsing {day}", "", f"Up: [[{INDEX_ID}]]", "", SUMMARY_HEAD + summary, "",
|
|
447
|
+
"## Topics", *_hub_lines(rows, others),
|
|
448
|
+
"", "Details are on the private page in Obsidian."]
|
|
449
|
+
return "\n".join(out) + "\n"
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _sections(items: list[Item], where: dict, titles: dict[str, str]):
|
|
453
|
+
"""[(heading, seconds, [(title, host, seconds, visits)])], longest first; a public and a
|
|
454
|
+
private visit of one URL stay apart."""
|
|
455
|
+
pages: dict[tuple[str, bool], list] = {}
|
|
456
|
+
for i in items:
|
|
457
|
+
if i.k.search:
|
|
458
|
+
continue
|
|
459
|
+
p = pages.setdefault((i.k.url, i.k.private), [i.k.title, i.k.host, 0.0, 0])
|
|
460
|
+
p[0] = i.k.title or p[0]
|
|
461
|
+
p[2] += i.secs
|
|
462
|
+
p[3] += 1
|
|
463
|
+
secs: dict[tuple, list] = defaultdict(list)
|
|
464
|
+
for (u, priv), p in pages.items():
|
|
465
|
+
secs[where.get((u, priv)) or where.get((u, True)) or ("site", p[1])].append(p)
|
|
466
|
+
out = []
|
|
467
|
+
for (kind, val), ps in secs.items():
|
|
468
|
+
head = (titles.get(val, val) if kind == "hub" else f"Other: {val}" if kind == "other"
|
|
469
|
+
else val.removeprefix("www."))
|
|
470
|
+
ps.sort(key=lambda p: (-p[2], p[0], p[1]))
|
|
471
|
+
out.append((head, sum(p[2] for p in ps), ps))
|
|
472
|
+
out.sort(key=lambda s: (-s[1], s[0]))
|
|
473
|
+
return out
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def private_body(day: str, items: list[Item], where: dict, titles: dict[str, str],
|
|
477
|
+
tz: tzinfo | None, hub_lines: list[str] | None = None,
|
|
478
|
+
summary: str | None = None, sessions: list | None = None) -> str:
|
|
479
|
+
"""The private day page: every kept item of the day, sensitive or not, as topics (by hub
|
|
480
|
+
title, with no link), searches, videos and top sites. Text from the browser goes through
|
|
481
|
+
`render.esc`. The one-line summary is the local LLM's `summary` when there is one, else
|
|
482
|
+
rule-made from the headings; `sessions` [(start, end, LLM line or None)] go under
|
|
483
|
+
"## Sessions". `hub_lines` (when no public page is written) go on top under "## Hubs"."""
|
|
484
|
+
sections = _sections(items, where, titles)
|
|
485
|
+
out = [f"# Browsing {day} (private)", "",
|
|
486
|
+
SUMMARY_HEAD + (esc(summary, 200) if summary else ", ".join(
|
|
487
|
+
f"{esc(h, 60) or 'untitled'} ({_dur(s)})" for h, s, _ in sections[:3])
|
|
488
|
+
or "nothing kept"), ""]
|
|
489
|
+
if hub_lines:
|
|
490
|
+
out += ["## Hubs", *hub_lines, ""]
|
|
491
|
+
if sessions:
|
|
492
|
+
out.append("## Sessions")
|
|
493
|
+
for a, b, line in sessions:
|
|
494
|
+
out += ["", f"### {a.astimezone(tz):%H:%M}–{b.astimezone(tz):%H:%M}"]
|
|
495
|
+
if line:
|
|
496
|
+
out.append(esc(line, 200))
|
|
497
|
+
out.append("")
|
|
498
|
+
out.append("## Topics")
|
|
499
|
+
for head, secs, ps in sections:
|
|
500
|
+
out += ["", f"### {esc(head, 80) or 'untitled'} · {_dur(secs)}"]
|
|
501
|
+
for t, host, s, n in ps[:SHOWN]:
|
|
502
|
+
out.append(f"- {esc(t) or host.removeprefix('www.')} · {host.removeprefix('www.')}"
|
|
503
|
+
f" · {_dur(s)}" + (f" · {n} visits" if n > 1 else ""))
|
|
504
|
+
if len(ps) > SHOWN:
|
|
505
|
+
out.append(f"- and {len(ps) - SHOWN} more")
|
|
506
|
+
searches, seen = [], set()
|
|
507
|
+
for i in items:
|
|
508
|
+
if i.k.search and (i.k.search, i.k.engine) not in seen:
|
|
509
|
+
seen.add((i.k.search, i.k.engine))
|
|
510
|
+
searches.append(f"- {i.start.astimezone(tz):%H:%M} · {esc(i.k.search)} · "
|
|
511
|
+
f"{i.k.engine}")
|
|
512
|
+
out += ["", "## Searches", *(searches[:SEARCHES] or ["- none"])]
|
|
513
|
+
videos: dict[str, list] = {}
|
|
514
|
+
for i in items:
|
|
515
|
+
if i.k.video:
|
|
516
|
+
v = videos.setdefault(i.k.video, [i.start, i.k.title, 0.0, ""])
|
|
517
|
+
v[1] = i.k.title or v[1]
|
|
518
|
+
v[2] += i.secs
|
|
519
|
+
v[3] = i.channel or v[3]
|
|
520
|
+
out += ["", "## Videos", *([f"- {s.astimezone(tz):%H:%M} · {esc(t) or 'untitled'}"
|
|
521
|
+
+ (f" · {esc(ch, 60)}" if esc(ch, 60) else "") + f" · {_dur(x)}"
|
|
522
|
+
for s, t, x, ch in videos.values()] or ["- none"])]
|
|
523
|
+
site: Counter = Counter()
|
|
524
|
+
for i in items:
|
|
525
|
+
site[i.k.host.removeprefix("www.")] += i.secs
|
|
526
|
+
top = sorted(site.items(), key=lambda x: (-x[1], x[0]))[:SITES]
|
|
527
|
+
out += ["", "## Top sites", *[f"- {h} · {_dur(s)}" for h, s in top]]
|
|
528
|
+
return "\n".join(out) + "\n"
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _page_text(fields: dict, body: str) -> str:
|
|
532
|
+
from ruamel.yaml.comments import CommentedMap
|
|
533
|
+
|
|
534
|
+
fm = CommentedMap((k, _to_yaml(v)) for k, v in fields.items())
|
|
535
|
+
return "---\n" + _dump_fm(fm, "\n") + "---\n" + body
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _old_summary(vault: Vault, path, inputs: str) -> str | None:
|
|
539
|
+
"""The local LLM's summary on the page as it stands when it was made from the same hubs,
|
|
540
|
+
so a rebuild does not ask the LLM again (and stays the same)."""
|
|
541
|
+
try:
|
|
542
|
+
n = vault.read_path(path)
|
|
543
|
+
except VaultError:
|
|
544
|
+
return None
|
|
545
|
+
if n.fields.get("browse_inputs") != inputs or n.fields.get("browse_llm") is not True:
|
|
546
|
+
return None
|
|
547
|
+
line = next((ln for ln in n.body.splitlines() if ln.startswith(SUMMARY_HEAD)), None)
|
|
548
|
+
return line[len(SUMMARY_HEAD):] if line else None
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _summary(runner, budget, names: list[str], cap: int = SUMMARY_TITLES, *,
|
|
552
|
+
escape: bool = True) -> str | None:
|
|
553
|
+
"""The local LLM's one line from `names`: the owner's own hub names for a public page
|
|
554
|
+
(never a page title); page titles only for a private page."""
|
|
555
|
+
if runner is None or not names or (budget is not None and not budget.ok()):
|
|
556
|
+
return None
|
|
557
|
+
got = runner.summarise(names[:cap], budget=budget)
|
|
558
|
+
return (esc(got, 200) if escape else got) if got else None
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _sessions(items: list[Item]) -> list[list[Item]]:
|
|
562
|
+
"""The day's items split where nothing happened for SESSION_GAP (a visit's time counts)."""
|
|
563
|
+
out: list[list[Item]] = []
|
|
564
|
+
end = None
|
|
565
|
+
for i in sorted(items, key=lambda i: i.start):
|
|
566
|
+
if end is None or (i.start - end).total_seconds() >= SESSION_GAP:
|
|
567
|
+
out.append([])
|
|
568
|
+
out[-1].append(i)
|
|
569
|
+
e = i.start + timedelta(seconds=i.secs)
|
|
570
|
+
end = e if end is None or e > end else end
|
|
571
|
+
return out
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _private_summaries(vault: Vault, path, items: list[Item], runner, budget):
|
|
575
|
+
"""The local LLM's private lines, from the page titles of the kept items (at most
|
|
576
|
+
DAY_TITLES): (day line, [(session start, end, line)], {inputs hash: line}). Lines already
|
|
577
|
+
on the page for the same titles are reused, so a rebuild does not ask again. Nothing at all
|
|
578
|
+
when no line exists."""
|
|
579
|
+
try:
|
|
580
|
+
old = vault.read_path(path).fields.get("browse_llm")
|
|
581
|
+
except VaultError:
|
|
582
|
+
old = None
|
|
583
|
+
old = old if isinstance(old, dict) else {}
|
|
584
|
+
cache: dict[str, str] = {}
|
|
585
|
+
|
|
586
|
+
def line(its: list[Item]) -> str | None:
|
|
587
|
+
names = list(dict.fromkeys(i.k.title for i in its if i.k.title and not i.k.search))
|
|
588
|
+
if not names:
|
|
589
|
+
return None
|
|
590
|
+
names = names[:DAY_TITLES]
|
|
591
|
+
key = hashlib.sha256(json.dumps(names).encode()).hexdigest()[:16]
|
|
592
|
+
got = old.get(key) if isinstance(old.get(key), str) else None
|
|
593
|
+
got = got or _summary(runner, budget, names, DAY_TITLES, escape=False)
|
|
594
|
+
if got:
|
|
595
|
+
cache[key] = got
|
|
596
|
+
return got
|
|
597
|
+
|
|
598
|
+
day = line(items)
|
|
599
|
+
sessions = [(s[0].start, max(i.start + timedelta(seconds=i.secs) for i in s), line(s))
|
|
600
|
+
for s in _sessions(items)]
|
|
601
|
+
return (day, sessions, cache) if cache else (None, [], {})
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _put(vault: Vault, path, pid: str, fields: dict, body: str) -> str:
|
|
605
|
+
"""Write a page unless it is the same; a line that looks like a secret is left out, and a
|
|
606
|
+
page the vault refuses is skipped ("failed"), never the run."""
|
|
607
|
+
body = "\n".join(ln for ln in body.split("\n") if not secret_pattern(ln))
|
|
608
|
+
text = _page_text(fields, body)
|
|
609
|
+
old = path.read_bytes().decode("utf-8") if path.is_file() else None
|
|
610
|
+
if old == text:
|
|
611
|
+
return "same"
|
|
612
|
+
try:
|
|
613
|
+
vault.write_text(path, text)
|
|
614
|
+
except VaultError as e:
|
|
615
|
+
log.warning("browse: %s not written: %s", pid, e.code)
|
|
616
|
+
return "failed"
|
|
617
|
+
return "written"
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def write_day(vault: Vault, day: str, items: list[Item], where: dict, titles: dict[str, str],
|
|
621
|
+
runner=None, budget=None, tz: tzinfo | None = None, *, visible: bool = False
|
|
622
|
+
) -> dict[str, str]:
|
|
623
|
+
"""Rebuild the day's public and private pages from all its items; a page with nothing to
|
|
624
|
+
show is removed. Public: topic hubs, time and counts only, and only when `visible`
|
|
625
|
+
(browse.visible_to_claude); otherwise those lines top the private page and any public page
|
|
626
|
+
goes. Private: every item. Returns
|
|
627
|
+
{"public"/"private": "written"|"same"|"removed"|"none"|"failed"}."""
|
|
628
|
+
res = {}
|
|
629
|
+
rows = _hub_rows(items, where)
|
|
630
|
+
others = len({i.k.url for i in items if not i.k.private and not public(i, where)})
|
|
631
|
+
pid, path = f"browse-{day}", vault.root / DIR / f"browse-{day}.md"
|
|
632
|
+
if not rows or not visible:
|
|
633
|
+
res["public"] = "removed" if vault.remove(path) else "none"
|
|
634
|
+
else:
|
|
635
|
+
inputs = hashlib.sha256(json.dumps([rows, others]).encode()).hexdigest()[:16]
|
|
636
|
+
names = [titles.get(h, h) for h, *_ in rows]
|
|
637
|
+
summary = _old_summary(vault, path, inputs) or _summary(runner, budget, names)
|
|
638
|
+
fields = {"id": pid, "title": f"Browsing {day}", "kind": "browse", "date": day,
|
|
639
|
+
"browse_inputs": inputs}
|
|
640
|
+
if summary:
|
|
641
|
+
fields["browse_llm"] = True
|
|
642
|
+
fallback = ", ".join(esc(titles.get(h, h), 60) + (f" ({_dur(s)})" if s else "")
|
|
643
|
+
for h, s, *_ in rows[:3])
|
|
644
|
+
res["public"] = _put(vault, path, pid, fields,
|
|
645
|
+
public_body(day, rows, others, summary or fallback))
|
|
646
|
+
pid = f"browse-private-{day}"
|
|
647
|
+
path = vault.root / PRIVATE_DIR / f"{pid}.md"
|
|
648
|
+
if not items:
|
|
649
|
+
res["private"] = "removed" if vault.remove(path) else "none"
|
|
650
|
+
else:
|
|
651
|
+
# the private page, never shown to Claude, is the only one whose titles the LLM hears
|
|
652
|
+
summary, sessions, cache = _private_summaries(vault, path, items, runner, budget)
|
|
653
|
+
fields = {"id": pid, "title": f"Browsing {day} (private)", "kind": "browse",
|
|
654
|
+
"date": day, "private": True}
|
|
655
|
+
if cache:
|
|
656
|
+
fields["browse_llm"] = cache
|
|
657
|
+
res["private"] = _put(vault, path, pid, fields, private_body(
|
|
658
|
+
day, items, where, titles, tz, None if visible else _hub_lines(rows, others),
|
|
659
|
+
summary, sessions))
|
|
660
|
+
return res
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _days(folder, pattern: re.Pattern) -> list[tuple[str, str]]:
|
|
664
|
+
"""[(day, text)] of the day pages in `folder` whose file name matches `pattern`."""
|
|
665
|
+
out = []
|
|
666
|
+
for p in sorted(folder.glob("*.md")):
|
|
667
|
+
if m := pattern.match(p.name):
|
|
668
|
+
out.append((m.group(1), p.read_bytes().decode("utf-8", "replace")))
|
|
669
|
+
return out
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _section_lines(text: str, heading: str) -> list[str]:
|
|
673
|
+
inside, out = False, []
|
|
674
|
+
for line in text.splitlines():
|
|
675
|
+
if line.startswith("## "):
|
|
676
|
+
inside = line == heading
|
|
677
|
+
elif inside:
|
|
678
|
+
out.append(line)
|
|
679
|
+
return out
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def _put_index(vault: Vault, path, fields: dict, lines: list[str]) -> bool:
|
|
683
|
+
text = _page_text(fields, "\n".join(lines) + "\n")
|
|
684
|
+
if path.is_file() and path.read_bytes().decode("utf-8") == text:
|
|
685
|
+
return False
|
|
686
|
+
vault.write_text(path, text)
|
|
687
|
+
return True
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _days_and_hubs(pages: list[tuple[str, str]], heading: str, prefix: str) -> list[str]:
|
|
691
|
+
"""Index lines: months and days (newest first, linked by `prefix`), and the hubs by time
|
|
692
|
+
summed from each page's hub lines under `heading`."""
|
|
693
|
+
hub = defaultdict(lambda: [0, 0.0])
|
|
694
|
+
for _, text in pages:
|
|
695
|
+
for line in _section_lines(text, heading):
|
|
696
|
+
if m := _HUB_LINE.match(line):
|
|
697
|
+
hub[m.group(1)][0] += 1
|
|
698
|
+
hub[m.group(1)][1] += _secs(m.group(2))
|
|
699
|
+
days = sorted((d for d, _ in pages), reverse=True)
|
|
700
|
+
out = ["## Days"]
|
|
701
|
+
for month in sorted({d[:7] for d in days}, reverse=True):
|
|
702
|
+
out += ["", f"### {month}", *[f"- [[{prefix}{d}]]" for d in days
|
|
703
|
+
if d.startswith(month)]]
|
|
704
|
+
top = sorted(hub.items(), key=lambda x: (-x[1][1], -x[1][0], x[0]))[:INDEX_SITES]
|
|
705
|
+
return out + ["", "## Topics by time",
|
|
706
|
+
*[f"- [[{h}]] · {n} day{'s' if n > 1 else ''} · {_dur(s)}"
|
|
707
|
+
for h, (n, s) in top]]
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def write_index(vault: Vault, *, visible: bool = False) -> bool:
|
|
711
|
+
"""`browse/browse-index.md` from the public day pages on disk: months and days, newest
|
|
712
|
+
first, and the topic hubs by time (no site, no title). The sites returned to most go to
|
|
713
|
+
the private index, `browse/private/browse-private-index.md`. Not `visible`: no public
|
|
714
|
+
index (an old one goes) and the private index also gets the days and hubs. True if either
|
|
715
|
+
changed."""
|
|
716
|
+
pub, priv = _days(vault.root / DIR, _DAY_FILE), _days(vault.root / PRIVATE_DIR, _PDAY_FILE)
|
|
717
|
+
changed = False
|
|
718
|
+
path = vault.root / DIR / f"{INDEX_ID}.md"
|
|
719
|
+
if not pub or not visible:
|
|
720
|
+
changed |= vault.remove(path)
|
|
721
|
+
else:
|
|
722
|
+
changed |= _put_index(vault, path, {"id": INDEX_ID, "title": "Browsing",
|
|
723
|
+
"kind": "browse"},
|
|
724
|
+
["# Browsing", "", *_days_and_hubs(pub, "## Topics", "browse-")])
|
|
725
|
+
path = vault.root / PRIVATE_DIR / f"{PRIVATE_INDEX_ID}.md"
|
|
726
|
+
if not priv:
|
|
727
|
+
return vault.remove(path) or changed
|
|
728
|
+
sites = defaultdict(lambda: [0, 0.0])
|
|
729
|
+
for _, text in priv:
|
|
730
|
+
for line in _section_lines(text, "## Top sites"):
|
|
731
|
+
if s := _SITE.match(line):
|
|
732
|
+
sites[s.group(1)][0] += 1
|
|
733
|
+
sites[s.group(1)][1] += _secs(s.group(2))
|
|
734
|
+
top = sorted(sites.items(), key=lambda x: (-x[1][0], -x[1][1], x[0]))[:INDEX_SITES]
|
|
735
|
+
out = ["# Browsing (private)", ""]
|
|
736
|
+
if not visible:
|
|
737
|
+
out += [*_days_and_hubs(priv, "## Hubs", "browse-private-"), ""]
|
|
738
|
+
out += ["## Sites I return to",
|
|
739
|
+
*[f"- {h} · {n} day{'s' if n > 1 else ''} · {_dur(s)}" for h, (n, s) in top]]
|
|
740
|
+
return _put_index(vault, path, {"id": PRIVATE_INDEX_ID, "title": "Browsing (private)",
|
|
741
|
+
"kind": "browse", "private": True}, out) or changed
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
# ---- signals ------------------------------------------------------------------------------
|
|
745
|
+
|
|
746
|
+
def signals(vault: Vault, items: list[Item], where: dict, titles: dict[str, str],
|
|
747
|
+
tz: tzinfo | None = None, con=None, days: set[str] | None = None) -> int:
|
|
748
|
+
"""§3 interest: per topic hub and week, >= 30 min or >= 3 days of public browsing earns one
|
|
749
|
+
journal line and one `touch` event (keyed, so once). With the store (`con`), `items` are
|
|
750
|
+
those of `days` only: their time per hub and day is saved, and the weeks are summed from
|
|
751
|
+
every day saved. Returns how many were new."""
|
|
752
|
+
weeks: dict[tuple[str, str], list] = {}
|
|
753
|
+
for i in items:
|
|
754
|
+
if i.k.search or not public(i, where):
|
|
755
|
+
continue
|
|
756
|
+
row = weeks.setdefault((where[(i.k.url, False)][1], _monday(i.day)), [0.0, set(), i])
|
|
757
|
+
row[0] += i.secs
|
|
758
|
+
row[1].add(i.day)
|
|
759
|
+
if i.start > row[2].start:
|
|
760
|
+
row[2] = i
|
|
761
|
+
if con is not None:
|
|
762
|
+
from keepfold.browse import store
|
|
763
|
+
|
|
764
|
+
per: dict[tuple[str, str], list] = {}
|
|
765
|
+
for i in items:
|
|
766
|
+
if not i.k.search and public(i, where):
|
|
767
|
+
r = per.setdefault((i.day, where[(i.k.url, False)][1]), [0.0, 0.0])
|
|
768
|
+
r[0] += i.secs
|
|
769
|
+
r[1] = max(r[1], i.start.timestamp())
|
|
770
|
+
store.put_hub_days(con, days if days is not None else {i.day for i in items}, per)
|
|
771
|
+
weeks = {(hub, week): [secs, n, (day, datetime.fromtimestamp(t, UTC))]
|
|
772
|
+
for (hub, week), (secs, n, day, t) in store.hub_weeks(
|
|
773
|
+
con, {w for _, w in weeks} | {_monday(d) for d in days or ()}).items()}
|
|
774
|
+
else:
|
|
775
|
+
weeks = {k: [s, len(ds), (i.day, i.start)] for k, (s, ds, i) in weeks.items()}
|
|
776
|
+
evlog, new = EventLog(vault), 0
|
|
777
|
+
for (hub, week), (secs, n, (day, at)) in sorted(weeks.items()):
|
|
778
|
+
key = f"browse:touch:{hub}:{week}"
|
|
779
|
+
if (secs < INTEREST_SECS and n < INTEREST_DAYS) or evlog.has_key(key):
|
|
780
|
+
continue
|
|
781
|
+
vault.append_journal(day, f"{at.astimezone(tz):%H:%M}",
|
|
782
|
+
f"Browsing: spent {_dur(secs)} on {plain(titles.get(hub, hub), 80)}"
|
|
783
|
+
f" this week ({n} day{'s' if n > 1 else ''})")
|
|
784
|
+
evlog.append(session="cli", kind="log", source="imported", key=key,
|
|
785
|
+
fields={"payload": {"kind": "touch", "ids": [hub]}}, now=at)
|
|
786
|
+
new += 1
|
|
787
|
+
return new
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
# ---- the run ------------------------------------------------------------------------------
|
|
791
|
+
|
|
792
|
+
PHASES = ("reading browsers", "saving new visits", "checking titles", "writing day pages",
|
|
793
|
+
"updating search index")
|
|
794
|
+
RESUMMARISE = 7 # days made while the local model was away, redone per run once it is here
|
|
795
|
+
RENDER_VISITS = 20000 # visits whose days' pages are made together (bounds the memory)
|
|
796
|
+
# the background import rests this long after each chunk: it runs on a thread of the app's own
|
|
797
|
+
# process, so it yields rather than lowering a process priority
|
|
798
|
+
PAUSE_S = 0.05
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _local_set_up() -> bool:
|
|
802
|
+
"""A local model is set up (`localllm.enabled`), loaded or not: then a title with no
|
|
803
|
+
verdict yet stays local (C1), whether or not this run may ask the model."""
|
|
804
|
+
from keepfold import localllm
|
|
805
|
+
|
|
806
|
+
try:
|
|
807
|
+
return localllm.enabled()
|
|
808
|
+
except Exception: # an unreadable config: the safe side
|
|
809
|
+
return True
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
@sites.held
|
|
813
|
+
def run(vault: Vault, srcs: list[sources.Source], settings: Settings, *, embed=None,
|
|
814
|
+
runner=None, budget=None, since: str | None = None, now: datetime | None = None,
|
|
815
|
+
tz: tzinfo | None = None, dry_run: bool = False, progress=None, say=None,
|
|
816
|
+
takeout: list[sources.Visit] | None = None, step=None, ask: bool | None = None,
|
|
817
|
+
summaries: bool = True, keep_local: bool | None = None, pause: float = 0.0) -> dict:
|
|
818
|
+
"""One import into the store (`keepfold.browse.store`), then the pages of the days it
|
|
819
|
+
changed. Counts only.
|
|
820
|
+
1 reading browsers: each source from its cursor on (`sources.Since`); a History file
|
|
821
|
+
unchanged since the last run is not even copied. 2 saving new visits: through the §2
|
|
822
|
+
filter into the store, store.CHUNK visits read and saved at a time, the source's cursor
|
|
823
|
+
moved after its last; the extension's inbox files (and the archive of consumed ones) not
|
|
824
|
+
read since they changed; `takeout` (Google activity, keepfold.browse.takeout) too, which
|
|
825
|
+
counts only on days no browser or inbox visit holds. 3 checking titles: the local model's
|
|
826
|
+
verdicts (C1, `vet`) on the changed days' texts, in batches, when `ask` (default: visible
|
|
827
|
+
to Claude and not a dry run). 4 writing day pages: every dirty day (new or changed rows, a
|
|
828
|
+
forget, a verdict; all days on a settings change, from `since` on with it), newest first,
|
|
829
|
+
RENDER_VISITS visits' days at a time; each batch's days are clean once their pages and site
|
|
830
|
+
counts are saved, so a stop goes on there next time. Memory stays bounded by those
|
|
831
|
+
chunks, however long the history. 5 updating search index: the browse index, the site
|
|
832
|
+
pages (`keepfold.browse.sites`, only when the counts or settings changed), the state.
|
|
833
|
+
`runner` (the local LLM, laptop only) writes the public pages' one-line summary from hub
|
|
834
|
+
names and the private pages' day and session summaries from their kept titles; with
|
|
835
|
+
`summaries` False (the app's import job: the model's time goes to the titles) or no
|
|
836
|
+
runner, a day made with a local model set up goes on a list and is redone, RESUMMARISE
|
|
837
|
+
days a run, newest first, by a later run that has the model. `keep_local`: a local model
|
|
838
|
+
is set up (default: a local runner or `localllm.enabled`). Without
|
|
839
|
+
settings.visible_to_claude only the private pages are written: no public page or index,
|
|
840
|
+
journal line or touch.
|
|
841
|
+
A source that fails is skipped and keeps its cursor. `dry_run` writes nothing (an
|
|
842
|
+
in-memory copy of the store) and counts the day pages it would write. `pause`: seconds
|
|
843
|
+
of rest after each chunk (the background import, so the owner's machine stays quick).
|
|
844
|
+
`progress(key, visits, new, error)` per source; `step(phase, done, total)` (phase 1-5,
|
|
845
|
+
PHASES) as each part goes. `srcs` are read as given: callers that did not pick browsers
|
|
846
|
+
explicitly pass `sources.chosen(settings)` (S2). Runs under the browse-wide lock
|
|
847
|
+
(`sites.busy`), so a forget never lands in the middle of it."""
|
|
848
|
+
from keepfold import taint
|
|
849
|
+
from keepfold.browse import store
|
|
850
|
+
|
|
851
|
+
taint.check_config("the browsing import") # `settings` may be the defaults read in its place
|
|
852
|
+
now = now or datetime.now(UTC)
|
|
853
|
+
vis = settings.visible_to_claude
|
|
854
|
+
tell = say or (lambda s: None) # counts-only progress, so a long run is never silent
|
|
855
|
+
phase = step or (lambda n, done, total: None)
|
|
856
|
+
state = load_state(vault)
|
|
857
|
+
# the files from before the store read in, once, first (the old cursors' days need the
|
|
858
|
+
# counts): the name a torn site-days.json was set aside as
|
|
859
|
+
moved = {} if dry_run else migrate_legacy(vault)
|
|
860
|
+
bad = m if (m := moved.get(sites.DAYS)) not in (None, "migrated", "failed") else None
|
|
861
|
+
report: Counter = Counter()
|
|
862
|
+
fp = fingerprint(settings)
|
|
863
|
+
keep_local = local_only(runner) is not None or _local_set_up() if keep_local is None \
|
|
864
|
+
else keep_local
|
|
865
|
+
ask = vis and not dry_run if ask is None else ask and not dry_run
|
|
866
|
+
con = store.connect(vault, memory=dry_run)
|
|
867
|
+
try:
|
|
868
|
+
# a vault imported before the store (its state has no sites_stamp yet, or the store no
|
|
869
|
+
# visit: the app makes the store before the first import): the old cursors, taken
|
|
870
|
+
# once and kept in the store, so a stop never loses them (`_read_and_save`)
|
|
871
|
+
legacy = store.get_meta(con, "legacy")
|
|
872
|
+
if legacy is None:
|
|
873
|
+
before = bool(state.get("last_run")) and (
|
|
874
|
+
"sites_stamp" not in state
|
|
875
|
+
or con.execute("SELECT 1 FROM visits LIMIT 1").fetchone() is None)
|
|
876
|
+
rows = (state.get("sources") or {}) if before else {}
|
|
877
|
+
legacy = {"cursors": {k: r["cursor"] for k, r in rows.items()
|
|
878
|
+
if isinstance(r, dict) and isinstance(r.get("cursor"), int)},
|
|
879
|
+
"archive": True} if before else {}
|
|
880
|
+
with con:
|
|
881
|
+
store.set_meta(con, "legacy", legacy)
|
|
882
|
+
# who may see what changed (visibility, hidden or skipped categories, the domain
|
|
883
|
+
# lists, the filter's own rules) since the stored rows were filtered (the store's
|
|
884
|
+
# mark, else the state's: a vault imported before the store): everything stored is
|
|
885
|
+
# filtered again (C2) and every day redone. A first import has nothing to redo, so a
|
|
886
|
+
# stopped one goes on from its saved chunks.
|
|
887
|
+
was = store.get_meta(con, "settings") or state.get("settings")
|
|
888
|
+
reset = was is not None and was != fp
|
|
889
|
+
if reset and not dry_run:
|
|
890
|
+
tell("settings changed: filtering what is stored again")
|
|
891
|
+
report.update({f"refiltered_{k}": n for k, n in forget.purge(
|
|
892
|
+
vault, forget.Rule.of(settings), write=False).items()})
|
|
893
|
+
elif was is None and not dry_run:
|
|
894
|
+
with con:
|
|
895
|
+
store.set_meta(con, "settings", fp)
|
|
896
|
+
if not dry_run:
|
|
897
|
+
forget.sync_private(vault)
|
|
898
|
+
cursors = _read_and_save(vault, con, srcs, settings, tz, now, reset, legacy,
|
|
899
|
+
takeout, report, tell, phase, progress, pause)
|
|
900
|
+
part = store.partial(con)
|
|
901
|
+
# the site counts or the model's site cache changed since the last run (a forget, a
|
|
902
|
+
# deepen): every site page is made again, not only those of the days made now
|
|
903
|
+
outside = state.get("sites_stamp") != _sites_stamp(vault)
|
|
904
|
+
held = store.days(con) - part if reset or since else set() # no scan on a live run
|
|
905
|
+
if reset and not vis and not dry_run and (n := _void_signals(vault)):
|
|
906
|
+
report["browse_voided"] += n
|
|
907
|
+
if not dry_run and (gone := _drop_public(vault, None if not vis else held if reset
|
|
908
|
+
else "")):
|
|
909
|
+
report["public_removed"] += gone
|
|
910
|
+
with con:
|
|
911
|
+
if reset:
|
|
912
|
+
store.mark(con, held)
|
|
913
|
+
# the days to redo are saved: a stop goes on from them, not from a new
|
|
914
|
+
# refilter; "refilter" keeps the full site pages and vector prune owed
|
|
915
|
+
store.set_meta(con, "settings", fp)
|
|
916
|
+
store.set_meta(con, "refilter", True)
|
|
917
|
+
if since:
|
|
918
|
+
store.mark(con, {d for d in held if d >= since})
|
|
919
|
+
if summaries and local_only(runner) is not None and not dry_run:
|
|
920
|
+
store.mark(con, store.unsummarised(con, RESUMMARISE))
|
|
921
|
+
todo = store.dirty(con) - part
|
|
922
|
+
purged = reset or bool(store.get_meta(con, "refilter"))
|
|
923
|
+
touched = None
|
|
924
|
+
if todo:
|
|
925
|
+
got = _render(vault, con, todo, settings, embed=embed, runner=runner, budget=budget,
|
|
926
|
+
tz=tz, dry_run=dry_run, ask=ask, keep_local=keep_local,
|
|
927
|
+
summaries=summaries, report=report, tell=tell, phase=phase,
|
|
928
|
+
pause=pause)
|
|
929
|
+
if dry_run:
|
|
930
|
+
return {**report, "days_from": _monday(min(todo)), "days": got,
|
|
931
|
+
"visible_to_claude": vis, "dry_run": True}
|
|
932
|
+
touched, b, skipped = got
|
|
933
|
+
bad, purged = bad or b, purged | skipped
|
|
934
|
+
elif dry_run:
|
|
935
|
+
return {**report, "visible_to_claude": vis, "dry_run": True}
|
|
936
|
+
phase(5, 0, 1)
|
|
937
|
+
if todo or report["public_removed"] or purged:
|
|
938
|
+
report["index_changed"] = int(write_index(vault, visible=vis))
|
|
939
|
+
stats = _archive_consumed(vault, inbox_stats(vault), settings)
|
|
940
|
+
if not report["sources_failed"]: # the store holds what the archive held
|
|
941
|
+
report["archive_pruned"] = _prune_archive(
|
|
942
|
+
vault, (now - timedelta(days=ARCHIVE_DAYS)).date().isoformat())
|
|
943
|
+
if todo or purged or outside:
|
|
944
|
+
tell("sites: making the site pages")
|
|
945
|
+
# every time the counts change, so a settings change reaches the site pages; a
|
|
946
|
+
# live read makes again only the sites of the days it made
|
|
947
|
+
report.update(sites.write(vault, settings, tz, say=say, bad=bad,
|
|
948
|
+
only=None if purged or outside else touched))
|
|
949
|
+
if purged:
|
|
950
|
+
report["refiltered_vectors"] = forget.prune_vectors(vault)["vectors"]
|
|
951
|
+
vault.write_text(vault.root / STATE, json.dumps({
|
|
952
|
+
"pending": None, "last_run": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
953
|
+
"llm": runner.describe() if runner is not None else None,
|
|
954
|
+
"embedder": embed is not None,
|
|
955
|
+
"sources": {**(state.get("sources") or {}), **cursors},
|
|
956
|
+
"settings": fp, "inbox": stats, "sites_stamp": _sites_stamp(vault)},
|
|
957
|
+
indent=1, sort_keys=True))
|
|
958
|
+
with con:
|
|
959
|
+
store.set_meta(con, "settings", fp)
|
|
960
|
+
store.set_meta(con, "refilter", False)
|
|
961
|
+
phase(5, 1, 1)
|
|
962
|
+
return {**report, "visible_to_claude": vis}
|
|
963
|
+
finally:
|
|
964
|
+
con.close()
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def _sites_stamp(vault: Vault) -> list:
|
|
968
|
+
"""The site counts' change count (`sites.days_gen`) and the local model's site cache
|
|
969
|
+
(size, mtime): the site pages are made again only when one changed."""
|
|
970
|
+
try:
|
|
971
|
+
st = (vault.root / sites.CACHE).stat()
|
|
972
|
+
return [sites.days_gen(vault), st.st_size, st.st_mtime_ns]
|
|
973
|
+
except OSError:
|
|
974
|
+
return [sites.days_gen(vault), 0, 0]
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _state_row(cursor: int | None, ran: str, stat: str | None) -> dict:
|
|
978
|
+
"""A source's row in the state (`status`, the app's auto import): its cursor, when it was
|
|
979
|
+
read, its History file's size and mtime."""
|
|
980
|
+
row: dict = {"cursor": cursor, "ran": ran}
|
|
981
|
+
if stat:
|
|
982
|
+
row["size"], row["mtime_ns"] = json.loads(stat)[:2]
|
|
983
|
+
return row
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def _read_and_save(vault: Vault, con, srcs, settings: Settings, tz, now: datetime,
|
|
987
|
+
reset: bool, legacy: dict, takeout, report: Counter, tell,
|
|
988
|
+
phase, progress, pause: float = 0.0) -> dict:
|
|
989
|
+
"""Phases 1 and 2 of `run`: the new visits of every source, the inbox files and `takeout`
|
|
990
|
+
into the store. A source is read and saved store.CHUNK visits at a time (memory stays
|
|
991
|
+
bounded however long the history), its cursor moved with each chunk (a stop or crash
|
|
992
|
+
loses at most one) and its History file's stat once the last is saved; a first import
|
|
993
|
+
into an empty store makes the indexes after its rows (`store.bulk`). `pause` s between
|
|
994
|
+
chunks (the background import leaves the machine to its owner). `legacy` (run's store
|
|
995
|
+
meta of that name, a vault imported before the store): until a source's first read into
|
|
996
|
+
the store is whole, its rows up to the old cursor mark no day (those days have pages),
|
|
997
|
+
and the archive is read in once the same way; then its partly expired oldest days are
|
|
998
|
+
kept as they are (`store.partial`) and its cursor leaves the meta. The state's cursor
|
|
999
|
+
rows of the sources read (for `status`)."""
|
|
1000
|
+
from keepfold.browse import store
|
|
1001
|
+
|
|
1002
|
+
cursors: dict = {}
|
|
1003
|
+
ran = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
1004
|
+
with ExitStack() as copies, store.bulk(con):
|
|
1005
|
+
got = []
|
|
1006
|
+
for n, s in enumerate(srcs):
|
|
1007
|
+
phase(1, n, len(srcs))
|
|
1008
|
+
id_cur, t_cur, stat_old = store.cursor(con, s.key)
|
|
1009
|
+
stat = store.file_stat(s.path)
|
|
1010
|
+
if not reset and id_cur is not None and stat is not None and stat == stat_old:
|
|
1011
|
+
report["sources"] += 1 # the browser wrote nothing since: not even copied
|
|
1012
|
+
cursors[s.key] = _state_row(t_cur, ran, stat)
|
|
1013
|
+
if progress:
|
|
1014
|
+
progress(s.key, 0, 0, None)
|
|
1015
|
+
continue
|
|
1016
|
+
tell(f"{s.key}: reading its history")
|
|
1017
|
+
try:
|
|
1018
|
+
# a settings change reads everything again: a visit dropped before may pass now
|
|
1019
|
+
got.append((s, copies.enter_context(sources.Since(
|
|
1020
|
+
s, None if reset else id_cur, None if reset else t_cur)), stat))
|
|
1021
|
+
except Exception as e: # one bad source never stops the others
|
|
1022
|
+
_failed(s, e, report, progress)
|
|
1023
|
+
phase(1, len(srcs), len(srcs))
|
|
1024
|
+
olds = legacy.get("cursors") or {}
|
|
1025
|
+
total, done, seen = sum(g[1].total for g in got), 0, {}
|
|
1026
|
+
for s, rd, stat in got:
|
|
1027
|
+
old = olds.get(s.key)
|
|
1028
|
+
quiet = sources.to_time(s.browser, old).timestamp() if isinstance(old, int) else None
|
|
1029
|
+
tell(f"{s.key}: saving {rd.total} visits")
|
|
1030
|
+
read = new = 0
|
|
1031
|
+
try:
|
|
1032
|
+
for chunk in rd.chunks(store.CHUNK):
|
|
1033
|
+
c = store.ingest(con, chunk, settings, tz, quiet_until=quiet, seen=seen)
|
|
1034
|
+
# the cursor follows each chunk (rows come oldest first, so every row
|
|
1035
|
+
# before it is saved), without the file's stat: a stop goes on from here
|
|
1036
|
+
with con:
|
|
1037
|
+
store.set_cursor(con, s.key, rd.top_id, rd.top_time, None, now)
|
|
1038
|
+
read += len(chunk)
|
|
1039
|
+
new += c["new"]
|
|
1040
|
+
report["dropped"] += c["dropped"]
|
|
1041
|
+
phase(2, min(done + read, total), total)
|
|
1042
|
+
if pause:
|
|
1043
|
+
time.sleep(pause)
|
|
1044
|
+
with con:
|
|
1045
|
+
store.set_cursor(con, s.key, rd.top_id, rd.top_time, stat, now)
|
|
1046
|
+
except Exception as e: # what was saved stays, and the cursor with it
|
|
1047
|
+
_failed(s, e, report, progress)
|
|
1048
|
+
continue
|
|
1049
|
+
finally:
|
|
1050
|
+
done += rd.total
|
|
1051
|
+
report["sources"] += 1
|
|
1052
|
+
report["visits_new"] += new
|
|
1053
|
+
if progress:
|
|
1054
|
+
progress(s.key, read, new, None)
|
|
1055
|
+
cursors[s.key] = _state_row(store.cursor(con, s.key)[1], ran, stat)
|
|
1056
|
+
if legacy.get("archive"): # the archive's days were imported before
|
|
1057
|
+
store.ingest_files(con, vault, settings, tz, [ARCHIVE], quiet_until=float("inf"))
|
|
1058
|
+
legacy["archive"] = False
|
|
1059
|
+
with con:
|
|
1060
|
+
store.set_meta(con, "legacy", legacy)
|
|
1061
|
+
c = store.ingest_files(con, vault, settings, tz, [".keepfold/browse", ARCHIVE])
|
|
1062
|
+
report["dropped"] += c["dropped"]
|
|
1063
|
+
# read whole into the store (its stat saved): its oldest days, partly expired since the
|
|
1064
|
+
# old import, keep their pages
|
|
1065
|
+
whole = [k for k in olds if store.cursor(con, k)[2] is not None]
|
|
1066
|
+
if whole:
|
|
1067
|
+
oldest = {k: [d] for k in whole if (d := con.execute(
|
|
1068
|
+
"SELECT MIN(day) FROM visits WHERE source = ?", (k,)).fetchone()[0])}
|
|
1069
|
+
expiring = local_day(now - timedelta(days=EXPIRING_DAYS), tz)
|
|
1070
|
+
part = store.first_fill_partial(oldest, sites.stored_days(vault), expiring)
|
|
1071
|
+
legacy["cursors"] = {k: v for k, v in olds.items() if k not in whole}
|
|
1072
|
+
with con:
|
|
1073
|
+
store.set_meta(con, "partial", sorted(store.partial(con) | set(part)))
|
|
1074
|
+
store.set_meta(con, "legacy", legacy)
|
|
1075
|
+
if takeout:
|
|
1076
|
+
for v in takeout:
|
|
1077
|
+
v.native = store.native_of(v.start.isoformat(), v.url, v.title, v.source)
|
|
1078
|
+
c = store.ingest(con, takeout, settings, tz)
|
|
1079
|
+
have = store.browsing_days(con)
|
|
1080
|
+
report["takeout"] = sum(1 for v in takeout if local_day(v.start, tz) not in have)
|
|
1081
|
+
report["dropped"] += c["dropped"]
|
|
1082
|
+
phase(2, total, total)
|
|
1083
|
+
return cursors
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
def _failed(s: sources.Source, e: Exception, report: Counter, progress) -> None:
|
|
1087
|
+
log.warning("browse: %s not read: %s", s.key, type(e).__name__)
|
|
1088
|
+
report["sources_failed"] += 1
|
|
1089
|
+
if progress:
|
|
1090
|
+
progress(s.key, 0, 0, e)
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def _batches(con, todo: set[str]) -> list[list[str]]:
|
|
1094
|
+
"""`todo`, newest first, in runs of days holding about RENDER_VISITS visits."""
|
|
1095
|
+
from keepfold.browse import store
|
|
1096
|
+
|
|
1097
|
+
size = store.by_day(con, todo)
|
|
1098
|
+
out: list[list[str]] = [[]]
|
|
1099
|
+
n = 0
|
|
1100
|
+
for d in sorted(todo, reverse=True):
|
|
1101
|
+
if out[-1] and n + size.get(d, 0) > RENDER_VISITS:
|
|
1102
|
+
out.append([])
|
|
1103
|
+
n = 0
|
|
1104
|
+
out[-1].append(d)
|
|
1105
|
+
n += size.get(d, 0)
|
|
1106
|
+
return out
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _render(vault: Vault, con, todo: set[str], settings: Settings, *, embed, runner, budget,
|
|
1110
|
+
tz, dry_run: bool, ask: bool, keep_local: bool, summaries: bool, report: Counter,
|
|
1111
|
+
tell, phase, pause: float = 0.0):
|
|
1112
|
+
"""Phases 3 and 4 of `run` for the days `todo`, in runs of days of about RENDER_VISITS
|
|
1113
|
+
visits (`_batches`, newest first: memory stays bounded however long the history): 3 the
|
|
1114
|
+
texts of every run with no verdict yet, then the local model's verdicts on them; 4 each
|
|
1115
|
+
run's pages. Returns (site counts, the name a torn counts file went to, whether a new skip
|
|
1116
|
+
verdict purged anything); in a dry run, the number of days."""
|
|
1117
|
+
from keepfold.browse import store
|
|
1118
|
+
|
|
1119
|
+
vis = settings.visible_to_claude
|
|
1120
|
+
local = local_only(runner)
|
|
1121
|
+
batches = _batches(con, todo)
|
|
1122
|
+
tell(f"filtering: the visits of {len(todo)} days")
|
|
1123
|
+
phase(3, 0, 1)
|
|
1124
|
+
had = sites.load_verdicts(vault)
|
|
1125
|
+
verdicts = dict(had)
|
|
1126
|
+
need: dict[str, str] = {}
|
|
1127
|
+
if local is not None and ask:
|
|
1128
|
+
for b in batches:
|
|
1129
|
+
_unvetted(store.items(con, set(b), settings)[0], verdicts, need)
|
|
1130
|
+
tell(f"local model: checking {len(need)} titles and searches")
|
|
1131
|
+
report.update(_ask(vault, need, local, budget, verdicts, save=not dry_run, con=con,
|
|
1132
|
+
step=lambda d, t: phase(3, d, t)))
|
|
1133
|
+
# a text the model now files under a Don't-save category may sit on a day this run does
|
|
1134
|
+
# not make (kept unvetted before): every store loses it now
|
|
1135
|
+
skip = frozenset(v for h, v in verdicts.items()
|
|
1136
|
+
if had.get(h) != v and privacy.audience(v, settings) == "skip")
|
|
1137
|
+
if skip and not dry_run:
|
|
1138
|
+
report.update({f"refiltered_{k}": n for k, n in forget.purge(
|
|
1139
|
+
vault, forget.Rule(cats=skip), write=False).items()})
|
|
1140
|
+
with con: # the site pages and vectors it owes outlive a stop
|
|
1141
|
+
store.set_meta(con, "refilter", True)
|
|
1142
|
+
phase(3, 1, 1)
|
|
1143
|
+
phase(4, 0, len(todo))
|
|
1144
|
+
if embed is not None:
|
|
1145
|
+
tell("topics: reading the topic hubs")
|
|
1146
|
+
hub_ids, unit, titles = (hubs(vault, embed, save=not dry_run) if embed is not None
|
|
1147
|
+
else ([], None, {}))
|
|
1148
|
+
bad, touched = None, set()
|
|
1149
|
+
report["days_from"] = _monday(min(todo)) # type: ignore[assignment]
|
|
1150
|
+
asks = runner if summaries else None
|
|
1151
|
+
tell(f"topics: placing the visits of {len(todo)} days under {len(hub_ids)} topic hubs")
|
|
1152
|
+
if not dry_run:
|
|
1153
|
+
tell(f"sites: counting the visits of {len(todo)} days by site")
|
|
1154
|
+
last, done = 0.0, 0
|
|
1155
|
+
for b in batches:
|
|
1156
|
+
items, c = store.items(con, set(b), settings)
|
|
1157
|
+
report.update(c)
|
|
1158
|
+
items = _apply(items, verdicts, settings, local is not None if keep_local is None
|
|
1159
|
+
else keep_local, report)
|
|
1160
|
+
# its progress lines at most every PROGRESS_S, however many runs
|
|
1161
|
+
where = place(items, embed, hub_ids, unit,
|
|
1162
|
+
tell if time.monotonic() - last >= PROGRESS_S else None)
|
|
1163
|
+
by_day: dict[str, list[Item]] = {d: [] for d in b}
|
|
1164
|
+
for i in items:
|
|
1165
|
+
report["kept" if public(i, where) else "private"] += 1
|
|
1166
|
+
by_day.setdefault(i.day, []).append(i)
|
|
1167
|
+
if dry_run:
|
|
1168
|
+
for its in by_day.values():
|
|
1169
|
+
report["private_would"] += bool(its)
|
|
1170
|
+
report["public_would"] += bool(vis and _hub_rows(its, where))
|
|
1171
|
+
report["empty_would"] += not its
|
|
1172
|
+
continue
|
|
1173
|
+
# this run's days only: the sites they held or hold now are the ones made again
|
|
1174
|
+
days, was = sites.load_days(vault, only_days=set(b))
|
|
1175
|
+
bad = bad or was
|
|
1176
|
+
touched.update(sites._key_site(k) for keys in days.values() for k in keys)
|
|
1177
|
+
days = sites.record(vault, items, where, settings, tz, "", set(by_day), days,
|
|
1178
|
+
save=False)
|
|
1179
|
+
touched.update(sites._key_site(k) for keys in days.values() for k in keys)
|
|
1180
|
+
if vis:
|
|
1181
|
+
report["signals"] += signals(vault, items, where, titles, tz, con, set(by_day))
|
|
1182
|
+
for day in b: # the newest first
|
|
1183
|
+
for side, what in write_day(vault, day, by_day[day], where, titles, asks, budget,
|
|
1184
|
+
tz, visible=vis).items():
|
|
1185
|
+
report[f"{side}_{what}"] += 1
|
|
1186
|
+
if keep_local and by_day[day]: # its local-model lines are made once it is here
|
|
1187
|
+
store.mark_unsummarised(con, [day], local_only(asks) is None
|
|
1188
|
+
or (budget is not None and not budget.ok()))
|
|
1189
|
+
done += 1
|
|
1190
|
+
phase(4, done, len(todo))
|
|
1191
|
+
if time.monotonic() - last >= PROGRESS_S:
|
|
1192
|
+
tell(f"day pages: {done} of {len(todo)} days")
|
|
1193
|
+
last = time.monotonic()
|
|
1194
|
+
# a day is clean once its pages and its site counts are saved: a stop goes on there
|
|
1195
|
+
sites.save_days(vault, days, settings)
|
|
1196
|
+
store.clean(con, b)
|
|
1197
|
+
if pause:
|
|
1198
|
+
time.sleep(pause)
|
|
1199
|
+
if dry_run:
|
|
1200
|
+
return len(todo)
|
|
1201
|
+
report.setdefault("signals", 0)
|
|
1202
|
+
return touched, bad, bool(skip)
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
# bump when the filter's rules change, so stored browsing is re-filtered and every day the
|
|
1206
|
+
# browsers still hold is rebuilt once (3: per-browser counts and Don't-save by the site's
|
|
1207
|
+
# category, 0.2.3)
|
|
1208
|
+
FILTER_VERSION = 3
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def fingerprint(settings: Settings) -> str:
|
|
1212
|
+
"""A hash of the settings (and FILTER_VERSION) that decide what a public page may hold."""
|
|
1213
|
+
return hashlib.sha256(json.dumps([
|
|
1214
|
+
FILTER_VERSION, settings.visible_to_claude, sorted(settings.hidden_from_claude),
|
|
1215
|
+
sorted(settings.skip_categories), settings.private, settings.deny, settings.allow
|
|
1216
|
+
]).encode()).hexdigest()[:16]
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
def _void_signals(vault: Vault) -> int:
|
|
1220
|
+
"""Q12: browsing went hidden from Claude, so void every live browse touch and take the
|
|
1221
|
+
browse lines out of the journal pages. How many touches were voided."""
|
|
1222
|
+
evlog = EventLog(vault)
|
|
1223
|
+
ids = [e["id"] for e in live(evlog.iter_events())
|
|
1224
|
+
if str(e.get("key") or "").startswith("browse:touch:")]
|
|
1225
|
+
for i in ids:
|
|
1226
|
+
void_event(evlog, session="cli", event_id=i, reason="browsing hidden from Claude",
|
|
1227
|
+
source="imported")
|
|
1228
|
+
for p in vault.note_paths("journal"):
|
|
1229
|
+
if _JOURNAL_LINE.search(p.read_bytes().decode("utf-8", "replace")):
|
|
1230
|
+
vault._mutate(p, lambda text: _JOURNAL_LINE.sub("", text))
|
|
1231
|
+
return len(ids)
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
def _drop_public(vault: Vault, held: set[str] | str | None) -> int:
|
|
1235
|
+
"""Remove the public day pages of the days no source holds (None: every one; "": none),
|
|
1236
|
+
the ones a run cannot rebuild after the visibility rules changed. How many went."""
|
|
1237
|
+
if held == "":
|
|
1238
|
+
return 0
|
|
1239
|
+
gone = 0
|
|
1240
|
+
for p in sorted((vault.root / DIR).glob("browse-*.md")):
|
|
1241
|
+
if (m := _DAY_FILE.match(p.name)) and (held is None or m.group(1) not in held):
|
|
1242
|
+
gone += vault.remove(p)
|
|
1243
|
+
return gone
|
|
1244
|
+
|
|
1245
|
+
|
|
1246
|
+
def _archive_consumed(vault: Vault, stats: dict[str, list[int]], settings: Settings
|
|
1247
|
+
) -> dict[str, list[int]]:
|
|
1248
|
+
"""Move each inbox file this run read whole and that is unchanged since, whatever its
|
|
1249
|
+
date (C16), into ARCHIVE (C5), so a later rebuild of its day still has the visits only
|
|
1250
|
+
the extension saw. Its records are filtered again on the way (the settings of now): a
|
|
1251
|
+
dropped one goes, a private one keeps no excerpt. The stats of the files that stay."""
|
|
1252
|
+
left = dict(stats)
|
|
1253
|
+
with vault.lock(): # the receiver appended under the same lock (before 0.3.2)
|
|
1254
|
+
for name, st in stats.items():
|
|
1255
|
+
p = vault.root / ".keepfold" / "browse" / name
|
|
1256
|
+
try:
|
|
1257
|
+
same = [p.stat().st_size, p.stat().st_mtime_ns] == st
|
|
1258
|
+
lines = p.read_bytes().decode("utf-8", "replace").splitlines()
|
|
1259
|
+
except OSError:
|
|
1260
|
+
continue
|
|
1261
|
+
if not same:
|
|
1262
|
+
continue
|
|
1263
|
+
keep = []
|
|
1264
|
+
for line in lines:
|
|
1265
|
+
try:
|
|
1266
|
+
r = json.loads(line)
|
|
1267
|
+
k = privacy.filter_record(str(r["url"]), str(r.get("title") or ""),
|
|
1268
|
+
settings=settings,
|
|
1269
|
+
channel=str(r.get("channel") or ""))
|
|
1270
|
+
except (ValueError, TypeError, KeyError):
|
|
1271
|
+
continue
|
|
1272
|
+
if k is None:
|
|
1273
|
+
continue
|
|
1274
|
+
if k.private and r.get("excerpt"):
|
|
1275
|
+
r["excerpt"] = ""
|
|
1276
|
+
keep.append(json.dumps(r, ensure_ascii=False))
|
|
1277
|
+
if keep:
|
|
1278
|
+
a = vault.root / ARCHIVE / name
|
|
1279
|
+
old = a.read_bytes().decode("utf-8", "replace") if a.is_file() else ""
|
|
1280
|
+
vault.write_text(a, old + "".join(f"{ln}\n" for ln in keep))
|
|
1281
|
+
vault.remove(p)
|
|
1282
|
+
del left[name]
|
|
1283
|
+
return left
|
|
1284
|
+
|
|
1285
|
+
|
|
1286
|
+
def _prune_archive(vault: Vault, horizon: str) -> int:
|
|
1287
|
+
"""Delete the archived inbox files of days before `horizon` (the oldest day the browsers'
|
|
1288
|
+
History holds, or ARCHIVE_DAYS ago when that is older; a day of zone slack). How many
|
|
1289
|
+
went."""
|
|
1290
|
+
cut = (date.fromisoformat(horizon) - timedelta(days=1)).isoformat()
|
|
1291
|
+
gone = 0
|
|
1292
|
+
for p in sorted((vault.root / ARCHIVE).glob("inbox-*.jsonl")):
|
|
1293
|
+
m = re.search(r"\d{4}-\d{2}-\d{2}", p.name)
|
|
1294
|
+
if m and m.group(0) < cut:
|
|
1295
|
+
gone += vault.remove(p)
|
|
1296
|
+
return gone
|
|
1297
|
+
|
|
1298
|
+
|
|
1299
|
+
def status(vault: Vault, tz: tzinfo | None = None, *, visible: bool = False) -> list[str]:
|
|
1300
|
+
"""`keepfold browse status` lines: the mode, last run, last run and cursor per source, the
|
|
1301
|
+
local LLM used."""
|
|
1302
|
+
s = load_state(vault)
|
|
1303
|
+
mode = ("visible to Claude: yes (public day pages, index and interest lines)" if visible
|
|
1304
|
+
else "visible to Claude: no (private pages only; browse.visible_to_claude)")
|
|
1305
|
+
if not s.get("last_run"):
|
|
1306
|
+
return [mode, "never imported; run `keepfold browse selftest`, `keepfold browse scan`, "
|
|
1307
|
+
"then `keepfold browse import`"]
|
|
1308
|
+
out = [mode, f"last run: {s['last_run']}",
|
|
1309
|
+
f"local LLM: {s.get('llm') or 'none (rules and embeddings only)'}",
|
|
1310
|
+
f"embeddings: {'yes' if s.get('embedder') else 'no (sections by site)'}"]
|
|
1311
|
+
if s.get("pending"):
|
|
1312
|
+
out.append(f"a source failed last time; the next import rebuilds from {s['pending']}")
|
|
1313
|
+
for key, row in sorted((s.get("sources") or {}).items()):
|
|
1314
|
+
row = row if isinstance(row, dict) else {}
|
|
1315
|
+
cur = row.get("cursor")
|
|
1316
|
+
when = (sources.to_time(key.split("/", 1)[0], cur).astimezone(tz)
|
|
1317
|
+
.strftime("%Y-%m-%d %H:%M") if isinstance(cur, int) else "none")
|
|
1318
|
+
out.append(f"{key}: up to {when}, last read {row.get('ran') or 'unknown'}")
|
|
1319
|
+
out.append(f"extension inbox files: {len(s.get('inbox') or {})}")
|
|
1320
|
+
return out
|