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/home.py
ADDED
|
@@ -0,0 +1,714 @@
|
|
|
1
|
+
"""The app's live home (v8): the dashboard blob plus `feed`, `next_up` and `exams`, kept
|
|
2
|
+
between requests by one HomeCache per app server and sent to the page as deltas.
|
|
3
|
+
|
|
4
|
+
`version(vault)` stamps what the home reads, from directory listings only (no file is opened):
|
|
5
|
+
- events/<year>/<month>/*.jsonl: each file's name, size and mtime;
|
|
6
|
+
- each kind folder's *.md: each file's name, size and mtime; under browse/ its subfolders too,
|
|
7
|
+
except browse/private/ (never read) and browse/sites/<category>/ (whole-vault walks skip the
|
|
8
|
+
site pages);
|
|
9
|
+
- catalog.yaml, inbox.md, .keepfold/brain-layout.json, .keepfold/vectors.db and its -wal, and
|
|
10
|
+
.keepfold/recall-log.jsonl: size and mtime;
|
|
11
|
+
- the browsing store, .keepfold/browse/store.db and its -wal: size and mtime (the brain's stem of
|
|
12
|
+
websites; `store.version`);
|
|
13
|
+
- the Keepfold day (04:00 local), so Today rolls over.
|
|
14
|
+
Left out: the time of day (an exam forecast moves with it and is refreshed with any other
|
|
15
|
+
change), the search index snapshot (a parse shortcut with the same content) and the shipped
|
|
16
|
+
help text. A file rewritten within one mtime tick at the same size is seen at its next change.
|
|
17
|
+
The stamp is a hash of these listings, valid within one process (the app server's).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import base64
|
|
23
|
+
import logging
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
import sqlite3
|
|
27
|
+
import statistics
|
|
28
|
+
import threading
|
|
29
|
+
from collections import OrderedDict
|
|
30
|
+
from datetime import UTC, date, datetime, time, timedelta
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
|
|
35
|
+
from keepfold import brainmap, dashboard, planner, recall_log, semantic, topics
|
|
36
|
+
from keepfold.access import Audience, audience_of_note, audience_of_study, may_see
|
|
37
|
+
from keepfold.browse import store
|
|
38
|
+
from keepfold.catalog import CATALOG
|
|
39
|
+
from keepfold.events import DAY_ROLLOVER, STUDY_MODES, live, local_day
|
|
40
|
+
from keepfold.render import plain, term
|
|
41
|
+
from keepfold.vault import ID_RE, PRIVATE_BROWSE_DIR, Vault, VaultError, is_private, parse_error
|
|
42
|
+
|
|
43
|
+
log = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
FILES = {"catalog": CATALOG, "inbox": "inbox.md", "layout": brainmap.LAYOUT,
|
|
46
|
+
"vectors": semantic.CACHE, "vectors_wal": semantic.CACHE + "-wal", # saves land here
|
|
47
|
+
"recall": recall_log.FILE}
|
|
48
|
+
WEEK_DAYS = 7 # Today plus the six days before it
|
|
49
|
+
FEED_CAP = 200 # items in each of Today and This week
|
|
50
|
+
PER_GROUP = 20 # items of one kind for one subject on one day (an import adds hundreds)
|
|
51
|
+
NEXT_SUBJECTS, NEXT_ITEMS = 8, 5
|
|
52
|
+
KEEP_MIN = 3 # concepts with a stability a subject needs before its sharp line shows a number
|
|
53
|
+
KEEP = 5 # homes kept per Private setting, for deltas
|
|
54
|
+
# the brain stem's websites: the STEM_TOP most visited, then up to STEM_RECENT more visited in
|
|
55
|
+
# the last STEM_DAYS days (the rest stay in the browsing store; the legend says how many)
|
|
56
|
+
STEM_TOP, STEM_RECENT, STEM_DAYS = 1500, 1000, 30
|
|
57
|
+
SITE_LIST = 50 # searches of each kind a site's details carry
|
|
58
|
+
_JOURNAL = re.compile(r"^- (\d\d:\d\d|—) (.+)$") # as vault.append_journal writes them
|
|
59
|
+
_NOT_ADDED = {"journal", "browse", "session", "rollup"} # their own items say more than "added"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ---- the version stamp ---------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
def _md(folder: str) -> list:
|
|
65
|
+
"""(name, mtime_ns, size) of the *.md entries directly in `folder`, as glob("*.md") finds
|
|
66
|
+
them, in directory order. DirEntry.stat comes with the listing on Windows: no call per file."""
|
|
67
|
+
try:
|
|
68
|
+
with os.scandir(folder) as it:
|
|
69
|
+
return [(e.name, (st := e.stat()).st_mtime_ns, st.st_size) for e in it
|
|
70
|
+
if e.name.endswith(".md")]
|
|
71
|
+
except OSError:
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _kind_md(root: str, kind: str) -> list:
|
|
76
|
+
"""(vault-relative path, mtime_ns, size) of a kind's *.md pages in all its folders
|
|
77
|
+
(Vault.dirs: an archived chat page in archive/chats/ too)."""
|
|
78
|
+
return [(os.path.join(*d.split("/"), n), m, s) for d in Vault.dirs(kind)
|
|
79
|
+
for n, m, s in _md(os.path.join(root, *d.split("/")))]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _browse(root: str) -> list:
|
|
83
|
+
"""browse/'s *.md files at any depth (paths relative to it), except under browse/private/
|
|
84
|
+
and the site pages in browse/sites/<category>/."""
|
|
85
|
+
base = os.path.join(root, Vault.KIND_DIRS["browse"])
|
|
86
|
+
private = os.path.normcase(os.path.join(root, *PRIVATE_BROWSE_DIR.split("/")))
|
|
87
|
+
sites = os.path.normcase(os.path.join(base, "sites"))
|
|
88
|
+
out, todo = [], [""]
|
|
89
|
+
while todo:
|
|
90
|
+
rel = todo.pop()
|
|
91
|
+
folder = os.path.join(base, rel)
|
|
92
|
+
try:
|
|
93
|
+
with os.scandir(folder) as it:
|
|
94
|
+
entries = list(it)
|
|
95
|
+
except OSError:
|
|
96
|
+
continue
|
|
97
|
+
in_sites = os.path.normcase(folder) == sites # its subfolders hold the site pages
|
|
98
|
+
for e in entries:
|
|
99
|
+
if e.is_dir():
|
|
100
|
+
if not in_sites and os.path.normcase(e.path) != private:
|
|
101
|
+
todo.append(os.path.join(rel, e.name))
|
|
102
|
+
elif e.name.endswith(".md"):
|
|
103
|
+
st = e.stat()
|
|
104
|
+
out.append((os.path.join(rel, e.name), st.st_mtime_ns, st.st_size))
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _events(root: str) -> list:
|
|
109
|
+
"""(year/month/name, mtime_ns, size) of events/*/*/*.jsonl, as EventLog globs them."""
|
|
110
|
+
out = []
|
|
111
|
+
ev = os.path.join(root, "events")
|
|
112
|
+
for y in _names(ev, dirs=True):
|
|
113
|
+
for m in _names(os.path.join(ev, y), dirs=True):
|
|
114
|
+
try:
|
|
115
|
+
with os.scandir(os.path.join(ev, y, m)) as it:
|
|
116
|
+
for e in it:
|
|
117
|
+
if e.name.endswith(".jsonl") and not e.name.startswith("."):
|
|
118
|
+
st = e.stat()
|
|
119
|
+
out.append((f"{y}/{m}/{e.name}", st.st_mtime_ns, st.st_size))
|
|
120
|
+
except OSError:
|
|
121
|
+
continue
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _names(folder: str, dirs: bool) -> list[str]:
|
|
126
|
+
try:
|
|
127
|
+
with os.scandir(folder) as it:
|
|
128
|
+
return [e.name for e in it if not e.name.startswith(".") and e.is_dir() == dirs]
|
|
129
|
+
except OSError:
|
|
130
|
+
return []
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _stat(path: str) -> tuple[int, int] | None:
|
|
134
|
+
try:
|
|
135
|
+
st = os.stat(path)
|
|
136
|
+
except OSError:
|
|
137
|
+
return None
|
|
138
|
+
return st.st_mtime_ns, st.st_size
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _scan(root: Path, day: str) -> dict:
|
|
142
|
+
"""The listings `version` hashes: {"events", "notes": {kind: files}, FILES..., "day"}, in
|
|
143
|
+
directory order (stable while a folder is unchanged)."""
|
|
144
|
+
r = str(root)
|
|
145
|
+
notes = {kind: tuple(_browse(r) if kind == "browse" else _kind_md(r, kind))
|
|
146
|
+
for kind in Vault.KIND_DIRS}
|
|
147
|
+
db = os.path.join(r, *store.PATH.split("/"))
|
|
148
|
+
return {"events": tuple(_events(r)), "notes": notes,
|
|
149
|
+
**{k: _stat(os.path.join(r, *f.split("/"))) for k, f in FILES.items()},
|
|
150
|
+
"browse": (_stat(db), _stat(db + "-wal")), "day": day}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _hash(scan: dict) -> str:
|
|
154
|
+
key = tuple((k, tuple(v.items()) if isinstance(v, dict) else v) for k, v in scan.items())
|
|
155
|
+
return format(hash(key) & 0xFFFF_FFFF_FFFF_FFFF, "016x")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def version(vault: Vault, now: datetime | None = None) -> str:
|
|
159
|
+
"""A cheap stamp of everything the home reads (see the module doc)."""
|
|
160
|
+
return _hash(_scan(vault.root, local_day(now or datetime.now(UTC))))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ---- the cache -----------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
class _Served:
|
|
166
|
+
"""The vault for one build: `iter_notes` serves the cache's notes; the rest is the vault's."""
|
|
167
|
+
|
|
168
|
+
def __init__(self, vault: Vault, notes: dict[str, list]):
|
|
169
|
+
self._vault, self._served, self.root = vault, notes, vault.root
|
|
170
|
+
|
|
171
|
+
def __getattr__(self, name):
|
|
172
|
+
return getattr(self._vault, name)
|
|
173
|
+
|
|
174
|
+
def iter_notes(self, kind: str | None = None):
|
|
175
|
+
if kind is not None and kind not in self._served:
|
|
176
|
+
raise VaultError("invalid_argument", f"Unknown kind '{kind}'.")
|
|
177
|
+
return iter(self._served[kind] if kind else
|
|
178
|
+
[n for k in Vault.KIND_DIRS for n in self._served[k]])
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class HomeCache:
|
|
182
|
+
"""The home for one vault, rebuilt only in the parts whose files changed: unchanged notes
|
|
183
|
+
keep their parsed objects (and so their page rows), the brain is laid out again only when
|
|
184
|
+
the notes, vectors or layout changed and never relaid by itself, and the feed alone follows
|
|
185
|
+
the recall log. Keeps the last KEEP homes per Private setting for `delta`. Thread-safe: one
|
|
186
|
+
build at a time."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, vault: Vault, clock=None):
|
|
189
|
+
self.vault = vault
|
|
190
|
+
self._clock = clock or (lambda: datetime.now(UTC))
|
|
191
|
+
self._lock = threading.Lock()
|
|
192
|
+
# kind -> (its listing, {relpath: ((mtime_ns, size), Note)}, its notes in order)
|
|
193
|
+
self._notes: dict[str, tuple] = {}
|
|
194
|
+
self._memo: dict = {} # dashboard.build_data's
|
|
195
|
+
self._scan: dict | None = None
|
|
196
|
+
self._data: dict | None = None
|
|
197
|
+
self._items: list[dict] = [] # the feed, every audience
|
|
198
|
+
self._homes = {False: OrderedDict(), True: OrderedDict()}
|
|
199
|
+
# the stem's placement, in memory only (no file holds a site name): {site: (first,
|
|
200
|
+
# share of the axis)}; and per Private setting (stamp, page brain, brain with the stem)
|
|
201
|
+
self._placed: dict = {}
|
|
202
|
+
self._stems: dict = {}
|
|
203
|
+
|
|
204
|
+
def version(self) -> str:
|
|
205
|
+
return version(self.vault, self._clock())
|
|
206
|
+
|
|
207
|
+
def get(self, private: bool = False) -> dict:
|
|
208
|
+
"""The whole home: build_data's keys, `feed`, `next_up`, `exams` and its version `v`."""
|
|
209
|
+
with self._lock:
|
|
210
|
+
return self._current(private)
|
|
211
|
+
|
|
212
|
+
def delta(self, since: str | None, private: bool = False) -> dict:
|
|
213
|
+
"""What changed since version `since`: {"v", "full": false, "sections": {name: value}}
|
|
214
|
+
with "pages" ({"upsert": rows, "removed": ids}) and "brain" ({"blob", "added",
|
|
215
|
+
"removed", "changed"}) only when they changed. An unknown `since` gets
|
|
216
|
+
{"full": true, ...the whole home}."""
|
|
217
|
+
with self._lock:
|
|
218
|
+
new = self._current(private)
|
|
219
|
+
old = self._homes[private].get(since) if since else None
|
|
220
|
+
if old is None:
|
|
221
|
+
return {**new, "full": True}
|
|
222
|
+
out = {"v": new["v"], "full": False, "sections": {
|
|
223
|
+
k: v for k, v in new.items() if k not in ("v", "pages", "brain")
|
|
224
|
+
and (k not in old or (old[k] is not v and old[k] != v))}}
|
|
225
|
+
if old["pages"] is not new["pages"]:
|
|
226
|
+
was = {p["id"]: p for p in old["pages"]}
|
|
227
|
+
ids = {p["id"] for p in new["pages"]}
|
|
228
|
+
up = [p for p in new["pages"] if (q := was.get(p["id"])) is not p and q != p]
|
|
229
|
+
gone = [i for i in was if i not in ids]
|
|
230
|
+
if up or gone or [p["id"] for p in old["pages"]] != [p["id"] for p in new["pages"]]:
|
|
231
|
+
out["pages"] = {"upsert": up, "removed": gone,
|
|
232
|
+
"order": [p["id"] for p in new["pages"]]}
|
|
233
|
+
if old["brain"] is not new["brain"]:
|
|
234
|
+
out["brain"] = {"blob": new["brain"], **_brain_diff(old["brain"], new["brain"])}
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
def site(self, site: str, private: bool = False) -> dict | None:
|
|
238
|
+
"""One website's details for the brain's side panel, from the browsing store (never a
|
|
239
|
+
vault page): None when the store has no such site for this Private setting, so a
|
|
240
|
+
private site is unknown while the switch is locked. Its topic hubs only as pages the
|
|
241
|
+
home shows."""
|
|
242
|
+
try:
|
|
243
|
+
rows = store.site_rows(self.vault, include_private=private)
|
|
244
|
+
r = next((x for x in rows if x["site"] == site), None)
|
|
245
|
+
if r is None:
|
|
246
|
+
return None
|
|
247
|
+
open_ = not private or any(x["site"] == site for x in store.site_rows(self.vault))
|
|
248
|
+
except sqlite3.Error as e:
|
|
249
|
+
log.warning("browsing store not read: %s", type(e).__name__)
|
|
250
|
+
return None
|
|
251
|
+
with self._lock:
|
|
252
|
+
titles = {p["id"]: p["title"] for p in (self._data or {}).get("pages", [])}
|
|
253
|
+
|
|
254
|
+
def text(x):
|
|
255
|
+
return " ".join(term(x).split())[:300]
|
|
256
|
+
return {"site": r["site"], "category": r["category"] or "other", "private": not open_,
|
|
257
|
+
"visits": r["visits"], "secs": r["secs"], "days": r["days"],
|
|
258
|
+
"titles": [text(t) for t in r["titles"]],
|
|
259
|
+
"searches": [[text(t), n] for t, n in r["searches"][:SITE_LIST]],
|
|
260
|
+
"led": [[text(t), n] for t, n in r["led"][:SITE_LIST]],
|
|
261
|
+
"hubs": [{"id": h, "title": titles[h], "visits": n} for h, n in r["hubs"]
|
|
262
|
+
if h in titles],
|
|
263
|
+
"related": list(r["related"]), "description": text(r["description"])}
|
|
264
|
+
|
|
265
|
+
# ---- building ----
|
|
266
|
+
|
|
267
|
+
def _stem(self, scan: dict, private: bool) -> dict:
|
|
268
|
+
"""The page brain with the browsing store's websites as its stem (`brainmap.with_stem`)
|
|
269
|
+
for one Private setting: locked, only the visible side of the store is read
|
|
270
|
+
(`include_private=False`); unlocked, every site, those with no visible side marked
|
|
271
|
+
private. The same object while nothing it shows changed; the page brain itself when
|
|
272
|
+
the store holds no site."""
|
|
273
|
+
brain = self._data["brain"]
|
|
274
|
+
key = (scan["browse"], scan["day"])
|
|
275
|
+
hit = self._stems.get(private)
|
|
276
|
+
if hit is not None and hit[0] == key and hit[1] is brain:
|
|
277
|
+
return hit[2]
|
|
278
|
+
try:
|
|
279
|
+
pub = store.site_rows(self.vault)
|
|
280
|
+
rows = store.site_rows(self.vault, include_private=True) if private else pub
|
|
281
|
+
except sqlite3.Error as e: # the home goes on without the stem
|
|
282
|
+
log.warning("browsing store not read: %s", type(e).__name__)
|
|
283
|
+
pub = rows = []
|
|
284
|
+
out = brain
|
|
285
|
+
if rows:
|
|
286
|
+
cut = (date.fromisoformat(scan["day"]) - timedelta(days=STEM_DAYS)).isoformat()
|
|
287
|
+
shown = rows[:STEM_TOP] + sorted(
|
|
288
|
+
(r for r in rows[STEM_TOP:] if r["days"] and r["days"][-1] >= cut),
|
|
289
|
+
key=lambda r: (r["days"][-1], r["site"]), reverse=True)[:STEM_RECENT]
|
|
290
|
+
brainmap.stem_order(pub, self._placed) # the visible sites first: never placed by
|
|
291
|
+
brainmap.stem_order(shown, self._placed) # where private ones are
|
|
292
|
+
open_ = {r["site"] for r in pub}
|
|
293
|
+
sites = sorted(({**r, "first_day": (r["days"] or [""])[0],
|
|
294
|
+
"last_day": (r["days"] or [""])[-1], "private": r["site"] not in open_}
|
|
295
|
+
for r in shown), key=lambda r: (self._placed[r["site"]][1], r["site"]))
|
|
296
|
+
out = brainmap.with_stem(brain, sites, self._placed, len(rows))
|
|
297
|
+
if hit is not None and hit[1] is brain and hit[2] == out:
|
|
298
|
+
out = hit[2] # only the store's file moved: no brain change to send
|
|
299
|
+
self._stems[private] = (key, brain, out)
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
def _current(self, private: bool) -> dict:
|
|
303
|
+
now = self._clock()
|
|
304
|
+
scan = _scan(self.vault.root, local_day(now))
|
|
305
|
+
v = _hash(scan)
|
|
306
|
+
homes = self._homes[private]
|
|
307
|
+
if v in homes:
|
|
308
|
+
homes.move_to_end(v)
|
|
309
|
+
return homes[v]
|
|
310
|
+
if scan != self._scan:
|
|
311
|
+
self._build(scan, now)
|
|
312
|
+
# the build may have written the layout: stamp what it wrote, so the next poll
|
|
313
|
+
# does not see a change of its own making
|
|
314
|
+
wrote = self._memo.get("brain", {}).get("layout")
|
|
315
|
+
if wrote and wrote[0] == _stat(str(self.vault.root / brainmap.LAYOUT)) \
|
|
316
|
+
and wrote[0] != scan["layout"]:
|
|
317
|
+
scan = {**scan, "layout": wrote[0]}
|
|
318
|
+
v = _hash(scan)
|
|
319
|
+
self._scan = scan
|
|
320
|
+
home = {**self._data, "brain": self._stem(scan, private),
|
|
321
|
+
"feed": _split(self._items, scan["day"], private), "v": v}
|
|
322
|
+
homes[v] = home
|
|
323
|
+
while len(homes) > KEEP:
|
|
324
|
+
homes.popitem(last=False)
|
|
325
|
+
return home
|
|
326
|
+
|
|
327
|
+
def _build(self, scan: dict, now: datetime) -> None:
|
|
328
|
+
old = self._scan or {}
|
|
329
|
+
learn = ("events", "notes", "catalog", "inbox", "day")
|
|
330
|
+
served = _Served(self.vault, self._load(scan["notes"]))
|
|
331
|
+
if self._data is None or any(scan[k] != old.get(k) for k in learn):
|
|
332
|
+
data = dashboard.build_data(served, now=now, auto_relayout=False, memo=self._memo)
|
|
333
|
+
parts = self._memo["parts"]
|
|
334
|
+
self._data = {**data, "next_up": _next_up(data, parts, scan["day"]),
|
|
335
|
+
"exams": [a for a in data["assessments"] if a["date"]],
|
|
336
|
+
"cold_check": bool(cold_due(parts["states"], parts["catalog"],
|
|
337
|
+
parts["hidden"], scan["day"]))}
|
|
338
|
+
elif any(scan[k] != old.get(k) for k in ("vectors", "vectors_wal", "layout")):
|
|
339
|
+
self._data = {**self._data, "brain": brainmap.build(
|
|
340
|
+
served, self._data["pages"], self._data["clusters"], auto_relayout=False,
|
|
341
|
+
memo=self._memo.setdefault("brain", {}))}
|
|
342
|
+
if any(scan[k] != old.get(k) for k in (*learn, "recall")):
|
|
343
|
+
self._items = _feed(self.vault, self._data, self._memo["parts"], scan["day"])
|
|
344
|
+
|
|
345
|
+
def _load(self, listing: dict) -> dict[str, list]:
|
|
346
|
+
"""Each kind's notes in iter_notes order; a file whose (mtime, size) is unchanged keeps
|
|
347
|
+
its Note object, and an unchanged folder its list. Many to parse (the first build):
|
|
348
|
+
through the search index snapshot."""
|
|
349
|
+
miss = 0
|
|
350
|
+
for kind, files in listing.items():
|
|
351
|
+
had = self._notes.get(kind)
|
|
352
|
+
if had is None or had[0] != files:
|
|
353
|
+
miss += sum(1 for f in files if (got := (had or (0, {}))[1].get(f[0])) is None
|
|
354
|
+
or got[0] != f[1:])
|
|
355
|
+
if miss > 50:
|
|
356
|
+
with dashboard._snapshot_parses(self.vault):
|
|
357
|
+
return self._parse(listing)
|
|
358
|
+
return self._parse(listing)
|
|
359
|
+
|
|
360
|
+
def _parse(self, listing: dict) -> dict[str, list]:
|
|
361
|
+
root, keep = self.vault.root, {}
|
|
362
|
+
for kind, files in listing.items():
|
|
363
|
+
had = self._notes.get(kind)
|
|
364
|
+
if had is not None and had[0] == files:
|
|
365
|
+
keep[kind] = had
|
|
366
|
+
continue
|
|
367
|
+
# _browse paths are browse/-relative, _kind_md ones vault-relative
|
|
368
|
+
d = Vault.KIND_DIRS[kind] if kind == "browse" else ""
|
|
369
|
+
ns, old, by = [], (had or (0, {}))[1], {}
|
|
370
|
+
for rel, mtime, size in sorted(files, key=lambda f: os.path.normcase(f[0]).split(
|
|
371
|
+
os.sep)): # iter_notes' order
|
|
372
|
+
got = old.get(rel)
|
|
373
|
+
if got is None or got[0] != (mtime, size):
|
|
374
|
+
if not ID_RE.fullmatch(os.path.basename(rel)[:-3]):
|
|
375
|
+
continue
|
|
376
|
+
try:
|
|
377
|
+
n = self.vault._parse(root / d / rel, kind)
|
|
378
|
+
except Exception as e: # noqa: BLE001 as iter_notes: skip, never fail
|
|
379
|
+
log.warning("skipping %s: %s", rel, parse_error(e))
|
|
380
|
+
continue
|
|
381
|
+
n.fields = dict(n.fields) # only read here; a dict reads ~8x faster
|
|
382
|
+
got = ((mtime, size), n)
|
|
383
|
+
by[rel] = got
|
|
384
|
+
ns.append(got[1])
|
|
385
|
+
keep[kind] = (files, by, ns)
|
|
386
|
+
self._notes = keep
|
|
387
|
+
return {kind: k[2] for kind, k in keep.items()}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ---- feed, next up -------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
def _split(items: list[dict], day: str, private: bool) -> dict:
|
|
393
|
+
"""Today and This week for one Private setting: grouped by subject (the group of the
|
|
394
|
+
newest item first), newest first in a group, FEED_CAP each."""
|
|
395
|
+
seen = [i for i in items if may_see("app_home", i["_aud"], i["_access"],
|
|
396
|
+
private_flag=private)]
|
|
397
|
+
out = {}
|
|
398
|
+
for name, keep in (("today", lambda d: d == day), ("week", lambda d: d < day)):
|
|
399
|
+
got = [i for i in seen if keep(i["day"])][:FEED_CAP]
|
|
400
|
+
rank: dict = {}
|
|
401
|
+
for i in got:
|
|
402
|
+
rank.setdefault((i["subject"] or {}).get("id"), len(rank))
|
|
403
|
+
got.sort(key=lambda i: rank[(i["subject"] or {}).get("id")]) # stable
|
|
404
|
+
out[name] = [{k: v for k, v in i.items() if not k.startswith("_")} for i in got]
|
|
405
|
+
return out
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class _Lookup:
|
|
409
|
+
"""Titles, subjects (brain lobes) and audiences of page and catalog ids."""
|
|
410
|
+
|
|
411
|
+
def __init__(self, data: dict, parts: dict):
|
|
412
|
+
self.catalog, self.hidden = parts["catalog"], parts["hidden"]
|
|
413
|
+
self.notes = {}
|
|
414
|
+
for ns in parts["notes"].values():
|
|
415
|
+
for n in ns:
|
|
416
|
+
self.notes.setdefault(n.id, n)
|
|
417
|
+
self.lobe = {p["id"]: p["cluster"] for p in data["pages"]}
|
|
418
|
+
self.ltitle = {c["id"]: c["title"] for c in data["clusters"]}
|
|
419
|
+
|
|
420
|
+
def title(self, i: str) -> str:
|
|
421
|
+
if (e := self.catalog.entries.get(i)) is not None:
|
|
422
|
+
return plain(e.title) or i
|
|
423
|
+
n = self.notes.get(i)
|
|
424
|
+
return dashboard._title(n) if n is not None else i
|
|
425
|
+
|
|
426
|
+
def subject(self, i: str | None) -> dict | None:
|
|
427
|
+
lobe = self.lobe.get(i) if i else None
|
|
428
|
+
if lobe is None and i and (e := self.catalog.entries.get(i)) is not None and e.domain:
|
|
429
|
+
lobe = f"domain:{e.domain}"
|
|
430
|
+
if lobe is None:
|
|
431
|
+
return None
|
|
432
|
+
d = self.catalog.entries.get(lobe.removeprefix("domain:"))
|
|
433
|
+
return {"id": lobe, "title": self.ltitle.get(lobe)
|
|
434
|
+
or (plain(d.title) if d is not None and lobe.startswith("domain:") else lobe)}
|
|
435
|
+
|
|
436
|
+
def audience(self, i: str | None) -> Audience:
|
|
437
|
+
if not i:
|
|
438
|
+
return Audience.CLOUD
|
|
439
|
+
n = self.notes.get(i)
|
|
440
|
+
if i in self.catalog.entries:
|
|
441
|
+
return audience_of_study([i], self.hidden, note_private=n is not None
|
|
442
|
+
and is_private(n))
|
|
443
|
+
return audience_of_note(n, self.hidden) if n is not None else Audience.CLOUD
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _ts(day: str, hhmm: str | None) -> str:
|
|
447
|
+
"""A local Keepfold-day time as UTC 'YYYY-MM-DDTHH:MM:SSZ'; no time: the day's start."""
|
|
448
|
+
d = date.fromisoformat(day)
|
|
449
|
+
if hhmm:
|
|
450
|
+
t = time(int(hhmm[:2]), int(hhmm[3:5]))
|
|
451
|
+
at = datetime.combine(d + timedelta(days=t < time(4)), t) # 01:30 ends the day before
|
|
452
|
+
else:
|
|
453
|
+
at = datetime.combine(d, time()) + DAY_ROLLOVER
|
|
454
|
+
return at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _obj(e: dict) -> str | None:
|
|
458
|
+
o = e.get("object")
|
|
459
|
+
return o.split(":", 1)[1] if isinstance(o, str) and ":" in o else None
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _feed(vault: Vault, data: dict, parts: dict, day: str) -> list[dict]:
|
|
463
|
+
"""Every feed item of the last WEEK_DAYS days, newest first, each with its audience."""
|
|
464
|
+
look = _Lookup(data, parts)
|
|
465
|
+
start = (date.fromisoformat(day) - timedelta(days=WEEK_DAYS - 1)).isoformat()
|
|
466
|
+
evs = live(parts["events"])
|
|
467
|
+
items: list[dict] = []
|
|
468
|
+
|
|
469
|
+
def add(ts, d, kind, i, title, detail="", access="note", aud=None, timed=True):
|
|
470
|
+
items.append({"ts": ts, "day": d, "timed": timed, "kind": kind, "subject": look.subject(i),
|
|
471
|
+
"title": plain(title, 200), "detail": plain(detail, 300), "id": i,
|
|
472
|
+
"_aud": aud or look.audience(i), "_access": access})
|
|
473
|
+
|
|
474
|
+
graded: dict[str, str] = {} # object id -> its last grade's ts
|
|
475
|
+
answered = set()
|
|
476
|
+
for e in evs:
|
|
477
|
+
if e.get("kind") == "grade" and (o := _obj(e)):
|
|
478
|
+
graded[o] = max(graded.get(o, ""), e["ts"])
|
|
479
|
+
answered.add(e.get("ref"))
|
|
480
|
+
quiz: dict[tuple, dict] = {}
|
|
481
|
+
sessions: dict[str, dict] = {}
|
|
482
|
+
added = set()
|
|
483
|
+
for e in evs:
|
|
484
|
+
d, kind, o = str(e.get("day", "")), e.get("kind"), _obj(e)
|
|
485
|
+
if d < start:
|
|
486
|
+
continue
|
|
487
|
+
p = e.get("payload") if isinstance(e.get("payload"), dict) else {}
|
|
488
|
+
pk = p.get("kind") if kind == "log" else None
|
|
489
|
+
if kind == "grade" or pk == "self_report":
|
|
490
|
+
o = o or p.get("concept")
|
|
491
|
+
verdict = e.get("verdict") if kind == "grade" else p.get("verdict")
|
|
492
|
+
if o and verdict in ("correct", "partial", "wrong"):
|
|
493
|
+
q = quiz.setdefault((d, o), {"ts": "", "correct": 0, "partial": 0, "wrong": 0})
|
|
494
|
+
q["ts"] = max(q["ts"], e["ts"])
|
|
495
|
+
q[verdict] += 1
|
|
496
|
+
elif kind == "ask" and o and e.get("id") not in answered:
|
|
497
|
+
add(e["ts"], d, "ask", o, look.title(o), str(e.get("question") or ""), "study")
|
|
498
|
+
elif kind == "taught" and o and graded.get(o, "") < e["ts"]:
|
|
499
|
+
add(e["ts"], d, "taught", o, look.title(o),
|
|
500
|
+
str(p.get("summary") or "Taught, not yet tested"), "study")
|
|
501
|
+
elif kind in ("open", "close") and e.get("session"):
|
|
502
|
+
sessions.setdefault(e["session"], {})[kind] = e
|
|
503
|
+
elif kind == "change" and p.get("note") == "added" and isinstance(p.get("change"), dict):
|
|
504
|
+
c = p["change"]
|
|
505
|
+
i = str(c.get("id") or "")
|
|
506
|
+
if i and i in look.notes and i not in added:
|
|
507
|
+
added.add(i)
|
|
508
|
+
src = topics.page_source(look.notes[i].body).lower()
|
|
509
|
+
add(e["ts"], d, "chat" if src in dashboard.CHATS else "added", i, look.title(i),
|
|
510
|
+
str(c.get("kind") or ""), "chat" if src in dashboard.CHATS else "note")
|
|
511
|
+
elif pk == "problem_status" and (i := str(p.get("problem") or o or "")):
|
|
512
|
+
add(e["ts"], d, "problem", i, look.title(i), str(p.get("status") or ""), "study")
|
|
513
|
+
elif pk == "assessment_result" and (i := str(p.get("assessment") or o or "")):
|
|
514
|
+
add(e["ts"], d, "result", i, look.title(i),
|
|
515
|
+
" ".join(str(p[k]) for k in ("outcome", "score") if p.get(k) is not None),
|
|
516
|
+
"study")
|
|
517
|
+
elif pk == "chat_saved" and p.get("auto"): # the automatic chat import: each page as
|
|
518
|
+
for i in p.get("pages") or []: # an added one, on the day it came in, once
|
|
519
|
+
if isinstance(i, str) and i in look.notes and i not in added:
|
|
520
|
+
added.add(i)
|
|
521
|
+
add(e["ts"], d, "chat", i, look.title(i), str(p.get("source") or ""), "chat")
|
|
522
|
+
elif pk in ("chat_saved", "chat_learned") and not p.get("auto"):
|
|
523
|
+
pages = [x for x in p.get("pages") or [] if isinstance(x, str)]
|
|
524
|
+
i = pages[0] if pages else None
|
|
525
|
+
add(e["ts"], d, "chat", i, str(p.get("title") or "Chat"), str(p.get("source") or ""),
|
|
526
|
+
"chat", Audience.LOCAL if any(look.audience(x) is not Audience.CLOUD
|
|
527
|
+
for x in pages) else Audience.CLOUD)
|
|
528
|
+
for (d, o), q in quiz.items():
|
|
529
|
+
n = q["correct"] + q["partial"] + q["wrong"]
|
|
530
|
+
add(q["ts"], d, "quiz", o, look.title(o),
|
|
531
|
+
f"{q['correct']} of {n} right" + (f", {q['partial']} partial" if q["partial"] else ""),
|
|
532
|
+
"study")
|
|
533
|
+
for s in sessions.values():
|
|
534
|
+
e = s.get("close") or s["open"]
|
|
535
|
+
mode = e.get("mode") or (s.get("open") or {}).get("mode")
|
|
536
|
+
add(e["ts"], str(e["day"]), "session", None,
|
|
537
|
+
"Study session" if mode in STUDY_MODES
|
|
538
|
+
else "Keepfold tidied lines about you" if mode == "tidy"
|
|
539
|
+
else "Keepfold saved lines about you from your chats" if mode == "harvest"
|
|
540
|
+
else "Chat session",
|
|
541
|
+
str((s.get("close") or {}).get("summary") or ""), "study", Audience.CLOUD)
|
|
542
|
+
try:
|
|
543
|
+
rows = recall_log.rows(vault)
|
|
544
|
+
except (OSError, UnicodeDecodeError) as e: # usage stats: the feed goes on without them
|
|
545
|
+
log.warning("recall log not read: %s", e)
|
|
546
|
+
rows = []
|
|
547
|
+
for row in rows:
|
|
548
|
+
q = row.get("query") if isinstance(row, dict) else None
|
|
549
|
+
if not isinstance(q, str) or not isinstance(row.get("ts"), str):
|
|
550
|
+
continue
|
|
551
|
+
try:
|
|
552
|
+
d = local_day(datetime.fromisoformat(row["ts"].replace("Z", "+00:00")))
|
|
553
|
+
except ValueError:
|
|
554
|
+
continue
|
|
555
|
+
if d < start:
|
|
556
|
+
continue
|
|
557
|
+
ids = [x for x in row.get("ids") or [] if isinstance(x, str)]
|
|
558
|
+
add(row["ts"], d, "research", ids[0] if ids else None, q, f"{len(ids)} pages found",
|
|
559
|
+
"note", Audience.LOCAL if any(look.audience(x) is not Audience.CLOUD for x in ids)
|
|
560
|
+
else Audience.CLOUD)
|
|
561
|
+
for n in parts["notes"]["journal"]:
|
|
562
|
+
if not start <= n.id <= day:
|
|
563
|
+
continue
|
|
564
|
+
for ln in n.body.splitlines():
|
|
565
|
+
if m := _JOURNAL.match(ln):
|
|
566
|
+
hhmm = m.group(1) if m.group(1) != "—" else None
|
|
567
|
+
add(_ts(n.id, hhmm), n.id, "journal", n.id, m.group(2), "", "note")
|
|
568
|
+
for i, n in look.notes.items(): # pages dated this week that no tool event added
|
|
569
|
+
if n.kind in _NOT_ADDED or i in added:
|
|
570
|
+
continue
|
|
571
|
+
d = topics.page_date(i, n.fields, n.body)
|
|
572
|
+
if start <= d <= day:
|
|
573
|
+
src = topics.page_source(n.body).lower()
|
|
574
|
+
add(_ts(d, None), d, "chat" if src in dashboard.CHATS else "added", i,
|
|
575
|
+
look.title(i), n.kind, "chat" if src in dashboard.CHATS else "note", timed=False)
|
|
576
|
+
items.sort(key=lambda i: i["ts"], reverse=True)
|
|
577
|
+
count: dict[tuple, int] = {}
|
|
578
|
+
out = []
|
|
579
|
+
for i in items:
|
|
580
|
+
k = (i["day"], i["kind"], (i["subject"] or {}).get("id"), i["_aud"])
|
|
581
|
+
count[k] = count.get(k, 0) + 1
|
|
582
|
+
if count[k] <= PER_GROUP:
|
|
583
|
+
out.append(i)
|
|
584
|
+
return out
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _next_up(data: dict, parts: dict, day: str) -> list[dict]:
|
|
588
|
+
"""Subjects by their latest activity, each with its next steps: the plan's items, then
|
|
589
|
+
the due reviews the plan had no room for; no dates. Private subjects are left out. Each
|
|
590
|
+
subject's `keep` is its stays-sharp line (`_keep`) over its shown concepts."""
|
|
591
|
+
look = _Lookup(data, parts)
|
|
592
|
+
states, hidden = parts["states"], parts["hidden"]
|
|
593
|
+
steps = []
|
|
594
|
+
for i in data["today"]:
|
|
595
|
+
why = "Due for review" if i["kind"] == "refresh" and i["why"].startswith("due ") \
|
|
596
|
+
else i["why"]
|
|
597
|
+
steps.append({**i, "why": why})
|
|
598
|
+
planned = {i["id"] for i in steps}
|
|
599
|
+
for c in sorted(states):
|
|
600
|
+
if c not in planned and c not in hidden and c in look.catalog.entries \
|
|
601
|
+
and look.audience(c) is Audience.CLOUD and planner.is_due(states[c], day):
|
|
602
|
+
steps.append({"kind": "review", "id": c, "title": look.title(c),
|
|
603
|
+
"state": states[c].state, "why": "Due for review"})
|
|
604
|
+
last: dict = {} # subject id -> its latest study event (taught, asked, graded, self-report)
|
|
605
|
+
for e in parts["events"]:
|
|
606
|
+
p = e.get("payload") if isinstance(e.get("payload"), dict) else {}
|
|
607
|
+
k = e.get("kind")
|
|
608
|
+
# a page edit or an AI app saving a note is not study: it must not reorder Next up
|
|
609
|
+
study = k in ("taught", "ask", "grade") or (k == "log" and p.get("kind") == "self_report")
|
|
610
|
+
if not study:
|
|
611
|
+
continue
|
|
612
|
+
i = _obj(e) or (str(p["concept"]) if p.get("concept") else None)
|
|
613
|
+
if i and (s := look.subject(i)):
|
|
614
|
+
last[s["id"]] = max(last.get(s["id"], ""), e.get("ts", ""))
|
|
615
|
+
sharp: dict = {} # subject id -> FSRS stabilities (days) of its shown concepts
|
|
616
|
+
for c, st in states.items():
|
|
617
|
+
if st.stability is not None and c not in hidden and c in look.catalog.entries \
|
|
618
|
+
and look.audience(c) is Audience.CLOUD and (subj := look.subject(c)):
|
|
619
|
+
sharp.setdefault(subj["id"], []).append(st.stability)
|
|
620
|
+
groups: dict = {}
|
|
621
|
+
for s in steps:
|
|
622
|
+
subj = look.subject(s["id"])
|
|
623
|
+
sid = (subj or {}).get("id")
|
|
624
|
+
g = groups.setdefault(sid, {"subject": subj, "items": [],
|
|
625
|
+
"keep": _keep(sharp.get(sid, [])) if subj else None})
|
|
626
|
+
if len(g["items"]) < NEXT_ITEMS:
|
|
627
|
+
g["items"].append(s)
|
|
628
|
+
order = sorted(groups.values(), key=lambda g: last.get((g["subject"] or {}).get("id"), ""),
|
|
629
|
+
reverse=True) # stable: subjects never touched keep the plan's order
|
|
630
|
+
return order[:NEXT_SUBJECTS]
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _keep(stabilities: list[float]) -> dict:
|
|
634
|
+
"""A subject's stays-sharp line: the median FSRS stability of its concepts, the days until
|
|
635
|
+
recall falls to 9 in 10 (R(S) = 0.9 by definition), or no number with fewer than KEEP_MIN
|
|
636
|
+
of them. `days` and `n` stay in the data; the page shows `text` only."""
|
|
637
|
+
n = len(stabilities)
|
|
638
|
+
if n < KEEP_MIN:
|
|
639
|
+
return {"n": n, "days": None, "text": "Not enough checks yet"}
|
|
640
|
+
d = statistics.median(stabilities)
|
|
641
|
+
if d < 1:
|
|
642
|
+
text = "Stays sharp under a day"
|
|
643
|
+
elif d < 14:
|
|
644
|
+
text = f"Stays sharp about {round(d)} day" + ("s" if round(d) != 1 else "")
|
|
645
|
+
elif d < 63:
|
|
646
|
+
text = f"Stays sharp about {round(d / 7)} weeks"
|
|
647
|
+
else:
|
|
648
|
+
text = f"Stays sharp about {round(d / 30)} months"
|
|
649
|
+
return {"n": n, "days": round(d, 1), "text": text}
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
# ---- the 90-second check -------------------------------------------------------------------
|
|
653
|
+
|
|
654
|
+
COLD_N = 3 # concepts in one 90-second check
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def cold_due(states: dict, catalog, hidden: set[str], day: str) -> list[str]:
|
|
658
|
+
"""Concepts the check may offer: cloud-visible, due today or tomorrow (planner.is_due),
|
|
659
|
+
most overdue (earliest next_due) first."""
|
|
660
|
+
tomorrow = (date.fromisoformat(day) + timedelta(days=1)).isoformat()
|
|
661
|
+
due = [c for c, st in states.items() if c in catalog.entries
|
|
662
|
+
and audience_of_study([c], hidden) is Audience.CLOUD and planner.is_due(st, tomorrow)]
|
|
663
|
+
return sorted(due, key=lambda c: (states[c].next_due or "", c))
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _summary(vault: Vault, cid: str) -> str | None:
|
|
667
|
+
"""A concept page's one line: its `summary`, else its first body line that is not a
|
|
668
|
+
heading; plain text (links, images and markup stripped)."""
|
|
669
|
+
try:
|
|
670
|
+
n = vault.read("concept", cid)
|
|
671
|
+
except VaultError:
|
|
672
|
+
return None
|
|
673
|
+
s = str(n.fields.get("summary") or "")
|
|
674
|
+
if not s.strip():
|
|
675
|
+
s = next((ln for ln in n.body.splitlines()
|
|
676
|
+
if ln.strip() and not ln.lstrip().startswith("#")), "")
|
|
677
|
+
s = s.strip().lstrip("-*+> ").strip()
|
|
678
|
+
return plain(s, 200) or None
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def cold_check(vault: Vault, now: datetime) -> list[dict]:
|
|
682
|
+
"""The 90-second check's items: up to COLD_N `cold_due` concepts with their titles and
|
|
683
|
+
one-line summaries. Never a private concept."""
|
|
684
|
+
from keepfold.catalog import Catalog
|
|
685
|
+
day = local_day(now)
|
|
686
|
+
catalog = Catalog.load(vault)
|
|
687
|
+
states, _ = planner.current_states(vault, day, catalog)
|
|
688
|
+
ids = cold_due(states, catalog, planner.hidden(vault, catalog), day)[:COLD_N]
|
|
689
|
+
return [{"id": c, "title": plain(catalog.entries[c].title) or c,
|
|
690
|
+
"summary": _summary(vault, c)} for c in ids]
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def _brain_diff(old: dict, new: dict) -> dict:
|
|
694
|
+
"""Node ids added, removed, and kept but moved or restyled (place, lobe, depth, embedded,
|
|
695
|
+
weight) between two brain blobs."""
|
|
696
|
+
def cols(b):
|
|
697
|
+
n = b["nodes"]
|
|
698
|
+
lobes = [x["id"] for x in b["lobes"]]
|
|
699
|
+
arr = {k: np.frombuffer(base64.b64decode(n[k]), t).reshape(-1, w)
|
|
700
|
+
for k, t, w in (("xyz", "<f4", 3), ("depth", "<f4", 1), ("embedded", "u1", 1),
|
|
701
|
+
("weight", "<f4", 1))}
|
|
702
|
+
lobe = np.frombuffer(base64.b64decode(n["lobe"]), "<u2") # 65535: a stem site, no lobe
|
|
703
|
+
return ({i: k for k, i in enumerate(n["ids"])}, arr,
|
|
704
|
+
[lobes[k] if k < len(lobes) else None for k in lobe.tolist()])
|
|
705
|
+
(oi, oa, ol), (ni, na, nl) = cols(old), cols(new)
|
|
706
|
+
both = [i for i in ni if i in oi]
|
|
707
|
+
a = np.array([oi[i] for i in both], np.int64)
|
|
708
|
+
b = np.array([ni[i] for i in both], np.int64)
|
|
709
|
+
moved = np.zeros(len(both), bool)
|
|
710
|
+
for k in oa:
|
|
711
|
+
if len(both):
|
|
712
|
+
moved |= (oa[k][a] != na[k][b]).any(1)
|
|
713
|
+
return {"added": [i for i in ni if i not in oi], "removed": [i for i in oi if i not in ni],
|
|
714
|
+
"changed": [i for k, i in enumerate(both) if moved[k] or ol[a[k]] != nl[b[k]]]}
|