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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Keepfold: a local-first learner model."""
keepfold/_proc.py ADDED
@@ -0,0 +1,102 @@
1
+ """Shared subprocess flags. The installed app (`keepfold-app.exe`) has no console, and on Windows
2
+ every console child of such a process opens its own visible window unless it is started with
3
+ CREATE_NO_WINDOW: pass `creationflags=NO_WINDOW` to every subprocess (0 elsewhere)."""
4
+
5
+ import contextlib
6
+ import os
7
+ import signal
8
+ import subprocess
9
+ import threading
10
+ import urllib.request
11
+
12
+ NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
13
+ _PROXY_VARS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy")
14
+
15
+
16
+ def proxy_env(base: dict | None = None) -> dict:
17
+ """`base` (default os.environ) plus the system proxy (the Windows registry, macOS settings)
18
+ as HTTP(S)_PROXY/NO_PROXY when neither is set, for downloaders that read only the env (uv,
19
+ hf_xet, ollama). shortcut: a PAC file (automatic proxy script) is not read; a network that
20
+ needs one still needs HTTPS_PROXY set by hand."""
21
+ env = dict(os.environ if base is None else base)
22
+ if not any(env.get(k) for k in _PROXY_VARS):
23
+ for scheme, url in urllib.request.getproxies().items():
24
+ if scheme in ("http", "https", "no"):
25
+ env[f"{scheme.upper()}_PROXY"] = url
26
+ return env
27
+
28
+
29
+ class Tree:
30
+ """A started process and every process it starts, for Cancel: `terminate()` ends them all,
31
+ where Popen.terminate() would leave grandchildren (an installer under winget, the model
32
+ download under uv) running and holding our pipe. Windows: a Job Object with
33
+ KILL_ON_JOB_CLOSE (taskkill /T when the process could not join one). Elsewhere: the child's
34
+ own session (start it with start_new_session=True), SIGTERM then SIGKILL to the group.
35
+ `close()` once the process has ended."""
36
+
37
+ def __init__(self, p):
38
+ self.p, self.ended = p, False
39
+ self.job = _job_for(p) if os.name == "nt" else None
40
+
41
+ def terminate(self) -> None:
42
+ pid = getattr(self.p, "pid", None)
43
+ if not self.ended:
44
+ with contextlib.suppress(OSError, subprocess.SubprocessError):
45
+ if self.job:
46
+ _k32.TerminateJobObject(self.job, 1)
47
+ elif os.name == "nt" and isinstance(pid, int):
48
+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)],
49
+ capture_output=True, timeout=10, creationflags=NO_WINDOW)
50
+ elif isinstance(pid, int):
51
+ _killpg(pid, signal.SIGTERM)
52
+ threading.Timer(3, _killpg, (pid, signal.SIGKILL)).start()
53
+ self.p.terminate()
54
+
55
+ def close(self) -> None:
56
+ self.ended = True
57
+ if self.job:
58
+ _set_kill_on_close(self.job, False) # a server the finished command started lives on
59
+ _k32.CloseHandle(self.job)
60
+ self.job = None
61
+
62
+
63
+ def _killpg(pgid: int, sig) -> None:
64
+ with contextlib.suppress(OSError):
65
+ os.killpg(pgid, sig)
66
+
67
+
68
+ if os.name == "nt":
69
+ import ctypes
70
+ from ctypes import wintypes
71
+
72
+ _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
73
+ _k32.CreateJobObjectW.restype = wintypes.HANDLE
74
+ _k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
75
+ _k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
76
+ wintypes.DWORD)
77
+ _k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
78
+ _k32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT)
79
+ _k32.CloseHandle.argtypes = (wintypes.HANDLE,)
80
+
81
+ class _Limits(ctypes.Structure): # JOBOBJECT_EXTENDED_LIMIT_INFORMATION
82
+ _fields_ = [("times", ctypes.c_int64 * 2), ("flags", wintypes.DWORD),
83
+ ("working_set", ctypes.c_size_t * 2), ("active", wintypes.DWORD),
84
+ ("affinity", ctypes.c_size_t), ("priority", wintypes.DWORD),
85
+ ("scheduling", wintypes.DWORD), ("io", ctypes.c_uint64 * 6),
86
+ ("memory", ctypes.c_size_t * 4)]
87
+
88
+ def _set_kill_on_close(job, on: bool) -> bool:
89
+ info = _Limits(flags=0x2000 if on else 0) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
90
+ return bool(_k32.SetInformationJobObject(job, 9, ctypes.byref(info), # extended limits
91
+ ctypes.sizeof(info)))
92
+
93
+ def _job_for(p):
94
+ """A new Job Object holding `p` (a Popen), or None (a fake, or Windows refused)."""
95
+ handle = getattr(p, "_handle", None)
96
+ job = _k32.CreateJobObjectW(None, None) if handle is not None else None
97
+ if not job:
98
+ return None
99
+ if _set_kill_on_close(job, True) and _k32.AssignProcessToJobObject(job, int(handle)):
100
+ return job
101
+ _k32.CloseHandle(job)
102
+ return None
keepfold/access.py ADDED
@@ -0,0 +1,154 @@
1
+ """Who may see what: the single place Keepfold's privacy rules are stated
2
+ (docs/design/v7-review/SPEC-privacy-gate.md §1-2).
3
+
4
+ Every output asks one question, `may_see(viewer, audience, kind)`. A record's audience comes
5
+ from the `audience_of_*` helpers, which delegate to the existing rules (`vault.is_private`,
6
+ `planner.hidden`, `browse.privacy.audience`) instead of restating them. Nothing else may
7
+ re-implement these rules; new outputs call in here. Pure functions, no I/O.
8
+
9
+ Owner rules (fixed): Claude and cloud apps never see private notes, private subjects, private
10
+ mistakes or local-only browsing; the local model may see everything within Chat's switches; a
11
+ terminal counts as "maybe an AI app".
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Iterable, Mapping
17
+ from enum import StrEnum
18
+
19
+ from keepfold.browse import privacy
20
+ from keepfold.vault import Note, is_private
21
+
22
+
23
+ class Audience(StrEnum):
24
+ """SKIP: never stored or shown. LOCAL: local models (and the owner at a private terminal)
25
+ only. CLOUD: anyone the owner lets read Keepfold. Values match `browse.privacy.audience`."""
26
+ SKIP = "skip"
27
+ LOCAL = "local"
28
+ CLOUD = "cloud"
29
+
30
+
31
+ KINDS = ("note", "chat", "browse", "study")
32
+ VIEWERS = ("mcp", "dashboard", "page_public", "today_md", "start_card", "terminal",
33
+ "chat_local", "cloud_model", "app_home")
34
+ # Chat's switch (ask.SOURCES) for each kind's CLOUD records; studying sits under "notes"
35
+ KIND_SWITCH = {"note": "notes", "chat": "chats", "browse": "browsing", "study": "notes"}
36
+ _CLOUD_ONLY = ("mcp", "dashboard", "page_public", "today_md", "start_card")
37
+
38
+
39
+ def may_see(viewer: str, audience: Audience | str, kind: str,
40
+ switches: Mapping[str, bool] | None = None, *, private_flag: bool = False,
41
+ tty: bool = False, cloud_opt_in: bool = False) -> bool:
42
+ """May `viewer` see a `kind` record of `audience`? SKIP: nobody. The other cells:
43
+
44
+ - mcp, dashboard, page_public, today_md, start_card: CLOUD only.
45
+ - terminal: CLOUD; LOCAL only with `private_flag` (`--private`) and `tty` (stdin and
46
+ stdout are both a TTY; the caller checks them).
47
+ - chat_local: LOCAL under `switches["private"]`; CLOUD under the kind's switch
48
+ (KIND_SWITCH). `switches` None counts as every switch off.
49
+ - cloud_model: CLOUD only, and only when `cloud_opt_in` (the user opted this data in).
50
+ - app_home: the app's home page; CLOUD, and LOCAL only with `private_flag` (the app's
51
+ Private switch is unlocked).
52
+
53
+ An unknown viewer, audience or kind raises ValueError: a new one must be added here."""
54
+ audience = Audience(audience)
55
+ if viewer not in VIEWERS:
56
+ raise ValueError(f"unknown viewer {viewer!r}")
57
+ if kind not in KINDS:
58
+ raise ValueError(f"unknown kind {kind!r}")
59
+ if audience is Audience.SKIP:
60
+ return False
61
+ if viewer in _CLOUD_ONLY:
62
+ return audience is Audience.CLOUD
63
+ if viewer == "terminal":
64
+ return audience is Audience.CLOUD or (private_flag and tty)
65
+ if viewer == "app_home":
66
+ return audience is Audience.CLOUD or private_flag
67
+ if viewer == "chat_local":
68
+ switches = switches or {}
69
+ key = "private" if audience is Audience.LOCAL else KIND_SWITCH[kind]
70
+ return bool(switches.get(key))
71
+ return audience is Audience.CLOUD and cloud_opt_in # cloud_model
72
+
73
+
74
+ def audience_of_note(note: Note, hidden: Iterable[str] | None = None) -> Audience:
75
+ """A note or page, or an imported AI chat (owner: like a note). LOCAL when
76
+ `vault.is_private` says so or its id is in `hidden` (`planner.hidden`: private subjects
77
+ and what sits under them), else CLOUD."""
78
+ return Audience.LOCAL if is_private(note) or note.id in (hidden or ()) else Audience.CLOUD
79
+
80
+
81
+ def audience_of_browse(category: str | None, settings: privacy.Settings, *,
82
+ host: str = "", private: bool = False) -> Audience:
83
+ """A browse item or site: its category's audience (`browse.privacy.audience`), with a
84
+ `private_domains` host or an item already marked private (`Kept.private` or `Kept.local`)
85
+ LOCAL. A skipped category stays SKIP whatever the host."""
86
+ a = Audience(privacy.audience(category, settings))
87
+ if a is Audience.CLOUD and (private or (host and privacy.in_domains(host, settings.private))):
88
+ return Audience.LOCAL
89
+ return a
90
+
91
+
92
+ def audience_of_study(subjects: Iterable[str], hidden: Iterable[str], *,
93
+ note_private: bool = False) -> Audience:
94
+ """A study item (concept, mistake, assessment): LOCAL when any of its subject ids is in
95
+ `hidden` (`planner.hidden`) or its own note is private (`note_private`), else CLOUD."""
96
+ hidden = set(hidden)
97
+ return Audience.LOCAL if note_private or any(s in hidden for s in subjects) \
98
+ else Audience.CLOUD
99
+
100
+
101
+ # ---- per-agent profiles (plan v9 item 8) ----------------------------------------------------
102
+ # A profile (keepfold.profiles) names the context scopes an MCP client may get; None or "all" is
103
+ # everything. A me/ page sits under one scope whole, except preferences and personality, whose
104
+ # `## ` sections each sit under one (the keepfold_context scopes: a preferences section is named
105
+ # after its scope). Journal and people pages are personal; project pages are projects;
106
+ # assessments are learning and job applications career (R12).
107
+ SCOPES = ("all", "core", "coding", "communication", "learning", "projects", "environment",
108
+ "career", "personal")
109
+ SECTIONED = ("preferences", "personality")
110
+ # me/ pages outside SECTIONED: their scope (the teaching contract is for tutors, not coding
111
+ # agents; setup, the hardware and software, is for them); a page not listed is "personal"
112
+ PAGE_SCOPE = {"core": "core", "teaching-contract": "learning", "setup": "environment"}
113
+ PERSONALITY_SCOPE = {"communication": "communication", "how i think": "learning"}
114
+ # preferences sections not named after a scope: the scope they sit under
115
+ PREFERENCE_SCOPE = {"workflow": "coding"}
116
+ KIND_SCOPE = {"journal": "personal", "person": "personal", "project": "projects",
117
+ "assessment": "learning", "application": "career"}
118
+
119
+
120
+ def _all(scopes) -> bool:
121
+ return scopes is None or "all" in scopes
122
+
123
+
124
+ def scope_page(scopes, page: str) -> bool:
125
+ """May a client with `scopes` get me/<page>? A sectioned page: some of it (scope_section)."""
126
+ if _all(scopes) or page in SECTIONED:
127
+ return True
128
+ need = PAGE_SCOPE.get(page, "personal")
129
+ return need is None or need in scopes
130
+
131
+
132
+ def scope_section(scopes, page: str, heading: str) -> bool:
133
+ """May a client with `scopes` get the `## heading` section of me/<page>?"""
134
+ if _all(scopes):
135
+ return True
136
+ h = heading.strip().lower()
137
+ if page == "personality":
138
+ return PERSONALITY_SCOPE.get(h) in scopes
139
+ if page == "preferences":
140
+ h = PREFERENCE_SCOPE.get(h, h)
141
+ return h in SCOPES[2:] and h in scopes
142
+ return scope_page(scopes, page)
143
+
144
+
145
+ def scope_kind(scopes, kind: str) -> bool:
146
+ """May a client with `scopes` get vault pages of `kind` (journal and people: personal;
147
+ project: projects; assessment: learning; application: career)?"""
148
+ return _all(scopes) or KIND_SCOPE.get(kind) is None or KIND_SCOPE[kind] in scopes
149
+
150
+
151
+ def scope_own(scopes, scope) -> bool:
152
+ """May a client with `scopes` get a page with its own `scope:` field `scope` (a playbook's;
153
+ none or "all": every client)?"""
154
+ return _all(scopes) or str(scope or "all") in ("all", *scopes)
keepfold/agent_eval.py ADDED
@@ -0,0 +1,162 @@
1
+ """`keepfold eval agent` (R12): does each AI app get the right lines about the owner, and none it
2
+ must not? Eleven cases (assets/agent_eval.json, adapted from Gemini round 5's A01-A10), each a
3
+ made-up vault, an AI app's MCP client name and a prompt.
4
+
5
+ Layer A, model-free: each case's vault is built in a temp folder through keepfold.vault, and the
6
+ text that client is served on the case's channels (keepfold_prime over MCP as that client, the
7
+ rules-file block app/targets.py writes for it, a context pack) is checked for the lines it must
8
+ get and the ones it must not. The real serving code runs, never a copy of its logic.
9
+
10
+ Layer B, owner-run only (`--model`): that text and the prompt go to the local model the owner
11
+ already loaded (chat_eval.find_model: never loads, unloads or downloads one, never a cloud API),
12
+ three times per case; a case passes only if all three replies pass its regexes (pass^3).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ import shutil
20
+ import tempfile
21
+ import time
22
+ from pathlib import Path
23
+
24
+ from keepfold import claims, taint, xray
25
+ from keepfold.vault import Vault
26
+
27
+ SPEC = Path(__file__).parent / "assets" / "agent_eval.json"
28
+ RUNS = 3
29
+ SYSTEM = ("You are the user's AI assistant. Keepfold, the user's memory, gave you this context "
30
+ "about them:\n\n{served}")
31
+
32
+
33
+ def spec() -> dict:
34
+ return json.loads(SPEC.read_text(encoding="utf-8"))
35
+
36
+
37
+ def build(root: Path, *blocks: dict) -> Vault:
38
+ """A new vault at `root` from `blocks` (the spec's `base`, then a case's `vault`), in order:
39
+ pages, lines, an agent's guesses, X-ray mutes (agent_eval.json's meta.vault_block)."""
40
+ root.mkdir(parents=True)
41
+ (root / ".keepfold").mkdir()
42
+ v = Vault(root)
43
+ for b in blocks:
44
+ for p in b.get("pages", []):
45
+ v.create_note(p["kind"], p["id"], p.get("fields", {}), p["body"], p.get("folder"))
46
+ for page, head, text in b.get("lines", []):
47
+ v.append_to_section("me", page, head, text)
48
+ guesses = [g for b in blocks for g in b.get("guesses", [])]
49
+ if guesses:
50
+ from keepfold.mcp_server import Keepfold
51
+
52
+ c = Keepfold(v) # in process, no user_confirmed: an AI app's inferred line, tier agent
53
+ c.session = c.sessions.require("patch") # the ambient session a tool call opens
54
+ for page, head, text in guesses:
55
+ c.keepfold_patch(f"me/{page}", "append_to_section", head, text)
56
+ ids = {r["text"]: r["id"] for r in claims.rows(v)}
57
+ for text in (t for b in blocks for t in b.get("mute", [])):
58
+ xray.set_flag(v, "mute", xray.claim(ids[text]), True)
59
+ return v
60
+
61
+
62
+ def served(vault: Vault, case: dict) -> str:
63
+ """What `case["client"]` is served on each of the case's channels, joined."""
64
+ from keepfold import packs
65
+ from keepfold.app import targets
66
+ from keepfold.mcp_server import Keepfold
67
+
68
+ out = []
69
+ for ch in case["serve"]:
70
+ if ch == "prime":
71
+ c = Keepfold(vault)
72
+ c.over_mcp, c.sessions.client = True, case["client"] # as the MCP handshake names it
73
+ out.append(c.keepfold_prime(case["prompt"])["context"])
74
+ elif ch == "rules":
75
+ entry = {"args": ["mcp", "--vault", str(vault.root)]} # as clients.server_entry
76
+ out.append(targets.rule_block(entry, case["client"]))
77
+ elif ch.startswith("pack:"):
78
+ out.append(packs.pack(vault, ch.removeprefix("pack:")))
79
+ else:
80
+ raise ValueError(f"{case['id']}: unknown channel {ch!r}")
81
+ return "\n\n".join(out)
82
+
83
+
84
+ def check_a(text: str, case: dict) -> list[str]:
85
+ """Layer A's reasons `text` fails `case` ([] passes): a must_serve line missing, a forbid
86
+ one present (substrings, any case)."""
87
+ low, a = text.lower(), case["layer_a"]
88
+ return ([f"not served: {s!r}" for s in a["must_serve"] if s.lower() not in low]
89
+ + [f"served: {s!r}" for s in a["forbid"] if s.lower() in low])
90
+
91
+
92
+ def check_b(reply: str | None, case: dict) -> list[str]:
93
+ """Layer B's reasons one model reply fails `case` ([] passes)."""
94
+ if not reply:
95
+ return ["no answer"]
96
+ b = case["layer_b"]
97
+ return ([f"no match for {r!r}" for r in b["regex_all"] if not re.search(r, reply)]
98
+ + [f"matched {r!r}" for r in b["regex_none"] if re.search(r, reply)]
99
+ + [f"leaked {s!r}" for s in b["must_not_leak"] if s.lower() in reply.lower()])
100
+
101
+
102
+ def case_a(case: dict, base: dict, root: Path) -> tuple[str, list[str]]:
103
+ """(served text, Layer A's reasons) for `case`, its vault built at `root`. The owner's
104
+ config is never read (taint.pinned), so the result is the same on any machine."""
105
+ with taint.pinned({}):
106
+ text = served(build(root, base, case["vault"]), case)
107
+ return text, check_a(text, case)
108
+
109
+
110
+ def run(*, model: bool = False, runner=None, runs: int = RUNS, progress=None) -> dict:
111
+ """Layer A on every case; with `model`, Layer B too on `runner` (default: the loaded local
112
+ model, chat_eval.find_model). `progress(done, total, id)` after each case."""
113
+ sp = spec()
114
+ why_b = "" if model else "no --model"
115
+ if model and runner is None:
116
+ from keepfold import chat_eval
117
+
118
+ runner, why_b = chat_eval.find_model()
119
+ rows, tmp, t0 = [], Path(tempfile.mkdtemp(prefix="keepfold-agent-eval-")), time.monotonic()
120
+ try:
121
+ for n, case in enumerate(sp["cases"], 1):
122
+ text, why = case_a(case, sp["base"], tmp / case["id"])
123
+ known = case.get("known_failure")
124
+ row = {k: case[k] for k in ("id", "category", "client")}
125
+ row |= {"a": "known failure" if why and known else "fail" if why else "pass",
126
+ "a_why": why, **({"known_failure": known} if known else {}),
127
+ "b": None, "b_why": []}
128
+ if runner is not None:
129
+ fails = [check_b(runner.chat(SYSTEM.format(served=text), case["prompt"]), case)
130
+ for _ in range(runs)]
131
+ row["b"] = sum(not f for f in fails)
132
+ row["b_why"] = next((f for f in fails if f), [])
133
+ rows.append(row)
134
+ if progress:
135
+ progress(n, len(sp["cases"]), case["id"])
136
+ finally:
137
+ shutil.rmtree(tmp, ignore_errors=True)
138
+ return {"cases": rows, "runs": runs if runner is not None else 0,
139
+ "model": getattr(runner, "model", None), "b_not_run": why_b if runner is None else "",
140
+ "a_seconds": round(time.monotonic() - t0, 2) if runner is None else None,
141
+ "a_pass": sum(r["a"] == "pass" for r in rows),
142
+ "a_known": sum(r["a"] == "known failure" for r in rows),
143
+ "a_fail": sum(r["a"] == "fail" for r in rows),
144
+ "b_pass": sum(r["b"] == runs for r in rows) if runner is not None else None}
145
+
146
+
147
+ def summary(r: dict) -> str:
148
+ """One line per case (id, category, A, B) and the totals."""
149
+ out = []
150
+ for c in r["cases"]:
151
+ b = f"{c['b']}/{r['runs']}" if c["b"] is not None else "not run"
152
+ why = "; ".join(c["a_why"] + c["b_why"])
153
+ out.append(f"{c['id']} {c['category']:<26} A {c['a']:<13} B {b}"
154
+ + (f" ({why})" if why else ""))
155
+ n = len(r["cases"])
156
+ out.append(f"Layer A: {r['a_pass']}/{n} pass" + (
157
+ f", {r['a_known']} known failure(s)" if r["a_known"] else "") + (
158
+ f", {r['a_fail']} FAIL" if r["a_fail"] else "") + (
159
+ f" in {r['a_seconds']} s" if r["a_seconds"] is not None else ""))
160
+ out.append(f"Layer B: {r['b_pass']}/{n} pass^{r['runs']} on {r['model']}"
161
+ if r["b_pass"] is not None else f"Layer B: not run ({r['b_not_run']})")
162
+ return "\n".join(out)
keepfold/agent_text.py ADDED
@@ -0,0 +1,56 @@
1
+ """RR-36: every fixed string an agent can see, with its size, and the total per app profile
2
+ (`keepfold agent-text`), so a prompt-budget change shows up in one place. Only what the code and
3
+ the skill ship: server instructions, tool descriptions, `next` hints, SKILL.md, the prime hook's
4
+ templates and the rule-file block; vault text (claims, pages) is never part of it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ REPO = Path(__file__).resolve().parents[2]
12
+ SKILL = ("skills", "keepfold", "SKILL.md") # a checkout only: the wheel does not ship the skill
13
+ HOOK_TEMPLATES = ("HEAD", "NEXT", "TAGGED", "NUDGE") # keepfold.prime_hook's output
14
+ HINTS = ("OFFER", "MOCK_BRIEF", "ASK_FOCUS") # mcp_server `next` text not named *_NEXT
15
+ # The channels that reach an app (by profiles.norm name): MCP reaches every client; the Claude
16
+ # Code plugin (skill and hooks) only Claude; Connect's rule file Cursor, VS Code and Codex.
17
+ PLUGIN_APPS = ("claude",)
18
+ RULE_APPS = ("cursor", "visualstudiocode", "copilot", "codex")
19
+
20
+
21
+ def _text(v) -> str | None:
22
+ if isinstance(v, str):
23
+ return v
24
+ if isinstance(v, dict) and v and all(isinstance(x, str) for x in v.values()):
25
+ return "\n".join(f"{k}: {x}" for k, x in v.items())
26
+ return None
27
+
28
+
29
+ def sources() -> list[tuple[str, str, str]]:
30
+ """(label, channel mcp|plugin|rules, text) of every fixed agent-facing string."""
31
+ from keepfold import mcp_server, packs, prime_hook
32
+
33
+ out = [("mcp_server.INSTRUCTIONS", "mcp", mcp_server.INSTRUCTIONS)]
34
+ out += [(f"mcp_server.DESCRIPTIONS[{k}]", "mcp", v)
35
+ for k, v in mcp_server.DESCRIPTIONS.items()]
36
+ out += [(f"mcp_server.{k}", "mcp", t) for k, v in sorted(vars(mcp_server).items())
37
+ if k.isupper() and (k.endswith("_NEXT") or k in HINTS) and (t := _text(v))]
38
+ if (p := REPO.joinpath(*SKILL)).is_file():
39
+ out.append(("/".join(SKILL), "plugin", p.read_text(encoding="utf-8")))
40
+ out += [(f"prime_hook.{k}", "plugin", getattr(prime_hook, k)) for k in HOOK_TEMPLATES]
41
+ out.append(("packs.rule_block (no vault)", "rules", packs.rule_block(None)))
42
+ return out
43
+
44
+
45
+ def channels(app: str) -> set[str]:
46
+ from keepfold.profiles import norm
47
+
48
+ n = norm(app)
49
+ return {"mcp"} | ({"plugin"} if any(a in n for a in PLUGIN_APPS) else set()) \
50
+ | ({"rules"} if any(a in n for a in RULE_APPS) else set())
51
+
52
+
53
+ def sizes(data: dict, srcs: list[tuple[str, str, str]]) -> list[tuple[str, int]]:
54
+ """(profile match or 'unknown', chars of fixed text that app can see) per profile."""
55
+ names = [p["match"] for p in data["profiles"]] + ["unknown"]
56
+ return [(n, sum(len(t) for _, c, t in srcs if c in channels(n))) for n in names]