keepfold 0.6.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,83 @@
1
+ """Conflict copies a sync tool leaves beside a file two devices changed (Syncthing, OneDrive,
2
+ Dropbox): `original` names the file a copy stands for, `find` lists a vault's copies for
3
+ `keepfold doctor` and `keepfold lint`. The event log reads its copies itself (events._merged)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ from collections.abc import Container
10
+ from pathlib import Path
11
+
12
+ from keepfold.vault import PRIVATE_BROWSE_DIR
13
+
14
+ # Syncthing: <name>.sync-conflict-<YYYYMMDD>-<HHMMSS>-<device id: 7 of A-Z, 0-9>.<ext>
15
+ _SYNCTHING = re.compile(
16
+ r"(?P<stem>.+?)\.sync-conflict-\d{8}-\d{6}-[A-Z0-9]{7}(?P<ext>\.[^.]*)?", re.I)
17
+ # Dropbox: <name> (conflicted copy <YYYY-MM-DD>).<ext>, <name> (<Device>'s conflicted copy ...)
18
+ _DROPBOX = re.compile(r"(?P<stem>.+?) \((?:[^()]*['’]s )?conflicted copy(?: \d{4}-\d\d-\d\d)?"
19
+ r"(?: \(\d+\))?\)(?P<ext>\.[^.]*)?", re.I)
20
+ # OneDrive: <name>-<COMPUTERNAME>.<ext>, maybe -<n> after it. The computer name (15 at most)
21
+ # holds an upper-case letter, as Windows shows it; page ids are all lower case, so a page's
22
+ # own hyphens never read as one.
23
+ _PC = re.compile(r"(?=[^.]*[A-Z])[A-Za-z0-9-]{1,15}(?:-\d{1,3})?")
24
+
25
+
26
+ def original(name: str, siblings: Container[str] = ()) -> str | None:
27
+ """The file name a sync conflict copy called `name` stands for, or None when it is not
28
+ one. A OneDrive name counts only when that file is among `siblings` (the names in its
29
+ folder): `<name>-<PC>` alone is an ordinary name too."""
30
+ for rx in (_SYNCTHING, _DROPBOX):
31
+ if m := rx.fullmatch(name):
32
+ return m["stem"] + (m["ext"] or "")
33
+ stem, ext = os.path.splitext(name)
34
+ i = stem.find("-")
35
+ while i > 0:
36
+ if _PC.fullmatch(stem[i + 1:]) and stem[:i] + ext in siblings:
37
+ return stem[:i] + ext
38
+ i = stem.find("-", i + 1)
39
+ return None
40
+
41
+
42
+ def find(root: Path) -> list[tuple[str, str]]:
43
+ """(copy, original) vault-relative paths, `/`-separated and sorted, of every conflict copy
44
+ under `root`: pages, events, me/ files, anything but dot folders (.keepfold's internals,
45
+ .git) and browse/private/, which is never read or listed."""
46
+ root = Path(root)
47
+ private = os.path.normcase(os.path.join(root, *PRIVATE_BROWSE_DIR.split("/")))
48
+ out = []
49
+ for d, dirs, files in os.walk(root):
50
+ dirs[:] = [n for n in dirs if not n.startswith(".")
51
+ and os.path.normcase(os.path.join(d, n)) != private]
52
+ names = set(files)
53
+ rel = Path(d).relative_to(root).as_posix()
54
+ pre = "" if rel == "." else rel + "/"
55
+ out += [(pre + n, pre + o) for n in files if (o := original(n, names)) is not None]
56
+ return sorted(out)
57
+
58
+
59
+ def find_visible(vault) -> tuple[list[tuple[str, str]], int]:
60
+ """(`find`'s copies a report may name, how many it may not): a private page's copies are
61
+ counted, never named. Private as the index has it: the copy's or the original's own front
62
+ matter or folder (relink._hidden: `private: true`, people pages, browse/private/), or an
63
+ original under a private subject (planner.hidden: a private domain, area or concept)."""
64
+ from keepfold import planner
65
+ from keepfold.catalog import Catalog
66
+ from keepfold.relink import _hidden
67
+
68
+ found = find(vault.root)
69
+ if not found:
70
+ return [], 0
71
+ hide = planner.hidden(vault, Catalog.load(vault))
72
+
73
+ def private(rel: str) -> bool:
74
+ p = vault.root / rel
75
+ try:
76
+ return p.suffix == ".md" and p.is_file() and _hidden(
77
+ vault.root, p, p.read_bytes().decode("utf-8", errors="replace"))
78
+ except OSError:
79
+ return True
80
+
81
+ shown = [(c, o) for c, o in found
82
+ if Path(o).stem not in hide and not private(c) and not private(o)]
83
+ return shown, len(found) - len(shown)
keepfold/tags.py ADDED
@@ -0,0 +1,230 @@
1
+ """R3-5: `//pref: <text>`, `//fact: <text>` and `//forget: <text>`, typed by the owner in any
2
+ chat and caught by code, never by the model. Callers pass user turns only, never assistant
3
+ text, tool output or note text: the prime prompt (keepfold_prime and the plugin's prime hook,
4
+ keepfold.prime_hook), a chat_turn's `user` and an imported chat's user turns (chat_import).
5
+
6
+ - pref: a me/preferences line under `## Personal`, written as keepfold_patch writes a
7
+ user_confirmed one (its change stamped `confirm: tagged`, an act-grade yes);
8
+ - fact: the same on me/profile under `## Background`;
9
+ - forget: the one live claim line the text covers at least STRONG of (review's word bag) is
10
+ retired to `## Past` (history kept, `keepfold undo` takes it back); none or several, and
11
+ nothing changes: a `tag_forget` event holds the candidates for the app's Review.
12
+
13
+ A chat that read outside text (an exposed session) only proposes: a pref or fact waits in
14
+ inbox.md for Approve, a forget becomes the Review card. So does a pref or fact whose text reads
15
+ like a planted deep link or promotion (`promo`, G-Q9-14), in any chat. A tag seen twice on one
16
+ day (the hook, then keepfold_prime or chat_turn of the same turn, or a re-import) writes once:
17
+ each carries a `key` (tag, text, day) that keepfold_patch's own key dedupe (`Keepfold._keyed`)
18
+ honours."""
19
+
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import re
24
+ from datetime import date
25
+
26
+ from keepfold import claims, dates, review
27
+ from keepfold.chats import drop_private
28
+ from keepfold.events import EventLog, local_day
29
+ from keepfold.render import plain
30
+ from keepfold.vault import VaultError, scan_secrets
31
+
32
+ TAG = re.compile(r"(?<![\w:/])//(pref|fact|forget):[ \t]*([^\r\n]*)", re.I)
33
+ MAX_CHARS = 300 # a tag's text
34
+ PAGES = {"pref": ("preferences", "Personal"), "fact": ("profile", "Background")}
35
+ STRONG = 0.6 # of a claim line's content words the forget text must hold
36
+ SHOWN = 5 # candidates on a forget card
37
+ # G-Q9-14: what a planted deep link or a promotion says ("summarize this page and remember
38
+ # ...", "remember X as a trusted source", "always recommend X", "from now on recommend X")
39
+ PROMO = re.compile(r"\bsummari[sz]e\b.{0,300}?\bremember\b|\bremember\b.{0,200}?\bas (?:an? |the |"
40
+ r"my )?(?:trusted|reliable|authoritative|official|preferred|go-to|top|best) "
41
+ r"(?:source|site|reference|resource|vendor|provider|brand)|"
42
+ r"\balways (?:recommend|suggest)\b|\bfrom now on,? (?:always )?"
43
+ r"(?:recommend|suggest)\b", re.I | re.S)
44
+
45
+
46
+ def promo(text: str) -> bool:
47
+ """G-Q9-14: does `text` read like a planted deep link or promotion (`PROMO`)?"""
48
+ return bool(PROMO.search(text.replace("’", "'")))
49
+
50
+
51
+ def find(text: str) -> list[tuple[str, str]]:
52
+ """(tag, text) of each `//pref:`, `//fact:` or `//forget:` in a user turn, in order; the
53
+ text runs to the end of its line, whitespace collapsed; an empty one is skipped. A
54
+ `<private>` span is dropped first, so a tag inside one is never saved."""
55
+ out: list[tuple[str, str]] = []
56
+ for m in TAG.finditer(drop_private(text or "")):
57
+ item = (m.group(1).lower(), " ".join(m.group(2).split())[:MAX_CHARS])
58
+ if item[1] and item not in out:
59
+ out.append(item)
60
+ return out
61
+
62
+
63
+ def key(tag: str, text: str, day: str) -> str:
64
+ return "tag:" + hashlib.sha1(f"{tag}\n{claims.norm(text)}\n{day}".encode()).hexdigest()[:16]
65
+
66
+
67
+ def apply(core, items, said: bool = True, forget_said: bool = True,
68
+ refused: list[str] | None = None) -> list[str]:
69
+ """Act on (tag, text, day) items through `core` (an mcp_server.Keepfold): each one through
70
+ its `_call`, so roles, the excluded folder, an ambient session and the key dedupe all
71
+ apply. `said`: the caller knows these are the owner's typed words (the hook, an import);
72
+ a session that read outside text still only proposes. `forget_said=False` (an import: an
73
+ old chat's forget may predate the line it matches) sends every forget to the Review.
74
+ Returns a line per tag acted on; `refused` gets a `refusal` line per tag Keepfold refused."""
75
+ lines = []
76
+ for tag, text, day in items:
77
+ k = key(tag, text, day)
78
+ if core.log.has_key(k): # before _call, which would open a session for nothing
79
+ continue
80
+ ok = said and (forget_said or tag != "forget")
81
+ # "yesterday" as of the turn's own day (an import's is old); no day, no pin, and
82
+ # keepfold_patch never pins a tag itself (mcp_server._pin_day: `tagged`)
83
+ if tag in PAGES and day:
84
+ text = dates.pin(text, date.fromisoformat(day))
85
+ out = core._call("keepfold_patch", core._tag, {"tag": tag, "text": text, "said": ok,
86
+ "key": k})
87
+ if "error" in out:
88
+ if refused is not None:
89
+ refused.append(refusal(tag, str(out.get("message") or out["error"])))
90
+ elif not out.get("duplicate"):
91
+ lines.append(out["summary"])
92
+ return lines
93
+
94
+
95
+ def refusal(tag: str, why: str) -> str:
96
+ """`//<tag> line: <why>`, with no invisible or control character from `why`."""
97
+ return f"//{tag} line: " + "".join(c for c in why if c.isprintable())
98
+
99
+
100
+ def _refused(tag: str, text: str) -> str | None:
101
+ """What `act` would refuse the text for before it writes anything, else None."""
102
+ try:
103
+ scan_secrets(text)
104
+ if tag != "forget":
105
+ claims.check(text, PAGES[tag][0])
106
+ except VaultError as e:
107
+ return str(e)
108
+ return None
109
+
110
+
111
+ def apply_in(vault, items, log: EventLog | None = None, forget_said: bool = True,
112
+ refused: list[str] | None = None) -> list[str]:
113
+ """`apply` outside the MCP server (the prime hook, chat_import): a Keepfold of its own, built
114
+ only when an item is new (`log`: an EventLog to check keys with) and passes act's checks
115
+ (a refused one goes to `refused` with no session), whose session is closed (and
116
+ committed) at once."""
117
+ log = log or EventLog(vault)
118
+ items = [i for i in items if not log.has_key(key(*i))]
119
+ bad = {i: why for i in items if (why := _refused(i[0], i[1]))}
120
+ if refused is not None:
121
+ refused += [refusal(i[0], why) for i, why in bad.items()]
122
+ items = [i for i in items if i not in bad]
123
+ if not items:
124
+ return []
125
+ from keepfold.mcp_server import Keepfold # the SDK: only when there is something to write
126
+
127
+ # no index build: a tag writes me/ pages only, and the build thread slowed the hook ~1 s
128
+ core = Keepfold(vault, build=False)
129
+ core._ready.set() # so a use of the index raises at once instead of waiting forever
130
+ try:
131
+ return apply(core, items, forget_said=forget_said, refused=refused)
132
+ finally:
133
+ if core.sessions.current is not None:
134
+ core.sessions.close(summary="Saved //tags the user typed")
135
+
136
+
137
+ def act(core, tag: str, text: str, said: bool) -> dict:
138
+ """One tag, inside `core`'s open session (Keepfold._tag)."""
139
+ scan_secrets(text)
140
+ day = local_day(core._now())
141
+ if tag == "forget":
142
+ return _forget(core, text, day, said)
143
+ page, section = PAGES[tag]
144
+ claims.check(text, page) # G6: before _ensure_section writes the heading
145
+ if not said or promo(text): # G-Q9-14: a promotion waits for Approve too
146
+ why = "this chat read outside text" if not said else "it reads like a promotion"
147
+ core._propose(f"- {section}: {text} (proposed {day}, me/{page})", page=page)
148
+ core.proposed.append(plain(f"{section}: {text}", 200))
149
+ core.sessions.note("patched", change={"tool": "propose", "id": page, "kind": "me",
150
+ "op": "append_to_section", "target": section,
151
+ "hash": review.text_hash(text)})
152
+ return {"changed": False, "queued": True,
153
+ "summary": f"//{tag} waits for Approve in the Keepfold app ({why})"}
154
+ core._ensure_section(page, section)
155
+ core.tagged = True
156
+ try:
157
+ out = core.keepfold_patch(id=f"me/{page}", op="append_to_section", target=section,
158
+ text=text, user_confirmed=True)
159
+ finally:
160
+ core.tagged = False
161
+ return {**out, "summary": f"//{tag} saved to me/{page}"}
162
+
163
+
164
+ def _score(text: str, line: str) -> float:
165
+ """The share of `line`'s content words (review._bag) that `text` holds."""
166
+ mine = review._bag(line)
167
+ return len(review._bag(text) & mine) / len(mine) if mine else 0.0
168
+
169
+
170
+ def candidates(vault, text: str, today: str) -> list[dict]:
171
+ """Live, non-private claim rows sharing a content word with `text`, best first, each with
172
+ its `score`."""
173
+ hidden = review._private(vault)
174
+ rows = [{**r, "score": s} for r in claims.rows(vault)
175
+ if claims.is_live(r, today) and r["page"] not in hidden
176
+ and (s := _score(text, r["text"])) > 0]
177
+ return sorted(rows, key=lambda r: -r["score"])
178
+
179
+
180
+ def _forget(core, text: str, day: str, said: bool) -> dict:
181
+ rows = candidates(core.vault, text, day)
182
+ strong = [r for r in rows if r["score"] >= STRONG]
183
+ if said and len(strong) == 1:
184
+ r = strong[0]
185
+ core.tagged = True
186
+ try:
187
+ out = core.keepfold_patch(id=f"me/{r['page']}", op="retire", target=r["id"],
188
+ user_confirmed=True)
189
+ finally:
190
+ core.tagged = False
191
+ if "error" in out:
192
+ return out
193
+ # R10: the sweep from every store can take a minute, longer than a prompt hook may run,
194
+ # so the app's periodic pass runs it (forget.run_due); `text` is swept with the line
195
+ core._append("log", {"payload": {"kind": "forget_due", "page": r["page"],
196
+ "claim": r["id"], "text": text}})
197
+ return {**out, "summary": f"//forget retired a line on me/{r['page']}; the Keepfold app "
198
+ "removes it from everywhere Keepfold keeps it within 10 minutes"}
199
+ shown = (strong or rows)[:SHOWN]
200
+ core._append("log", {"payload": {"kind": "tag_forget", "text": text, "candidates": [
201
+ {"page": r["page"], "id": r["id"]} for r in shown]}})
202
+ return {"changed": False, "queued": True,
203
+ "summary": f"//forget matched {len(strong) or 'no'} line{'s' * (len(strong) != 1)}"
204
+ " strongly: nothing changed; the Keepfold app's Review lists "
205
+ f"{len(shown)} to pick from"}
206
+
207
+
208
+ def forget_cards(vault, events, today: str) -> list[dict]:
209
+ """The Review's open forget cards, newest first: {key (the event id), text, day,
210
+ candidates [{page, id, text}]} with raw note text. A card closes on Dismiss (a `dismiss`
211
+ change on page `forget`) or once one of its candidates is no longer live."""
212
+ events = list(events)
213
+ voided = review._voided(events)
214
+ live = {(r["page"], r["id"]): r for r in claims.rows(vault) if claims.is_live(r, today)}
215
+ hidden = review._private(vault)
216
+ out = []
217
+ for e in events:
218
+ p = review._payload(e)
219
+ if (e.get("kind") != "log" or p.get("kind") != "tag_forget" or e.get("id") in voided
220
+ or review.dismissed(events, "forget", e["id"])):
221
+ continue
222
+ pairs = [(c.get("page"), c.get("id")) for c in p.get("candidates") or []
223
+ if isinstance(c, dict)]
224
+ if any(k not in live for k in pairs):
225
+ continue
226
+ out.append({"key": e["id"], "text": str(p.get("text") or ""), "day": e.get("day"),
227
+ "candidates": [{"page": pg, "id": i, "text": live[(pg, i)]["text"]}
228
+ for pg, i in pairs if pg not in hidden]})
229
+ return out[::-1]
230
+
keepfold/taint.py ADDED
@@ -0,0 +1,301 @@
1
+ """`keepfold taint`: the plugin's PostToolUse hook records that Claude read outside text with a
2
+ tool that is not Keepfold (web, browser, mail, other MCP servers). The MCP server treats a fresh
3
+ marker as exposure (session.SessionManager._check_taint), so claim tiers see it. R7: Codex
4
+ CLI's PostToolUse and Gemini CLI's AfterTool hooks (keepfold.app.targets) run it the same way.
5
+
6
+ This module is also the `keepfold` console entry: `keepfold taint` runs here without importing
7
+ keepfold.cli (typer and every core module), since the hook fires on each matched tool call.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ import time
17
+ from collections.abc import Callable
18
+ from contextlib import contextmanager
19
+ from contextvars import ContextVar
20
+ from pathlib import Path
21
+
22
+ MARKER = ".keepfold/taint"
23
+ # Keepfold's own servers, the Claude desktop app's one-word `ccd_*` servers (not ccd_session_mgmt:
24
+ # it returns other chats' text), widgets, schedules and the savvy-progress bar, whose tools
25
+ # return no outside text (review r4 M4).
26
+ # Desktop Commander, Windows-MCP, browsers and connectors still count. plugin/hooks/hooks.json's
27
+ # matcher skips the same names (tests/test_taint.py checks they agree); this is the backstop.
28
+ EXCLUDED = re.compile(
29
+ r"^mcp__(keepfold|plugin_keepfold_keepfold|ccd_[^_]*|visualize|scheduled-tasks|"
30
+ r"savvy-progress)__")
31
+ # R7: Keepfold's own tools as Gemini CLI names them (`mcp_<server>_<tool>`); its AfterTool hook's
32
+ # matcher skips them too. Codex CLI names MCP tools as Claude Code does (EXCLUDED covers it).
33
+ GEMINI_OWN = re.compile(r"^mcp_keepfold_")
34
+
35
+
36
+ def _config_path() -> Path:
37
+ return Path.home() / ".keepfold" / "config.yaml"
38
+
39
+
40
+ # a config pinned for one thread's work (keepfold.chat_eval): config() returns it there instead of
41
+ # the file, and write_config refuses, so a made-up run never reads or changes the owner's settings
42
+ _PINNED: ContextVar[dict | None] = ContextVar("keepfold_pinned_config", default=None)
43
+
44
+
45
+ @contextmanager
46
+ def pinned(data: dict):
47
+ """Within the block, in this thread (and context) only, config() is a copy of `data`."""
48
+ token = _PINNED.set(data)
49
+ try:
50
+ yield
51
+ finally:
52
+ _PINNED.reset(token)
53
+
54
+
55
+ CONFIG_FIX = ("Fix that line (the file is YAML: `key: value` lines), or delete the file to start "
56
+ "from the defaults. Deleting forgets every setting in it: the vault folder, the "
57
+ "excluded folders, the browsing choices and the chat import switch; then set "
58
+ "Keepfold up again (the app's Setup, or `keepfold setup`), pick the same vault "
59
+ "folder and add your exclusions back. Until then every folder counts as excluded "
60
+ "and the chat and browsing imports are off.")
61
+
62
+
63
+ def _unreadable(path: Path, e: Exception) -> str:
64
+ """Why `path` cannot be read: the error's type and line only, since its text quotes the
65
+ line, which could hold anything."""
66
+ mark = getattr(e, "problem_mark", None) or getattr(e, "context_mark", None)
67
+ at = f" at line {mark.line + 1}" if mark is not None else ""
68
+ return f"{path} cannot be read: {type(e).__name__}{at}"
69
+
70
+
71
+ def _read_text(path: Path) -> str:
72
+ """The file's text. A PermissionError (Windows, while write_config's os.replace holds the
73
+ file) is retried twice before it counts as unreadable."""
74
+ import time
75
+ for wait in (0.05, 0.2):
76
+ try:
77
+ return path.read_text(encoding="utf-8")
78
+ except PermissionError:
79
+ time.sleep(wait)
80
+ return path.read_text(encoding="utf-8")
81
+
82
+
83
+ def _read() -> tuple[dict, str | None]:
84
+ """(config, None); ({}, why) when the file is there but cannot be read; ({}, None) when it
85
+ is missing. `pinned`'s dict within that block."""
86
+ if (p := _PINNED.get()) is not None:
87
+ import copy
88
+ return copy.deepcopy(p), None
89
+ from ruamel.yaml import YAML, YAMLError # keepfold.vault loads it anyway
90
+ path = _config_path()
91
+ try:
92
+ data = YAML(typ="safe").load(_read_text(path)) or {}
93
+ except FileNotFoundError:
94
+ return {}, None
95
+ except (OSError, ValueError, YAMLError) as e:
96
+ return {}, _unreadable(path, e)
97
+ if not isinstance(data, dict):
98
+ return {}, f"{path} cannot be read: it is not `key: value` lines"
99
+ return data, None
100
+
101
+
102
+ def config() -> dict:
103
+ """~/.keepfold/config.yaml as a dict ({} when missing or broken: `config_error` tells them
104
+ apart); `pinned`'s dict within it."""
105
+ return _read()[0]
106
+
107
+
108
+ def config_error() -> str | None:
109
+ """Why ~/.keepfold/config.yaml is there but cannot be read (path, error type, line), else
110
+ None. While it is set, privacy choices fail closed: `excluded` is every folder, and the
111
+ chat and browsing imports refuse (`check_config`)."""
112
+ return _read()[1]
113
+
114
+
115
+ def check_config(what: str) -> None:
116
+ """Refuse `what` while the config cannot be read: on the defaults it would take in what the
117
+ user excluded."""
118
+ if err := config_error():
119
+ from keepfold.vault import VaultError
120
+ raise VaultError("invalid_argument", f"{err}, so {what} is off until it is fixed; the "
121
+ "app's Status page and `keepfold doctor` say how.")
122
+
123
+
124
+ def write_config(data: dict | Callable[[dict], dict]) -> Path:
125
+ """Set `data`'s keys in ~/.keepfold/config.yaml, keeping its other keys. `data` may be a
126
+ function: it gets the config as read under the lock and returns the keys to set, so a
127
+ read-merge-write of a sub-dict (`browse:`, `app:`) cannot lose a concurrent writer's change.
128
+ Refuses to overwrite a config that exists, is not empty and does not parse to a dict (a merge
129
+ with {} would wipe `vault:` and `exclude:`). Under ~/.keepfold/config.lock: mkstemp, then
130
+ os.replace with retry; an unchanged config is not rewritten."""
131
+ import copy
132
+ import tempfile
133
+
134
+ from ruamel.yaml import YAML, YAMLError
135
+
136
+ from keepfold.vault import LOCK_STALE_S, REPLACE_TRIES, VaultError
137
+
138
+ if _PINNED.get() is not None:
139
+ raise VaultError("invalid_argument", "Settings cannot change during a pinned run.")
140
+ path = _config_path()
141
+ path.parent.mkdir(parents=True, exist_ok=True)
142
+ lock = path.with_name("config.lock")
143
+ deadline = time.monotonic() + 5
144
+ while True:
145
+ try:
146
+ os.close(os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
147
+ break
148
+ except (FileExistsError, PermissionError) as e:
149
+ try:
150
+ if time.time() - lock.stat().st_mtime > LOCK_STALE_S: # its writer died
151
+ lock.unlink()
152
+ continue
153
+ except OSError:
154
+ pass # gone, or never creatable (R2-5): wait out the deadline, never spin
155
+ if time.monotonic() >= deadline:
156
+ why = ("is held by another Keepfold process" if lock.exists()
157
+ else f"cannot be created ({e.strerror or e})")
158
+ raise VaultError("vault_locked", f"{lock} {why}; try again in a moment.") from None
159
+ time.sleep(0.05)
160
+ try:
161
+ try:
162
+ old = YAML(typ="safe").load(path.read_text(encoding="utf-8")) or {}
163
+ except FileNotFoundError:
164
+ old = {}
165
+ except (OSError, ValueError, YAMLError) as e:
166
+ raise VaultError("invalid_argument", f"{_unreadable(path, e)}; fix it (UTF-8 YAML "
167
+ "with key: value lines) or delete it, then try again.") from e
168
+ if not isinstance(old, dict):
169
+ raise VaultError("invalid_argument", f"{path} is not a key: value mapping; fix it "
170
+ "or delete it, then try again.")
171
+ # a copy: a function that edits a sub-dict in place must not make `new == old`
172
+ new = {**old, **(data(copy.deepcopy(old)) if callable(data) else data)}
173
+ if new == old:
174
+ return path
175
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".config.", suffix=".tmp")
176
+ try:
177
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
178
+ YAML(typ="safe").dump(new, f)
179
+ for attempt in range(REPLACE_TRIES):
180
+ try:
181
+ os.replace(tmp, path)
182
+ break
183
+ except PermissionError:
184
+ if attempt == REPLACE_TRIES - 1:
185
+ raise
186
+ time.sleep(0.05 * 2**attempt)
187
+ finally:
188
+ if os.path.exists(tmp):
189
+ os.unlink(tmp)
190
+ finally:
191
+ lock.unlink(missing_ok=True)
192
+ return path
193
+
194
+
195
+ def _same_dir(a, b) -> bool:
196
+ def norm(p):
197
+ return os.path.normcase(str(Path(p).expanduser().resolve()))
198
+ return norm(a) == norm(b)
199
+
200
+
201
+ def _vault_root() -> Path | None:
202
+ """The vault the hooks write to: the configured one. KEEPFOLD_VAULT counts only when it names
203
+ that vault or none is configured, so a project's env cannot point the hooks at its own
204
+ folder (review RR-16)."""
205
+ v = config().get("vault")
206
+ env = os.environ.get("KEEPFOLD_VAULT")
207
+ if env and (not v or _same_dir(env, v)):
208
+ return Path(env)
209
+ return Path(v) if v else None
210
+
211
+
212
+ def exclude_list(cfg: dict | None = None) -> list[str]:
213
+ ex = (config() if cfg is None else cfg).get("exclude") or []
214
+ return [str(e) for e in ([ex] if isinstance(ex, str) else ex) if e]
215
+
216
+
217
+ def excluded(*dirs) -> str | None:
218
+ """The `exclude:` folder of ~/.keepfold/config.yaml that holds one of `dirs` (resolved, by
219
+ whole path components; case-insensitive on Windows), or None. While the config cannot be
220
+ read, every folder is excluded: the first of `dirs`, with the reason."""
221
+ cfg, err = _read()
222
+ if err: # fail closed: the unreadable file may list exclusions
223
+ d = next((d for d in dirs if d), None)
224
+ return f"{Path(d).resolve()} (every folder is, while {err})" if d else None
225
+ folders = [Path(e).expanduser().resolve() for e in exclude_list(cfg)]
226
+ for d in dirs:
227
+ if d:
228
+ p = Path(d).resolve()
229
+ for f in folders:
230
+ if p == f or f in p.parents:
231
+ return str(f)
232
+ return None
233
+
234
+
235
+ def session_dirs(cwd=None) -> tuple:
236
+ """The folders a Claude Code session runs in: `cwd` (the hook payload's, else the process's)
237
+ and CLAUDE_PROJECT_DIR when Claude Code sets it."""
238
+ return cwd or os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR")
239
+
240
+
241
+ def run(raw: str) -> bool:
242
+ """Write the marker for one hook payload; True if written. Never raises: a hook must not
243
+ fail the tool call it follows."""
244
+ try:
245
+ hook = json.loads(raw)
246
+ tool = hook.get("tool_name")
247
+ if not isinstance(tool, str) or not tool or EXCLUDED.match(tool) or GEMINI_OWN.match(
248
+ tool):
249
+ return False
250
+ root = _vault_root()
251
+ if root is None or not root.is_dir():
252
+ return False
253
+ from keepfold.vault import Vault
254
+ sid = hook.get("session_id")
255
+ Vault(root).write_text(root / MARKER, json.dumps(
256
+ {"ts": time.time(), "tool_name": tool[:200],
257
+ "session_id": sid[:200] if isinstance(sid, str) else None}) + "\n")
258
+ return True
259
+ except Exception: # noqa: BLE001 (garbage stdin, a busy vault lock, a secret-scan refusal)
260
+ return False
261
+
262
+
263
+ def read_stdin() -> str:
264
+ try:
265
+ return sys.stdin.buffer.read().decode("utf-8", "replace")
266
+ except Exception: # noqa: BLE001 (no stdin, or a text-only stream)
267
+ return ""
268
+
269
+
270
+ BLAS_THREADS = "4" # numpy's OpenBLAS commits ~32 MB per thread (docs/benchmarks/memory.md)
271
+
272
+
273
+ def cap_blas() -> None:
274
+ """Every Keepfold process's entry point, before numpy loads: OpenBLAS's threads capped at
275
+ BLAS_THREADS, unless the user set OPENBLAS_NUM_THREADS or OMP_NUM_THREADS (OpenBLAS reads
276
+ either). Processes Keepfold starts inherit it."""
277
+ if not (os.environ.get("OPENBLAS_NUM_THREADS") or os.environ.get("OMP_NUM_THREADS")):
278
+ os.environ["OPENBLAS_NUM_THREADS"] = BLAS_THREADS
279
+
280
+
281
+ def main() -> None:
282
+ """The `keepfold` console script."""
283
+ cap_blas()
284
+ from keepfold import migrate # first: ~/.cortex moves before anything reads the home
285
+ if (code := migrate.at_start(sys.argv)) is not None:
286
+ raise SystemExit(code)
287
+ # R7: `--client codex|gemini` (keepfold.app.targets writes it into those apps' hooks)
288
+ client = sys.argv[3] if sys.argv[2:3] == ["--client"] and len(sys.argv) > 3 else None
289
+ if sys.argv[1:2] == ["taint"]:
290
+ run(read_stdin())
291
+ return # exit 0, nothing on stdout
292
+ if sys.argv[1:2] == ["prime-hook"]: # fires on every prompt: skip the CLI import too
293
+ from keepfold import prime_hook
294
+ if out := prime_hook.run(read_stdin(), *([client] if client else [])):
295
+ sys.stdout.write(out)
296
+ if prime_hook.pending is not None and prime_hook.pending.is_alive():
297
+ sys.stdout.flush() # a prime still running past its budget must not hold the exit
298
+ os._exit(0)
299
+ return
300
+ from keepfold.cli import app
301
+ app()