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
keepfold/doctor.py ADDED
@@ -0,0 +1,565 @@
1
+ """Environment checks for `keepfold doctor` (SPEC §7): each returns (status, name, detail, fix)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import sqlite3
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from keepfold import claims, share
14
+ from keepfold.app import targets
15
+ from keepfold.clients import claude_desktop_config_paths
16
+ from keepfold.contract import MAX_CHARS as CONTRACT_MAX_CHARS
17
+ from keepfold.events import EventLog
18
+ from keepfold.session import _git, git_choice, git_exe
19
+ from keepfold.vault import CHAT_ARCHIVE, PRIVATE_BROWSE_DIR, Vault
20
+
21
+
22
+ def connects() -> list[str]:
23
+ """The "Where Keepfold connects" section: a heading, then one line per destination off this
24
+ PC (keepfold.egress)."""
25
+ from keepfold import egress
26
+ return ["Where Keepfold connects:", *(f" {s}" for s in egress.summary())]
27
+
28
+
29
+ def check_python() -> tuple[str, str, str, str]:
30
+ name = "Python and FTS5"
31
+ ver = ".".join(map(str, sys.version_info[:3]))
32
+ if sys.version_info < (3, 12): # noqa: UP036 (the check is the point)
33
+ return "FAIL", name, f"Python {ver}", "Run keepfold through `uv run` (Python 3.12+)."
34
+ try:
35
+ sqlite3.connect(":memory:").execute("CREATE VIRTUAL TABLE t USING fts5(x)")
36
+ except sqlite3.Error as e:
37
+ return "FAIL", name, f"sqlite3 has no FTS5: {e}", "Use the uv-managed Python 3.12."
38
+ return "PASS", name, f"Python {ver}, sqlite {sqlite3.sqlite_version} with FTS5", ""
39
+
40
+
41
+ SYNC_MARKS = {"onedrive": "OneDrive", "dropbox": "Dropbox", "google drive": "Google Drive",
42
+ "googledrive": "Google Drive", "my drive": "Google Drive", "icloud": "iCloud",
43
+ "clouddocs": "iCloud"} # casefolded path text -> the sync service
44
+
45
+
46
+ def check_onedrive(root: Path) -> tuple[str, str, str, str]:
47
+ """WARN when the vault sits in a cloud-synced folder (OneDrive, Dropbox, Google Drive,
48
+ iCloud): sync breaks the lock and silently copies private pages off the machine."""
49
+ name = "Vault outside cloud sync"
50
+ root = Path(root).resolve()
51
+ text = str(root).casefold()
52
+ synced = next((svc for mark, svc in SYNC_MARKS.items() if mark in text), None)
53
+ for var in ("OneDrive", "OneDriveConsumer", "OneDriveCommercial"):
54
+ base = os.environ.get(var)
55
+ if base and root.is_relative_to(Path(base).resolve()):
56
+ synced = "OneDrive"
57
+ if synced:
58
+ return ("WARN", name, f"{root} is inside {synced}",
59
+ f"Move the vault out of {synced}; sync can break the lock and atomic writes, "
60
+ "and silently copies private pages and voice samples to the cloud.")
61
+ return "PASS", name, str(root), ""
62
+
63
+
64
+ def _old_repo(root: Path) -> bool:
65
+ """git is off but the vault still has a repo git can read: its remotes and history still
66
+ matter for privacy, so those read-only checks still run."""
67
+ return (root / ".git").exists() and git_exe() is not None
68
+
69
+
70
+ def _remote_warn(name: str, remotes: list[str], off: bool) -> tuple[str, str, str, str]:
71
+ return ("WARN", name, ("git is off in your settings, but the vault's repo still has "
72
+ if off else "") + f"remotes: {', '.join(remotes)}",
73
+ "Remove them with `git remote remove <name>`; a push would publish private "
74
+ "people pages and voice samples. The vault stays local.")
75
+
76
+
77
+ def check_git(root: Path) -> tuple[str, str, str, str]:
78
+ name = "Vault git: no remote, push blocked"
79
+ root = Path(root).resolve()
80
+ if not git_choice()[0]:
81
+ if _old_repo(root) and (remotes := _git(root, "remote").stdout.split()):
82
+ return _remote_warn(name, remotes, off=True)
83
+ return ("PASS", name, "git is off in your settings (your choice): Keepfold keeps no "
84
+ "history of the vault and `keepfold undo` is off", "")
85
+ if not (root / ".git").is_dir() and git_exe() is None:
86
+ return ("WARN", name, "git is not installed, so the vault has no history and undo does "
87
+ "nothing", "Install git: in the Keepfold app, Status → Git → Install Git "
88
+ "(Windows; or run `winget install --id Git.Git -e --scope user`); else get it "
89
+ "from git-scm.com. The app then starts the vault's history by itself; from a "
90
+ "terminal, run `keepfold init <vault>` after the install.")
91
+ if not (root / ".git").is_dir():
92
+ return "FAIL", name, "the vault has no git repo", "Run `keepfold init <vault>`."
93
+ if not (root / ".git" / "hooks" / "pre-push").is_file():
94
+ return "FAIL", name, "no pre-push hook", "Run `keepfold init <vault>` to add it."
95
+ remotes = _git(root, "remote").stdout.split()
96
+ if remotes:
97
+ return _remote_warn(name, remotes, off=False)
98
+ return "PASS", name, "no remote; pre-push hook present", ""
99
+
100
+
101
+ def check_private_browse_git(root: Path) -> tuple[str, str, str, str]:
102
+ """v7 C3: private browse pages must not be in the vault's git. Keepfold untracks them on the
103
+ next browse import, but never rewrites history; this says how."""
104
+ from keepfold.browse import forget
105
+
106
+ name = "Private browsing out of git"
107
+ root = Path(root)
108
+ git_on, kept = git_choice()
109
+ if not git_on:
110
+ if _old_repo(root) and (n := forget.private_in_history(root)):
111
+ return _history_warn(name, n)
112
+ return "PASS", name, "git is off in your settings (see Vault git)", ""
113
+ if kept:
114
+ return "PASS", name, "private browsing pages are kept in git by your choice", ""
115
+ if not (root / ".git").exists():
116
+ return "PASS", name, "no repo (see Vault git)", ""
117
+ if _git(root, "ls-files", "--", PRIVATE_BROWSE_DIR).stdout.strip():
118
+ return ("WARN", name, "browse/private/ is still tracked by git",
119
+ "Run `keepfold browse import` once (it untracks the folder), or run "
120
+ "`git rm -r --cached browse/private` in the vault and commit.")
121
+ if _git(root, "check-ignore", "-q", PRIVATE_BROWSE_DIR + "/x.md").returncode:
122
+ if not (root / PRIVATE_BROWSE_DIR).exists(): # an older vault, nothing private yet
123
+ return ("PASS", name, "no private pages yet; the .gitignore line is added before "
124
+ "the first one", "")
125
+ return ("WARN", name, "browse/private/ is not in the vault's .gitignore",
126
+ f"Run `keepfold init {root}` or `keepfold browse import`; either adds the line.")
127
+ n = forget.private_in_history(root)
128
+ if n:
129
+ return _history_warn(name, n)
130
+ return "PASS", name, "browse/private/ is ignored and in no commit", ""
131
+
132
+
133
+ def check_chat_archive_git(root: Path) -> tuple[str, str, str, str]:
134
+ """v9 C5: imported chat pages sit in archive/chats/, which the vault's .gitignore keeps out
135
+ of git."""
136
+ name = "Chat archive out of git"
137
+ root = Path(root)
138
+ if not (root / ".git").exists():
139
+ return "PASS", name, "no repo (see Vault git)", ""
140
+ if _git(root, "check-ignore", "-q", CHAT_ARCHIVE + "/x.md").returncode:
141
+ return ("WARN", name, f"{CHAT_ARCHIVE}/ is not in the vault's .gitignore",
142
+ f"Run `keepfold init {root}` or `keepfold chats archive`; either adds the line.")
143
+ if _git(root, "ls-files", "--", CHAT_ARCHIVE).stdout.strip():
144
+ return ("WARN", name, f"{CHAT_ARCHIVE}/ is still tracked by git",
145
+ f"Run `git rm -r --cached {CHAT_ARCHIVE}` in the vault and commit.")
146
+ return "PASS", name, f"{CHAT_ARCHIVE}/ is ignored", ""
147
+
148
+
149
+ def check_browse_legacy(root: Path) -> tuple[str, str, str, str]:
150
+ """F3: the browse files from before the store (`browse.legacy`), not read in yet."""
151
+ from keepfold.browse import legacy
152
+ from keepfold.vault import Vault
153
+ name = "Old browse files"
154
+ left = legacy.pending(Vault(root))
155
+ if not left:
156
+ return "PASS", name, "none left to read in", ""
157
+ return ("WARN", name, f"{len(left)} not read into the browsing store yet: "
158
+ + ", ".join(Path(r).name for r in left),
159
+ "Run `keepfold browse import` (or open the app): it reads them in and renames each "
160
+ "to <name>.migrated.")
161
+
162
+
163
+ def _history_warn(name: str, n: int) -> tuple[str, str, str, str]:
164
+ return ("WARN", name, f"{n} commit{'s' * (n != 1)} in the vault's git history hold "
165
+ "private browse pages",
166
+ "They are no longer committed, but old commits keep them. To remove them, "
167
+ "back up the vault, then in it run `git filter-repo --path browse/private "
168
+ "--invert-paths` (or `git filter-branch --index-filter \"git rm -r -q --cached "
169
+ "--ignore-unmatch browse/private\" -- --all`), then `git reflog expire "
170
+ "--expire=now --all` and `git gc --prune=now`. Keepfold never rewrites history "
171
+ "itself.")
172
+
173
+
174
+ def check_git_identity(root: Path) -> tuple[str, str, str, str]:
175
+ """N11: with no git identity every session commit fails silently, so `keepfold undo` has
176
+ nothing to revert."""
177
+ name = "Vault git identity"
178
+ if not git_choice()[0]:
179
+ return "PASS", name, "git is off in your settings (see Vault git)", ""
180
+ if not (Path(root) / ".git").is_dir():
181
+ return "PASS", name, "no repo (see Vault git)", ""
182
+ email = _git(Path(root), "config", "user.email").stdout.strip()
183
+ if not email:
184
+ return ("WARN", name, "git has no user.email here, so session commits fail and "
185
+ "`keepfold undo` does nothing",
186
+ f"Run `keepfold init {root}`; it sets Keepfold <keepfold@localhost> for this "
187
+ "vault only.")
188
+ return "PASS", name, email, ""
189
+
190
+
191
+ MODEL_READY = ".complete" # `keepfold model download` writes it into models_dir() when it is done
192
+
193
+
194
+ def search_model_ready() -> bool:
195
+ """The search model is whole: the download finished. Older downloads have no marker; they
196
+ count when no file is left half-written (Hugging Face's `*.incomplete`)."""
197
+ from keepfold import semantic
198
+
199
+ d = semantic.models_dir()
200
+ if (d / MODEL_READY).is_file():
201
+ return True
202
+ return d.is_dir() and any(d.iterdir()) and not any(d.rglob("*.incomplete"))
203
+
204
+
205
+ def installer() -> bool:
206
+ """Keepfold runs from a KeepfoldSetup.exe install (no terminal commands for its user)."""
207
+ from keepfold import update # update imports cli, which imports this module
208
+
209
+ return update.mode() == "installer"
210
+
211
+
212
+ def app_hint() -> str:
213
+ """How this user opens the app: the Start menu for an installer install, else the command."""
214
+ return "open Keepfold from the Start menu" if installer() else "run `keepfold app`"
215
+
216
+
217
+ def check_search_model() -> tuple[str, str, str, str]:
218
+ from keepfold import semantic
219
+
220
+ d = semantic.models_dir()
221
+ if search_model_ready():
222
+ return "PASS", "Search model", str(d), ""
223
+ return ("WARN", "Search model", "not downloaded: recall uses keywords only and a history "
224
+ "import files every page under Other",
225
+ "In the Keepfold app (Start menu), Setup → Download search model." if installer() else
226
+ "Run `keepfold model download` (about 150 MB, once) or use `keepfold app` → Setup.")
227
+
228
+
229
+ def check_on_path() -> tuple[str, str, str, str]:
230
+ """The Claude Code plugin's server and hooks run `keepfold` by name; hooks fail silently."""
231
+ if found := shutil.which("keepfold"):
232
+ return "PASS", "`keepfold` on PATH", found, ""
233
+ return ("WARN", "`keepfold` on PATH", "not found: the Claude Code plugin's server and hooks "
234
+ "cannot start it",
235
+ "Sign out of Windows and in again (setup added Keepfold to your PATH), or run "
236
+ "KeepfoldSetup.exe again." if installer() else
237
+ "Run `uv tool update-shell`, then open a new terminal.")
238
+
239
+
240
+ def check_ai_apps() -> tuple[str, str, str, str]:
241
+ """N9: WARN when no AI app the app's Connect section lists has a `keepfold` entry."""
242
+ name = "AI app connected"
243
+ on = [t.label for t in targets.targets() if t.connected()]
244
+ if on:
245
+ return "PASS", name, ", ".join(on), ""
246
+ return ("WARN", name, "no AI app runs Keepfold yet, so nothing reads or records anything",
247
+ "Open Keepfold from the Start menu and tick an app under Connect AI apps."
248
+ if installer() else
249
+ "Run `keepfold app` and tick an app under Connect, or `keepfold setup`.")
250
+
251
+
252
+ def check_old_connections() -> tuple[str, str, str, str]:
253
+ """R4: WARN while an AI app still holds an entry under the old name Cortex (an MCP entry,
254
+ a hook, a rules block, the cortex@cortex plugin): targets.migrate_old_entries, dry run."""
255
+ name = "Old Cortex connections"
256
+ try:
257
+ rows = [r for r in targets.migrate_old_entries(dry_run=True) if r["action"] != "nothing"]
258
+ except Exception as e: # noqa: BLE001 (a check never stops doctor)
259
+ return "WARN", name, f"could not check: {e}", ""
260
+ if not rows:
261
+ return "PASS", name, "none left", ""
262
+ return ("WARN", name, "; ".join(f"{r['app']}: {r['file']}" for r in rows),
263
+ " ".join(dict.fromkeys(
264
+ (f"{r['app']}: run `keepfold migrate` to move it ({r['note']})."
265
+ if r["action"] == "moved" else f"{r['app']}: {r['note']}") for r in rows)))
266
+
267
+
268
+ def check_local_model() -> tuple[str, str, str, str]:
269
+ from keepfold import localllm
270
+ from keepfold.taint import config
271
+
272
+ name = "Local model"
273
+ conf = config()
274
+ if not localllm.enabled(conf):
275
+ return "PASS", name, "off", ""
276
+ got = localllm.status(conf) # read-only, like `keepfold llm status`
277
+ if got["error"]: # a non-loopback url or a cloud model
278
+ return "WARN", name, got["error"], "Fix `localllm` in ~/.keepfold/config.yaml."
279
+ if (runner := got["runner"]) is None:
280
+ return ("WARN", name, "on, but not running: no local runner answers with the "
281
+ "configured model", "Run `keepfold llm start` (or `keepfold app` → Setup → Start).")
282
+ return "PASS", name, runner.describe(), ""
283
+
284
+
285
+ def check_kill(root: Path) -> tuple[str, str, str, str]:
286
+ """v5 PHASE4 V5: show the kill switch state (a state, not a fault)."""
287
+ on = share.killed(Vault(root))
288
+ return "PASS", "Kill switch", ("on: act-as-me and the reader role "
289
+ "are refused (`keepfold kill --off`)" if on else "off"), ""
290
+
291
+
292
+ def check_exclude() -> tuple[str, str, str, str]:
293
+ """Folders where Claude Code gets no priming and no Keepfold tools (a state); FAIL while
294
+ ~/.keepfold/config.yaml cannot be read, since every privacy choice then fails closed."""
295
+ from keepfold.taint import CONFIG_FIX, config_error, exclude_list
296
+
297
+ if err := config_error():
298
+ return "FAIL", "Settings file", err, CONFIG_FIX
299
+ folders = exclude_list()
300
+ return "PASS", "Excluded folders", "; ".join(folders) if folders else "none", ""
301
+
302
+
303
+ def check_me_pages(root: Path) -> tuple[str, str, str, str]:
304
+ """Pages added by later versions (e.g. me/voice.md) on an older vault."""
305
+ from keepfold.cli import ME_PAGES # cli imports doctor at module level
306
+
307
+ missing = [rel for rel in ME_PAGES if not (Path(root) / rel).exists()]
308
+ if missing:
309
+ return ("WARN", "me/ pages", "missing: " + ", ".join(missing),
310
+ f"Run `keepfold init {root}`; it adds missing pages and changes nothing else.")
311
+ return "PASS", "me/ pages", f"{len(ME_PAGES)} present", ""
312
+
313
+
314
+ SYNC_COPY_FIX = "Open both, keep what you want in the original, delete the copy."
315
+
316
+
317
+ def check_sync_copies(root: Path) -> tuple[str, str, str, str]:
318
+ """WARN on a sync tool's conflict copies (sync_copies.find_visible): a copied page is not
319
+ read (its edit lives only there); the event log reads each event once, copies included.
320
+ Up to 5 are named; a private page's copies are only counted, as an agent may run doctor."""
321
+ from keepfold import sync_copies
322
+
323
+ name = "Sync conflict copies"
324
+ shown, private = sync_copies.find_visible(Vault(root))
325
+ if not shown and not private:
326
+ return "PASS", name, "none", ""
327
+ parts = [", ".join(c for c, _ in shown[:5])] if shown else []
328
+ if len(shown) > 5:
329
+ parts.append(f"{len(shown) - 5} more")
330
+ if private:
331
+ parts.append(f"{private} cop{'y' if private == 1 else 'ies'} of private pages")
332
+ return ("WARN", name, f"{len(shown) + private} found: {' and '.join(parts)}",
333
+ f"{SYNC_COPY_FIX} Keepfold does not read a copied page, so an edit made on the "
334
+ "other device is only in the copy.")
335
+
336
+
337
+ def check_damaged_stores(root: Path) -> list[tuple[str, str, str, str]]:
338
+ """One WARN naming the damaged stores Keepfold moved aside (keepfold.quarantine) and started
339
+ again; no row when there are none."""
340
+ from keepfold import quarantine
341
+
342
+ names = [p.relative_to(root).as_posix() for p in quarantine.found(root)
343
+ if quarantine.STORE.fullmatch(p.name)]
344
+ if not names:
345
+ return []
346
+ return [("WARN", "Damaged databases moved aside", ", ".join(names),
347
+ "Keepfold found these damaged (often a sync tool copying a database apart from its "
348
+ "-wal file), set them aside and started fresh ones: search vectors are built "
349
+ "again, chats are read again. Delete the copies (with their -wal and -shm files) "
350
+ "once recall and chat import work again.")]
351
+
352
+
353
+ def check_id_clashes(root: Path) -> tuple[str, str, str, str]:
354
+ name = "Note ids unique across kinds"
355
+ seen: dict[str, list[str]] = {}
356
+ for kind in Vault.KIND_DIRS:
357
+ for path in sorted(p for d in Vault.dirs(kind) for p in (Path(root) / d).glob("*.md")):
358
+ seen.setdefault(path.stem, []).append(kind)
359
+ clashes = [f"{id} ({', '.join(kinds)})" for id, kinds in seen.items() if len(kinds) > 1]
360
+ if clashes:
361
+ return ("WARN", name, f"{len(clashes)} clash(es): {'; '.join(clashes)}",
362
+ "Rename one note in each pair; the index keeps only one note per id.")
363
+ return "PASS", name, f"{len(seen)} ids", ""
364
+
365
+
366
+ # RR-38: the import header (`Source: <label> · Date:`) or a chat page's Timeline line
367
+ _IMPORT_HEAD = re.compile(r"^(?:Timeline: [^\n]*?)?Source: ([^·\n]+?) · Date: [^\n]*$", re.M)
368
+ OTHER_SOURCE = "other" # a label no Keepfold importer writes: never printed, it may be page text
369
+
370
+
371
+ def _quartiles(xs: list[int]) -> list[int]:
372
+ s = sorted(xs)
373
+ return [s[round(q * (len(s) - 1))] for q in (0.25, 0.5, 0.75)]
374
+
375
+
376
+ def check_import_shapes(root: Path) -> list[tuple[str, str, str, str]]:
377
+ """RR-38: per import source, its pages' length quartiles (characters below the header
378
+ line) and the share of pages that are mostly links (sources.link_lines over 60% of the
379
+ lines, the quality gate's rule) or numbers only (under 10% letters and at least 30% digits
380
+ of their non-space characters). Numbers only: no page text, and a label Keepfold's importers
381
+ do not write shows as OTHER_SOURCE."""
382
+ from keepfold import chat_import, importers, sources
383
+ known = {*chat_import.LABELS.values(), *importers.LABELS.values(), "Calendar", "Documents",
384
+ "Git", "Highlights", "Pocket"}
385
+ shapes: dict[str, list[tuple[int, bool, bool]]] = {}
386
+ for p in Vault(root).note_paths("resource"):
387
+ try:
388
+ text = p.read_text("utf-8", errors="replace")
389
+ except OSError:
390
+ continue
391
+ if not (m := _IMPORT_HEAD.search(text, text.find("\n---", 3) + 1)):
392
+ continue
393
+ body = text[m.end():]
394
+ lines = [ln.strip() for ln in body.splitlines() if ln.strip()]
395
+ chars = [c for c in body if not c.isspace()]
396
+ links = bool(lines) and sources.link_lines(lines) > 0.6 * len(lines)
397
+ numbers = bool(chars) and sum(c.isalpha() for c in chars) < 0.1 * len(chars) \
398
+ and sum(c.isdigit() for c in chars) >= 0.3 * len(chars)
399
+ label = m.group(1).strip() if m.group(1).strip() in known else OTHER_SOURCE
400
+ shapes.setdefault(label, []).append((len(body.strip()), links, numbers))
401
+ if not shapes:
402
+ return [("PASS", "Import shapes", "no imported pages", "")]
403
+ out = []
404
+ for label, rows in sorted(shapes.items(), key=lambda kv: (-len(kv[1]), kv[0])):
405
+ q, n = _quartiles([r[0] for r in rows]), len(rows)
406
+ out.append(("PASS", f"Import shapes: {label}", (
407
+ f"{n:,} page{'s' * (n != 1)}, length quartiles {q[0]:,} / {q[1]:,} / {q[2]:,} "
408
+ f"characters, mostly links {sum(r[1] for r in rows) / n:.0%}, numbers only "
409
+ f"{sum(r[2] for r in rows) / n:.0%}"), ""))
410
+ return out
411
+
412
+
413
+ def check_claims(root: Path) -> tuple[str, str, str, str]:
414
+ """Live claims per authorship tier (v5 F3); a preview, so doctor records no baseline."""
415
+ v = Vault(root)
416
+ rows = claims.tiers(v, EventLog(v).iter_events())
417
+ return "PASS", "Claim tiers", ", ".join(
418
+ f"{t} {sum(r['tier'] == t for r in rows)}" for t in claims.TIERS), ""
419
+
420
+
421
+ def check_contract_size(root: Path) -> tuple[str, str, str, str]:
422
+ name = "Teaching contract size"
423
+ p = Path(root) / "me" / "teaching-contract.md"
424
+ n = len(p.read_bytes().decode("utf-8")) if p.is_file() else 0 # whole file, before scoping
425
+ if n > CONTRACT_MAX_CHARS:
426
+ return ("WARN", name, f"me/teaching-contract.md is {n} characters (whole file, before "
427
+ f"domain scoping); keepfold_start cuts the contract at {CONTRACT_MAX_CHARS} "
428
+ "(about 1,200 tokens)",
429
+ "Trim the core rules or move domain-specific ones under `## Domain overrides`.")
430
+ return "PASS", name, f"{n} characters", ""
431
+
432
+
433
+ def _base(s) -> str:
434
+ """File name of a Windows or POSIX path, whatever OS reads it."""
435
+ return re.split(r"[\\/]", str(s))[-1].casefold()
436
+
437
+
438
+ def _is_keepfold_server(entry) -> bool:
439
+ if not isinstance(entry, dict):
440
+ return False
441
+ base = _base
442
+ args = entry.get("args") if isinstance(entry.get("args"), list) else []
443
+ return base(entry.get("command", "")).startswith("keepfold") or (
444
+ "mcp" in args and any(base(a).startswith("keepfold") for a in args))
445
+
446
+
447
+ def _read_json(path: Path) -> dict:
448
+ try:
449
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
450
+ except (OSError, ValueError):
451
+ return {}
452
+ return data if isinstance(data, dict) else {}
453
+
454
+
455
+ def _has_keepfold(path: Path) -> bool:
456
+ """`path`'s mcpServers hold a Keepfold server."""
457
+ servers = _read_json(path).get("mcpServers")
458
+ return isinstance(servers, dict) and any(_is_keepfold_server(e) for e in servers.values())
459
+
460
+
461
+ def plugin_enabled(settings: Path | None = None) -> bool:
462
+ """True when ~/.claude/settings.json enables a `keepfold@...` Claude Code plugin."""
463
+ settings = settings or Path.home() / ".claude" / "settings.json"
464
+ plugins = _read_json(settings).get("enabledPlugins")
465
+ return isinstance(plugins, dict) and any(
466
+ str(k).startswith("keepfold@") and v is True for k, v in plugins.items())
467
+
468
+
469
+ def last_calls(root: Path) -> dict[str, float]:
470
+ """Client name -> the time (epoch s) of its latest call, from the marks the server writes
471
+ (mcp_server.SEEN: one file per client, its mtime the call, rewritten at most once a
472
+ minute)."""
473
+ out = {}
474
+ for p in (Path(root) / ".keepfold" / "clients").glob("*.txt"):
475
+ try:
476
+ out[p.read_text(encoding="utf-8").strip() or p.stem] = p.stat().st_mtime
477
+ except OSError:
478
+ continue
479
+ return out
480
+
481
+
482
+ def _when(t: float | None) -> str:
483
+ from datetime import datetime
484
+ return f"last call {datetime.fromtimestamp(t):%Y-%m-%d %H:%M}" if t else \
485
+ "no call recorded yet"
486
+
487
+
488
+ def check_clients(root: Path, settings: Path | None = None,
489
+ desktop_configs: list[Path] | None = None) -> list[tuple[str, str, str, str]]:
490
+ """Per Claude client: Keepfold configured, the Claude Code prime hook, and its last call."""
491
+ calls = last_calls(root)
492
+ seen = {k.casefold(): t for k, t in calls.items()}
493
+
494
+ def last(chat: bool) -> float | None: # the Chat tab names itself claude-ai; Code claude-code
495
+ ts = [t for k, t in seen.items() if "claude" in k and ("claude-code" in k) != chat]
496
+ return max(ts, default=None)
497
+
498
+ rows = []
499
+ paths = claude_desktop_config_paths() if desktop_configs is None else desktop_configs
500
+ have = [str(p) for p in paths if _has_keepfold(p)]
501
+ name, t = "Claude Desktop (Chat)", last(True)
502
+ if not paths:
503
+ rows.append(("PASS", name, "not installed", ""))
504
+ elif not have:
505
+ rows.append(("WARN", name, f"Keepfold is not in {paths[0]}, so its chats are not "
506
+ "logged", "Tick Claude Desktop under Connect in the Keepfold app (or run "
507
+ "`keepfold setup`), then quit Claude Desktop from the tray and open it "
508
+ "again."))
509
+ else:
510
+ rows.append(("PASS" if t else "WARN", name, f"Keepfold in {'; '.join(have)}; {_when(t)}",
511
+ "" if t else "Quit Claude Desktop from the tray, open it again and start "
512
+ "a new chat; if no call shows up, see docs/INSTALL.md (Troubleshooting)."))
513
+ home = Path.home()
514
+ settings = settings or home / ".claude" / "settings.json"
515
+ plugin = plugin_enabled(settings)
516
+ entry = _has_keepfold(home / ".claude.json")
517
+ hook = plugin or "prime-hook" in json.dumps(_read_json(settings).get("hooks") or {})
518
+ name, t = "Claude Code", last(False)
519
+ if not targets.ClaudeCode().detect(): # the app's test: `claude` on PATH counts too
520
+ rows.append(("PASS", name, "not installed", ""))
521
+ return rows
522
+ how = "plugin" if plugin else "~/.claude.json" if entry else \
523
+ "the desktop config only (its Code tab)" if have else ""
524
+ detail = (f"Keepfold from {how}" if how else "Keepfold not configured") + \
525
+ f"; prime hook {'installed' if hook else 'missing'}; {_when(t)}"
526
+ ok = bool(how) and hook and t
527
+ rows.append(("PASS" if ok else "WARN", name, detail, "" if ok else
528
+ "Tick Claude Code under Connect in the Keepfold app: it installs the Keepfold "
529
+ "plugin, which brings the server and the prime hook. Its chats are saved "
530
+ "from their transcripts either way."
531
+ if not (plugin and hook) else
532
+ "Restart Claude Code and start a new chat; if no call shows up, see "
533
+ "docs/INSTALL.md (Troubleshooting)."))
534
+ return rows
535
+
536
+
537
+ def check_duplicate_servers(settings: Path | None = None,
538
+ desktop_configs: list[Path] | None = None
539
+ ) -> tuple[str, str, str, str]:
540
+ """WARN when the Claude Code plugin and a desktop-config entry both register Keepfold."""
541
+ name = "One Keepfold server per client"
542
+ plugin_on = plugin_enabled(settings)
543
+ desktop = [str(p) for p in (claude_desktop_config_paths() if desktop_configs is None
544
+ else desktop_configs) if _has_keepfold(p)]
545
+ if plugin_on and desktop:
546
+ return ("WARN", name, "the Claude Code plugin and the desktop config "
547
+ f"({'; '.join(desktop)}) both register Keepfold; the desktop app's Code tab loads "
548
+ "both, so every tool and session is duplicated there",
549
+ "Keep both if you use them: Claude Chat needs the desktop entry and the Claude "
550
+ "Code CLI needs the plugin. In the desktop Code tab, expect two copies.")
551
+ return "PASS", name, "plugin" if plugin_on else ("desktop config" if desktop else "none"), ""
552
+
553
+
554
+ def check_moved(root: Path | None) -> list[tuple[str, str, str, str]]:
555
+ """R3: "Moved from Cortex" (keepfold.migrate.status: done, nothing to move, not moved yet,
556
+ both folders), and a WARN while a CORTEX_* variable is set (Keepfold reads only KEEPFOLD_*)."""
557
+ from keepfold import migrate
558
+ state, value, fix = migrate.status(root)
559
+ rows = [] if value == "nothing to move" else [ # only for people who had Cortex
560
+ ("PASS" if state == "ok" else "WARN", "Moved from Cortex", value, fix)]
561
+ if old := migrate.old_env():
562
+ rows.append(("WARN", "Old setting names", ", ".join(old) + " still set",
563
+ "Rename " + ", ".join(f"{k} to KEEPFOLD_{k[len('CORTEX_'):]}" for k in old)
564
+ + ": Keepfold no longer reads the CORTEX_ names."))
565
+ return rows