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/app/status.py
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
"""Read-only checks behind the app's sections, and thin adapters to `keepfold.localllm` and the
|
|
2
|
+
browse code (both still growing: every call is guarded, so a missing function shows as "not
|
|
3
|
+
available yet"). Nothing here writes, and nothing from browsing leaves as text: only counts,
|
|
4
|
+
states, dates and the owner's own settings (`safe` filters the browse answers)."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import contextlib
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import plistlib
|
|
13
|
+
import re
|
|
14
|
+
import shlex
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from dataclasses import replace
|
|
21
|
+
from datetime import UTC, datetime, timedelta
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from keepfold.vault import VaultError, in_temp_folder
|
|
25
|
+
|
|
26
|
+
TEMP_VAULT = ("This vault is in a temporary folder. Windows can empty it at any time. "
|
|
27
|
+
"Use Change folder to pick your real vault.")
|
|
28
|
+
|
|
29
|
+
log = logging.getLogger(__name__)
|
|
30
|
+
LOGIN_TASK = "Keepfold browse receiver"
|
|
31
|
+
LOGIN_ID = "keepfold-browse-receiver" # LaunchAgent label, unit and .desktop name
|
|
32
|
+
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}(?:[T ][0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def config() -> dict:
|
|
36
|
+
from keepfold import taint
|
|
37
|
+
return taint.config()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def safe(d) -> dict:
|
|
41
|
+
"""Only numbers, booleans and date strings: what a browse answer may show the page."""
|
|
42
|
+
if not isinstance(d, dict):
|
|
43
|
+
return {}
|
|
44
|
+
return {str(k): v for k, v in d.items()
|
|
45
|
+
if isinstance(v, (bool, int, float)) or (isinstance(v, str) and _DATE.fullmatch(v))}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# The Status board's slow probes (HTTP to Ollama and LM Studio, `lms`: seconds together on
|
|
49
|
+
# Windows, where a refused loopback connect waits) are kept for KEEP_S: the first
|
|
50
|
+
# read waits, later ones answer at once and refresh a stale answer in the background. `forget`
|
|
51
|
+
# drops them all (any action, and Check again), so the next read waits for fresh answers.
|
|
52
|
+
KEEP_S = 30.0
|
|
53
|
+
_kept: dict = {} # key -> [monotonic time, answer, refreshing]
|
|
54
|
+
_kept_lock = threading.Lock()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def kept(key, fn):
|
|
58
|
+
"""`fn()`'s answer kept under `key` (see KEEP_S)."""
|
|
59
|
+
with _kept_lock:
|
|
60
|
+
hit = _kept.get(key)
|
|
61
|
+
if hit is not None:
|
|
62
|
+
if time.monotonic() - hit[0] > KEEP_S and not hit[2]:
|
|
63
|
+
hit[2] = True
|
|
64
|
+
threading.Thread(target=_refresh, args=(key, fn, hit), daemon=True).start()
|
|
65
|
+
return hit[1]
|
|
66
|
+
v = fn()
|
|
67
|
+
with _kept_lock:
|
|
68
|
+
_kept[key] = [time.monotonic(), v, False]
|
|
69
|
+
return v
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _refresh(key, fn, hit: list) -> None:
|
|
73
|
+
try:
|
|
74
|
+
v = fn()
|
|
75
|
+
except Exception: # noqa: BLE001 (the probes catch their own; a bug keeps the old answer)
|
|
76
|
+
log.exception("status probe refresh failed")
|
|
77
|
+
hit[2] = False
|
|
78
|
+
return
|
|
79
|
+
with _kept_lock:
|
|
80
|
+
if _kept.get(key) is hit: # not forgotten meanwhile
|
|
81
|
+
_kept[key] = [time.monotonic(), v, False]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def forget() -> None:
|
|
85
|
+
with _kept_lock:
|
|
86
|
+
_kept.clear()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def when(p: Path) -> str | None:
|
|
90
|
+
try:
|
|
91
|
+
return datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y-%m-%d %H:%M")
|
|
92
|
+
except OSError:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---- vault ----------------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def notes(root: Path) -> int:
|
|
100
|
+
"""Markdown pages in the vault, outside dot folders and browse/ (counted, never read)."""
|
|
101
|
+
n = 0
|
|
102
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
103
|
+
top = Path(dirpath) == root
|
|
104
|
+
dirnames[:] = [d for d in dirnames if not d.startswith(".") and not (top and d == "browse")]
|
|
105
|
+
n += sum(f.endswith(".md") for f in filenames)
|
|
106
|
+
return n
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def vault(root: Path | None) -> dict:
|
|
110
|
+
if root is None:
|
|
111
|
+
return {"path": None, "ok": False}
|
|
112
|
+
ok = (root / ".keepfold").is_dir()
|
|
113
|
+
return {"path": str(root), "ok": ok, "exists": root.is_dir(), "temp": in_temp_folder(root),
|
|
114
|
+
"notes": notes(root) if ok else 0,
|
|
115
|
+
"last_index": indexed(root),
|
|
116
|
+
"backups": len(list((root / ".keepfold" / "backups").glob("*.zip"))) if ok else 0,
|
|
117
|
+
"last_backup": max((when(p) or "" for p in (root / ".keepfold" / "backups")
|
|
118
|
+
.glob("*.zip")), default=None) if ok else None}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def indexed(root: Path) -> str | None:
|
|
122
|
+
"""When the notes were last indexed: the vector cache "Index my notes" writes. The one
|
|
123
|
+
answer Setup, Status and Dashboard and vault all show."""
|
|
124
|
+
from keepfold import semantic
|
|
125
|
+
p = root / semantic.CACHE # a save lands in its -wal first
|
|
126
|
+
return max(filter(None, (when(p), when(Path(f"{p}-wal")) if p.is_file() else None)),
|
|
127
|
+
default=None)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def embedding(root: Path | None = None) -> dict:
|
|
131
|
+
from keepfold import doctor, semantic
|
|
132
|
+
d = semantic.models_dir()
|
|
133
|
+
out = {"downloaded": doctor.search_model_ready(), "dir": str(d)}
|
|
134
|
+
if root is not None:
|
|
135
|
+
out["indexed"] = indexed(root)
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ---- local model (adapter to keepfold.localllm) -----------------------------------------------
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _llm_cfg() -> dict:
|
|
143
|
+
c = config().get("localllm")
|
|
144
|
+
return c if isinstance(c, dict) else {}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def ollama_models() -> list[str] | None:
|
|
148
|
+
"""Ollama's local model names (cloud ones left out), or None when it does not answer."""
|
|
149
|
+
try:
|
|
150
|
+
from keepfold import localllm
|
|
151
|
+
data = localllm._request("http://127.0.0.1:11434/api/tags", None, 0.5)
|
|
152
|
+
names = [r.get("name") for r in data.get("models", []) if isinstance(r, dict)]
|
|
153
|
+
return [n for n in names if isinstance(n, str) and not localllm._cloud(n)]
|
|
154
|
+
except (OSError, ValueError): # not running (refused, timeout) or not JSON
|
|
155
|
+
return None
|
|
156
|
+
except Exception: # noqa: BLE001 (a bug: logged, still "not available")
|
|
157
|
+
log.exception("Ollama check failed")
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def lms_path() -> str | None:
|
|
162
|
+
try:
|
|
163
|
+
from keepfold import localllm
|
|
164
|
+
exe = localllm._lms_exe(_llm_cfg())
|
|
165
|
+
return str(exe) if exe else None
|
|
166
|
+
except OSError:
|
|
167
|
+
return None
|
|
168
|
+
except Exception: # noqa: BLE001
|
|
169
|
+
log.exception("lms lookup failed")
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _lms_state() -> dict:
|
|
174
|
+
"""LM Studio's server port, loaded models and localllm's error, read-only."""
|
|
175
|
+
out = {"server_port": None, "loaded": [], "available": True, "error": None}
|
|
176
|
+
try:
|
|
177
|
+
from keepfold import localllm
|
|
178
|
+
got = localllm.status(lms=True) # read-only; "error": a cloud model or non-local url
|
|
179
|
+
st, out["error"] = got["lmstudio"], got["error"]
|
|
180
|
+
if st:
|
|
181
|
+
out["server_port"] = st.get("port")
|
|
182
|
+
out["loaded"] = [str(r.get("identifier") or r.get("modelKey"))
|
|
183
|
+
for r in st.get("loaded") or []]
|
|
184
|
+
except ImportError:
|
|
185
|
+
out["available"] = False
|
|
186
|
+
except (OSError, ValueError): # lms missing a command, a slow LM Studio
|
|
187
|
+
pass
|
|
188
|
+
except Exception: # noqa: BLE001
|
|
189
|
+
log.exception("LM Studio state check failed")
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def llm(quick: bool = False) -> dict:
|
|
194
|
+
"""The local model's settings and both runners' state; `quick`: the probes as `kept`."""
|
|
195
|
+
c = _llm_cfg()
|
|
196
|
+
key = json.dumps(c, sort_keys=True, default=str) # a settings change asks again
|
|
197
|
+
|
|
198
|
+
def probe(name, fn):
|
|
199
|
+
return kept((name, key), fn) if quick else fn()
|
|
200
|
+
return {"enabled": c.get("enabled") is True, "runner": c.get("runner") or "auto",
|
|
201
|
+
"model": c.get("model") or None,
|
|
202
|
+
"background_model": c.get("background_model") or None,
|
|
203
|
+
"lms": probe("lms", lms_path), "ollama": probe("ollama", ollama_models),
|
|
204
|
+
**probe("lms_state", _lms_state)}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def lms_models() -> list[dict]:
|
|
208
|
+
"""`lms ls`: the LLMs on this machine (never ones on another device)."""
|
|
209
|
+
try:
|
|
210
|
+
from keepfold import localllm
|
|
211
|
+
exe = localllm._lms_exe(_llm_cfg())
|
|
212
|
+
rows = localllm._rows(localllm._lms(exe, "ls", "--json")) if exe else []
|
|
213
|
+
except OSError:
|
|
214
|
+
return []
|
|
215
|
+
except Exception: # noqa: BLE001
|
|
216
|
+
log.exception("lms ls failed")
|
|
217
|
+
return []
|
|
218
|
+
return [{"key": str(r.get("modelKey")), "name": str(r.get("displayName") or r.get("modelKey")),
|
|
219
|
+
"size": r.get("sizeBytes") if isinstance(r.get("sizeBytes"), int) else None,
|
|
220
|
+
"params": str(r.get("paramsString") or "")}
|
|
221
|
+
for r in rows if r.get("modelKey") and r.get("type", "llm") == "llm"
|
|
222
|
+
and not r.get("deviceIdentifier")]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ---- browsing (adapter to keepfold.browse and keepfold.browse_serve): counts and states only ----
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def browse_settings() -> dict:
|
|
229
|
+
try:
|
|
230
|
+
from keepfold.browse import lists, load_settings
|
|
231
|
+
from keepfold.browse_serve import auto_import_hours
|
|
232
|
+
s = load_settings()
|
|
233
|
+
except (ImportError, OSError, ValueError): # no browse code, an unreadable config
|
|
234
|
+
return {"available": False}
|
|
235
|
+
except Exception: # noqa: BLE001
|
|
236
|
+
log.exception("browse settings failed")
|
|
237
|
+
return {"available": False}
|
|
238
|
+
from keepfold.browse.privacy import audience
|
|
239
|
+
return {"available": True, "visible_to_claude": s.visible_to_claude, "adult": s.adult,
|
|
240
|
+
"sensitive": s.sensitive, "deny": list(s.deny), "allow": list(s.allow),
|
|
241
|
+
"private": list(s.private), "categories": list(lists.CATEGORIES),
|
|
242
|
+
"hidden_from_claude": list(s.hidden_from_claude),
|
|
243
|
+
"skip_categories": list(s.skip_categories), "private_mcp": s.private_mcp,
|
|
244
|
+
"auto_import_hours": auto_import_hours(),
|
|
245
|
+
# per category as stored; with visible_to_claude off every kept one is local anyway
|
|
246
|
+
"audience": {c: audience(c, replace(s, visible_to_claude=True))
|
|
247
|
+
for c in lists.CATEGORIES}}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cloud(root: Path | None) -> dict:
|
|
251
|
+
"""The cloud-model settings (never the key: only whether its variable is set) and the last
|
|
252
|
+
runs from <vault>/.keepfold/cloud-log.jsonl, counts only."""
|
|
253
|
+
from keepfold import cloudllm
|
|
254
|
+
c = config().get("cloudllm")
|
|
255
|
+
c = c if isinstance(c, dict) else {}
|
|
256
|
+
b = config().get("browse")
|
|
257
|
+
env = c.get("api_key_env") if isinstance(c.get("api_key_env"), str) else None
|
|
258
|
+
runs = []
|
|
259
|
+
try:
|
|
260
|
+
lines = (root / cloudllm.LOG).read_text(encoding="utf-8").splitlines()[-10:] \
|
|
261
|
+
if root is not None else []
|
|
262
|
+
except OSError:
|
|
263
|
+
lines = []
|
|
264
|
+
for line in reversed(lines):
|
|
265
|
+
try:
|
|
266
|
+
r = json.loads(line)
|
|
267
|
+
except ValueError:
|
|
268
|
+
continue
|
|
269
|
+
if isinstance(r, dict):
|
|
270
|
+
runs.append({**safe({k: r.get(k) for k in ("ts", "items", "chars", "skipped")}),
|
|
271
|
+
**{k: str(r.get(k, ""))[:100] for k in ("provider", "model")}})
|
|
272
|
+
return {"cloud_processing": isinstance(b, dict) and b.get("cloud_processing") is True,
|
|
273
|
+
"provider": c.get("provider"), "model": c.get("model"),
|
|
274
|
+
"base_url": c.get("base_url"), "api_key_env": env,
|
|
275
|
+
"key_set": bool(env and os.environ.get(env, "").strip()),
|
|
276
|
+
"presets": list(cloudllm.PRESETS), "runs": runs}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def history(root: Path | None, scanned: dict) -> dict:
|
|
280
|
+
"""The browser profiles on this computer (found by file, never read here), with the counts
|
|
281
|
+
of the last scan: the "Import my past history" step."""
|
|
282
|
+
try:
|
|
283
|
+
from keepfold.browse import build, load_settings, sources
|
|
284
|
+
found = sources.discover()
|
|
285
|
+
skip = load_settings().skip_profiles
|
|
286
|
+
except (ImportError, OSError):
|
|
287
|
+
return {"available": False, "sources": [], "imported": None}
|
|
288
|
+
except Exception: # noqa: BLE001
|
|
289
|
+
log.exception("browser profile scan failed")
|
|
290
|
+
return {"available": False, "sources": [], "imported": None}
|
|
291
|
+
imported = None
|
|
292
|
+
if root is not None:
|
|
293
|
+
try:
|
|
294
|
+
from keepfold.vault import Vault
|
|
295
|
+
imported = safe({"t": build.load_state(Vault(root)).get("last_run")}).get("t")
|
|
296
|
+
except (OSError, ValueError, VaultError): # no vault or no state yet
|
|
297
|
+
pass
|
|
298
|
+
except Exception: # noqa: BLE001
|
|
299
|
+
log.exception("browse state read failed")
|
|
300
|
+
return {"available": True, "imported": imported, "scanned": bool(scanned),
|
|
301
|
+
"sources": [{"key": s.key, "browser": s.browser, "profile": s.profile,
|
|
302
|
+
"skip": s.key in skip, **safe(scanned.get(s.key, {}))}
|
|
303
|
+
for s in found]}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def imports(root: Path | None = None) -> dict:
|
|
307
|
+
"""Per guided-import source: what is imported so far, and when. Chats: conversations in
|
|
308
|
+
their folder (its time); notes: the resource pages the notes import names; calendar: the
|
|
309
|
+
event lines on its month pages (the newest page's time); docs, repos and highlights:
|
|
310
|
+
their pages."""
|
|
311
|
+
from keepfold import chats
|
|
312
|
+
out = {}
|
|
313
|
+
for source, (folder, _) in chats.EXPORT_DIRS.items():
|
|
314
|
+
d = chats.export_root() / folder
|
|
315
|
+
n = sum(1 for _ in d.glob("*.jsonl")) if d.is_dir() else 0
|
|
316
|
+
out[source] = {"count": n, "when": when(d) if n else None}
|
|
317
|
+
if root is not None:
|
|
318
|
+
from keepfold import importers
|
|
319
|
+
res = root / "resources"
|
|
320
|
+
notes = [p for k in importers.LABELS for p in res.glob(f"{k}-*.md")]
|
|
321
|
+
cal = list(res.glob("calendar-*.md"))
|
|
322
|
+
events = 0
|
|
323
|
+
for p in cal:
|
|
324
|
+
with contextlib.suppress(OSError):
|
|
325
|
+
events += sum(x.startswith("- ") for x in p.read_text("utf-8").splitlines())
|
|
326
|
+
more = {k: [p for g in globs for p in res.glob(g)] for k, globs in (
|
|
327
|
+
("docs", ("docs-*.md",)), ("repos", ("repo-*.md",)),
|
|
328
|
+
("highlights", ("highlights-*.md", "pocket-*.md")), ("mail", ("mail-*.md",)),
|
|
329
|
+
("selfchat", ("selfchat-*.md",)), ("location", ("location-*.md",)),
|
|
330
|
+
("photos", ("photos-*.md",)), ("spotify", ("listening-*.md",)),
|
|
331
|
+
("voice-memos", ("voice-*.md",)))}
|
|
332
|
+
for source, pages, n in (("notes", notes, len(notes)), ("calendar", cal, events),
|
|
333
|
+
*((k, ps, len(ps)) for k, ps in more.items())):
|
|
334
|
+
out[source] = {"count": n,
|
|
335
|
+
"when": max(when(p) or "" for p in pages) if n else None}
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def login_task() -> dict:
|
|
340
|
+
"""The entry that starts the receiver at login: a value under HKCU's Run key on Windows,
|
|
341
|
+
else the file `login_file()` names."""
|
|
342
|
+
if (f := login_file()) is not None:
|
|
343
|
+
return {"supported": True, "exists": f.is_file()}
|
|
344
|
+
return {"supported": True, "exists": run_get() is not None}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# Windows: HKCU ...\Run starts the no-console `keepfold-receiver` at login. It replaced a Task
|
|
348
|
+
# Scheduler entry (LOGIN_TASK) that opened a console and stopped on battery; `actions.login`
|
|
349
|
+
# and the uninstaller delete that old task. The desktop app's Start with Windows is another value
|
|
350
|
+
# under the same key (desktop.AUTOSTART).
|
|
351
|
+
RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def test_copy() -> bool:
|
|
355
|
+
"""Whether this Keepfold runs with a home folder that is not the signed-in user's profile (a
|
|
356
|
+
test, screenshot or demo copy with USERPROFILE moved to a temp folder): such a copy never
|
|
357
|
+
changes the Windows settings the real install owns (the Run values, Task Scheduler)."""
|
|
358
|
+
if sys.platform != "win32":
|
|
359
|
+
return False
|
|
360
|
+
try: # set by Windows at sign-in, whatever this process's environment says
|
|
361
|
+
import winreg
|
|
362
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Volatile Environment") as k:
|
|
363
|
+
real = winreg.QueryValueEx(k, "USERPROFILE")[0]
|
|
364
|
+
except (ImportError, OSError):
|
|
365
|
+
return False
|
|
366
|
+
return os.path.normcase(os.path.realpath(real)) != os.path.normcase(
|
|
367
|
+
os.path.realpath(Path.home()))
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _no_test_copy() -> None:
|
|
371
|
+
if test_copy():
|
|
372
|
+
raise OSError("this copy of Keepfold runs with a test home folder, so it leaves Windows' "
|
|
373
|
+
"start-up settings alone")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def run_get(name: str = LOGIN_TASK) -> str | None: # tests replace run_get/set/delete (conftest)
|
|
377
|
+
import winreg
|
|
378
|
+
try:
|
|
379
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
|
|
380
|
+
return winreg.QueryValueEx(k, name)[0]
|
|
381
|
+
except OSError:
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def run_set(value: str, name: str = LOGIN_TASK) -> None:
|
|
386
|
+
_no_test_copy()
|
|
387
|
+
import winreg
|
|
388
|
+
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
|
|
389
|
+
winreg.SetValueEx(k, name, 0, winreg.REG_SZ, value)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def run_delete(name: str = LOGIN_TASK) -> None:
|
|
393
|
+
_no_test_copy()
|
|
394
|
+
import winreg
|
|
395
|
+
try:
|
|
396
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY, 0, winreg.KEY_SET_VALUE) as k:
|
|
397
|
+
winreg.DeleteValue(k, name)
|
|
398
|
+
except FileNotFoundError:
|
|
399
|
+
pass
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def receiver_exe() -> str:
|
|
403
|
+
"""`keepfold-receiver.exe` (no console) beside `keepfold.exe`; the console `keepfold` when it is
|
|
404
|
+
missing (shortcut: a dev venv without the gui script; reinstall the tool to get it)."""
|
|
405
|
+
from keepfold import clients
|
|
406
|
+
keepfold = Path(clients.keepfold_command())
|
|
407
|
+
gui = keepfold.with_name("keepfold-receiver" + keepfold.suffix)
|
|
408
|
+
return str(gui) if gui.is_file() else str(keepfold)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def login_is_for(root: Path) -> bool:
|
|
412
|
+
"""Whether the entry that starts the receiver at login is the one this Keepfold made for
|
|
413
|
+
`root` (the same receiver and vault): only then may a vault move re-point it. Another
|
|
414
|
+
install's entry, or one a test copy of Keepfold did not make, is left alone."""
|
|
415
|
+
if (f := login_file()) is not None:
|
|
416
|
+
try:
|
|
417
|
+
return f.read_text(encoding="utf-8") == login_text(root)
|
|
418
|
+
except OSError:
|
|
419
|
+
return False
|
|
420
|
+
return run_get() == login_command(root)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def login_command(root: Path) -> str:
|
|
424
|
+
"""The Run value: the receiver for `root`, as `keepfold browse serve --vault <root>` runs."""
|
|
425
|
+
exe = receiver_exe()
|
|
426
|
+
serve = "" if Path(exe).stem == "keepfold-receiver" else " browse serve"
|
|
427
|
+
return f'"{exe}"{serve} --vault "{root}"'
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _systemd() -> bool: # tests replace this; sd_booted()'s own test
|
|
431
|
+
return Path("/run/systemd/system").is_dir()
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def login_file() -> Path | None:
|
|
435
|
+
"""Start at login outside Windows (None there): a macOS LaunchAgent, a systemd user unit,
|
|
436
|
+
or an XDG autostart entry when there is no systemd. Untested on a real Mac."""
|
|
437
|
+
if sys.platform == "win32":
|
|
438
|
+
return None
|
|
439
|
+
if sys.platform == "darwin":
|
|
440
|
+
return Path.home() / "Library" / "LaunchAgents" / f"{LOGIN_ID}.plist"
|
|
441
|
+
xdg = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
442
|
+
return (xdg / "systemd" / "user" / f"{LOGIN_ID}.service" if _systemd()
|
|
443
|
+
else xdg / "autostart" / f"{LOGIN_ID}.desktop")
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def login_text(root: Path) -> str:
|
|
447
|
+
"""`login_file()`'s content: it runs `keepfold browse serve --vault <root>` at login."""
|
|
448
|
+
from keepfold import clients
|
|
449
|
+
args = [clients.keepfold_command(), "browse", "serve", "--vault", str(root)]
|
|
450
|
+
if any(re.search(r"[\x00-\x1f\x7f]", a) for a in args): # a newline would add a directive
|
|
451
|
+
raise ValueError("Start at login is not offered for a vault path holding a line break "
|
|
452
|
+
"or another control character; move the vault to a plainer folder.")
|
|
453
|
+
kind = login_file().suffix
|
|
454
|
+
if kind == ".plist": # plistlib escapes &, < and > as XML
|
|
455
|
+
return plistlib.dumps({"Label": LOGIN_ID, "ProgramArguments": args,
|
|
456
|
+
"RunAtLoad": True}).decode("utf-8")
|
|
457
|
+
if kind == ".service": # systemd quoting: \ and " escaped, % and $ doubled (expansions)
|
|
458
|
+
cmd = " ".join('"' + a.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")
|
|
459
|
+
.replace("$", "$$") + '"' for a in args)
|
|
460
|
+
return (f"[Unit]\nDescription={LOGIN_TASK}\n\n[Service]\nExecStart={cmd}\n\n"
|
|
461
|
+
"[Install]\nWantedBy=default.target\n")
|
|
462
|
+
# Desktop Entry spec: \ " ` $ escaped inside quotes, then every \ doubled, % doubled
|
|
463
|
+
cmd = " ".join('"' + re.sub(r'([\\"`$])', r"\\\1", a).replace("\\", "\\\\")
|
|
464
|
+
.replace("%", "%%") + '"' for a in args)
|
|
465
|
+
return f"[Desktop Entry]\nType=Application\nName={LOGIN_TASK}\nExec={cmd}\nNoDisplay=true\n"
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def login_commands(on: bool) -> list[list[str]]:
|
|
469
|
+
"""What runs after `login_file()` is written (on) or before it is deleted (off)."""
|
|
470
|
+
f = login_file()
|
|
471
|
+
if f.suffix == ".plist":
|
|
472
|
+
return [["launchctl", "load" if on else "unload", "-w", str(f)]]
|
|
473
|
+
if f.suffix == ".service":
|
|
474
|
+
return ([["systemctl", "--user", "daemon-reload"]] if on else []) + [
|
|
475
|
+
["systemctl", "--user", "enable" if on else "disable", f.name]]
|
|
476
|
+
return []
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def login_shown(root: Path) -> str:
|
|
480
|
+
"""The exact command, or the file and its commands, the page shows before the click."""
|
|
481
|
+
if (f := login_file()) is None:
|
|
482
|
+
return f'Adds "{LOGIN_TASK}" under HKCU\\{RUN_KEY}:\n{login_command(root)}'
|
|
483
|
+
try:
|
|
484
|
+
text = login_text(root)
|
|
485
|
+
except ValueError as e:
|
|
486
|
+
return str(e)
|
|
487
|
+
return "\n".join([f"Writes {f}:", text.rstrip(),
|
|
488
|
+
*("Then runs: " + shlex.join(c) for c in login_commands(True))])
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def browse(root: Path | None) -> dict:
|
|
492
|
+
"""The Browsing section: settings, the last import and Start at login (the receiver that
|
|
493
|
+
imports in the background)."""
|
|
494
|
+
out = {"settings": browse_settings(), "last_processed": None, "login": login_task()}
|
|
495
|
+
try:
|
|
496
|
+
from keepfold import browse_serve # noqa: F401
|
|
497
|
+
except ImportError:
|
|
498
|
+
out["available"] = False
|
|
499
|
+
return out
|
|
500
|
+
except Exception: # noqa: BLE001
|
|
501
|
+
log.exception("browse receiver import failed")
|
|
502
|
+
out["available"] = False
|
|
503
|
+
return out
|
|
504
|
+
out["available"] = True
|
|
505
|
+
if root is None:
|
|
506
|
+
return out
|
|
507
|
+
try:
|
|
508
|
+
from keepfold.browse import build
|
|
509
|
+
from keepfold.vault import Vault
|
|
510
|
+
out["last_processed"] = safe({"t": build.load_state(Vault(root)).get("last_run")}
|
|
511
|
+
).get("t")
|
|
512
|
+
except (OSError, ValueError, VaultError):
|
|
513
|
+
pass
|
|
514
|
+
except Exception: # noqa: BLE001
|
|
515
|
+
log.exception("browse state read failed")
|
|
516
|
+
if out["login"].get("supported"):
|
|
517
|
+
out["login"]["command"] = login_shown(root)
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
# ---- the Status board ---------------------------------------------------------------------
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _go(section: str, label: str) -> dict:
|
|
525
|
+
return {"go": section, "label": label}
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def rows(root: Path | None) -> list[dict]:
|
|
529
|
+
"""One row per check: {id, label, state: ok|warn|off, value, detail, action}."""
|
|
530
|
+
v, out = vault(root), []
|
|
531
|
+
if not v["path"]:
|
|
532
|
+
out.append({"id": "vault", "label": "Vault", "state": "off", "value": "not set",
|
|
533
|
+
"detail": "Keepfold keeps your notes in a folder you choose.",
|
|
534
|
+
"action": _go("setup", "Set up")})
|
|
535
|
+
else:
|
|
536
|
+
hot = v["ok"] and v["temp"]
|
|
537
|
+
out.append({"id": "vault", "label": "Vault",
|
|
538
|
+
"state": "ok" if v["ok"] and not hot else "warn",
|
|
539
|
+
"value": v["path"], "count": v["notes"],
|
|
540
|
+
"detail": (TEMP_VAULT if hot else
|
|
541
|
+
f"Last indexed {v['last_index'] or 'not yet'}."
|
|
542
|
+
if v["ok"] else "This folder is not a Keepfold vault yet."),
|
|
543
|
+
"action": _go("vault", "Change folder") if hot else
|
|
544
|
+
None if v["ok"] else _go("setup", "Set up")})
|
|
545
|
+
if v["ok"] and (row := archive_row(root)):
|
|
546
|
+
out.append(row)
|
|
547
|
+
out.append(git_row())
|
|
548
|
+
e = embedding(root if v["ok"] else None)
|
|
549
|
+
out.append({"id": "embed", "label": "Search model", "state": "ok" if e["downloaded"] else "off",
|
|
550
|
+
"value": "downloaded" if e["downloaded"] else "not downloaded",
|
|
551
|
+
"detail": "Finds notes by meaning, not just matching words." if e["downloaded"]
|
|
552
|
+
else "Without it, search matches words only.",
|
|
553
|
+
"action": None if e["downloaded"] else _go("setup", "Download")})
|
|
554
|
+
from keepfold import clients
|
|
555
|
+
from keepfold.app import targets
|
|
556
|
+
# with a vault, the same describe(entry) (and cache key) as the server's /api/status uses,
|
|
557
|
+
# so `stale` (an entry naming another vault folder) costs nothing extra there
|
|
558
|
+
entry = clients.server_entry(clients.mcp_command(), root) if v["ok"] else None
|
|
559
|
+
ts = kept(("targets", json.dumps(entry, sort_keys=True) if entry else None),
|
|
560
|
+
lambda: targets.describe(entry))
|
|
561
|
+
on = [t["label"] for t in ts if t["connected"]]
|
|
562
|
+
out.append({"id": "apps", "label": "AI apps", "state": "ok" if on else "off",
|
|
563
|
+
"value": ", ".join(on) or "none connected",
|
|
564
|
+
"detail": "They read and record through Keepfold." if on else
|
|
565
|
+
"Without one, nothing reads or records anything.",
|
|
566
|
+
"action": _go("connect", "Open" if on else "Connect")})
|
|
567
|
+
if any(t["connected"] and t.get("stale") for t in ts):
|
|
568
|
+
out[-1].update(state="warn", detail="An AI app still uses your old vault folder. Open "
|
|
569
|
+
"Connect AI apps and click Apply.", action=_go("connect", "Open"))
|
|
570
|
+
if stale := targets.ClaudeDesktop().other_copy(): # uncached: Apply fixes it at once
|
|
571
|
+
out[-1].update(state="warn", value="Claude Desktop runs a different copy of Keepfold",
|
|
572
|
+
detail=f"{'; '.join(map(str, stale))} starts another keepfold than the "
|
|
573
|
+
"installed app, so its updates do not reach Claude Desktop. "
|
|
574
|
+
"Apply under Connect points it at the installed one (backup "
|
|
575
|
+
"beside the file); then quit Claude Desktop from the tray and "
|
|
576
|
+
"open it again.",
|
|
577
|
+
action=_go("connect", "Fix"))
|
|
578
|
+
if row := claude_code_row():
|
|
579
|
+
out.append(row)
|
|
580
|
+
out.append(llm_row())
|
|
581
|
+
b = browse(root if v["ok"] else None)
|
|
582
|
+
out.append(history_row(root if v["ok"] else None, b))
|
|
583
|
+
if (m := moved_row(root))["value"] != "nothing to move": # only for people who had Cortex
|
|
584
|
+
out.append(m)
|
|
585
|
+
return out
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def moved_row(root: Path | None) -> dict:
|
|
589
|
+
"""R3: the move from Cortex (keepfold.migrate.status): done, nothing to move, not moved yet
|
|
590
|
+
(an old Cortex holds files) or both folders exist (which one is used)."""
|
|
591
|
+
from keepfold import migrate
|
|
592
|
+
state, value, detail = migrate.status(root)
|
|
593
|
+
return {"id": "moved", "label": "Moved from Cortex", "state": state, "value": value,
|
|
594
|
+
"detail": detail or ("Your Cortex settings and vault folder now use the Keepfold "
|
|
595
|
+
"names." if value == "done" else "No Cortex folders here."),
|
|
596
|
+
"action": None}
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def keepfold_version(exe: str) -> str | None: # tests replace this: never a real exe
|
|
600
|
+
"""`<exe> --version`'s "keepfold X.Y.Z", else None (unknown)."""
|
|
601
|
+
from keepfold._proc import NO_WINDOW
|
|
602
|
+
try:
|
|
603
|
+
r = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=5,
|
|
604
|
+
stdin=subprocess.DEVNULL, creationflags=NO_WINDOW)
|
|
605
|
+
except (OSError, subprocess.SubprocessError):
|
|
606
|
+
return None
|
|
607
|
+
m = re.search(r"\bkeepfold (\d[\w.+-]*)", r.stdout or "")
|
|
608
|
+
return m.group(1) if m else None
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def claude_code_row() -> dict | None:
|
|
612
|
+
"""Claude Code starts the first `keepfold` on PATH (its plugin's MCP entry and hooks): a warn
|
|
613
|
+
row when that is another copy than the installed Keepfold, of another version; Fix puts the
|
|
614
|
+
installed bin folder first on the user PATH, unless the other copy's folder is on the
|
|
615
|
+
system PATH, which Windows reads first."""
|
|
616
|
+
from keepfold import clients, update
|
|
617
|
+
from keepfold.app import winpath
|
|
618
|
+
exe, found = clients.installed_keepfold(), shutil.which("keepfold")
|
|
619
|
+
if not exe or not found or Path(found).resolve() == exe.resolve():
|
|
620
|
+
return None
|
|
621
|
+
other = str(Path(found).resolve())
|
|
622
|
+
have = kept(("keepfold_version", other), lambda: keepfold_version(other))
|
|
623
|
+
app_v = update.current()
|
|
624
|
+
if have == app_v:
|
|
625
|
+
return None
|
|
626
|
+
try:
|
|
627
|
+
older = bool(have) and update.newer(update.parse_version(app_v), update.parse_version(have))
|
|
628
|
+
except update.UpdateError: # a dev or odd version: say "different", not "older"
|
|
629
|
+
older = False
|
|
630
|
+
row = {"id": "claude-code", "label": "Claude Code", "state": "warn", "action": None,
|
|
631
|
+
"value": (f"Claude Code runs Keepfold {have}, the app is {app_v}" if have else
|
|
632
|
+
f"Claude Code runs an unknown Keepfold version, the app is {app_v}")}
|
|
633
|
+
start = (f"Claude Code's hooks and tools start the first keepfold on your PATH ({found}), "
|
|
634
|
+
f"{'an older' if older else 'a different'} copy.")
|
|
635
|
+
folder = str(Path(found).parent)
|
|
636
|
+
if winpath.in_system(folder):
|
|
637
|
+
return {**row, "detail": f"{start} Its folder ({folder}) is on the system PATH, which "
|
|
638
|
+
"comes first, so Keepfold cannot fix this. Remove that folder "
|
|
639
|
+
"from the system PATH, or update that copy; then restart Claude."}
|
|
640
|
+
return {**row, "detail": f"{start} Fix puts the app's copy first; then restart Claude.",
|
|
641
|
+
"fix": {"post": "/api/connect/path", "label": "Fix"}}
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def archive_row(root: Path) -> dict | None:
|
|
645
|
+
"""R3-10: after the automatic chat archive move, one line: what moved and how to undo it
|
|
646
|
+
(chat_archive.last_move, from the marker the move writes); None before or after an undo."""
|
|
647
|
+
from keepfold import chat_archive
|
|
648
|
+
from keepfold.vault import Vault
|
|
649
|
+
m = chat_archive.last_move(Vault(root))
|
|
650
|
+
if m is None:
|
|
651
|
+
return None
|
|
652
|
+
n = m["count"]
|
|
653
|
+
return {"id": "archive", "label": "Chat archive", "state": "ok", "action": None,
|
|
654
|
+
"value": f"{n} chat page{'s' * (n != 1)} moved to {m['folder']} on {m['day']}",
|
|
655
|
+
"detail": f"Out of git, still searchable. To undo: run `{m['undo']}` in a terminal."}
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def git_row() -> dict:
|
|
659
|
+
"""Git keeps the vault's history (undo). Missing: the same Install Git as Setup's."""
|
|
660
|
+
from keepfold import session
|
|
661
|
+
from keepfold.app import wizard
|
|
662
|
+
row = {"id": "git", "label": "Git", "action": None}
|
|
663
|
+
if not session.git_choice()[0]:
|
|
664
|
+
return {**row, "state": "off", "value": "off in settings",
|
|
665
|
+
"detail": "Your choice: Keepfold keeps no history of the vault, so undo is off.",
|
|
666
|
+
"action": _go("vault", "Open")}
|
|
667
|
+
if session.git_exe():
|
|
668
|
+
return {**row, "state": "ok", "value": "installed",
|
|
669
|
+
"detail": "Keeps your vault's history, so undo works."}
|
|
670
|
+
plan = wizard.git_plan()
|
|
671
|
+
return {**row, "state": "off", "value": "not installed",
|
|
672
|
+
"detail": "Without git, Keepfold keeps no history of your vault, so undo does "
|
|
673
|
+
"nothing. Free.",
|
|
674
|
+
"install": {"label": f"Install Git ({plan['size']}, via {plan['source']})",
|
|
675
|
+
"license": plan["license"]} if plan["run"] else None,
|
|
676
|
+
"page": None if plan["run"] else plan["page"]}
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def llm_row() -> dict:
|
|
680
|
+
"""The configured runner by name, "ok" only when that runner holds the chosen model
|
|
681
|
+
(runner auto: whichever does)."""
|
|
682
|
+
from keepfold import localllm
|
|
683
|
+
m = llm(quick=True)
|
|
684
|
+
want = str(m["model"] or "")
|
|
685
|
+
loaded = [x for x in m["loaded"] if want and x.lower() == want.lower()]
|
|
686
|
+
in_ollama = bool(want and localllm._local_name(m["ollama"] or [], want))
|
|
687
|
+
if m["runner"] == "ollama":
|
|
688
|
+
name, ready, up = "Ollama", in_ollama, m["ollama"] is not None
|
|
689
|
+
elif m["runner"] == "lmstudio":
|
|
690
|
+
name, up = "LM Studio", bool(m["lms"]) # LM Studio starts its server when needed
|
|
691
|
+
ready = bool(m["lms"] and want and (loaded or any(
|
|
692
|
+
want.lower() in (r["key"].lower(), r["name"].lower())
|
|
693
|
+
for r in kept(("lms_models", m["lms"]), lms_models))))
|
|
694
|
+
else: # auto: the runner holding the model, else whichever one is running
|
|
695
|
+
ready = bool(in_ollama or loaded)
|
|
696
|
+
name = ("Ollama" if in_ollama else "LM Studio" if loaded
|
|
697
|
+
else "Ollama" if m["ollama"] is not None
|
|
698
|
+
else "LM Studio" if m.get("server_port") else "")
|
|
699
|
+
up = bool(name)
|
|
700
|
+
if not m["enabled"]:
|
|
701
|
+
detail = "Off. Optional: a small AI that runs on this computer."
|
|
702
|
+
elif ready:
|
|
703
|
+
detail = ("On: sorts your browsing on this computer. "
|
|
704
|
+
+ ("Loaded now." if loaded else "Loads when needed."))
|
|
705
|
+
elif not want:
|
|
706
|
+
detail = "On, but no model is chosen. Open Local model to choose one."
|
|
707
|
+
elif not name:
|
|
708
|
+
detail = "On, but neither Ollama nor LM Studio is running. Open Local model to start one."
|
|
709
|
+
elif not up:
|
|
710
|
+
detail = (f"On, but {name} is not running. Open Local model to start it."
|
|
711
|
+
if name == "Ollama" else
|
|
712
|
+
"On, but LM Studio is not on this computer. Open Local model to set it up.")
|
|
713
|
+
else:
|
|
714
|
+
detail = (f"On, but {name} does not have {want}. "
|
|
715
|
+
"Open Local model to get it or choose another model.")
|
|
716
|
+
return {"id": "llm", "label": "Local model",
|
|
717
|
+
"state": "off" if not m["enabled"] else "ok" if ready else "warn",
|
|
718
|
+
"value": f"{name or 'none running'}, {want or 'no model chosen'}",
|
|
719
|
+
"detail": detail, "action": _go("llm", "Open")}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def history_row(root: Path | None, b: dict, now: datetime | None = None) -> dict:
|
|
723
|
+
"""Is the automatic import keeping up? Warns when the last import is older than twice
|
|
724
|
+
`browse.auto_import_hours` (browsers keep ~90 days, so missed days are lost). `at` is the
|
|
725
|
+
import time the page shows in words where "{ago}" stands; `import` the sources imported
|
|
726
|
+
before (the automatic import's); `login_hint` that only a running Keepfold imports."""
|
|
727
|
+
row = {"id": "history", "label": "Browsing history", "action": _go("browse", "Open")}
|
|
728
|
+
state: dict = {}
|
|
729
|
+
if root is not None and b.get("available"):
|
|
730
|
+
try:
|
|
731
|
+
from keepfold.browse import build
|
|
732
|
+
from keepfold.vault import Vault
|
|
733
|
+
state = build.load_state(Vault(root))
|
|
734
|
+
except (OSError, ValueError, VaultError):
|
|
735
|
+
pass
|
|
736
|
+
except Exception: # noqa: BLE001
|
|
737
|
+
log.exception("browse state read failed")
|
|
738
|
+
last = state.get("last_run")
|
|
739
|
+
try:
|
|
740
|
+
t = datetime.strptime(last, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
|
|
741
|
+
except (TypeError, ValueError): # never imported (the automatic import waits for a first)
|
|
742
|
+
return {**row, "state": "off", "value": "never imported",
|
|
743
|
+
"detail": "Import your past history once under Browsing; after that Keepfold "
|
|
744
|
+
"keeps it up to date."}
|
|
745
|
+
hours = (b.get("settings") or {}).get("auto_import_hours") or 0
|
|
746
|
+
row |= {"at": last, "value": "last import {ago}"}
|
|
747
|
+
if not hours:
|
|
748
|
+
return {**row, "state": "off",
|
|
749
|
+
"detail": "Automatic import is off: new visits come in only when you import "
|
|
750
|
+
"them. Turn it on under Browsing."}
|
|
751
|
+
login = b.get("login") or {}
|
|
752
|
+
row["login_hint"] = bool(login.get("supported") and not login.get("exists"))
|
|
753
|
+
if (now or datetime.now(UTC)) - t > timedelta(hours=2 * hours):
|
|
754
|
+
from keepfold import browse_serve # the automatic import's sources: never an unticked one
|
|
755
|
+
from keepfold.vault import Vault
|
|
756
|
+
return {**row, "state": "warn",
|
|
757
|
+
"detail": "Last import {ago}: newer visits are not in Keepfold yet.",
|
|
758
|
+
"import": [s.key for s in browse_serve.auto_sources(Vault(root))]}
|
|
759
|
+
return {**row, "state": "ok", "detail": f"New visits come in every {hours:g} hours."}
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
# ---- "Something not working?": the text a user pastes into a bug report ---------------------
|
|
763
|
+
|
|
764
|
+
_REDACT = ((re.compile(r"(?i)\b[a-z]:[\\/][^\s'\"<>|]*"), "<path>"), # a drive path
|
|
765
|
+
(re.compile(r"(?<![\w.])/(?:Users|home|root|var|tmp|opt|etc)/[^\s'\"<>|]*"), "<path>"),
|
|
766
|
+
(re.compile(r"(?i)([?&](?:token|key|api_?key|access_token|auth|secret|password)=)"
|
|
767
|
+
r"[^\s&'\"]*"), r"\1<redacted>"),
|
|
768
|
+
(re.compile(r"\b(?:sk|pk|ghp|gho|ghs|xox[bap])[-_][A-Za-z0-9_-]{8,}"), "<key>"))
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def redact(text, root: Path | str | None = None) -> str:
|
|
772
|
+
"""`text` with the vault path, the home folder and any other path as `<path>`, the user name
|
|
773
|
+
as `<user>`, a URL's token= value and an API key removed."""
|
|
774
|
+
import getpass
|
|
775
|
+
|
|
776
|
+
s = str(text)
|
|
777
|
+
for p in sorted({str(x) for x in (root, Path.home()) if x}, key=len, reverse=True):
|
|
778
|
+
s = s.replace(p, "<path>").replace(p.replace("\\", "/"), "<path>")
|
|
779
|
+
for rx, sub in _REDACT:
|
|
780
|
+
s = rx.sub(sub, s)
|
|
781
|
+
names = {Path.home().name}
|
|
782
|
+
with contextlib.suppress(Exception):
|
|
783
|
+
names.add(getpass.getuser())
|
|
784
|
+
for n in names:
|
|
785
|
+
if n:
|
|
786
|
+
s = re.sub(rf"(?i)(?<![A-Za-z0-9]){re.escape(n)}(?![A-Za-z0-9])", "<user>", s)
|
|
787
|
+
return s
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def report(root: Path | None) -> str:
|
|
791
|
+
"""The plain-text block for a bug report: versions, each Status row's name and state, which
|
|
792
|
+
optional parts are on. No value, path, note or model name; every line passes `redact`.
|
|
793
|
+
(Status shows no last-error line, so none is included.)"""
|
|
794
|
+
import platform
|
|
795
|
+
|
|
796
|
+
from keepfold import doctor, update
|
|
797
|
+
|
|
798
|
+
rs = rows(root)
|
|
799
|
+
by = {r["id"]: r for r in rs}
|
|
800
|
+
state = {"ok": "Ready", "off": "Off"}
|
|
801
|
+
llm, embed, hist = by.get("llm", {}), by.get("embed", {}), by.get("history", {})
|
|
802
|
+
runner = (llm.get("value") or "").split(",")[0].strip()
|
|
803
|
+
lines = [f"Keepfold {update.current()} ({'KeepfoldSetup.exe' if doctor.installer() else 'uv'})",
|
|
804
|
+
f"{platform.system()} {platform.release()} (build {platform.version()}), "
|
|
805
|
+
f"Python {platform.python_version()}", "", "Status:"]
|
|
806
|
+
lines += [f"- {r['label']}: {state.get(r['state'], 'Needs attention')}" for r in rs]
|
|
807
|
+
lines += ["", "Optional parts:",
|
|
808
|
+
f"- Search model: {'on' if embed.get('state') == 'ok' else 'off'}",
|
|
809
|
+
f"- Local model: {(runner or 'on') if llm.get('state', 'off') != 'off' else 'off'}",
|
|
810
|
+
f"- Browsing import: {'yes' if hist.get('state', 'off') != 'off' else 'no'}"]
|
|
811
|
+
return redact("\n".join(lines), root)
|