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/where.py ADDED
@@ -0,0 +1,119 @@
1
+ """FW: keepfold_find's `where`, frontmatter filters such as `status=open tags=dsa due<=2026-12-01`.
2
+
3
+ `parse(text)` turns up to MAX_CLAUSES `field op value` clauses into (field, op, value) tuples
4
+ (field casefolded), raising invalid_argument; `match(clauses, fields)` is true when every clause
5
+ passes on a page's frontmatter (index `_plain` form). Pure: no vault, no index."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import re
11
+
12
+ from keepfold.vault import invalid
13
+
14
+ MAX_CLAUSES = 6
15
+ OPS = ("!=", "<=", ">=", "=", "<", ">", "~")
16
+ EXAMPLE = "for example where='status=open tags=dsa due<=2026-12-01 title~\"binary search\"'"
17
+ _CLAUSE = re.compile(r'([\w-]+)(!=|<=|>=|=|<|>|~)("[^"]*"|[^\s"]*)')
18
+ _LINK = re.compile(r"^\[\[([^\]|#^]+)(?:[|#^][^\]]*)?\]\]$")
19
+ _DAY = re.compile(r"^\d{4}-\d{2}-\d{2}(?:$|[T ])")
20
+ _NUM = re.compile(r"^-?\d+(?:\.\d+)?$")
21
+
22
+
23
+ def _bad(why: str) -> Exception:
24
+ return invalid(f"where: {why}; clauses are field, operator, value with no spaces "
25
+ f"(operators {' '.join(OPS)}; quote a value with spaces), {EXAMPLE}.")
26
+
27
+
28
+ def parse(text) -> list[tuple[str, str, str]]:
29
+ if not isinstance(text, str) or not text.strip():
30
+ raise _bad("it is blank")
31
+ out, pos, n = [], 0, len(text)
32
+ while True:
33
+ while pos < n and text[pos].isspace():
34
+ pos += 1
35
+ if pos >= n:
36
+ break
37
+ tok = text[pos:].split(None, 1)[0]
38
+ m = _CLAUSE.match(text, pos)
39
+ if not m:
40
+ raise _bad(f"'{tok}' has no operator" if not re.search(r"[=!<>~]", tok)
41
+ else f"'{tok}' has an unknown operator or no field")
42
+ field, op, value = m.groups()
43
+ end = m.end()
44
+ if value.startswith('"'):
45
+ value = value[1:-1]
46
+ elif value[:1] in ("=", "!", "<", ">", "~"): # ==, =>, <>, =~ and the like
47
+ raise _bad(f"'{tok}' has an unknown operator")
48
+ if end < n and not text[end].isspace():
49
+ raise _bad(f"'{tok}' has an unbalanced quote" if '"' in text[pos:end + 1]
50
+ else f"'{tok}' has an unknown operator")
51
+ if not value.strip():
52
+ raise _bad(f"'{tok}' has no value")
53
+ out.append((field.casefold(), op, value))
54
+ if len(out) > MAX_CLAUSES:
55
+ raise _bad(f"at most {MAX_CLAUSES} clauses")
56
+ pos = end
57
+ return out
58
+
59
+
60
+ def _norm(v) -> str:
61
+ """Casefolded and stripped; a `[[id]]` or `[[id|label]]` link compares as its bare id."""
62
+ s = str(v).strip()
63
+ if m := _LINK.match(s):
64
+ s = m.group(1).strip()
65
+ return s.casefold()
66
+
67
+
68
+ @functools.lru_cache(maxsize=256)
69
+ def _value(b: str) -> tuple[str, str | None, float | None]:
70
+ """A clause value once per call, not once per page: its _norm, day and number."""
71
+ t = b.strip()
72
+ return _norm(b), t[:10] if _DAY.match(t) else None, float(t) if _NUM.match(t) else None
73
+
74
+
75
+ def _order(a, b: str) -> tuple | None:
76
+ """Both days (a timestamp by its first 10 characters) or both numbers, else None."""
77
+ _, day, num = _value(b)
78
+ if day is not None and isinstance(a, str) and _DAY.match(a.strip()):
79
+ return a.strip()[:10], day
80
+ if num is None or isinstance(a, bool):
81
+ return None
82
+ if isinstance(a, (int, float)) or isinstance(a, str) and _NUM.match(a.strip()):
83
+ return float(a), num
84
+ return None
85
+
86
+
87
+ def _one(op: str, field, value: str) -> bool:
88
+ if op == "~":
89
+ return _value(value)[0] in _norm(field)
90
+ if op in ("=", "!="): # two days or two numbers compare as such: 4 = 4.0
91
+ same = _norm(field) == _value(value)[0] or (
92
+ (pair := _order(field, value)) is not None and pair[0] == pair[1])
93
+ return same == (op == "=")
94
+ pair = _order(field, value)
95
+ if pair is None:
96
+ return False # no string ordering: "10" < "9" would surprise
97
+ a, b = pair
98
+ return {"<": a < b, "<=": a <= b, ">": a > b, ">=": a >= b}[op]
99
+
100
+
101
+ def match(clauses, fields: dict) -> bool:
102
+ if not clauses:
103
+ return True
104
+ for key, op, value in clauses:
105
+ v = fields.get(key)
106
+ if v is None and key not in fields: # keys compare in any case
107
+ v = next((x for k, x in fields.items() if str(k).casefold() == key), None)
108
+ if v is None:
109
+ if op != "!=":
110
+ return False
111
+ continue
112
+ items = v if isinstance(v, list) else [v]
113
+ if op == "!=":
114
+ ok = all(_one("!=", x, value) for x in items) # none equals
115
+ else:
116
+ ok = any(_one(op, x, value) for x in items)
117
+ if not ok:
118
+ return False
119
+ return True
keepfold/xray.py ADDED
@@ -0,0 +1,516 @@
1
+ """Agent X-ray (v9 plan item 6, D5): what keepfold_prime and keepfold_context served each AI app,
2
+ and the owner's Pin and Mute. R27b: also what keepfold_find, keepfold_recall and keepfold_read
3
+ returned, a broad-read flag, a pasted reply traced to the served items, two apps compared.
4
+
5
+ `.keepfold/xray.jsonl` (tool-private, gitignored, never an event): the last CAP calls, and apart
6
+ the last READ_CAP find, recall and read calls, one row each `{ts, tool, client, served:
7
+ {block: [ids]}, trimmed: {block: [ids]}, chars}`. Ids and counts only, never text, the prompt,
8
+ the query or a pasted reply. A page is its bare id (`me/profile` for a me/ page), a me/ claim
9
+ is `^c-…`.
10
+
11
+ `.keepfold/xray.json`: the owner's settings `{"pin": [ids], "mute": [ids], "ack": {client: ts}}`,
12
+ same id forms; `ack` holds the end of each app's broad-read window the owner said Got it to.
13
+ Only the Keepfold app's own clicks set them (app.server); no MCP tool takes them. Pinned pages
14
+ lead prime's Related and pinned claims lead its Preferences; a muted id is never served by
15
+ prime or context. Stdlib and keepfold.vault only at import, so the prime hook stays light.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import json
22
+ import logging
23
+ import math
24
+ import re
25
+ from collections import Counter
26
+ from datetime import UTC, datetime, timedelta
27
+
28
+ from keepfold.vault import ID_RE, Vault, VaultError, is_private
29
+
30
+ log = logging.getLogger(__name__)
31
+ _CLAIM = re.compile(r"\^c-[a-z2-7]{5}")
32
+
33
+ RING = ".keepfold/xray.jsonl"
34
+ SETTINGS = ".keepfold/xray.json"
35
+ CAP = 500 # calls kept, find, recall and read apart (READ_CAP)
36
+ LOCK_S = 0.2 # a busy vault skips the row rather than slow the tool call
37
+ # R27b: what an app pulls itself, kept apart up to READ_CAP so a busy agent's searches never
38
+ # push the prime, context, chat-turn, hook and resource rows (review's crowded, unused and use
39
+ # folds read them) out of the ring
40
+ READS = ("keepfold_find", "keepfold_recall", "keepfold_read")
41
+ READ_CAP = 1000
42
+ _READ_ROW = re.compile(r'\{"ts":"[^"]*","tool":"keepfold_(?:find|recall|read)"')
43
+ # the broad-read flag: over WIDE_PAGES distinct pages through READS within WIDE_MINUTES. A
44
+ # chat's few finds (8 hits each), a recall and some reads come to 10-30 pages; over 50 in a
45
+ # quarter hour is a dump, or an app reading on its own
46
+ WIDE_PAGES = 50
47
+ WIDE_MINUTES = 15
48
+ WIDE_DAYS = 7 # the windows looked at: the last week's
49
+ TS = "%Y-%m-%dT%H:%M:%SZ"
50
+
51
+
52
+ def claim(cid: str) -> str:
53
+ return f"^{cid}"
54
+
55
+
56
+ def record(vault: Vault, tool: str, client: str | None, served: dict, trimmed: dict,
57
+ chars: int) -> None:
58
+ """Append one call row, best effort: any error is logged and swallowed."""
59
+ try:
60
+ row = {"ts": datetime.now(UTC).strftime(TS), "tool": tool,
61
+ "client": client or "unknown",
62
+ "served": {k: list(v) for k, v in served.items() if v},
63
+ "trimmed": {k: list(v) for k, v in trimmed.items() if v}, "chars": int(chars)}
64
+ path = vault.root / RING
65
+ with vault.lock(LOCK_S): # the lock creates .keepfold/
66
+ old = path.read_text("utf-8").splitlines() if path.is_file() else []
67
+ vault.write_text(path, "\n".join(_trim([*old, json.dumps(
68
+ row, separators=(",", ":"))])) + "\n")
69
+ except Exception as e: # noqa: BLE001 (a view of the past: never fail the tool over it)
70
+ log.warning("x-ray row not written: %s", e)
71
+
72
+
73
+ def _trim(lines: list[str]) -> list[str]:
74
+ """The last READ_CAP find, recall and read rows and the last CAP others, in order."""
75
+ read = [bool(_READ_ROW.match(x)) for x in lines]
76
+ drop = {True: sum(read) - READ_CAP, False: len(lines) - sum(read) - CAP}
77
+ out = []
78
+ for x, r in zip(lines, read, strict=True):
79
+ if drop[r] > 0:
80
+ drop[r] -= 1
81
+ else:
82
+ out.append(x)
83
+ return out
84
+
85
+
86
+ def rows(vault: Vault) -> list[dict]:
87
+ path = vault.root / RING
88
+ out = []
89
+ for line in path.read_text("utf-8").splitlines() if path.is_file() else []:
90
+ try:
91
+ r = json.loads(line)
92
+ except ValueError:
93
+ continue
94
+ if isinstance(r, dict):
95
+ out.append(r)
96
+ return out
97
+
98
+
99
+ def _stored(vault: Vault) -> dict:
100
+ """The settings file as stored; {} when it is missing or broken."""
101
+ try:
102
+ d = json.loads((vault.root / SETTINGS).read_text("utf-8"))
103
+ except (OSError, ValueError):
104
+ d = {}
105
+ return d if isinstance(d, dict) else {}
106
+
107
+
108
+ def settings(vault: Vault) -> dict[str, set[str]]:
109
+ """{"pin": ids, "mute": ids}; empty sets when the file is missing or broken."""
110
+ d = _stored(vault)
111
+ return {k: {x for x in d.get(k) or () if isinstance(x, str)} for k in ("pin", "mute")}
112
+
113
+
114
+ def _acks(d: dict) -> dict[str, str]:
115
+ """The stored Got it window ends by client (the ring's `client`)."""
116
+ a = d.get("ack")
117
+ return {k: v for k, v in a.items() if isinstance(v, str)} if isinstance(a, dict) else {}
118
+
119
+
120
+ def token(id: str) -> str:
121
+ """An opaque handle for an id the view must not show (a private page), to undo its flag."""
122
+ return hashlib.sha256(id.encode()).hexdigest()[:16]
123
+
124
+
125
+ def set_flag(vault: Vault, which: str, id: str, on: bool) -> dict[str, set[str]]:
126
+ """Pin or mute `id` (on) or undo it; pinning unmutes and muting unpins. The app's own
127
+ click path calls this; nothing over MCP does. ValueError for anything but a page or
128
+ `^c-…` claim id."""
129
+ if which not in ("pin", "mute") or not isinstance(id, str) or not (
130
+ ID_RE.fullmatch(id) or _CLAIM.fullmatch(id)):
131
+ raise ValueError("Pin or mute takes one page or claim id.")
132
+ with vault.lock():
133
+ s = settings(vault)
134
+ s[which].discard(id)
135
+ if on:
136
+ s[which].add(id)
137
+ s["mute" if which == "pin" else "pin"].discard(id)
138
+ vault.write_text(vault.root / SETTINGS, json.dumps( # the Got it ends kept
139
+ {**_stored(vault), **{k: sorted(v) for k, v in s.items()}}, indent=1) + "\n")
140
+ return s
141
+
142
+
143
+ def resolve_token(vault: Vault, tok: str) -> str | None:
144
+ """The pinned or muted id whose `token` is `tok`, else None."""
145
+ s = settings(vault)
146
+ return next((i for i in sorted(s["pin"] | s["mute"]) if token(i) == tok), None)
147
+
148
+
149
+ CLIENTS = {"claude-ai": "Claude Desktop", "claude-code": "Claude Code", "cursor": "Cursor"}
150
+ ME_TITLES = {"me/profile": "Profile", "me/core": "Core lines",
151
+ "me/teaching-contract": "Teaching contract"}
152
+ PER_CLIENT = 20 # calls shown per AI app; the ring keeps CAP in all
153
+ PRIVATE = "a private page"
154
+ OFTEN = 5 # "served most often" rows per AI app
155
+
156
+
157
+ def _items(vault: Vault, index=None):
158
+ """(item(id), blocks({block: ids}), settings) as the app shows ids: resolved to titles
159
+ now. A private or hidden page (planner.hidden) or a line of a private me/ page shows as
160
+ "a private page", without its id; its pin or mute keeps only a `token` to undo it.
161
+ `index`: an Index just refreshed, whose private flags planner.hidden reads instead of
162
+ walking the vault again (as the Index's own refresh does)."""
163
+ from keepfold import claims, planner
164
+ from keepfold.catalog import Catalog
165
+
166
+ hide = planner.hidden(vault, Catalog.load(vault)) if index is None else planner.hidden(
167
+ vault, index.catalog, index._flagged)
168
+ s = settings(vault)
169
+ lines = {claim(r["id"]): r for r in claims.rows(vault)}
170
+ seen: dict[str, dict] = {}
171
+
172
+ def private_me(page: str) -> bool:
173
+ try:
174
+ return is_private(vault.read("me", page))
175
+ except VaultError:
176
+ return False
177
+
178
+ def item(id: str) -> dict:
179
+ if id in seen:
180
+ return seen[id]
181
+ flags = {"pinned": id in s["pin"], "muted": id in s["mute"]}
182
+ if id.startswith("^"):
183
+ r = lines.get(id)
184
+ out = ({"title": PRIVATE, "kind": "claim", "token": token(id), **flags}
185
+ if r and private_me(r["page"]) else
186
+ {"id": id, "kind": "claim", **flags,
187
+ "title": r["text"] if r else "a line no longer there",
188
+ "where": f"{r['page']} · {r['section']}" if r else ""})
189
+ elif id.startswith("me/"):
190
+ out = ({"title": PRIVATE, "kind": "me"} if private_me(id[3:])
191
+ else {"id": id, "kind": "me", "title": ME_TITLES.get(id, id)})
192
+ else:
193
+ note = None
194
+ for kind in Vault.KIND_DIRS:
195
+ try:
196
+ note = vault.read(kind, id)
197
+ break
198
+ except VaultError:
199
+ continue
200
+ if note is not None and (is_private(note) or id in hide):
201
+ out = {"title": PRIVATE, "kind": "page", "token": token(id), **flags}
202
+ else: # shortcut: a browse site page (browse/sites/) is not looked up; its id shows
203
+ out = {"id": id, "kind": "page", **flags, "title": str(
204
+ note.fields.get("title") or id) if note else f"{id} (not found now)"}
205
+ seen[id] = out
206
+ return out
207
+
208
+ def blocks(d) -> list[dict]:
209
+ return [{"block": b, "items": [item(i) for i in ids if isinstance(i, str)]}
210
+ for b, ids in (d if isinstance(d, dict) else {}).items()
211
+ if isinstance(ids, list) and ids]
212
+
213
+ return item, blocks, s
214
+
215
+
216
+ def present(vault: Vault, served: dict, trimmed: dict, chars: int) -> dict:
217
+ """One call (the app's dry run) as `view` shows a call: titles, never text."""
218
+ _, blocks, _ = _items(vault)
219
+ return {"served": blocks(served), "trimmed": blocks(trimmed), "chars": chars}
220
+
221
+
222
+ def view(vault: Vault) -> dict:
223
+ """The app's X-ray: recent calls grouped by AI app, newest first (`_items` shows the ids).
224
+ Per app also its raw `name` ("" when it sent none), the `scopes` its profile gives it
225
+ (keepfold.profiles), that profile's `match` as `rule` (None: it gets `unknown`), the other
226
+ apps here the same rule covers (`shared`), and the OFTEN pages and lines served to it most
227
+ often (`often`, with a `count`; me/ pages, which no one pins or mutes, and READS rows'
228
+ hits left out). Also the
229
+ owner's `profiles`, their cap and `all_scopes` (access.SCOPES), for the scope bar's own
230
+ save through /api/profiles. R27b: `wide`, the app's broad-read window (`wide`) not yet
231
+ said Got it to, else None."""
232
+ from keepfold import profiles
233
+ from keepfold.access import SCOPES
234
+
235
+ item, blocks, s = _items(vault)
236
+ acks = _acks(_stored(vault))
237
+ groups: dict[str, list] = {}
238
+ for r in reversed(rows(vault)):
239
+ groups.setdefault(str(r.get("client") or "unknown"), []).append(r)
240
+ data = profiles.load(vault)
241
+ names = {c: "" if c == "unknown" else c for c in groups} # record() had no name
242
+ rule = {c: profiles.match(data, n) for c, n in names.items()}
243
+
244
+ def often(rs: list[dict]) -> list[dict]:
245
+ # what prime and context served, which Pin and Mute act on; never a search's hits
246
+ n = Counter(i for r in rs if r.get("tool") not in READS
247
+ and isinstance(r.get("served"), dict)
248
+ for ids in r["served"].values()
249
+ if isinstance(ids, list) for i in ids
250
+ if isinstance(i, str) and not i.startswith("me/"))
251
+ return [{**item(i), "count": k} for i, k in n.most_common(OFTEN)]
252
+
253
+ return {"clients": [{
254
+ "client": CLIENTS.get(c, c), "name": names[c], "total": len(rs),
255
+ "scopes": profiles.scopes_of(data, names[c]),
256
+ "rule": None if rule[c] is None else data["profiles"][rule[c]]["match"],
257
+ "shared": [CLIENTS.get(o, o) for o in groups if o != c and rule[c] is not None
258
+ and rule[o] == rule[c]],
259
+ "often": often(rs), "wide": wide(rs, acks.get(c, "")), "calls": [
260
+ {"ts": r.get("ts"), "tool": r.get("tool"), "chars": r.get("chars"),
261
+ "served": blocks(r.get("served")), "trimmed": blocks(r.get("trimmed"))}
262
+ for r in rs[:PER_CLIENT]]} for c, rs in groups.items()],
263
+ "pinned": [item(i) for i in sorted(s["pin"])],
264
+ "muted": [item(i) for i in sorted(s["mute"])],
265
+ "profiles": data, "profiles_max": profiles.MAX_PROFILES, "all_scopes": list(SCOPES)}
266
+
267
+
268
+ # ---- R27b (G5b-5): the broad-read flag --------------------------------------------------------
269
+ def _when(r: dict) -> datetime | None:
270
+ try:
271
+ return datetime.strptime(str(r.get("ts")), TS).replace(tzinfo=UTC)
272
+ except ValueError:
273
+ return None
274
+
275
+
276
+ def wide(rs: list[dict], after: str = "", now: datetime | None = None) -> dict | None:
277
+ """The most distinct pages one app's rows `rs` got through READS (resource reads serve
278
+ packs, not pages) within any WIDE_MINUTES of the last WIDE_DAYS, counting only calls after
279
+ `after` (the end of the window it said Got it to), as {n, day (local), end (that window's
280
+ last call)} when over WIDE_PAGES, else None. A private page counts, by its id only."""
281
+ from keepfold.events import local_day
282
+
283
+ since = (now or datetime.now(UTC)) - timedelta(days=WIDE_DAYS)
284
+ calls = sorted(((t, {i for ids in r["served"].values() if isinstance(ids, list)
285
+ for i in ids if isinstance(i, str)})
286
+ for r in rs if r.get("tool") in READS and isinstance(r.get("served"), dict)
287
+ and str(r.get("ts")) > after and (t := _when(r)) and t >= since),
288
+ key=lambda c: c[0])
289
+ have: Counter = Counter()
290
+ lo, best, end = 0, 0, None
291
+ for t, ids in calls:
292
+ have.update(ids)
293
+ while calls[lo][0] < t - timedelta(minutes=WIDE_MINUTES):
294
+ have.subtract(calls[lo][1])
295
+ have += Counter() # drops the pages no call left in the window got
296
+ lo += 1
297
+ if len(have) > best:
298
+ best, end = len(have), t
299
+ if best <= WIDE_PAGES:
300
+ return None
301
+ return {"n": best, "day": local_day(end), "end": end.strftime(TS)}
302
+
303
+
304
+ def ack(vault: Vault, client: str, end: str) -> None:
305
+ """Got it on an app's broad-read warning (the app's own click only; `client` as the view's
306
+ `name`): `end`, the shown window's, is kept as its `ack`, so only later calls raise it
307
+ again. ValueError when that app shows no such warning."""
308
+ key = client or "unknown"
309
+ with vault.lock():
310
+ d = _stored(vault)
311
+ acks = _acks(d)
312
+ w = wide([r for r in rows(vault) if str(r.get("client") or "unknown") == key],
313
+ acks.get(key, ""))
314
+ if w is None or w["end"] != end:
315
+ raise ValueError("That warning is no longer shown.")
316
+ vault.write_text(vault.root / SETTINGS, json.dumps(
317
+ {**d, "ack": {**acks, key: end}}, indent=1) + "\n")
318
+
319
+
320
+ # ---- R27b (C2): trace a reply -----------------------------------------------------------------
321
+ TRACE_CALLS = 10 # an app's latest calls a pasted reply is matched against
322
+ TRACE_HITS = 5
323
+ TRACE_WORDS = 8 # shared words shown per item
324
+ TRACE_BODY = 1500 # characters of a page's body matched, after its title and summary
325
+ TRACE_MAX = 4000 # characters of a pasted reply
326
+ _WORD = re.compile(r"[^\W_]+")
327
+
328
+
329
+ def _fold(w: str) -> str:
330
+ """A light plural fold: policies -> policy, tools -> tool, class stays."""
331
+ if len(w) > 4 and w.endswith("ies"):
332
+ return w[:-3] + "y"
333
+ return w[:-1] if len(w) > 3 and w.endswith("s") and not w.endswith("ss") else w
334
+
335
+
336
+ def _words(text: str) -> list[str]:
337
+ """Content words in order: lowercase, 3 or more characters, not an index.STOPWORDS one."""
338
+ from keepfold.index import STOPWORDS
339
+ return [w for w in _WORD.findall(text.lower()) if len(w) >= 3 and w not in STOPWORDS]
340
+
341
+
342
+ def _rarity(idx, words: list[str]) -> dict[str, float]:
343
+ """log((N + 1) / (df + 0.5)) per folded word, N and df over the indexed pages of `idx` (a
344
+ throwaway Index that never saves; the FTS table's document counts, private pages not in
345
+ it): a word few pages hold weighs more, one every page holds next to nothing."""
346
+ forms = sorted(set(words) | {_fold(w) for w in words})
347
+ n = idx.db.execute("SELECT count(*) FROM fts").fetchone()[0]
348
+ idx.db.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.vocab USING fts5vocab(main, fts, "
349
+ "row)")
350
+ df = dict(idx.db.execute("SELECT term, doc FROM temp.vocab WHERE term IN (SELECT value "
351
+ "FROM json_each(?))", (json.dumps(forms),)))
352
+ most: dict[str, int] = {}
353
+ for w in words:
354
+ f = _fold(w)
355
+ most[f] = max(most.get(f, 0), df.get(w, 0), df.get(f, 0))
356
+ return {f: math.log((n + 1) / (d + 0.5)) for f, d in most.items()}
357
+
358
+
359
+ def _note(vault: Vault, id: str):
360
+ """The page a served id names (`me/x`: a me/ page), else None."""
361
+ kinds, id = (("me",), id[3:]) if id.startswith("me/") else (Vault.KIND_DIRS, id)
362
+ for kind in kinds:
363
+ try:
364
+ return vault.read(kind, id)
365
+ except VaultError:
366
+ continue
367
+ return None
368
+
369
+
370
+ def _text(vault: Vault, id: str, lines: dict[str, str]) -> str:
371
+ """What a served id said: a claim's line; a page's title, summary and first TRACE_BODY
372
+ characters of its body; "" once it is gone."""
373
+ if id.startswith("^"):
374
+ return lines.get(id, "")
375
+ note = _note(vault, id)
376
+ if note is None:
377
+ return ""
378
+ f = note.fields
379
+ return f"{f.get('title') or ''}\n{f.get('summary') or ''}\n{note.body[:TRACE_BODY]}"
380
+
381
+
382
+ def trace(vault: Vault, client: str, text: str) -> dict:
383
+ """Which items Keepfold served the app `client` (the view's `name`; "": none named) in its
384
+ last TRACE_CALLS calls (any tool, resource reads included) a pasted AI reply `text` echoes,
385
+ ranked here with no model or network: the summed rarity (`_rarity`) of the distinct content
386
+ words (`_words`, plural-folded) an item's text (`_text`) shares with the reply. Up to
387
+ TRACE_HITS scoring above 0, best first (the newer call first on a tie), each as `_items`
388
+ shows its id plus its newest serving call's `tool` and `ts` and up to TRACE_WORDS shared
389
+ `words` in the reply's order; a private page is matched but shows only as PRIVATE, with
390
+ its call and no words, id or token. `calls`: the rows matched against.
391
+ `text` is never written, logged or kept."""
392
+ from keepfold import claims
393
+
394
+ key = client or "unknown"
395
+ rs = [r for r in rows(vault) if str(r.get("client") or "unknown") == key][-TRACE_CALLS:]
396
+ seen: dict[str, tuple[str, str]] = {} # id -> (tool, ts) of the newest call serving it
397
+ for r in rs:
398
+ got = r.get("served")
399
+ for ids in got.values() if isinstance(got, dict) else ():
400
+ for i in ids if isinstance(ids, list) else ():
401
+ if isinstance(i, str):
402
+ seen.pop(i, None) # re-inserted: the newest call's last
403
+ seen[i] = (str(r.get("tool") or ""), str(r.get("ts") or ""))
404
+ words = _words(text)
405
+ if not seen or not words:
406
+ return {"calls": len(rs), "hits": []}
407
+ from keepfold.catalog import Catalog
408
+ from keepfold.index import Index
409
+
410
+ idx = Index(vault, Catalog.load(vault), save=False)
411
+ try:
412
+ rare = _rarity(idx, words)
413
+ finally:
414
+ idx.db.close()
415
+ order = list(dict.fromkeys(_fold(w) for w in words))
416
+ form: dict[str, str] = {}
417
+ for w in words:
418
+ form.setdefault(_fold(w), w)
419
+ lines = {claim(r["id"]): r["text"] for r in claims.rows(vault)}
420
+ scored = []
421
+ for i in reversed(seen): # newest first; the stable sort keeps that order on a tie
422
+ have = {_fold(w) for w in _words(_text(vault, i, lines))}
423
+ shared = [f for f in order if f in have]
424
+ if (score := sum(rare[f] for f in shared)) > 0:
425
+ scored.append((score, i, shared))
426
+ scored.sort(key=lambda x: -x[0])
427
+ item, _, _ = _items(vault, idx)
428
+ hits = []
429
+ for _, i, shared in scored[:TRACE_HITS]:
430
+ x, (tool, ts) = item(i), seen[i]
431
+ hits.append({**x, "tool": tool, "ts": ts,
432
+ "words": [form[f] for f in shared[:TRACE_WORDS]]} if "id" in x
433
+ else {"title": PRIVATE, "kind": x["kind"], "tool": tool, "ts": ts})
434
+ return {"calls": len(rs), "hits": hits}
435
+
436
+
437
+ # ---- R27b (G5b-7): compare two apps -----------------------------------------------------------
438
+ def _gives(vault: Vault, scopes, id: str, lines: dict[str, dict]) -> bool:
439
+ """May an MCP client with `scopes` be served `id`, by the rules the tools use: a claim by its
440
+ section (access.scope_section), a me/ page whole (scope_page), a vault page by its kind
441
+ (scope_kind) and a playbook by its own scope (scope_own), as the index's withhold applies
442
+ them; no vault page for a core-only client (mcp_server.Keepfold._core_only, asked)."""
443
+ from types import SimpleNamespace
444
+
445
+ from keepfold import access
446
+ from keepfold.mcp_server import Keepfold
447
+ from keepfold.review import PLAYBOOK_TAG
448
+
449
+ if id.startswith("^"):
450
+ r = lines.get(id)
451
+ return r is not None and access.scope_section(scopes, r["page"], r["section"])
452
+ if id.startswith("me/"):
453
+ return access.scope_page(scopes, id[3:])
454
+ note = _note(vault, id)
455
+ if note is None or Keepfold._core_only(SimpleNamespace(_scopes=lambda: scopes)):
456
+ return False
457
+ tags = note.fields.get("tags")
458
+ book = note.kind == "note" and PLAYBOOK_TAG in (tags if isinstance(tags, list) else [tags])
459
+ return access.scope_kind(scopes, note.kind) and (
460
+ not book or access.scope_own(scopes, note.fields.get("scope")))
461
+
462
+
463
+ def _not_given(vault: Vault, scopes, full: dict | None, run: dict,
464
+ lines: dict[str, dict]) -> list[str]:
465
+ """The scopes (access.SCOPES order) a client with `scopes` lacks that would give it an item
466
+ the run with every scope (`full`) serves and its own `run` does not: each scope that alone
467
+ gives one back, or "all" when every one it lacks would (a core-only app's pages)."""
468
+ from keepfold.access import SCOPES
469
+
470
+ if scopes is None or full is None:
471
+ return []
472
+ got = {i for d in (run["served"], run["trimmed"]) for ids in d.values() for i in ids}
473
+ lacks = [s for s in SCOPES[1:] if s not in scopes] # SCOPES[0] is "all"
474
+ names: set[str] = set()
475
+ for i in {i for ids in full["served"].values() for i in ids} - got:
476
+ if _gives(vault, scopes, i, lines):
477
+ continue # its profile allows it: cut for space, or held for another reason
478
+ back = [s for s in lacks if _gives(vault, scopes | {s}, i, lines)]
479
+ names |= {"all"} if len(back) > 1 and len(back) == len(lacks) else set(back)
480
+ return [s for s in SCOPES if s in names]
481
+
482
+
483
+ def compare(vault: Vault, prompt: str, a: str, b: str, index=None) -> dict:
484
+ """What a new chat's keepfold_prime would serve the apps named `a` and `b` (the view's
485
+ `name`s) for `prompt` (mcp_server.dry_prime), each as `present` shows a call plus its
486
+ `withheld` scopes (`_not_given`, against a run with every scope: the other app's when its
487
+ profile has them all, else one more run). Nothing is written or logged, the prompt
488
+ included. `index`: the app's shared read-only Index (kept open), else one of its own."""
489
+ from keepfold import claims, profiles
490
+ from keepfold.catalog import Catalog
491
+ from keepfold.index import Index
492
+ from keepfold.mcp_server import dry_prime
493
+
494
+ data = profiles.load(vault)
495
+ scopes = {n: profiles.scopes_for(data, "" if n == "unknown" else n) for n in (a, b)}
496
+ # one read-only index for the runs, each setting its own withhold; a core-only app's run
497
+ # withholds every page, so it goes last and no run after it adds them all back
498
+ def last(n):
499
+ return scopes[n] is not None and scopes[n] <= {"core"}
500
+
501
+ every = [n for n in (a, b) if scopes[n] is None or "all" in scopes[n]]
502
+ own = index is None
503
+ index = Index(vault, Catalog.load(vault), save=False) if own else index
504
+ try:
505
+ full = None if every else dry_prime(vault, "", prompt, every=True, index=index)
506
+ runs = {n: dry_prime(vault, n, prompt, index=index) for n in sorted((a, b), key=last)}
507
+ finally:
508
+ if own:
509
+ index.db.close()
510
+ full = runs[every[0]] if every else full
511
+ lines = {claim(r["id"]): r for r in claims.rows(vault)}
512
+ _, blocks, _ = _items(vault, index) # its flags: no second vault walk
513
+ return {k: {"served": blocks(runs[n]["served"]), "trimmed": blocks(runs[n]["trimmed"]),
514
+ "chars": runs[n]["chars"],
515
+ "withheld": _not_given(vault, scopes[n], full, runs[n], lines)}
516
+ for k, n in (("a", a), ("b", b))}