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/cli.py ADDED
@@ -0,0 +1,3254 @@
1
+ """The `keepfold` command-line interface. Logic lives in the core modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import webbrowser
14
+ from collections import Counter
15
+ from datetime import UTC, datetime, timedelta
16
+ from importlib.metadata import version
17
+ from pathlib import Path
18
+ from typing import Annotated
19
+
20
+ import typer
21
+
22
+ from keepfold import backup as backup_mod
23
+ from keepfold import dashboard as dashboard_mod
24
+ from keepfold import doctor as doctor_mod
25
+ from keepfold import levels, planner, render, taint
26
+ from keepfold import session as session_mod
27
+ from keepfold._proc import NO_WINDOW, proxy_env
28
+ from keepfold.catalog import Catalog, page_slug, resolve_or_inbox
29
+ from keepfold.catalog import sync as catalog_sync
30
+ from keepfold.events import EventLog, local_day, log_assessment, parse_ts, void_event
31
+ from keepfold.session import _git
32
+ from keepfold.update import CHECKOUT, REPO # stdlib-only; update must not import cli (a cycle)
33
+ from keepfold.vault import CHAT_ARCHIVE, PRIVATE_BROWSE_DIR, Vault, VaultError, in_temp_folder
34
+
35
+ EPILOG = ("About you: claims [--unasked|--summary], voice, export context · "
36
+ "Study: today, brief, reflect, recall, log, eval · "
37
+ "Import: import [--dry-run|--private], import-chats, watch, digest · "
38
+ "Chats: chats, harvest status, safety-net, fact-harvest · "
39
+ "Vault: lint, relink, concept duplicates, topics, replay, undo, backup · "
40
+ "Setup: app, setup [--print-mcp-config], init, doctor, model download, exclude")
41
+ # typer 0.29 prints <bool> after every flag, --help too; a flag takes no value, so show none
42
+ _display_type = typer.core.TyperOption.display_type_rich
43
+ typer.core.TyperOption.display_type_rich = \
44
+ lambda self, ctx: None if self.is_flag else _display_type(self, ctx)
45
+ app = typer.Typer(no_args_is_help=True, epilog=EPILOG)
46
+ log_app = typer.Typer(no_args_is_help=True, help="Record evidence (source external).")
47
+ concept_app = typer.Typer(no_args_is_help=True, help="Edit the concept catalog.")
48
+ app.add_typer(log_app, name="log")
49
+ app.add_typer(concept_app, name="concept")
50
+ catalog_app = typer.Typer(no_args_is_help=True, help="Keep catalog.yaml in step with the notes.")
51
+ app.add_typer(catalog_app, name="catalog")
52
+ session_app = typer.Typer(no_args_is_help=True, help="Close orphan sessions.")
53
+ app.add_typer(session_app, name="session")
54
+ model_app = typer.Typer(no_args_is_help=True, help="The local embedding model for recall.")
55
+ app.add_typer(model_app, name="model")
56
+ eval_app = typer.Typer(help="Measure ranking on logged usage; bare `keepfold eval` runs `all`.")
57
+ app.add_typer(eval_app, name="eval")
58
+ topics_app = typer.Typer(no_args_is_help=True, help="The topic tree: hubs, filing, rebuilds.")
59
+ app.add_typer(topics_app, name="topics")
60
+
61
+ VaultOpt = Annotated[Path | None, typer.Option(
62
+ "--vault", envvar="KEEPFOLD_VAULT", help="Vault path; else KEEPFOLD_VAULT, else "
63
+ "~/.keepfold/config.yaml.")]
64
+ SECTIONS = ("me", "tracks", "concepts", "areas", "domains", "mistakes", "problems",
65
+ "assessments", "applications", "sessions", "events", ".keepfold", "resources", "notes",
66
+ "projects", "decisions", "loops", "raw")
67
+ PRE_PUSH = "#!/bin/sh\necho 'keepfold: this vault is local only; push refused.' >&2\nexit 1\n"
68
+ WORKSPACE_IGNORE = ".obsidian/workspace*.json"
69
+ PRIVATE_BROWSE_IGNORE = PRIVATE_BROWSE_DIR + "/" # v7 C3: private browsing never enters git
70
+ CHAT_ARCHIVE_IGNORE = CHAT_ARCHIVE + "/" # v9 C5: imported AI chats never enter git
71
+ TMP_IGNORE = ".*.tmp" # D1 §2.2: a crash's leftover vault._atomic_write temp file never enters git
72
+ GITIGNORE = (f".keepfold/*\n!.keepfold/config.yaml\n{WORKSPACE_IGNORE}\n{PRIVATE_BROWSE_IGNORE}\n"
73
+ f"{CHAT_ARCHIVE_IGNORE}\n{TMP_IGNORE}\n")
74
+ SESSION_ID_RE = re.compile(r"^s_[0-9A-HJKMNP-TV-Z]{26}$")
75
+ OLD_COLOR_GROUPS = [("[keepfold_status:solid]", "1D9E75"), ("[keepfold_status:learning]", "BA7517"),
76
+ ("[keepfold_status:needs_refresh]", "993556"), ("path:domains", "7F77DD"),
77
+ ("path:areas", "888780"), ("path:projects", "7F77DD"),
78
+ ("path:resources", "888780"), ("path:notes", "888780"),
79
+ ("path:decisions", "888780")] # before v6: init upgrades only these
80
+ COLOR_GROUPS = [ # first match wins in Obsidian, so the order matters
81
+ ("file:my-topic-map", "FFFFFF"), ("tag:#topic", "F472B6"),
82
+ ('path:"me/" OR path:"people/"', "FDE68A"),
83
+ ("[keepfold_status:solid]", "22C55E"), ("[keepfold_status:needs_refresh]", "F59E0B"),
84
+ ("[keepfold_status:learning]", "3B82F6"), ("[keepfold_status:unverified]", "22D3EE"),
85
+ ("[keepfold_status:not_started]", "475569"),
86
+ ('path:"domains/"', "8B5CF6"), ('path:"areas/"', "2DD4BF"), ('path:"problems/"', "FB923C"),
87
+ ('path:"mistakes/"', "EF4444"), ('path:"assessments/" OR path:"applications/"', "FACC15"),
88
+ ('path:"projects/"', "84CC16"), ('path:"decisions/"', "10B981"),
89
+ ('path:"journal/"', "C4B5FD"), ('path:"notes/"', "A78BFA"), ('path:"loops/"', "FDBA74"),
90
+ ('path:"resources/"', "5B4636"),
91
+ ('path:"sessions/" OR path:"events/" OR path:"views/" OR path:"raw/"', "3F3F46"),
92
+ ("file:index OR file:inbox OR file:log OR file:Today OR file:BRIEF", "E2E8F0")]
93
+ BASES = {
94
+ "views/Due.base": """filters:
95
+ and:
96
+ - file.inFolder("concepts")
97
+ - keepfold_next <= today()
98
+ views:
99
+ - type: table
100
+ name: Due
101
+ order:
102
+ - file.name
103
+ - keepfold_status
104
+ - keepfold_next
105
+ sort:
106
+ - property: keepfold_next
107
+ direction: ASC
108
+ """,
109
+ "views/Weak.base": """filters:
110
+ and:
111
+ - file.inFolder("concepts")
112
+ - or:
113
+ - keepfold_status == "learning"
114
+ - keepfold_status == "needs_refresh"
115
+ views:
116
+ - type: table
117
+ name: Weak
118
+ order:
119
+ - file.name
120
+ - keepfold_status
121
+ - keepfold_next
122
+ """,
123
+ "views/Projects.base": """filters:
124
+ and:
125
+ - file.inFolder("projects")
126
+ views:
127
+ - type: table
128
+ name: Projects
129
+ groupBy:
130
+ property: status
131
+ direction: ASC
132
+ order:
133
+ - file.name
134
+ - status
135
+ - summary
136
+ - stack
137
+ """,
138
+ "views/Resources.base": """filters:
139
+ and:
140
+ - file.inFolder("resources")
141
+ views:
142
+ - type: table
143
+ name: Resources
144
+ groupBy:
145
+ property: status
146
+ direction: ASC
147
+ order:
148
+ - file.name
149
+ - status
150
+ - resource_type
151
+ - summary
152
+ """,
153
+ "views/Mistakes.base": """filters:
154
+ and:
155
+ - file.inFolder("mistakes")
156
+ views:
157
+ - type: table
158
+ name: Mistakes
159
+ order:
160
+ - file.name
161
+ - file.mtime
162
+ sort:
163
+ - property: file.mtime
164
+ direction: DESC
165
+ """,
166
+ }
167
+ VERDICTS = {"pass": "correct", "partial": "partial", "fail": "wrong"}
168
+
169
+
170
+ def _pointer() -> Path:
171
+ return Path.home() / ".keepfold" / "config.yaml"
172
+
173
+
174
+ def _write_config(**keys) -> Path:
175
+ """Set `keys` in ~/.keepfold/config.yaml, keeping its other keys (exclude, rerank)."""
176
+ return taint.write_config(keys)
177
+
178
+
179
+ def _vault(path: Path | Vault | None) -> Vault:
180
+ if isinstance(path, Vault): # undo reruns commands on its locked Vault (the lock is per Vault)
181
+ return path
182
+ if path is None and (v := taint.config().get("vault")):
183
+ path = Path(v)
184
+ if path is None:
185
+ raise VaultError("invalid_argument", "No vault set; run `keepfold app` (or `keepfold "
186
+ "setup` in a terminal) to set Keepfold up, or pass --vault PATH or set "
187
+ "KEEPFOLD_VAULT.")
188
+ if not Path(path).is_dir():
189
+ raise VaultError("invalid_argument", f"The vault folder {path} does not exist; "
190
+ "run `keepfold init <path>`.")
191
+ _opened.append(Vault(Path(path)))
192
+ return _opened[-1]
193
+
194
+
195
+ def _refuse_excluded(action: str) -> None:
196
+ """Commands that print me/ text refuse inside an `exclude:` folder, as the server does:
197
+ an agent there could otherwise read the user's lines through Bash."""
198
+ if folder := taint.excluded(*taint.session_dirs()):
199
+ raise VaultError("invalid_argument", f"{folder} is excluded; refusing to {action}.")
200
+
201
+
202
+ _opened: list[Vault] = [] # the vaults this command opened; _errors commits what it wrote
203
+ _depth = 0 # undo reruns replay and today; only the outermost command commits
204
+
205
+
206
+ def _commit_cli(name: str) -> None:
207
+ """`keepfold: cli <name>` commit of the files this command wrote (none: no commit). Other
208
+ uncommitted changes stay for the next session close's `other changes` commit."""
209
+ for v in dict.fromkeys(_opened):
210
+ if v.writes:
211
+ session_mod._commit(v, f"keepfold: cli {name}", v.wrote_since(0))
212
+
213
+
214
+ def _errors(fn):
215
+ """Print a VaultError as one line on stderr and exit 1, instead of a traceback. On
216
+ success, commit the vault files the command wrote (not for `mcp`: its sessions commit)."""
217
+ @functools.wraps(fn)
218
+ def wrapper(*args, **kwargs):
219
+ global _depth
220
+ if _depth == 0:
221
+ _opened.clear()
222
+ _depth += 1
223
+ try:
224
+ out = fn(*args, **kwargs)
225
+ except VaultError as e:
226
+ typer.echo(f"error ({e.code}): {e}", err=True)
227
+ raise typer.Exit(1) from None
228
+ finally:
229
+ _depth -= 1
230
+ if _depth == 0 and fn.__name__ != "mcp":
231
+ _commit_cli(fn.__name__.removesuffix("_cmd").replace("_", " ")) # "log taught"
232
+ return out
233
+ return wrapper
234
+
235
+
236
+ def _version(value: bool) -> None:
237
+ if value:
238
+ typer.echo(f"keepfold {version('keepfold')}")
239
+ raise typer.Exit()
240
+
241
+
242
+ @app.callback()
243
+ def main(
244
+ _v: bool = typer.Option(False, "--version", callback=_version, is_eager=True),
245
+ ) -> None:
246
+ """Keepfold, your local second brain. New here? Run `keepfold app`."""
247
+ for stream in (sys.stdout, sys.stderr):
248
+ try:
249
+ stream.reconfigure(encoding="utf-8") # state glyphs on a cp1252 console
250
+ except (AttributeError, ValueError):
251
+ pass
252
+
253
+
254
+ def _obsidian(vault: Vault, did: list, skipped: list) -> None:
255
+ """Graph colours and Bases views. colorGroups are set only when graph.json has none or only
256
+ old Keepfold defaults (order matters, so merging into the user's own groups would scramble
257
+ them); every other graph setting is kept."""
258
+ graph = vault.root / ".obsidian" / "graph.json"
259
+ data = json.loads(graph.read_text(encoding="utf-8")) if graph.exists() else {}
260
+ have = [g.get("query") for g in data.get("colorGroups") or []]
261
+ new = [{"query": q, "color": {"a": 1, "rgb": int(h, 16)}} for q, h in COLOR_GROUPS]
262
+ if have == [g["query"] for g in new]:
263
+ skipped.append(".obsidian/graph.json colorGroups")
264
+ elif set(have) <= {q for q, _ in OLD_COLOR_GROUPS}:
265
+ data["colorGroups"] = new
266
+ graph.parent.mkdir(exist_ok=True)
267
+ vault.write_text(graph, json.dumps(data, indent=2) + "\n")
268
+ did.append(".obsidian/graph.json colorGroups")
269
+ else:
270
+ skipped.append(".obsidian/graph.json colorGroups (custom colour groups)")
271
+ for rel, text in BASES.items():
272
+ if (vault.root / rel).exists():
273
+ skipped.append(rel)
274
+ else:
275
+ (vault.root / rel).parent.mkdir(exist_ok=True)
276
+ vault.write_text(vault.root / rel, text)
277
+ did.append(rel)
278
+
279
+
280
+ def _page(summary: str, *headings: str, intro: str = "") -> str:
281
+ body = "".join(f"\n## {h}\n" for h in headings)
282
+ return f"---\nsummary: {summary}\n---\n\n# {summary}\n{intro}{body}"
283
+
284
+
285
+ CLAIM_TAIL = ("Past", "Not me") # v5 F1: reserved on every claim page, never served
286
+ ME_PAGES = {
287
+ "me/profile.md": _page("Who I am", "Background", "Current focus", *CLAIM_TAIL),
288
+ "me/teaching-contract.md": _page(
289
+ "How to teach me", "Core rules",
290
+ intro="\nAsk before you teach. Keep answers short.\n") + (
291
+ "\n- Ask a closed-book question before explaining.\n\n## Domain overrides\n\n"
292
+ "<!-- Add `### <domain id>` subsections (e.g. `### math`); only matching ones load. -->\n"),
293
+ "me/preferences.md": _page("My preferences", "Coding", "Communication", "Learning",
294
+ "Workflow", "Environment", "Career", "Personal", *CLAIM_TAIL),
295
+ "me/goals.md": _page("My goals", "Now", "Later", *CLAIM_TAIL),
296
+ "me/setup.md": _page("My setup", "Hardware", "Software", *CLAIM_TAIL),
297
+ "me/personality.md": _page(
298
+ "How I tick", "Values", "How I think", "How I decide", "Strengths", "Growth edges",
299
+ "Communication", "Energy and routines", *CLAIM_TAIL,
300
+ intro="\nOne line per entry: `- <trait> — seen: <evidence> (confirmed YYYY-MM-DD)`.\n"),
301
+ "me/portrait.md": _page(
302
+ "My monthly portrait",
303
+ intro="\nOne `## YYYY-MM` section per month, drafted by the assistant and approved by "
304
+ "me.\n"),
305
+ "me/core.md": _page( # prime.core_lines: pinned, first in every prime
306
+ "Always about me", "Core", *CLAIM_TAIL,
307
+ intro="\nPinned: every chat starts with these lines, word for word, ahead of "
308
+ "everything else (500 characters in all; a line that does not fit is left out "
309
+ "whole). Only lines you write or confirm count.\n"),
310
+ "me/voice.md": _page( # PHASE4 V2: served only by keepfold_as_me
311
+ "How I write", "Everyone", *CLAIM_TAIL,
312
+ intro="\nStyle rules per audience: one `## <audience>` section each (professor, friend, "
313
+ "people/<slug>), e.g. `- Formal greeting, at most 5 sentences, signs \"Regards\"`."
314
+ "\n"),
315
+ }
316
+
317
+
318
+ # ---- init, doctor ---------------------------------------------------------------
319
+
320
+ @app.command()
321
+ @_errors
322
+ def init(
323
+ path: Path,
324
+ default: Annotated[bool, typer.Option(
325
+ "--default", help="Make this the default vault even when one is already set.")]
326
+ = False,
327
+ ) -> None:
328
+ """Create or adopt a vault (idempotent; never touches notes); point ~/.keepfold at it when no
329
+ default vault is set yet, or with --default."""
330
+ _report(*_init(path.resolve(), default=default))
331
+ typer.echo("Next: run `keepfold app`")
332
+
333
+
334
+ def _report(did: list[str], skipped: list[str], warned: list[str] = ()) -> None:
335
+ for line in did:
336
+ typer.echo(f"created {line}")
337
+ for line in skipped:
338
+ typer.echo(f"skipped {line} (exists)")
339
+ for line in warned:
340
+ typer.echo(f"warning {line}")
341
+
342
+
343
+ INSTALL_MARKER = "keepfold-install.txt" # installer/setup_app.py drops it in the install folder
344
+
345
+
346
+ def install_folder(p: Path) -> Path | None:
347
+ """The KeepfoldSetup.exe install folder `p` is in (or is), else None."""
348
+ p = Path(p).resolve()
349
+ return next((d for d in (p, *p.parents) if (d / INSTALL_MARKER).is_file()), None)
350
+
351
+
352
+ def _init(root: Path, default: bool = False) -> tuple[list[str], list[str], list[str]]:
353
+ """The work of `keepfold init`: (created, skipped, warnings). The ~/.keepfold pointer moves
354
+ only when it names no vault yet or `default` is set (every chat's hook and server read it)."""
355
+ if root.exists() and not root.is_dir():
356
+ raise VaultError("invalid_argument", f"{root} is a file; pick a folder.")
357
+ if inst := install_folder(root):
358
+ raise VaultError("invalid_argument", f"{root} is inside the folder Keepfold is installed "
359
+ f"in ({inst}); uninstalling Keepfold empties that folder. Pick another "
360
+ "folder for your notes.")
361
+ root.mkdir(parents=True, exist_ok=True)
362
+ vault = Vault(root)
363
+ did, skipped = [], []
364
+ for name in SECTIONS:
365
+ (skipped if (root / name).is_dir() else did).append(f"{name}/")
366
+ (root / name).mkdir(exist_ok=True)
367
+ for rel, text in ((".keepfold/config.yaml", "schema: 1\n"), (".gitignore", GITIGNORE),
368
+ (".gitattributes", "* text=auto eol=lf\n")): # keep LF despite core.autocrlf
369
+ if (root / rel).exists():
370
+ skipped.append(rel)
371
+ else:
372
+ vault.write_text(root / rel, text)
373
+ did.append(rel)
374
+ git_on, private_kept = session_mod.git_choice()
375
+ ignore = root / ".gitignore"
376
+ old = ignore.read_text(encoding="utf-8")
377
+ # older vaults: append if missing; the private line only while private browsing stays out
378
+ # of git (the default)
379
+ for line in (WORKSPACE_IGNORE, *(() if private_kept else (PRIVATE_BROWSE_IGNORE,)),
380
+ CHAT_ARCHIVE_IGNORE, TMP_IGNORE):
381
+ if line not in old.splitlines():
382
+ old += ("" if old.endswith("\n") or not old else "\n") + line + "\n"
383
+ vault.write_text(ignore, old)
384
+ did.append(".gitignore line")
385
+ if private_kept:
386
+ from keepfold.browse.forget import drop_private_ignore
387
+ if drop_private_ignore(vault):
388
+ did.append(".gitignore: browse/private/ kept in git (your choice)")
389
+ _obsidian(vault, did, skipped)
390
+ for rel, text in ME_PAGES.items():
391
+ if (root / rel).exists():
392
+ skipped.append(rel)
393
+ else:
394
+ vault.write_text(root / rel, text)
395
+ did.append(rel)
396
+ warned = []
397
+ if not git_on: # the owner's choice; an existing .git is left as it is
398
+ skipped.append("git (off in settings)")
399
+ return _init_pointer(root, default, did, skipped, warned)
400
+ if (root / ".git").exists():
401
+ skipped.append("git init")
402
+ elif session_mod.git_exe() is None:
403
+ warned.append("git not found: no vault history or push block yet; install git, then "
404
+ "rerun `keepfold init` or `keepfold setup`")
405
+ else:
406
+ r = _git(root, "init", "-q")
407
+ if r.returncode:
408
+ raise VaultError("invalid_argument", f"git init failed: {r.stderr.strip()}")
409
+ did.append("git init")
410
+ hook = root / ".git" / "hooks" / "pre-push"
411
+ if hook.exists():
412
+ skipped.append("pre-push hook")
413
+ elif (root / ".git").is_dir():
414
+ vault.write_text(hook, PRE_PUSH)
415
+ os.chmod(hook, 0o755)
416
+ did.append("pre-push hook")
417
+ # without an identity every session commit fails silently and `keepfold undo` does nothing
418
+ if ((root / ".git").is_dir() and session_mod.git_exe()
419
+ and not _git(root, "config", "user.email").stdout.strip()):
420
+ _git(root, "config", "user.name", "Keepfold")
421
+ _git(root, "config", "user.email", "keepfold@localhost")
422
+ did.append("git identity Keepfold <keepfold@localhost> (this vault only)")
423
+ if (root / ".git").is_dir() and session_mod.git_exe() and vault.writes:
424
+ # the starter pages get a first version, so `keepfold undo` has one to go back to
425
+ if session_mod._commit(vault, "keepfold: init", vault.wrote_since(0)):
426
+ did.append("git commit keepfold: init")
427
+ return _init_pointer(root, default, did, skipped, warned)
428
+
429
+
430
+ def _init_pointer(root: Path, default: bool, did: list[str], skipped: list[str],
431
+ warned: list[str]) -> tuple[list[str], list[str], list[str]]:
432
+ """The last step of `_init`: point ~/.keepfold at the vault if it names none (or `default`)."""
433
+ current = taint.config().get("vault")
434
+ if not current: # a first setup: What's new starts at this version, not at BEFORE_NEWS
435
+ from keepfold.app import news
436
+ news.start()
437
+ if (default and current and Path(current).is_dir() and not in_temp_folder(current)
438
+ and in_temp_folder(root)): # a probe or a stray click must not take the vault over
439
+ warned.append(f"Kept your vault {current}: {root} is a temporary folder, which Windows "
440
+ "can empty. Pick a folder outside Temp.")
441
+ elif default or not current:
442
+ did.append(f"pointer {_write_config(vault=str(root))}")
443
+ elif Path(current).resolve() == root:
444
+ skipped.append(f"pointer {_pointer()}")
445
+ else:
446
+ warned.append(f"kept the default vault {current}; run `keepfold init \"{root}\" "
447
+ "--default` to make this one the default")
448
+ return did, skipped, warned
449
+
450
+
451
+ @app.command()
452
+ def doctor(vault: VaultOpt = None, privacy: Annotated[bool, typer.Option(
453
+ "--privacy", help="Print only where Keepfold connects.")] = False,
454
+ security: Annotated[bool, typer.Option(
455
+ "--security", help="Fire six memory attacks at a throwaway made-up vault "
456
+ "(never your notes) and say PASS or FAIL for each.")] = False,
457
+ report: Annotated[bool, typer.Option(
458
+ "--report", help="Print the details to paste into a bug report: versions and "
459
+ "each check's state, no paths, names or notes.")] = False) -> None:
460
+ """Check Python/FTS5, the search model, PATH, the local model, OneDrive and the vault git,
461
+ then list where Keepfold connects; exit 1 on any FAIL. --security: the offline red team
462
+ (keepfold.redteam) instead. --report: the details for a bug report."""
463
+ if report:
464
+ from keepfold.app import status
465
+ try:
466
+ root = _vault(vault).root
467
+ except VaultError:
468
+ root = None
469
+ typer.echo(status.report(root))
470
+ return
471
+ if privacy:
472
+ typer.echo("\n".join(doctor_mod.connects()))
473
+ return
474
+ if security:
475
+ from keepfold import redteam
476
+
477
+ probes = redteam.run()
478
+ for p in probes:
479
+ typer.echo(p.line())
480
+ bad = sum(not p.ok for p in probes)
481
+ typer.echo(f"\n{len(probes) - bad} of {len(probes)} attacks stopped"
482
+ + (f"; {bad} got through." if bad else "."))
483
+ if bad:
484
+ raise typer.Exit(1)
485
+ return
486
+ results = [doctor_mod.check_python(), doctor_mod.check_duplicate_servers(),
487
+ doctor_mod.check_exclude(), doctor_mod.check_search_model(),
488
+ doctor_mod.check_on_path(), doctor_mod.check_local_model(),
489
+ doctor_mod.check_ai_apps()]
490
+ try:
491
+ root = _vault(vault).root
492
+ results += [doctor_mod.check_onedrive(root), doctor_mod.check_git(root),
493
+ doctor_mod.check_git_identity(root), doctor_mod.check_id_clashes(root),
494
+ doctor_mod.check_sync_copies(root), *doctor_mod.check_damaged_stores(root),
495
+ doctor_mod.check_contract_size(root), doctor_mod.check_claims(root),
496
+ doctor_mod.check_kill(root), doctor_mod.check_me_pages(root),
497
+ doctor_mod.check_private_browse_git(root),
498
+ doctor_mod.check_chat_archive_git(root),
499
+ doctor_mod.check_browse_legacy(root), *doctor_mod.check_clients(root),
500
+ *doctor_mod.check_import_shapes(root)]
501
+ except VaultError as e:
502
+ results.append(("FAIL", "Vault", str(e), "Open Keepfold from the Start menu and set "
503
+ "up a vault under Setup." if doctor_mod.installer() else
504
+ "Run `keepfold app` (or `keepfold setup` in a terminal) to set "
505
+ "Keepfold up, or pass --vault."))
506
+ # the vault's folder even when opening it failed (a move from Cortex it waits for)
507
+ results += doctor_mod.check_moved(Path(vault) if vault else taint._vault_root())
508
+ for status, name, detail, fix in results:
509
+ typer.echo(f"{status:<4} {name}: {detail}")
510
+ if fix:
511
+ typer.echo(f" fix: {fix}")
512
+ typer.echo("\n" + "\n".join(doctor_mod.connects()))
513
+ if any(r[0] == "FAIL" for r in results):
514
+ raise typer.Exit(1)
515
+
516
+
517
+ MOVED = {"nothing": "nothing to move", "done": "done", "both": "both folders exist",
518
+ "blocked": "blocked", "error": "failed"}
519
+
520
+
521
+ @app.command()
522
+ def migrate(vaults: Annotated[list[Path] | None, typer.Option(
523
+ "--vault", help="A vault to move (repeatable); else the configured one.")] = None,
524
+ as_json: Annotated[bool, typer.Option(
525
+ "--json", help="One JSON object (state, exit, home, vaults, apps) for the "
526
+ "installer.")] = False) -> None:
527
+ """Move what Cortex (0.6.1 and older) left: ~/.cortex to ~/.keepfold, a vault's .cortex/ to
528
+ .keepfold/ with its ignore lines and note keys, and the AI-app connections. Exit 0 done or
529
+ nothing to do, 2 blocked (an old Cortex still runs), 1 error."""
530
+ from keepfold import migrate as migrate_mod
531
+ r = migrate_mod.everything(vaults or None)
532
+ if as_json:
533
+ typer.echo(json.dumps(r, default=str)) # the installer reads it: never a crash
534
+ else:
535
+ for name, part in (("Settings", r["home"]),
536
+ *((f"Vault {x['path']}", x) for x in r["vaults"])):
537
+ n = f", {part['notes']} pages updated" if part.get("notes") else ""
538
+ typer.echo(f"{name}: {MOVED.get(part['state'], part['state'])}{n}")
539
+ if part.get("message"):
540
+ typer.echo(f" {part['message']}")
541
+ if part.get("skipped"):
542
+ typer.echo(f" {part['skipped']} pages kept their old keys: their front matter "
543
+ "could not be read.")
544
+ for row in (r["apps"] or {}).get("rows", []):
545
+ if row["action"] != "nothing":
546
+ typer.echo(f"AI app {row['app']}: {row['action']}"
547
+ + (f"\n {row['note']}" if row.get("note") else ""))
548
+ raise typer.Exit(r["exit"])
549
+
550
+
551
+ # ---- setup wizard, sample vault -------------------------------------------------
552
+
553
+ RELEASES = f"https://github.com/{REPO}/releases"
554
+ FIRST_PROMPTS = ("what do you know about me?", "/keepfold",
555
+ "remember that I prefer short answers")
556
+ PRIVACY = ("Privacy: the vault stays in a folder on this disk; Keepfold has no account or "
557
+ "telemetry. It downloads the search model, Ollama or a local model only when you ask. "
558
+ "While the app runs it checks GitHub for a new version (turn this off under Status → "
559
+ "Updates). Its server listens on 127.0.0.1 only. Tool results go to the AI model you "
560
+ "chat with. See docs/PRIVACY.md.")
561
+
562
+
563
+ def _marketplace() -> str | None:
564
+ """Where `claude plugin marketplace add` points: this source checkout, else the published
565
+ repo; None while neither exists."""
566
+ if (CHECKOUT / ".claude-plugin" / "marketplace.json").is_file():
567
+ return str(CHECKOUT)
568
+ return None if "<" in REPO else REPO
569
+
570
+
571
+ NO_MARKETPLACE = ("Claude Code plugin: no Keepfold source checkout found and no published repo "
572
+ "yet. Clone the Keepfold repo, then in Claude Code type `/plugin marketplace add "
573
+ "<the clone's folder>` and `/plugin install keepfold@keepfold`, and restart it.")
574
+
575
+
576
+ def _default_vault() -> Path:
577
+ return taint._vault_root() or Path.home() / "Keepfold"
578
+
579
+
580
+ @app.command()
581
+ @_errors
582
+ def setup(
583
+ vault: Annotated[Path | None, typer.Option(
584
+ "--vault", help="Vault folder; asked when missing (default ~/Keepfold).")] = None,
585
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Take every default; ask nothing.")]
586
+ = False,
587
+ no_model: Annotated[bool, typer.Option("--no-model", help="Skip the model download.")]
588
+ = False,
589
+ no_desktop: Annotated[bool, typer.Option(
590
+ "--no-desktop", help="Leave the Claude desktop config alone.")] = False,
591
+ no_code: Annotated[bool, typer.Option("--no-code", help="Skip the Claude Code plugin.")]
592
+ = False,
593
+ sample: Annotated[bool | None, typer.Option(
594
+ "--sample/--no-sample", help="Add the sample vault (default: yes for a new vault).")]
595
+ = None,
596
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Print the plan; change nothing.")]
597
+ = False,
598
+ print_mcp_config: Annotated[bool, typer.Option(
599
+ "--print-mcp-config", help="Print only an mcpServers JSON snippet that runs `keepfold mcp "
600
+ "--vault` (Cursor, Gemini CLI); change nothing.")] = False,
601
+ ) -> None:
602
+ """Set up Keepfold step by step (safe to rerun): vault, sample, model, Claude Code, Claude
603
+ desktop, checks."""
604
+ from keepfold import clients
605
+ from keepfold import sample as sample_mod
606
+
607
+ if print_mcp_config:
608
+ _print_mcp_config(vault or os.environ.get("KEEPFOLD_VAULT")) # as VaultOpt resolves it
609
+ return
610
+
611
+ def ask(question: str) -> bool:
612
+ return yes or typer.confirm(question, default=True)
613
+
614
+ # 1. preflight
615
+ status, name, detail, fix = doctor_mod.check_python()
616
+ typer.echo(f"{status:<4} {name}: {detail}")
617
+ if status == "FAIL":
618
+ typer.echo(f" fix: {fix}")
619
+ raise typer.Exit(1)
620
+ if session_mod.git_exe() is None and session_mod.git_choice()[0]:
621
+ typer.echo("WARN git not found: the vault gets no history or push block until you "
622
+ "install git and rerun `keepfold setup`.")
623
+ if shutil.which("keepfold") is None:
624
+ typer.echo("WARN `keepfold` is not on PATH: run `uv tool update-shell`, then open a new "
625
+ "terminal. Claude Code's plugin needs it on PATH.")
626
+
627
+ # 2. vault location
628
+ if vault is None:
629
+ vault = _default_vault() if yes else Path(typer.prompt( # Explorer's "Copy as path" quotes
630
+ "Vault folder", default=str(_default_vault())).strip().strip("\"'"))
631
+ root = vault.expanduser().resolve()
632
+ if root.exists() and not root.is_dir():
633
+ raise VaultError("invalid_argument", f"{root} is a file; pick a folder.")
634
+ if inst := install_folder(root): # before the sample pages land there
635
+ raise VaultError("invalid_argument", f"{root} is inside the folder Keepfold is installed "
636
+ f"in ({inst}); pick another folder for your notes.")
637
+ sync = doctor_mod.check_onedrive(root)
638
+ if sync[0] != "PASS":
639
+ typer.echo(f"WARN {sync[2]}: {sync[3]}")
640
+ new = not (root / ".keepfold").is_dir()
641
+ if new and root.is_dir() and any(root.iterdir()) and not ask(
642
+ f"{root} has files but is no Keepfold vault yet. Use it? Keepfold adds folders and "
643
+ "never changes your notes."):
644
+ typer.echo("Nothing changed. Run `keepfold setup` again and pick another folder.")
645
+ raise typer.Exit(1)
646
+ if sample is None:
647
+ sample = new and ask("Add a small sample vault (a made-up person, Sam) to try things? "
648
+ "`keepfold sample remove` clears it.")
649
+ model = not no_model and ask("Download the search model now? About 150 MB, once, from "
650
+ "huggingface.co; without it recall uses keywords only.")
651
+ entry = clients.server_entry(clients.mcp_command(), root)
652
+ configs = [] if no_desktop else clients.setup_targets(clients.claude_desktop_config_paths())
653
+
654
+ if dry_run:
655
+ typer.echo(f"plan vault {root} ({'new' if new else 'exists'}): missing folders, "
656
+ f"me/ pages, .gitignore, git repo, pre-push hook; pointer {_pointer()}")
657
+ if sample:
658
+ missing = [r for r in sample_mod.files() if not (root / r).exists()]
659
+ typer.echo(f"plan sample: {len(missing)} of {len(sample_mod.files())} pages "
660
+ f"missing, {len(sample_mod.SEED)} sample events")
661
+ typer.echo("plan model: download (about 150 MB) into "
662
+ f"{Path.home() / '.keepfold' / 'models'}" if model else "skip model")
663
+ src = _marketplace()
664
+ typer.echo("skip Claude Code plugin" if no_code else
665
+ f"plan Claude Code: claude plugin marketplace add {src}; "
666
+ "claude plugin install keepfold@keepfold" if src
667
+ else f"plan {NO_MARKETPLACE}")
668
+ for p in configs:
669
+ try:
670
+ typer.echo(f"plan Claude desktop {p}: "
671
+ f"{_desktop_change(p, entry, dry_run=True)}")
672
+ except ValueError as e:
673
+ typer.echo(f"warning {e}")
674
+ if not no_desktop and not configs:
675
+ typer.echo("plan Claude desktop: no config folder found; print the entry")
676
+ typer.echo("skip Claude desktop" if no_desktop else
677
+ f" entry: {json.dumps({'keepfold': entry})}")
678
+ typer.echo("plan run the doctor checks")
679
+ typer.echo("dry run: nothing written")
680
+ return
681
+
682
+ # 3-4. sample pages first, so Sam's me/ pages take the place of the empty templates
683
+ did, skipped, warned = [], [], []
684
+ if sample:
685
+ root.mkdir(parents=True, exist_ok=True)
686
+ d, s = sample_mod.seed(Vault(root))
687
+ did, skipped = [f"sample {x}" for x in d], [f"sample {x}" for x in s]
688
+ d, s, warned = _init(root, default=True) # the wizard's vault choice is explicit
689
+ _report(did + d, skipped + s, warned)
690
+
691
+ # 5. model
692
+ if model:
693
+ try:
694
+ model_download(vault=root)
695
+ except Exception as e: # noqa: BLE001 (offline, disk, Hugging Face down)
696
+ typer.echo(f"warning model download failed ({e}); recall uses keyword search "
697
+ "until `keepfold model download` works.")
698
+ else:
699
+ typer.echo("skipped model (run `keepfold model download` later)")
700
+
701
+ # 6. Claude Code
702
+ if no_code:
703
+ typer.echo("skipped Claude Code plugin")
704
+ elif doctor_mod.plugin_enabled():
705
+ typer.echo("skipped Claude Code plugin (enabled)")
706
+ else:
707
+ _setup_code(ask)
708
+
709
+ # 7. Claude desktop
710
+ if not no_desktop:
711
+ _setup_desktop(configs, entry, ask)
712
+
713
+ # 8. verify
714
+ typer.echo("\nChecks:")
715
+ try:
716
+ doctor(vault=root)
717
+ except typer.Exit:
718
+ typer.echo("Fix the FAIL lines above, then rerun `keepfold setup`.")
719
+ typer.echo("\nTry these in Claude: " + " | ".join(f'"{p}"' for p in FIRST_PROMPTS))
720
+ typer.echo(PRIVACY)
721
+ if not yes and typer.confirm("Open the Keepfold app for other AI apps, a local model and "
722
+ "browsing?", default=True):
723
+ app_cmd(vault=root)
724
+
725
+
726
+ def _setup_code(ask) -> None:
727
+ src = _marketplace()
728
+ if src is None:
729
+ typer.echo(NO_MARKETPLACE)
730
+ return
731
+ cmds = [["plugin", "marketplace", "add", src], ["plugin", "install", "keepfold@keepfold"]]
732
+ claude = shutil.which("claude")
733
+ if src == REPO and session_mod.git_exe() is None: # Claude Code clones the repo with git
734
+ from keepfold.app.wizard import GIT_PAGE
735
+ typer.echo("Claude Code needs Git to download the Keepfold plugin from GitHub. Install Git "
736
+ f"from {GIT_PAGE}, open a new terminal, then run `keepfold setup` again.")
737
+ return
738
+ # runs `claude` itself only once a published repo is chosen; a checkout path is printed
739
+ if claude and "<" not in REPO and ask("Install the Claude Code plugin with `claude`?"):
740
+ for c in cmds:
741
+ r = subprocess.run([claude, *c], capture_output=True, text=True,
742
+ creationflags=NO_WINDOW)
743
+ ok = r.returncode == 0
744
+ typer.echo(f"{'ran ' if ok else 'warning '} claude {' '.join(c)}"
745
+ + ("" if ok else f": {(r.stderr or r.stdout).strip()[:200]}"))
746
+ typer.echo("Restart Claude Code, then type /keepfold.")
747
+ return
748
+ typer.echo("In Claude Code, type these two commands, then restart it:")
749
+ for c in cmds:
750
+ typer.echo(f" /{' '.join(c)}")
751
+
752
+
753
+ def _desktop_change(p: Path, entry: dict, dry_run: bool = False) -> str:
754
+ """Set mcpServers.keepfold in `p` through the app's writer (timestamped backups); returns
755
+ "created", "updated" or "unchanged". ValueError leaves a file it cannot parse untouched."""
756
+ from keepfold.app import targets
757
+
758
+ existed = p.is_file()
759
+ if targets.edit_json(p, "mcpServers", entry, dry_run=dry_run) == "none":
760
+ return "unchanged"
761
+ return "updated" if existed else "created"
762
+
763
+
764
+ def _setup_desktop(configs: list[Path], entry: dict, ask) -> None:
765
+ from keepfold.app import targets
766
+
767
+ if not configs:
768
+ typer.echo("Claude desktop: no config folder found. Open Settings > Developer > Edit "
769
+ "Config and add this under \"mcpServers\":")
770
+ typer.echo(json.dumps({"keepfold": entry}, indent=2))
771
+ for p in configs:
772
+ if not ask(f"Add Keepfold to the Claude desktop config {p}?"):
773
+ typer.echo(f"skipped {p}")
774
+ continue
775
+ try:
776
+ status = _desktop_change(p, entry)
777
+ except ValueError as e:
778
+ typer.echo(f"warning {e} Or add this under \"mcpServers\" yourself:")
779
+ typer.echo(json.dumps({"keepfold": entry}, indent=2))
780
+ continue
781
+ typer.echo(f"skipped {p} (keepfold entry exists)" if status == "unchanged"
782
+ else f"{status:<8} {p} (backup beside it: {p.name}.keepfold-<time>.bak)"
783
+ if status == "updated"
784
+ else f"created {p}")
785
+ src = _marketplace()
786
+ zip_from = (f"{CHECKOUT / 'dist'} (build it with `uv run python scripts/build_skills.py` "
787
+ f"in {CHECKOUT})" if src == str(CHECKOUT)
788
+ else f"{RELEASES}/latest/download/keepfold-skill.zip")
789
+ typer.echo("Fully quit Claude desktop (tray or menu bar > Quit) and open it again. For "
790
+ f"/keepfold in Chat, upload keepfold-skill.zip from {zip_from} under Settings > "
791
+ "Capabilities > Skills.")
792
+ _paste_text("Chat has no hooks, so Claude uses Keepfold in every chat only when its "
793
+ "instructions say so. " + targets.PASTE_DESKTOP)
794
+
795
+
796
+ def _paste_text(where: str) -> None:
797
+ """Print packs.USE_TEXT (the app's Copy instructions) with where to paste it."""
798
+ from keepfold import packs
799
+ typer.echo(f"\n{where} The text:\n")
800
+ typer.echo(packs.USE_TEXT)
801
+
802
+
803
+ @app.command(hidden=True) # the uninstaller's step; people use Connect AI apps in the app
804
+ def disconnect() -> None:
805
+ """Remove Keepfold from every AI app it is connected to, as Connect AI apps does (backups
806
+ beside each file). The Windows uninstaller runs it when asked."""
807
+ from keepfold.app import targets
808
+
809
+ rows = targets.apply_all({t.id: False for t in targets.targets()}, None, typer.echo)
810
+ for r in rows:
811
+ typer.echo(f"{r['change']:<8} {r['label']}: {r.get('file') or ''} {r.get('detail') or ''}"
812
+ .rstrip())
813
+ if not rows:
814
+ typer.echo("No AI app had Keepfold.")
815
+ if any(r["change"] == "error" for r in rows):
816
+ raise typer.Exit(1)
817
+
818
+
819
+ sample_app = typer.Typer(no_args_is_help=True, help="The sample vault (a made-up learner).")
820
+ app.add_typer(sample_app, name="sample")
821
+
822
+
823
+ @sample_app.command("remove")
824
+ @_errors
825
+ def sample_remove(vault: VaultOpt = None) -> None:
826
+ """Delete the `sample: true` pages and void the sample events (history stays)."""
827
+ from keepfold import sample as sample_mod
828
+
829
+ v = _vault(vault)
830
+ removed, n = sample_mod.remove(v)
831
+ for rel in removed:
832
+ typer.echo(f"removed {rel}")
833
+ for rel, text in ME_PAGES.items(): # put back the empty templates Sam's pages replaced
834
+ if not (v.root / rel).exists():
835
+ v.write_text(v.root / rel, text)
836
+ typer.echo(f"created {rel}")
837
+ typer.echo(f"voided {n} sample events")
838
+
839
+
840
+ @app.command("lint")
841
+ @_errors
842
+ def lint_cmd(findability: Annotated[bool, typer.Option(
843
+ "--findability", help="Also check that each long page's own deep text finds it "
844
+ "(top 3, no rerank; keyword only without the model). Report only.")] = False,
845
+ vault: VaultOpt = None) -> None:
846
+ """List vault problems to fix and add a line to log.md."""
847
+ from keepfold import lint as lint_mod
848
+
849
+ v = _vault(vault)
850
+ findings, totals = lint_mod.lint_report(v)
851
+ for f in findings:
852
+ typer.echo(render.term(f"{f['kind']}: {f['id']} - {f['detail']}"))
853
+ more = lint_mod.not_shown(findings, totals)
854
+ typer.echo(f"{len(findings)} findings" + (f" (not shown: {more})" if more else ""))
855
+ if findability:
856
+ from keepfold import semantic
857
+
858
+ embed = semantic.load_embedder() # never downloads; None: keyword only
859
+ lost = lint_mod.findability(v, embed)
860
+ for f in lost:
861
+ typer.echo(render.term(f"{f['kind']}: {f['id']} - {f['detail']}"))
862
+ typer.echo(f"{len(lost)} pages not findable by their own text"
863
+ + ("" if embed else " (keyword only: no model)"))
864
+ v.append_log(local_day(datetime.now(UTC)), "lint", f"{len(findings)} findings")
865
+
866
+
867
+ @app.command("agent-text")
868
+ @_errors
869
+ def agent_text_cmd(vault: VaultOpt = None) -> None:
870
+ """Print every fixed string an agent can see (server instructions, tool descriptions, next
871
+ hints, SKILL.md, hook templates, the rule-file block), then its size per app profile."""
872
+ from keepfold import agent_text, profiles
873
+
874
+ srcs = agent_text.sources()
875
+ for label, channel, text in srcs:
876
+ typer.echo(f"== {label} [{channel}] ({len(text)} chars) ==\n{text}\n")
877
+ try: # the owner's profiles when a vault is set; DEFAULT otherwise (no vault text is read)
878
+ data = profiles.load(_vault(vault))
879
+ except VaultError:
880
+ data = profiles.DEFAULT
881
+ typer.echo("== chars per app profile ==")
882
+ for name, n in agent_text.sizes(data, srcs):
883
+ typer.echo(f"{name}: {n} ({', '.join(sorted(agent_text.channels(name)))})")
884
+
885
+
886
+ @app.command("relink")
887
+ @_errors
888
+ def relink_cmd(dry_run: Annotated[bool, typer.Option(
889
+ "--dry-run", help="Report what would change; write nothing.")] = False,
890
+ vault: VaultOpt = None) -> None:
891
+ r"""Add the [\[links]] Obsidian's graph needs (session -> day -> month -> topic map, the
892
+ people hub, frontmatter edges as "[\[id]]"), fix near-miss links, escape junk ones, and
893
+ report unresolved links.""" # \[ keeps Rich markup in --help from eating [links]
894
+ from keepfold import relink
895
+
896
+ out = relink.run(_vault(vault), dry_run=dry_run)
897
+ for line in relink.report_lines(out):
898
+ typer.echo(line)
899
+ typer.echo("dry run: nothing written" if dry_run else "written")
900
+
901
+
902
+ @app.command("rollups")
903
+ @_errors
904
+ def rollups_cmd(since: Annotated[str | None, typer.Option(
905
+ help="Only periods ending in or after this month (YYYY-MM).")] = None,
906
+ vault: VaultOpt = None) -> None:
907
+ """Write the week, month and year rollup pages (rollups/): counts and top items per source,
908
+ built by code, no model. Only pages whose text changed are written."""
909
+ from keepfold import rollups
910
+
911
+ out = rollups.run(_vault(vault), since)
912
+ typer.echo("rollups: nothing changed" if out is None else
913
+ f"rollups: {out['written']} written, {out['kept']} unchanged, "
914
+ f"{out['removed']} removed")
915
+
916
+
917
+ @app.command("reflect")
918
+ @_errors
919
+ def reflect_cmd(vault: VaultOpt = None) -> None:
920
+ """Show the reflect pack: unconfirmed lines, emerging clusters, old fleeting lines, week."""
921
+ from keepfold import reflect as reflect_mod
922
+
923
+ v = _vault(vault)
924
+ out = reflect_mod.reflect(v, Catalog.load(v), datetime.now(UTC))
925
+ typer.echo(f"Unconfirmed about-me lines: {len(out['unconfirmed'])}"
926
+ + (f" ({out['unconfirmed_dropped']} older than 60 days not shown)"
927
+ if out["unconfirmed_dropped"] else ""))
928
+ for u in out["unconfirmed"]:
929
+ typer.echo(render.term(f" - {u['text']}"
930
+ + (f" (since {u['since']})" if u["since"] else "")))
931
+ typer.echo(f"Emerging clusters: {len(out['emerging'])}")
932
+ for c in out["emerging"]:
933
+ typer.echo(render.term(f" - {c['suggested_title']}: {', '.join(c['members'])} "
934
+ f"(shared: {', '.join(c['shared'])})"))
935
+ typer.echo(f"Old fleeting lines: {len(out['old_fleeting'])}")
936
+ for f in out["old_fleeting"]:
937
+ typer.echo(render.term(f" - {f['text']} (since {f['since']})"))
938
+ w = out["week"]
939
+ typer.echo(f"Week {w['from']} to {w['to']}: {w['sessions']} sessions, "
940
+ f"{w['correct']}/{w['grades']} correct, {len(w['changed'])} concepts changed")
941
+
942
+
943
+ @app.command("pack")
944
+ @_errors
945
+ def pack_cmd(name: Annotated[str, typer.Argument(
946
+ help="general, coding, writing, interview, research or review")],
947
+ chars: Annotated[int, typer.Option(
948
+ "--chars", help="the most characters: 1500 or 5000")] = 1500,
949
+ vault: VaultOpt = None) -> None:
950
+ """Print a context pack to paste into a web chat (ChatGPT, Gemini): your pinned core, then
951
+ the pack's preference lines, at most 1,500 (or 5,000) characters, never a private page."""
952
+ from keepfold import packs
953
+
954
+ if name not in packs.PACKS:
955
+ typer.echo(f"error: the pack is one of {', '.join(packs.PACKS)}.", err=True)
956
+ raise typer.Exit(2)
957
+ if chars not in packs.SIZES:
958
+ typer.echo("error: --chars is 1500 or 5000.", err=True)
959
+ raise typer.Exit(2)
960
+ text = packs.pack(_vault(vault), name, chars)
961
+ if not text:
962
+ typer.echo("Nothing to pack yet: add lines to me/core.md or me/preferences.md.",
963
+ err=True)
964
+ raise typer.Exit(1)
965
+ typer.echo(render.term(text))
966
+
967
+
968
+ chats_app = typer.Typer(invoke_without_command=True)
969
+ app.add_typer(chats_app, name="chats")
970
+
971
+
972
+ @chats_app.callback()
973
+ @_errors
974
+ def chats_cmd(ctx: typer.Context,
975
+ since: Annotated[str | None, typer.Option(help="Only chats updated on or after "
976
+ "this date (YYYY-MM-DD).")] = None,
977
+ limit: Annotated[int, typer.Option(help="Show at most this many.")] = 20,
978
+ vault: VaultOpt = None) -> None:
979
+ r"""List past chats (Claude Code, and Claude Chat once imported), newest first; \[saved]
980
+ marks ones already saved. `keepfold chats archive` moves chat pages out of git.""" # \[ keeps
981
+ # Rich markup in --help from eating [saved]
982
+ from keepfold import chats
983
+
984
+ if ctx.invoked_subcommand:
985
+ return
986
+ v = _vault(vault)
987
+ saved = {c for _, c in chats.saved_ids(EventLog(v).iter_events())}
988
+ for c in chats.list_chats(saved, since, limit):
989
+ mark = " [saved]" if c["saved"] else ""
990
+ typer.echo(render.term(f"{c['updated'][:16]} {c['id']} {c['turns']} turns{mark} "
991
+ f"{c['first_user_line']}"))
992
+
993
+
994
+ @chats_app.command("archive")
995
+ @_errors
996
+ def chats_archive_cmd(
997
+ dry_run: Annotated[bool, typer.Option(
998
+ "--dry-run", help="List the pages that would move; change nothing.")] = False,
999
+ undo: Annotated[bool, typer.Option(
1000
+ "--undo", help="Instead: move them back to resources/ and keep new chat pages "
1001
+ "there.")] = False,
1002
+ vault: VaultOpt = None) -> None:
1003
+ """Move imported AI chat pages from resources/ into archive/chats/, which git ignores: they
1004
+ stay searchable, links keep working, and they leave the vault's git (old commits keep
1005
+ them). New chat pages go there too. --undo moves them back."""
1006
+ from keepfold import chat_archive
1007
+
1008
+ v = _vault(vault)
1009
+ where, to = (CHAT_ARCHIVE, "resources") if undo else ("resources", CHAT_ARCHIVE)
1010
+ r = chat_archive.move(v, undo=undo, dry_run=dry_run)
1011
+ n = len(r["ids"])
1012
+ for i in r["ids"] if dry_run else ():
1013
+ typer.echo(f" {i}")
1014
+ typer.echo(f"{'Would move' if dry_run else 'Moved'} {n} chat page{'s' * (n != 1)} from "
1015
+ f"{where}/ to {to}/" + (" (dry run: nothing changed)." if dry_run else "."))
1016
+ if r["kept"]:
1017
+ typer.echo(f"Left {len(r['kept'])} where they are (another page of that id is in "
1018
+ f"{to}/, or the file is open): {', '.join(r['kept'][:10])}")
1019
+ if r["git"]:
1020
+ typer.echo(r["git"])
1021
+ elif not dry_run and not (v.root / ".git").exists():
1022
+ typer.echo("The vault is not a git repo: no git step.")
1023
+ if not dry_run:
1024
+ typer.echo("New chat pages go to resources/ until you run `keepfold chats archive` again."
1025
+ if undo else "New chat pages go to archive/chats/; `--undo` reverses this.")
1026
+
1027
+
1028
+ @app.command("import-chats")
1029
+ @_errors
1030
+ def import_chats_cmd(export: Annotated[Path | None, typer.Argument(
1031
+ help="The export: a claude.ai or ChatGPT .zip, a Google Takeout .zip of Gemini Apps "
1032
+ "activity (JSON or HTML), or Perplexity thread .md files (one, a folder or a .zip).")]
1033
+ = None,
1034
+ source: Annotated[str | None, typer.Option(
1035
+ help="Force the service when detection fails: claude, chatgpt, gemini or "
1036
+ "perplexity.")] = None,
1037
+ auto: Annotated[bool, typer.Option(
1038
+ "--auto", help="Instead: write a chat page for each Claude Code chat and imported "
1039
+ "conversation not saved yet or changed since (what the app does "
1040
+ "every 5 minutes); no model.")] = False,
1041
+ vault: VaultOpt = None) -> None:
1042
+ """Import conversations from a claude.ai, ChatGPT, Gemini or Perplexity export so /keepfold can
1043
+ learn from them like Claude Code chats. The service is detected from the file. Secrets are
1044
+ redacted; re-importing a newer export updates them. With --auto, save past chats as chat
1045
+ pages instead: your own turns only (a coding session as a short summary)."""
1046
+ from keepfold import chats, importers
1047
+
1048
+ if auto:
1049
+ from keepfold import chat_import
1050
+ counts = chat_import.run(_vault(vault), progress=lambda k, n, s: typer.echo(
1051
+ chat_import.eta(k, n, s)) if k == n or k % 25 == 0 else None)
1052
+ wrote = counts.get("saved", 0) + counts.get("updated", 0)
1053
+ said = ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(counts.items()))
1054
+ typer.echo(f"{wrote} chat page{'s' * (wrote != 1)} written"
1055
+ + (f" ({said})." if counts else "; no new or changed chats."))
1056
+ return
1057
+ if export is None:
1058
+ raise VaultError("invalid_argument", "Give the export to import, or --auto.")
1059
+ got = chats.import_export(export, source)
1060
+ source, n = got
1061
+ typer.echo(f"Imported {n} {chats.GUIDES[source]['name']} conversation{'s' * (n != 1)} "
1062
+ f"into {chats.export_root()}. Run /keepfold to learn from them.")
1063
+ typer.echo(importers.report_line(chats.GUIDES[source]["name"], got.report()))
1064
+
1065
+
1066
+ @app.command("safety-net")
1067
+ @_errors
1068
+ def safety_net_cmd(
1069
+ dry_run: Annotated[bool, typer.Option(
1070
+ "--dry-run", help="Print what would be recorded; write nothing.")] = False,
1071
+ undo: Annotated[bool, typer.Option(
1072
+ "--undo", help="Instead: void every event the safety net recorded (with --chat, "
1073
+ "only that chat's).")] = False,
1074
+ chat: Annotated[str | None, typer.Option(
1075
+ help="With --undo: the chat page id whose events to void.")] = None,
1076
+ vault: VaultOpt = None) -> None:
1077
+ """Record what the chat model forgot: topic touches for concepts and topics named in your
1078
+ recent chat pages, and (with a local model already loaded) the concepts a chat explained,
1079
+ as taught. Private chats and hidden subjects are skipped; what a chat model logged is not
1080
+ repeated. The app runs it after each chat import."""
1081
+ from keepfold import safety_net
1082
+
1083
+ v = _vault(vault)
1084
+ if undo:
1085
+ n = safety_net.undo(v, chat)
1086
+ typer.echo(f"voided {n} safety-net event{'s' * (n != 1)}")
1087
+ return
1088
+ runner, embed = safety_net.cli_tools()
1089
+ out = safety_net.run(v, runner, embed, dry_run=dry_run)
1090
+ if runner is None:
1091
+ typer.echo("No local model is loaded: only topic touches (load the small model to "
1092
+ "also record taught concepts).")
1093
+ said = ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(out.items())
1094
+ if isinstance(n, int))
1095
+ dry = " [dry run: nothing written]" if dry_run else ""
1096
+ typer.echo((out.get("line") or "Safety net: nothing new to record")
1097
+ + (f" ({said})" if said else "") + dry)
1098
+
1099
+
1100
+ @app.command("fact-harvest")
1101
+ @_errors
1102
+ def fact_harvest_cmd(vault: VaultOpt = None) -> None:
1103
+ """Save facts you stated about yourself in your recent chat pages (where you live, work or
1104
+ study, what you work on, tools, goals, preferences) as about-me guesses, with a local model
1105
+ already loaded. Your own words only; private chats and hidden subjects are skipped. The app
1106
+ runs it after each chat import; `keepfold undo <session>` takes a pass back."""
1107
+ from keepfold import fact_harvest
1108
+
1109
+ v = _vault(vault)
1110
+ runner = fact_harvest.cli_runner()
1111
+ if runner is None:
1112
+ typer.echo("No local model is loaded: load the small model, then run this again.")
1113
+ return
1114
+ out = fact_harvest.run(v, runner)
1115
+ said = ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in sorted(out.items())
1116
+ if isinstance(n, int))
1117
+ typer.echo(f"Fact harvest: {said or 'nothing new'}"
1118
+ + (f" (undo: keepfold undo {out['session']})" if out.get("session") else ""))
1119
+
1120
+
1121
+ @app.command("digest")
1122
+ @_errors
1123
+ def digest_cmd(yes: Annotated[bool, typer.Option(
1124
+ "--yes", help="Confirm every topic shown without asking.")] = False,
1125
+ dry_run: Annotated[bool, typer.Option(
1126
+ "--dry-run", help="List only; write nothing and keep the chats for next time.")]
1127
+ = False,
1128
+ since: Annotated[str | None, typer.Option(
1129
+ help="Only chats updated on or after this date (YYYY-MM-DD).")] = None,
1130
+ limit: Annotated[int, typer.Option(min=1, max=50, help="Chats per digest.")] = 10,
1131
+ vault: VaultOpt = None) -> None:
1132
+ """Review chats imported since your last digest: the topics each one seems to be about.
1133
+ Each topic you confirm records a topic touch (context, never a grade); the chats listed are
1134
+ not shown again. Runs only when you ask; local search only, no model."""
1135
+ from datetime import date
1136
+
1137
+ from keepfold import digest, harvest, semantic
1138
+ from keepfold.index import Index
1139
+
1140
+ if since is not None:
1141
+ try:
1142
+ date.fromisoformat(since)
1143
+ except ValueError:
1144
+ raise VaultError("invalid_argument", "--since must be a date like 2026-11-13.") \
1145
+ from None
1146
+ v = _vault(vault)
1147
+ events = list(EventLog(v).iter_events())
1148
+ rows = digest.new_chats(digest.reviewed(events), limit, since)
1149
+ if not rows:
1150
+ typer.echo("No new imported chats since your last digest.")
1151
+ return
1152
+ idx, embed = Index(v, Catalog.load(v)), semantic.load_embedder()
1153
+ if embed is None:
1154
+ typer.echo(semantic.NOT_SET_UP, err=True)
1155
+ quiet = harvest.quiet(events)
1156
+ confirmed: list[tuple[str, str]] = []
1157
+ done: set[str] = set() # a topic is asked about once per digest
1158
+ typer.echo(f"Since your last digest you discussed (from {len(rows)} chat"
1159
+ f"{'s' * (len(rows) != 1)}):")
1160
+ for r in rows:
1161
+ found = [c for c in digest.concepts_for(idx, r["query"], embed, quiet)
1162
+ if c["id"] not in done]
1163
+ typer.echo(render.term(f"\n{r['updated'][:10]} {r['source']} {r['title']}"))
1164
+ if not found:
1165
+ typer.echo(" (no matching topic)")
1166
+ for c in found:
1167
+ line = render.term(f" {c['title']} ({c['id']})")
1168
+ if dry_run:
1169
+ typer.echo(line)
1170
+ elif yes or typer.confirm(f"{line}: right?", default=False):
1171
+ confirmed.append((r["id"], c["id"]))
1172
+ done.add(c["id"])
1173
+ if yes:
1174
+ typer.echo(line)
1175
+ if dry_run:
1176
+ typer.echo("\n(dry run: nothing written)")
1177
+ return
1178
+ digest.record(v, confirmed, [r["id"] for r in rows])
1179
+ typer.echo(f"\nRecorded {len(confirmed)} topic touch{'es' * (len(confirmed) != 1)} "
1180
+ "(context only; a graded check is what moves a topic's level).")
1181
+
1182
+
1183
+ @app.command("import")
1184
+ @_errors
1185
+ def import_cmd(path: Annotated[Path | None, typer.Argument(
1186
+ help="A chat export (claude.ai, ChatGPT, Gemini Takeout, Perplexity .md), a Google "
1187
+ "Takeout of My Activity, a notes folder or .zip (Obsidian, Notion, .md/.txt), "
1188
+ "a calendar .ics (or Google's .zip of them), a folder of documents (.pdf, "
1189
+ ".docx), a folder of your git projects, reading highlights (Kindle "
1190
+ "My Clippings.txt, a Readwise or Pocket .csv), sent mail (.mbox), a Google "
1191
+ "Timeline (location history), a photo folder, a Spotify data export, a "
1192
+ "folder of voice memos (transcribed locally), Zotero's data folder or Anki "
1193
+ "(an .apkg/.colpkg export or your Anki profile folder). With "
1194
+ "--source zotero it may be left out: Keepfold finds your Zotero library.")] = None,
1195
+ source: Annotated[str | None, typer.Option(
1196
+ help="Force the kind: claude, chatgpt, gemini, perplexity, google-activity, "
1197
+ "obsidian, notion, notes, calendar, docs, repos, highlights, mail, "
1198
+ "selfchat (a WhatsApp chat with yourself, Telegram Saved Messages), "
1199
+ "location (Google Timeline), photos (a photo folder), spotify, "
1200
+ "voice-memos (a folder of recordings), zotero (a Zotero library) or anki "
1201
+ "(Anki decks).")] = None,
1202
+ dry_run: Annotated[bool, typer.Option(
1203
+ "--dry-run", help="Print counts only; write nothing.")] = False,
1204
+ private: Annotated[bool, typer.Option(
1205
+ "--private", help="The same as --tier private.")] = False,
1206
+ tier: Annotated[str | None, typer.Option(
1207
+ help="Who may read the imported pages (every import but chats and Google "
1208
+ "activity): private (local models "
1209
+ "only), normal (the AI apps you connect too) or skip (import nothing). "
1210
+ "Without it a terminal asks once per source; the choice is remembered. "
1211
+ "Refused for chats and Google activity.")] = None,
1212
+ vault: VaultOpt = None) -> None:
1213
+ """Import anything about you; the kind is detected from the file. Re-importing skips notes
1214
+ and events already in and updates chats. `import-chats` still imports chat exports only."""
1215
+ from keepfold import chats, importers, more_sources, sources
1216
+
1217
+ if source is not None and source not in importers.SOURCES:
1218
+ raise VaultError("invalid_argument",
1219
+ f"--source must be one of {', '.join(importers.SOURCES)}.")
1220
+ if tier is not None and tier not in sources.WORDS:
1221
+ raise VaultError("invalid_argument", f"--tier must be one of {', '.join(sources.WORDS)}.")
1222
+ if private and tier not in (None, "private"):
1223
+ raise VaultError("invalid_argument", "--private is --tier private; give only one.")
1224
+ given = tier or ("private" if private else None)
1225
+ if path is None and source != "zotero":
1226
+ raise VaultError("invalid_argument", "Give the file or folder to import (only --source "
1227
+ "zotero finds its library by itself).")
1228
+ kinds = [importers.SOURCES[source]] if source else importers.detect(path)
1229
+ if not kinds:
1230
+ raise VaultError("invalid_argument", f"Cannot tell what {path.name} is; add --source "
1231
+ f"{'|'.join(importers.SOURCES)}.")
1232
+ if given and {"chats", "takeout"} & set(kinds): # G5: these have no private mode
1233
+ from keepfold.app.actions import TIERED # the imports that take a tier
1234
+ flag = "--private" if private else "--tier"
1235
+ *some, last = ["calendars" if k == "calendar" else k for k in TIERED]
1236
+ raise VaultError("invalid_argument", f"{flag} applies to {', '.join(some)} and {last} "
1237
+ "only. "
1238
+ "Chats are always readable by /keepfold; Google activity follows your "
1239
+ f"Browsing settings. Run again without {flag}.")
1240
+ dry = " (dry run: nothing written)" if dry_run else ""
1241
+ for kind in kinds:
1242
+ if kind == "chats":
1243
+ got = chats.import_export(path, source if source in chats.EXPORT_DIRS else None,
1244
+ dry_run)
1245
+ name = chats.GUIDES[got[0]]["name"]
1246
+ typer.echo(f"{name}: {got[1]} new conversations, {got[2]} already imported{dry}"
1247
+ if dry_run else f"{name}: {got[1]} conversations imported into "
1248
+ f"{chats.export_root()}. Run /keepfold to learn from them.")
1249
+ typer.echo(importers.report_line(name, got.report()))
1250
+ continue
1251
+ if kind == "takeout": # also reads the browsers, as `browse import --takeout` does
1252
+ browse_import(since=None, browser=None, profile=None, dry_run=dry_run,
1253
+ takeout=path, vault=vault)
1254
+ continue
1255
+ v, flavor = _vault(vault), source if source in importers.LABELS else None
1256
+ src = importers.notes_source(path, flavor) if kind == "notes" else \
1257
+ importers.calendar_source(path) if kind == "calendar" else \
1258
+ more_sources.SOURCE_OF[kind](path)
1259
+ # C2: asked once per source in a real terminal, then remembered (sources.TIERS_FILE)
1260
+ ask = _ask_tier if given is None and _tty() else None
1261
+ told: list[str] = [] # RR-29: what a stricter tier did to the pages already in
1262
+ t, how = sources.pick_tier(v, src, given, ask, save=not dry_run, said=told.append)
1263
+ typer.echo(f"{src.label}: tier {sources.word(t)} (" + (
1264
+ "--tier" if given else "your answer" if how == "chosen"
1265
+ else f"{how}; change it with --tier") + ")")
1266
+ for line in told:
1267
+ typer.echo(line)
1268
+ if t is sources.Audience.SKIP:
1269
+ typer.echo(f"{src.label}: skip, so nothing was imported.")
1270
+ elif kind == "notes":
1271
+ r = importers.import_notes(v, path, flavor, dry_run, tier=t)
1272
+ typer.echo(f"{importers.LABELS[r['source']]}: {r['new']} new notes, {r['same']} "
1273
+ f"already imported, {r['skipped']} skipped (hidden, not text or over "
1274
+ f"5 MB){dry}")
1275
+ typer.echo(importers.report_line(importers.LABELS[r["source"]], r))
1276
+ elif kind in more_sources.SOURCE_OF:
1277
+ typer.echo(importers.report_line(src.label, sources.run(v, src, t, dry_run)) + dry)
1278
+ if kind == "anki" and not dry_run: # parent decks and concepts, once pages exist
1279
+ from keepfold import anki
1280
+ anki.link(v)
1281
+ else:
1282
+ r = importers.import_calendar(v, path, dry_run, tier=t)
1283
+ typer.echo(f"calendar: {r['events']} events in {r['months']} months, {r['new']} "
1284
+ f"new events{dry}")
1285
+ typer.echo(importers.report_line("calendar", r))
1286
+
1287
+
1288
+ watch_app = typer.Typer(no_args_is_help=True, help="Folders (and Zotero) that come in by "
1289
+ "themselves: the app reads their new and changed files every 10 "
1290
+ "minutes while it runs.")
1291
+ app.add_typer(watch_app, name="watch")
1292
+
1293
+
1294
+ @watch_app.command("add")
1295
+ @_errors
1296
+ def watch_add_cmd(path: Annotated[Path | None, typer.Argument(
1297
+ help="The folder to watch (its full path); for --source zotero, Zotero's data folder, "
1298
+ "or leave it out to find your library.")] = None,
1299
+ source: Annotated[str, typer.Option(
1300
+ help="What it holds: docs (PDFs, Word, text), notes (.md/.txt), repos (your git "
1301
+ "projects), calendar (.ics files; or give one .ics file) or zotero.")] = "docs",
1302
+ tier: Annotated[str | None, typer.Option(
1303
+ help="Who may read its pages: private, normal or skip. Without it, the source's "
1304
+ "last choice (or normal).")] = None,
1305
+ vault: VaultOpt = None) -> None:
1306
+ """Watch a folder: the Keepfold app imports its new and changed files by itself."""
1307
+ from keepfold import sources, watch
1308
+
1309
+ if tier is not None and tier not in sources.WORDS:
1310
+ raise VaultError("invalid_argument", f"--tier must be one of {', '.join(sources.WORDS)}.")
1311
+ told: list[str] = []
1312
+ w = watch.add(_vault(vault), path, source, tier, said=told.append)
1313
+ typer.echo(render.term(f"Watching {w['path']} as {w['source']}, tier "
1314
+ f"{sources.word(sources.Audience(w['tier']))}. The Keepfold app reads "
1315
+ "its new and changed files every 10 minutes while it runs."))
1316
+ for line in told:
1317
+ typer.echo(line)
1318
+
1319
+
1320
+ @watch_app.command("list")
1321
+ @_errors
1322
+ def watch_list_cmd(vault: VaultOpt = None) -> None:
1323
+ """The watched folders, their source and tier, and what their last pass did."""
1324
+ from keepfold import sources, watch
1325
+
1326
+ rows = watch.listing(_vault(vault))["rows"]
1327
+ if not rows:
1328
+ typer.echo("No folder is watched; add one with `keepfold watch add <folder>`.")
1329
+ for w in rows:
1330
+ last = w.get("last") or {}
1331
+ typer.echo(render.term(f"{w['path']} {w['source']} "
1332
+ f"{sources.word(sources.Audience(w['tier']))}"
1333
+ + (" (not found)" if w["missing"] else "")))
1334
+ typer.echo(render.term(f" last {last['at']}: {last['line']}" if last.get("line")
1335
+ else " not read yet"))
1336
+
1337
+
1338
+ @watch_app.command("remove")
1339
+ @_errors
1340
+ def watch_remove_cmd(path: Annotated[Path, typer.Argument(help="A watched folder.")],
1341
+ vault: VaultOpt = None) -> None:
1342
+ """Stop watching a folder; the pages it brought stay."""
1343
+ from keepfold import watch
1344
+
1345
+ if not watch.remove(_vault(vault), path):
1346
+ raise VaultError("invalid_argument", f"{path} is not watched; see `keepfold watch list`.")
1347
+ typer.echo(render.term(f"Stopped watching {path}; its pages stay."))
1348
+
1349
+
1350
+ def _ask_tier(src) -> str:
1351
+ """`keepfold import`'s tier question, with the source's default; asked again until the
1352
+ answer is one of the three words."""
1353
+ from keepfold import sources
1354
+ while (a := typer.prompt(f"{src.label}: who may read these pages? private (local models "
1355
+ "only), normal (the AI apps you connect too) or skip (import "
1356
+ "nothing)", default=sources.word(src.default_tier))
1357
+ .strip().lower()) not in sources.WORDS:
1358
+ typer.echo("Type private, normal or skip.")
1359
+ return a
1360
+
1361
+
1362
+ @app.command("claims")
1363
+ @_errors
1364
+ def claims_cmd(tier: Annotated[str | None, typer.Option(
1365
+ help="Only this tier: confirmed, agent, exposed, typed or legacy.")] = None,
1366
+ unasked: Annotated[bool, typer.Option(
1367
+ "--unasked", help="What was saved about you without your say, with undo steps.")]
1368
+ = False,
1369
+ summary: Annotated[bool, typer.Option(
1370
+ "--summary", help="How well Keepfold knows you, per me/ page.")]
1371
+ = False,
1372
+ days: Annotated[int, typer.Option(help="With --unasked: days of me/ changes.")] = 14,
1373
+ vault: VaultOpt = None) -> None:
1374
+ """List live claims on the me/ claim pages with their id and authorship tier.
1375
+ --unasked and --summary print the other two views instead."""
1376
+ from keepfold import claims
1377
+
1378
+ if sum((tier is not None, unasked, summary)) > 1:
1379
+ raise VaultError("invalid_argument", "Use one of --tier, --unasked and --summary.")
1380
+ if unasked:
1381
+ return saved_cmd(days, vault)
1382
+ if summary:
1383
+ return know_cmd(vault)
1384
+ if tier is not None and tier not in claims.TIERS:
1385
+ raise VaultError("invalid_argument", f"--tier must be one of {', '.join(claims.TIERS)}.")
1386
+ _refuse_excluded("list claims")
1387
+ v = _vault(vault)
1388
+ log = EventLog(v)
1389
+ events = list(log.iter_events())
1390
+ sample = {n.id for n in v.iter_notes("me") if n.fields.get("sample") is True}
1391
+ for r in claims.tiers(v, events, log):
1392
+ if tier in (None, r["tier"]):
1393
+ typer.echo(f"^{r['id']} {r['tier']:<9} me/{r['page']} § "
1394
+ f"{render.esc(r['section'], 40)} {render.esc(r['text'], 80)}"
1395
+ + (" (sample)" if r["page"] in sample else ""))
1396
+
1397
+
1398
+ @app.command("saved", hidden=True) # now `claims --unasked`
1399
+ @_errors
1400
+ def saved_cmd(days: int = 14, vault: VaultOpt = None) -> None:
1401
+ """What was saved about you without your say: claim lines an assistant wrote unasked or
1402
+ from outside text, then recent me/ changes, each with its undo. Read-only."""
1403
+ from keepfold import claims
1404
+
1405
+ _refuse_excluded("list saved lines")
1406
+ v = _vault(vault)
1407
+ out = claims.saved(v, EventLog(v).iter_events(), local_day(datetime.now(UTC)), days)
1408
+ typer.echo(f"Claim lines saved unasked: {len(out['claims'])}")
1409
+ for r in out["claims"]:
1410
+ label = {"exposed": "from outside text", "confirmed": "relayed yes"}.get(r["tier"],
1411
+ "unasked")
1412
+ typer.echo(f" ^{r['id']} {r['day'] or '-'} {label} me/{r['page']} § "
1413
+ f"{render.esc(r['section'], 40)} {render.esc(r['text'], 100)}")
1414
+ typer.echo(f" undo: {r['undo']}")
1415
+ typer.echo(f"me/ changes in the last {days} days: {len(out['changes'])}"
1416
+ + (f" (latest {claims.SAVED_CHANGES})"
1417
+ if len(out["changes"]) == claims.SAVED_CHANGES else ""))
1418
+ for c in out["changes"]:
1419
+ typer.echo(f" {c['day']} me/{render.esc(c['page'], 40)} {c['op']} "
1420
+ f"{render.esc(c['target'], 60)}"
1421
+ + (" (from outside text)" if c["exposed"] else ""))
1422
+ typer.echo(f" undo: {c['undo']}")
1423
+ if out["claims"]:
1424
+ typer.echo("To keep an unasked line, say yes in a /keepfold reflect with no outside reads.")
1425
+
1426
+
1427
+ @app.command("know", hidden=True) # now `claims --summary`
1428
+ @_errors
1429
+ def know_cmd(vault: VaultOpt = None) -> None:
1430
+ """How well Keepfold knows you: per me/ page, live claims by tier. Read-only."""
1431
+ from keepfold import know
1432
+
1433
+ def counts(d: dict) -> str:
1434
+ return ", ".join(f"{k} {n}" for k, n in d.items())
1435
+
1436
+ _refuse_excluded("report")
1437
+
1438
+ def split(p: dict) -> str: # idea 11: who gave the confirmed lines their yes
1439
+ n = p["tiers"]["confirmed"]
1440
+ return (f" (confirmed: {p['clicked']} clicked, {p['reflected']} reflected, "
1441
+ f"{n - p['clicked'] - p['reflected']} relayed)") if n else ""
1442
+
1443
+ v = _vault(vault)
1444
+ out = know.report(v, EventLog(v).iter_events(), local_day(datetime.now(UTC)))
1445
+ for p in out["pages"]:
1446
+ if p["private"]:
1447
+ typer.echo(f"me/{p['page']}: private")
1448
+ continue
1449
+ typer.echo(f"me/{p['page']}: {p['live']} live claims")
1450
+ typer.echo(f" tiers: {counts(p['tiers'])}{split(p)}")
1451
+ t = out["total"]
1452
+ typer.echo(f"All claim pages: {t['live']} live claims")
1453
+ typer.echo(f" tiers: {counts(t['tiers'])}{split(t)}")
1454
+
1455
+
1456
+ voice_app = typer.Typer(help="Your own sent messages (voice samples).")
1457
+ app.add_typer(voice_app, name="voice")
1458
+
1459
+
1460
+ @voice_app.callback(invoke_without_command=True)
1461
+ @_errors
1462
+ def voice_cmd(ctx: typer.Context, vault: VaultOpt = None) -> None:
1463
+ """Count voice samples per audience and channel."""
1464
+
1465
+ from keepfold import voice
1466
+
1467
+ if ctx.invoked_subcommand is not None:
1468
+ return
1469
+ v = _vault(vault)
1470
+ counts = Counter((str(s.get("audience")), str(s.get("channel")))
1471
+ for s in voice.rows(v, voice.SAMPLES))
1472
+ for (a, c), n in sorted(counts.items()):
1473
+ typer.echo(f"{render.esc(a, 60):<30} {render.esc(c, 10):<7} {n:>4}")
1474
+ if not counts:
1475
+ typer.echo("No voice samples yet; add your sent messages with `keepfold voice import`.")
1476
+
1477
+
1478
+ @voice_app.command("import")
1479
+ @_errors
1480
+ def voice_import(file: Path,
1481
+ audience: Annotated[str, typer.Option(help="A tag (professor) or people/<slug>.")],
1482
+ act: Annotated[str, typer.Option(help="request|reply|thanks|apology|update|"
1483
+ "decline|intro|other")],
1484
+ channel: Annotated[str, typer.Option(help="email|chat|sms|social|ai|other")],
1485
+ vault: VaultOpt = None) -> None:
1486
+ """Add your own sent messages, separated by lines of `---`, as voice samples."""
1487
+ from keepfold import voice
1488
+
1489
+ v = _vault(vault)
1490
+ try:
1491
+ text = file.read_bytes().decode("utf-8")
1492
+ except (OSError, UnicodeDecodeError) as e:
1493
+ raise VaultError("invalid_argument", f"Cannot read {file}: {e}") from None
1494
+ n = voice.import_text(v, text, audience, act, channel, datetime.now(UTC))
1495
+ typer.echo(f"Imported {n} voice samples for {audience}.")
1496
+
1497
+
1498
+ @voice_app.command("measure")
1499
+ @_errors
1500
+ def voice_measure(propose: Annotated[bool, typer.Option(
1501
+ "--propose", help="Save the lines to me/voice; each waits for your Approve.")] = False,
1502
+ vault: VaultOpt = None) -> None:
1503
+ """Count how you write (sentence length, questions, greetings...) from your samples."""
1504
+ from keepfold import voice
1505
+
1506
+ v = _vault(vault)
1507
+ m = voice.measure(v)
1508
+ if not m:
1509
+ typer.echo(f"Not enough voice samples yet (at least {voice.MIN_GROUP} per audience, "
1510
+ "not counting ones typed to an AI).")
1511
+ return
1512
+ for g, nums in m.items():
1513
+ typer.echo(f"{render.esc(g, 60)}: " + ", ".join(
1514
+ f"{k} {render.esc(str(x), 40)}" for k, x in nums.items()))
1515
+ for line in voice.style_lines(m, g):
1516
+ typer.echo(f" - {render.esc(line, 200)}")
1517
+ if propose:
1518
+ n = voice.propose(v, m)
1519
+ typer.echo(f"me/voice: {n.get('proposed', 0)} proposed, {n.get('kept', 0)} kept, "
1520
+ f"{n.get('withdrawn', 0)} withdrawn; they wait for your Approve in the Keepfold "
1521
+ "app (Review).")
1522
+
1523
+
1524
+ # ---- brief ----------------------------------------------------------------------
1525
+
1526
+ FIRST_STEPS = ("To start: 1. add a test date (tell any Claude chat, or add one in assessments/); "
1527
+ "2. run /keepfold in Claude; 3. import your notes or chats with "
1528
+ "`keepfold import <file>`.")
1529
+
1530
+
1531
+ def _today_line(it: dict) -> str:
1532
+ state = it["state"]
1533
+ head = f"{levels.GLYPH[state]} {levels.LABEL[state]}" if state else "- Plan step"
1534
+ # the id only when it says something the title doesn't ("Sorting", not "Sorting (sorting)")
1535
+ name = it["title"] if not it["id"] or page_slug(it["title"]) == it["id"] else \
1536
+ f"{it['title']} ({it['id']})"
1537
+ return f"{head}: {name} [{it['why']}]"
1538
+
1539
+
1540
+ def _print_today(v: Vault, now: datetime, minutes: int | None = None) -> list[dict]:
1541
+ """Print Today (cut to `minutes` when given) and return the whole plan for Today.md."""
1542
+ catalog, day = Catalog.load(v), local_day(now)
1543
+ states, _ = planner.current_states(v, day, catalog)
1544
+ typer.echo("## Today")
1545
+ items = planner.today(v, catalog, states, now=now)
1546
+ shown = planner.fit(items, minutes) if minutes else items
1547
+ for it in shown:
1548
+ typer.echo(render.term(_today_line(it)))
1549
+ if minutes and shown:
1550
+ typer.echo(f"Time: {planner.budget_note(shown, minutes)}")
1551
+ if not items: # "done" only after work today; a vault never graded gets first steps
1552
+ events = list(EventLog(v).iter_events())
1553
+ typer.echo("Nothing planned yet.")
1554
+ if not any(e.get("kind") == "grade" for e in events):
1555
+ typer.echo(FIRST_STEPS)
1556
+ elif any(e.get("day") == day for e in events):
1557
+ typer.echo("Done for today ✓")
1558
+ return items
1559
+
1560
+
1561
+ @app.command()
1562
+ @_errors
1563
+ def brief(vault: VaultOpt = None) -> None:
1564
+ """Print BRIEF.md, the teaching contract verbatim, and Today."""
1565
+ _refuse_excluded("print the brief")
1566
+ v = _vault(vault)
1567
+ for rel in ("BRIEF.md", "me/teaching-contract.md"):
1568
+ p = v.root / rel
1569
+ if rel == "BRIEF.md" and not p.is_file(): # optional: only a vault you wrote one in
1570
+ continue
1571
+ text = p.read_bytes().decode("utf-8") if p.is_file() else f"({rel} is missing)\n"
1572
+ typer.echo(text.rstrip("\n") + "\n")
1573
+ _print_today(v, datetime.now(UTC))
1574
+
1575
+
1576
+ @app.command()
1577
+ @_errors
1578
+ def today(minutes: Annotated[int | None, typer.Option(
1579
+ help=f"Print only what fits a session this long (1-{planner.MINUTES_MAX}; "
1580
+ "estimates). Today.md keeps the whole plan.")] = None,
1581
+ vault: VaultOpt = None) -> None:
1582
+ """Print Today and rewrite Today.md."""
1583
+ v, now = _vault(vault), datetime.now(UTC)
1584
+ items = _print_today(v, now, planner.check_minutes(minutes))
1585
+ v.write_text(v.root / "Today.md", render.today_md(
1586
+ today=items, assessments=planner.assessments(v),
1587
+ as_of=local_day(now), cues=planner.last_questions(v),
1588
+ deadlines=planner.deadlines(v, local_day(now))))
1589
+
1590
+
1591
+ @app.command()
1592
+ @_errors
1593
+ def dashboard(no_open: Annotated[bool, typer.Option(
1594
+ "--no-open", help="Rewrite index.md only; do not open the app.")] = False,
1595
+ relayout: Annotated[bool, typer.Option(
1596
+ "--relayout", help="Lay the brain out again from scratch.")] = False,
1597
+ vault: VaultOpt = None) -> None:
1598
+ """Rewrite index.md and open the dashboard: the Keepfold app's live home, starting the app
1599
+ as `keepfold app` does when it is not running. Export snapshot (the app's Vault page) saves
1600
+ an offline copy."""
1601
+ v, now = _vault(vault), datetime.now(UTC)
1602
+ if (old := dashboard_mod.retire_old(v)) is not None:
1603
+ typer.echo(f"Keepfold no longer writes .keepfold/dashboard.html; moved it to {old}",
1604
+ err=True)
1605
+ if relayout:
1606
+ typer.echo("Laying the brain out again…", err=True) # a big vault takes a while
1607
+ dashboard_mod.build(v, now=now, relayout=True)
1608
+ typer.echo(str(dashboard_mod.write_index(v, now=now)))
1609
+ if no_open:
1610
+ return
1611
+ from keepfold.app import server
1612
+ if url := server.running_url(): # the open app, not a second one
1613
+ if not server.show_window(url): # the browser app has no window
1614
+ webbrowser.open(url)
1615
+ return
1616
+ server.run(v.root, echo=typer.echo)
1617
+
1618
+
1619
+ @app.command()
1620
+ @_errors
1621
+ def void(event_id: str, reason: Annotated[str, typer.Option(help="Why it is cancelled.")],
1622
+ vault: VaultOpt = None) -> None:
1623
+ """Cancel one earlier event so it stops counting toward levels."""
1624
+ v = _vault(vault)
1625
+ void_event(EventLog(v), session="cli", event_id=event_id, reason=reason, source="external")
1626
+ typer.echo(f"voided {event_id}")
1627
+
1628
+
1629
+ # ---- log ------------------------------------------------------------------------
1630
+
1631
+ def _problem(v: Vault, id: str) -> str:
1632
+ v.read("problem", id) # raises unknown_id with a hint
1633
+ return id
1634
+
1635
+
1636
+ @log_app.command("result")
1637
+ @_errors
1638
+ def log_result(concept: str, outcome: Annotated[str, typer.Argument(help="pass|partial|fail")],
1639
+ hints: Annotated[int, typer.Option(help="Hints you needed.")] = 0,
1640
+ confidence: Annotated[int | None, typer.Option(
1641
+ help="How sure you were before checking, 1-4.")] = None,
1642
+ problem: Annotated[str | None, typer.Option(
1643
+ help="The problem id it was about, if any.")] = None,
1644
+ vault: VaultOpt = None) -> None:
1645
+ """Log a graded result on a concept."""
1646
+ if outcome not in VERDICTS:
1647
+ raise VaultError("invalid_argument", "The outcome must be pass, partial or fail.")
1648
+ v = _vault(vault)
1649
+ obj = resolve_or_inbox(v, Catalog.load(v), concept, "keepfold log result")
1650
+ fields = {"object": obj, "verdict": VERDICTS[outcome], "hints": hints}
1651
+ if confidence is not None:
1652
+ fields["confidence"] = confidence
1653
+ if problem:
1654
+ fields["problem"] = f"problem:{_problem(v, problem)}"
1655
+ EventLog(v).append(session="cli", kind="grade", source="external", fields=fields)
1656
+ typer.echo(f"logged {outcome} on {obj}" + (" (added to inbox.md)" if
1657
+ obj.startswith("inbox:") else ""))
1658
+
1659
+
1660
+ @log_app.command("solved")
1661
+ @_errors
1662
+ def log_solved(problem: str, hints: Annotated[int, typer.Option(help="Hints you needed.")] = 0,
1663
+ vault: VaultOpt = None) -> None:
1664
+ """Log a solved problem (a correct verdict on its primary concept)."""
1665
+ v = _vault(vault)
1666
+ _problem(v, problem)
1667
+ EventLog(v).append(session="cli", kind="log", source="external", fields={
1668
+ "object": f"problem:{problem}", "payload": {
1669
+ "kind": "problem_status", "problem": problem, "status": "solved", "hints": hints}})
1670
+ v.set_field("problem", problem, "status", "solved") # the planner reads the note
1671
+ v.set_field("problem", problem, "solved_on", local_day(datetime.now(UTC)))
1672
+ typer.echo(f"logged solved on problem:{problem}")
1673
+
1674
+
1675
+ @log_app.command("assessment")
1676
+ @_errors
1677
+ def log_assessment_cmd(id: str, outcome: Annotated[str, typer.Option(
1678
+ help="pass|fail|pending|unknown")],
1679
+ score: Annotated[str | None, typer.Option(
1680
+ help="Your score as written, e.g. 7/10.")] = None,
1681
+ company: Annotated[str | None, typer.Option(
1682
+ help="Who set the test.")] = None,
1683
+ kind: Annotated[str | None, typer.Option(
1684
+ help="The kind of test, e.g. oa, interview, exam.")] = None,
1685
+ date: Annotated[str | None, typer.Option(
1686
+ help="The test's date (YYYY-MM-DD).")] = None,
1687
+ weak: Annotated[str | None, typer.Option(help="a,b,c")] = None,
1688
+ vault: VaultOpt = None) -> None:
1689
+ """Log an assessment result; creates the assessment note if it is missing."""
1690
+ v = _vault(vault)
1691
+ felt_weak = [w.strip() for w in (weak or "").split(",") if w.strip()]
1692
+ log_assessment(EventLog(v), session="cli", source="external", assessment=id,
1693
+ outcome=outcome, score=score, company=company, kind=kind, date=date,
1694
+ felt_weak=felt_weak)
1695
+ typer.echo(f"logged {outcome} on assessment:{id}")
1696
+
1697
+
1698
+ @log_app.command("taught")
1699
+ @_errors
1700
+ def log_taught(concept: str, vault: VaultOpt = None) -> None:
1701
+ """Mark a concept as taught, not yet checked."""
1702
+ v = _vault(vault)
1703
+ obj = resolve_or_inbox(v, Catalog.load(v), concept, "keepfold log taught")
1704
+ EventLog(v).append(session="cli", kind="taught", source="external", fields={"object": obj})
1705
+ typer.echo(f"logged taught on {obj}" + (" (added to inbox.md)" if
1706
+ obj.startswith("inbox:") else ""))
1707
+
1708
+
1709
+ # ---- concept --------------------------------------------------------------------
1710
+
1711
+ @concept_app.command("add")
1712
+ @_errors
1713
+ def concept_add(title: str,
1714
+ parent: Annotated[str | None, typer.Option(
1715
+ help="The parent id (a domain for an area, an area for a concept).")] = None,
1716
+ kind: Annotated[str, typer.Option(help="domain|area|concept")] = "concept",
1717
+ alias: Annotated[list[str] | None, typer.Option(
1718
+ help="Another name for it; repeat for more.")] = None,
1719
+ requires: Annotated[list[str] | None, typer.Option(
1720
+ help="A concept id it builds on; repeat for more.")] = None,
1721
+ force: Annotated[bool, typer.Option(
1722
+ help="Add it even when a similar concept exists.")] = False,
1723
+ vault: VaultOpt = None) -> None:
1724
+ """Add a domain, area or concept to the catalog and create its note."""
1725
+ v = _vault(vault)
1726
+ try:
1727
+ cat = Catalog.load(v)
1728
+ id = cat.add(kind, title, parent, alias or [], requires or [], force)
1729
+ except VaultError as e:
1730
+ if e.code == "duplicate_suggested":
1731
+ raise VaultError(e.code, f"{e} (pass --force)") from None
1732
+ raise
1733
+ typer.echo(f"{'adopted' if cat.adopted else 'added'} {kind} {id}")
1734
+
1735
+
1736
+ @concept_app.command("alias")
1737
+ @_errors
1738
+ def concept_alias(id: str, alias: str, vault: VaultOpt = None) -> None:
1739
+ """Add an alias to a domain, area or concept."""
1740
+ Catalog.load(_vault(vault)).alias(id, alias)
1741
+ typer.echo(f"aliased '{alias}' -> {id}")
1742
+
1743
+
1744
+ @concept_app.command("merge")
1745
+ @_errors
1746
+ def concept_merge(src: str, dst: str, vault: VaultOpt = None) -> None:
1747
+ """Fold concept SRC into DST and append a remap event."""
1748
+ v = _vault(vault)
1749
+ cat = Catalog.load(v)
1750
+ src, dst = cat.resolve(src), cat.resolve(dst)
1751
+ cat.merge(src, dst)
1752
+ EventLog(v).append(session="cli", kind="remap", source="external",
1753
+ fields={"object": f"concept:{dst}", "ref": f"concept:{src}"})
1754
+ typer.echo(f"merged {src} into {dst}; remap logged")
1755
+
1756
+
1757
+ @concept_app.command("duplicates")
1758
+ @_errors
1759
+ def concept_duplicates(limit: Annotated[int, typer.Option(help="pairs to show")] = 20,
1760
+ vault: VaultOpt = None) -> None:
1761
+ """List concept pairs that probably mean the same thing, with evidence and the merge
1762
+ command for each. Read-only: it merges nothing."""
1763
+ from keepfold import duplicates, semantic
1764
+
1765
+ v = _vault(vault)
1766
+ typer.echo(duplicates.report(*duplicates.find(v, semantic.load_embedder(), limit)))
1767
+
1768
+
1769
+ # ---- replay, backup, undo, import -----------------------------------------------
1770
+
1771
+ def _why(st) -> str:
1772
+ """Short reason for a concept's new state, from the Solid criteria it misses."""
1773
+ if st is None:
1774
+ return "no events"
1775
+ if st.state == "solid":
1776
+ return "meets solid criteria"
1777
+ why = []
1778
+ if not st.depth_pass:
1779
+ why.append("no application/transfer pass")
1780
+ if (st.stability or 0) < levels.SOLID_STABILITY:
1781
+ # truncate, so 9.97 never prints as "10.0 < 10"
1782
+ why.append(f"stability {int((st.stability or 0) * 10) / 10:.1f} < "
1783
+ f"{levels.SOLID_STABILITY:g}")
1784
+ if st.pass_days < levels.SOLID_PASS_DAYS:
1785
+ why.append(f"{st.pass_days} pass day{'s' * (st.pass_days != 1)} < {levels.SOLID_PASS_DAYS}")
1786
+ if st.solid_after:
1787
+ why.append(levels.gap_note(st))
1788
+ elif not st.gap_pass and st.pass_days:
1789
+ why.append(f"no pass {levels.SOLID_GAP_DAYS}+ days after the first pass "
1790
+ f"with {levels.SOLID_REST_DAYS}+ days off before it")
1791
+ return "; ".join(why) or st.state
1792
+
1793
+
1794
+ def _sync_lines(report: dict[str, list[str]]) -> list[str]:
1795
+ return [f"{what} {item}" for what, items in report.items() for item in items]
1796
+
1797
+
1798
+ @catalog_app.command("sync")
1799
+ @_errors
1800
+ def catalog_sync_cmd(vault: VaultOpt = None) -> None:
1801
+ """Make catalog.yaml agree with domains/, areas/ and concepts/; never deletes."""
1802
+ typer.echo("\n".join(_sync_lines(catalog_sync(_vault(vault)))) or "catalog in sync")
1803
+
1804
+
1805
+ @app.command()
1806
+ @_errors
1807
+ def replay(dry_run: Annotated[bool, typer.Option(
1808
+ help="Print a diff of what would change; write nothing.")] = False,
1809
+ all_: Annotated[bool, typer.Option(
1810
+ "--all", help="Show every changed line, not 25 per group.")] = False,
1811
+ vault: VaultOpt = None) -> None:
1812
+ """Recompute all states and rewrite keepfold_status/keepfold_next where they changed.
1813
+
1814
+ --dry-run prints a diff of what would change; --all lifts its 25-line cap per group."""
1815
+ v = _vault(vault)
1816
+ if not dry_run: # a dry run changes nothing, so it skips the catalog sync too
1817
+ for line in _sync_lines(catalog_sync(v, if_changed=True)):
1818
+ typer.echo(line)
1819
+ states, _ = planner.current_states(v, local_day(datetime.now(UTC)))
1820
+ counts = dict.fromkeys(levels.STATES, 0)
1821
+ changed = 0
1822
+ groups: dict[str, list[str]] = {}
1823
+ for note in v.iter_notes("concept"):
1824
+ st = states.get(note.id)
1825
+ status, nxt = (st.state, st.next_due) if st else ("not_started", None)
1826
+ counts[status] += 1
1827
+ old_next = note.fields.get("keepfold_next")
1828
+ old_next = None if old_next is None else str(old_next) # YAML may parse a bare date
1829
+ old = note.fields.get("keepfold_status")
1830
+ if (old, old_next) != (status, nxt):
1831
+ changed += 1
1832
+ if dry_run:
1833
+ key = f"{old or 'unstamped'} → {status}" if old != status else "next due moved"
1834
+ groups.setdefault(key, []).append(
1835
+ f"{note.id} {old or 'unstamped'} → {status} (next {old_next} → {nxt})"
1836
+ f" {_why(st)}")
1837
+ else:
1838
+ v.set_tool_props("concept", note.id, status, nxt)
1839
+ if dry_run:
1840
+ for key, lines in sorted(groups.items(), key=lambda kv: -len(kv[1])):
1841
+ typer.echo(f"{key}: {len(lines)}")
1842
+ typer.echo(f"unchanged: {sum(counts.values()) - changed}")
1843
+ for key, lines in groups.items():
1844
+ typer.echo(f"\n{key}")
1845
+ shown = lines if all_ else lines[:25]
1846
+ for line in shown:
1847
+ typer.echo(line)
1848
+ if len(shown) < len(lines):
1849
+ typer.echo(f"+{len(lines) - len(shown)} more")
1850
+ typer.echo("\ncalibration: state going into a graded day, and how often that day's"
1851
+ " first item passed")
1852
+ for s, (n, ok) in levels.calibration(EventLog(v).iter_events(),
1853
+ levels.problem_concepts(v)).items():
1854
+ typer.echo(f"{levels.LABEL[s]}: {n} concept-day{'s' * (n != 1)}"
1855
+ + (f", {ok / n:.0%} passed" if n else ""))
1856
+ typer.echo("")
1857
+ for s in levels.STATES:
1858
+ typer.echo(f"{levels.GLYPH[s]} {levels.LABEL[s]}: {counts[s]}")
1859
+ typer.echo(f"{changed} note(s) {'would change' if dry_run else 'updated'}")
1860
+
1861
+
1862
+ @app.command()
1863
+ @_errors
1864
+ def backup(to: Annotated[Path | None, typer.Option(
1865
+ help="Folder for the zip; default .keepfold/backups in the vault.")] = None,
1866
+ no_private: bool = typer.Option(False, "--no-private", help=(
1867
+ "Leave out private pages, pages under a private subject, their raw sources, "
1868
+ "browse/private, the browse store and .git (its history holds private pages).")),
1869
+ vault: VaultOpt = None) -> None:
1870
+ """Zip the whole vault (with .git) to .keepfold/backups or --to DIR."""
1871
+ v = _vault(vault)
1872
+ dest = backup_mod.backup(v.root, to, private=not no_private)
1873
+ typer.echo(f"{dest} ({dest.stat().st_size:,} bytes)")
1874
+ if to is not None and backup_mod.same_drive(dest, v.root):
1875
+ typer.echo("WARN: the backup is on the same drive as the vault; copy it elsewhere.",
1876
+ err=True)
1877
+
1878
+
1879
+ @app.command()
1880
+ @_errors
1881
+ def undo(session_id: str, vault: VaultOpt = None) -> None:
1882
+ """Revert a session's vault commit; where a later session changed the same lines, the later
1883
+ text is kept. Then restamp props and Today.md and commit."""
1884
+ if not SESSION_ID_RE.fullmatch(session_id):
1885
+ raise VaultError("invalid_argument", "The session id looks like s_<26-char ULID>.")
1886
+ v = _vault(vault)
1887
+ git_on, private_kept = session_mod.git_choice()
1888
+ if not git_on:
1889
+ raise VaultError("invalid_argument", "Undo needs the vault's git history, and git is "
1890
+ "off in your settings, so no session was saved to go back to. Turn on "
1891
+ "\"Keep the vault's history in git\" under Vault in the app (or set "
1892
+ "`git: {enabled: true}` in ~/.keepfold/config.yaml); sessions closed "
1893
+ "after that can be undone.")
1894
+ with v.lock():
1895
+ # anchored: `keepfold: other changes before session <id>` is not that session's commit;
1896
+ # `cortex:` is how 0.6.1 and older (Cortex) named the same commits
1897
+ found = _git(v.root, "log", "-E",
1898
+ f"--grep=^(keepfold|cortex): (session|undo) {session_id}",
1899
+ "--format=%H %s", "-n", "1")
1900
+ commit, _, subject = found.stdout.strip().partition(" ")
1901
+ if found.returncode or not commit:
1902
+ typer.echo(f"No vault commit mentions {session_id}; nothing to undo.")
1903
+ return
1904
+ if subject.partition(": ")[2].startswith("undo "):
1905
+ typer.echo(f"{session_id} is already undone ({commit[:10]}).")
1906
+ return
1907
+ if busy := session_mod.git_busy(v.root):
1908
+ raise VaultError("invalid_argument", f"The vault repo is mid-operation ({busy}); "
1909
+ "finish or abort it in git first.")
1910
+ if dirty := [ln[3:] for ln in _git(v.root, "status", "--porcelain").stdout.splitlines()
1911
+ if ln.strip()]:
1912
+ from keepfold import duplicates # a path is vault data: no control chars or links
1913
+ names = ", ".join(duplicates.safe(p, 80) for p in dirty[:5])
1914
+ raise VaultError("invalid_argument", f"The vault has uncommitted changes ({names}"
1915
+ f"{f' and {len(dirty) - 5} more' if len(dirty) > 5 else ''}); "
1916
+ "close the open session or commit them first. If a session close "
1917
+ "keeps leaving a file out, it looks like it holds a key: remove "
1918
+ "the key and close again.")
1919
+
1920
+ from keepfold.browse.forget import PRIVATE_IGNORE
1921
+
1922
+ # C3: a private browse page the commit holds (an older vault) is never reverted,
1923
+ # committed or deleted: git may overwrite an ignored file, so what is on disk now is
1924
+ # put back, and the index left as HEAD has it, after each step that may touch it.
1925
+ # With `git.private_browsing` on they are ordinary tracked pages and revert as such.
1926
+ private = [] if private_kept else [
1927
+ p for p in _git(v.root, "diff-tree", "-r", "--name-only", "--no-commit-id",
1928
+ "--relative", commit).stdout.splitlines()
1929
+ if p.startswith(PRIVATE_IGNORE)]
1930
+ saved = {p: (v.root / p).read_bytes() for p in private if (v.root / p).is_file()}
1931
+
1932
+ def keep_private():
1933
+ for p in private:
1934
+ _git(v.root, "reset", "-q", "--", p)
1935
+ if p in saved:
1936
+ (v.root / p).parent.mkdir(parents=True, exist_ok=True)
1937
+ v._atomic_write(v.root / p, saved[p])
1938
+ elif (v.root / p).exists():
1939
+ v.remove(v.root / p)
1940
+
1941
+ def restore(): # the tree was clean and we hold the lock, so HEAD is the whole state
1942
+ _git(v.root, "revert", "--abort")
1943
+ _git(v.root, "reset", "-q", "--hard", "HEAD")
1944
+ keep_private()
1945
+
1946
+ try:
1947
+ kept = []
1948
+ # R10: only a forget's redaction changes a session's own event file later, so the
1949
+ # session's undo still deletes it
1950
+ own = lambda p: "events" in Path(p).parts and Path(p).stem == session_id # noqa: E731
1951
+ if _git(v.root, "revert", "--no-commit", commit).returncode:
1952
+ kept = [p for p in session_mod.unmerged_paths(v.root) # a later commit overlapped
1953
+ if not any(p.endswith(q) for q in private) and not own(p)]
1954
+ restore()
1955
+ r = _git(v.root, "revert", "--no-commit", "-X", "ours", commit)
1956
+ if r.returncode and not session_mod.unmerged_paths(v.root):
1957
+ raise VaultError("invalid_argument", f"git revert failed: {r.stderr.strip()}")
1958
+ keep_private()
1959
+ for p in session_mod.unmerged_paths(v.root): # modify/delete: keep HEAD's side
1960
+ in_head = not own(p) and not _git(v.root, "cat-file", "-e", f"HEAD:{p}").returncode
1961
+ _git(v.root, *(("checkout", "HEAD", "--") if in_head else ("rm", "-qf", "--")),
1962
+ p)
1963
+ if left := session_mod.unmerged_paths(v.root):
1964
+ raise VaultError("invalid_argument", f"unresolved: {', '.join(left)}")
1965
+ replay(dry_run=False, vault=v) # stamp props and Today.md as session close does
1966
+ today(vault=v)
1967
+ for args in (("add", "-A"), ("commit", "-q", "-m", f"keepfold: undo {session_id}")):
1968
+ r = _git(v.root, *args)
1969
+ if r.returncode:
1970
+ raise VaultError("invalid_argument", f"git {args[0]} failed: "
1971
+ f"{r.stderr.strip() or r.stdout.strip()}")
1972
+ except BaseException:
1973
+ restore()
1974
+ raise
1975
+ for p in kept:
1976
+ typer.echo(f"kept later text: {p}")
1977
+ typer.echo(f"reverted {commit[:10]} ({session_id})")
1978
+
1979
+
1980
+ # ---- session, hook --------------------------------------------------------------
1981
+
1982
+ def _closed(ids: list[str]) -> None:
1983
+ for sid in ids:
1984
+ typer.echo(f"closed {sid}")
1985
+ if not ids:
1986
+ typer.echo("No orphan sessions to close.")
1987
+
1988
+
1989
+ @session_app.command("sweep")
1990
+ @_errors
1991
+ def session_sweep(vault: VaultOpt = None) -> None:
1992
+ """Close sessions with no close event whose server has exited or that have idled 2 h."""
1993
+ _closed(session_mod.sweep(_vault(vault)))
1994
+
1995
+
1996
+ @session_app.command("close")
1997
+ @_errors
1998
+ def session_close(vault: VaultOpt = None) -> None:
1999
+ """Close every session with no close event now, whatever its age."""
2000
+ _closed(session_mod.sweep(_vault(vault), force=True))
2001
+
2002
+
2003
+ @app.command()
2004
+ @_errors
2005
+ def mcp(vault: VaultOpt = None,
2006
+ role: Annotated[str, typer.Option(help="owner (default) or reader; fixed "
2007
+ "for this server's life.")] = "owner",
2008
+ private: Annotated[bool, typer.Option(
2009
+ "--private", help="Also serve keepfold_browse_search over every browse page, private "
2010
+ "ones included. For local models only; needs browse.private_mcp: true.")] = False,
2011
+ ) -> None:
2012
+ """Serve the Keepfold MCP tools over stdio."""
2013
+ from keepfold import mcp_server # the mcp SDK is only needed here
2014
+
2015
+ if role not in mcp_server.ROLES:
2016
+ raise VaultError("invalid_argument", f"--role must be one of "
2017
+ f"{', '.join(mcp_server.ROLES)}.")
2018
+ if private:
2019
+ from keepfold.browse.privacy import load_settings
2020
+ if not load_settings().private_mcp:
2021
+ raise VaultError("invalid_argument", "--private is off: it serves your private "
2022
+ "browsing, so turn on 'Local AI access (LM Studio only)' in "
2023
+ "`keepfold app` (browse.private_mcp: true) first.")
2024
+ if folder := taint.excluded(*taint.session_dirs()):
2025
+ typer.echo(f"keepfold: {folder} is excluded; refusing every tool.", err=True)
2026
+ mcp_server.serve(_vault(vault), role, folder, private=private)
2027
+
2028
+
2029
+ # ---- v5 PHASE4 V4-V5: forget, kill switch, access log ----------------------------
2030
+
2031
+ @app.command()
2032
+ @_errors
2033
+ def forget(
2034
+ id: str,
2035
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip the confirmation prompt.")] = False,
2036
+ vault: VaultOpt = None,
2037
+ ) -> None:
2038
+ """Forget a page (people/<slug>, a page id, a chat page) or one line of a me/ page
2039
+ (me/<page>^c-xxxxx) everywhere Keepfold keeps it: the page or line, the event log (its text
2040
+ redacted, ids and grades kept), Keepfold's own pages and caches, the chats it keeps, the
2041
+ search snapshot and vectors. Prints a receipt, with what Keepfold cannot remove."""
2042
+ from keepfold import forget as forget_
2043
+
2044
+ v = _vault(vault)
2045
+ if not yes:
2046
+ typer.confirm(f"Forget {forget_.check(v, id)} everywhere Keepfold keeps it? This cannot be "
2047
+ "undone.", abort=True)
2048
+ for line in forget_.lines(forget_.forget(v, id)):
2049
+ typer.echo(line)
2050
+
2051
+
2052
+ @app.command()
2053
+ @_errors
2054
+ def kill(off: Annotated[bool, typer.Option("--off", help="Turn the switch off.")] = False,
2055
+ vault: VaultOpt = None) -> None:
2056
+ """Kill switch: stop act-as-me and every reader server."""
2057
+ from keepfold import share
2058
+
2059
+ share.set_kill(_vault(vault), not off)
2060
+ typer.echo("kill switch off" if off else "kill switch on: act-as-me and the reader role "
2061
+ "are refused (`keepfold kill --off` to undo)")
2062
+
2063
+
2064
+ exclude_app = typer.Typer(no_args_is_help=True, help="Folders where Claude Code sessions get "
2065
+ "no priming and no Keepfold tools (a client's repo, cloned code).")
2066
+ app.add_typer(exclude_app, name="exclude")
2067
+
2068
+
2069
+ @exclude_app.command("add")
2070
+ @_errors
2071
+ def exclude_add(path: Path) -> None:
2072
+ """Exclude a folder and everything under it."""
2073
+ p = str(path.expanduser().resolve())
2074
+ taint.check_config("adding an excluded folder") # else excluded() says every one already is
2075
+ if f := taint.excluded(p):
2076
+ typer.echo(f"already excluded (by {f})")
2077
+ return
2078
+ taint.write_config(lambda cfg: {"exclude": [*taint.exclude_list(cfg), p]})
2079
+ typer.echo(f"excluded {p} (new Claude Code sessions there: no priming, no Keepfold tools)")
2080
+
2081
+
2082
+ @exclude_app.command("remove")
2083
+ @_errors
2084
+ def exclude_remove(path: Path) -> None:
2085
+ """Stop excluding a folder (as listed by `keepfold exclude list`)."""
2086
+ p = path.expanduser().resolve()
2087
+
2088
+ def merge(cfg: dict) -> dict: # under the config lock
2089
+ folders = taint.exclude_list(cfg)
2090
+ keep = [f for f in folders if Path(f).expanduser().resolve() != p]
2091
+ if len(keep) == len(folders):
2092
+ raise VaultError("invalid_argument", f"{p} is not in the exclude list; see "
2093
+ "`keepfold exclude list`.")
2094
+ return {"exclude": keep}
2095
+ taint.write_config(merge)
2096
+ typer.echo(f"no longer excluded: {p}")
2097
+
2098
+
2099
+ @exclude_app.command("list")
2100
+ @_errors
2101
+ def exclude_list() -> None:
2102
+ """Print the excluded folders, one per line."""
2103
+ taint.check_config("`keepfold exclude list`") # an empty list would read as "none excluded"
2104
+ for f in taint.exclude_list():
2105
+ typer.echo(f)
2106
+
2107
+
2108
+ @app.command("access")
2109
+ @_errors
2110
+ def access_cmd(days: Annotated[int, typer.Option(help="How many days back to list.")] = 30,
2111
+ vault: VaultOpt = None) -> None:
2112
+ """List act-as-me reads (and an old vault's drafts) from the access log, oldest first."""
2113
+ from keepfold import share
2114
+
2115
+ since = (datetime.now() - timedelta(days=days)).date().isoformat()
2116
+ rows = share.access_rows(EventLog(_vault(vault)).iter_events(), since)
2117
+ for r in rows:
2118
+ ts = parse_ts(r["ts"])
2119
+ typer.echo(f"{r['day']} {ts.astimezone():%H:%M} {r['client'] or '-'} {r['access']} "
2120
+ f"{r['audience'] or '-'} {render.plain(r['task'] or '', 80)}")
2121
+ if not rows:
2122
+ typer.echo(f"no access in the last {days} days")
2123
+
2124
+
2125
+ # ---- semantic recall ------------------------------------------------
2126
+
2127
+
2128
+ def _dir_mb(d: Path) -> float:
2129
+ return sum(p.stat().st_size for p in d.rglob("*")
2130
+ if p.is_file() and not p.is_symlink()) / 1e6
2131
+
2132
+
2133
+ # Trying again restarts the unfinished file: huggingface_hub deletes a partial download (only
2134
+ # whole files are kept), so no message promises it continues where it stopped.
2135
+ _AGAIN = " Then try again: the download starts over."
2136
+ _DOWNLOAD_ERRORS = ( # (words in the error, in lower case; the plain sentence), first match wins
2137
+ (("no space left", "errno 28", "os error 112", "winerror 112", "not enough space"),
2138
+ "Your disk is full: the search model needs about 150 MB free. Free up some space, then "
2139
+ "try again."),
2140
+ (("407", "proxy"),
2141
+ "Your network's proxy refused the download from huggingface.co (it may need you to sign "
2142
+ "in first). Try a phone hotspot or another network." + _AGAIN),
2143
+ (("certificate", "ssl"),
2144
+ "Your network blocked huggingface.co (common on campus Wi-Fi). Try a phone hotspot or "
2145
+ "another network." + _AGAIN),
2146
+ (("timed out", "timeout"),
2147
+ "The download from huggingface.co took too long and stopped. Try a faster or steadier "
2148
+ "network." + _AGAIN),
2149
+ (("getaddrinfo", "name or service", "nodename", "11001", "resolve", "connect",
2150
+ "unreachable", "network"),
2151
+ "Could not reach huggingface.co. Check that you are online, or try another network."
2152
+ + _AGAIN),
2153
+ )
2154
+
2155
+
2156
+ def _download_error(e: BaseException, seen: list[str]) -> str:
2157
+ """One plain sentence for a failed model download. fastembed swallows the network error and
2158
+ raises a bare ValueError, so `seen` (its logged errors) is read along with the chain."""
2159
+ if isinstance(e, OSError) and (e.errno == 28 or getattr(e, "winerror", None) == 112):
2160
+ return _DOWNLOAD_ERRORS[0][1]
2161
+ parts, x = [*seen], e
2162
+ while x is not None and len(parts) < 20:
2163
+ parts.append(f"{type(x).__name__} {x}")
2164
+ x = x.__cause__ or x.__context__
2165
+ text = " ".join(parts).lower()
2166
+ for words, sentence in _DOWNLOAD_ERRORS:
2167
+ if any(w in text for w in words):
2168
+ return sentence
2169
+ return "The search model download stopped. Try again later or on another network." + _AGAIN
2170
+
2171
+
2172
+ def _log_download_error(e: BaseException, seen: list[str]) -> Path:
2173
+ """The full error, for whoever helps: ~/.keepfold/logs/model-download.log (never printed)."""
2174
+ import logging
2175
+
2176
+ path = Path.home() / ".keepfold" / "logs" / "model-download.log"
2177
+ path.parent.mkdir(parents=True, exist_ok=True)
2178
+ h = logging.FileHandler(path, encoding="utf-8")
2179
+ h.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
2180
+ log = logging.getLogger("keepfold.model_download")
2181
+ log.propagate = False
2182
+ log.addHandler(h)
2183
+ try:
2184
+ log.error("model download failed; fastembed said: %s", " | ".join(seen) or "-",
2185
+ exc_info=e)
2186
+ finally:
2187
+ log.removeHandler(h)
2188
+ h.close()
2189
+ return path
2190
+
2191
+
2192
+ def _download_setup() -> None:
2193
+ """For this download only: the OS certificate store (campus TLS inspection) and the system
2194
+ proxy for hf_xet, which reads only the env."""
2195
+ try:
2196
+ import truststore
2197
+ truststore.inject_into_ssl()
2198
+ except Exception: # noqa: BLE001 (certifi's certificates still work off campus)
2199
+ pass
2200
+ os.environ.update(proxy_env())
2201
+ # unless this is set, huggingface_hub fetches its list of AI agents from huggingface.co and
2202
+ # adds the agent it detects and the torch version to its User-Agent (read at its import,
2203
+ # which comes after this)
2204
+ os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
2205
+
2206
+
2207
+ @model_app.command("download")
2208
+ @_errors
2209
+ def model_download(vault: VaultOpt = None, voice: Annotated[bool, typer.Option(
2210
+ "--voice", help="Instead: install faster-whisper and download the local speech model "
2211
+ "for voice memos (about 150 MB).")] = False) -> None:
2212
+ """Download the embedding and rerank models once, then build the vault's vector cache."""
2213
+ from keepfold import semantic
2214
+
2215
+ if voice:
2216
+ from keepfold import voice_memos
2217
+ try:
2218
+ _download_setup()
2219
+ voice_memos.install(typer.echo)
2220
+ except Exception as e: # noqa: BLE001 (a plain sentence, never a traceback)
2221
+ typer.echo(f"The speech model install stopped ({e}). Try again later or on "
2222
+ "another network.", err=True)
2223
+ raise typer.Exit(1) from None
2224
+ typer.echo(f"speech model ready in {semantic.models_dir()}")
2225
+ return
2226
+
2227
+ d = semantic.models_dir()
2228
+ seen: list[str] = []
2229
+ try:
2230
+ from loguru import logger # fastembed's logger, where its download errors go
2231
+ sink = logger.add(lambda m: seen.append(m.record["message"]), level="ERROR")
2232
+ except Exception: # noqa: BLE001
2233
+ logger = sink = None
2234
+ try:
2235
+ _download_setup()
2236
+ (d / doctor_mod.MODEL_READY).unlink(missing_ok=True) # back only once this run finishes
2237
+ typer.echo(f"model {semantic.MODEL}: downloading if missing into {d} ...")
2238
+ embed = semantic.load_embedder(download=True)
2239
+ typer.echo(f"reranker {semantic.RERANK_MODEL}: downloading if missing ...")
2240
+ semantic.load_reranker(download=True)
2241
+ (d / doctor_mod.MODEL_READY).write_text("downloaded\n", encoding="utf-8")
2242
+ except Exception as e: # noqa: BLE001 (a plain sentence, never a traceback)
2243
+ sentence = _download_error(e, seen)
2244
+ try:
2245
+ log = _log_download_error(e, seen)
2246
+ sentence += f" Details are in the log: {log}"
2247
+ except OSError: # a full disk may refuse the log too
2248
+ pass
2249
+ typer.echo(sentence, err=True)
2250
+ raise typer.Exit(1) from None
2251
+ finally:
2252
+ if sink is not None:
2253
+ logger.remove(sink)
2254
+ typer.echo(f"model ready: {_dir_mb(d):.0f} MB in {d}")
2255
+ try:
2256
+ v = _vault(vault)
2257
+ except VaultError as e:
2258
+ typer.echo(f"no vault indexed: {e}")
2259
+ return
2260
+ _build(v, embed)
2261
+
2262
+
2263
+ def _build(v: Vault, embed) -> None:
2264
+ from keepfold import semantic
2265
+ from keepfold.index import Index
2266
+
2267
+ t = time.perf_counter()
2268
+ shown = [t]
2269
+
2270
+ def progress(done: int, total: int) -> None:
2271
+ if time.perf_counter() - shown[0] >= 30 or done == total:
2272
+ shown[0] = time.perf_counter()
2273
+ typer.echo(f" {done}/{total} chunks, {time.perf_counter() - t:.0f}s")
2274
+
2275
+ ids, _, start, _ = semantic.vectors(Index(v, Catalog.load(v)), embed,
2276
+ len(embed(["keepfold"])[0]), save_every=60,
2277
+ progress=progress)
2278
+ typer.echo(f"indexed {len(ids)} pages, {len(start)} chunks in "
2279
+ f"{time.perf_counter() - t:.1f}s -> {v.root / semantic.CACHE}")
2280
+
2281
+
2282
+ @model_app.command("build")
2283
+ @_errors
2284
+ def model_build(vault: VaultOpt = None) -> None:
2285
+ """Build every chunk of the vault's vector cache (a recall builds only a second's worth).
2286
+ Saves each minute; run it again to resume. Never downloads."""
2287
+ from keepfold import semantic
2288
+
2289
+ semantic.ARENA = True # a short-lived bulk build: the arena's speed, its memory ends with us
2290
+ embed = semantic.load_embedder()
2291
+ if embed is None:
2292
+ raise VaultError("invalid_argument", semantic.NOT_SET_UP)
2293
+ _build(_vault(vault), embed)
2294
+
2295
+
2296
+ @model_app.command("status")
2297
+ @_errors
2298
+ def model_status(vault: VaultOpt = None) -> None:
2299
+ """Show whether the model is downloaded and the vault's vector cache size."""
2300
+ from keepfold import semantic
2301
+
2302
+ d = semantic.models_dir()
2303
+ if semantic.load_embedder() is None:
2304
+ typer.echo(f"model {semantic.MODEL}: not downloaded; run `keepfold model download`")
2305
+ else:
2306
+ typer.echo(f"model {semantic.MODEL}: ready, {_dir_mb(d):.0f} MB in {d}")
2307
+ on = semantic.rerank_on()
2308
+ typer.echo(f"reranker {semantic.RERANK_MODEL}: "
2309
+ + ("ready" if semantic.load_reranker(config=False) else "not downloaded")
2310
+ + ("" if on else " (off: rerank: false in ~/.keepfold/config.yaml)"))
2311
+ try:
2312
+ cache = _vault(vault).root / semantic.CACHE
2313
+ except VaultError:
2314
+ return
2315
+ typer.echo(f"vectors: {cache} ({cache.stat().st_size / 1e6:.1f} MB)" if cache.exists()
2316
+ else "vectors: not built yet (built on the first recall)")
2317
+
2318
+
2319
+ @app.command("recall")
2320
+ @_errors
2321
+ def recall_cmd(query: str,
2322
+ limit: Annotated[int, typer.Option(help="Show at most this many hits.")] = 8,
2323
+ hops: Annotated[int, typer.Option(
2324
+ help="Also follow links up to this many steps from each hit (0-2).")] = 1,
2325
+ vault: VaultOpt = None,
2326
+ explain: bool = typer.Option(False, help="Print each hit's score parts."),
2327
+ show_misses: bool = typer.Option(
2328
+ False, help="Also list the next 5 pages that missed the cut, and why.")) -> None:
2329
+ """Pages similar in meaning or by keyword, plus their linked pages. Never logs a recall."""
2330
+ from keepfold import harvest, semantic
2331
+ from keepfold.index import Index
2332
+
2333
+ v = _vault(vault)
2334
+ idx = Index(v, Catalog.load(v))
2335
+ ex = {} if explain or show_misses else None
2336
+ hits, notice = semantic.search(idx, query, limit, hops,
2337
+ quiet=harvest.quiet(EventLog(v).iter_events()), explain=ex)
2338
+ if notice:
2339
+ typer.echo(notice, err=True)
2340
+ parts, misses = semantic.explained(idx, ex, hits, 5 if show_misses else 0) if ex is not None \
2341
+ else ([], [])
2342
+ for k, h in enumerate(hits):
2343
+ typer.echo(render.term(f"{h['score']:.3f} {h['match']:<7} {h['id']} — {h['title']}"
2344
+ + (f" (via {h['via']})" if "via" in h else "")))
2345
+ if explain:
2346
+ typer.echo(" " + _parts(parts[k]))
2347
+ if not hits:
2348
+ typer.echo("no hits")
2349
+ if show_misses:
2350
+ typer.echo("missed:" if misses else "missed: none")
2351
+ for p in misses:
2352
+ typer.echo(f"{p['score']:.3f} {p['id']}: {p['reason']}\n " + _parts(p))
2353
+
2354
+
2355
+ @app.command("ask")
2356
+ @_errors
2357
+ def ask_cmd(question: str, vault: VaultOpt = None,
2358
+ private: bool = typer.Option(False, "--private", help=(
2359
+ "Also read private notes and private browsing. The answer and its sources "
2360
+ "print here, so never use it where an AI app reads this terminal."))) -> None:
2361
+ """Answer a question from your notes, saved AI chats and browsing with the local model
2362
+ only (Ollama or LM Studio); never a cloud model. Prints the cited sources. Private notes
2363
+ and private browsing only with --private: a terminal an AI app runs must never print them."""
2364
+ from keepfold import access, ask
2365
+
2366
+ if private and not access.may_see("terminal", access.Audience.LOCAL, "note",
2367
+ private_flag=True, tty=_tty()):
2368
+ typer.echo("Refused: private answers print only in a real terminal, never in one an AI "
2369
+ "app reads (stdin and stdout must both be a terminal). Run `keepfold ask "
2370
+ "--private` yourself in a terminal window, or ask without --private.",
2371
+ err=True)
2372
+ raise typer.Exit(1)
2373
+ try:
2374
+ out = ask.ask(_vault(vault), question, private=private)
2375
+ except ValueError as e: # localllm refuses a cloud model or a non-loopback url in config
2376
+ typer.echo(f"{e}. Fix localllm in ~/.keepfold/config.yaml: it must name a model on this "
2377
+ "computer.", err=True)
2378
+ raise typer.Exit(1) from None
2379
+ if "error" in out:
2380
+ typer.echo(out["message"], err=True)
2381
+ raise typer.Exit(1)
2382
+ typer.echo(render.term(out["answer"]))
2383
+ for s in out["sources"]:
2384
+ typer.echo(render.term(f"[{s['n']}] {s['path']}"))
2385
+ typer.echo(f"answered by {out['model']}")
2386
+
2387
+
2388
+ def _tty() -> bool:
2389
+ """stdin and stdout are both a real terminal (E3: a pipe or an AI app's runner is not; nor
2390
+ is NUL, which Windows calls a tty, so stdin must also be a console)."""
2391
+ try:
2392
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
2393
+ return False
2394
+ if os.name != "nt":
2395
+ return True
2396
+ import ctypes
2397
+ import msvcrt
2398
+ return bool(ctypes.windll.kernel32.GetConsoleMode(
2399
+ msvcrt.get_osfhandle(sys.stdin.fileno()), ctypes.byref(ctypes.c_ulong())))
2400
+ except (AttributeError, ValueError, OSError): # no stream, or a closed one
2401
+ return False
2402
+
2403
+
2404
+ def _parts(p: dict) -> str:
2405
+ """One line of `semantic.explained` parts for `recall --explain`."""
2406
+ from keepfold import duplicates # imported chat text is untrusted: no control chars, links
2407
+ out = [f"cos {p['cos']:.3f}" if p["cos"] is not None else "cos -",
2408
+ f"kw {p['kw']:.3f}"]
2409
+ if p["cover"] is not None:
2410
+ out.append(f"cover {p['cover']:.2f}")
2411
+ if p["weight"] != 1.0:
2412
+ out.append(f"weight {p['weight']:.3g} ("
2413
+ + " ".join(f"{k} {v:g}" for k, v in p["factors"].items()) + ")")
2414
+ if "rerank" in p:
2415
+ out.append(f"rerank {p['rerank']:.3f}")
2416
+ if p["chunk"]:
2417
+ out.append(f"chunk@{p['at']} \"{duplicates.safe(p['chunk'], 80)}\"")
2418
+ return " ".join(out)
2419
+
2420
+
2421
+ chat_app = typer.Typer(help="Keepfold's Chat, from the command line.")
2422
+ app.add_typer(chat_app, name="chat")
2423
+
2424
+
2425
+ @chat_app.command("eval")
2426
+ def chat_eval_cmd(
2427
+ out: Annotated[Path | None, typer.Option(
2428
+ "--out", help="Also write the full report (answers, served passages) as JSON.")]
2429
+ = None,
2430
+ keep: Annotated[Path | None, typer.Option(
2431
+ "--keep", help="Build the made-up vault in this new folder and leave it there.")]
2432
+ = None,
2433
+ no_model: Annotated[bool, typer.Option(
2434
+ "--no-model", help="Run only the questions Keepfold answers with no model.")] = False,
2435
+ served: Annotated[bool, typer.Option(
2436
+ "--served", help="List the passages each answer was given.")] = False,
2437
+ runs: Annotated[int, typer.Option(
2438
+ "--runs", min=1, help="Ask each model question this many times; a question passes "
2439
+ "pass^N only if every run passed.")] = 1) -> None:
2440
+ """Chat's offline test: 60 questions on a made-up vault in a temp folder, scored in code.
2441
+ Questions that need a model run only when a 2B local model is already loaded; nothing is
2442
+ loaded or downloaded, and your vault, settings and browsing are not used."""
2443
+ from keepfold import chat_eval
2444
+
2445
+ if keep is not None and keep.exists():
2446
+ typer.echo(f"error: {keep} already exists; --keep needs a new folder.", err=True)
2447
+ raise typer.Exit(1)
2448
+ try:
2449
+ r = chat_eval.run(use_model=not no_model, keep=keep, runs=runs,
2450
+ progress=lambda d, n, qid: typer.echo(f"{d}/{n} {qid}", err=True))
2451
+ except RuntimeError as e:
2452
+ typer.echo(f"error: {e}", err=True)
2453
+ raise typer.Exit(1) from None
2454
+ typer.echo(render.term(chat_eval.summary(r, served)))
2455
+ if out is not None:
2456
+ out.write_text(json.dumps(r, ensure_ascii=False, indent=1), encoding="utf-8")
2457
+ typer.echo(f"Report written to {out}")
2458
+
2459
+
2460
+ @eval_app.callback(invoke_without_command=True)
2461
+ def eval_main(ctx: typer.Context, k: int = 8, vault: VaultOpt = None) -> None:
2462
+ """Measure ranking on logged usage; bare `keepfold eval` runs `all`."""
2463
+ if ctx.invoked_subcommand is None:
2464
+ eval_all(k, vault)
2465
+ elif vault is not None or k != 8: # the subcommand has its own options; never drop them
2466
+ raise typer.BadParameter("put --k and --vault after the subcommand, e.g. "
2467
+ "`keepfold eval recall --vault X`.")
2468
+
2469
+
2470
+ @eval_app.command("recall")
2471
+ @_errors
2472
+ def eval_recall(k: Annotated[int, typer.Option(help="Score the top k hits.")] = 8,
2473
+ vault: VaultOpt = None) -> None:
2474
+ """Replay logged recall queries (relevant = pages opened after them) through each ranking
2475
+ variant: recall@k and MRR."""
2476
+ from keepfold import recall_log, semantic
2477
+ from keepfold.index import Index
2478
+
2479
+ v = _vault(vault)
2480
+ pairs = recall_log.eval_set(recall_log.rows(v))
2481
+ embed, ce = semantic.load_embedder(), semantic.load_reranker(config=False)
2482
+ typer.echo(f"queries: {len(pairs)}" + (
2483
+ f" (too few to trust; need about {recall_log.MIN_TRUST})"
2484
+ if len(pairs) < recall_log.MIN_TRUST else ""))
2485
+ if not embed:
2486
+ typer.echo(semantic.NOT_SET_UP + " (variants run keyword-only)", err=True)
2487
+ typer.echo(f"{'variant':<12} {'recall@' + str(k):>9} {'MRR':>6}")
2488
+ for name, m in recall_log.evaluate(Index(v, Catalog.load(v)), pairs, embed, ce, k).items():
2489
+ typer.echo(f"{name:<12} " + (f"{m[0]:>9.3f} {m[1]:>6.3f}" if m
2490
+ else "skipped: reranker not downloaded"))
2491
+
2492
+
2493
+ @eval_app.command("learning")
2494
+ @_errors
2495
+ def eval_learning(since: Annotated[str | None, typer.Option(
2496
+ help="Only items graded on or after this local day (YYYY-MM-DD).")] = None,
2497
+ json_out: Annotated[bool, typer.Option("--json", help="Print JSON.")] = False,
2498
+ vault: VaultOpt = None) -> None:
2499
+ """Read-only: how well the logged predicted_p forecasts graded items (pass = correct at
2500
+ hints <= 1): Brier, skill, log loss, reliability bins, split by mode, grader, source,
2501
+ item type and confidence."""
2502
+ from keepfold import learning_eval
2503
+
2504
+ if since is not None and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", since):
2505
+ raise VaultError("invalid_argument", "--since must be a day like 2026-11-01.")
2506
+ v = _vault(vault)
2507
+ r = learning_eval.report(EventLog(v).iter_events(), levels.problem_concepts(v), since)
2508
+ typer.echo(json.dumps(r, indent=1) if json_out else learning_eval.text(r))
2509
+
2510
+
2511
+ @eval_app.command("harvest-facts")
2512
+ @_errors
2513
+ def eval_harvest_facts(file: Annotated[Path | None, typer.Option(
2514
+ "--file", help="A labelled eval file (default: the repo's "
2515
+ "tests/fixtures/harvest_eval.json).")] = None) -> None:
2516
+ """R6d: run the no-model fact finder (Tier 0) over labelled chat turns: precision,
2517
+ recall, hypothetical false positives and polarity flips against their targets. Reads no
2518
+ vault and writes nothing."""
2519
+ from keepfold import fact_harvest as fh
2520
+
2521
+ p = file or Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "harvest_eval.json"
2522
+ try:
2523
+ items = json.loads(p.read_text(encoding="utf-8"))["items"]
2524
+ except (OSError, ValueError, KeyError, TypeError) as e:
2525
+ raise VaultError("invalid_argument", f"Cannot read the eval file {p}: {e}") from None
2526
+ r = fh.evaluate(items)
2527
+ t = fh.TARGETS
2528
+ typer.echo(f"turns: {r['turns']} facts extracted: {r['extracted']} right: {r['right']}")
2529
+ typer.echo(f"precision: {r['precision']:.1%} (target >= {t['precision']:.0%})")
2530
+ typer.echo(f"recall: {r['recall']:.1%} ({r['found']} of {r['expected']} expected facts)")
2531
+ typer.echo(f"hypothetical false positives: {r['hypothetical_fp']:.1%} ({r['unreal_hit']} of "
2532
+ f"{r['unreal']} hypothetical or roleplay turns; target <= "
2533
+ f"{t['hypothetical_fp']:.0%})")
2534
+ typer.echo(f"reactions saved as facts: {r['reaction_fp']:.1%} ({r['reaction_hit']} of "
2535
+ f"{r['reaction']} reactions to the chat's own output; target <= "
2536
+ f"{t['reaction_fp']:.0%})")
2537
+ typer.echo(f"polarity flips: {r['flips']} (target {t['flips']})")
2538
+ typer.echo(f"promotion facts not held for the Review: {r['held_missed']}")
2539
+ typer.echo("targets: met" if fh.meets(r) else "targets: NOT met")
2540
+
2541
+
2542
+ @eval_app.command("agent")
2543
+ @_errors
2544
+ def eval_agent(model: Annotated[bool, typer.Option(
2545
+ "--model", help="Also ask the local model you already loaded (Layer B, "
2546
+ "three replies per case); never loads one.")] = False,
2547
+ json_out: Annotated[bool, typer.Option("--json", help="Print JSON.")] = False
2548
+ ) -> None:
2549
+ """R12: does each AI app get the right lines about you and none it must not? Builds ten
2550
+ made-up vaults and checks what each app is served (Layer A, no model); --model also
2551
+ checks a loaded local model's replies. Reads no vault of yours."""
2552
+ from keepfold import agent_eval
2553
+
2554
+ r = agent_eval.run(model=model)
2555
+ typer.echo(json.dumps(r, indent=1) if json_out else agent_eval.summary(r))
2556
+ if r["a_fail"]:
2557
+ raise typer.Exit(1)
2558
+
2559
+
2560
+ @eval_app.command("all")
2561
+ @_errors
2562
+ def eval_all(k: Annotated[int, typer.Option(help="Score the top k recall hits.")] = 8,
2563
+ vault: VaultOpt = None) -> None:
2564
+ """Recall and learning evals in one report; appends its numbers (never queries or text) to
2565
+ .keepfold/eval-history.jsonl and prints deltas against an earlier run from another commit on
2566
+ the same day and index. Run it before and after a tuning change."""
2567
+ from keepfold import eval_history, learning_eval, recall_log, semantic
2568
+ from keepfold.index import Index
2569
+
2570
+ v = _vault(vault)
2571
+ idx = Index(v, Catalog.load(v))
2572
+ pairs = recall_log.eval_set(recall_log.rows(v))
2573
+ embed, ce = semantic.load_embedder(), semantic.load_reranker(config=False)
2574
+ if pairs and not embed:
2575
+ typer.echo(semantic.NOT_SET_UP + " (recall variants run keyword-only)", err=True)
2576
+ recall = recall_log.evaluate(idx, pairs, embed, ce, k) if pairs else {}
2577
+ learning = learning_eval.report(EventLog(v).iter_events(), levels.problem_concepts(v))
2578
+ run = eval_history.rows(recall, len(pairs), k, learning, date=local_day(datetime.now(UTC)),
2579
+ sha=eval_history.git_sha(),
2580
+ index=eval_history.fingerprint(idx, embed is not None))
2581
+ typer.echo(eval_history.text(run, eval_history.before(eval_history.read(v), run)))
2582
+ if run:
2583
+ eval_history.append(v, run)
2584
+
2585
+
2586
+ def _topics(vault: Path | None, embed: bool = False):
2587
+ """(vault, index, embedder or None) for the topics commands; `embed` requires the model."""
2588
+ from keepfold import semantic
2589
+ from keepfold.index import Index
2590
+
2591
+ model = semantic.load_embedder() if embed else None
2592
+ if embed and model is None:
2593
+ raise VaultError("invalid_argument", semantic.NOT_SET_UP)
2594
+ v = _vault(vault)
2595
+ return v, Index(v, Catalog.load(v)), model
2596
+
2597
+
2598
+ DryRun = Annotated[bool, typer.Option("--dry-run", help="Report what would change; write "
2599
+ "nothing.")]
2600
+
2601
+
2602
+ @topics_app.command("status")
2603
+ @_errors
2604
+ def topics_status(vault: VaultOpt = None) -> None:
2605
+ """Counts: hubs per depth, hubs over the split size, unfiled pages."""
2606
+ from keepfold import topics
2607
+
2608
+ _, idx, _ = _topics(vault)
2609
+ s = topics.status(idx, topics.tree(idx))
2610
+ typer.echo(f"hubs: {s['hubs']} (" + ", ".join(f"depth {d}: {n}" for d, n in
2611
+ s["by_depth"].items()) + ")")
2612
+ typer.echo(f"hubs over {topics.SPLIT_N} direct pages: {s['over_split']}")
2613
+ typer.echo(f"pages (resources and notes): {s['pages']}; unfiled: {s['unfiled']}")
2614
+
2615
+
2616
+ @topics_app.command("attach")
2617
+ @_errors
2618
+ def topics_attach(dry_run: DryRun = False,
2619
+ margin: Annotated[float | None, typer.Option(
2620
+ help="How far the best hub must beat the next one (default 0.02).")]
2621
+ = None,
2622
+ floor: Annotated[float | None, typer.Option(
2623
+ help="The lowest similarity that still files a page (default 0.80).")]
2624
+ = None,
2625
+ limit: Annotated[int | None, typer.Option(
2626
+ help="Try a seeded sample of N unfiled pages.")] = None,
2627
+ vault: VaultOpt = None) -> None:
2628
+ """File unfiled resources and notes under their nearest topic hub (backing off to the
2629
+ parent when the top hubs are close); the rest stay unfiled."""
2630
+ from keepfold import topics
2631
+
2632
+ margin = topics.MARGIN if margin is None else margin # None default: topics imports numpy
2633
+ floor = topics.FLOOR if floor is None else floor
2634
+ v, idx, embed = _topics(vault, embed=True)
2635
+ n, results = topics.attach_unfiled(idx, embed, margin, floor, limit)
2636
+ tree = topics.tree(idx)
2637
+ done = [(p, a) for p, a in results if a.hub]
2638
+ by = Counter(min(tree.depth(a.hub), 3) for _, a in done)
2639
+ typer.echo(f"attached {len(done)} of {n} (area {by[1]}, subtopic {by[2]}, leaf {by[3]}); "
2640
+ f"left unfiled {n - len(done)}")
2641
+ for p, a in done[:max(10, limit or 0)]:
2642
+ typer.echo(f" {p} -> {a.hub} ({a.score:.3f}): {render.term(idx._notes[p]['title'])} -> "
2643
+ f"{render.term(tree.title[a.hub])}")
2644
+ if not dry_run:
2645
+ for p, a in done:
2646
+ topics.place(v, p, [a.hub])
2647
+ typer.echo("dry run: nothing written" if dry_run else "written")
2648
+
2649
+
2650
+ @topics_app.command("build")
2651
+ @_errors
2652
+ def topics_build(dry_run: DryRun = False, vault: VaultOpt = None) -> None:
2653
+ """Regenerate the generated hub sections (Part of line, Sub-topics, Conversations, Areas)
2654
+ and the month pages' Links in place; hand-written text is never rewritten."""
2655
+ from keepfold import topics
2656
+
2657
+ v, idx, _ = _topics(vault)
2658
+ c = topics.build(v, idx, dry_run)
2659
+ typer.echo(f"{'would change' if dry_run else 'changed'}: hubs {c['hubs']}, month pages "
2660
+ f"{c['months']}; unchanged {c['unchanged']}"
2661
+ + (f"; skipped {c['unsafe']} (hand-written text would change)"
2662
+ if c["unsafe"] else ""))
2663
+
2664
+
2665
+ @topics_app.command("split")
2666
+ @_errors
2667
+ def topics_split(hub: Annotated[str | None, typer.Argument(help="The hub to split.")] = None,
2668
+ propose: Annotated[bool, typer.Option("--propose", help="Write and print the "
2669
+ "proposal.")] = False,
2670
+ apply: Annotated[bool, typer.Option("--apply", help="Apply the proposal "
2671
+ "(needs --auto-names).")] = False,
2672
+ auto_names: Annotated[bool, typer.Option(
2673
+ "--auto-names", help="Name the children from their title terms and mark "
2674
+ "them names: provisional (no chat needed).")] = False,
2675
+ vault: VaultOpt = None) -> None:
2676
+ """Split proposals for big hubs: no HUB lists the candidates; --propose writes and prints
2677
+ one; --apply --auto-names applies it offline."""
2678
+ from keepfold import topics
2679
+
2680
+ if hub is None:
2681
+ _, idx, _ = _topics(vault)
2682
+ rows = topics.split_candidates(idx, topics.tree(idx))
2683
+ typer.echo(f"split candidates (over {topics.SPLIT_N} direct pages): {len(rows)}")
2684
+ for h, n in rows:
2685
+ typer.echo(f" {h} ({n} pages)")
2686
+ return
2687
+ if propose == apply:
2688
+ raise VaultError("invalid_argument", "Pass --propose or --apply --auto-names.")
2689
+ if apply and not auto_names:
2690
+ raise VaultError("invalid_argument", "--apply needs --auto-names; to name the children "
2691
+ "yourself, use keepfold_reflect (pack, then action=split) in a chat.")
2692
+ v, idx, embed = _topics(vault, embed=True)
2693
+ t = topics.tree(idx)
2694
+ prop = topics.propose_split(idx, t, topics.head_stack(idx, embed), hub)
2695
+ if prop is None:
2696
+ raise VaultError("invalid_argument", f"No split proposal for '{hub}': not a hub, too "
2697
+ f"deep, under {3 * topics.MIN_CHILD} pages, or no clear clusters.")
2698
+ if propose:
2699
+ topics.write_proposal(v, prop)
2700
+ typer.echo(f"{hub}: k={prop['k']} silhouette {prop['silhouette']:.3f} hash "
2701
+ f"{prop['hash']}" + (f" ({prop['note']})" if prop.get("note") else ""))
2702
+ for k, c in enumerate(prop["clusters"], 1):
2703
+ typer.echo(f" cluster {k} ({len(c['members'])} pages): {', '.join(c['terms'])}")
2704
+ for s in c["sample_titles"]:
2705
+ typer.echo(f" - {s}")
2706
+ typer.echo(f" stay on the parent: {len(prop['stay'])}")
2707
+ typer.echo(f"written {topics.proposal_path(v, hub)}")
2708
+ return
2709
+ res = topics.apply_split(v, idx, embed, hub, prop["hash"], topics.auto_children(prop),
2710
+ provisional=True)
2711
+ for c in res["children"]:
2712
+ typer.echo(f" {c['id']} ({c['n']} pages): {render.term(c['title'])}")
2713
+ typer.echo(f"created {len(res['children'])} provisional sub-topics; {res['stayed']} pages "
2714
+ "stay on the parent")
2715
+
2716
+
2717
+ @topics_app.command("eval")
2718
+ @_errors
2719
+ def topics_eval(margins: Annotated[str, typer.Option(
2720
+ help="Comma-separated margins to try.")] = "0.01,0.02,0.03",
2721
+ floor: Annotated[float | None, typer.Option(
2722
+ help="The similarity floor (default 0.80).")] = None,
2723
+ splits: Annotated[bool, typer.Option(
2724
+ "--splits", help="Score the hand-made splits against automatic ones "
2725
+ "instead.")] = False,
2726
+ vault: VaultOpt = None) -> None:
2727
+ """Leave-one-out on the pages that have hubs: attached share, precision (the page's hub or
2728
+ an ancestor) and exact share per margin. --splits: silhouette, browse cost, cohesion and ARI
2729
+ of the hand-made splits against automatic ones. Read-only."""
2730
+ from keepfold import topics
2731
+
2732
+ floor = topics.FLOOR if floor is None else floor
2733
+ try:
2734
+ ms = [float(m) for m in margins.split(",") if m.strip()]
2735
+ except ValueError:
2736
+ raise VaultError("invalid_argument", "margins must be numbers like 0.01,0.02.") from None
2737
+ _, idx, embed = _topics(vault, embed=True)
2738
+ if splits:
2739
+ r = topics.evaluate_splits(idx, topics.tree(idx), topics.head_stack(idx, embed))
2740
+ typer.echo(f"split hubs: {r['hubs']}; compared with an automatic split: {r['compared']}")
2741
+ typer.echo(f"manual silhouette: p25 {r['manual_sil_p25']:.3f} (SIL_MIN candidate), "
2742
+ f"median {r['manual_sil_median']:.3f}; SIL_MIN now {topics.SIL_MIN}")
2743
+ typer.echo(f"browse reduction (median): manual {r['manual_browse']:.3f}, automatic "
2744
+ f"{r['auto_browse']:.3f}, ratio {r['browse_ratio']:.2f} (gate >= 0.80)")
2745
+ typer.echo(f"cohesion (median): manual {r['manual_cohesion']:.3f}, automatic "
2746
+ f"{r['auto_cohesion']:.3f}; ARI median {r['ari']:.3f}")
2747
+ return
2748
+ rows = topics.evaluate(idx, topics.tree(idx), topics.head_stack(idx, embed), ms, floor)
2749
+ typer.echo(f"pages with hubs: {rows[0]['pages'] if rows else 0}; floor {floor}")
2750
+ typer.echo(f"{'margin':>7} {'attached':>9} {'precision':>10} {'exact':>6} depth 1/2/3+")
2751
+ for r in rows:
2752
+ d: Counter = Counter()
2753
+ for k, x in r["depth"].items():
2754
+ d[min(k, 3)] += x
2755
+ typer.echo(f"{r['margin']:>7.3f} {r['attached']:>9.3f} {r['precision']:>10.3f} "
2756
+ f"{r['exact']:>6.3f} {d[1]}/{d[2]}/{d[3]}")
2757
+
2758
+
2759
+ def _share(x) -> str:
2760
+ return "-" if x is None else f"{x:.2f}"
2761
+
2762
+
2763
+ harvest_app = typer.Typer(no_args_is_help=True, help="The imported-chat harvest.")
2764
+ app.add_typer(harvest_app, name="harvest")
2765
+
2766
+
2767
+ @harvest_app.command("status")
2768
+ @eval_app.command("harvest", hidden=True) # now `harvest status`
2769
+ @_errors
2770
+ def harvest_status(since: Annotated[str | None, typer.Option(
2771
+ help="Only harvests on or after this local day (YYYY-MM-DD).")] = None,
2772
+ json_out: Annotated[bool, typer.Option("--json", help="Print JSON.")] = False,
2773
+ vault: VaultOpt = None) -> None:
2774
+ """Read-only: how the chat harvest is going: placement coverage,
2775
+ bridged hubs, the yes-rate, the waiting backlog, the 7-day keep share, the empty rate per
2776
+ app, and each run's pages with its `keepfold undo` command."""
2777
+ from keepfold import duplicates, harvest, semantic, topics
2778
+ from keepfold.index import Index
2779
+
2780
+ if since is not None and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", since):
2781
+ raise VaultError("invalid_argument", "--since must be a day like 2026-11-01.")
2782
+ v = _vault(vault)
2783
+ idx = Index(v, Catalog.load(v))
2784
+ embed = semantic.load_embedder()
2785
+ r = harvest.status(idx, topics.tree(idx), topics.head_stack(idx, embed) if embed else None,
2786
+ EventLog(v).iter_events(), local_day(datetime.now(UTC)), since)
2787
+ if json_out:
2788
+ typer.echo(json.dumps(r, indent=1))
2789
+ return
2790
+ if not embed:
2791
+ typer.echo(semantic.NOT_SET_UP + " (no placement coverage)", err=True)
2792
+ p, y, k = r["placement"], r["yes_rate"], r["keep"]
2793
+ typer.echo(f"chats: {r['chats']}, harvested {r['harvested']}")
2794
+ if p:
2795
+ typer.echo(f"placement coverage: {p['coverage']:.2f} ({p['harvested']} of {p['chats']} "
2796
+ f"chats in {p['hubs']} hubs; target 0.40)")
2797
+ typer.echo(f"bridged hubs: {r['bridged_hubs']} of {r['hubs']}"
2798
+ + (f"; placement hubs {p['bridged']} of {p['hubs']} (target 30)" if p else ""))
2799
+ typer.echo(f"yes-rate: {_share(y['rate'])} ({y['yes']} yes, {y['no']} no; guard 0.50 "
2800
+ f"over 20+)")
2801
+ typer.echo(f"waiting about-me lines: {r['waiting']} (guard 12 or fewer)")
2802
+ typer.echo(f"7-day keep share: {_share(k['share'])} ({k['kept']} of {k['pages']} pages; "
2803
+ "guard 0.85)")
2804
+ for app_, e in r["empty"].items(): # app names and page ids are page/event text: escape
2805
+ typer.echo(f"empty rate {duplicates.safe(app_, 40)}: {e['rate']:.2f} ({e['empty']} of "
2806
+ f"{e['chats']} chats)")
2807
+ for run in r["runs"]:
2808
+ pages = ", ".join(duplicates.safe(p, 80) for p in run["pages"])
2809
+ typer.echo(f"run {run['day']} {run['session']}: {run['bundles']} bundles, "
2810
+ f"{run['chats']} chats, pages: {pages or 'none'}")
2811
+ typer.echo(f" undo: {run['undo']}")
2812
+
2813
+
2814
+ # ---- v6 agenda 7: portable context for other assistants ---------------------------
2815
+
2816
+ def _print_mcp_config(vault: Path | None) -> None:
2817
+ """The mcpServers JSON snippet for clients `setup` does not write (Cursor, Gemini CLI)."""
2818
+ from keepfold import clients
2819
+
2820
+ entry = clients.server_entry(clients.mcp_command(), _vault(vault).root.resolve())
2821
+ typer.echo(json.dumps({"mcpServers": {"keepfold": entry}}, indent=2))
2822
+
2823
+
2824
+ export_app = typer.Typer(no_args_is_help=True, help="Snapshots for other assistants.")
2825
+ app.add_typer(export_app, name="export")
2826
+
2827
+
2828
+ @export_app.command("context")
2829
+ @_errors
2830
+ def export_context_cmd(out: Annotated[Path | None, typer.Argument(
2831
+ help="File to write (outside the vault and the Keepfold repo); "
2832
+ "else stdout.")] = None,
2833
+ mcp_config: Annotated[bool, typer.Option( # now setup --print-mcp-config
2834
+ "--mcp-config", hidden=True)] = False,
2835
+ vault: VaultOpt = None) -> None:
2836
+ """Your profile, preferences, contract rules and current goals as plain Markdown to paste
2837
+ into other assistants: confirmed lines only, at most 6,000 characters, a dated snapshot."""
2838
+ from keepfold import export_context as ec
2839
+
2840
+ _refuse_excluded("export")
2841
+ if mcp_config:
2842
+ return _print_mcp_config(vault)
2843
+ v = _vault(vault)
2844
+ target = ec.check_target(out, v) if out else None
2845
+ text, skipped = ec.build(v, list(EventLog(v).iter_events()), datetime.now(UTC))
2846
+ if target:
2847
+ target.write_text(text, encoding="utf-8")
2848
+ typer.echo(f"wrote {target} ({len(text)} characters)", err=True)
2849
+ else:
2850
+ typer.echo(text, nl=False)
2851
+ if skipped:
2852
+ typer.echo(f"{skipped} lines are not confirmed, so they were left out; confirm them in "
2853
+ "/keepfold reflect to export them.", err=True)
2854
+
2855
+
2856
+ # ---- the Keepfold app ----------------------------------------------
2857
+
2858
+ @app.command("app")
2859
+ def app_cmd(vault: VaultOpt = None,
2860
+ no_open: Annotated[bool, typer.Option("--no-open", help="Print the link only.")]
2861
+ = False,
2862
+ port: Annotated[int, typer.Option(
2863
+ help="Port on 127.0.0.1 (0: 47615 if free, else any free one).")] = 0,
2864
+ window: Annotated[bool, typer.Option(
2865
+ "--window", help="Its own window and a tray icon (Windows), as the Start menu's "
2866
+ "Keepfold opens it; runs until Quit in the tray.")] = False) -> None:
2867
+ """Open the Keepfold app in your browser: setup, AI apps, local model, browsing, vault.
2868
+ Runs on 127.0.0.1 only and stops after 30 minutes idle."""
2869
+ from keepfold.app import server
2870
+
2871
+ if window:
2872
+ from keepfold.app import desktop
2873
+ desktop.run(vault or taint._vault_root(), hidden=no_open, port=port, echo=typer.echo)
2874
+ return
2875
+ server.run(vault or taint._vault_root(), open_browser=not no_open, port=port,
2876
+ echo=typer.echo)
2877
+
2878
+
2879
+ # ---- browse brain: browsing, processed on this machine only ----
2880
+
2881
+ browse_app = typer.Typer(no_args_is_help=True, help="Your browser history as Keepfold pages, "
2882
+ "read and filtered on this machine only.")
2883
+ app.add_typer(browse_app, name="browse")
2884
+ llm_app = typer.Typer(no_args_is_help=True, help="The optional local LLM (loopback only).")
2885
+ app.add_typer(llm_app, name="llm")
2886
+ BrowserOpt = Annotated[str | None, typer.Option(
2887
+ help="chrome, edge, brave, comet or firefox.")]
2888
+ ProfileOpt = Annotated[str | None, typer.Option(
2889
+ help="A profile folder name, such as Default or 'Profile 1'.")]
2890
+
2891
+
2892
+ def _browse_sources(browser: str | None, profile: str | None) -> list:
2893
+ from keepfold.browse import sources
2894
+
2895
+ if browser is not None and browser.lower() not in sources.BROWSERS:
2896
+ raise VaultError("invalid_argument",
2897
+ f"--browser must be one of {', '.join(sources.BROWSERS)}.")
2898
+ from dataclasses import replace
2899
+
2900
+ from keepfold.browse.privacy import load_settings
2901
+
2902
+ # an explicit --browser wins; otherwise `browse.browsers` in config (default: every one).
2903
+ # A named --profile is read even when unticked (`browse.skip_profiles`), but only when the
2904
+ # name is that one profile: "Default" never also reads another browser's unticked Default
2905
+ s = load_settings()
2906
+ if browser:
2907
+ return sources.pick(sources.discover(), browser, profile)
2908
+ got = sources.pick(sources.chosen(s), None, profile)
2909
+ if profile and not got:
2910
+ named = sources.pick(sources.chosen(replace(s, skip_profiles=())), None, profile)
2911
+ got = named if len(named) == 1 else []
2912
+ return got
2913
+
2914
+
2915
+ def _local_llm(config: dict | None = None, background: bool = False):
2916
+ """The loopback runner, or None (no runner, or a bad localllm.url, said on stderr)."""
2917
+ try:
2918
+ from keepfold import localllm
2919
+ return localllm.find(config, background=background)
2920
+ except ImportError:
2921
+ return None
2922
+ except ValueError as e: # a non-loopback localllm.url is refused
2923
+ typer.echo(f"local LLM not used: {e}", err=True)
2924
+ return None
2925
+
2926
+
2927
+ NEXT_SCAN = ("next: `keepfold browse selftest` to see the import work on made-up data, then "
2928
+ "`keepfold browse import --dry-run`, then `keepfold browse import`")
2929
+ NO_BROWSERS = ("no browser history found (looked for Chrome, Edge, Brave and Comet under "
2930
+ "%LOCALAPPDATA% and Firefox under %APPDATA%; on macOS and Linux for Chrome, "
2931
+ "Edge, Brave and Firefox in their usual folders)")
2932
+ NO_MODEL = ("embedding model not downloaded: every page goes to the private page under "
2933
+ "\"Other\" sections, none under your topic hubs. To fix: keepfold model download")
2934
+
2935
+
2936
+ @browse_app.command("selftest")
2937
+ def browse_selftest() -> None:
2938
+ """The whole import on made-up history in a temp folder (Chrome, Comet, Firefox and a
2939
+ throwaway vault): never your vault or your browsers. Prints PASS/FAIL per check; exits 1
2940
+ on any failure."""
2941
+ from keepfold.browse import selftest
2942
+
2943
+ if not selftest.run(typer.echo):
2944
+ raise typer.Exit(1)
2945
+
2946
+
2947
+ @browse_app.command("scan")
2948
+ @_errors
2949
+ def browse_scan(browser: BrowserOpt = None, profile: ProfileOpt = None) -> None:
2950
+ """Dry run: per browser and profile, the visit and search counts, the date range, and how
2951
+ many visits the privacy filter would drop, keep private or keep. Counts only; never a
2952
+ title or URL; writes nothing."""
2953
+ from keepfold.browse import load_settings, sources
2954
+
2955
+ srcs = _browse_sources(browser, profile)
2956
+ s = load_settings()
2957
+ typer.echo(f"settings: not saved {', '.join(s.skip_categories) or 'none'}; hidden from "
2958
+ f"Claude {', '.join(s.hidden_from_claude) or 'none'}; {len(s.deny)} denied, "
2959
+ f"{len(s.allow)} allowed, {len(s.private)} private domains")
2960
+ typer.echo(f"Comet found: {'yes' if any(x.browser == 'comet' for x in srcs) else 'no'}")
2961
+ if not srcs:
2962
+ typer.echo(NO_BROWSERS)
2963
+ return
2964
+ rows = sources.scan(srcs, s)
2965
+ for r in rows:
2966
+ if "error" in r:
2967
+ typer.echo(f"{r['source']}: not read: {r['why']}")
2968
+ continue
2969
+ typer.echo(f"{r['source']}: {r['visits']} visits, {r['searches']} searches, "
2970
+ f"{r['first'] or '-'} to {r['last'] or '-'}; would drop {r['dropped']}, "
2971
+ f"keep private {r['private']}, keep {r['kept']} ({r['maybe']} unsure)")
2972
+ if any(r.get("maybe") for r in rows):
2973
+ typer.echo("unsure: a sensitive word only; kept private like the rest")
2974
+ days = [d for r in rows for d in (r.get("first"), r.get("last")) if d]
2975
+ typer.echo(f"date range: {min(days)} to {max(days)}" if days else "date range: no visits")
2976
+ typer.echo(NEXT_SCAN)
2977
+
2978
+
2979
+ @browse_app.command("import")
2980
+ @_errors
2981
+ def browse_import(since: Annotated[str | None, typer.Option(
2982
+ help="Rebuild the days from the Monday of this local day (YYYY-MM-DD) "
2983
+ "on, not just the days with new visits.")] = None,
2984
+ browser: BrowserOpt = None, profile: ProfileOpt = None,
2985
+ dry_run: Annotated[bool, typer.Option(
2986
+ "--dry-run", help="Do everything except writing; print counts only.")]
2987
+ = False,
2988
+ takeout: Annotated[Path | None, typer.Option(
2989
+ "--takeout", help="Also read a Google Takeout My Activity export (.zip "
2990
+ "or folder): Search, YouTube and Chrome, through the same privacy "
2991
+ "filter; rows on days your browsers already hold are skipped.")] = None,
2992
+ vault: VaultOpt = None) -> None:
2993
+ """Write or update the browse day pages, the index, interest journal lines and "New
2994
+ interest?" inbox lines. Idempotent: each day page is rebuilt from all of that day's visits
2995
+ (from the chosen browsers only, with --browser or --profile). Prints counts only.
2996
+ The public pages and journal lines need `browse.visible_to_claude: true`; by default only
2997
+ the private pages are written. Ctrl+C is safe: pages stay whole and the next run redoes
2998
+ the same days."""
2999
+ from keepfold import semantic
3000
+ from keepfold.browse import build, load_settings, sources
3001
+
3002
+ if since is not None and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", since):
3003
+ raise VaultError("invalid_argument", "--since must be a day like 2026-11-01.")
3004
+ t0 = time.perf_counter()
3005
+ v = _vault(vault)
3006
+ google = None
3007
+ if takeout is not None:
3008
+ from keepfold.browse import takeout as takeout_mod
3009
+
3010
+ google = takeout_mod.records(takeout)
3011
+ typer.echo(f"takeout: {len(google)} activity rows read"
3012
+ + (f"; {google.skipped} row{'s' * (google.skipped != 1)} skipped "
3013
+ "(unreadable date)" if google.skipped else ""))
3014
+ srcs = _browse_sources(browser, profile)
3015
+ if not srcs:
3016
+ typer.echo(NO_BROWSERS + "; only visits the old capture extension saved, if any, "
3017
+ "are read")
3018
+ embed = semantic.load_embedder()
3019
+ if embed is None:
3020
+ typer.echo(NO_MODEL)
3021
+ from keepfold import localllm
3022
+
3023
+ runner, budget = None, None
3024
+ if localllm.enabled():
3025
+ try: # the model only when it is already loaded: an import never loads one
3026
+ runner = localllm.find_loaded()
3027
+ except ValueError as e: # a non-loopback localllm.url is refused
3028
+ typer.echo(f"local LLM not used: {e}", err=True)
3029
+ if runner is not None:
3030
+ cfg = taint.config().get("localllm")
3031
+ secs = cfg.get("budget_s", 300) if isinstance(cfg, dict) else 300
3032
+ budget = localllm.Budget(secs if isinstance(secs, (int, float)) else 300)
3033
+
3034
+ def progress(key, n, new, err):
3035
+ typer.echo(f"{key}: not read: {sources.why(err)}; the other sources go on" if err
3036
+ else f"{key}: {n} visits read, {new} new")
3037
+
3038
+ try:
3039
+ r = build.run(v, srcs, load_settings(), embed=embed, runner=runner, budget=budget,
3040
+ since=since, dry_run=dry_run, progress=progress, say=typer.echo,
3041
+ takeout=google)
3042
+ except KeyboardInterrupt:
3043
+ typer.echo("stopped: every page on disk is whole and what was read is saved; run the "
3044
+ "import again to finish", err=True)
3045
+ raise typer.Exit(130) from None
3046
+ took = time.perf_counter() - t0
3047
+ if google is not None:
3048
+ typer.echo(f"takeout: {r.get('takeout', 0)} rows used from days your browsers do not "
3049
+ "hold; the rest the browsers already have")
3050
+ if "days_from" not in r:
3051
+ typer.echo("nothing new since the last import"
3052
+ + (" (dry run: nothing written)" if dry_run else ""))
3053
+ return
3054
+ typer.echo(f"visits from {r['days_from']}: kept {r.get('kept', 0)}, private "
3055
+ f"{r.get('private', 0)}, dropped by the privacy filter {r.get('dropped', 0)}")
3056
+ if dry_run:
3057
+ typer.echo(f"dry run, nothing written: would write {r.get('private_would', 0)} private "
3058
+ f"and {r.get('public_would', 0)} public day pages, and remove up to "
3059
+ f"{r.get('empty_would', 0)} emptied ones ({took:.1f} s)")
3060
+ return
3061
+ typer.echo(f"days written: {r.get('private_written', 0)} private pages, "
3062
+ f"{r.get('public_written', 0)} public; unchanged "
3063
+ f"{r.get('public_same', 0) + r.get('private_same', 0)}, removed "
3064
+ f"{r.get('public_removed', 0) + r.get('private_removed', 0)}")
3065
+ if refused := r.get("public_failed", 0) + r.get("private_failed", 0):
3066
+ typer.echo(f"pages the vault refused: {refused} (skipped)")
3067
+ typer.echo(f"interest lines {r.get('signals', 0)}; local model used: "
3068
+ f"{'yes' if runner is not None else 'no'}; time taken {took:.1f} s")
3069
+ if r.get("sources_failed"):
3070
+ typer.echo(f"{r['sources_failed']} source(s) not read: they keep their place, and the "
3071
+ "next import rebuilds these days with them")
3072
+ typer.echo("visible to Claude: yes — public day pages, index and interest lines written"
3073
+ if r.get("visible_to_claude") else
3074
+ "visible to Claude: no — only private pages written (browse.visible_to_claude)")
3075
+ from keepfold.browse import sites
3076
+
3077
+ sites.update_vectors(v, typer.echo)
3078
+
3079
+
3080
+ @browse_app.command("deepen")
3081
+ @_errors
3082
+ def browse_deepen(budget_s: Annotated[float | None, typer.Option(
3083
+ "--budget-s", help="Seconds the local model may spend (default: "
3084
+ "localllm.budget_s in config, else 300).")] = None,
3085
+ vault: VaultOpt = None) -> None:
3086
+ """The local model's long pass over your site pages, most visited first: a category for
3087
+ sites the built-in table does not know, a one-line description, related sites and topic
3088
+ hubs. Resumable: answers are cached as they come, so the next run goes on where this one
3089
+ stopped. Needs `localllm: {enabled: true}`. Prints counts only."""
3090
+ from keepfold import browse_serve
3091
+
3092
+ v = _vault(vault)
3093
+ try:
3094
+ r = browse_serve.run_deepen(v, say=typer.echo, budget_s=budget_s)
3095
+ except KeyboardInterrupt:
3096
+ typer.echo("stopped: the answers so far are saved; run deepen again to go on", err=True)
3097
+ raise typer.Exit(130) from None
3098
+ if r is None:
3099
+ typer.echo("no local model: add `localllm: {enabled: true}` to ~/.keepfold/config.yaml "
3100
+ "and start one (see `keepfold llm status`)")
3101
+
3102
+
3103
+ @browse_app.command("status")
3104
+ @_errors
3105
+ def browse_status(vault: VaultOpt = None) -> None:
3106
+ """The mode, the last import, the last read and cursor per browser and profile, and the
3107
+ local LLM it used."""
3108
+ from keepfold.browse import build, load_settings
3109
+
3110
+ for line in build.status(_vault(vault), visible=load_settings().visible_to_claude):
3111
+ typer.echo(line)
3112
+
3113
+
3114
+ @browse_app.command("forget")
3115
+ @_errors
3116
+ def browse_forget(site: Annotated[str | None, typer.Option(
3117
+ "--site", help="A domain, such as example.com (its subdomains too).")]
3118
+ = None,
3119
+ category: Annotated[str | None, typer.Option(
3120
+ "--category", help="A category, such as health or shopping.")] = None,
3121
+ vault: VaultOpt = None) -> None:
3122
+ """Remove everything stored about one site or one category: the private day page lines,
3123
+ the site counts and pages, the old capture extension's saved visits, the local model's site
3124
+ notes and the search vectors. Prints counts only. Your browsers still hold recent visits:
3125
+ add the site to deny_domains (or skip the category) so the next import leaves them out.
3126
+ Old versions in the vault's git history stay (see `keepfold doctor`)."""
3127
+ from keepfold.browse import forget, sites
3128
+
3129
+ if (site is None) == (category is None):
3130
+ raise VaultError("invalid_argument", "give exactly one of --site or --category.")
3131
+ if category is not None:
3132
+ category = category.strip().lower()
3133
+ if category not in sites.LABELS:
3134
+ raise VaultError("invalid_argument",
3135
+ f"--category must be one of {', '.join(sites.LABELS)}.")
3136
+ rule, what = forget.Rule(cats=frozenset({category})), f"category {category}"
3137
+ else:
3138
+ host = (site or "").strip().lower().removeprefix("https://").removeprefix("http://")
3139
+ host = host.split("/", 1)[0].removeprefix("www.").rstrip(".")
3140
+ if not re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)+", host):
3141
+ raise VaultError("invalid_argument", "--site must be a domain like example.com.")
3142
+ rule, what = forget.Rule(hosts=(host,)), host
3143
+ from keepfold import forget as forget_
3144
+
3145
+ v = _vault(vault)
3146
+ r = forget_.browse(v, rule, what)
3147
+ c = Counter(r["removed"])
3148
+ typer.echo(f"forgot {what}: {c['day_lines']} lines on {c['day_pages']} private day pages, "
3149
+ f"{c['site_keys']} site counts and {c['site_rows']} titles or searches, "
3150
+ f"{c['sites_removed']} site pages, {c['inbox_records']} saved extension visits, "
3151
+ f"{c['cache_sites'] + c['cache_descriptions']} local-model notes, "
3152
+ f"{c['vectors']} search vectors, {c['compacted']} databases compacted")
3153
+ for line in forget_.lines(r)[1:]:
3154
+ typer.echo(line)
3155
+
3156
+
3157
+ @browse_app.command("serve")
3158
+ @_errors
3159
+ def browse_serve_cmd(port: Annotated[int | None, typer.Option(
3160
+ hidden=True, help="Ignored: the receiver opens no port since 0.3.2.")]
3161
+ = None,
3162
+ vault: VaultOpt = None) -> None:
3163
+ """Import new browser history in the background, every browse.auto_import_hours (as Start
3164
+ at login runs it), until Ctrl+C. Opens no network port."""
3165
+ from keepfold import browse_serve
3166
+
3167
+ v = _vault(vault)
3168
+ typer.echo("Keepfold browse receiver: imports new browser history in the background; "
3169
+ "Ctrl+C stops it.")
3170
+ try:
3171
+ browse_serve.serve(v)
3172
+ except KeyboardInterrupt:
3173
+ pass
3174
+
3175
+
3176
+ @llm_app.command("status")
3177
+ def llm_status() -> None:
3178
+ """Which local runner (Ollama, llama.cpp or LM Studio on loopback) answers: runner, model,
3179
+ port, whether LM Studio has it loaded, and a one-token latency test. Read-only: it never
3180
+ starts LM Studio's server or loads a model (`keepfold llm start` does). Never downloads."""
3181
+ from keepfold import localllm
3182
+
3183
+ conf = taint.config()
3184
+ cfg = conf.get("localllm")
3185
+ cfg = cfg if isinstance(cfg, dict) else {}
3186
+ typer.echo(f"config: runner {cfg.get('runner') or 'auto'}, model "
3187
+ f"{cfg.get('model') or 'any'}, {'on' if localllm.enabled() else 'off'}")
3188
+ got = localllm.status(conf) # read-only: never starts LM Studio or loads a model
3189
+ if (st := got["lmstudio"]) is not None:
3190
+ ids = ", ".join(str(r.get("identifier")) for r in st["loaded"]) or "none"
3191
+ srv = f"on port {st['port']}" if st["port"] else "off"
3192
+ typer.echo(f"LM Studio: server {srv}, loaded: {ids}")
3193
+ if got["error"]: # a non-loopback localllm.url or a cloud model is refused
3194
+ typer.echo(f"local LLM not used: {got['error']}", err=True)
3195
+ if (runner := got["runner"]) is None:
3196
+ typer.echo("no local LLM found (Ollama on 127.0.0.1:11434, LM Studio with "
3197
+ "localllm.runner: lmstudio, or llama.cpp / LM Studio at localllm.url, holding "
3198
+ "localllm.model if set). Optional; to add one, install Ollama and run: "
3199
+ "ollama pull qwen3.5:4b (qwen3.5:2b under 6 GB of memory). Installed but "
3200
+ "stopped? Run `keepfold llm start`.")
3201
+ return
3202
+ typer.echo(f"found: {runner.describe()}")
3203
+ if not localllm.enabled():
3204
+ typer.echo("not used by `keepfold browse import` until you add `localllm: {enabled: true}` "
3205
+ "to ~/.keepfold/config.yaml")
3206
+ if st is not None and st["port"]:
3207
+ on = any(runner.model.lower() == str(r.get("identifier", "")).lower()
3208
+ for r in st["loaded"])
3209
+ typer.echo(f"loaded in LM Studio: {'yes' if on else 'no'}")
3210
+ if not on: # a ping would make LM Studio load it
3211
+ typer.echo("latency: not tested; run `keepfold llm start` to load it")
3212
+ return
3213
+ lat = runner.ping()
3214
+ typer.echo(f"latency (1 token): {lat:.2f} s" if lat is not None else "latency: no answer")
3215
+
3216
+
3217
+ @llm_app.command("start")
3218
+ @_errors
3219
+ def llm_start(runner: Annotated[str | None, typer.Option(
3220
+ help="ollama (recommended) or lmstudio; default: localllm.runner, else ollama.")]
3221
+ = None) -> None:
3222
+ """Start an installed local runner: Ollama (its app, else `ollama serve`) or LM Studio
3223
+ (`lms server start`), and wait until it answers. Never installs or downloads."""
3224
+ from keepfold.app import wizard
3225
+
3226
+ if runner is None:
3227
+ cfg = taint.config().get("localllm")
3228
+ runner = cfg.get("runner") if isinstance(cfg, dict) else None
3229
+ runner = runner if runner in wizard.RUNNERS else "ollama"
3230
+ try:
3231
+ out = wizard.start(runner)
3232
+ except ValueError as e:
3233
+ raise VaultError("invalid_argument", str(e)) from None
3234
+ for line in out["lines"]:
3235
+ typer.echo(line)
3236
+ if not out["ok"]:
3237
+ raise typer.Exit(1)
3238
+
3239
+
3240
+ @llm_app.command("test")
3241
+ def llm_test() -> None:
3242
+ """Send the runner one synthetic prompt (never your data) and print its answer and time."""
3243
+ runner = _local_llm()
3244
+ if runner is None:
3245
+ typer.echo("no local LLM found; see `keepfold llm status`")
3246
+ raise typer.Exit(1)
3247
+ typer.echo(f"runner: {runner.describe()}")
3248
+ text, labels = "Dijkstra shortest path tutorial", ["programming", "cooking", "sports"]
3249
+ typer.echo(f"classify: {text!r} as one of {', '.join(labels)}")
3250
+ t = time.perf_counter()
3251
+ got = runner.classify(text, labels)
3252
+ took = time.perf_counter() - t
3253
+ typer.echo(f"answer: {got[0]} (confidence {got[1]:.2f})" if got else "answer: none valid")
3254
+ typer.echo(f"time: {took:.2f} s")