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,54 @@
1
+ """The Windows PATH in the registry: the system PATH (read only) and the user PATH
2
+ (HKCU\\Environment `Path`), which Status's Claude Code Fix rewrites with the installed Keepfold's
3
+ bin folder first. Twin of installer/setup_app.py's `_same`/`get_user_path`/`set_user_path`
4
+ (the installer does not import keepfold code); a fix to one belongs in both."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ SYSTEM_KEY = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
11
+
12
+
13
+ def _same(a: str, b: str) -> bool:
14
+ def norm(s):
15
+ return os.path.normcase(os.path.expandvars(s.strip().strip('"')).rstrip("\\/"))
16
+ return norm(a) == norm(b)
17
+
18
+
19
+ def first(current: str, entry: str) -> str:
20
+ """`current` (a `;` PATH) with `entry` first: every other entry kept in order, no copy of
21
+ `entry` left behind, empty entries dropped."""
22
+ return ";".join([entry, *(p for p in current.split(";") if p.strip() and not _same(p, entry))])
23
+
24
+
25
+ def in_system(folder: str) -> bool:
26
+ """`folder` is on the system PATH, which Windows puts before the user PATH."""
27
+ import winreg
28
+ try:
29
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, SYSTEM_KEY) as k:
30
+ value = str(winreg.QueryValueEx(k, "Path")[0])
31
+ except OSError:
32
+ return False
33
+ return any(_same(p, folder) for p in value.split(";") if p.strip())
34
+
35
+
36
+ def put_first(folder: str) -> None:
37
+ """The user PATH with `folder` first (its registry type kept), then the change announced."""
38
+ import winreg
39
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0,
40
+ winreg.KEY_READ | winreg.KEY_SET_VALUE) as k:
41
+ try:
42
+ value, kind = winreg.QueryValueEx(k, "Path")
43
+ except FileNotFoundError:
44
+ value, kind = "", winreg.REG_EXPAND_SZ
45
+ if kind not in (winreg.REG_SZ, winreg.REG_EXPAND_SZ):
46
+ kind = winreg.REG_EXPAND_SZ
47
+ winreg.SetValueEx(k, "Path", 0, kind, first(str(value), folder))
48
+ broadcast()
49
+
50
+
51
+ def broadcast() -> None: # tests replace this
52
+ """WM_SETTINGCHANGE "Environment" to every window, so programs started next see the PATH."""
53
+ import ctypes
54
+ ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x1A, 0, "Environment", 2, 5000, None)
keepfold/app/wizard.py ADDED
@@ -0,0 +1,506 @@
1
+ """The Setup wizard (docs/design/keepfold-app.md section 2.6): vault, search model, local AI
2
+ runner, a model sized to this computer, a test, then the optional sections.
3
+
4
+ Nothing downloads or installs unless the owner clicks a button naming the item, its size and
5
+ its source; each download runs as a cancellable process. `keepfold.localllm` never downloads."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import functools
11
+ import json
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from pathlib import Path
21
+
22
+ from keepfold import session
23
+ from keepfold._proc import proxy_env
24
+ from keepfold.app import actions, status, targets
25
+
26
+ # The models Setup offers: edit tags and sizes here. Sizes are approximate (4-bit downloads).
27
+ MODELS = [
28
+ {"id": "2b", "label": "Qwen 3.5 2B", "min_gb": 0, "ollama": "qwen3.5:2b",
29
+ "lms": "qwen/qwen3.5-2b", "size": "about 2 GB", "bytes": 2 * 10**9,
30
+ "tradeoff": "Fast on any computer; good enough to sort pages into topics."},
31
+ {"id": "4b", "label": "Qwen 3.5 4B", "min_gb": 6, "ollama": "qwen3.5:4b",
32
+ "lms": "qwen/qwen3.5-4b", "size": "about 3 GB", "bytes": 3 * 10**9,
33
+ "tradeoff": "Better one-line summaries; wants 6 GB of graphics memory or RAM."},
34
+ {"id": "9b", "label": "Qwen 3.5 9B", "min_gb": 10, "ollama": "qwen3.5:9b",
35
+ "lms": "qwen/qwen3.5-9b", "size": "about 6 GB", "bytes": 6 * 10**9,
36
+ "tradeoff": "The best answers; slow without 10 GB or more."},
37
+ ]
38
+ EMBED = {"size": "about 150 MB", "source": "huggingface.co"}
39
+ # council 18 Nov: connect first (the first useful result; recall falls back to keywords until
40
+ # the search model is in), then the search model; the multi-GB local model is optional
41
+ ORDER = ("vault", "connect", "embed", "history", "llm")
42
+ OLLAMA_PAGE = "https://ollama.com/download"
43
+ LMSTUDIO_PAGE = "https://lmstudio.ai/download"
44
+ OLLAMA_SIZE, OLLAMA_BYTES = "about 1 GB", 10**9
45
+ OLLAMA_LICENSE = "https://github.com/ollama/ollama/blob/main/LICENSE"
46
+ GIT_PAGE = "https://git-scm.com/downloads"
47
+ GIT_SIZE, GIT_BYTES = "about 70 MB", 70 * 10**6
48
+ GIT_LICENSE = "https://git-scm.com/about/free-and-open-source"
49
+ # winget run from the app has no console to answer on (stdin is closed): never ask. The
50
+ # agreements are accepted only by a button shown beside the package's License link.
51
+ WINGET = ["--source", "winget", "--disable-interactivity", "--accept-package-agreements",
52
+ "--accept-source-agreements"]
53
+ REGISTRY = "https://registry.ollama.ai" # where `ollama pull` downloads from
54
+ SPARE_BYTES = 10**9 # free space a download must leave behind
55
+ LINUX_INSTALL = "curl -fsSL https://ollama.com/install.sh | sh"
56
+ RUNNERS = {"ollama": "Ollama", "lmstudio": "LM Studio"} # Ollama is the recommended one
57
+ STOPPED = "{} is installed but not running: click Start (or run `keepfold llm start`)."
58
+ START_WAIT_S = 15 # Ollama's server takes a few seconds to answer after a start
59
+
60
+
61
+ # ---- hardware ---------------------------------------------------------------------------------
62
+
63
+
64
+ def _vram_gb() -> float | None:
65
+ """The largest NVIDIA GPU's memory, from nvidia-smi; None without one."""
66
+ if targets._which("nvidia-smi") is None:
67
+ return None
68
+ ok, out = targets._run(["nvidia-smi", "--query-gpu=memory.total",
69
+ "--format=csv,noheader,nounits"], timeout=10)
70
+ mib = [float(x) for x in out.split() if x.replace(".", "", 1).isdigit()] if ok else []
71
+ return round(max(mib) / 1024, 1) if mib else None
72
+
73
+
74
+ def _ram_gb() -> float | None:
75
+ try:
76
+ if sys.platform == "win32":
77
+ class Mem(ctypes.Structure):
78
+ _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
79
+ ("ullTotalPhys", ctypes.c_ulonglong),
80
+ *((n, ctypes.c_ulonglong) for n in (
81
+ "ullAvailPhys", "ullTotalPageFile", "ullAvailPageFile",
82
+ "ullTotalVirtual", "ullAvailVirtual", "ullAvailExtendedVirtual"))]
83
+ m = Mem()
84
+ m.dwLength = ctypes.sizeof(Mem)
85
+ if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)):
86
+ return None
87
+ return round(m.ullTotalPhys / 2**30, 1)
88
+ return round(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 2**30, 1)
89
+ except (AttributeError, OSError, ValueError):
90
+ return None
91
+
92
+
93
+ @functools.cache # nvidia-smi or a RAM query: the machine does not change while the app runs
94
+ def hardware() -> dict:
95
+ if (gb := _vram_gb()) is not None:
96
+ return {"kind": "gpu", "gb": gb, "label": f"{gb:g} GB of graphics memory (NVIDIA)"}
97
+ gb = _ram_gb()
98
+ return {"kind": "ram", "gb": gb,
99
+ "label": f"{gb:g} GB of memory (no NVIDIA graphics card found)" if gb
100
+ else "memory size unknown"}
101
+
102
+
103
+ def recommend(gb: float | None, kind: str = "gpu") -> str:
104
+ """≤ 4 GB → 2B, 6–8 GB → 4B, ≥ 10 GB → 9B (sizes in between round down); without an
105
+ NVIDIA card ("ram") at most 4B, since 9B runs slowly there (it stays selectable)."""
106
+ if gb is None or gb < 6:
107
+ return "2b"
108
+ return "4b" if gb < 10 or kind != "gpu" else "9b"
109
+
110
+
111
+ def model(id: str) -> dict:
112
+ for m in MODELS:
113
+ if m["id"] == id:
114
+ return m
115
+ raise ValueError(f"unknown model {id!r}")
116
+
117
+
118
+ # ---- runners ------------------------------------------------------------------------------------
119
+
120
+
121
+ def ollama_exe() -> str | None:
122
+ """`ollama` on PATH, or where the Windows installer puts it (PATH is not updated for a
123
+ process started before the install)."""
124
+ if found := targets._which("ollama"):
125
+ return found
126
+ local = os.environ.get("LOCALAPPDATA")
127
+ p = Path(local, "Programs", "Ollama", "ollama.exe") if local else None
128
+ return str(p) if p and p.is_file() else None
129
+
130
+
131
+ def install_plan() -> dict:
132
+ """How to install Ollama here: a command the app may run on click, or one shown only."""
133
+ if sys.platform == "win32":
134
+ ok = targets._which("winget") is not None
135
+ return {"run": ["winget", "install", "--id", "Ollama.Ollama", "-e", *WINGET]
136
+ if ok else None, "source": "winget package Ollama.Ollama, from ollama.com",
137
+ "size": OLLAMA_SIZE, "page": OLLAMA_PAGE, "license": OLLAMA_LICENSE}
138
+ if sys.platform == "darwin":
139
+ ok = targets._which("brew") is not None
140
+ return {"run": ["brew", "install", "ollama"] if ok else None,
141
+ "source": "Homebrew", "size": OLLAMA_SIZE, "page": OLLAMA_PAGE}
142
+ return {"run": None, "show": LINUX_INSTALL, "source": "ollama.com", "size": OLLAMA_SIZE,
143
+ "page": OLLAMA_PAGE}
144
+
145
+
146
+ def _ollama_state(serving: list[str] | None) -> str:
147
+ return "running" if serving is not None else "stopped" if ollama_exe() else "not_installed"
148
+
149
+
150
+ def _lms_state(exe: str | None) -> str:
151
+ if exe is None:
152
+ return "not_installed"
153
+ from keepfold import localllm
154
+ st = localllm.lmstudio_state()
155
+ return "running" if st and st["port"] else "stopped"
156
+
157
+
158
+ def runner_state(runner: str) -> str:
159
+ """"not_installed", "stopped" or "running"."""
160
+ if runner == "ollama":
161
+ return _ollama_state(status.ollama_models())
162
+ if runner == "lmstudio":
163
+ return _lms_state(status.lms_path())
164
+ raise ValueError("runner must be ollama or lmstudio")
165
+
166
+
167
+ def _ollama_start_cmd() -> list[str]:
168
+ """Ollama's desktop app when installed (it runs the server), else `ollama serve`."""
169
+ local = os.environ.get("LOCALAPPDATA")
170
+ if sys.platform == "win32" and local and (
171
+ app := Path(local, "Programs", "Ollama", "ollama app.exe")).is_file():
172
+ return [str(app)]
173
+ if sys.platform == "darwin" and Path("/Applications/Ollama.app").is_dir():
174
+ return ["open", "-a", "Ollama"]
175
+ return [ollama_exe(), "serve"]
176
+
177
+
178
+ def start(runner: str) -> dict:
179
+ """Start an installed runner and wait until it answers. Ollama: its desktop app, else a
180
+ detached `ollama serve` with no OLLAMA_HOST set by us; LM Studio: `lms server start`.
181
+ {"ok", "state", "lines"}; raises ValueError when it is not installed or fails to start."""
182
+ if runner not in RUNNERS:
183
+ raise ValueError("runner must be ollama or lmstudio")
184
+ name, now = RUNNERS[runner], runner_state(runner)
185
+ if now == "running":
186
+ return {"ok": True, "state": now, "lines": [f"{name} is already running"]}
187
+ if now == "not_installed":
188
+ raise ValueError(f"{name} is not installed yet (step 3).")
189
+ if runner == "lmstudio":
190
+ args = [status.lms_path(), "server", "start"]
191
+ ok, out = targets._run(args, timeout=60)
192
+ if not ok:
193
+ raise ValueError(f"`lms server start` failed: {out[-300:]}")
194
+ else:
195
+ args = _ollama_start_cmd()
196
+ detach = ({"creationflags": subprocess.DETACHED_PROCESS
197
+ | subprocess.CREATE_NEW_PROCESS_GROUP} if sys.platform == "win32"
198
+ else {"start_new_session": True}) # outlives the app and its console
199
+ try:
200
+ actions._popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
201
+ stderr=subprocess.DEVNULL, close_fds=True, **detach)
202
+ except OSError as e:
203
+ raise ValueError(f"could not start {args[0]}: {e}") from None
204
+ deadline = time.monotonic() + START_WAIT_S
205
+ while (now := runner_state(runner)) != "running" and time.monotonic() < deadline:
206
+ time.sleep(0.5)
207
+ ran = "ran: " + subprocess.list2cmdline(args)
208
+ if now != "running":
209
+ return {"ok": False, "state": now, "lines": [
210
+ ran, f"{name} did not answer within {START_WAIT_S} s; try Start again, or open "
211
+ f"{name} yourself."]}
212
+ return {"ok": True, "state": now, "lines": [ran, f"{name} is running"]}
213
+
214
+
215
+ def _have(m: dict, ollama: list[str] | None, lms: list[dict]) -> dict:
216
+ tag, key = m["ollama"].lower(), m["lms"].lower()
217
+ return {"ollama": any(n.lower() in (tag, tag + ":latest") for n in ollama or []),
218
+ "lmstudio": any(key in (r["key"].lower(), r["name"].lower()) or
219
+ r["key"].lower().endswith("/" + key.split("/")[-1]) for r in lms)}
220
+
221
+
222
+ def state(root: Path | None, scanned: dict | None = None) -> dict:
223
+ v = status.vault(root)
224
+ e = status.embedding(root if v["ok"] else None)
225
+ q = status.llm(quick=True) # the slow probes (~2.7 s), kept and shared with Status's
226
+ ollama, lms_exe = q["ollama"], q["lms"]
227
+ lms = status.kept(("lms_models", None), status.lms_models) if lms_exe else []
228
+ hw = hardware()
229
+ models = [{**m, "have": _have(m, ollama, lms)} for m in MODELS]
230
+ cfg = status.config().get("localllm")
231
+ cfg = cfg if isinstance(cfg, dict) else {}
232
+ from keepfold import cli
233
+ o_state = _ollama_state(ollama)
234
+ l_state = "not_installed" if lms_exe is None else "running" if q["server_port"] else "stopped"
235
+ return {
236
+ # moved: the config names a folder that is gone; Setup asks instead of recreating it
237
+ "vault": {"done": v["ok"], "path": v["path"], "default": str(cli._default_vault()),
238
+ "moved": bool(v["path"]) and not v.get("exists")},
239
+ "git": {"found": session.git_exe() is not None, "install": git_plan(),
240
+ "enabled": session.git_choice()[0]},
241
+ "embed": {"done": e["downloaded"], "indexed": e.get("indexed"), **EMBED},
242
+ "runner": {"done": "running" in (o_state, l_state), "recommend": "ollama",
243
+ "ollama": {"found": ollama_exe() is not None, "serving": ollama is not None,
244
+ "state": o_state},
245
+ "lmstudio": {"found": lms_exe is not None, "page": LMSTUDIO_PAGE,
246
+ "state": l_state},
247
+ "install": install_plan()},
248
+ "model": {"done": any(m["have"]["ollama"] or m["have"]["lmstudio"] for m in models),
249
+ "hardware": hw, "recommend": recommend(hw["gb"], hw["kind"]), "options": models},
250
+ "test": {"done": cfg.get("enabled") is True and bool(cfg.get("model")),
251
+ "model": cfg.get("model"), "runner": cfg.get("runner")},
252
+ "history": (h := status.history(root if v["ok"] else None, scanned or {}))
253
+ | {"done": bool(h.get("imported"))},
254
+ "order": list(ORDER),
255
+ }
256
+
257
+
258
+ # ---- the steps' jobs ---------------------------------------------------------------------------
259
+
260
+
261
+ TEMP_REFUSED = ("That folder is inside Windows' temporary folder, which Windows can empty at any "
262
+ "time. Pick a folder outside it, such as one in Documents.")
263
+
264
+
265
+ def vault_path(path) -> Path:
266
+ """The folder `make_vault` would set up, or ValueError in plain words. A temp folder is
267
+ refused while a real vault exists; a first setup may use it (Status warns). The app checks
268
+ this before the job starts, so a refused folder is one message, not a failed job too."""
269
+ from keepfold import taint
270
+ from keepfold.vault import in_temp_folder
271
+ if not isinstance(path, str) or not path.strip():
272
+ raise ValueError("Choose a folder for the vault.")
273
+ root = Path(path.strip().strip("\"'")).expanduser()
274
+ if not root.is_absolute():
275
+ raise ValueError("Give the full path of the folder, such as C:\\Users\\you\\Keepfold.")
276
+ root = root.resolve()
277
+ if root.exists() and not root.is_dir():
278
+ raise ValueError(f"{root} is a file; pick a folder.")
279
+ current = taint.config().get("vault")
280
+ if (current and Path(current).is_dir() and not in_temp_folder(current)
281
+ and in_temp_folder(root)):
282
+ raise ValueError(TEMP_REFUSED)
283
+ return root
284
+
285
+
286
+ def make_vault(job, path: str) -> tuple[Path, dict]:
287
+ """`keepfold init` on the chosen folder (it becomes the default vault), refused as
288
+ `vault_path` says before anything is made there."""
289
+ from keepfold import cli
290
+ root = vault_path(path)
291
+ job.say(f"setting up {root}")
292
+ did, skipped, warned = cli._init(root, default=True)
293
+ from keepfold import doctor
294
+ if (sync := doctor.check_onedrive(root))[0] != "PASS":
295
+ warned.append(f"{sync[2]}: {sync[3]}")
296
+ for line in [*did, *warned]:
297
+ job.say(str(line))
298
+ return root, {"ok": True, "vault": str(root),
299
+ "lines": [str(x) for x in [*did, *warned]][-100:]}
300
+
301
+
302
+ def _keepfold() -> str:
303
+ from keepfold import clients
304
+ return clients.keepfold_command()
305
+
306
+
307
+ def embed(job, root: Path | None) -> dict:
308
+ """`keepfold model download` (the only path that fetches the search model)."""
309
+ return actions.run_proc(job, [_keepfold(), "model", "download",
310
+ *(["--vault", str(root)] if root else [])], env=proxy_env())
311
+
312
+
313
+ def voice(job) -> dict:
314
+ """`keepfold model download --voice` (the only path that installs faster-whisper and fetches
315
+ the speech model), on the owner's click."""
316
+ return actions.run_proc(job, [_keepfold(), "model", "download", "--voice"], env=proxy_env())
317
+
318
+
319
+ def index(job, root: Path) -> dict:
320
+ return actions.run_proc(job, [_keepfold(), "model", "build", "--vault", str(root)])
321
+
322
+
323
+ def git_plan(scope: str = "user") -> dict:
324
+ """How to get git (the vault's history and undo): winget on Windows, else its page.
325
+ `scope` "user" needs no admin; "machine" is offered only after that failed, and Windows
326
+ then asks for admin permission itself (Keepfold never elevates)."""
327
+ if scope not in ("user", "machine"):
328
+ raise ValueError("scope must be user or machine")
329
+ run = (["winget", "install", "--id", "Git.Git", "-e", "--scope", scope, *WINGET]
330
+ if sys.platform == "win32" and targets._which("winget") else None)
331
+ return {"run": run, "source": "winget package Git.Git, from git-scm.com", "size": GIT_SIZE,
332
+ "page": GIT_PAGE, "license": GIT_LICENSE}
333
+
334
+
335
+ ADMIN_GIT = ("Git could not be installed for your Windows account only. It can be installed "
336
+ "for everyone on this computer instead; Windows will ask for admin permission.")
337
+
338
+
339
+ def install_git(job, scope: str = "user", root: Path | None = None) -> dict:
340
+ """winget's Git, then (git on, `root` a vault) the vault's history starts at once: the
341
+ app finds the new git itself, so nobody quits and reopens Keepfold. A failed user-scope
342
+ install says so and sets "admin" (the page then offers the machine-scope install)."""
343
+ plan = git_plan(scope)
344
+ if not plan["run"]:
345
+ raise ValueError(f"Install git yourself from {plan['page']}")
346
+ out = actions.run_proc(job, plan["run"])
347
+ if out["cancelled"]:
348
+ return out
349
+ if not out["ok"]:
350
+ if scope == "user": # the page offers the machine-scope install with its License link
351
+ out |= {"admin": ADMIN_GIT, "license": plan["license"]}
352
+ return out
353
+ if session.git_exe() is None:
354
+ out["lines"].append("Git is installed, but Keepfold cannot find it yet. Quit Keepfold and "
355
+ "open it again, then click Use this folder under Vault.")
356
+ return out
357
+ if root is None or not session.git_choice()[0] or not (root / ".keepfold").is_dir():
358
+ out["lines"].append("Git is installed.")
359
+ return out
360
+ from keepfold import cli
361
+ from keepfold.vault import VaultError
362
+ try:
363
+ did, _, warned = cli._init(root)
364
+ except VaultError as e:
365
+ out["lines"].append(f"Git is installed, but starting your vault's history failed: {e} "
366
+ "Click Use this folder under Vault to try again.")
367
+ return out
368
+ out["lines"] += [str(x) for x in [*did, *warned]]
369
+ out["lines"].append("Git is installed and your vault's history has started.")
370
+ return out
371
+
372
+
373
+ def size_text(n: int) -> str:
374
+ """"about 2.0 GB" or "about 70 MB"."""
375
+ return f"about {n / 10**9:.1f} GB" if n >= 10**9 else f"about {max(1, round(n / 10**6))} MB"
376
+
377
+
378
+ def free_space_ok(path, need_bytes: int) -> tuple[bool, str]:
379
+ """(ok, message) for a download of `need_bytes` into `path` (its nearest existing folder
380
+ counts): ok while it leaves SPARE_BYTES free. The message says both sizes, for example
381
+ "Needs about 2.0 GB; 1.1 GB free on C:." A failed check never blocks."""
382
+ p = Path(path).expanduser().absolute()
383
+ while not p.exists() and p != p.parent:
384
+ p = p.parent
385
+ try:
386
+ free = shutil.disk_usage(p).free
387
+ except OSError:
388
+ return True, ""
389
+ msg = f"Needs {size_text(need_bytes)}; {free / 10**9:.1f} GB free on {p.drive or 'this disk'}."
390
+ if free >= need_bytes + SPARE_BYTES:
391
+ return True, msg
392
+ return False, msg + " Free up some space first, or continue anyway."
393
+
394
+
395
+ def install_dir() -> Path:
396
+ """Where winget's per-user installs go (Ollama, Git), for the free-space check."""
397
+ return Path(os.environ.get("LOCALAPPDATA") or Path.home())
398
+
399
+
400
+ def models_dir(runner: str) -> Path:
401
+ """Where a runner keeps its models, for the free-space check."""
402
+ if runner == "ollama":
403
+ return Path(os.environ.get("OLLAMA_MODELS") or Path.home() / ".ollama")
404
+ return Path.home() / ".lmstudio"
405
+
406
+
407
+ def install_ollama(job) -> dict:
408
+ plan = install_plan()
409
+ if not plan["run"]:
410
+ raise ValueError(f"Install Ollama yourself from {plan['page']}"
411
+ + (f" or run: {plan['show']}" if plan.get("show") else ""))
412
+ return actions.run_proc(job, plan["run"])
413
+
414
+
415
+ # an Ollama registry name: name[:tag] or namespace/name[:tag]; names are lowercase, tags may
416
+ # not be (qwen3.5:4b-q4_K_M); never a URL or option
417
+ _OLLAMA_NAME = re.compile(r"(?:[a-z0-9][a-z0-9_-]*/)?[a-z0-9][a-z0-9._-]*"
418
+ r"(?::[A-Za-z0-9][A-Za-z0-9._-]*)?")
419
+
420
+
421
+ def ollama_name(name) -> str:
422
+ """`name` when it is a local Ollama model name to download; ValueError otherwise."""
423
+ from keepfold import localllm
424
+ if not isinstance(name, str) or len(name) > 100 or not _OLLAMA_NAME.fullmatch(name):
425
+ raise ValueError("Not an Ollama model name: use one like qwen3.5:4b.")
426
+ if localllm._cloud(name):
427
+ raise ValueError("That is a cloud model; Keepfold downloads local models only.")
428
+ return name
429
+
430
+
431
+ _SIZES: dict[str, int] = {} # a model's download size, once the registry told it
432
+
433
+
434
+ def ollama_size(name: str) -> int:
435
+ """The download size in bytes of Ollama model `name`: a Setup model's from MODELS, else
436
+ the total of its manifest on ollama.com's registry (one request, made on the owner's
437
+ click). ValueError in plain words when the registry does not know it or cannot be
438
+ reached."""
439
+ name = ollama_name(name)
440
+ if m := next((m for m in MODELS if m["ollama"] == name), None):
441
+ return m["bytes"]
442
+ if name in _SIZES:
443
+ return _SIZES[name]
444
+ repo, _, tag = name.partition(":")
445
+ repo = repo if "/" in repo else "library/" + repo
446
+ req = urllib.request.Request(f"{REGISTRY}/v2/{repo}/manifests/{tag or 'latest'}", headers={
447
+ "Accept": "application/vnd.docker.distribution.manifest.v2+json"})
448
+ try:
449
+ with urllib.request.urlopen(req, timeout=15) as r:
450
+ data = json.loads(r.read(1_000_000))
451
+ total = sum(int(x.get("size") or 0)
452
+ for x in [data.get("config") or {}, *(data.get("layers") or [])])
453
+ except urllib.error.HTTPError as e:
454
+ if e.code == 404:
455
+ raise ValueError(f"ollama.com has no model named {name}. Check the name on "
456
+ "ollama.com/library.") from None
457
+ total = 0
458
+ except (OSError, ValueError, TypeError, AttributeError):
459
+ total = 0
460
+ if total <= 0:
461
+ raise ValueError(f"Keepfold could not get the size of {name} from ollama.com. Check your "
462
+ "internet connection and try again.")
463
+ _SIZES[name] = total
464
+ return total
465
+
466
+
467
+ def pull_ollama(job, name: str) -> dict:
468
+ if (exe := ollama_exe()) is None:
469
+ raise ValueError("Ollama is not installed yet: install it under Setup → Local model.")
470
+ if status.ollama_models() is None: # `ollama pull` needs the server
471
+ raise ValueError(STOPPED.format("Ollama"))
472
+ return actions.run_proc(job, [exe, "pull", name], env=proxy_env())
473
+
474
+
475
+ def pull(job, id: str, runner: str) -> dict:
476
+ m = model(id)
477
+ if runner == "ollama":
478
+ return pull_ollama(job, m["ollama"])
479
+ if runner == "lmstudio":
480
+ if (exe := status.lms_path()) is None:
481
+ raise ValueError("LM Studio's `lms` was not found (step 3).")
482
+ return actions.run_proc(job, [exe, "get", m["lms"], "--yes"], env=proxy_env())
483
+ raise ValueError("runner must be ollama or lmstudio")
484
+
485
+
486
+ def test_and_save(job, id: str, runner: str) -> dict:
487
+ """Test the model with a synthetic prompt; on success turn it on in config."""
488
+ from keepfold import taint
489
+ m = model(id)
490
+ if runner not in ("ollama", "lmstudio"):
491
+ raise ValueError("runner must be ollama or lmstudio")
492
+ name = m["ollama"] if runner == "ollama" else m["lms"]
493
+ old = status.config().get("localllm")
494
+ local = {**(old if isinstance(old, dict) else {}), "enabled": True, "model": name,
495
+ "runner": runner}
496
+ try:
497
+ out = actions.llm_test(job, actions.llm_config(**local))
498
+ except ValueError:
499
+ if runner_state(runner) == "stopped":
500
+ raise ValueError(STOPPED.format(RUNNERS[runner])) from None
501
+ raise
502
+ taint.write_config(lambda cfg: {"localllm": { # merged under the lock
503
+ **(cfg["localllm"] if isinstance(cfg.get("localllm"), dict) else {}),
504
+ "enabled": True, "model": name, "runner": runner}})
505
+ job.say(f"saved: localllm on, {name} ({runner})")
506
+ return {**out, "lines": [*out["lines"], f"saved: local model on, {name}"]}