keepfold 0.6.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,690 @@
1
+ """The app's long actions, each run as a background job (`server.Jobs`, one at a time) with a
2
+ progress line: the existing CLI commands (doctor, backup, dashboard, model download), the local
3
+ model's load and test, and the browse actions. Browse results are counts only (`status.safe`):
4
+ a title, URL or search never reaches the page."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import io
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import threading
14
+ import time
15
+ from collections import Counter
16
+ from pathlib import Path
17
+
18
+ from keepfold._proc import NO_WINDOW, Tree
19
+ from keepfold.app import status
20
+
21
+ TEST_TEXT = "Dijkstra shortest path tutorial" # synthetic: never the owner's data
22
+ TEST_LABELS = ["programming", "cooking", "sports"]
23
+ _ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07")
24
+ _popen = subprocess.Popen # tests replace this: nothing installs or downloads in a test
25
+
26
+
27
+ class _Lines(io.TextIOBase):
28
+ """A text stream that hands each finished line to `say`."""
29
+
30
+ def __init__(self, say):
31
+ self.say, self.buf = say, ""
32
+
33
+ def write(self, s: str) -> int:
34
+ self.buf += s
35
+ while "\n" in self.buf:
36
+ line, self.buf = self.buf.split("\n", 1)
37
+ self.say(line)
38
+ return len(s)
39
+
40
+ def flush(self) -> None:
41
+ if self.buf:
42
+ self.say(self.buf)
43
+ self.buf = ""
44
+
45
+
46
+ _target = threading.local() # .out: where this thread's prints go while `capture` runs it
47
+
48
+
49
+ class _Route(io.TextIOBase):
50
+ """sys.stdout/sys.stderr: a thread inside `capture` writes to its job, others to the
51
+ original stream. No fileno or buffer, so click.echo writes through it, not around it."""
52
+
53
+ def __init__(self, orig):
54
+ self.orig = orig
55
+
56
+ def _to(self):
57
+ return getattr(_target, "out", None) or self.orig
58
+
59
+ def write(self, s):
60
+ to = self._to()
61
+ return len(s) if to is None else to.write(s) # None: a GUI app has no console
62
+
63
+ def flush(self) -> None:
64
+ if (to := self._to()) is not None:
65
+ to.flush()
66
+
67
+ def isatty(self) -> bool:
68
+ to = self._to()
69
+ return to is not None and to.isatty()
70
+
71
+
72
+ def capture(job, fn, *args, **kwargs) -> dict:
73
+ """Run a `keepfold` CLI command function in-process, its printed lines going to the job's
74
+ progress line; {"ok", "lines"}. Only this thread's output is taken: other threads (the
75
+ HTTP server, the update check, Chat) keep printing to the console. None of the commands
76
+ run here print from threads of their own."""
77
+ import typer
78
+ from click.exceptions import Exit
79
+
80
+ if not isinstance(sys.stdout, _Route):
81
+ sys.stdout = _Route(sys.stdout)
82
+ if not isinstance(sys.stderr, _Route):
83
+ sys.stderr = _Route(sys.stderr)
84
+ lines: list[str] = []
85
+ out = _Lines(lambda s: (lines.append(s), job.say(s)))
86
+ ok = True
87
+ _target.out = out
88
+ try:
89
+ try:
90
+ fn(*args, **kwargs)
91
+ except (Exit, typer.Exit) as e:
92
+ ok = getattr(e, "exit_code", 1) == 0
93
+ out.flush()
94
+ finally:
95
+ _target.out = None
96
+ return {"ok": ok, "lines": lines[-300:]}
97
+
98
+
99
+ def run_proc(job, args: list[str], env: dict | None = None) -> dict:
100
+ """Run a command (a download or an install) with its output as the progress line; Cancel
101
+ terminates it and everything it started (`_proc.Tree`). {"ok", "cancelled", "lines"}.
102
+ `env`: the child's environment (default ours)."""
103
+ job.say("running: " + subprocess.list2cmdline(args))
104
+ try:
105
+ p = _popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
106
+ stdin=subprocess.DEVNULL, creationflags=NO_WINDOW, env=env,
107
+ start_new_session=True) # POSIX: its own process group, for Cancel
108
+ except OSError as e:
109
+ raise ValueError(f"could not start {args[0]}: {e}") from None
110
+ tree = job.proc = Tree(p)
111
+ lines, buf = [], b""
112
+ read = getattr(p.stdout, "read1", None) or p.stdout.read
113
+ try:
114
+ while True:
115
+ chunk = read(4096)
116
+ buf += chunk or b"\n"
117
+ *done, buf = re.split(rb"[\r\n]", buf)
118
+ for raw in done:
119
+ line = _ANSI.sub("", raw.decode("utf-8", "replace")).strip()
120
+ if line:
121
+ job.say(line)
122
+ lines.append(line)
123
+ if not chunk:
124
+ break
125
+ rc = p.wait()
126
+ finally:
127
+ tree.close()
128
+ cancelled = job.cancelled.is_set()
129
+ return {"ok": rc == 0 and not cancelled, "cancelled": cancelled, "lines": lines[-50:]}
130
+
131
+
132
+ # ---- dashboard and vault (the existing CLI commands) ------------------------------------------
133
+
134
+
135
+ # the doctor's fixes that say to open the app, as the app says them (the CLI is unchanged)
136
+ APP_FIX = {"Search model": "Setup → Search model → Download search model.",
137
+ "AI app connected": "Setup → Connect AI apps.",
138
+ "Local model": "Setup → Local model → Start.",
139
+ "Vault": "Setup → Vault."}
140
+
141
+
142
+ def doctor(job, root: Path | None) -> dict:
143
+ from keepfold import cli
144
+ out = capture(job, cli.doctor, vault=root)
145
+ lines, name = [], ""
146
+ for line in out["lines"]:
147
+ if not line.startswith(" "): # "WARN Search model: ..." names the check
148
+ name = line[6:].split(":", 1)[0]
149
+ elif (name in APP_FIX and "fix:" in line
150
+ and ("keepfold app" in line or "Start menu" in line)):
151
+ line = line[:line.index("fix:")] + "fix: in this app, " + APP_FIX[name]
152
+ lines.append(line)
153
+ return {**out, "lines": lines}
154
+
155
+
156
+ def backup(job, root: Path) -> dict:
157
+ from keepfold import cli
158
+ return capture(job, cli.backup, vault=root)
159
+
160
+
161
+ # ---- local model (adapter to keepfold.localllm) ----------------------------------------------
162
+
163
+
164
+ def llm_config(**changes) -> dict:
165
+ """The whole config with `localllm` changed in memory only (for a load or a test)."""
166
+ cfg = status.config()
167
+ old = cfg.get("localllm") if isinstance(cfg.get("localllm"), dict) else {}
168
+ return {**cfg, "localllm": {**old, **changes}}
169
+
170
+
171
+ def llm_load(job, model: str) -> dict:
172
+ from keepfold import localllm
173
+ if not hasattr(localllm, "ensure_lmstudio"):
174
+ raise ValueError("loading through LM Studio is not available in this version yet")
175
+ job.say(f"starting LM Studio's server and loading {model} (no download)")
176
+ url = localllm.ensure_lmstudio(model, config=llm_config(enabled=True, runner="lmstudio"))
177
+ if url is None:
178
+ raise ValueError(f"LM Studio did not load {model}: is it in `lms ls`?")
179
+ return {"ok": True, "lines": [f"{model} loaded in LM Studio"]}
180
+
181
+
182
+ def llm_test(job, config: dict | None = None) -> dict:
183
+ """One synthetic prompt through the runner the config picks; its answer and time."""
184
+ from keepfold import localllm
185
+ job.say("looking for a local runner")
186
+ runner = localllm.find(config)
187
+ if runner is None:
188
+ raise ValueError("no local runner answered (start Ollama or LM Studio, and check the "
189
+ "model name)")
190
+ job.say(f"asking {runner.describe()}")
191
+ t = time.perf_counter()
192
+ got = runner.classify(TEST_TEXT, TEST_LABELS)
193
+ took = time.perf_counter() - t
194
+ if got is None:
195
+ raise ValueError(f"{runner.describe()} gave no valid answer in {took:.1f} s")
196
+ line = f"{TEST_TEXT!r} -> {got[0]} ({got[1]:.2f}) in {took:.2f} s"
197
+ return {"ok": True, "runner": runner.describe(), "answer": got[0], "seconds": round(took, 2),
198
+ "lines": [line]}
199
+
200
+
201
+ # ---- browsing (adapters; counts only) --------------------------------------------------------
202
+
203
+
204
+ def _vault(root: Path):
205
+ from keepfold.vault import Vault
206
+ return Vault(root)
207
+
208
+
209
+ def browse_process(job, root: Path) -> dict:
210
+ from keepfold import browse_serve
211
+ job.say("importing new browser history (counts only)")
212
+ v = _vault(root) # only the profiles imported before; old extension visits not yet
213
+ # imported come along (build.run reads what is left of its inbox)
214
+ report = browse_serve.run_import(v, srcs=browse_serve.auto_sources(v))
215
+ return {"ok": True, "counts": status.safe(report)}
216
+
217
+
218
+ def browse_selftest(job) -> dict:
219
+ from keepfold.browse import selftest
220
+ lines: list[str] = []
221
+ ok = selftest.run(lambda s: lines.append(str(s)))
222
+ # the check names are fixed strings in selftest.py; only PASS/FAIL lines go on
223
+ lines = [x for x in lines if x.startswith(("PASS", "FAIL"))]
224
+ for x in lines:
225
+ job.say(x)
226
+ return {"ok": bool(ok), "lines": lines}
227
+
228
+
229
+ def browse_scan(job) -> dict:
230
+ from keepfold.browse import load_settings, sources
231
+ job.say("reading browser history counts (nothing is written)")
232
+ out = []
233
+ for r in sources.scan(sources.discover(), load_settings()):
234
+ row = {"source": str(r.get("source", "")), **status.safe(r)}
235
+ if "error" in r:
236
+ row["error"] = True
237
+ out.append(row)
238
+ return {"ok": True, "kind": "scan", "rows": out}
239
+
240
+
241
+ class Cancelled(KeyboardInterrupt):
242
+ """Raised inside `build.run` on Cancel. Like Ctrl+C there, it leaves whole pages only;
243
+ what was read and checked is saved in the store, so the next import goes on from there."""
244
+
245
+
246
+ def browse_migrate(job, root: Path) -> dict:
247
+ """The site Markdown pages into the browsing store (`store.migrate`): zipped into
248
+ .keepfold/backups first, removed from the vault only once the store holds every one. Counts
249
+ only."""
250
+ from keepfold.browse import load_settings, store
251
+ steps = store.MIGRATE_STEPS
252
+ job.say("moving the site pages into Keepfold's own store")
253
+ r = store.migrate(_vault(root), settings=load_settings(), step=lambda n, d, t: job.progress(
254
+ n, len(steps), d, t, steps[n - 1]))
255
+ if r.get("missing") or r.get("error"):
256
+ return {"ok": False, "counts": status.safe(r), "lines": [
257
+ "The site pages were not moved: the store does not hold every one yet. Nothing "
258
+ "was removed."]}
259
+ return {"ok": True, "counts": status.safe(r)}
260
+
261
+
262
+ class _Watched:
263
+ """A local-model runner whose every call first checks for Cancel."""
264
+
265
+ def __init__(self, inner, check):
266
+ self._inner, self._check = inner, check
267
+
268
+ def __getattr__(self, name):
269
+ attr = getattr(self._inner, name)
270
+ if not callable(attr):
271
+ return attr
272
+
273
+ def call(*a, **k):
274
+ self._check()
275
+ return attr(*a, **k)
276
+ return call
277
+
278
+
279
+ def history_import(job, root: Path, keys: set[str], takeout: list | None = None) -> dict:
280
+ """The full import of the chosen browsers' past history (`build.run`, no `since`: every
281
+ visit not read yet), plus Google activity rows (`takeout`) when given, in named steps
282
+ (`job.progress`; the site pages' move into the store first, once). Without the search
283
+ model it stops first: every page would land under Other. The local model checks titles
284
+ only when it is already loaded and the PC idle (`titles.may_run`); its summaries wait for
285
+ the background runs. Cancel keeps what was saved. Progress and summary are counts only."""
286
+ from keepfold import browse_serve, semantic
287
+ from keepfold.app import wizard
288
+ from keepfold.browse import build, load_settings, sources, store
289
+
290
+ srcs = [s for s in sources.discover() if s.key in keys]
291
+ if not srcs and not takeout:
292
+ raise ValueError("Tick at least one browser that is on this computer.")
293
+ embed = semantic.load_embedder()
294
+ if embed is None:
295
+ return {"ok": False, "need": "embed", "lines": [
296
+ f"Download the search model first ({wizard.EMBED['size']}): without it every page "
297
+ "lands under Other."]}
298
+
299
+ def check():
300
+ if job.cancelled.is_set():
301
+ raise Cancelled
302
+
303
+ runner, budget = browse_serve.idle_runner()
304
+ v = _vault(root)
305
+ moving = () if store.migrated(v) else store.MIGRATE_STEPS
306
+ names = (*moving, *build.PHASES)
307
+
308
+ def step(n, done, total): # n counts from 1 over `names`
309
+ job.progress(n, len(names), done, total, names[n - 1])
310
+ check()
311
+
312
+ def progress(key, n, new, err):
313
+ job.say(f"{key}: not read ({type(err).__name__}); the others go on" if err
314
+ else f"{key}: {n} visits read, {new} new")
315
+ check()
316
+
317
+ def watched_embed(texts):
318
+ check()
319
+ return embed(texts)
320
+
321
+ try:
322
+ if moving:
323
+ store.migrate(v, settings=load_settings(), step=step)
324
+ if not store.migrated(v):
325
+ return {"ok": False, "lines": ["The site pages could not be moved into the "
326
+ "store; nothing was imported."]}
327
+ job.say(f"reading {len(srcs)} browser profile(s); the first time can take a while")
328
+ r = build.run(v, srcs, load_settings(), embed=watched_embed,
329
+ runner=_Watched(runner, check) if runner is not None else None,
330
+ budget=budget, progress=progress, takeout=takeout,
331
+ step=lambda n, d, t: step(n + len(moving), d, t), summaries=False)
332
+ except Cancelled:
333
+ return {"ok": False, "cancelled": True, "lines": [
334
+ "Stopped. What was read is saved; the next import goes on from there."]}
335
+ summary = {"days_written": r.get("private_written", 0) + r.get("public_written", 0),
336
+ "private_pages": r.get("private_written", 0), "kept": r.get("kept", 0),
337
+ "private": r.get("private", 0), "dropped": r.get("dropped", 0),
338
+ "sources_read": r.get("sources", 0), "sources_failed": r.get("sources_failed", 0),
339
+ "local_model_used": runner is not None, "first_day": r.get("days_from")}
340
+ if takeout is not None:
341
+ summary["google_rows_used"] = r.get("takeout", 0)
342
+ if "days_from" not in r:
343
+ job.say("nothing new since the last import")
344
+ return {"ok": True, "counts": status.safe(summary)}
345
+
346
+
347
+ def chat_import(job, root: Path) -> dict:
348
+ """One `chat_import.run` pass, committed. `quiet` (no notification) when nothing was saved
349
+ or failed; a failed chat makes the job fail (`ok: false`). Counts only."""
350
+ from keepfold import chat_archive
351
+ from keepfold import chat_import as ci
352
+ from keepfold.vault import VaultError
353
+ v = _vault(root)
354
+ try: # C5: once, chat pages already in resources/ move to the git-ignored archive
355
+ if (moved := chat_archive.auto(v)) and moved["ids"]:
356
+ job.say(f"{len(moved['ids'])} chat pages moved out of git, to archive/chats/")
357
+ except VaultError as e: # busy (another import) or a file open elsewhere: next pass
358
+ print(f"keepfold app: chat archive not moved yet ({e.code})")
359
+ try:
360
+ counts = ci.run(v, progress=lambda k, n, s: job.say(ci.eta(k, n, s)),
361
+ cancelled=job.cancelled.is_set)
362
+ except Exception as e:
363
+ print(f"keepfold app: chat import failed ({type(e).__name__})") # type only: no chat text
364
+ raise
365
+ finally:
366
+ _commit(v, "chats")
367
+ wrote = counts.get("saved", 0) + counts.get("updated", 0)
368
+ job.say(f"{wrote} chat page{_s(wrote)} written" if wrote else "no new chats")
369
+ return {"ok": not counts.get("failed"), "quiet": not (wrote or counts.get("failed")),
370
+ "cancelled": bool(counts.get("stopped")), "counts": status.safe(counts)}
371
+
372
+
373
+ # ---- guided imports (chat exports through keepfold.chats; Google activity through browse) ----
374
+
375
+ GOOGLE_NOTE = ("Google activity goes through your browsing privacy filter, like your browser "
376
+ "history: adult and sensitive rows follow your Browsing settings, and the pages "
377
+ "stay private unless you made browsing visible to Claude.")
378
+
379
+
380
+ def tmp_dir() -> Path:
381
+ return Path.home() / ".keepfold" / "tmp"
382
+
383
+
384
+ def sweep_uploads(max_age_s: float = 24 * 3600) -> None:
385
+ """Delete uploads older than a day: a killed app never ran its own cleanup (r1 S7)."""
386
+ cutoff = time.time() - max_age_s
387
+ for p in tmp_dir().glob("upload-*"):
388
+ with contextlib.suppress(OSError):
389
+ if p.is_file() and p.stat().st_mtime < cutoff:
390
+ p.unlink()
391
+
392
+
393
+ def sweep_updates(keep: Path | None = None) -> None:
394
+ """Delete downloaded installers (~/.keepfold/tmp/update-*) except `keep`; one still running
395
+ is locked and goes next time."""
396
+ import shutil
397
+ for p in tmp_dir().glob("update-*"):
398
+ if p != keep:
399
+ shutil.rmtree(p, ignore_errors=True)
400
+
401
+
402
+ # importers.detect's kind -> how the page names it, and the card that imports it
403
+ KIND = {"chats": ("a chat export", "the Claude, ChatGPT, Gemini or Perplexity card"),
404
+ "takeout": ("Google activity (My Activity)", "the Google activity card"),
405
+ "notes": ("a notes folder or export", "the Notes card"),
406
+ "calendar": ("a calendar", "the Calendar card"),
407
+ "docs": ("a folder of documents", "the Documents card"),
408
+ "repos": ("a folder of git projects", "the code projects card"),
409
+ "highlights": ("reading highlights", "the Reading highlights card"),
410
+ "mail": ("sent mail (.mbox)", "the Sent mail card"),
411
+ "selfchat": ("notes to yourself", "the Notes to self card"),
412
+ "location": ("a location history", "the Location card"),
413
+ "photos": ("a photo folder", "the Photos card"),
414
+ "spotify": ("a Spotify export", "the Spotify card"),
415
+ "voice-memos": ("a folder of recordings", "the Voice memos card"),
416
+ "anki": ("Anki decks", "the Anki card")}
417
+ TIERED = ("notes", "calendar", "docs", "repos", "highlights", "mail", "selfchat",
418
+ "location", "photos", "spotify", "voice-memos", "anki") # imports that ask the tier
419
+ OWN_CHECK = ("docs", "repos", "mail", "selfchat", "location", "photos",
420
+ "spotify", "voice-memos") # the source checks the path itself
421
+
422
+
423
+ def _kind(source: str, path: Path) -> str:
424
+ """The importer this card's file needs, detected as `keepfold import` does. A file of
425
+ another kind is refused with the card that takes it (R3-1)."""
426
+ from keepfold import importers
427
+ if source in OWN_CHECK: # the source says what it skips, or refuses
428
+ return source
429
+ want, got = importers.SOURCES[source], _readable(importers.detect, path)
430
+ if want in got:
431
+ return want
432
+ if not got:
433
+ raise ValueError(f"Keepfold cannot tell what {path.name} is. Step 1 shows the file to "
434
+ "pick.")
435
+ what, card = KIND[got[0]]
436
+ raise ValueError(f"This is {what}, not {KIND[want][0]}: use {card} under Add your "
437
+ "history.")
438
+
439
+
440
+ def _commit(v, what: str) -> None:
441
+ """Commit the vault files an import wrote, as `keepfold import` does."""
442
+ from keepfold import session
443
+ if v.writes:
444
+ session._commit(v, f"keepfold: app import {what}", v.wrote_since(0))
445
+
446
+
447
+ def _s(n: int) -> str:
448
+ return "s" * (n != 1)
449
+
450
+
451
+ def _notes(flavor: str, n: int) -> str:
452
+ """"Obsidian notes", "Notion note"; a plain folder is just "notes", never "Notes notes"."""
453
+ from keepfold import importers
454
+ label = importers.LABELS[flavor]
455
+ return ("" if label == "Notes" else label + " ") + "note" + _s(n)
456
+
457
+
458
+ def _skipped_rows(rows) -> str:
459
+ """The count of HTML rows takeout.records skipped for an unreadable time, as a sentence."""
460
+ n = rows.skipped
461
+ return f" {n:,} row{_s(n)} skipped (unreadable date)." if n else ""
462
+
463
+
464
+ def _readable(fn, *args):
465
+ """keepfold.chats and takeout refuse a bad file with VaultError; the page shows its text."""
466
+ from keepfold.vault import VaultError
467
+ try:
468
+ return fn(*args)
469
+ except VaultError as e:
470
+ raise ValueError(str(e)) from None
471
+
472
+
473
+ def import_preview(job, source: str, path: Path, root: Path | None = None) -> dict:
474
+ """A dry run: what an import of `path` would bring, counts and dates only."""
475
+ from keepfold import chats, importers, more_sources, sources
476
+ job.say("reading the file (nothing is imported yet)")
477
+ kind = _kind(source, path)
478
+ if kind == "takeout":
479
+ from keepfold import semantic
480
+ from keepfold.browse import takeout
481
+ rows = _readable(takeout.records, path)
482
+ if not rows:
483
+ raise ValueError("Found no Search, YouTube or Chrome activity in this "
484
+ "export (My Activity, or YouTube's watch and search history; "
485
+ "Takeouts in some languages are not read yet)."
486
+ + _skipped_rows(rows))
487
+ kinds = Counter(v.source.rsplit("/", 1)[-1] for v in rows)
488
+ out = {"ok": True, "kind": "import-preview", "found": len(rows), "note": GOOGLE_NOTE,
489
+ "lines": [f"Found {len(rows):,} activity rows from {rows[0].start:%Y-%m-%d} to "
490
+ f"{rows[-1].start:%Y-%m-%d}: " + ", ".join(
491
+ f"{k.capitalize() if k != 'youtube' else 'YouTube'} {n:,}"
492
+ for k, n in sorted(kinds.items())) + "." + _skipped_rows(rows)]}
493
+ if semantic.load_embedder() is None: # said here, not after Import (R3-3)
494
+ from keepfold.app import wizard
495
+ out.update(ok=False, need="embed", lines=[*out["lines"], (
496
+ f"Download the search model first ({wizard.EMBED['size']}): it sorts each page "
497
+ "into a topic, and without it every page lands under Other.")])
498
+ return out
499
+ if kind == "voice-memos":
500
+ from keepfold import voice_memos
501
+ if not path.is_dir():
502
+ raise ValueError(f"{path.name} is not a folder; paste the folder of recordings.")
503
+ if voice_memos.load_transcriber() is None: # asked at Check; nothing downloads unasked
504
+ return {"ok": False, "kind": "import-preview", "need": "voice", "found": 0,
505
+ "lines": ["Needs the local speech model (~150 MB). Install?"],
506
+ "note": "It transcribes on this computer: your recordings never leave it, "
507
+ "and nothing is downloaded until you click Install."}
508
+ if kind in TIERED:
509
+ # C2: the page asks the tier before Import, starting from the last choice or default
510
+ v = _vault(root)
511
+ t = _tier(v, kind, path)[0]
512
+ counted = sources.Audience.CLOUD if t is sources.Audience.SKIP else t
513
+ if kind == "voice-memos": # counted only: transcribing waits for Import
514
+ n, new = voice_memos.count(v, path)
515
+ return {"ok": True, "kind": "import-preview", "found": new, "tier": t.value,
516
+ "lines": [f"Found {n:,} recording{_s(n)}, {new:,} of them new. Each new one is "
517
+ "transcribed on this computer when you click Import, which can take "
518
+ "a while; the progress shows at the top."]}
519
+ if kind in more_sources.SOURCE_OF:
520
+ src = _source(kind, path)
521
+ r = _readable(sources.run, v, src, counted, True)
522
+ return {"ok": True, "kind": "import-preview", "found": r["imported"] + r["updated"],
523
+ "tier": t.value, "lines": [_found(r), importers.report_line(src.label, r)]}
524
+ if kind == "notes":
525
+ r = _readable(importers.import_notes, v, path, None, True, False, counted)
526
+ new, same, skipped = r["new"], r["same"], r["skipped"]
527
+ return {"ok": True, "kind": "import-preview", "found": new, "tier": t.value, "lines": [
528
+ f"Found {new:,} new {_notes(r['source'], new)}"
529
+ + (f", {same:,} already imported" if same else "")
530
+ + (f"; {skipped:,} file{_s(skipped)} skipped (hidden, not text or over 5 MB)"
531
+ if skipped else "") + "."]}
532
+ if kind == "calendar":
533
+ r = _readable(importers.import_calendar, v, path, True, False, counted)
534
+ return {"ok": True, "kind": "import-preview", "found": r["new"], "tier": t.value,
535
+ "lines": [f"Found {r['events']:,} event{_s(r['events'])} in {r['months']:,} "
536
+ f"month{_s(r['months'])}, {r['new']:,} of them new."]}
537
+ got, new, old = _readable(chats.import_export, path, None, True)
538
+ n = new + old
539
+ name = chats.GUIDES[got]["name"]
540
+ lines = [f"Found {n:,} {name} conversation{_s(n)}"
541
+ + (f", {old:,} already imported (those are updated)." if old else ".")]
542
+ if got != source:
543
+ lines.append(f"This is a {name} export, so it is imported as {name}.")
544
+ return {"ok": True, "kind": "import-preview", "found": n, "already": old,
545
+ "detected": got, "lines": lines}
546
+
547
+
548
+ def _keepfold_hint() -> str:
549
+ """Where to use imported chats: /keepfold in a connected app, else connect one first."""
550
+ from keepfold.app import targets
551
+ on = [t["label"] for t in targets.describe(None) if t["connected"]]
552
+ return (f"In {', '.join(on)}, type /keepfold to learn from them." if on else
553
+ "Connect an AI app (Setup, Connect AI apps), then type /keepfold in it to learn "
554
+ "from them.")
555
+
556
+
557
+ def _source(kind: str, path: Path, job=None):
558
+ from keepfold import importers, more_sources, voice_memos
559
+ if kind == "voice-memos": # the job: a line per recording, and Cancel
560
+ return _readable(voice_memos.voice_source, path, job)
561
+ return _readable({"notes": importers.notes_source, "calendar": importers.calendar_source,
562
+ **more_sources.SOURCE_OF}[kind], path)
563
+
564
+
565
+ def _found(r: dict) -> str:
566
+ """A docs, repos or highlights preview's count, as a sentence."""
567
+ return (f"Found {r['imported']:,} new item{_s(r['imported'])}"
568
+ + (f", {r['updated']:,} changed" if r["updated"] else "")
569
+ + (f", {r['duplicate']:,} already in" if r["duplicate"] else "") + ".")
570
+
571
+
572
+ def _tier(v, kind: str, path: Path, given: str | None = None, said=None):
573
+ """(tier, how) for a tiered import: the page's choice (remembered), else the last choice,
574
+ else the source's default (sources.pick_tier; a stricter choice's line goes to `said`)."""
575
+ from keepfold import sources
576
+ return sources.pick_tier(v, _source(kind, path), given, said=said)
577
+
578
+
579
+ def import_run(job, source: str, path: Path, root: Path | None = None,
580
+ tier: str | None = None) -> dict:
581
+ """Import `path`; `tier` (skip, local or cloud) is the page's choice for notes and
582
+ calendars, the user's click."""
583
+ from keepfold import chats, importers, more_sources, sources
584
+ job.say("reading the file")
585
+ kind, told = _kind(source, path), [] # told: RR-29's line when the tier got stricter
586
+ if kind in TIERED:
587
+ v = _vault(root)
588
+ t = _tier(v, kind, path, tier, told.append)[0]
589
+ if t is sources.Audience.SKIP:
590
+ return {"ok": True, "kind": "import", "counts": {
591
+ "notes" if kind == "notes" else "events" if kind == "calendar" else kind: 0},
592
+ "lines": ["Nothing was imported: you chose Don't save.", *told]}
593
+ if kind in more_sources.SOURCE_OF:
594
+ job.say("importing")
595
+ src = _source(kind, path, job)
596
+ r = _readable(sources.run, v, src, t, False)
597
+ if kind == "anki": # parent decks and concepts, once the pages exist
598
+ from keepfold import anki
599
+ anki.link(v)
600
+ _commit(v, kind)
601
+ return {"ok": True, "kind": "import", "counts": {kind: r["imported"] + r["updated"]},
602
+ "lines": [f"{_found(r).replace('Found', 'Imported', 1)} Pages are in "
603
+ f"{root / 'resources'}.", importers.report_line(src.label, r), *told]}
604
+ if kind == "notes":
605
+ job.say("importing the notes")
606
+ r = _readable(importers.import_notes, v, path, None, False, False, t)
607
+ _commit(v, "notes")
608
+ return {"ok": True, "kind": "import", "counts": {"notes": r["new"]}, "lines": [
609
+ f"Imported {r['new']:,} {_notes(r['source'], r['new'])} into "
610
+ f"{root / 'resources'}" + (f"; {r['same']:,} were already in." if r["same"]
611
+ else "."),
612
+ importers.report_line(importers.LABELS[r["source"]], r), *told]}
613
+ if kind == "calendar":
614
+ job.say("importing the calendar")
615
+ r = _readable(importers.import_calendar, v, path, False, False, t)
616
+ _commit(v, "calendar")
617
+ return {"ok": True, "kind": "import", "counts": {"events": r["new"]}, "lines": [
618
+ f"Imported {r['new']:,} new event{_s(r['new'])} into the calendar-YYYY-MM month "
619
+ f"pages in {root / 'resources'}.", importers.report_line("Calendar", r), *told]}
620
+ if kind == "takeout":
621
+ from keepfold.browse import load_settings, sources, takeout
622
+ from keepfold.vault import PRIVATE_BROWSE_DIR
623
+ rows = _readable(takeout.records, path)
624
+ # S2: only the browsers `browse.browsers` allows
625
+ out = history_import(job, root, {s.key for s in sources.chosen(load_settings())},
626
+ takeout=rows)
627
+ if out.get("ok"):
628
+ out["lines"] = [f"Your Google activity is in the private day pages under "
629
+ f"{root / PRIVATE_BROWSE_DIR}. Rows on days your browsers "
630
+ "already hold were skipped: the browsers have them."
631
+ + _skipped_rows(rows), GOOGLE_NOTE]
632
+ return out
633
+ job.say("importing the conversations")
634
+ res = _readable(chats.import_export, path)
635
+ got, n = res
636
+ where = chats.export_root() / chats.EXPORT_DIRS[got][0]
637
+ return {"ok": True, "kind": "import", "counts": {"conversations": n}, "lines": [
638
+ f"Imported {n:,} {chats.GUIDES[got]['name']} conversation{_s(n)} into {where}. "
639
+ + _keepfold_hint(), importers.report_line(chats.GUIDES[got]["name"], res.report())]}
640
+
641
+
642
+ def drop_old_task() -> bool:
643
+ """Delete the Task Scheduler entry older versions made (Windows); True when one was there."""
644
+ from keepfold.app import targets
645
+ if status.test_copy(): # a test copy never deletes the real install's entry
646
+ return False
647
+ return targets._run(["schtasks", "/Delete", "/F", "/TN", status.LOGIN_TASK], timeout=30)[0]
648
+
649
+
650
+ def migrate_login(root: Path | None) -> None:
651
+ """At app start (Windows): an old Task Scheduler entry becomes the Run value, for this
652
+ app's vault (shortcut: assumes the task served the default vault, as the app made it)."""
653
+ if root is None or status.login_file() is not None or status.run_get() is not None:
654
+ return
655
+ if drop_old_task():
656
+ status.run_set(status.login_command(root))
657
+
658
+
659
+ def login(job, root: Path, on: bool) -> dict:
660
+ """Create or delete what starts the receiver at login: a Run value on Windows (and any old
661
+ Task Scheduler entry goes), else `status.login_file()` with its launchctl or systemctl
662
+ commands."""
663
+ from keepfold.app import targets
664
+ if (f := status.login_file()) is None:
665
+ if on:
666
+ value = status.login_command(root)
667
+ status.run_set(value)
668
+ job.say(f"added the Run value: {value}")
669
+ else:
670
+ status.run_delete()
671
+ job.say("removed the Run value")
672
+ if drop_old_task():
673
+ job.say("removed the old Task Scheduler entry")
674
+ return {"ok": True, "lines": [("Starts at login: " + value) if on
675
+ else "No longer starts at login."]}
676
+ if on:
677
+ f.parent.mkdir(parents=True, exist_ok=True)
678
+ f.write_text(status.login_text(root), encoding="utf-8", newline="\n")
679
+ job.say(f"wrote {f}")
680
+ lines = []
681
+ for args in status.login_commands(on):
682
+ job.say("running: " + " ".join(args))
683
+ ok, out = targets._run(args, timeout=30)
684
+ if not ok and on:
685
+ raise ValueError(f"{args[0]} failed: {out[-300:]}")
686
+ lines.append(out[-300:])
687
+ if not on: # removing the file is what stops it, even when unload or disable failed
688
+ f.unlink(missing_ok=True)
689
+ job.say(f"removed {f}")
690
+ return {"ok": True, "lines": lines}