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/prime.py ADDED
@@ -0,0 +1,630 @@
1
+ """The light part of keepfold_prime: the pinned Core, Profile, claim legend, Preferences and the
2
+ teaching-contract core, built from a Vault and the event log alone. It never imports the `mcp`
3
+ SDK, numpy or `keepfold.semantic` and never builds the Index, so the `keepfold prime-hook` process
4
+ stays fast on a large vault; the MCP server adds the Related block on top
5
+ (mcp_server.Keepfold.keepfold_prime). Preferences rank by meaning only with an embedder that
6
+ process already loaded.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import sys
13
+ from datetime import UTC, datetime
14
+
15
+ from keepfold import access, claims, render, review, xray
16
+ from keepfold.contract import MAX_CHARS as CONTRACT_MAX
17
+ from keepfold.contract import scope_contract
18
+ from keepfold.events import EventLog, local_day
19
+ from keepfold.index import STOPWORDS, TRUNCATED, _edge_targets, _wrap
20
+ from keepfold.vault import ID_RE, Vault, VaultError, is_private
21
+
22
+ CONTEXT_MAX = 2400 # characters, about 600 tokens
23
+ # keepfold_prime: one cheap first call per chat, about 500 tokens
24
+ PRIME_MAX, PRIME_PROMPT = 2000, 2000
25
+ PRIME_CAPS = {"profile": 250, "preferences": 800, "contract": 400, "related": 450,
26
+ "mistakes": 250}
27
+ # me/core.md: the user's pinned lines, first in every prime, whole lines within this many chars
28
+ CORE_MAX, CORE_HEAD = 500, "Core"
29
+ VEC_CACHE = 5000 # line vectors kept for a long-running server; past it the cache starts over
30
+ # PHASE3 H3: served claim labels and ranking
31
+ LEGEND = "(ask) = check with the user before relying on it."
32
+ ASK_WEIGHT = 0.3
33
+ # phase4-wiki §7.2: the me/personality.md sections keepfold_context serves, by scope
34
+ PERSONALITY_HEADINGS = {"all": ("communication", "how i think"),
35
+ "communication": ("communication",), "learning": ("how i think",)}
36
+ NOT_RECORDED = "not recorded yet; ask the user and save it with keepfold_patch."
37
+ # Sections that say how to work with the user in any chat; when no line matches the prompt,
38
+ # these lead, and situational ones (Projects, Coursework, …) wait for a match.
39
+ GENERAL_SECTIONS = ("communication", "working with ai", "learning", "how i think")
40
+ # Words that say what to do, not what about: "revise" must not pull a line that says
41
+ # "revised a dissertation". Prime-only; index.STOPWORDS stays as search needs it.
42
+ TASK_WORDS = frozenset(("revise", "revision", "help", "make", "write", "solve",
43
+ "explain", "learn", "study", "practice", "practise", "today",
44
+ "tomorrow", "please", "want", "need", "can", "how", "what",
45
+ "why", "show", "give", "tell", "let", "lets", "get", "use"))
46
+ # Study abbreviations in a prompt -> the long words preference lines use. The match is a
47
+ # substring test, so only expansions of 4+ letters, never the short forms ("os" is in "most").
48
+ ABBREVIATIONS = {
49
+ "dbms": ("database",), "sql": ("database",), "os": ("operating",),
50
+ "oop": ("object", "oriented"), "dsa": ("data structure", "algorithm"),
51
+ "ml": ("machine learning",), "dl": ("deep learning",), "ai": ("artificial intelligence",),
52
+ "cn": ("network",), "dp": ("dynamic programming",), "llm": ("language model",),
53
+ "genai": ("generative",), "nlp": ("language processing",), "js": ("javascript",),
54
+ "py": ("python",)}
55
+ PROFILE_TEMPLATE = "Who I am" # the me/profile.md summary `keepfold init` writes (cli.ME_PAGES)
56
+ # a non-owner server leaves out me/ pages not shared with work (mcp_server.Keepfold._withheld)
57
+ WITHHELD = "withheld: {n} me/ page(s) not shared with this server's role."
58
+
59
+ # ideas-r2 #2: one line, never a gate (forced work before AI help did worse, IZA DP 18338).
60
+ # Its block comes out of the preferences cap, so the prime budget stays the same.
61
+ ATTEMPT_HEAD = "Attempt first"
62
+ ATTEMPT = ("[[{id}]] is {status}: before solving, ask once for their approach (pattern and "
63
+ "complexity) in a sentence or two and grade it with keepfold_grade(item_type="
64
+ "'application', problem='{id}'{concept}); if they say just show me, solve it.")
65
+ _LC_ID = re.compile(r"\blc-\d+\b")
66
+ _LC_URL = re.compile(r"leetcode\.(?:com|cn)/problems/([a-z0-9-]+)")
67
+ _FRONT_FIELD = re.compile(r"""^(title|url):[ \t]*["']?(.*?)["']?[ \t\r]*$""", re.M)
68
+
69
+ # relink's navigation lines (`Up: [[x]]`, `People: [[people]]`, `Topics: [[a]], [[b]]`)
70
+ _NAV_LINE = re.compile(r"\s*\w+:\s*\[\[[^\]]*\]\](?:\s*,\s*\[\[[^\]]*\]\])*\s*")
71
+
72
+
73
+ def _first_paragraph(body: str) -> str:
74
+ """The first paragraph of a note body that is not only headings or navigation links."""
75
+ for para in body.strip().split("\n\n"):
76
+ text = "\n".join(ln for ln in para.splitlines()
77
+ if not ln.lstrip().startswith("#") and not _NAV_LINE.fullmatch(ln))
78
+ if text.strip():
79
+ return text.strip()
80
+ return ""
81
+
82
+
83
+ def _sections(body: str) -> list[str]:
84
+ """Each `## ` section of a note body, heading line included."""
85
+ return [f"## {c}".strip() for c in ("\n" + body).split("\n## ")[1:]]
86
+
87
+
88
+ def me(vault: Vault, id: str):
89
+ """A me/ note, or None if the file does not exist or cannot be parsed."""
90
+ try:
91
+ return vault.read("me", id)
92
+ except VaultError as e:
93
+ if e.code in ("unknown_id", "invalid_argument"): # unparsable: absent, not a failed prime
94
+ return None
95
+ raise
96
+
97
+
98
+ def profile_summary(vault: Vault, today: str, served: dict | None = None,
99
+ held_ids: set[str] = frozenset()) -> str:
100
+ """The `summary:` of me/profile.md, else its first paragraph, without lines past their
101
+ `(until …)` day on local day `today` (agenda 4); "" when absent. The init template's
102
+ summary carries no fact, so its live claim lines stand in for it, less those whose id is
103
+ in `held_ids` (R3-3, `held`). A claim line gets its `served` label (B3: an agent or
104
+ exposed line is ` (ask)`, as in claim_items)."""
105
+ profile = me(vault, "profile")
106
+ summary = str(profile.fields.get("summary") or "").strip() if profile else ""
107
+ if summary == PROFILE_TEMPLATE:
108
+ ids = claim_ids(vault) if held_ids else {}
109
+ text = "\n".join(claims.strip_id(ln) for sec in _sections(profile.body)
110
+ if (head := sec.partition("\n")[0][3:].strip()).lower()
111
+ not in claims.RESERVED
112
+ for ln in sec.splitlines()[1:] if ln.startswith("- ") and ids.get(
113
+ ("profile", head, claims.strip_id(ln)[2:].strip())) not in held_ids)
114
+ else:
115
+ text = summary or (_first_paragraph(profile.body) if profile else "")
116
+ labels = {t: lab for (p, _, t), (lab, _) in (served or {}).items() if p == "profile" and lab}
117
+
118
+ def label(ln: str) -> str:
119
+ lab = labels.get(claims.strip_id(ln)[2:].strip()) if ln.startswith("- ") else None
120
+ return claims.strip_since(claims.strip_id(ln) + lab if lab else ln)
121
+
122
+ # G6: template claim lines are held (`held_ids`) until Keep; free text has no Keep
123
+ return "\n".join(label(ln) for ln in text.splitlines()
124
+ if not claims.expired(ln, today) and (
125
+ summary == PROFILE_TEMPLATE or not claims.unsafe(ln, "profile"))).strip()
126
+
127
+
128
+ def contract(vault: Vault, domains: set, events=None) -> str:
129
+ """me/teaching-contract.md with the overrides of `domains`, cut at CONTRACT_MAX, without
130
+ the lines changed outside Keepfold (R5a, review.outside_lines over `events`, else the log)
131
+ until the owner keeps them."""
132
+ p = vault.root / "me/teaching-contract.md"
133
+ raw = p.read_bytes().decode("utf-8") if p.is_file() else ""
134
+ if raw:
135
+ evs = EventLog(vault).iter_events() if events is None else events
136
+ out = {x["key"] for x in review.outside_lines(vault, evs)
137
+ if x["page"] == "teaching-contract"}
138
+ if out:
139
+ raw = "".join(ln for ln in raw.splitlines(keepends=True)
140
+ if review.line_key("teaching-contract", ln) not in out)
141
+ text = scope_contract(raw, domains)
142
+ if len(text) > CONTRACT_MAX:
143
+ text = text[:CONTRACT_MAX - len(TRUNCATED)].rstrip() + TRUNCATED
144
+ return text
145
+
146
+
147
+ _CORE_HEAD = re.compile(r"##\s+core(\s+rules)?\s*", re.I)
148
+ _RULE = re.compile(r"(\d+[.)]|[-*+])\s+(.*)")
149
+ _SENTENCE_END = re.compile(r"(?<=[.!?])\s")
150
+
151
+
152
+ def contract_core(text: str) -> list[str]:
153
+ """CONSENSUS item 3: the contract's rules, not its title or preamble. The lines of a
154
+ `## Core rules` (or `## Core`) section if there is one, else each top-level numbered or
155
+ bulleted rule's lead (its leading bold text, else its first sentence), in order."""
156
+ lines = text.splitlines()
157
+ if lines and lines[0].strip() == "---": # frontmatter
158
+ end = next((i for i, ln in enumerate(lines[1:], 1) if ln.strip() == "---"), 0)
159
+ lines = lines[end + 1:]
160
+ at = next((i for i, ln in enumerate(lines) if _CORE_HEAD.fullmatch(ln.rstrip())), None)
161
+ if at is not None:
162
+ out = []
163
+ for ln in lines[at + 1:]:
164
+ if ln.startswith("#"):
165
+ break
166
+ if ln.strip():
167
+ out.append(ln.rstrip())
168
+ return out
169
+ out = []
170
+ for ln in lines:
171
+ if not (m := _RULE.fullmatch(ln.rstrip())): # indented lines are sub-points
172
+ continue
173
+ body = m.group(2)
174
+ bold = re.match(r"\*\*(.+?)\*\*", body)
175
+ lead = bold.group(0) if bold else _SENTENCE_END.split(body, maxsplit=1)[0]
176
+ out.append(f"{m.group(1)} {lead}")
177
+ return out
178
+
179
+
180
+ def served_claims(vault: Vault, events: list[dict], rows: list[dict] | None = None) -> dict:
181
+ """PHASE3 H3: {(page, section, text): (label, score)} for each live claim, by tier alone.
182
+ The user's own lines (typed, legacy, confirmed) are served plain; (ask) for agent or
183
+ exposed, or a yes the model relayed from claims.RELAYED_FROM, ranked below plain lines.
184
+ `rows`: claims.tiers' result when the caller has it."""
185
+ out = {}
186
+ for r in claims.tiers(vault, events) if rows is None else rows:
187
+ ask = claims.late_relay(r) or r["tier"] in ("agent", "exposed")
188
+ out[r["page"], r["section"], r["text"]] = (" (ask)" if ask else "",
189
+ 0.5 * (ASK_WEIGHT if ask else 1))
190
+ return out
191
+
192
+
193
+ def held(vault: Vault, events, today: str) -> set[str]:
194
+ """The `^c-…` ids of lines held back while a Review card waits. R3-3: the older line of
195
+ each recorded pair (claims.recorded_pairs: `update_of`, `supersedes`), both lines live on
196
+ non-private pages; prime and keepfold_context serve only the newer line until the user keeps
197
+ both or one. G6: every line review.unsafe_lines flags, until Keep. R5a: every line
198
+ review.outside_lines finds (changed outside Keepfold) until Keep, by its claim id and by its
199
+ card key (`me/setup` lines that are no claim, `claim_items`). Every serving path (prime,
200
+ keepfold_context, the delta, packs and rules files, Chat's About block) mutes these.
201
+ Derived from events at read time; nothing stored."""
202
+ events = list(events)
203
+ out = {xray.claim(x["id"]) for x in review.unsafe_lines(vault, events)}
204
+ for x in review.outside_lines(vault, events):
205
+ out.add(x["key"])
206
+ if x["id"]:
207
+ out.add(xray.claim(x["id"]))
208
+ pairs, _ = claims.recorded_pairs(events)
209
+ if not pairs:
210
+ return out
211
+ hidden = {n.id for n in vault.iter_notes("me") if is_private(n)}
212
+ live = {(r["page"], r["id"]) for r in claims.rows(vault)
213
+ if claims.is_live(r, today) and r["page"] not in hidden}
214
+ return out | {xray.claim(old[1]) for old, new, _ in pairs.values()
215
+ if old in live and new in live}
216
+
217
+
218
+ def _app(name) -> str:
219
+ """An AI app's name as profiles.norm compares it."""
220
+ return re.sub(r"[^a-z0-9]", "", str(name or "").lower())
221
+
222
+
223
+ def cross_app(vault: Vault, events, client: str | None, rows: list[dict] | None = None
224
+ ) -> set[str]:
225
+ """R5d: the `^c-…` ids of the inferred about-me lines (tier agent or exposed) written in a
226
+ session of another AI app than `client`: the session's `open` event names its app
227
+ (session.py, the MCP handshake). An unknown `client` (None, "") gets none of them; a line
228
+ whose session names no app (an old one, a harvest from imports) is served as before. The
229
+ owner's Still true or Approve (tier confirmed) ends the hold. `rows`: claims.tiers'."""
230
+ events = list(events)
231
+ apps = {e.get("session"): _app(e["payload"].get("client")) for e in events
232
+ if e.get("kind") == "open" and isinstance(e.get("payload"), dict)
233
+ and e["payload"].get("client")}
234
+ if not apps:
235
+ return set()
236
+ me = _app(client)
237
+ return {xray.claim(r["id"]) for r in (claims.tiers(vault, events) if rows is None else rows)
238
+ if r["tier"] in ("agent", "exposed") and r["session"] in apps
239
+ and (not me or apps[r["session"]] != me)}
240
+
241
+
242
+ def claim_ids(vault: Vault) -> dict:
243
+ """{(page, section, text): `^c-…`} for every claim line (xray's claim id form)."""
244
+ return {(r["page"], r["section"], r["text"]): xray.claim(r["id"]) for r in claims.rows(vault)}
245
+
246
+
247
+ def claim_items(vault: Vault, page: str, keep, served: dict, today: str, ids: dict | None = None,
248
+ mute: set[str] = frozenset(), use: dict | None = None) -> list[tuple]:
249
+ """Per kept `## ` section of me/<page> (heading line, other lines, [(score, labelled list
250
+ line, labelled?, `^c-…` id or None)] best first, ties by `use` (`use_order`), then newest
251
+ first); never `## Past`, `## Not me`, a line whose own `(until …)` day is before `today`
252
+ (agenda 4) or one whose id (`ids`) is muted. Lines lose their `(since …)` stamp (R13a). On
253
+ a review.GUARDED page a heading or line whose card key is muted (R5a) is left out."""
254
+ note = me(vault, page)
255
+ out = []
256
+ guarded = page in review.GUARDED and mute
257
+ for sec in _sections(note.body if note else ""):
258
+ head, _, rest = sec.partition("\n")
259
+ name = head[3:].strip().lower()
260
+ lines = [ln.rstrip() for ln in rest.splitlines() if ln.strip()]
261
+ if guarded:
262
+ if review.line_key(page, head) in mute:
263
+ continue
264
+ lines = [ln for ln in lines if review.line_key(page, ln) not in mute]
265
+ if lines and name not in claims.RESERVED and keep(name):
266
+ items = []
267
+ for ln in reversed([ln for ln in lines if ln.startswith("- ")
268
+ and not claims.expired(claims.strip_id(ln), today)]):
269
+ key = (page, head[3:].strip(), claims.strip_id(ln)[2:].strip())
270
+ cid = (ids or {}).get(key)
271
+ if cid in mute:
272
+ continue
273
+ label, score = served.get(key, ("", 0.5))
274
+ items.append((score, claims.strip_since(claims.strip_id(ln)) + label,
275
+ bool(label), cid))
276
+ # stable: ties stay newest first
277
+ items.sort(key=lambda x: (-x[0], -(use or {}).get(x[3], 0)))
278
+ out.append((head, [ln for ln in lines if not ln.startswith("- ")], items))
279
+ return out
280
+
281
+
282
+ def putter(parts: list[str], left: list[int]):
283
+ """A `put(head, text, id, cap, tail)` that appends a wrapped block to `parts`, within `cap`
284
+ and the remaining budget `left[0]`; `tail` (a `more` line) follows the wrapped text,
285
+ outside the note, since it is Keepfold's own word."""
286
+ def put(head: str, text: str, id: str | None = None, cap: int = CONTEXT_MAX,
287
+ tail: str = "") -> None:
288
+ while True: # trim until the wrapped block fits (escaping can lengthen the text)
289
+ block = f"## {head}\n" + (_wrap(id, text) if id else text) + (
290
+ f"\n{tail}" if tail else "")
291
+ over = len(block) - min(cap, left[0])
292
+ if over <= 0:
293
+ break
294
+ if len(text) - over < 40:
295
+ return
296
+ text = text[: len(text) - over - 1].rstrip() + "…"
297
+ parts.append(block)
298
+ left[0] -= len(block) + 2
299
+ return put
300
+
301
+
302
+ def fit(lines: list[str], id: str, cap: int, left: int, what: str = "") -> list[str]:
303
+ """`lines` minus the last ones until their wrapped block fits `cap` and `left`. With
304
+ `what` (a MORE key) and lines cut, room is kept for the `more` line saying so (RR-13)."""
305
+ keep, room = list(lines), 0
306
+ while keep and len(_wrap(id, "\n".join(keep))) + 40 + room > min(cap, left):
307
+ keep.pop() # 40: room for the "## <head>\n" line
308
+ if what and not room:
309
+ room = len(more(len(lines), what)) + 1 # n has at most this many digits
310
+ return keep
311
+
312
+
313
+ # RR-13: the line after a block fit() cut, naming the call that reads the rest
314
+ MORE = {"preference": "keepfold_context(scope='all')",
315
+ "contract": "keepfold_read(id='me/teaching-contract')",
316
+ "related": "keepfold_recall(query=<the message>)",
317
+ "mistake": "keepfold_context(topic=<the topic>)"}
318
+
319
+
320
+ def more(n: int, what: str) -> str:
321
+ """`(+N more <what> lines: <call> reads them)`, or "" when nothing was cut."""
322
+ return f"(+{n} more {what} lines: {MORE[what]} reads them)" if n > 0 else ""
323
+
324
+
325
+ # G4: playbooks (notes tagged `playbook`) the prompt matches, out of the Related budget
326
+ PRIME_PLAYBOOKS, PLAYBOOK_TAG, PLAYBOOK_SUMMARY = 2, "playbook", 60
327
+ PLAYBOOK_SAYS = ("Follow it for this task (keepfold_read it first); if the user corrects how, "
328
+ "keepfold_patch that playbook.")
329
+ # a playbook file changed this long after the last write Keepfold logged on it: the owner edited it
330
+ OWNER_EDIT_SLACK = 2
331
+
332
+
333
+ def playbooks(vault: Vault, prompt: str, hits: list[dict], notes: dict, mute: set[str],
334
+ scopes, evs: list[dict]) -> list[tuple[str, str]]:
335
+ """G4: [(id, "- [[id]] title: summary")] of the playbooks (`note` pages tagged
336
+ `playbook`) the prompt matches, best first: recall `hits`, then by the content words
337
+ (pref_rows' terms) their title and summary share. `notes` ({id: {kind, title, fields}},
338
+ as the index holds them) holds no private page; a muted one, or one whose `scope` the
339
+ client's `scopes` (None: all) lack, is out, and so is each `withheld_playbooks` one (R5b:
340
+ an agent's until the owner confirms it). keepfold_prime and the prime hook's later-turn
341
+ delta (keepfold.delta.playbooks) both select with this."""
342
+ words = re.findall(r"\w+", prompt.lower())
343
+ terms = {t for t in words if len(t) > 2 and t not in STOPWORDS
344
+ and t not in TASK_WORDS}
345
+ terms |= {x for w in words for x in ABBREVIATIONS.get(w, ())}
346
+ rank = {h["id"]: n for n, h in enumerate(hits) if h.get("match") != "linked"}
347
+ found = []
348
+ for i, n in notes.items():
349
+ f, tags = n["fields"], n["fields"].get("tags")
350
+ if (n["kind"] != "note" or i in mute or PLAYBOOK_TAG not in (
351
+ tags if isinstance(tags, list) else [tags])):
352
+ continue
353
+ if not access.scope_own(scopes, f.get("scope")):
354
+ continue
355
+ summary = render.plain(str(f.get("summary") or ""), PLAYBOOK_SUMMARY)
356
+ shared = sum(t in f"{n['title']} {summary}".lower() for t in terms)
357
+ if i in rank or shared:
358
+ found.append((rank.get(i, len(rank)), -shared, i, n["title"], summary))
359
+ found.sort()
360
+ out = withheld_playbooks(vault, {x[2] for x in found}, evs)
361
+ return [(i, f"- [[{i}]] {title}" + (f": {summary}" if summary else ""))
362
+ for _, _, i, title, summary in found if i not in out]
363
+
364
+
365
+ def withheld_playbooks(vault: Vault, ids: set[str], evs: list[dict]) -> set[str]:
366
+ """R5b: the playbooks of `ids` prime does not serve: one an agent wrote that the owner has
367
+ not confirmed (`unconfirmed_notes`; served "(ask)" before R5b, but an AI app follows a
368
+ playbook's steps all the same), and one written through Keepfold (a logged write) whose
369
+ title, summary or text claims.unsafe flags, as an about-me line (links pass: a playbook
370
+ may name a docs page). A page with no logged write is the owner's own and is not checked."""
371
+ out = unconfirmed_notes(vault, ids, evs)
372
+ logged = set()
373
+ for e in evs:
374
+ pl = e.get("payload") if e.get("kind") == "change" else None
375
+ c = pl.get("change") if isinstance(pl, dict) else None
376
+ if isinstance(c, dict) and c.get("kind") == "note" and c.get("id") in ids:
377
+ logged.add(c["id"])
378
+ for i in sorted(logged - out):
379
+ try:
380
+ n = vault.read("note", i)
381
+ except VaultError:
382
+ out.add(i)
383
+ continue
384
+ if claims.unsafe(f"{n.fields.get('title') or ''}\n{n.fields.get('summary') or ''}\n"
385
+ f"{n.body}"):
386
+ out.add(i)
387
+ return out
388
+
389
+
390
+ def unconfirmed_notes(vault: Vault, ids: set[str], evs: list[dict]) -> set[str]:
391
+ """G4: which of the note `ids` an agent wrote and the owner has not confirmed: the last
392
+ write Keepfold logged on the page (its `keepfold_add`, or a `keepfold_patch` with its `tier`
393
+ as for claims) is not the owner's (`confirmed`, or `clicked` in the app), and the file
394
+ has not changed since. A page with no logged write is the owner's own; filing it under
395
+ a topic (`set_topics`) is no write about its content."""
396
+ last, at = {}, {}
397
+ for e in evs:
398
+ pl = e.get("payload") if e.get("kind") == "change" else None
399
+ c = pl.get("change") if isinstance(pl, dict) else None
400
+ if isinstance(c, dict) and c.get("kind") == "note" and c.get("id") in ids:
401
+ at[c["id"]] = e.get("ts")
402
+ if c.get("op") != "set_topics":
403
+ last[c["id"]] = c
404
+ out = set()
405
+ for i, c in last.items():
406
+ if c.get("tier") == "confirmed" or c.get("confirm") == "clicked":
407
+ continue
408
+ ts = at[i]
409
+ try: # shortcut: any later write Keepfold did not log (a relink) reads as the owner's
410
+ # edit; record a hash with each write if that ever matters
411
+ edited = vault.path_for("note", i).stat().st_mtime > datetime.strptime(
412
+ ts, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC).timestamp() + OWNER_EDIT_SLACK
413
+ except (OSError, TypeError, ValueError):
414
+ edited = False
415
+ if not edited:
416
+ out.add(i)
417
+ return out
418
+
419
+
420
+ def named_problem(vault: Vault, prompt: str):
421
+ """ideas-r2 #2: the `todo` or `attempted` problem note the prompt names by id (`lc-<n>`),
422
+ LeetCode URL slug or title (2+ words; the longest match wins), else None. It regex-reads
423
+ each front matter and parses only the match: YAML-parsing ~300 problems takes seconds,
424
+ past the prime hook's budget."""
425
+ low = prompt.lower()
426
+ ids, slugs = set(_LC_ID.findall(low)), set(_LC_URL.findall(low))
427
+ folder = vault.root / Vault.KIND_DIRS["problem"]
428
+ best, rank = None, 0
429
+ for path in sorted(folder.glob("*.md")) if folder.is_dir() else []:
430
+ try:
431
+ front = path.read_text(encoding="utf-8").split("\n---", 1)[0]
432
+ except (OSError, UnicodeDecodeError):
433
+ continue
434
+ f = dict(_FRONT_FIELD.findall(front))
435
+ title = f.get("title", "").strip().lower()
436
+ r = (10_000 if path.stem in ids else
437
+ 5_000 if set(_LC_URL.findall(f.get("url", "").lower())) & slugs else
438
+ len(title) if len(title.split()) > 1 and re.search(
439
+ rf"(?<!\w){re.escape(title)}(?!\w)", low) else 0)
440
+ if r > rank:
441
+ best, rank = path.stem, r
442
+ try:
443
+ note = vault.read("problem", best) if best else None
444
+ except VaultError:
445
+ return None
446
+ return note if note and note.fields.get("status") in ("todo", "attempted") \
447
+ and not is_private(note) else None
448
+
449
+
450
+ def attempt_line(note) -> str:
451
+ """The Attempt first line for a named problem note (ids and status only, no note text)."""
452
+ cs = _edge_targets(note.fields.get("concepts") or [])
453
+ concept = f", concept='{cs[0]}'" if cs and ID_RE.fullmatch(cs[0]) else ""
454
+ return ATTEMPT.format(id=note.id, status=note.fields["status"], concept=concept)
455
+
456
+
457
+ def core_lines(vault: Vault, served: dict, today: str,
458
+ withheld: set[str] = frozenset(), ids: dict | None = None,
459
+ mute: set[str] = frozenset()) -> list[str]:
460
+ """me/core.md's live lines the user wrote or confirmed (the ones `served` labels plain),
461
+ verbatim (claim id and `(since …)` stripped) in page order, as many whole lines as fit
462
+ CORE_MAX; [] with no
463
+ page, a withheld or private page. Agent, exposed or relayed lines are never pinned, and a
464
+ line whose id (`ids`) is muted in the X-ray is left out."""
465
+ note = None if "core" in withheld else me(vault, "core")
466
+ if note is None or is_private(note):
467
+ return []
468
+ out, size = [], 0
469
+ for (page, sec, text), (label, _) in served.items():
470
+ line = f"- {claims.strip_since(text)}"
471
+ if page != "core" or label or claims.expired(text, today) or (
472
+ ids or {}).get((page, sec, text)) in mute:
473
+ continue
474
+ if size + bool(out) + len(line) <= CORE_MAX: # a line that does not fit is dropped whole
475
+ size += bool(out) + len(line)
476
+ out.append(line)
477
+ return out
478
+
479
+
480
+ _VECS: dict = {} # line text -> unit vector, from the embedder in _VECS_OF[0]
481
+ _VECS_OF: list = [None]
482
+
483
+
484
+ def similarity(prompt: str, texts: list[str]) -> list[float] | None:
485
+ """Cosine of `prompt` to each of `texts` with the bge embedder, only if this process has it
486
+ loaded already (the MCP server's warm-up): it never imports keepfold.semantic, so the prime
487
+ hook stays light, and never loads a model. None when it is not warm or fails."""
488
+ sem = sys.modules.get("keepfold.semantic")
489
+ embed = getattr(sem, "_embedder", None)
490
+ if embed is None:
491
+ return None
492
+ try:
493
+ if _VECS_OF[0] is not embed or len(_VECS) > VEC_CACHE:
494
+ _VECS.clear()
495
+ _VECS_OF[0] = embed
496
+ if new := [t for t in dict.fromkeys(texts) if t not in _VECS]:
497
+ _VECS.update(zip(new, sem._embed(embed, new), strict=True))
498
+ q = sem._embed(embed, [sem.QUERY_PREFIX + prompt])[0]
499
+ return [float(_VECS[t] @ q) for t in texts]
500
+ except Exception: # a model error must never cost the prime: word overlap serves
501
+ return None
502
+
503
+
504
+ def pref_rows(vault: Vault, prompt: str, served: dict, today: str, pinned: list[str],
505
+ withheld: set[str] = frozenset(), allow=None, ids: dict | None = None,
506
+ xs: dict | None = None, back: dict | None = None,
507
+ use: dict | None = None) -> list[list]:
508
+ """The preference, setup and personality lines as prime ranks them for `prompt`, best first:
509
+ [-match, situational?, -served score, "- [Section] line", labelled?, "Section: text", id].
510
+ Never a `pinned` line again, a `withheld` page, a section `allow(page, heading)` (an
511
+ agent profile, access.scope_section) refuses, or an X-ray muted claim; X-ray pins lead.
512
+ `ids` (claim_ids) and `xs` (xray.settings) are read when not given. R13b: of lines that
513
+ rank equal, the one that came back latest (`back`: `^c-…` id -> review.reinforced's last
514
+ day) goes first, and one that never came back after it; G5b-4: then, inside a section, the
515
+ more used (`use`: `use_order`)."""
516
+ ids = claim_ids(vault) if ids is None else ids
517
+ xs = xray.settings(vault) if xs is None else xs
518
+ words = re.findall(r"\w+", prompt.lower())
519
+ terms = {t for t in words if len(t) > 2 and t not in STOPWORDS and t not in TASK_WORDS}
520
+ terms |= {x for w in words for x in ABBREVIATIONS.get(w, ())}
521
+ rows = [] # [-prompt match, situational?, -served score, line, labelled, text, id]; stable
522
+ seen = {claims.norm(ln) for ln in pinned} # a pinned line is not repeated
523
+ for page, keep in (("preferences", lambda h: True), ("setup", lambda h: True),
524
+ ("personality", lambda h: h in PERSONALITY_HEADINGS["all"])):
525
+ if page in withheld:
526
+ continue
527
+ ok = keep if allow is None else (lambda h, k=keep, p=page: k(h) and allow(p, h))
528
+ for head, _, items in claim_items(vault, page, ok, served, today, ids, xs["mute"], use):
529
+ name = head[3:].strip()
530
+ for score, line, lab, cid in items: # a section name match counts (my presentation)
531
+ bare = line[2:].removesuffix(" (ask)")
532
+ if claims.norm(bare) in seen:
533
+ continue
534
+ text = f"{name} {line}".lower()
535
+ rows.append([-sum(t in text for t in terms),
536
+ name.lower() not in GENERAL_SECTIONS, -score,
537
+ f"- [{name}] {line[2:]}", lab, f"{name}: {bare}", cid])
538
+ # by meaning when this process's embedder is warm: cosine times the tier weight, a line
539
+ # under semantic.MIN_COS counting as no match; else by the prompt words a line shares
540
+ if rows and (sims := similarity(prompt, [r[5] for r in rows])) is not None:
541
+ floor = sys.modules["keepfold.semantic"].MIN_COS
542
+ for r, s in zip(rows, sims, strict=True):
543
+ r[0] = s * r[2] / 0.5 if s >= floor else 0 # r[2] / 0.5: -1, or -ASK_WEIGHT
544
+ for r in rows: # the owner's X-ray pins lead, still within the preferences cap
545
+ if r[6] in xs["pin"]:
546
+ r[0] = float("-inf")
547
+ if back: # stable sorts: ties stay as they were unless a line came back
548
+ rows.sort(key=lambda r: back.get(r[6], ""), reverse=True)
549
+ rows.sort(key=lambda r: r[:3])
550
+ return rows
551
+
552
+
553
+ def use_order(vault: Vault, events, today: str, known: dict | None = None,
554
+ back: dict | None = None) -> dict[str, int]:
555
+ """G5b-4: {`^c-…` id: use bucket}: the log2 of how often a line was used before `today`
556
+ (review.use; `back`: its `reinforced` fold when the caller has it), so the calls of one day
557
+ leave prime's order as it was that morning."""
558
+ return {xray.claim(c): x["n"].bit_length()
559
+ for c, x in review.use(vault, events, today, known, back).items()}
560
+
561
+
562
+ def core(vault: Vault, prompt: str, events: list[dict], now: datetime,
563
+ withheld: set[str] = frozenset(), xr: dict | None = None, allow=None,
564
+ client: str | None = None) -> tuple[list[str], list[int]]:
565
+ """keepfold_prime's blocks before Related, and the budget left: (parts, [chars left]).
566
+ Order: Core, Profile, Teaching contract (core), the legend, Preferences (the owner's
567
+ standing text), then the prompt's Attempt first line.
568
+ `withheld`: bare ids of me/ pages left out (a non-owner server or an agent profile);
569
+ `allow(page, heading)`: the preference and personality sections an agent profile allows
570
+ (None: all). The X-ray's pinned claims lead Preferences and muted ones are left out; `xr`,
571
+ if given, gets the `served` and `trimmed` ids by block (keepfold.xray). `client`: the AI app
572
+ asking (R5d, `cross_app`; None: not known)."""
573
+ prompt = prompt[:PRIME_PROMPT]
574
+ parts: list[str] = []
575
+ left = [PRIME_MAX]
576
+ put = putter(parts, left)
577
+ rows = claims.tiers(vault, events)
578
+ served = served_claims(vault, events, rows)
579
+ xs, ids = xray.settings(vault), claim_ids(vault)
580
+ # R3-3: as muted while its pair waits; R5d: another app's guesses until the owner's yes
581
+ waits = held(vault, events, local_day(now)) | cross_app(vault, events, client, rows)
582
+ xs = {**xs, "mute": xs["mute"] | waits}
583
+ if pinned := core_lines(vault, served, local_day(now), withheld, ids, xs["mute"]):
584
+ put(CORE_HEAD, "\n".join(pinned), "me/core", PRIME_MAX) # first and whole, never shrunk
585
+ # the core is the user's own pick of preferences, so it comes out of their cap
586
+ pref_cap = max(0, PRIME_CAPS["preferences"] - (PRIME_MAX - left[0]))
587
+ summary = "" if "profile" in withheld else profile_summary(vault, local_day(now), served,
588
+ waits)
589
+ if summary:
590
+ put("Profile", summary, "me/profile", PRIME_CAPS["profile"])
591
+ if "teaching-contract" not in withheld and (rules := contract_core(contract(vault, set(),
592
+ events))):
593
+ # whole rules that fit, else the first one cut by put
594
+ lines = fit(rules, "me/teaching-contract", PRIME_CAPS["contract"], left[0],
595
+ "contract") or rules[:1]
596
+ put("Teaching contract (core)", "\n".join(lines), "me/teaching-contract",
597
+ PRIME_CAPS["contract"], more(len(rules) - len(lines), "contract"))
598
+ known = review.known_texts(vault)
599
+ again = review.reinforced(events, known) # once per prompt: R13b's `back` and the use order
600
+ back = {xray.claim(c): x["last"] for c, x in again.items()}
601
+ rows = pref_rows(vault, prompt, served, local_day(now), pinned, withheld, allow,
602
+ ids, xs, back, use_order(vault, events, local_day(now), known, again))
603
+ # the prompt's Attempt first line follows Preferences (the owner's standing text first, so
604
+ # it stays the same from chat to chat) and still comes out of the preferences cap
605
+ problem = named_problem(vault, prompt)
606
+ attempt = attempt_line(problem) if problem else ""
607
+ cap = pref_cap - (len(f"## {ATTEMPT_HEAD}\n{attempt}") + 2 if attempt else 0)
608
+ # the legend only when an (ask) line can be served: the Preferences fit below has no more
609
+ # room than this one, so it serves a prefix of these lines
610
+ asks = {r[3] for r in rows if r[4]}
611
+ shown = fit([r[3] for r in rows], "me", cap, left[0])
612
+ if asks.intersection(shown) or " (ask)" in summary:
613
+ put("How to read the claims", LEGEND)
614
+ if prefs := fit([r[3] for r in rows], "me", cap, left[0], "preference"):
615
+ put("Preferences", "\n".join(prefs), "me", cap,
616
+ more(len(rows) - len(prefs), "preference"))
617
+ elif n := len(withheld & {"preferences", "personality"}):
618
+ put("Preferences", WITHHELD.format(n=n)) # no "not recorded" nag: /keepfold home asks
619
+ if attempt:
620
+ put(ATTEMPT_HEAD, attempt)
621
+ if xr is not None:
622
+ heads = {b.split("\n", 1)[0][3:] for b in parts}
623
+ xr["served"] = {"core": [c for (p, _, t), c in ids.items()
624
+ if p == "core" and f"- {claims.strip_since(t)}" in pinned],
625
+ "profile": ["me/profile"] * ("Profile" in heads),
626
+ "preferences": [r[6] for r in rows[:len(prefs)] if r[6]],
627
+ "contract": ["me/teaching-contract"] * (
628
+ "Teaching contract (core)" in heads)}
629
+ xr["trimmed"] = {"preferences": [r[6] for r in rows[len(prefs):] if r[6]]}
630
+ return parts, left